xref: /sqlite-3.40.0/src/shell.c.in (revision 4c8404e5)
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  unsigned char *aBlob = (unsigned char*)pBlob;
1504
1505  char *zStr = sqlite3_malloc(nBlob*2 + 1);
1506  shell_check_oom(zStr);
1507
1508  for(i=0; i<nBlob; i++){
1509    static const char aHex[] = {
1510        '0', '1', '2', '3', '4', '5', '6', '7',
1511        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1512    };
1513    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1514    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1515  }
1516  zStr[i*2] = '\0';
1517
1518  raw_printf(out,"X'%s'", zStr);
1519  sqlite3_free(zStr);
1520}
1521
1522/*
1523** Find a string that is not found anywhere in z[].  Return a pointer
1524** to that string.
1525**
1526** Try to use zA and zB first.  If both of those are already found in z[]
1527** then make up some string and store it in the buffer zBuf.
1528*/
1529static const char *unused_string(
1530  const char *z,                    /* Result must not appear anywhere in z */
1531  const char *zA, const char *zB,   /* Try these first */
1532  char *zBuf                        /* Space to store a generated string */
1533){
1534  unsigned i = 0;
1535  if( strstr(z, zA)==0 ) return zA;
1536  if( strstr(z, zB)==0 ) return zB;
1537  do{
1538    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1539  }while( strstr(z,zBuf)!=0 );
1540  return zBuf;
1541}
1542
1543/*
1544** Output the given string as a quoted string using SQL quoting conventions.
1545**
1546** See also: output_quoted_escaped_string()
1547*/
1548static void output_quoted_string(FILE *out, const char *z){
1549  int i;
1550  char c;
1551  setBinaryMode(out, 1);
1552  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1553  if( c==0 ){
1554    utf8_printf(out,"'%s'",z);
1555  }else{
1556    raw_printf(out, "'");
1557    while( *z ){
1558      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1559      if( c=='\'' ) i++;
1560      if( i ){
1561        utf8_printf(out, "%.*s", i, z);
1562        z += i;
1563      }
1564      if( c=='\'' ){
1565        raw_printf(out, "'");
1566        continue;
1567      }
1568      if( c==0 ){
1569        break;
1570      }
1571      z++;
1572    }
1573    raw_printf(out, "'");
1574  }
1575  setTextMode(out, 1);
1576}
1577
1578/*
1579** Output the given string as a quoted string using SQL quoting conventions.
1580** Additionallly , escape the "\n" and "\r" characters so that they do not
1581** get corrupted by end-of-line translation facilities in some operating
1582** systems.
1583**
1584** This is like output_quoted_string() but with the addition of the \r\n
1585** escape mechanism.
1586*/
1587static void output_quoted_escaped_string(FILE *out, const char *z){
1588  int i;
1589  char c;
1590  setBinaryMode(out, 1);
1591  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1592  if( c==0 ){
1593    utf8_printf(out,"'%s'",z);
1594  }else{
1595    const char *zNL = 0;
1596    const char *zCR = 0;
1597    int nNL = 0;
1598    int nCR = 0;
1599    char zBuf1[20], zBuf2[20];
1600    for(i=0; z[i]; i++){
1601      if( z[i]=='\n' ) nNL++;
1602      if( z[i]=='\r' ) nCR++;
1603    }
1604    if( nNL ){
1605      raw_printf(out, "replace(");
1606      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1607    }
1608    if( nCR ){
1609      raw_printf(out, "replace(");
1610      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1611    }
1612    raw_printf(out, "'");
1613    while( *z ){
1614      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1615      if( c=='\'' ) i++;
1616      if( i ){
1617        utf8_printf(out, "%.*s", i, z);
1618        z += i;
1619      }
1620      if( c=='\'' ){
1621        raw_printf(out, "'");
1622        continue;
1623      }
1624      if( c==0 ){
1625        break;
1626      }
1627      z++;
1628      if( c=='\n' ){
1629        raw_printf(out, "%s", zNL);
1630        continue;
1631      }
1632      raw_printf(out, "%s", zCR);
1633    }
1634    raw_printf(out, "'");
1635    if( nCR ){
1636      raw_printf(out, ",'%s',char(13))", zCR);
1637    }
1638    if( nNL ){
1639      raw_printf(out, ",'%s',char(10))", zNL);
1640    }
1641  }
1642  setTextMode(out, 1);
1643}
1644
1645/*
1646** Output the given string as a quoted according to C or TCL quoting rules.
1647*/
1648static void output_c_string(FILE *out, const char *z){
1649  unsigned int c;
1650  fputc('"', out);
1651  while( (c = *(z++))!=0 ){
1652    if( c=='\\' ){
1653      fputc(c, out);
1654      fputc(c, out);
1655    }else if( c=='"' ){
1656      fputc('\\', out);
1657      fputc('"', out);
1658    }else if( c=='\t' ){
1659      fputc('\\', out);
1660      fputc('t', out);
1661    }else if( c=='\n' ){
1662      fputc('\\', out);
1663      fputc('n', out);
1664    }else if( c=='\r' ){
1665      fputc('\\', out);
1666      fputc('r', out);
1667    }else if( !isprint(c&0xff) ){
1668      raw_printf(out, "\\%03o", c&0xff);
1669    }else{
1670      fputc(c, out);
1671    }
1672  }
1673  fputc('"', out);
1674}
1675
1676/*
1677** Output the given string as a quoted according to JSON quoting rules.
1678*/
1679static void output_json_string(FILE *out, const char *z, int n){
1680  unsigned int c;
1681  if( n<0 ) n = (int)strlen(z);
1682  fputc('"', out);
1683  while( n-- ){
1684    c = *(z++);
1685    if( c=='\\' || c=='"' ){
1686      fputc('\\', out);
1687      fputc(c, out);
1688    }else if( c<=0x1f ){
1689      fputc('\\', out);
1690      if( c=='\b' ){
1691        fputc('b', out);
1692      }else if( c=='\f' ){
1693        fputc('f', out);
1694      }else if( c=='\n' ){
1695        fputc('n', out);
1696      }else if( c=='\r' ){
1697        fputc('r', out);
1698      }else if( c=='\t' ){
1699        fputc('t', out);
1700      }else{
1701         raw_printf(out, "u%04x",c);
1702      }
1703    }else{
1704      fputc(c, out);
1705    }
1706  }
1707  fputc('"', out);
1708}
1709
1710/*
1711** Output the given string with characters that are special to
1712** HTML escaped.
1713*/
1714static void output_html_string(FILE *out, const char *z){
1715  int i;
1716  if( z==0 ) z = "";
1717  while( *z ){
1718    for(i=0;   z[i]
1719            && z[i]!='<'
1720            && z[i]!='&'
1721            && z[i]!='>'
1722            && z[i]!='\"'
1723            && z[i]!='\'';
1724        i++){}
1725    if( i>0 ){
1726      utf8_printf(out,"%.*s",i,z);
1727    }
1728    if( z[i]=='<' ){
1729      raw_printf(out,"&lt;");
1730    }else if( z[i]=='&' ){
1731      raw_printf(out,"&amp;");
1732    }else if( z[i]=='>' ){
1733      raw_printf(out,"&gt;");
1734    }else if( z[i]=='\"' ){
1735      raw_printf(out,"&quot;");
1736    }else if( z[i]=='\'' ){
1737      raw_printf(out,"&#39;");
1738    }else{
1739      break;
1740    }
1741    z += i + 1;
1742  }
1743}
1744
1745/*
1746** If a field contains any character identified by a 1 in the following
1747** array, then the string must be quoted for CSV.
1748*/
1749static const char needCsvQuote[] = {
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, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1753  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1754  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1755  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1756  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1757  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1758  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1759  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1760  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1761  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1762  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1763  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1764  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1765  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1766};
1767
1768/*
1769** Output a single term of CSV.  Actually, p->colSeparator is used for
1770** the separator, which may or may not be a comma.  p->nullValue is
1771** the null value.  Strings are quoted if necessary.  The separator
1772** is only issued if bSep is true.
1773*/
1774static void output_csv(ShellState *p, const char *z, int bSep){
1775  FILE *out = p->out;
1776  if( z==0 ){
1777    utf8_printf(out,"%s",p->nullValue);
1778  }else{
1779    unsigned i;
1780    for(i=0; z[i]; i++){
1781      if( needCsvQuote[((unsigned char*)z)[i]] ){
1782        i = 0;
1783        break;
1784      }
1785    }
1786    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1787      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1788      shell_check_oom(zQuoted);
1789      utf8_printf(out, "%s", zQuoted);
1790      sqlite3_free(zQuoted);
1791    }else{
1792      utf8_printf(out, "%s", z);
1793    }
1794  }
1795  if( bSep ){
1796    utf8_printf(p->out, "%s", p->colSeparator);
1797  }
1798}
1799
1800/*
1801** This routine runs when the user presses Ctrl-C
1802*/
1803static void interrupt_handler(int NotUsed){
1804  UNUSED_PARAMETER(NotUsed);
1805  seenInterrupt++;
1806  if( seenInterrupt>2 ) exit(1);
1807  if( globalDb ) sqlite3_interrupt(globalDb);
1808}
1809
1810#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1811/*
1812** This routine runs for console events (e.g. Ctrl-C) on Win32
1813*/
1814static BOOL WINAPI ConsoleCtrlHandler(
1815  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1816){
1817  if( dwCtrlType==CTRL_C_EVENT ){
1818    interrupt_handler(0);
1819    return TRUE;
1820  }
1821  return FALSE;
1822}
1823#endif
1824
1825#ifndef SQLITE_OMIT_AUTHORIZATION
1826/*
1827** This authorizer runs in safe mode.
1828*/
1829static int safeModeAuth(
1830  void *pClientData,
1831  int op,
1832  const char *zA1,
1833  const char *zA2,
1834  const char *zA3,
1835  const char *zA4
1836){
1837  ShellState *p = (ShellState*)pClientData;
1838  static const char *azProhibitedFunctions[] = {
1839    "edit",
1840    "fts3_tokenizer",
1841    "load_extension",
1842    "readfile",
1843    "writefile",
1844    "zipfile",
1845    "zipfile_cds",
1846  };
1847  UNUSED_PARAMETER(zA2);
1848  UNUSED_PARAMETER(zA3);
1849  UNUSED_PARAMETER(zA4);
1850  switch( op ){
1851    case SQLITE_ATTACH: {
1852#ifndef SQLITE_SHELL_FIDDLE
1853      /* In WASM builds the filesystem is a virtual sandbox, so
1854      ** there's no harm in using ATTACH. */
1855      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1856#endif
1857      break;
1858    }
1859    case SQLITE_FUNCTION: {
1860      int i;
1861      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1862        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1863          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1864                         azProhibitedFunctions[i]);
1865        }
1866      }
1867      break;
1868    }
1869  }
1870  return SQLITE_OK;
1871}
1872
1873/*
1874** When the ".auth ON" is set, the following authorizer callback is
1875** invoked.  It always returns SQLITE_OK.
1876*/
1877static int shellAuth(
1878  void *pClientData,
1879  int op,
1880  const char *zA1,
1881  const char *zA2,
1882  const char *zA3,
1883  const char *zA4
1884){
1885  ShellState *p = (ShellState*)pClientData;
1886  static const char *azAction[] = { 0,
1887     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1888     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1889     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1890     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1891     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1892     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1893     "PRAGMA",               "READ",                 "SELECT",
1894     "TRANSACTION",          "UPDATE",               "ATTACH",
1895     "DETACH",               "ALTER_TABLE",          "REINDEX",
1896     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1897     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1898  };
1899  int i;
1900  const char *az[4];
1901  az[0] = zA1;
1902  az[1] = zA2;
1903  az[2] = zA3;
1904  az[3] = zA4;
1905  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1906  for(i=0; i<4; i++){
1907    raw_printf(p->out, " ");
1908    if( az[i] ){
1909      output_c_string(p->out, az[i]);
1910    }else{
1911      raw_printf(p->out, "NULL");
1912    }
1913  }
1914  raw_printf(p->out, "\n");
1915  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1916  return SQLITE_OK;
1917}
1918#endif
1919
1920/*
1921** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1922**
1923** This routine converts some CREATE TABLE statements for shadow tables
1924** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1925**
1926** If the schema statement in z[] contains a start-of-comment and if
1927** sqlite3_complete() returns false, try to terminate the comment before
1928** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
1929*/
1930static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1931  char *zToFree = 0;
1932  if( z==0 ) return;
1933  if( zTail==0 ) return;
1934  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
1935    const char *zOrig = z;
1936    static const char *azTerm[] = { "", "*/", "\n" };
1937    int i;
1938    for(i=0; i<ArraySize(azTerm); i++){
1939      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
1940      if( sqlite3_complete(zNew) ){
1941        size_t n = strlen(zNew);
1942        zNew[n-1] = 0;
1943        zToFree = zNew;
1944        z = zNew;
1945        break;
1946      }
1947      sqlite3_free(zNew);
1948    }
1949  }
1950  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1951    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1952  }else{
1953    utf8_printf(out, "%s%s", z, zTail);
1954  }
1955  sqlite3_free(zToFree);
1956}
1957static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1958  char c = z[n];
1959  z[n] = 0;
1960  printSchemaLine(out, z, zTail);
1961  z[n] = c;
1962}
1963
1964/*
1965** Return true if string z[] has nothing but whitespace and comments to the
1966** end of the first line.
1967*/
1968static int wsToEol(const char *z){
1969  int i;
1970  for(i=0; z[i]; i++){
1971    if( z[i]=='\n' ) return 1;
1972    if( IsSpace(z[i]) ) continue;
1973    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1974    return 0;
1975  }
1976  return 1;
1977}
1978
1979/*
1980** Add a new entry to the EXPLAIN QUERY PLAN data
1981*/
1982static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1983  EQPGraphRow *pNew;
1984  int nText = strlen30(zText);
1985  if( p->autoEQPtest ){
1986    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1987  }
1988  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1989  shell_check_oom(pNew);
1990  pNew->iEqpId = iEqpId;
1991  pNew->iParentId = p2;
1992  memcpy(pNew->zText, zText, nText+1);
1993  pNew->pNext = 0;
1994  if( p->sGraph.pLast ){
1995    p->sGraph.pLast->pNext = pNew;
1996  }else{
1997    p->sGraph.pRow = pNew;
1998  }
1999  p->sGraph.pLast = pNew;
2000}
2001
2002/*
2003** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2004** in p->sGraph.
2005*/
2006static void eqp_reset(ShellState *p){
2007  EQPGraphRow *pRow, *pNext;
2008  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2009    pNext = pRow->pNext;
2010    sqlite3_free(pRow);
2011  }
2012  memset(&p->sGraph, 0, sizeof(p->sGraph));
2013}
2014
2015/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2016** pOld, or return the first such line if pOld is NULL
2017*/
2018static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2019  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2020  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2021  return pRow;
2022}
2023
2024/* Render a single level of the graph that has iEqpId as its parent.  Called
2025** recursively to render sublevels.
2026*/
2027static void eqp_render_level(ShellState *p, int iEqpId){
2028  EQPGraphRow *pRow, *pNext;
2029  int n = strlen30(p->sGraph.zPrefix);
2030  char *z;
2031  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2032    pNext = eqp_next_row(p, iEqpId, pRow);
2033    z = pRow->zText;
2034    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2035                pNext ? "|--" : "`--", z);
2036    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2037      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2038      eqp_render_level(p, pRow->iEqpId);
2039      p->sGraph.zPrefix[n] = 0;
2040    }
2041  }
2042}
2043
2044/*
2045** Display and reset the EXPLAIN QUERY PLAN data
2046*/
2047static void eqp_render(ShellState *p){
2048  EQPGraphRow *pRow = p->sGraph.pRow;
2049  if( pRow ){
2050    if( pRow->zText[0]=='-' ){
2051      if( pRow->pNext==0 ){
2052        eqp_reset(p);
2053        return;
2054      }
2055      utf8_printf(p->out, "%s\n", pRow->zText+3);
2056      p->sGraph.pRow = pRow->pNext;
2057      sqlite3_free(pRow);
2058    }else{
2059      utf8_printf(p->out, "QUERY PLAN\n");
2060    }
2061    p->sGraph.zPrefix[0] = 0;
2062    eqp_render_level(p, 0);
2063    eqp_reset(p);
2064  }
2065}
2066
2067#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2068/*
2069** Progress handler callback.
2070*/
2071static int progress_handler(void *pClientData) {
2072  ShellState *p = (ShellState*)pClientData;
2073  p->nProgress++;
2074  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2075    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2076    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2077    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2078    return 1;
2079  }
2080  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2081    raw_printf(p->out, "Progress %u\n", p->nProgress);
2082  }
2083  return 0;
2084}
2085#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2086
2087/*
2088** Print N dashes
2089*/
2090static void print_dashes(FILE *out, int N){
2091  const char zDash[] = "--------------------------------------------------";
2092  const int nDash = sizeof(zDash) - 1;
2093  while( N>nDash ){
2094    fputs(zDash, out);
2095    N -= nDash;
2096  }
2097  raw_printf(out, "%.*s", N, zDash);
2098}
2099
2100/*
2101** Print a markdown or table-style row separator using ascii-art
2102*/
2103static void print_row_separator(
2104  ShellState *p,
2105  int nArg,
2106  const char *zSep
2107){
2108  int i;
2109  if( nArg>0 ){
2110    fputs(zSep, p->out);
2111    print_dashes(p->out, p->actualWidth[0]+2);
2112    for(i=1; i<nArg; i++){
2113      fputs(zSep, p->out);
2114      print_dashes(p->out, p->actualWidth[i]+2);
2115    }
2116    fputs(zSep, p->out);
2117  }
2118  fputs("\n", p->out);
2119}
2120
2121/*
2122** This is the callback routine that the shell
2123** invokes for each row of a query result.
2124*/
2125static int shell_callback(
2126  void *pArg,
2127  int nArg,        /* Number of result columns */
2128  char **azArg,    /* Text of each result column */
2129  char **azCol,    /* Column names */
2130  int *aiType      /* Column types.  Might be NULL */
2131){
2132  int i;
2133  ShellState *p = (ShellState*)pArg;
2134
2135  if( azArg==0 ) return 0;
2136  switch( p->cMode ){
2137    case MODE_Count:
2138    case MODE_Off: {
2139      break;
2140    }
2141    case MODE_Line: {
2142      int w = 5;
2143      if( azArg==0 ) break;
2144      for(i=0; i<nArg; i++){
2145        int len = strlen30(azCol[i] ? azCol[i] : "");
2146        if( len>w ) w = len;
2147      }
2148      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2149      for(i=0; i<nArg; i++){
2150        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2151                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2152      }
2153      break;
2154    }
2155    case MODE_Explain: {
2156      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2157      if( nArg>ArraySize(aExplainWidth) ){
2158        nArg = ArraySize(aExplainWidth);
2159      }
2160      if( p->cnt++==0 ){
2161        for(i=0; i<nArg; i++){
2162          int w = aExplainWidth[i];
2163          utf8_width_print(p->out, w, azCol[i]);
2164          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2165        }
2166        for(i=0; i<nArg; i++){
2167          int w = aExplainWidth[i];
2168          print_dashes(p->out, w);
2169          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2170        }
2171      }
2172      if( azArg==0 ) break;
2173      for(i=0; i<nArg; i++){
2174        int w = aExplainWidth[i];
2175        if( i==nArg-1 ) w = 0;
2176        if( azArg[i] && strlenChar(azArg[i])>w ){
2177          w = strlenChar(azArg[i]);
2178        }
2179        if( i==1 && p->aiIndent && p->pStmt ){
2180          if( p->iIndent<p->nIndent ){
2181            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2182          }
2183          p->iIndent++;
2184        }
2185        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2186        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2187      }
2188      break;
2189    }
2190    case MODE_Semi: {   /* .schema and .fullschema output */
2191      printSchemaLine(p->out, azArg[0], ";\n");
2192      break;
2193    }
2194    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2195      char *z;
2196      int j;
2197      int nParen = 0;
2198      char cEnd = 0;
2199      char c;
2200      int nLine = 0;
2201      assert( nArg==1 );
2202      if( azArg[0]==0 ) break;
2203      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2204       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2205      ){
2206        utf8_printf(p->out, "%s;\n", azArg[0]);
2207        break;
2208      }
2209      z = sqlite3_mprintf("%s", azArg[0]);
2210      shell_check_oom(z);
2211      j = 0;
2212      for(i=0; IsSpace(z[i]); i++){}
2213      for(; (c = z[i])!=0; i++){
2214        if( IsSpace(c) ){
2215          if( z[j-1]=='\r' ) z[j-1] = '\n';
2216          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2217        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2218          j--;
2219        }
2220        z[j++] = c;
2221      }
2222      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2223      z[j] = 0;
2224      if( strlen30(z)>=79 ){
2225        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2226          if( c==cEnd ){
2227            cEnd = 0;
2228          }else if( c=='"' || c=='\'' || c=='`' ){
2229            cEnd = c;
2230          }else if( c=='[' ){
2231            cEnd = ']';
2232          }else if( c=='-' && z[i+1]=='-' ){
2233            cEnd = '\n';
2234          }else if( c=='(' ){
2235            nParen++;
2236          }else if( c==')' ){
2237            nParen--;
2238            if( nLine>0 && nParen==0 && j>0 ){
2239              printSchemaLineN(p->out, z, j, "\n");
2240              j = 0;
2241            }
2242          }
2243          z[j++] = c;
2244          if( nParen==1 && cEnd==0
2245           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2246          ){
2247            if( c=='\n' ) j--;
2248            printSchemaLineN(p->out, z, j, "\n  ");
2249            j = 0;
2250            nLine++;
2251            while( IsSpace(z[i+1]) ){ i++; }
2252          }
2253        }
2254        z[j] = 0;
2255      }
2256      printSchemaLine(p->out, z, ";\n");
2257      sqlite3_free(z);
2258      break;
2259    }
2260    case MODE_List: {
2261      if( p->cnt++==0 && p->showHeader ){
2262        for(i=0; i<nArg; i++){
2263          utf8_printf(p->out,"%s%s",azCol[i],
2264                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2265        }
2266      }
2267      if( azArg==0 ) break;
2268      for(i=0; i<nArg; i++){
2269        char *z = azArg[i];
2270        if( z==0 ) z = p->nullValue;
2271        utf8_printf(p->out, "%s", z);
2272        if( i<nArg-1 ){
2273          utf8_printf(p->out, "%s", p->colSeparator);
2274        }else{
2275          utf8_printf(p->out, "%s", p->rowSeparator);
2276        }
2277      }
2278      break;
2279    }
2280    case MODE_Html: {
2281      if( p->cnt++==0 && p->showHeader ){
2282        raw_printf(p->out,"<TR>");
2283        for(i=0; i<nArg; i++){
2284          raw_printf(p->out,"<TH>");
2285          output_html_string(p->out, azCol[i]);
2286          raw_printf(p->out,"</TH>\n");
2287        }
2288        raw_printf(p->out,"</TR>\n");
2289      }
2290      if( azArg==0 ) break;
2291      raw_printf(p->out,"<TR>");
2292      for(i=0; i<nArg; i++){
2293        raw_printf(p->out,"<TD>");
2294        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2295        raw_printf(p->out,"</TD>\n");
2296      }
2297      raw_printf(p->out,"</TR>\n");
2298      break;
2299    }
2300    case MODE_Tcl: {
2301      if( p->cnt++==0 && p->showHeader ){
2302        for(i=0; i<nArg; i++){
2303          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2304          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2305        }
2306        utf8_printf(p->out, "%s", p->rowSeparator);
2307      }
2308      if( azArg==0 ) break;
2309      for(i=0; i<nArg; i++){
2310        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2311        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2312      }
2313      utf8_printf(p->out, "%s", p->rowSeparator);
2314      break;
2315    }
2316    case MODE_Csv: {
2317      setBinaryMode(p->out, 1);
2318      if( p->cnt++==0 && p->showHeader ){
2319        for(i=0; i<nArg; i++){
2320          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2321        }
2322        utf8_printf(p->out, "%s", p->rowSeparator);
2323      }
2324      if( nArg>0 ){
2325        for(i=0; i<nArg; i++){
2326          output_csv(p, azArg[i], i<nArg-1);
2327        }
2328        utf8_printf(p->out, "%s", p->rowSeparator);
2329      }
2330      setTextMode(p->out, 1);
2331      break;
2332    }
2333    case MODE_Insert: {
2334      if( azArg==0 ) break;
2335      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2336      if( p->showHeader ){
2337        raw_printf(p->out,"(");
2338        for(i=0; i<nArg; i++){
2339          if( i>0 ) raw_printf(p->out, ",");
2340          if( quoteChar(azCol[i]) ){
2341            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2342            shell_check_oom(z);
2343            utf8_printf(p->out, "%s", z);
2344            sqlite3_free(z);
2345          }else{
2346            raw_printf(p->out, "%s", azCol[i]);
2347          }
2348        }
2349        raw_printf(p->out,")");
2350      }
2351      p->cnt++;
2352      for(i=0; i<nArg; i++){
2353        raw_printf(p->out, i>0 ? "," : " VALUES(");
2354        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2355          utf8_printf(p->out,"NULL");
2356        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2357          if( ShellHasFlag(p, SHFLG_Newlines) ){
2358            output_quoted_string(p->out, azArg[i]);
2359          }else{
2360            output_quoted_escaped_string(p->out, azArg[i]);
2361          }
2362        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2363          utf8_printf(p->out,"%s", azArg[i]);
2364        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2365          char z[50];
2366          double r = sqlite3_column_double(p->pStmt, i);
2367          sqlite3_uint64 ur;
2368          memcpy(&ur,&r,sizeof(r));
2369          if( ur==0x7ff0000000000000LL ){
2370            raw_printf(p->out, "1e999");
2371          }else if( ur==0xfff0000000000000LL ){
2372            raw_printf(p->out, "-1e999");
2373          }else{
2374            sqlite3_int64 ir = (sqlite3_int64)r;
2375            if( r==(double)ir ){
2376              sqlite3_snprintf(50,z,"%lld.0", ir);
2377            }else{
2378              sqlite3_snprintf(50,z,"%!.20g", r);
2379            }
2380            raw_printf(p->out, "%s", z);
2381          }
2382        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2383          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2384          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2385          output_hex_blob(p->out, pBlob, nBlob);
2386        }else if( isNumber(azArg[i], 0) ){
2387          utf8_printf(p->out,"%s", azArg[i]);
2388        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2389          output_quoted_string(p->out, azArg[i]);
2390        }else{
2391          output_quoted_escaped_string(p->out, azArg[i]);
2392        }
2393      }
2394      raw_printf(p->out,");\n");
2395      break;
2396    }
2397    case MODE_Json: {
2398      if( azArg==0 ) break;
2399      if( p->cnt==0 ){
2400        fputs("[{", p->out);
2401      }else{
2402        fputs(",\n{", p->out);
2403      }
2404      p->cnt++;
2405      for(i=0; i<nArg; i++){
2406        output_json_string(p->out, azCol[i], -1);
2407        putc(':', p->out);
2408        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2409          fputs("null",p->out);
2410        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2411          char z[50];
2412          double r = sqlite3_column_double(p->pStmt, i);
2413          sqlite3_uint64 ur;
2414          memcpy(&ur,&r,sizeof(r));
2415          if( ur==0x7ff0000000000000LL ){
2416            raw_printf(p->out, "1e999");
2417          }else if( ur==0xfff0000000000000LL ){
2418            raw_printf(p->out, "-1e999");
2419          }else{
2420            sqlite3_snprintf(50,z,"%!.20g", r);
2421            raw_printf(p->out, "%s", z);
2422          }
2423        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2424          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2425          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2426          output_json_string(p->out, pBlob, nBlob);
2427        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2428          output_json_string(p->out, azArg[i], -1);
2429        }else{
2430          utf8_printf(p->out,"%s", azArg[i]);
2431        }
2432        if( i<nArg-1 ){
2433          putc(',', p->out);
2434        }
2435      }
2436      putc('}', p->out);
2437      break;
2438    }
2439    case MODE_Quote: {
2440      if( azArg==0 ) break;
2441      if( p->cnt==0 && p->showHeader ){
2442        for(i=0; i<nArg; i++){
2443          if( i>0 ) fputs(p->colSeparator, p->out);
2444          output_quoted_string(p->out, azCol[i]);
2445        }
2446        fputs(p->rowSeparator, p->out);
2447      }
2448      p->cnt++;
2449      for(i=0; i<nArg; i++){
2450        if( i>0 ) fputs(p->colSeparator, p->out);
2451        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2452          utf8_printf(p->out,"NULL");
2453        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2454          output_quoted_string(p->out, azArg[i]);
2455        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2456          utf8_printf(p->out,"%s", azArg[i]);
2457        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2458          char z[50];
2459          double r = sqlite3_column_double(p->pStmt, i);
2460          sqlite3_snprintf(50,z,"%!.20g", r);
2461          raw_printf(p->out, "%s", z);
2462        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2463          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2464          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2465          output_hex_blob(p->out, pBlob, nBlob);
2466        }else if( isNumber(azArg[i], 0) ){
2467          utf8_printf(p->out,"%s", azArg[i]);
2468        }else{
2469          output_quoted_string(p->out, azArg[i]);
2470        }
2471      }
2472      fputs(p->rowSeparator, p->out);
2473      break;
2474    }
2475    case MODE_Ascii: {
2476      if( p->cnt++==0 && p->showHeader ){
2477        for(i=0; i<nArg; i++){
2478          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2479          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2480        }
2481        utf8_printf(p->out, "%s", p->rowSeparator);
2482      }
2483      if( azArg==0 ) break;
2484      for(i=0; i<nArg; i++){
2485        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2486        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2487      }
2488      utf8_printf(p->out, "%s", p->rowSeparator);
2489      break;
2490    }
2491    case MODE_EQP: {
2492      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2493      break;
2494    }
2495  }
2496  return 0;
2497}
2498
2499/*
2500** This is the callback routine that the SQLite library
2501** invokes for each row of a query result.
2502*/
2503static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2504  /* since we don't have type info, call the shell_callback with a NULL value */
2505  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2506}
2507
2508/*
2509** This is the callback routine from sqlite3_exec() that appends all
2510** output onto the end of a ShellText object.
2511*/
2512static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2513  ShellText *p = (ShellText*)pArg;
2514  int i;
2515  UNUSED_PARAMETER(az);
2516  if( azArg==0 ) return 0;
2517  if( p->n ) appendText(p, "|", 0);
2518  for(i=0; i<nArg; i++){
2519    if( i ) appendText(p, ",", 0);
2520    if( azArg[i] ) appendText(p, azArg[i], 0);
2521  }
2522  return 0;
2523}
2524
2525/*
2526** Generate an appropriate SELFTEST table in the main database.
2527*/
2528static void createSelftestTable(ShellState *p){
2529  char *zErrMsg = 0;
2530  sqlite3_exec(p->db,
2531    "SAVEPOINT selftest_init;\n"
2532    "CREATE TABLE IF NOT EXISTS selftest(\n"
2533    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2534    "  op TEXT,\n"                   /* Operator:  memo run */
2535    "  cmd TEXT,\n"                  /* Command text */
2536    "  ans TEXT\n"                   /* Desired answer */
2537    ");"
2538    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2539    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2540    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2541    "         'memo','Tests generated by --init');\n"
2542    "INSERT INTO [_shell$self]\n"
2543    "  SELECT 'run',\n"
2544    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2545                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2546    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2547                          "FROM sqlite_schema ORDER BY 2',224));\n"
2548    "INSERT INTO [_shell$self]\n"
2549    "  SELECT 'run',"
2550    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2551    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2552    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2553    "  FROM (\n"
2554    "    SELECT name FROM sqlite_schema\n"
2555    "     WHERE type='table'\n"
2556    "       AND name<>'selftest'\n"
2557    "       AND coalesce(rootpage,0)>0\n"
2558    "  )\n"
2559    " ORDER BY name;\n"
2560    "INSERT INTO [_shell$self]\n"
2561    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2562    "INSERT INTO selftest(tno,op,cmd,ans)"
2563    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2564    "DROP TABLE [_shell$self];"
2565    ,0,0,&zErrMsg);
2566  if( zErrMsg ){
2567    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2568    sqlite3_free(zErrMsg);
2569  }
2570  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2571}
2572
2573
2574/*
2575** Set the destination table field of the ShellState structure to
2576** the name of the table given.  Escape any quote characters in the
2577** table name.
2578*/
2579static void set_table_name(ShellState *p, const char *zName){
2580  int i, n;
2581  char cQuote;
2582  char *z;
2583
2584  if( p->zDestTable ){
2585    free(p->zDestTable);
2586    p->zDestTable = 0;
2587  }
2588  if( zName==0 ) return;
2589  cQuote = quoteChar(zName);
2590  n = strlen30(zName);
2591  if( cQuote ) n += n+2;
2592  z = p->zDestTable = malloc( n+1 );
2593  shell_check_oom(z);
2594  n = 0;
2595  if( cQuote ) z[n++] = cQuote;
2596  for(i=0; zName[i]; i++){
2597    z[n++] = zName[i];
2598    if( zName[i]==cQuote ) z[n++] = cQuote;
2599  }
2600  if( cQuote ) z[n++] = cQuote;
2601  z[n] = 0;
2602}
2603
2604/*
2605** Maybe construct two lines of text that point out the position of a
2606** syntax error.  Return a pointer to the text, in memory obtained from
2607** sqlite3_malloc().  Or, if the most recent error does not involve a
2608** specific token that we can point to, return an empty string.
2609**
2610** In all cases, the memory returned is obtained from sqlite3_malloc64()
2611** and should be released by the caller invoking sqlite3_free().
2612*/
2613static char *shell_error_context(const char *zSql, sqlite3 *db){
2614  int iOffset;
2615  size_t len;
2616  char *zCode;
2617  char *zMsg;
2618  int i;
2619  if( db==0
2620   || zSql==0
2621   || (iOffset = sqlite3_error_offset(db))<0
2622  ){
2623    return sqlite3_mprintf("");
2624  }
2625  while( iOffset>50 ){
2626    iOffset--;
2627    zSql++;
2628    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2629  }
2630  len = strlen(zSql);
2631  if( len>78 ){
2632    len = 78;
2633    while( (zSql[len]&0xc0)==0x80 ) len--;
2634  }
2635  zCode = sqlite3_mprintf("%.*s", len, zSql);
2636  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2637  if( iOffset<25 ){
2638    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2639  }else{
2640    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2641  }
2642  return zMsg;
2643}
2644
2645
2646/*
2647** Execute a query statement that will generate SQL output.  Print
2648** the result columns, comma-separated, on a line and then add a
2649** semicolon terminator to the end of that line.
2650**
2651** If the number of columns is 1 and that column contains text "--"
2652** then write the semicolon on a separate line.  That way, if a
2653** "--" comment occurs at the end of the statement, the comment
2654** won't consume the semicolon terminator.
2655*/
2656static int run_table_dump_query(
2657  ShellState *p,           /* Query context */
2658  const char *zSelect      /* SELECT statement to extract content */
2659){
2660  sqlite3_stmt *pSelect;
2661  int rc;
2662  int nResult;
2663  int i;
2664  const char *z;
2665  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2666  if( rc!=SQLITE_OK || !pSelect ){
2667    char *zContext = shell_error_context(zSelect, p->db);
2668    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2669                sqlite3_errmsg(p->db), zContext);
2670    sqlite3_free(zContext);
2671    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2672    return rc;
2673  }
2674  rc = sqlite3_step(pSelect);
2675  nResult = sqlite3_column_count(pSelect);
2676  while( rc==SQLITE_ROW ){
2677    z = (const char*)sqlite3_column_text(pSelect, 0);
2678    utf8_printf(p->out, "%s", z);
2679    for(i=1; i<nResult; i++){
2680      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2681    }
2682    if( z==0 ) z = "";
2683    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2684    if( z[0] ){
2685      raw_printf(p->out, "\n;\n");
2686    }else{
2687      raw_printf(p->out, ";\n");
2688    }
2689    rc = sqlite3_step(pSelect);
2690  }
2691  rc = sqlite3_finalize(pSelect);
2692  if( rc!=SQLITE_OK ){
2693    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2694                sqlite3_errmsg(p->db));
2695    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2696  }
2697  return rc;
2698}
2699
2700/*
2701** Allocate space and save off string indicating current error.
2702*/
2703static char *save_err_msg(
2704  sqlite3 *db,           /* Database to query */
2705  const char *zPhase,    /* When the error occcurs */
2706  int rc,                /* Error code returned from API */
2707  const char *zSql       /* SQL string, or NULL */
2708){
2709  char *zErr;
2710  char *zContext;
2711  sqlite3_str *pStr = sqlite3_str_new(0);
2712  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2713  if( rc>1 ){
2714    sqlite3_str_appendf(pStr, " (%d)", rc);
2715  }
2716  zContext = shell_error_context(zSql, db);
2717  if( zContext ){
2718    sqlite3_str_appendall(pStr, zContext);
2719    sqlite3_free(zContext);
2720  }
2721  zErr = sqlite3_str_finish(pStr);
2722  shell_check_oom(zErr);
2723  return zErr;
2724}
2725
2726#ifdef __linux__
2727/*
2728** Attempt to display I/O stats on Linux using /proc/PID/io
2729*/
2730static void displayLinuxIoStats(FILE *out){
2731  FILE *in;
2732  char z[200];
2733  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2734  in = fopen(z, "rb");
2735  if( in==0 ) return;
2736  while( fgets(z, sizeof(z), in)!=0 ){
2737    static const struct {
2738      const char *zPattern;
2739      const char *zDesc;
2740    } aTrans[] = {
2741      { "rchar: ",                  "Bytes received by read():" },
2742      { "wchar: ",                  "Bytes sent to write():"    },
2743      { "syscr: ",                  "Read() system calls:"      },
2744      { "syscw: ",                  "Write() system calls:"     },
2745      { "read_bytes: ",             "Bytes read from storage:"  },
2746      { "write_bytes: ",            "Bytes written to storage:" },
2747      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2748    };
2749    int i;
2750    for(i=0; i<ArraySize(aTrans); i++){
2751      int n = strlen30(aTrans[i].zPattern);
2752      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2753        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2754        break;
2755      }
2756    }
2757  }
2758  fclose(in);
2759}
2760#endif
2761
2762/*
2763** Display a single line of status using 64-bit values.
2764*/
2765static void displayStatLine(
2766  ShellState *p,            /* The shell context */
2767  char *zLabel,             /* Label for this one line */
2768  char *zFormat,            /* Format for the result */
2769  int iStatusCtrl,          /* Which status to display */
2770  int bReset                /* True to reset the stats */
2771){
2772  sqlite3_int64 iCur = -1;
2773  sqlite3_int64 iHiwtr = -1;
2774  int i, nPercent;
2775  char zLine[200];
2776  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2777  for(i=0, nPercent=0; zFormat[i]; i++){
2778    if( zFormat[i]=='%' ) nPercent++;
2779  }
2780  if( nPercent>1 ){
2781    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2782  }else{
2783    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2784  }
2785  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2786}
2787
2788/*
2789** Display memory stats.
2790*/
2791static int display_stats(
2792  sqlite3 *db,                /* Database to query */
2793  ShellState *pArg,           /* Pointer to ShellState */
2794  int bReset                  /* True to reset the stats */
2795){
2796  int iCur;
2797  int iHiwtr;
2798  FILE *out;
2799  if( pArg==0 || pArg->out==0 ) return 0;
2800  out = pArg->out;
2801
2802  if( pArg->pStmt && pArg->statsOn==2 ){
2803    int nCol, i, x;
2804    sqlite3_stmt *pStmt = pArg->pStmt;
2805    char z[100];
2806    nCol = sqlite3_column_count(pStmt);
2807    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2808    for(i=0; i<nCol; i++){
2809      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2810      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2811#ifndef SQLITE_OMIT_DECLTYPE
2812      sqlite3_snprintf(30, z+x, "declared type:");
2813      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2814#endif
2815#ifdef SQLITE_ENABLE_COLUMN_METADATA
2816      sqlite3_snprintf(30, z+x, "database name:");
2817      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2818      sqlite3_snprintf(30, z+x, "table name:");
2819      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2820      sqlite3_snprintf(30, z+x, "origin name:");
2821      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2822#endif
2823    }
2824  }
2825
2826  if( pArg->statsOn==3 ){
2827    if( pArg->pStmt ){
2828      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2829      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2830    }
2831    return 0;
2832  }
2833
2834  displayStatLine(pArg, "Memory Used:",
2835     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2836  displayStatLine(pArg, "Number of Outstanding Allocations:",
2837     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2838  if( pArg->shellFlgs & SHFLG_Pagecache ){
2839    displayStatLine(pArg, "Number of Pcache Pages Used:",
2840       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2841  }
2842  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2843     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2844  displayStatLine(pArg, "Largest Allocation:",
2845     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2846  displayStatLine(pArg, "Largest Pcache Allocation:",
2847     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2848#ifdef YYTRACKMAXSTACKDEPTH
2849  displayStatLine(pArg, "Deepest Parser Stack:",
2850     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2851#endif
2852
2853  if( db ){
2854    if( pArg->shellFlgs & SHFLG_Lookaside ){
2855      iHiwtr = iCur = -1;
2856      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2857                        &iCur, &iHiwtr, bReset);
2858      raw_printf(pArg->out,
2859              "Lookaside Slots Used:                %d (max %d)\n",
2860              iCur, iHiwtr);
2861      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2862                        &iCur, &iHiwtr, bReset);
2863      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2864              iHiwtr);
2865      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2866                        &iCur, &iHiwtr, bReset);
2867      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2868              iHiwtr);
2869      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2870                        &iCur, &iHiwtr, bReset);
2871      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2872              iHiwtr);
2873    }
2874    iHiwtr = iCur = -1;
2875    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2876    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2877            iCur);
2878    iHiwtr = iCur = -1;
2879    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2880    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2881    iHiwtr = iCur = -1;
2882    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2883    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2884    iHiwtr = iCur = -1;
2885    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2886    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2887    iHiwtr = iCur = -1;
2888    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2889    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2890    iHiwtr = iCur = -1;
2891    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2892    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2893            iCur);
2894    iHiwtr = iCur = -1;
2895    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2896    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2897            iCur);
2898  }
2899
2900  if( pArg->pStmt ){
2901    int iHit, iMiss;
2902    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2903                               bReset);
2904    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2905    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2906    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2907    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2908    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2909    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2910    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2911    if( iHit || iMiss ){
2912      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2913            iHit, iHit+iMiss);
2914    }
2915    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2916    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2917    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2918    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2919    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2920    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2921    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2922    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2923  }
2924
2925#ifdef __linux__
2926  displayLinuxIoStats(pArg->out);
2927#endif
2928
2929  /* Do not remove this machine readable comment: extra-stats-output-here */
2930
2931  return 0;
2932}
2933
2934/*
2935** Display scan stats.
2936*/
2937static void display_scanstats(
2938  sqlite3 *db,                    /* Database to query */
2939  ShellState *pArg                /* Pointer to ShellState */
2940){
2941#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2942  UNUSED_PARAMETER(db);
2943  UNUSED_PARAMETER(pArg);
2944#else
2945  int i, k, n, mx;
2946  raw_printf(pArg->out, "-------- scanstats --------\n");
2947  mx = 0;
2948  for(k=0; k<=mx; k++){
2949    double rEstLoop = 1.0;
2950    for(i=n=0; 1; i++){
2951      sqlite3_stmt *p = pArg->pStmt;
2952      sqlite3_int64 nLoop, nVisit;
2953      double rEst;
2954      int iSid;
2955      const char *zExplain;
2956      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2957        break;
2958      }
2959      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2960      if( iSid>mx ) mx = iSid;
2961      if( iSid!=k ) continue;
2962      if( n==0 ){
2963        rEstLoop = (double)nLoop;
2964        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2965      }
2966      n++;
2967      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2968      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2969      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2970      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2971      rEstLoop *= rEst;
2972      raw_printf(pArg->out,
2973          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2974          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2975      );
2976    }
2977  }
2978  raw_printf(pArg->out, "---------------------------\n");
2979#endif
2980}
2981
2982/*
2983** Parameter azArray points to a zero-terminated array of strings. zStr
2984** points to a single nul-terminated string. Return non-zero if zStr
2985** is equal, according to strcmp(), to any of the strings in the array.
2986** Otherwise, return zero.
2987*/
2988static int str_in_array(const char *zStr, const char **azArray){
2989  int i;
2990  for(i=0; azArray[i]; i++){
2991    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2992  }
2993  return 0;
2994}
2995
2996/*
2997** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2998** and populate the ShellState.aiIndent[] array with the number of
2999** spaces each opcode should be indented before it is output.
3000**
3001** The indenting rules are:
3002**
3003**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3004**       all opcodes that occur between the p2 jump destination and the opcode
3005**       itself by 2 spaces.
3006**
3007**     * Do the previous for "Return" instructions for when P2 is positive.
3008**       See tag-20220407a in wherecode.c and vdbe.c.
3009**
3010**     * For each "Goto", if the jump destination is earlier in the program
3011**       and ends on one of:
3012**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
3013**       or if the P1 parameter is one instead of zero,
3014**       then indent all opcodes between the earlier instruction
3015**       and "Goto" by 2 spaces.
3016*/
3017static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3018  const char *zSql;               /* The text of the SQL statement */
3019  const char *z;                  /* Used to check if this is an EXPLAIN */
3020  int *abYield = 0;               /* True if op is an OP_Yield */
3021  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
3022  int iOp;                        /* Index of operation in p->aiIndent[] */
3023
3024  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3025                           "Return", 0 };
3026  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3027                            "Rewind", 0 };
3028  const char *azGoto[] = { "Goto", 0 };
3029
3030  /* Try to figure out if this is really an EXPLAIN statement. If this
3031  ** cannot be verified, return early.  */
3032  if( sqlite3_column_count(pSql)!=8 ){
3033    p->cMode = p->mode;
3034    return;
3035  }
3036  zSql = sqlite3_sql(pSql);
3037  if( zSql==0 ) return;
3038  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3039  if( sqlite3_strnicmp(z, "explain", 7) ){
3040    p->cMode = p->mode;
3041    return;
3042  }
3043
3044  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3045    int i;
3046    int iAddr = sqlite3_column_int(pSql, 0);
3047    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3048
3049    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3050    ** p2 is an instruction address, set variable p2op to the index of that
3051    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3052    ** the current instruction is part of a sub-program generated by an
3053    ** SQL trigger or foreign key.  */
3054    int p2 = sqlite3_column_int(pSql, 3);
3055    int p2op = (p2 + (iOp-iAddr));
3056
3057    /* Grow the p->aiIndent array as required */
3058    if( iOp>=nAlloc ){
3059      if( iOp==0 ){
3060        /* Do further verfication that this is explain output.  Abort if
3061        ** it is not */
3062        static const char *explainCols[] = {
3063           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3064        int jj;
3065        for(jj=0; jj<ArraySize(explainCols); jj++){
3066          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3067            p->cMode = p->mode;
3068            sqlite3_reset(pSql);
3069            return;
3070          }
3071        }
3072      }
3073      nAlloc += 100;
3074      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3075      shell_check_oom(p->aiIndent);
3076      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3077      shell_check_oom(abYield);
3078    }
3079    abYield[iOp] = str_in_array(zOp, azYield);
3080    p->aiIndent[iOp] = 0;
3081    p->nIndent = iOp+1;
3082
3083    if( str_in_array(zOp, azNext) && p2op>0 ){
3084      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3085    }
3086    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3087     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3088    ){
3089      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3090    }
3091  }
3092
3093  p->iIndent = 0;
3094  sqlite3_free(abYield);
3095  sqlite3_reset(pSql);
3096}
3097
3098/*
3099** Free the array allocated by explain_data_prepare().
3100*/
3101static void explain_data_delete(ShellState *p){
3102  sqlite3_free(p->aiIndent);
3103  p->aiIndent = 0;
3104  p->nIndent = 0;
3105  p->iIndent = 0;
3106}
3107
3108/*
3109** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3110*/
3111static unsigned int savedSelectTrace;
3112static unsigned int savedWhereTrace;
3113static void disable_debug_trace_modes(void){
3114  unsigned int zero = 0;
3115  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3116  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3117  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3118  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3119}
3120static void restore_debug_trace_modes(void){
3121  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3122  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3123}
3124
3125/* Create the TEMP table used to store parameter bindings */
3126static void bind_table_init(ShellState *p){
3127  int wrSchema = 0;
3128  int defensiveMode = 0;
3129  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3130  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3131  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3132  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3133  sqlite3_exec(p->db,
3134    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3135    "  key TEXT PRIMARY KEY,\n"
3136    "  value\n"
3137    ") WITHOUT ROWID;",
3138    0, 0, 0);
3139  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3140  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3141}
3142
3143/*
3144** Bind parameters on a prepared statement.
3145**
3146** Parameter bindings are taken from a TEMP table of the form:
3147**
3148**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3149**    WITHOUT ROWID;
3150**
3151** No bindings occur if this table does not exist.  The name of the table
3152** begins with "sqlite_" so that it will not collide with ordinary application
3153** tables.  The table must be in the TEMP schema.
3154*/
3155static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3156  int nVar;
3157  int i;
3158  int rc;
3159  sqlite3_stmt *pQ = 0;
3160
3161  nVar = sqlite3_bind_parameter_count(pStmt);
3162  if( nVar==0 ) return;  /* Nothing to do */
3163  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3164                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3165    return; /* Parameter table does not exist */
3166  }
3167  rc = sqlite3_prepare_v2(pArg->db,
3168          "SELECT value FROM temp.sqlite_parameters"
3169          " WHERE key=?1", -1, &pQ, 0);
3170  if( rc || pQ==0 ) return;
3171  for(i=1; i<=nVar; i++){
3172    char zNum[30];
3173    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3174    if( zVar==0 ){
3175      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3176      zVar = zNum;
3177    }
3178    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3179    if( sqlite3_step(pQ)==SQLITE_ROW ){
3180      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3181    }else{
3182      sqlite3_bind_null(pStmt, i);
3183    }
3184    sqlite3_reset(pQ);
3185  }
3186  sqlite3_finalize(pQ);
3187}
3188
3189/*
3190** UTF8 box-drawing characters.  Imagine box lines like this:
3191**
3192**           1
3193**           |
3194**       4 --+-- 2
3195**           |
3196**           3
3197**
3198** Each box characters has between 2 and 4 of the lines leading from
3199** the center.  The characters are here identified by the numbers of
3200** their corresponding lines.
3201*/
3202#define BOX_24   "\342\224\200"  /* U+2500 --- */
3203#define BOX_13   "\342\224\202"  /* U+2502  |  */
3204#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3205#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3206#define BOX_12   "\342\224\224"  /* U+2514  '- */
3207#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3208#define BOX_123  "\342\224\234"  /* U+251c  |- */
3209#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3210#define BOX_234  "\342\224\254"  /* U+252c -,- */
3211#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3212#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3213
3214/* Draw horizontal line N characters long using unicode box
3215** characters
3216*/
3217static void print_box_line(FILE *out, int N){
3218  const char zDash[] =
3219      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3220      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3221  const int nDash = sizeof(zDash) - 1;
3222  N *= 3;
3223  while( N>nDash ){
3224    utf8_printf(out, zDash);
3225    N -= nDash;
3226  }
3227  utf8_printf(out, "%.*s", N, zDash);
3228}
3229
3230/*
3231** Draw a horizontal separator for a MODE_Box table.
3232*/
3233static void print_box_row_separator(
3234  ShellState *p,
3235  int nArg,
3236  const char *zSep1,
3237  const char *zSep2,
3238  const char *zSep3
3239){
3240  int i;
3241  if( nArg>0 ){
3242    utf8_printf(p->out, "%s", zSep1);
3243    print_box_line(p->out, p->actualWidth[0]+2);
3244    for(i=1; i<nArg; i++){
3245      utf8_printf(p->out, "%s", zSep2);
3246      print_box_line(p->out, p->actualWidth[i]+2);
3247    }
3248    utf8_printf(p->out, "%s", zSep3);
3249  }
3250  fputs("\n", p->out);
3251}
3252
3253/*
3254** z[] is a line of text that is to be displayed the .mode box or table or
3255** similar tabular formats.  z[] might contain control characters such
3256** as \n, \t, \f, or \r.
3257**
3258** Compute characters to display on the first line of z[].  Stop at the
3259** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3260** from malloc()) of that first line, which caller should free sometime.
3261** Write anything to display on the next line into *pzTail.  If this is
3262** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3263*/
3264static char *translateForDisplayAndDup(
3265  const unsigned char *z,            /* Input text to be transformed */
3266  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3267  int mxWidth,                       /* Max width.  0 means no limit */
3268  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3269){
3270  int i;                 /* Input bytes consumed */
3271  int j;                 /* Output bytes generated */
3272  int k;                 /* Input bytes to be displayed */
3273  int n;                 /* Output column number */
3274  unsigned char *zOut;   /* Output text */
3275
3276  if( z==0 ){
3277    *pzTail = 0;
3278    return 0;
3279  }
3280  if( mxWidth<0 ) mxWidth = -mxWidth;
3281  if( mxWidth==0 ) mxWidth = 1000000;
3282  i = j = n = 0;
3283  while( n<mxWidth ){
3284    if( z[i]>=' ' ){
3285      n++;
3286      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3287      continue;
3288    }
3289    if( z[i]=='\t' ){
3290      do{
3291        n++;
3292        j++;
3293      }while( (n&7)!=0 && n<mxWidth );
3294      i++;
3295      continue;
3296    }
3297    break;
3298  }
3299  if( n>=mxWidth && bWordWrap  ){
3300    /* Perhaps try to back up to a better place to break the line */
3301    for(k=i; k>i/2; k--){
3302      if( isspace(z[k-1]) ) break;
3303    }
3304    if( k<=i/2 ){
3305      for(k=i; k>i/2; k--){
3306        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3307      }
3308    }
3309    if( k<=i/2 ){
3310      k = i;
3311    }else{
3312      i = k;
3313      while( z[i]==' ' ) i++;
3314    }
3315  }else{
3316    k = i;
3317  }
3318  if( n>=mxWidth && z[i]>=' ' ){
3319   *pzTail = &z[i];
3320  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3321    *pzTail = z[i+2] ? &z[i+2] : 0;
3322  }else if( z[i]==0 || z[i+1]==0 ){
3323    *pzTail = 0;
3324  }else{
3325    *pzTail = &z[i+1];
3326  }
3327  zOut = malloc( j+1 );
3328  shell_check_oom(zOut);
3329  i = j = n = 0;
3330  while( i<k ){
3331    if( z[i]>=' ' ){
3332      n++;
3333      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3334      continue;
3335    }
3336    if( z[i]=='\t' ){
3337      do{
3338        n++;
3339        zOut[j++] = ' ';
3340      }while( (n&7)!=0 && n<mxWidth );
3341      i++;
3342      continue;
3343    }
3344    break;
3345  }
3346  zOut[j] = 0;
3347  return (char*)zOut;
3348}
3349
3350/* Extract the value of the i-th current column for pStmt as an SQL literal
3351** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3352** the caller.
3353*/
3354static char *quoted_column(sqlite3_stmt *pStmt, int i){
3355  switch( sqlite3_column_type(pStmt, i) ){
3356    case SQLITE_NULL: {
3357      return sqlite3_mprintf("NULL");
3358    }
3359    case SQLITE_INTEGER:
3360    case SQLITE_FLOAT: {
3361      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3362    }
3363    case SQLITE_TEXT: {
3364      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3365    }
3366    case SQLITE_BLOB: {
3367      int j;
3368      sqlite3_str *pStr = sqlite3_str_new(0);
3369      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3370      int n = sqlite3_column_bytes(pStmt,i);
3371      sqlite3_str_append(pStr, "x'", 2);
3372      for(j=0; j<n; j++){
3373        sqlite3_str_appendf(pStr, "%02x", a[j]);
3374      }
3375      sqlite3_str_append(pStr, "'", 1);
3376      return sqlite3_str_finish(pStr);
3377    }
3378  }
3379  return 0; /* Not reached */
3380}
3381
3382/*
3383** Run a prepared statement and output the result in one of the
3384** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3385** or MODE_Box.
3386**
3387** This is different from ordinary exec_prepared_stmt() in that
3388** it has to run the entire query and gather the results into memory
3389** first, in order to determine column widths, before providing
3390** any output.
3391*/
3392static void exec_prepared_stmt_columnar(
3393  ShellState *p,                        /* Pointer to ShellState */
3394  sqlite3_stmt *pStmt                   /* Statment to run */
3395){
3396  sqlite3_int64 nRow = 0;
3397  int nColumn = 0;
3398  char **azData = 0;
3399  sqlite3_int64 nAlloc = 0;
3400  char *abRowDiv = 0;
3401  const unsigned char *uz;
3402  const char *z;
3403  char **azQuoted = 0;
3404  int rc;
3405  sqlite3_int64 i, nData;
3406  int j, nTotal, w, n;
3407  const char *colSep = 0;
3408  const char *rowSep = 0;
3409  const unsigned char **azNextLine = 0;
3410  int bNextLine = 0;
3411  int bMultiLineRowExists = 0;
3412  int bw = p->cmOpts.bWordWrap;
3413  const char *zEmpty = "";
3414  const char *zShowNull = p->nullValue;
3415
3416  rc = sqlite3_step(pStmt);
3417  if( rc!=SQLITE_ROW ) return;
3418  nColumn = sqlite3_column_count(pStmt);
3419  nAlloc = nColumn*4;
3420  if( nAlloc<=0 ) nAlloc = 1;
3421  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3422  shell_check_oom(azData);
3423  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3424  shell_check_oom((void*)azNextLine);
3425  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3426  if( p->cmOpts.bQuote ){
3427    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3428    shell_check_oom(azQuoted);
3429    memset(azQuoted, 0, nColumn*sizeof(char*) );
3430  }
3431  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3432  shell_check_oom(abRowDiv);
3433  if( nColumn>p->nWidth ){
3434    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3435    shell_check_oom(p->colWidth);
3436    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3437    p->nWidth = nColumn;
3438    p->actualWidth = &p->colWidth[nColumn];
3439  }
3440  memset(p->actualWidth, 0, nColumn*sizeof(int));
3441  for(i=0; i<nColumn; i++){
3442    w = p->colWidth[i];
3443    if( w<0 ) w = -w;
3444    p->actualWidth[i] = w;
3445  }
3446  for(i=0; i<nColumn; i++){
3447    const unsigned char *zNotUsed;
3448    int wx = p->colWidth[i];
3449    if( wx==0 ){
3450      wx = p->cmOpts.iWrap;
3451    }
3452    if( wx<0 ) wx = -wx;
3453    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3454    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3455  }
3456  do{
3457    int useNextLine = bNextLine;
3458    bNextLine = 0;
3459    if( (nRow+2)*nColumn >= nAlloc ){
3460      nAlloc *= 2;
3461      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3462      shell_check_oom(azData);
3463      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3464      shell_check_oom(abRowDiv);
3465    }
3466    abRowDiv[nRow] = 1;
3467    nRow++;
3468    for(i=0; i<nColumn; i++){
3469      int wx = p->colWidth[i];
3470      if( wx==0 ){
3471        wx = p->cmOpts.iWrap;
3472      }
3473      if( wx<0 ) wx = -wx;
3474      if( useNextLine ){
3475        uz = azNextLine[i];
3476        if( uz==0 ) uz = (u8*)zEmpty;
3477      }else if( p->cmOpts.bQuote ){
3478        sqlite3_free(azQuoted[i]);
3479        azQuoted[i] = quoted_column(pStmt,i);
3480        uz = (const unsigned char*)azQuoted[i];
3481      }else{
3482        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3483        if( uz==0 ) uz = (u8*)zShowNull;
3484      }
3485      azData[nRow*nColumn + i]
3486        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3487      if( azNextLine[i] ){
3488        bNextLine = 1;
3489        abRowDiv[nRow-1] = 0;
3490        bMultiLineRowExists = 1;
3491      }
3492    }
3493  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3494  nTotal = nColumn*(nRow+1);
3495  for(i=0; i<nTotal; i++){
3496    z = azData[i];
3497    if( z==0 ) z = (char*)zEmpty;
3498    n = strlenChar(z);
3499    j = i%nColumn;
3500    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3501  }
3502  if( seenInterrupt ) goto columnar_end;
3503  if( nColumn==0 ) goto columnar_end;
3504  switch( p->cMode ){
3505    case MODE_Column: {
3506      colSep = "  ";
3507      rowSep = "\n";
3508      if( p->showHeader ){
3509        for(i=0; i<nColumn; i++){
3510          w = p->actualWidth[i];
3511          if( p->colWidth[i]<0 ) w = -w;
3512          utf8_width_print(p->out, w, azData[i]);
3513          fputs(i==nColumn-1?"\n":"  ", p->out);
3514        }
3515        for(i=0; i<nColumn; i++){
3516          print_dashes(p->out, p->actualWidth[i]);
3517          fputs(i==nColumn-1?"\n":"  ", p->out);
3518        }
3519      }
3520      break;
3521    }
3522    case MODE_Table: {
3523      colSep = " | ";
3524      rowSep = " |\n";
3525      print_row_separator(p, nColumn, "+");
3526      fputs("| ", p->out);
3527      for(i=0; i<nColumn; i++){
3528        w = p->actualWidth[i];
3529        n = strlenChar(azData[i]);
3530        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3531        fputs(i==nColumn-1?" |\n":" | ", p->out);
3532      }
3533      print_row_separator(p, nColumn, "+");
3534      break;
3535    }
3536    case MODE_Markdown: {
3537      colSep = " | ";
3538      rowSep = " |\n";
3539      fputs("| ", p->out);
3540      for(i=0; i<nColumn; i++){
3541        w = p->actualWidth[i];
3542        n = strlenChar(azData[i]);
3543        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3544        fputs(i==nColumn-1?" |\n":" | ", p->out);
3545      }
3546      print_row_separator(p, nColumn, "|");
3547      break;
3548    }
3549    case MODE_Box: {
3550      colSep = " " BOX_13 " ";
3551      rowSep = " " BOX_13 "\n";
3552      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3553      utf8_printf(p->out, BOX_13 " ");
3554      for(i=0; i<nColumn; i++){
3555        w = p->actualWidth[i];
3556        n = strlenChar(azData[i]);
3557        utf8_printf(p->out, "%*s%s%*s%s",
3558            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3559            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3560      }
3561      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3562      break;
3563    }
3564  }
3565  for(i=nColumn, j=0; i<nTotal; i++, j++){
3566    if( j==0 && p->cMode!=MODE_Column ){
3567      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3568    }
3569    z = azData[i];
3570    if( z==0 ) z = p->nullValue;
3571    w = p->actualWidth[j];
3572    if( p->colWidth[j]<0 ) w = -w;
3573    utf8_width_print(p->out, w, z);
3574    if( j==nColumn-1 ){
3575      utf8_printf(p->out, "%s", rowSep);
3576      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3577        if( p->cMode==MODE_Table ){
3578          print_row_separator(p, nColumn, "+");
3579        }else if( p->cMode==MODE_Box ){
3580          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3581        }else if( p->cMode==MODE_Column ){
3582          raw_printf(p->out, "\n");
3583        }
3584      }
3585      j = -1;
3586      if( seenInterrupt ) goto columnar_end;
3587    }else{
3588      utf8_printf(p->out, "%s", colSep);
3589    }
3590  }
3591  if( p->cMode==MODE_Table ){
3592    print_row_separator(p, nColumn, "+");
3593  }else if( p->cMode==MODE_Box ){
3594    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3595  }
3596columnar_end:
3597  if( seenInterrupt ){
3598    utf8_printf(p->out, "Interrupt\n");
3599  }
3600  nData = (nRow+1)*nColumn;
3601  for(i=0; i<nData; i++){
3602    z = azData[i];
3603    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3604  }
3605  sqlite3_free(azData);
3606  sqlite3_free((void*)azNextLine);
3607  sqlite3_free(abRowDiv);
3608  if( azQuoted ){
3609    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3610    sqlite3_free(azQuoted);
3611  }
3612}
3613
3614/*
3615** Run a prepared statement
3616*/
3617static void exec_prepared_stmt(
3618  ShellState *pArg,                                /* Pointer to ShellState */
3619  sqlite3_stmt *pStmt                              /* Statment to run */
3620){
3621  int rc;
3622  sqlite3_uint64 nRow = 0;
3623
3624  if( pArg->cMode==MODE_Column
3625   || pArg->cMode==MODE_Table
3626   || pArg->cMode==MODE_Box
3627   || pArg->cMode==MODE_Markdown
3628  ){
3629    exec_prepared_stmt_columnar(pArg, pStmt);
3630    return;
3631  }
3632
3633  /* perform the first step.  this will tell us if we
3634  ** have a result set or not and how wide it is.
3635  */
3636  rc = sqlite3_step(pStmt);
3637  /* if we have a result set... */
3638  if( SQLITE_ROW == rc ){
3639    /* allocate space for col name ptr, value ptr, and type */
3640    int nCol = sqlite3_column_count(pStmt);
3641    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3642    if( !pData ){
3643      shell_out_of_memory();
3644    }else{
3645      char **azCols = (char **)pData;      /* Names of result columns */
3646      char **azVals = &azCols[nCol];       /* Results */
3647      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3648      int i, x;
3649      assert(sizeof(int) <= sizeof(char *));
3650      /* save off ptrs to column names */
3651      for(i=0; i<nCol; i++){
3652        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3653      }
3654      do{
3655        nRow++;
3656        /* extract the data and data types */
3657        for(i=0; i<nCol; i++){
3658          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3659          if( x==SQLITE_BLOB
3660           && pArg
3661           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3662          ){
3663            azVals[i] = "";
3664          }else{
3665            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3666          }
3667          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3668            rc = SQLITE_NOMEM;
3669            break; /* from for */
3670          }
3671        } /* end for */
3672
3673        /* if data and types extracted successfully... */
3674        if( SQLITE_ROW == rc ){
3675          /* call the supplied callback with the result row data */
3676          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3677            rc = SQLITE_ABORT;
3678          }else{
3679            rc = sqlite3_step(pStmt);
3680          }
3681        }
3682      } while( SQLITE_ROW == rc );
3683      sqlite3_free(pData);
3684      if( pArg->cMode==MODE_Json ){
3685        fputs("]\n", pArg->out);
3686      }else if( pArg->cMode==MODE_Count ){
3687        char zBuf[200];
3688        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3689                         nRow, nRow!=1 ? "s" : "");
3690        printf("%s", zBuf);
3691      }
3692    }
3693  }
3694}
3695
3696#ifndef SQLITE_OMIT_VIRTUALTABLE
3697/*
3698** This function is called to process SQL if the previous shell command
3699** was ".expert". It passes the SQL in the second argument directly to
3700** the sqlite3expert object.
3701**
3702** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3703** code. In this case, (*pzErr) may be set to point to a buffer containing
3704** an English language error message. It is the responsibility of the
3705** caller to eventually free this buffer using sqlite3_free().
3706*/
3707static int expertHandleSQL(
3708  ShellState *pState,
3709  const char *zSql,
3710  char **pzErr
3711){
3712  assert( pState->expert.pExpert );
3713  assert( pzErr==0 || *pzErr==0 );
3714  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3715}
3716
3717/*
3718** This function is called either to silently clean up the object
3719** created by the ".expert" command (if bCancel==1), or to generate a
3720** report from it and then clean it up (if bCancel==0).
3721**
3722** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3723** code. In this case, (*pzErr) may be set to point to a buffer containing
3724** an English language error message. It is the responsibility of the
3725** caller to eventually free this buffer using sqlite3_free().
3726*/
3727static int expertFinish(
3728  ShellState *pState,
3729  int bCancel,
3730  char **pzErr
3731){
3732  int rc = SQLITE_OK;
3733  sqlite3expert *p = pState->expert.pExpert;
3734  assert( p );
3735  assert( bCancel || pzErr==0 || *pzErr==0 );
3736  if( bCancel==0 ){
3737    FILE *out = pState->out;
3738    int bVerbose = pState->expert.bVerbose;
3739
3740    rc = sqlite3_expert_analyze(p, pzErr);
3741    if( rc==SQLITE_OK ){
3742      int nQuery = sqlite3_expert_count(p);
3743      int i;
3744
3745      if( bVerbose ){
3746        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3747        raw_printf(out, "-- Candidates -----------------------------\n");
3748        raw_printf(out, "%s\n", zCand);
3749      }
3750      for(i=0; i<nQuery; i++){
3751        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3752        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3753        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3754        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3755        if( bVerbose ){
3756          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3757          raw_printf(out, "%s\n\n", zSql);
3758        }
3759        raw_printf(out, "%s\n", zIdx);
3760        raw_printf(out, "%s\n", zEQP);
3761      }
3762    }
3763  }
3764  sqlite3_expert_destroy(p);
3765  pState->expert.pExpert = 0;
3766  return rc;
3767}
3768
3769/*
3770** Implementation of ".expert" dot command.
3771*/
3772static int expertDotCommand(
3773  ShellState *pState,             /* Current shell tool state */
3774  char **azArg,                   /* Array of arguments passed to dot command */
3775  int nArg                        /* Number of entries in azArg[] */
3776){
3777  int rc = SQLITE_OK;
3778  char *zErr = 0;
3779  int i;
3780  int iSample = 0;
3781
3782  assert( pState->expert.pExpert==0 );
3783  memset(&pState->expert, 0, sizeof(ExpertInfo));
3784
3785  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3786    char *z = azArg[i];
3787    int n;
3788    if( z[0]=='-' && z[1]=='-' ) z++;
3789    n = strlen30(z);
3790    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3791      pState->expert.bVerbose = 1;
3792    }
3793    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3794      if( i==(nArg-1) ){
3795        raw_printf(stderr, "option requires an argument: %s\n", z);
3796        rc = SQLITE_ERROR;
3797      }else{
3798        iSample = (int)integerValue(azArg[++i]);
3799        if( iSample<0 || iSample>100 ){
3800          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3801          rc = SQLITE_ERROR;
3802        }
3803      }
3804    }
3805    else{
3806      raw_printf(stderr, "unknown option: %s\n", z);
3807      rc = SQLITE_ERROR;
3808    }
3809  }
3810
3811  if( rc==SQLITE_OK ){
3812    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3813    if( pState->expert.pExpert==0 ){
3814      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3815      rc = SQLITE_ERROR;
3816    }else{
3817      sqlite3_expert_config(
3818          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3819      );
3820    }
3821  }
3822  sqlite3_free(zErr);
3823
3824  return rc;
3825}
3826#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3827
3828/*
3829** Execute a statement or set of statements.  Print
3830** any result rows/columns depending on the current mode
3831** set via the supplied callback.
3832**
3833** This is very similar to SQLite's built-in sqlite3_exec()
3834** function except it takes a slightly different callback
3835** and callback data argument.
3836*/
3837static int shell_exec(
3838  ShellState *pArg,                         /* Pointer to ShellState */
3839  const char *zSql,                         /* SQL to be evaluated */
3840  char **pzErrMsg                           /* Error msg written here */
3841){
3842  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3843  int rc = SQLITE_OK;             /* Return Code */
3844  int rc2;
3845  const char *zLeftover;          /* Tail of unprocessed SQL */
3846  sqlite3 *db = pArg->db;
3847
3848  if( pzErrMsg ){
3849    *pzErrMsg = NULL;
3850  }
3851
3852#ifndef SQLITE_OMIT_VIRTUALTABLE
3853  if( pArg->expert.pExpert ){
3854    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3855    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3856  }
3857#endif
3858
3859  while( zSql[0] && (SQLITE_OK == rc) ){
3860    static const char *zStmtSql;
3861    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3862    if( SQLITE_OK != rc ){
3863      if( pzErrMsg ){
3864        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3865      }
3866    }else{
3867      if( !pStmt ){
3868        /* this happens for a comment or white-space */
3869        zSql = zLeftover;
3870        while( IsSpace(zSql[0]) ) zSql++;
3871        continue;
3872      }
3873      zStmtSql = sqlite3_sql(pStmt);
3874      if( zStmtSql==0 ) zStmtSql = "";
3875      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3876
3877      /* save off the prepared statment handle and reset row count */
3878      if( pArg ){
3879        pArg->pStmt = pStmt;
3880        pArg->cnt = 0;
3881      }
3882
3883      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3884      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3885        sqlite3_stmt *pExplain;
3886        char *zEQP;
3887        int triggerEQP = 0;
3888        disable_debug_trace_modes();
3889        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3890        if( pArg->autoEQP>=AUTOEQP_trigger ){
3891          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3892        }
3893        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3894        shell_check_oom(zEQP);
3895        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3896        if( rc==SQLITE_OK ){
3897          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3898            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3899            int iEqpId = sqlite3_column_int(pExplain, 0);
3900            int iParentId = sqlite3_column_int(pExplain, 1);
3901            if( zEQPLine==0 ) zEQPLine = "";
3902            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3903            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3904          }
3905          eqp_render(pArg);
3906        }
3907        sqlite3_finalize(pExplain);
3908        sqlite3_free(zEQP);
3909        if( pArg->autoEQP>=AUTOEQP_full ){
3910          /* Also do an EXPLAIN for ".eqp full" mode */
3911          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3912          shell_check_oom(zEQP);
3913          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3914          if( rc==SQLITE_OK ){
3915            pArg->cMode = MODE_Explain;
3916            explain_data_prepare(pArg, pExplain);
3917            exec_prepared_stmt(pArg, pExplain);
3918            explain_data_delete(pArg);
3919          }
3920          sqlite3_finalize(pExplain);
3921          sqlite3_free(zEQP);
3922        }
3923        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3924          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3925          /* Reprepare pStmt before reactiving trace modes */
3926          sqlite3_finalize(pStmt);
3927          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3928          if( pArg ) pArg->pStmt = pStmt;
3929        }
3930        restore_debug_trace_modes();
3931      }
3932
3933      if( pArg ){
3934        pArg->cMode = pArg->mode;
3935        if( pArg->autoExplain ){
3936          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3937            pArg->cMode = MODE_Explain;
3938          }
3939          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3940            pArg->cMode = MODE_EQP;
3941          }
3942        }
3943
3944        /* If the shell is currently in ".explain" mode, gather the extra
3945        ** data required to add indents to the output.*/
3946        if( pArg->cMode==MODE_Explain ){
3947          explain_data_prepare(pArg, pStmt);
3948        }
3949      }
3950
3951      bind_prepared_stmt(pArg, pStmt);
3952      exec_prepared_stmt(pArg, pStmt);
3953      explain_data_delete(pArg);
3954      eqp_render(pArg);
3955
3956      /* print usage stats if stats on */
3957      if( pArg && pArg->statsOn ){
3958        display_stats(db, pArg, 0);
3959      }
3960
3961      /* print loop-counters if required */
3962      if( pArg && pArg->scanstatsOn ){
3963        display_scanstats(db, pArg);
3964      }
3965
3966      /* Finalize the statement just executed. If this fails, save a
3967      ** copy of the error message. Otherwise, set zSql to point to the
3968      ** next statement to execute. */
3969      rc2 = sqlite3_finalize(pStmt);
3970      if( rc!=SQLITE_NOMEM ) rc = rc2;
3971      if( rc==SQLITE_OK ){
3972        zSql = zLeftover;
3973        while( IsSpace(zSql[0]) ) zSql++;
3974      }else if( pzErrMsg ){
3975        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3976      }
3977
3978      /* clear saved stmt handle */
3979      if( pArg ){
3980        pArg->pStmt = NULL;
3981      }
3982    }
3983  } /* end while */
3984
3985  return rc;
3986}
3987
3988/*
3989** Release memory previously allocated by tableColumnList().
3990*/
3991static void freeColumnList(char **azCol){
3992  int i;
3993  for(i=1; azCol[i]; i++){
3994    sqlite3_free(azCol[i]);
3995  }
3996  /* azCol[0] is a static string */
3997  sqlite3_free(azCol);
3998}
3999
4000/*
4001** Return a list of pointers to strings which are the names of all
4002** columns in table zTab.   The memory to hold the names is dynamically
4003** allocated and must be released by the caller using a subsequent call
4004** to freeColumnList().
4005**
4006** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
4007** value that needs to be preserved, then azCol[0] is filled in with the
4008** name of the rowid column.
4009**
4010** The first regular column in the table is azCol[1].  The list is terminated
4011** by an entry with azCol[i]==0.
4012*/
4013static char **tableColumnList(ShellState *p, const char *zTab){
4014  char **azCol = 0;
4015  sqlite3_stmt *pStmt;
4016  char *zSql;
4017  int nCol = 0;
4018  int nAlloc = 0;
4019  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
4020  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
4021  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4022  int rc;
4023
4024  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4025  shell_check_oom(zSql);
4026  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4027  sqlite3_free(zSql);
4028  if( rc ) return 0;
4029  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4030    if( nCol>=nAlloc-2 ){
4031      nAlloc = nAlloc*2 + nCol + 10;
4032      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4033      shell_check_oom(azCol);
4034    }
4035    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4036    shell_check_oom(azCol[nCol]);
4037    if( sqlite3_column_int(pStmt, 5) ){
4038      nPK++;
4039      if( nPK==1
4040       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4041                          "INTEGER")==0
4042      ){
4043        isIPK = 1;
4044      }else{
4045        isIPK = 0;
4046      }
4047    }
4048  }
4049  sqlite3_finalize(pStmt);
4050  if( azCol==0 ) return 0;
4051  azCol[0] = 0;
4052  azCol[nCol+1] = 0;
4053
4054  /* The decision of whether or not a rowid really needs to be preserved
4055  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4056  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4057  ** rowids on tables where the rowid is inaccessible because there are other
4058  ** columns in the table named "rowid", "_rowid_", and "oid".
4059  */
4060  if( preserveRowid && isIPK ){
4061    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4062    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4063    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4064    ** ROWID aliases.  To distinguish these cases, check to see if
4065    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4066    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4067    */
4068    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4069                           " WHERE origin='pk'", zTab);
4070    shell_check_oom(zSql);
4071    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4072    sqlite3_free(zSql);
4073    if( rc ){
4074      freeColumnList(azCol);
4075      return 0;
4076    }
4077    rc = sqlite3_step(pStmt);
4078    sqlite3_finalize(pStmt);
4079    preserveRowid = rc==SQLITE_ROW;
4080  }
4081  if( preserveRowid ){
4082    /* Only preserve the rowid if we can find a name to use for the
4083    ** rowid */
4084    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4085    int i, j;
4086    for(j=0; j<3; j++){
4087      for(i=1; i<=nCol; i++){
4088        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4089      }
4090      if( i>nCol ){
4091        /* At this point, we know that azRowid[j] is not the name of any
4092        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4093        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4094        ** tables will fail this last check */
4095        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4096        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4097        break;
4098      }
4099    }
4100  }
4101  return azCol;
4102}
4103
4104/*
4105** Toggle the reverse_unordered_selects setting.
4106*/
4107static void toggleSelectOrder(sqlite3 *db){
4108  sqlite3_stmt *pStmt = 0;
4109  int iSetting = 0;
4110  char zStmt[100];
4111  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4112  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4113    iSetting = sqlite3_column_int(pStmt, 0);
4114  }
4115  sqlite3_finalize(pStmt);
4116  sqlite3_snprintf(sizeof(zStmt), zStmt,
4117       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4118  sqlite3_exec(db, zStmt, 0, 0, 0);
4119}
4120
4121/*
4122** This is a different callback routine used for dumping the database.
4123** Each row received by this callback consists of a table name,
4124** the table type ("index" or "table") and SQL to create the table.
4125** This routine should print text sufficient to recreate the table.
4126*/
4127static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4128  int rc;
4129  const char *zTable;
4130  const char *zType;
4131  const char *zSql;
4132  ShellState *p = (ShellState *)pArg;
4133  int dataOnly;
4134  int noSys;
4135
4136  UNUSED_PARAMETER(azNotUsed);
4137  if( nArg!=3 || azArg==0 ) return 0;
4138  zTable = azArg[0];
4139  zType = azArg[1];
4140  zSql = azArg[2];
4141  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4142  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4143
4144  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4145    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4146  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4147    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4148  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4149    return 0;
4150  }else if( dataOnly ){
4151    /* no-op */
4152  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4153    char *zIns;
4154    if( !p->writableSchema ){
4155      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4156      p->writableSchema = 1;
4157    }
4158    zIns = sqlite3_mprintf(
4159       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4160       "VALUES('table','%q','%q',0,'%q');",
4161       zTable, zTable, zSql);
4162    shell_check_oom(zIns);
4163    utf8_printf(p->out, "%s\n", zIns);
4164    sqlite3_free(zIns);
4165    return 0;
4166  }else{
4167    printSchemaLine(p->out, zSql, ";\n");
4168  }
4169
4170  if( strcmp(zType, "table")==0 ){
4171    ShellText sSelect;
4172    ShellText sTable;
4173    char **azCol;
4174    int i;
4175    char *savedDestTable;
4176    int savedMode;
4177
4178    azCol = tableColumnList(p, zTable);
4179    if( azCol==0 ){
4180      p->nErr++;
4181      return 0;
4182    }
4183
4184    /* Always quote the table name, even if it appears to be pure ascii,
4185    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4186    initText(&sTable);
4187    appendText(&sTable, zTable, quoteChar(zTable));
4188    /* If preserving the rowid, add a column list after the table name.
4189    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4190    ** instead of the usual "INSERT INTO tab VALUES(...)".
4191    */
4192    if( azCol[0] ){
4193      appendText(&sTable, "(", 0);
4194      appendText(&sTable, azCol[0], 0);
4195      for(i=1; azCol[i]; i++){
4196        appendText(&sTable, ",", 0);
4197        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4198      }
4199      appendText(&sTable, ")", 0);
4200    }
4201
4202    /* Build an appropriate SELECT statement */
4203    initText(&sSelect);
4204    appendText(&sSelect, "SELECT ", 0);
4205    if( azCol[0] ){
4206      appendText(&sSelect, azCol[0], 0);
4207      appendText(&sSelect, ",", 0);
4208    }
4209    for(i=1; azCol[i]; i++){
4210      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4211      if( azCol[i+1] ){
4212        appendText(&sSelect, ",", 0);
4213      }
4214    }
4215    freeColumnList(azCol);
4216    appendText(&sSelect, " FROM ", 0);
4217    appendText(&sSelect, zTable, quoteChar(zTable));
4218
4219    savedDestTable = p->zDestTable;
4220    savedMode = p->mode;
4221    p->zDestTable = sTable.z;
4222    p->mode = p->cMode = MODE_Insert;
4223    rc = shell_exec(p, sSelect.z, 0);
4224    if( (rc&0xff)==SQLITE_CORRUPT ){
4225      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4226      toggleSelectOrder(p->db);
4227      shell_exec(p, sSelect.z, 0);
4228      toggleSelectOrder(p->db);
4229    }
4230    p->zDestTable = savedDestTable;
4231    p->mode = savedMode;
4232    freeText(&sTable);
4233    freeText(&sSelect);
4234    if( rc ) p->nErr++;
4235  }
4236  return 0;
4237}
4238
4239/*
4240** Run zQuery.  Use dump_callback() as the callback routine so that
4241** the contents of the query are output as SQL statements.
4242**
4243** If we get a SQLITE_CORRUPT error, rerun the query after appending
4244** "ORDER BY rowid DESC" to the end.
4245*/
4246static int run_schema_dump_query(
4247  ShellState *p,
4248  const char *zQuery
4249){
4250  int rc;
4251  char *zErr = 0;
4252  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4253  if( rc==SQLITE_CORRUPT ){
4254    char *zQ2;
4255    int len = strlen30(zQuery);
4256    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4257    if( zErr ){
4258      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4259      sqlite3_free(zErr);
4260      zErr = 0;
4261    }
4262    zQ2 = malloc( len+100 );
4263    if( zQ2==0 ) return rc;
4264    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4265    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4266    if( rc ){
4267      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4268    }else{
4269      rc = SQLITE_CORRUPT;
4270    }
4271    sqlite3_free(zErr);
4272    free(zQ2);
4273  }
4274  return rc;
4275}
4276
4277/*
4278** Text of help messages.
4279**
4280** The help text for each individual command begins with a line that starts
4281** with ".".  Subsequent lines are supplemental information.
4282**
4283** There must be two or more spaces between the end of the command and the
4284** start of the description of what that command does.
4285*/
4286static const char *(azHelp[]) = {
4287#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4288  && !defined(SQLITE_SHELL_FIDDLE)
4289  ".archive ...             Manage SQL archives",
4290  "   Each command must have exactly one of the following options:",
4291  "     -c, --create               Create a new archive",
4292  "     -u, --update               Add or update files with changed mtime",
4293  "     -i, --insert               Like -u but always add even if unchanged",
4294  "     -r, --remove               Remove files from archive",
4295  "     -t, --list                 List contents of archive",
4296  "     -x, --extract              Extract files from archive",
4297  "   Optional arguments:",
4298  "     -v, --verbose              Print each filename as it is processed",
4299  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4300  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4301  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4302  "     -g, --glob                 Use glob matching for names in archive",
4303  "     -n, --dryrun               Show the SQL that would have occurred",
4304  "   Examples:",
4305  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4306  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4307  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4308  "   See also:",
4309  "      http://sqlite.org/cli.html#sqlite_archive_support",
4310#endif
4311#ifndef SQLITE_OMIT_AUTHORIZATION
4312  ".auth ON|OFF             Show authorizer callbacks",
4313#endif
4314#ifndef SQLITE_SHELL_FIDDLE
4315  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4316  "   Options:",
4317  "       --append            Use the appendvfs",
4318  "       --async             Write to FILE without journal and fsync()",
4319#endif
4320  ".bail on|off             Stop after hitting an error.  Default OFF",
4321  ".binary on|off           Turn binary output on or off.  Default OFF",
4322#ifndef SQLITE_SHELL_FIDDLE
4323  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4324#endif
4325  ".changes on|off          Show number of rows changed by SQL",
4326#ifndef SQLITE_SHELL_FIDDLE
4327  ".check GLOB              Fail if output since .testcase does not match",
4328  ".clone NEWDB             Clone data into NEWDB from the existing database",
4329#endif
4330  ".connection [close] [#]  Open or close an auxiliary database connection",
4331  ".databases               List names and files of attached databases",
4332  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4333#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4334  ".dbinfo ?DB?             Show status information about the database",
4335#endif
4336  ".dump ?OBJECTS?          Render database content as SQL",
4337  "   Options:",
4338  "     --data-only            Output only INSERT statements",
4339  "     --newlines             Allow unescaped newline characters in output",
4340  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4341  "     --preserve-rowids      Include ROWID values in the output",
4342  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4343  "   Additional LIKE patterns can be given in subsequent arguments",
4344  ".echo on|off             Turn command echo on or off",
4345  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4346  "   Other Modes:",
4347#ifdef SQLITE_DEBUG
4348  "      test                  Show raw EXPLAIN QUERY PLAN output",
4349  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4350#endif
4351  "      trigger               Like \"full\" but also show trigger bytecode",
4352#ifndef SQLITE_SHELL_FIDDLE
4353  ".excel                   Display the output of next command in spreadsheet",
4354  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4355#endif
4356#ifndef SQLITE_SHELL_FIDDLE
4357  ".exit ?CODE?             Exit this program with return-code CODE",
4358#endif
4359  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4360  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4361  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4362  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4363  "   --help                  Show CMD details",
4364  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4365  ".headers on|off          Turn display of headers on or off",
4366  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4367#ifndef SQLITE_SHELL_FIDDLE
4368  ".import FILE TABLE       Import data from FILE into TABLE",
4369  "   Options:",
4370  "     --ascii               Use \\037 and \\036 as column and row separators",
4371  "     --csv                 Use , and \\n as column and row separators",
4372  "     --skip N              Skip the first N rows of input",
4373  "     --schema S            Target table to be S.TABLE",
4374  "     -v                    \"Verbose\" - increase auxiliary output",
4375  "   Notes:",
4376  "     *  If TABLE does not exist, it is created.  The first row of input",
4377  "        determines the column names.",
4378  "     *  If neither --csv or --ascii are used, the input mode is derived",
4379  "        from the \".mode\" output mode",
4380  "     *  If FILE begins with \"|\" then it is a command that generates the",
4381  "        input text.",
4382#endif
4383#ifndef SQLITE_OMIT_TEST_CONTROL
4384  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4385#endif
4386  ".indexes ?TABLE?         Show names of indexes",
4387  "                           If TABLE is specified, only show indexes for",
4388  "                           tables matching TABLE using the LIKE operator.",
4389#ifdef SQLITE_ENABLE_IOTRACE
4390  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4391#endif
4392  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4393  ".lint OPTIONS            Report potential schema issues.",
4394  "     Options:",
4395  "        fkey-indexes     Find missing foreign key indexes",
4396#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4397  ".load FILE ?ENTRY?       Load an extension library",
4398#endif
4399#ifndef SQLITE_SHELL_FIDDLE
4400  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4401#endif
4402  ".mode MODE ?OPTIONS?     Set output mode",
4403  "   MODE is one of:",
4404  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4405  "     box         Tables using unicode box-drawing characters",
4406  "     csv         Comma-separated values",
4407  "     column      Output in columns.  (See .width)",
4408  "     html        HTML <table> code",
4409  "     insert      SQL insert statements for TABLE",
4410  "     json        Results in a JSON array",
4411  "     line        One value per line",
4412  "     list        Values delimited by \"|\"",
4413  "     markdown    Markdown table format",
4414  "     qbox        Shorthand for \"box --width 60 --quote\"",
4415  "     quote       Escape answers as for SQL",
4416  "     table       ASCII-art table",
4417  "     tabs        Tab-separated values",
4418  "     tcl         TCL list elements",
4419  "   OPTIONS: (for columnar modes or insert mode):",
4420  "     --wrap N       Wrap output lines to no longer than N characters",
4421  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4422  "     --ww           Shorthand for \"--wordwrap 1\"",
4423  "     --quote        Quote output text as SQL literals",
4424  "     --noquote      Do not quote output text",
4425  "     TABLE          The name of SQL table used for \"insert\" mode",
4426#ifndef SQLITE_SHELL_FIDDLE
4427  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4428#endif
4429  ".nullvalue STRING        Use STRING in place of NULL values",
4430#ifndef SQLITE_SHELL_FIDDLE
4431  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4432  "     If FILE begins with '|' then open as a pipe",
4433  "       --bom  Put a UTF8 byte-order mark at the beginning",
4434  "       -e     Send output to the system text editor",
4435  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4436  /* Note that .open is (partially) available in WASM builds but is
4437  ** currently only intended to be used by the fiddle tool, not
4438  ** end users, so is "undocumented." */
4439  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4440  "     Options:",
4441  "        --append        Use appendvfs to append database to the end of FILE",
4442#endif
4443#ifndef SQLITE_OMIT_DESERIALIZE
4444  "        --deserialize   Load into memory using sqlite3_deserialize()",
4445  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4446  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4447#endif
4448  "        --new           Initialize FILE to an empty database",
4449  "        --nofollow      Do not follow symbolic links",
4450  "        --readonly      Open FILE readonly",
4451  "        --zip           FILE is a ZIP archive",
4452#ifndef SQLITE_SHELL_FIDDLE
4453  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4454  "   If FILE begins with '|' then open it as a pipe.",
4455  "   Options:",
4456  "     --bom                 Prefix output with a UTF8 byte-order mark",
4457  "     -e                    Send output to the system text editor",
4458  "     -x                    Send output as CSV to a spreadsheet",
4459#endif
4460  ".parameter CMD ...       Manage SQL parameter bindings",
4461  "   clear                   Erase all bindings",
4462  "   init                    Initialize the TEMP table that holds bindings",
4463  "   list                    List the current parameter bindings",
4464  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4465  "                           PARAMETER should start with one of: $ : @ ?",
4466  "   unset PARAMETER         Remove PARAMETER from the binding table",
4467  ".print STRING...         Print literal STRING",
4468#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4469  ".progress N              Invoke progress handler after every N opcodes",
4470  "   --limit N                 Interrupt after N progress callbacks",
4471  "   --once                    Do no more than one progress interrupt",
4472  "   --quiet|-q                No output except at interrupts",
4473  "   --reset                   Reset the count for each input and interrupt",
4474#endif
4475  ".prompt MAIN CONTINUE    Replace the standard prompts",
4476#ifndef SQLITE_SHELL_FIDDLE
4477  ".quit                    Exit this program",
4478  ".read FILE               Read input from FILE or command output",
4479  "    If FILE begins with \"|\", it is a command that generates the input.",
4480#endif
4481#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4482  ".recover                 Recover as much data as possible from corrupt db.",
4483  "   --freelist-corrupt       Assume the freelist is corrupt",
4484  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4485  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4486  "   --no-rowids              Do not attempt to recover rowid values",
4487  "                            that are not also INTEGER PRIMARY KEYs",
4488#endif
4489#ifndef SQLITE_SHELL_FIDDLE
4490  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4491  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4492#endif
4493  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4494  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4495  "   Options:",
4496  "      --indent             Try to pretty-print the schema",
4497  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4498  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4499  "    Options:",
4500  "       --init               Create a new SELFTEST table",
4501  "       -v                   Verbose output",
4502  ".separator COL ?ROW?     Change the column and row separators",
4503#if defined(SQLITE_ENABLE_SESSION)
4504  ".session ?NAME? CMD ...  Create or control sessions",
4505  "   Subcommands:",
4506  "     attach TABLE             Attach TABLE",
4507  "     changeset FILE           Write a changeset into FILE",
4508  "     close                    Close one session",
4509  "     enable ?BOOLEAN?         Set or query the enable bit",
4510  "     filter GLOB...           Reject tables matching GLOBs",
4511  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4512  "     isempty                  Query whether the session is empty",
4513  "     list                     List currently open session names",
4514  "     open DB NAME             Open a new session on DB",
4515  "     patchset FILE            Write a patchset into FILE",
4516  "   If ?NAME? is omitted, the first defined session is used.",
4517#endif
4518  ".sha3sum ...             Compute a SHA3 hash of database content",
4519  "    Options:",
4520  "      --schema              Also hash the sqlite_schema table",
4521  "      --sha3-224            Use the sha3-224 algorithm",
4522  "      --sha3-256            Use the sha3-256 algorithm (default)",
4523  "      --sha3-384            Use the sha3-384 algorithm",
4524  "      --sha3-512            Use the sha3-512 algorithm",
4525  "    Any other argument is a LIKE pattern for tables to hash",
4526#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4527  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4528#endif
4529  ".show                    Show the current values for various settings",
4530  ".stats ?ARG?             Show stats or turn stats on or off",
4531  "   off                      Turn off automatic stat display",
4532  "   on                       Turn on automatic stat display",
4533  "   stmt                     Show statement stats",
4534  "   vmstep                   Show the virtual machine step count only",
4535#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4536  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4537#endif
4538  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4539#ifndef SQLITE_SHELL_FIDDLE
4540  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4541#endif
4542  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4543  "                           Run \".testctrl\" with no arguments for details",
4544  ".timeout MS              Try opening locked tables for MS milliseconds",
4545  ".timer on|off            Turn SQL timer on or off",
4546#ifndef SQLITE_OMIT_TRACE
4547  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4548  "    FILE                    Send output to FILE",
4549  "    stdout                  Send output to stdout",
4550  "    stderr                  Send output to stderr",
4551  "    off                     Disable tracing",
4552  "    --expanded              Expand query parameters",
4553#ifdef SQLITE_ENABLE_NORMALIZE
4554  "    --normalized            Normal the SQL statements",
4555#endif
4556  "    --plain                 Show SQL as it is input",
4557  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4558  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4559  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4560  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4561#endif /* SQLITE_OMIT_TRACE */
4562#ifdef SQLITE_DEBUG
4563  ".unmodule NAME ...       Unregister virtual table modules",
4564  "    --allexcept             Unregister everything except those named",
4565#endif
4566  ".vfsinfo ?AUX?           Information about the top-level VFS",
4567  ".vfslist                 List all available VFSes",
4568  ".vfsname ?AUX?           Print the name of the VFS stack",
4569  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4570  "     Negative values right-justify",
4571};
4572
4573/*
4574** Output help text.
4575**
4576** zPattern describes the set of commands for which help text is provided.
4577** If zPattern is NULL, then show all commands, but only give a one-line
4578** description of each.
4579**
4580** Return the number of matches.
4581*/
4582static int showHelp(FILE *out, const char *zPattern){
4583  int i = 0;
4584  int j = 0;
4585  int n = 0;
4586  char *zPat;
4587  if( zPattern==0
4588   || zPattern[0]=='0'
4589   || strcmp(zPattern,"-a")==0
4590   || strcmp(zPattern,"-all")==0
4591   || strcmp(zPattern,"--all")==0
4592  ){
4593    /* Show all commands, but only one line per command */
4594    if( zPattern==0 ) zPattern = "";
4595    for(i=0; i<ArraySize(azHelp); i++){
4596      if( azHelp[i][0]=='.' || zPattern[0] ){
4597        utf8_printf(out, "%s\n", azHelp[i]);
4598        n++;
4599      }
4600    }
4601  }else{
4602    /* Look for commands that for which zPattern is an exact prefix */
4603    zPat = sqlite3_mprintf(".%s*", zPattern);
4604    shell_check_oom(zPat);
4605    for(i=0; i<ArraySize(azHelp); i++){
4606      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4607        utf8_printf(out, "%s\n", azHelp[i]);
4608        j = i+1;
4609        n++;
4610      }
4611    }
4612    sqlite3_free(zPat);
4613    if( n ){
4614      if( n==1 ){
4615        /* when zPattern is a prefix of exactly one command, then include the
4616        ** details of that command, which should begin at offset j */
4617        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4618          utf8_printf(out, "%s\n", azHelp[j]);
4619          j++;
4620        }
4621      }
4622      return n;
4623    }
4624    /* Look for commands that contain zPattern anywhere.  Show the complete
4625    ** text of all commands that match. */
4626    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4627    shell_check_oom(zPat);
4628    for(i=0; i<ArraySize(azHelp); i++){
4629      if( azHelp[i][0]=='.' ) j = i;
4630      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4631        utf8_printf(out, "%s\n", azHelp[j]);
4632        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4633          j++;
4634          utf8_printf(out, "%s\n", azHelp[j]);
4635        }
4636        i = j;
4637        n++;
4638      }
4639    }
4640    sqlite3_free(zPat);
4641  }
4642  return n;
4643}
4644
4645/* Forward reference */
4646static int process_input(ShellState *p);
4647
4648/*
4649** Read the content of file zName into memory obtained from sqlite3_malloc64()
4650** and return a pointer to the buffer. The caller is responsible for freeing
4651** the memory.
4652**
4653** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4654** read.
4655**
4656** For convenience, a nul-terminator byte is always appended to the data read
4657** from the file before the buffer is returned. This byte is not included in
4658** the final value of (*pnByte), if applicable.
4659**
4660** NULL is returned if any error is encountered. The final value of *pnByte
4661** is undefined in this case.
4662*/
4663static char *readFile(const char *zName, int *pnByte){
4664  FILE *in = fopen(zName, "rb");
4665  long nIn;
4666  size_t nRead;
4667  char *pBuf;
4668  if( in==0 ) return 0;
4669  fseek(in, 0, SEEK_END);
4670  nIn = ftell(in);
4671  rewind(in);
4672  pBuf = sqlite3_malloc64( nIn+1 );
4673  if( pBuf==0 ){ fclose(in); return 0; }
4674  nRead = fread(pBuf, nIn, 1, in);
4675  fclose(in);
4676  if( nRead!=1 ){
4677    sqlite3_free(pBuf);
4678    return 0;
4679  }
4680  pBuf[nIn] = 0;
4681  if( pnByte ) *pnByte = nIn;
4682  return pBuf;
4683}
4684
4685#if defined(SQLITE_ENABLE_SESSION)
4686/*
4687** Close a single OpenSession object and release all of its associated
4688** resources.
4689*/
4690static void session_close(OpenSession *pSession){
4691  int i;
4692  sqlite3session_delete(pSession->p);
4693  sqlite3_free(pSession->zName);
4694  for(i=0; i<pSession->nFilter; i++){
4695    sqlite3_free(pSession->azFilter[i]);
4696  }
4697  sqlite3_free(pSession->azFilter);
4698  memset(pSession, 0, sizeof(OpenSession));
4699}
4700#endif
4701
4702/*
4703** Close all OpenSession objects and release all associated resources.
4704*/
4705#if defined(SQLITE_ENABLE_SESSION)
4706static void session_close_all(ShellState *p, int i){
4707  int j;
4708  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4709  for(j=0; j<pAuxDb->nSession; j++){
4710    session_close(&pAuxDb->aSession[j]);
4711  }
4712  pAuxDb->nSession = 0;
4713}
4714#else
4715# define session_close_all(X,Y)
4716#endif
4717
4718/*
4719** Implementation of the xFilter function for an open session.  Omit
4720** any tables named by ".session filter" but let all other table through.
4721*/
4722#if defined(SQLITE_ENABLE_SESSION)
4723static int session_filter(void *pCtx, const char *zTab){
4724  OpenSession *pSession = (OpenSession*)pCtx;
4725  int i;
4726  for(i=0; i<pSession->nFilter; i++){
4727    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4728  }
4729  return 1;
4730}
4731#endif
4732
4733/*
4734** Try to deduce the type of file for zName based on its content.  Return
4735** one of the SHELL_OPEN_* constants.
4736**
4737** If the file does not exist or is empty but its name looks like a ZIP
4738** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4739** Otherwise, assume an ordinary database regardless of the filename if
4740** the type cannot be determined from content.
4741*/
4742int deduceDatabaseType(const char *zName, int dfltZip){
4743  FILE *f = fopen(zName, "rb");
4744  size_t n;
4745  int rc = SHELL_OPEN_UNSPEC;
4746  char zBuf[100];
4747  if( f==0 ){
4748    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4749       return SHELL_OPEN_ZIPFILE;
4750    }else{
4751       return SHELL_OPEN_NORMAL;
4752    }
4753  }
4754  n = fread(zBuf, 16, 1, f);
4755  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4756    fclose(f);
4757    return SHELL_OPEN_NORMAL;
4758  }
4759  fseek(f, -25, SEEK_END);
4760  n = fread(zBuf, 25, 1, f);
4761  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4762    rc = SHELL_OPEN_APPENDVFS;
4763  }else{
4764    fseek(f, -22, SEEK_END);
4765    n = fread(zBuf, 22, 1, f);
4766    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4767       && zBuf[3]==0x06 ){
4768      rc = SHELL_OPEN_ZIPFILE;
4769    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4770      rc = SHELL_OPEN_ZIPFILE;
4771    }
4772  }
4773  fclose(f);
4774  return rc;
4775}
4776
4777#ifndef SQLITE_OMIT_DESERIALIZE
4778/*
4779** Reconstruct an in-memory database using the output from the "dbtotxt"
4780** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4781** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4782*/
4783static unsigned char *readHexDb(ShellState *p, int *pnData){
4784  unsigned char *a = 0;
4785  int nLine;
4786  int n = 0;
4787  int pgsz = 0;
4788  int iOffset = 0;
4789  int j, k;
4790  int rc;
4791  FILE *in;
4792  const char *zDbFilename = p->pAuxDb->zDbFilename;
4793  unsigned int x[16];
4794  char zLine[1000];
4795  if( zDbFilename ){
4796    in = fopen(zDbFilename, "r");
4797    if( in==0 ){
4798      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4799      return 0;
4800    }
4801    nLine = 0;
4802  }else{
4803    in = p->in;
4804    nLine = p->lineno;
4805    if( in==0 ) in = stdin;
4806  }
4807  *pnData = 0;
4808  nLine++;
4809  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4810  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4811  if( rc!=2 ) goto readHexDb_error;
4812  if( n<0 ) goto readHexDb_error;
4813  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4814  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4815  a = sqlite3_malloc( n ? n : 1 );
4816  shell_check_oom(a);
4817  memset(a, 0, n);
4818  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4819    utf8_printf(stderr, "invalid pagesize\n");
4820    goto readHexDb_error;
4821  }
4822  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4823    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4824    if( rc==2 ){
4825      iOffset = k;
4826      continue;
4827    }
4828    if( strncmp(zLine, "| end ", 6)==0 ){
4829      break;
4830    }
4831    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4832                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4833                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4834    if( rc==17 ){
4835      k = iOffset+j;
4836      if( k+16<=n && k>=0 ){
4837        int ii;
4838        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4839      }
4840    }
4841  }
4842  *pnData = n;
4843  if( in!=p->in ){
4844    fclose(in);
4845  }else{
4846    p->lineno = nLine;
4847  }
4848  return a;
4849
4850readHexDb_error:
4851  if( in!=p->in ){
4852    fclose(in);
4853  }else{
4854    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4855      nLine++;
4856      if(strncmp(zLine, "| end ", 6)==0 ) break;
4857    }
4858    p->lineno = nLine;
4859  }
4860  sqlite3_free(a);
4861  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4862  return 0;
4863}
4864#endif /* SQLITE_OMIT_DESERIALIZE */
4865
4866/*
4867** Scalar function "shell_int32". The first argument to this function
4868** must be a blob. The second a non-negative integer. This function
4869** reads and returns a 32-bit big-endian integer from byte
4870** offset (4*<arg2>) of the blob.
4871*/
4872static void shellInt32(
4873  sqlite3_context *context,
4874  int argc,
4875  sqlite3_value **argv
4876){
4877  const unsigned char *pBlob;
4878  int nBlob;
4879  int iInt;
4880
4881  UNUSED_PARAMETER(argc);
4882  nBlob = sqlite3_value_bytes(argv[0]);
4883  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4884  iInt = sqlite3_value_int(argv[1]);
4885
4886  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4887    const unsigned char *a = &pBlob[iInt*4];
4888    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4889                       + ((sqlite3_int64)a[1]<<16)
4890                       + ((sqlite3_int64)a[2]<< 8)
4891                       + ((sqlite3_int64)a[3]<< 0);
4892    sqlite3_result_int64(context, iVal);
4893  }
4894}
4895
4896/*
4897** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4898** using "..." with internal double-quote characters doubled.
4899*/
4900static void shellIdQuote(
4901  sqlite3_context *context,
4902  int argc,
4903  sqlite3_value **argv
4904){
4905  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4906  UNUSED_PARAMETER(argc);
4907  if( zName ){
4908    char *z = sqlite3_mprintf("\"%w\"", zName);
4909    sqlite3_result_text(context, z, -1, sqlite3_free);
4910  }
4911}
4912
4913/*
4914** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4915*/
4916static void shellUSleepFunc(
4917  sqlite3_context *context,
4918  int argcUnused,
4919  sqlite3_value **argv
4920){
4921  int sleep = sqlite3_value_int(argv[0]);
4922  (void)argcUnused;
4923  sqlite3_sleep(sleep/1000);
4924  sqlite3_result_int(context, sleep);
4925}
4926
4927/*
4928** Scalar function "shell_escape_crnl" used by the .recover command.
4929** The argument passed to this function is the output of built-in
4930** function quote(). If the first character of the input is "'",
4931** indicating that the value passed to quote() was a text value,
4932** then this function searches the input for "\n" and "\r" characters
4933** and adds a wrapper similar to the following:
4934**
4935**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4936**
4937** Or, if the first character of the input is not "'", then a copy
4938** of the input is returned.
4939*/
4940static void shellEscapeCrnl(
4941  sqlite3_context *context,
4942  int argc,
4943  sqlite3_value **argv
4944){
4945  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4946  UNUSED_PARAMETER(argc);
4947  if( zText && zText[0]=='\'' ){
4948    int nText = sqlite3_value_bytes(argv[0]);
4949    int i;
4950    char zBuf1[20];
4951    char zBuf2[20];
4952    const char *zNL = 0;
4953    const char *zCR = 0;
4954    int nCR = 0;
4955    int nNL = 0;
4956
4957    for(i=0; zText[i]; i++){
4958      if( zNL==0 && zText[i]=='\n' ){
4959        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4960        nNL = (int)strlen(zNL);
4961      }
4962      if( zCR==0 && zText[i]=='\r' ){
4963        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4964        nCR = (int)strlen(zCR);
4965      }
4966    }
4967
4968    if( zNL || zCR ){
4969      int iOut = 0;
4970      i64 nMax = (nNL > nCR) ? nNL : nCR;
4971      i64 nAlloc = nMax * nText + (nMax+64)*2;
4972      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4973      if( zOut==0 ){
4974        sqlite3_result_error_nomem(context);
4975        return;
4976      }
4977
4978      if( zNL && zCR ){
4979        memcpy(&zOut[iOut], "replace(replace(", 16);
4980        iOut += 16;
4981      }else{
4982        memcpy(&zOut[iOut], "replace(", 8);
4983        iOut += 8;
4984      }
4985      for(i=0; zText[i]; i++){
4986        if( zText[i]=='\n' ){
4987          memcpy(&zOut[iOut], zNL, nNL);
4988          iOut += nNL;
4989        }else if( zText[i]=='\r' ){
4990          memcpy(&zOut[iOut], zCR, nCR);
4991          iOut += nCR;
4992        }else{
4993          zOut[iOut] = zText[i];
4994          iOut++;
4995        }
4996      }
4997
4998      if( zNL ){
4999        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5000        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
5001        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
5002      }
5003      if( zCR ){
5004        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5005        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
5006        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
5007      }
5008
5009      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
5010      sqlite3_free(zOut);
5011      return;
5012    }
5013  }
5014
5015  sqlite3_result_value(context, argv[0]);
5016}
5017
5018/* Flags for open_db().
5019**
5020** The default behavior of open_db() is to exit(1) if the database fails to
5021** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5022** but still returns without calling exit.
5023**
5024** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5025** ZIP archive if the file does not exist or is empty and its name matches
5026** the *.zip pattern.
5027*/
5028#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5029#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5030
5031/*
5032** Make sure the database is open.  If it is not, then open it.  If
5033** the database fails to open, print an error message and exit.
5034*/
5035static void open_db(ShellState *p, int openFlags){
5036  if( p->db==0 ){
5037    const char *zDbFilename = p->pAuxDb->zDbFilename;
5038    if( p->openMode==SHELL_OPEN_UNSPEC ){
5039      if( zDbFilename==0 || zDbFilename[0]==0 ){
5040        p->openMode = SHELL_OPEN_NORMAL;
5041      }else{
5042        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5043                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5044      }
5045    }
5046    switch( p->openMode ){
5047      case SHELL_OPEN_APPENDVFS: {
5048        sqlite3_open_v2(zDbFilename, &p->db,
5049           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5050        break;
5051      }
5052      case SHELL_OPEN_HEXDB:
5053      case SHELL_OPEN_DESERIALIZE: {
5054        sqlite3_open(0, &p->db);
5055        break;
5056      }
5057      case SHELL_OPEN_ZIPFILE: {
5058        sqlite3_open(":memory:", &p->db);
5059        break;
5060      }
5061      case SHELL_OPEN_READONLY: {
5062        sqlite3_open_v2(zDbFilename, &p->db,
5063            SQLITE_OPEN_READONLY|p->openFlags, 0);
5064        break;
5065      }
5066      case SHELL_OPEN_UNSPEC:
5067      case SHELL_OPEN_NORMAL: {
5068        sqlite3_open_v2(zDbFilename, &p->db,
5069           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5070        break;
5071      }
5072    }
5073    globalDb = p->db;
5074    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5075      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5076          zDbFilename, sqlite3_errmsg(p->db));
5077      if( openFlags & OPEN_DB_KEEPALIVE ){
5078        sqlite3_open(":memory:", &p->db);
5079        return;
5080      }
5081      exit(1);
5082    }
5083#ifndef SQLITE_OMIT_LOAD_EXTENSION
5084    sqlite3_enable_load_extension(p->db, 1);
5085#endif
5086    sqlite3_shathree_init(p->db, 0, 0);
5087    sqlite3_uint_init(p->db, 0, 0);
5088    sqlite3_decimal_init(p->db, 0, 0);
5089    sqlite3_regexp_init(p->db, 0, 0);
5090    sqlite3_ieee_init(p->db, 0, 0);
5091    sqlite3_series_init(p->db, 0, 0);
5092#ifndef SQLITE_SHELL_FIDDLE
5093    sqlite3_fileio_init(p->db, 0, 0);
5094    sqlite3_completion_init(p->db, 0, 0);
5095#endif
5096#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5097    sqlite3_dbdata_init(p->db, 0, 0);
5098#endif
5099#ifdef SQLITE_HAVE_ZLIB
5100    if( !p->bSafeModePersist ){
5101      sqlite3_zipfile_init(p->db, 0, 0);
5102      sqlite3_sqlar_init(p->db, 0, 0);
5103    }
5104#endif
5105    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5106                            shellAddSchemaName, 0, 0);
5107    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5108                            shellModuleSchema, 0, 0);
5109    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5110                            shellPutsFunc, 0, 0);
5111    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5112                            shellEscapeCrnl, 0, 0);
5113    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5114                            shellInt32, 0, 0);
5115    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5116                            shellIdQuote, 0, 0);
5117    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5118                            shellUSleepFunc, 0, 0);
5119#ifndef SQLITE_NOHAVE_SYSTEM
5120    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5121                            editFunc, 0, 0);
5122    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5123                            editFunc, 0, 0);
5124#endif
5125    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5126      char *zSql = sqlite3_mprintf(
5127         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5128      shell_check_oom(zSql);
5129      sqlite3_exec(p->db, zSql, 0, 0, 0);
5130      sqlite3_free(zSql);
5131    }
5132#ifndef SQLITE_OMIT_DESERIALIZE
5133    else
5134    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5135      int rc;
5136      int nData = 0;
5137      unsigned char *aData;
5138      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5139        aData = (unsigned char*)readFile(zDbFilename, &nData);
5140      }else{
5141        aData = readHexDb(p, &nData);
5142        if( aData==0 ){
5143          return;
5144        }
5145      }
5146      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5147                   SQLITE_DESERIALIZE_RESIZEABLE |
5148                   SQLITE_DESERIALIZE_FREEONCLOSE);
5149      if( rc ){
5150        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5151      }
5152      if( p->szMax>0 ){
5153        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5154      }
5155    }
5156#endif
5157  }
5158  if( p->bSafeModePersist && p->db!=0 ){
5159    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5160  }
5161}
5162
5163/*
5164** Attempt to close the databaes connection.  Report errors.
5165*/
5166void close_db(sqlite3 *db){
5167  int rc = sqlite3_close(db);
5168  if( rc ){
5169    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5170        rc, sqlite3_errmsg(db));
5171  }
5172}
5173
5174#if HAVE_READLINE || HAVE_EDITLINE
5175/*
5176** Readline completion callbacks
5177*/
5178static char *readline_completion_generator(const char *text, int state){
5179  static sqlite3_stmt *pStmt = 0;
5180  char *zRet;
5181  if( state==0 ){
5182    char *zSql;
5183    sqlite3_finalize(pStmt);
5184    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5185                           "  FROM completion(%Q) ORDER BY 1", text);
5186    shell_check_oom(zSql);
5187    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5188    sqlite3_free(zSql);
5189  }
5190  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5191    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5192    zRet = z ? strdup(z) : 0;
5193  }else{
5194    sqlite3_finalize(pStmt);
5195    pStmt = 0;
5196    zRet = 0;
5197  }
5198  return zRet;
5199}
5200static char **readline_completion(const char *zText, int iStart, int iEnd){
5201  rl_attempted_completion_over = 1;
5202  return rl_completion_matches(zText, readline_completion_generator);
5203}
5204
5205#elif HAVE_LINENOISE
5206/*
5207** Linenoise completion callback
5208*/
5209static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5210  int nLine = strlen30(zLine);
5211  int i, iStart;
5212  sqlite3_stmt *pStmt = 0;
5213  char *zSql;
5214  char zBuf[1000];
5215
5216  if( nLine>sizeof(zBuf)-30 ) return;
5217  if( zLine[0]=='.' || zLine[0]=='#') return;
5218  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5219  if( i==nLine-1 ) return;
5220  iStart = i+1;
5221  memcpy(zBuf, zLine, iStart);
5222  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5223                         "  FROM completion(%Q,%Q) ORDER BY 1",
5224                         &zLine[iStart], zLine);
5225  shell_check_oom(zSql);
5226  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5227  sqlite3_free(zSql);
5228  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5229  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5230    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5231    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5232    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5233      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5234      linenoiseAddCompletion(lc, zBuf);
5235    }
5236  }
5237  sqlite3_finalize(pStmt);
5238}
5239#endif
5240
5241/*
5242** Do C-language style dequoting.
5243**
5244**    \a    -> alarm
5245**    \b    -> backspace
5246**    \t    -> tab
5247**    \n    -> newline
5248**    \v    -> vertical tab
5249**    \f    -> form feed
5250**    \r    -> carriage return
5251**    \s    -> space
5252**    \"    -> "
5253**    \'    -> '
5254**    \\    -> backslash
5255**    \NNN  -> ascii character NNN in octal
5256*/
5257static void resolve_backslashes(char *z){
5258  int i, j;
5259  char c;
5260  while( *z && *z!='\\' ) z++;
5261  for(i=j=0; (c = z[i])!=0; i++, j++){
5262    if( c=='\\' && z[i+1]!=0 ){
5263      c = z[++i];
5264      if( c=='a' ){
5265        c = '\a';
5266      }else if( c=='b' ){
5267        c = '\b';
5268      }else if( c=='t' ){
5269        c = '\t';
5270      }else if( c=='n' ){
5271        c = '\n';
5272      }else if( c=='v' ){
5273        c = '\v';
5274      }else if( c=='f' ){
5275        c = '\f';
5276      }else if( c=='r' ){
5277        c = '\r';
5278      }else if( c=='"' ){
5279        c = '"';
5280      }else if( c=='\'' ){
5281        c = '\'';
5282      }else if( c=='\\' ){
5283        c = '\\';
5284      }else if( c>='0' && c<='7' ){
5285        c -= '0';
5286        if( z[i+1]>='0' && z[i+1]<='7' ){
5287          i++;
5288          c = (c<<3) + z[i] - '0';
5289          if( z[i+1]>='0' && z[i+1]<='7' ){
5290            i++;
5291            c = (c<<3) + z[i] - '0';
5292          }
5293        }
5294      }
5295    }
5296    z[j] = c;
5297  }
5298  if( j<i ) z[j] = 0;
5299}
5300
5301/*
5302** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5303** for TRUE and FALSE.  Return the integer value if appropriate.
5304*/
5305static int booleanValue(const char *zArg){
5306  int i;
5307  if( zArg[0]=='0' && zArg[1]=='x' ){
5308    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5309  }else{
5310    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5311  }
5312  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5313  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5314    return 1;
5315  }
5316  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5317    return 0;
5318  }
5319  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5320          zArg);
5321  return 0;
5322}
5323
5324/*
5325** Set or clear a shell flag according to a boolean value.
5326*/
5327static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5328  if( booleanValue(zArg) ){
5329    ShellSetFlag(p, mFlag);
5330  }else{
5331    ShellClearFlag(p, mFlag);
5332  }
5333}
5334
5335/*
5336** Close an output file, assuming it is not stderr or stdout
5337*/
5338static void output_file_close(FILE *f){
5339  if( f && f!=stdout && f!=stderr ) fclose(f);
5340}
5341
5342/*
5343** Try to open an output file.   The names "stdout" and "stderr" are
5344** recognized and do the right thing.  NULL is returned if the output
5345** filename is "off".
5346*/
5347static FILE *output_file_open(const char *zFile, int bTextMode){
5348  FILE *f;
5349  if( strcmp(zFile,"stdout")==0 ){
5350    f = stdout;
5351  }else if( strcmp(zFile, "stderr")==0 ){
5352    f = stderr;
5353  }else if( strcmp(zFile, "off")==0 ){
5354    f = 0;
5355  }else{
5356    f = fopen(zFile, bTextMode ? "w" : "wb");
5357    if( f==0 ){
5358      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5359    }
5360  }
5361  return f;
5362}
5363
5364#ifndef SQLITE_OMIT_TRACE
5365/*
5366** A routine for handling output from sqlite3_trace().
5367*/
5368static int sql_trace_callback(
5369  unsigned mType,         /* The trace type */
5370  void *pArg,             /* The ShellState pointer */
5371  void *pP,               /* Usually a pointer to sqlite_stmt */
5372  void *pX                /* Auxiliary output */
5373){
5374  ShellState *p = (ShellState*)pArg;
5375  sqlite3_stmt *pStmt;
5376  const char *zSql;
5377  int nSql;
5378  if( p->traceOut==0 ) return 0;
5379  if( mType==SQLITE_TRACE_CLOSE ){
5380    utf8_printf(p->traceOut, "-- closing database connection\n");
5381    return 0;
5382  }
5383  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5384    zSql = (const char*)pX;
5385  }else{
5386    pStmt = (sqlite3_stmt*)pP;
5387    switch( p->eTraceType ){
5388      case SHELL_TRACE_EXPANDED: {
5389        zSql = sqlite3_expanded_sql(pStmt);
5390        break;
5391      }
5392#ifdef SQLITE_ENABLE_NORMALIZE
5393      case SHELL_TRACE_NORMALIZED: {
5394        zSql = sqlite3_normalized_sql(pStmt);
5395        break;
5396      }
5397#endif
5398      default: {
5399        zSql = sqlite3_sql(pStmt);
5400        break;
5401      }
5402    }
5403  }
5404  if( zSql==0 ) return 0;
5405  nSql = strlen30(zSql);
5406  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5407  switch( mType ){
5408    case SQLITE_TRACE_ROW:
5409    case SQLITE_TRACE_STMT: {
5410      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5411      break;
5412    }
5413    case SQLITE_TRACE_PROFILE: {
5414      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5415      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5416      break;
5417    }
5418  }
5419  return 0;
5420}
5421#endif
5422
5423/*
5424** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5425** a useful spot to set a debugger breakpoint.
5426*/
5427static void test_breakpoint(void){
5428  static int nCall = 0;
5429  nCall++;
5430}
5431
5432/*
5433** An object used to read a CSV and other files for import.
5434*/
5435typedef struct ImportCtx ImportCtx;
5436struct ImportCtx {
5437  const char *zFile;  /* Name of the input file */
5438  FILE *in;           /* Read the CSV text from this input stream */
5439  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5440  char *z;            /* Accumulated text for a field */
5441  int n;              /* Number of bytes in z */
5442  int nAlloc;         /* Space allocated for z[] */
5443  int nLine;          /* Current line number */
5444  int nRow;           /* Number of rows imported */
5445  int nErr;           /* Number of errors encountered */
5446  int bNotFirst;      /* True if one or more bytes already read */
5447  int cTerm;          /* Character that terminated the most recent field */
5448  int cColSep;        /* The column separator character.  (Usually ",") */
5449  int cRowSep;        /* The row separator character.  (Usually "\n") */
5450};
5451
5452/* Clean up resourced used by an ImportCtx */
5453static void import_cleanup(ImportCtx *p){
5454  if( p->in!=0 && p->xCloser!=0 ){
5455    p->xCloser(p->in);
5456    p->in = 0;
5457  }
5458  sqlite3_free(p->z);
5459  p->z = 0;
5460}
5461
5462/* Append a single byte to z[] */
5463static void import_append_char(ImportCtx *p, int c){
5464  if( p->n+1>=p->nAlloc ){
5465    p->nAlloc += p->nAlloc + 100;
5466    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5467    shell_check_oom(p->z);
5468  }
5469  p->z[p->n++] = (char)c;
5470}
5471
5472/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5473** with the option of having a separator other than ",".
5474**
5475**   +  Input comes from p->in.
5476**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5477**      from sqlite3_malloc64().
5478**   +  Use p->cSep as the column separator.  The default is ",".
5479**   +  Use p->rSep as the row separator.  The default is "\n".
5480**   +  Keep track of the line number in p->nLine.
5481**   +  Store the character that terminates the field in p->cTerm.  Store
5482**      EOF on end-of-file.
5483**   +  Report syntax errors on stderr
5484*/
5485static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5486  int c;
5487  int cSep = p->cColSep;
5488  int rSep = p->cRowSep;
5489  p->n = 0;
5490  c = fgetc(p->in);
5491  if( c==EOF || seenInterrupt ){
5492    p->cTerm = EOF;
5493    return 0;
5494  }
5495  if( c=='"' ){
5496    int pc, ppc;
5497    int startLine = p->nLine;
5498    int cQuote = c;
5499    pc = ppc = 0;
5500    while( 1 ){
5501      c = fgetc(p->in);
5502      if( c==rSep ) p->nLine++;
5503      if( c==cQuote ){
5504        if( pc==cQuote ){
5505          pc = 0;
5506          continue;
5507        }
5508      }
5509      if( (c==cSep && pc==cQuote)
5510       || (c==rSep && pc==cQuote)
5511       || (c==rSep && pc=='\r' && ppc==cQuote)
5512       || (c==EOF && pc==cQuote)
5513      ){
5514        do{ p->n--; }while( p->z[p->n]!=cQuote );
5515        p->cTerm = c;
5516        break;
5517      }
5518      if( pc==cQuote && c!='\r' ){
5519        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5520                p->zFile, p->nLine, cQuote);
5521      }
5522      if( c==EOF ){
5523        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5524                p->zFile, startLine, cQuote);
5525        p->cTerm = c;
5526        break;
5527      }
5528      import_append_char(p, c);
5529      ppc = pc;
5530      pc = c;
5531    }
5532  }else{
5533    /* If this is the first field being parsed and it begins with the
5534    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5535    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5536      import_append_char(p, c);
5537      c = fgetc(p->in);
5538      if( (c&0xff)==0xbb ){
5539        import_append_char(p, c);
5540        c = fgetc(p->in);
5541        if( (c&0xff)==0xbf ){
5542          p->bNotFirst = 1;
5543          p->n = 0;
5544          return csv_read_one_field(p);
5545        }
5546      }
5547    }
5548    while( c!=EOF && c!=cSep && c!=rSep ){
5549      import_append_char(p, c);
5550      c = fgetc(p->in);
5551    }
5552    if( c==rSep ){
5553      p->nLine++;
5554      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5555    }
5556    p->cTerm = c;
5557  }
5558  if( p->z ) p->z[p->n] = 0;
5559  p->bNotFirst = 1;
5560  return p->z;
5561}
5562
5563/* Read a single field of ASCII delimited text.
5564**
5565**   +  Input comes from p->in.
5566**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5567**      from sqlite3_malloc64().
5568**   +  Use p->cSep as the column separator.  The default is "\x1F".
5569**   +  Use p->rSep as the row separator.  The default is "\x1E".
5570**   +  Keep track of the row number in p->nLine.
5571**   +  Store the character that terminates the field in p->cTerm.  Store
5572**      EOF on end-of-file.
5573**   +  Report syntax errors on stderr
5574*/
5575static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5576  int c;
5577  int cSep = p->cColSep;
5578  int rSep = p->cRowSep;
5579  p->n = 0;
5580  c = fgetc(p->in);
5581  if( c==EOF || seenInterrupt ){
5582    p->cTerm = EOF;
5583    return 0;
5584  }
5585  while( c!=EOF && c!=cSep && c!=rSep ){
5586    import_append_char(p, c);
5587    c = fgetc(p->in);
5588  }
5589  if( c==rSep ){
5590    p->nLine++;
5591  }
5592  p->cTerm = c;
5593  if( p->z ) p->z[p->n] = 0;
5594  return p->z;
5595}
5596
5597/*
5598** Try to transfer data for table zTable.  If an error is seen while
5599** moving forward, try to go backwards.  The backwards movement won't
5600** work for WITHOUT ROWID tables.
5601*/
5602static void tryToCloneData(
5603  ShellState *p,
5604  sqlite3 *newDb,
5605  const char *zTable
5606){
5607  sqlite3_stmt *pQuery = 0;
5608  sqlite3_stmt *pInsert = 0;
5609  char *zQuery = 0;
5610  char *zInsert = 0;
5611  int rc;
5612  int i, j, n;
5613  int nTable = strlen30(zTable);
5614  int k = 0;
5615  int cnt = 0;
5616  const int spinRate = 10000;
5617
5618  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5619  shell_check_oom(zQuery);
5620  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5621  if( rc ){
5622    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5623            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5624            zQuery);
5625    goto end_data_xfer;
5626  }
5627  n = sqlite3_column_count(pQuery);
5628  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5629  shell_check_oom(zInsert);
5630  sqlite3_snprintf(200+nTable,zInsert,
5631                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5632  i = strlen30(zInsert);
5633  for(j=1; j<n; j++){
5634    memcpy(zInsert+i, ",?", 2);
5635    i += 2;
5636  }
5637  memcpy(zInsert+i, ");", 3);
5638  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5639  if( rc ){
5640    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5641            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5642            zQuery);
5643    goto end_data_xfer;
5644  }
5645  for(k=0; k<2; k++){
5646    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5647      for(i=0; i<n; i++){
5648        switch( sqlite3_column_type(pQuery, i) ){
5649          case SQLITE_NULL: {
5650            sqlite3_bind_null(pInsert, i+1);
5651            break;
5652          }
5653          case SQLITE_INTEGER: {
5654            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5655            break;
5656          }
5657          case SQLITE_FLOAT: {
5658            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5659            break;
5660          }
5661          case SQLITE_TEXT: {
5662            sqlite3_bind_text(pInsert, i+1,
5663                             (const char*)sqlite3_column_text(pQuery,i),
5664                             -1, SQLITE_STATIC);
5665            break;
5666          }
5667          case SQLITE_BLOB: {
5668            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5669                                            sqlite3_column_bytes(pQuery,i),
5670                                            SQLITE_STATIC);
5671            break;
5672          }
5673        }
5674      } /* End for */
5675      rc = sqlite3_step(pInsert);
5676      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5677        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5678                        sqlite3_errmsg(newDb));
5679      }
5680      sqlite3_reset(pInsert);
5681      cnt++;
5682      if( (cnt%spinRate)==0 ){
5683        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5684        fflush(stdout);
5685      }
5686    } /* End while */
5687    if( rc==SQLITE_DONE ) break;
5688    sqlite3_finalize(pQuery);
5689    sqlite3_free(zQuery);
5690    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5691                             zTable);
5692    shell_check_oom(zQuery);
5693    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5694    if( rc ){
5695      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5696      break;
5697    }
5698  } /* End for(k=0...) */
5699
5700end_data_xfer:
5701  sqlite3_finalize(pQuery);
5702  sqlite3_finalize(pInsert);
5703  sqlite3_free(zQuery);
5704  sqlite3_free(zInsert);
5705}
5706
5707
5708/*
5709** Try to transfer all rows of the schema that match zWhere.  For
5710** each row, invoke xForEach() on the object defined by that row.
5711** If an error is encountered while moving forward through the
5712** sqlite_schema table, try again moving backwards.
5713*/
5714static void tryToCloneSchema(
5715  ShellState *p,
5716  sqlite3 *newDb,
5717  const char *zWhere,
5718  void (*xForEach)(ShellState*,sqlite3*,const char*)
5719){
5720  sqlite3_stmt *pQuery = 0;
5721  char *zQuery = 0;
5722  int rc;
5723  const unsigned char *zName;
5724  const unsigned char *zSql;
5725  char *zErrMsg = 0;
5726
5727  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5728                           " WHERE %s", zWhere);
5729  shell_check_oom(zQuery);
5730  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5731  if( rc ){
5732    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5733                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5734                    zQuery);
5735    goto end_schema_xfer;
5736  }
5737  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5738    zName = sqlite3_column_text(pQuery, 0);
5739    zSql = sqlite3_column_text(pQuery, 1);
5740    if( zName==0 || zSql==0 ) continue;
5741    printf("%s... ", zName); fflush(stdout);
5742    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5743    if( zErrMsg ){
5744      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5745      sqlite3_free(zErrMsg);
5746      zErrMsg = 0;
5747    }
5748    if( xForEach ){
5749      xForEach(p, newDb, (const char*)zName);
5750    }
5751    printf("done\n");
5752  }
5753  if( rc!=SQLITE_DONE ){
5754    sqlite3_finalize(pQuery);
5755    sqlite3_free(zQuery);
5756    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5757                             " WHERE %s ORDER BY rowid DESC", zWhere);
5758    shell_check_oom(zQuery);
5759    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5760    if( rc ){
5761      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5762                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5763                      zQuery);
5764      goto end_schema_xfer;
5765    }
5766    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5767      zName = sqlite3_column_text(pQuery, 0);
5768      zSql = sqlite3_column_text(pQuery, 1);
5769      if( zName==0 || zSql==0 ) continue;
5770      printf("%s... ", zName); fflush(stdout);
5771      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5772      if( zErrMsg ){
5773        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5774        sqlite3_free(zErrMsg);
5775        zErrMsg = 0;
5776      }
5777      if( xForEach ){
5778        xForEach(p, newDb, (const char*)zName);
5779      }
5780      printf("done\n");
5781    }
5782  }
5783end_schema_xfer:
5784  sqlite3_finalize(pQuery);
5785  sqlite3_free(zQuery);
5786}
5787
5788/*
5789** Open a new database file named "zNewDb".  Try to recover as much information
5790** as possible out of the main database (which might be corrupt) and write it
5791** into zNewDb.
5792*/
5793static void tryToClone(ShellState *p, const char *zNewDb){
5794  int rc;
5795  sqlite3 *newDb = 0;
5796  if( access(zNewDb,0)==0 ){
5797    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5798    return;
5799  }
5800  rc = sqlite3_open(zNewDb, &newDb);
5801  if( rc ){
5802    utf8_printf(stderr, "Cannot create output database: %s\n",
5803            sqlite3_errmsg(newDb));
5804  }else{
5805    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5806    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5807    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5808    tryToCloneSchema(p, newDb, "type!='table'", 0);
5809    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5810    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5811  }
5812  close_db(newDb);
5813}
5814
5815/*
5816** Change the output file back to stdout.
5817**
5818** If the p->doXdgOpen flag is set, that means the output was being
5819** redirected to a temporary file named by p->zTempFile.  In that case,
5820** launch start/open/xdg-open on that temporary file.
5821*/
5822static void output_reset(ShellState *p){
5823  if( p->outfile[0]=='|' ){
5824#ifndef SQLITE_OMIT_POPEN
5825    pclose(p->out);
5826#endif
5827  }else{
5828    output_file_close(p->out);
5829#ifndef SQLITE_NOHAVE_SYSTEM
5830    if( p->doXdgOpen ){
5831      const char *zXdgOpenCmd =
5832#if defined(_WIN32)
5833      "start";
5834#elif defined(__APPLE__)
5835      "open";
5836#else
5837      "xdg-open";
5838#endif
5839      char *zCmd;
5840      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5841      if( system(zCmd) ){
5842        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5843      }else{
5844        /* Give the start/open/xdg-open command some time to get
5845        ** going before we continue, and potential delete the
5846        ** p->zTempFile data file out from under it */
5847        sqlite3_sleep(2000);
5848      }
5849      sqlite3_free(zCmd);
5850      outputModePop(p);
5851      p->doXdgOpen = 0;
5852    }
5853#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5854  }
5855  p->outfile[0] = 0;
5856  p->out = stdout;
5857}
5858
5859/*
5860** Run an SQL command and return the single integer result.
5861*/
5862static int db_int(sqlite3 *db, const char *zSql){
5863  sqlite3_stmt *pStmt;
5864  int res = 0;
5865  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5866  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5867    res = sqlite3_column_int(pStmt,0);
5868  }
5869  sqlite3_finalize(pStmt);
5870  return res;
5871}
5872
5873#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5874/*
5875** Convert a 2-byte or 4-byte big-endian integer into a native integer
5876*/
5877static unsigned int get2byteInt(unsigned char *a){
5878  return (a[0]<<8) + a[1];
5879}
5880static unsigned int get4byteInt(unsigned char *a){
5881  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5882}
5883
5884/*
5885** Implementation of the ".dbinfo" command.
5886**
5887** Return 1 on error, 2 to exit, and 0 otherwise.
5888*/
5889static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5890  static const struct { const char *zName; int ofst; } aField[] = {
5891     { "file change counter:",  24  },
5892     { "database page count:",  28  },
5893     { "freelist page count:",  36  },
5894     { "schema cookie:",        40  },
5895     { "schema format:",        44  },
5896     { "default cache size:",   48  },
5897     { "autovacuum top root:",  52  },
5898     { "incremental vacuum:",   64  },
5899     { "text encoding:",        56  },
5900     { "user version:",         60  },
5901     { "application id:",       68  },
5902     { "software version:",     96  },
5903  };
5904  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5905     { "number of tables:",
5906       "SELECT count(*) FROM %s WHERE type='table'" },
5907     { "number of indexes:",
5908       "SELECT count(*) FROM %s WHERE type='index'" },
5909     { "number of triggers:",
5910       "SELECT count(*) FROM %s WHERE type='trigger'" },
5911     { "number of views:",
5912       "SELECT count(*) FROM %s WHERE type='view'" },
5913     { "schema size:",
5914       "SELECT total(length(sql)) FROM %s" },
5915  };
5916  int i, rc;
5917  unsigned iDataVersion;
5918  char *zSchemaTab;
5919  char *zDb = nArg>=2 ? azArg[1] : "main";
5920  sqlite3_stmt *pStmt = 0;
5921  unsigned char aHdr[100];
5922  open_db(p, 0);
5923  if( p->db==0 ) return 1;
5924  rc = sqlite3_prepare_v2(p->db,
5925             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5926             -1, &pStmt, 0);
5927  if( rc ){
5928    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5929    sqlite3_finalize(pStmt);
5930    return 1;
5931  }
5932  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5933  if( sqlite3_step(pStmt)==SQLITE_ROW
5934   && sqlite3_column_bytes(pStmt,0)>100
5935  ){
5936    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5937    sqlite3_finalize(pStmt);
5938  }else{
5939    raw_printf(stderr, "unable to read database header\n");
5940    sqlite3_finalize(pStmt);
5941    return 1;
5942  }
5943  i = get2byteInt(aHdr+16);
5944  if( i==1 ) i = 65536;
5945  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5946  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5947  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5948  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5949  for(i=0; i<ArraySize(aField); i++){
5950    int ofst = aField[i].ofst;
5951    unsigned int val = get4byteInt(aHdr + ofst);
5952    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5953    switch( ofst ){
5954      case 56: {
5955        if( val==1 ) raw_printf(p->out, " (utf8)");
5956        if( val==2 ) raw_printf(p->out, " (utf16le)");
5957        if( val==3 ) raw_printf(p->out, " (utf16be)");
5958      }
5959    }
5960    raw_printf(p->out, "\n");
5961  }
5962  if( zDb==0 ){
5963    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5964  }else if( strcmp(zDb,"temp")==0 ){
5965    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5966  }else{
5967    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5968  }
5969  for(i=0; i<ArraySize(aQuery); i++){
5970    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5971    int val = db_int(p->db, zSql);
5972    sqlite3_free(zSql);
5973    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5974  }
5975  sqlite3_free(zSchemaTab);
5976  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5977  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5978  return 0;
5979}
5980#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5981          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5982
5983/*
5984** Print the current sqlite3_errmsg() value to stderr and return 1.
5985*/
5986static int shellDatabaseError(sqlite3 *db){
5987  const char *zErr = sqlite3_errmsg(db);
5988  utf8_printf(stderr, "Error: %s\n", zErr);
5989  return 1;
5990}
5991
5992/*
5993** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5994** if they match and FALSE (0) if they do not match.
5995**
5996** Globbing rules:
5997**
5998**      '*'       Matches any sequence of zero or more characters.
5999**
6000**      '?'       Matches exactly one character.
6001**
6002**     [...]      Matches one character from the enclosed list of
6003**                characters.
6004**
6005**     [^...]     Matches one character not in the enclosed list.
6006**
6007**      '#'       Matches any sequence of one or more digits with an
6008**                optional + or - sign in front
6009**
6010**      ' '       Any span of whitespace matches any other span of
6011**                whitespace.
6012**
6013** Extra whitespace at the end of z[] is ignored.
6014*/
6015static int testcase_glob(const char *zGlob, const char *z){
6016  int c, c2;
6017  int invert;
6018  int seen;
6019
6020  while( (c = (*(zGlob++)))!=0 ){
6021    if( IsSpace(c) ){
6022      if( !IsSpace(*z) ) return 0;
6023      while( IsSpace(*zGlob) ) zGlob++;
6024      while( IsSpace(*z) ) z++;
6025    }else if( c=='*' ){
6026      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6027        if( c=='?' && (*(z++))==0 ) return 0;
6028      }
6029      if( c==0 ){
6030        return 1;
6031      }else if( c=='[' ){
6032        while( *z && testcase_glob(zGlob-1,z)==0 ){
6033          z++;
6034        }
6035        return (*z)!=0;
6036      }
6037      while( (c2 = (*(z++)))!=0 ){
6038        while( c2!=c ){
6039          c2 = *(z++);
6040          if( c2==0 ) return 0;
6041        }
6042        if( testcase_glob(zGlob,z) ) return 1;
6043      }
6044      return 0;
6045    }else if( c=='?' ){
6046      if( (*(z++))==0 ) return 0;
6047    }else if( c=='[' ){
6048      int prior_c = 0;
6049      seen = 0;
6050      invert = 0;
6051      c = *(z++);
6052      if( c==0 ) return 0;
6053      c2 = *(zGlob++);
6054      if( c2=='^' ){
6055        invert = 1;
6056        c2 = *(zGlob++);
6057      }
6058      if( c2==']' ){
6059        if( c==']' ) seen = 1;
6060        c2 = *(zGlob++);
6061      }
6062      while( c2 && c2!=']' ){
6063        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6064          c2 = *(zGlob++);
6065          if( c>=prior_c && c<=c2 ) seen = 1;
6066          prior_c = 0;
6067        }else{
6068          if( c==c2 ){
6069            seen = 1;
6070          }
6071          prior_c = c2;
6072        }
6073        c2 = *(zGlob++);
6074      }
6075      if( c2==0 || (seen ^ invert)==0 ) return 0;
6076    }else if( c=='#' ){
6077      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6078      if( !IsDigit(z[0]) ) return 0;
6079      z++;
6080      while( IsDigit(z[0]) ){ z++; }
6081    }else{
6082      if( c!=(*(z++)) ) return 0;
6083    }
6084  }
6085  while( IsSpace(*z) ){ z++; }
6086  return *z==0;
6087}
6088
6089
6090/*
6091** Compare the string as a command-line option with either one or two
6092** initial "-" characters.
6093*/
6094static int optionMatch(const char *zStr, const char *zOpt){
6095  if( zStr[0]!='-' ) return 0;
6096  zStr++;
6097  if( zStr[0]=='-' ) zStr++;
6098  return strcmp(zStr, zOpt)==0;
6099}
6100
6101/*
6102** Delete a file.
6103*/
6104int shellDeleteFile(const char *zFilename){
6105  int rc;
6106#ifdef _WIN32
6107  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6108  rc = _wunlink(z);
6109  sqlite3_free(z);
6110#else
6111  rc = unlink(zFilename);
6112#endif
6113  return rc;
6114}
6115
6116/*
6117** Try to delete the temporary file (if there is one) and free the
6118** memory used to hold the name of the temp file.
6119*/
6120static void clearTempFile(ShellState *p){
6121  if( p->zTempFile==0 ) return;
6122  if( p->doXdgOpen ) return;
6123  if( shellDeleteFile(p->zTempFile) ) return;
6124  sqlite3_free(p->zTempFile);
6125  p->zTempFile = 0;
6126}
6127
6128/*
6129** Create a new temp file name with the given suffix.
6130*/
6131static void newTempFile(ShellState *p, const char *zSuffix){
6132  clearTempFile(p);
6133  sqlite3_free(p->zTempFile);
6134  p->zTempFile = 0;
6135  if( p->db ){
6136    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6137  }
6138  if( p->zTempFile==0 ){
6139    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6140    ** will not work and we will need to fallback to guessing */
6141    char *zTemp;
6142    sqlite3_uint64 r;
6143    sqlite3_randomness(sizeof(r), &r);
6144    zTemp = getenv("TEMP");
6145    if( zTemp==0 ) zTemp = getenv("TMP");
6146    if( zTemp==0 ){
6147#ifdef _WIN32
6148      zTemp = "\\tmp";
6149#else
6150      zTemp = "/tmp";
6151#endif
6152    }
6153    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6154  }else{
6155    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6156  }
6157  shell_check_oom(p->zTempFile);
6158}
6159
6160
6161/*
6162** The implementation of SQL scalar function fkey_collate_clause(), used
6163** by the ".lint fkey-indexes" command. This scalar function is always
6164** called with four arguments - the parent table name, the parent column name,
6165** the child table name and the child column name.
6166**
6167**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6168**
6169** If either of the named tables or columns do not exist, this function
6170** returns an empty string. An empty string is also returned if both tables
6171** and columns exist but have the same default collation sequence. Or,
6172** if both exist but the default collation sequences are different, this
6173** function returns the string " COLLATE <parent-collation>", where
6174** <parent-collation> is the default collation sequence of the parent column.
6175*/
6176static void shellFkeyCollateClause(
6177  sqlite3_context *pCtx,
6178  int nVal,
6179  sqlite3_value **apVal
6180){
6181  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6182  const char *zParent;
6183  const char *zParentCol;
6184  const char *zParentSeq;
6185  const char *zChild;
6186  const char *zChildCol;
6187  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6188  int rc;
6189
6190  assert( nVal==4 );
6191  zParent = (const char*)sqlite3_value_text(apVal[0]);
6192  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6193  zChild = (const char*)sqlite3_value_text(apVal[2]);
6194  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6195
6196  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6197  rc = sqlite3_table_column_metadata(
6198      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6199  );
6200  if( rc==SQLITE_OK ){
6201    rc = sqlite3_table_column_metadata(
6202        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6203    );
6204  }
6205
6206  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6207    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6208    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6209    sqlite3_free(z);
6210  }
6211}
6212
6213
6214/*
6215** The implementation of dot-command ".lint fkey-indexes".
6216*/
6217static int lintFkeyIndexes(
6218  ShellState *pState,             /* Current shell tool state */
6219  char **azArg,                   /* Array of arguments passed to dot command */
6220  int nArg                        /* Number of entries in azArg[] */
6221){
6222  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6223  FILE *out = pState->out;        /* Stream to write non-error output to */
6224  int bVerbose = 0;               /* If -verbose is present */
6225  int bGroupByParent = 0;         /* If -groupbyparent is present */
6226  int i;                          /* To iterate through azArg[] */
6227  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6228  int rc;                         /* Return code */
6229  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6230
6231  /*
6232  ** This SELECT statement returns one row for each foreign key constraint
6233  ** in the schema of the main database. The column values are:
6234  **
6235  ** 0. The text of an SQL statement similar to:
6236  **
6237  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6238  **
6239  **    This SELECT is similar to the one that the foreign keys implementation
6240  **    needs to run internally on child tables. If there is an index that can
6241  **    be used to optimize this query, then it can also be used by the FK
6242  **    implementation to optimize DELETE or UPDATE statements on the parent
6243  **    table.
6244  **
6245  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6246  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6247  **    contains an index that can be used to optimize the query.
6248  **
6249  ** 2. Human readable text that describes the child table and columns. e.g.
6250  **
6251  **       "child_table(child_key1, child_key2)"
6252  **
6253  ** 3. Human readable text that describes the parent table and columns. e.g.
6254  **
6255  **       "parent_table(parent_key1, parent_key2)"
6256  **
6257  ** 4. A full CREATE INDEX statement for an index that could be used to
6258  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6259  **
6260  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6261  **
6262  ** 5. The name of the parent table.
6263  **
6264  ** These six values are used by the C logic below to generate the report.
6265  */
6266  const char *zSql =
6267  "SELECT "
6268    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6269    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6270    "  || fkey_collate_clause("
6271    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6272    ", "
6273    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6274    "  || group_concat('*=?', ' AND ') || ')'"
6275    ", "
6276    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6277    ", "
6278    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6279    ", "
6280    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6281    "  || ' ON ' || quote(s.name) || '('"
6282    "  || group_concat(quote(f.[from]) ||"
6283    "        fkey_collate_clause("
6284    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6285    "  || ');'"
6286    ", "
6287    "     f.[table] "
6288    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6289    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6290    "GROUP BY s.name, f.id "
6291    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6292  ;
6293  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6294
6295  for(i=2; i<nArg; i++){
6296    int n = strlen30(azArg[i]);
6297    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6298      bVerbose = 1;
6299    }
6300    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6301      bGroupByParent = 1;
6302      zIndent = "    ";
6303    }
6304    else{
6305      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6306          azArg[0], azArg[1]
6307      );
6308      return SQLITE_ERROR;
6309    }
6310  }
6311
6312  /* Register the fkey_collate_clause() SQL function */
6313  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6314      0, shellFkeyCollateClause, 0, 0
6315  );
6316
6317
6318  if( rc==SQLITE_OK ){
6319    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6320  }
6321  if( rc==SQLITE_OK ){
6322    sqlite3_bind_int(pSql, 1, bGroupByParent);
6323  }
6324
6325  if( rc==SQLITE_OK ){
6326    int rc2;
6327    char *zPrev = 0;
6328    while( SQLITE_ROW==sqlite3_step(pSql) ){
6329      int res = -1;
6330      sqlite3_stmt *pExplain = 0;
6331      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6332      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6333      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6334      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6335      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6336      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6337
6338      if( zEQP==0 ) continue;
6339      if( zGlob==0 ) continue;
6340      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6341      if( rc!=SQLITE_OK ) break;
6342      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6343        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6344        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6345                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6346      }
6347      rc = sqlite3_finalize(pExplain);
6348      if( rc!=SQLITE_OK ) break;
6349
6350      if( res<0 ){
6351        raw_printf(stderr, "Error: internal error");
6352        break;
6353      }else{
6354        if( bGroupByParent
6355        && (bVerbose || res==0)
6356        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6357        ){
6358          raw_printf(out, "-- Parent table %s\n", zParent);
6359          sqlite3_free(zPrev);
6360          zPrev = sqlite3_mprintf("%s", zParent);
6361        }
6362
6363        if( res==0 ){
6364          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6365        }else if( bVerbose ){
6366          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6367              zIndent, zFrom, zTarget
6368          );
6369        }
6370      }
6371    }
6372    sqlite3_free(zPrev);
6373
6374    if( rc!=SQLITE_OK ){
6375      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6376    }
6377
6378    rc2 = sqlite3_finalize(pSql);
6379    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6380      rc = rc2;
6381      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6382    }
6383  }else{
6384    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6385  }
6386
6387  return rc;
6388}
6389
6390/*
6391** Implementation of ".lint" dot command.
6392*/
6393static int lintDotCommand(
6394  ShellState *pState,             /* Current shell tool state */
6395  char **azArg,                   /* Array of arguments passed to dot command */
6396  int nArg                        /* Number of entries in azArg[] */
6397){
6398  int n;
6399  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6400  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6401  return lintFkeyIndexes(pState, azArg, nArg);
6402
6403 usage:
6404  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6405  raw_printf(stderr, "Where sub-commands are:\n");
6406  raw_printf(stderr, "    fkey-indexes\n");
6407  return SQLITE_ERROR;
6408}
6409
6410#if !defined SQLITE_OMIT_VIRTUALTABLE
6411static void shellPrepare(
6412  sqlite3 *db,
6413  int *pRc,
6414  const char *zSql,
6415  sqlite3_stmt **ppStmt
6416){
6417  *ppStmt = 0;
6418  if( *pRc==SQLITE_OK ){
6419    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6420    if( rc!=SQLITE_OK ){
6421      raw_printf(stderr, "sql error: %s (%d)\n",
6422          sqlite3_errmsg(db), sqlite3_errcode(db)
6423      );
6424      *pRc = rc;
6425    }
6426  }
6427}
6428
6429/*
6430** Create a prepared statement using printf-style arguments for the SQL.
6431**
6432** This routine is could be marked "static".  But it is not always used,
6433** depending on compile-time options.  By omitting the "static", we avoid
6434** nuisance compiler warnings about "defined but not used".
6435*/
6436void shellPreparePrintf(
6437  sqlite3 *db,
6438  int *pRc,
6439  sqlite3_stmt **ppStmt,
6440  const char *zFmt,
6441  ...
6442){
6443  *ppStmt = 0;
6444  if( *pRc==SQLITE_OK ){
6445    va_list ap;
6446    char *z;
6447    va_start(ap, zFmt);
6448    z = sqlite3_vmprintf(zFmt, ap);
6449    va_end(ap);
6450    if( z==0 ){
6451      *pRc = SQLITE_NOMEM;
6452    }else{
6453      shellPrepare(db, pRc, z, ppStmt);
6454      sqlite3_free(z);
6455    }
6456  }
6457}
6458
6459/* Finalize the prepared statement created using shellPreparePrintf().
6460**
6461** This routine is could be marked "static".  But it is not always used,
6462** depending on compile-time options.  By omitting the "static", we avoid
6463** nuisance compiler warnings about "defined but not used".
6464*/
6465void shellFinalize(
6466  int *pRc,
6467  sqlite3_stmt *pStmt
6468){
6469  if( pStmt ){
6470    sqlite3 *db = sqlite3_db_handle(pStmt);
6471    int rc = sqlite3_finalize(pStmt);
6472    if( *pRc==SQLITE_OK ){
6473      if( rc!=SQLITE_OK ){
6474        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6475      }
6476      *pRc = rc;
6477    }
6478  }
6479}
6480
6481/* Reset the prepared statement created using shellPreparePrintf().
6482**
6483** This routine is could be marked "static".  But it is not always used,
6484** depending on compile-time options.  By omitting the "static", we avoid
6485** nuisance compiler warnings about "defined but not used".
6486*/
6487void shellReset(
6488  int *pRc,
6489  sqlite3_stmt *pStmt
6490){
6491  int rc = sqlite3_reset(pStmt);
6492  if( *pRc==SQLITE_OK ){
6493    if( rc!=SQLITE_OK ){
6494      sqlite3 *db = sqlite3_db_handle(pStmt);
6495      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6496    }
6497    *pRc = rc;
6498  }
6499}
6500#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6501
6502#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6503/******************************************************************************
6504** The ".archive" or ".ar" command.
6505*/
6506/*
6507** Structure representing a single ".ar" command.
6508*/
6509typedef struct ArCommand ArCommand;
6510struct ArCommand {
6511  u8 eCmd;                        /* An AR_CMD_* value */
6512  u8 bVerbose;                    /* True if --verbose */
6513  u8 bZip;                        /* True if the archive is a ZIP */
6514  u8 bDryRun;                     /* True if --dry-run */
6515  u8 bAppend;                     /* True if --append */
6516  u8 bGlob;                       /* True if --glob */
6517  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6518  int nArg;                       /* Number of command arguments */
6519  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6520  const char *zFile;              /* --file argument, or NULL */
6521  const char *zDir;               /* --directory argument, or NULL */
6522  char **azArg;                   /* Array of command arguments */
6523  ShellState *p;                  /* Shell state */
6524  sqlite3 *db;                    /* Database containing the archive */
6525};
6526
6527/*
6528** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6529*/
6530static int arUsage(FILE *f){
6531  showHelp(f,"archive");
6532  return SQLITE_ERROR;
6533}
6534
6535/*
6536** Print an error message for the .ar command to stderr and return
6537** SQLITE_ERROR.
6538*/
6539static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6540  va_list ap;
6541  char *z;
6542  va_start(ap, zFmt);
6543  z = sqlite3_vmprintf(zFmt, ap);
6544  va_end(ap);
6545  utf8_printf(stderr, "Error: %s\n", z);
6546  if( pAr->fromCmdLine ){
6547    utf8_printf(stderr, "Use \"-A\" for more help\n");
6548  }else{
6549    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6550  }
6551  sqlite3_free(z);
6552  return SQLITE_ERROR;
6553}
6554
6555/*
6556** Values for ArCommand.eCmd.
6557*/
6558#define AR_CMD_CREATE       1
6559#define AR_CMD_UPDATE       2
6560#define AR_CMD_INSERT       3
6561#define AR_CMD_EXTRACT      4
6562#define AR_CMD_LIST         5
6563#define AR_CMD_HELP         6
6564#define AR_CMD_REMOVE       7
6565
6566/*
6567** Other (non-command) switches.
6568*/
6569#define AR_SWITCH_VERBOSE     8
6570#define AR_SWITCH_FILE        9
6571#define AR_SWITCH_DIRECTORY  10
6572#define AR_SWITCH_APPEND     11
6573#define AR_SWITCH_DRYRUN     12
6574#define AR_SWITCH_GLOB       13
6575
6576static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6577  switch( eSwitch ){
6578    case AR_CMD_CREATE:
6579    case AR_CMD_EXTRACT:
6580    case AR_CMD_LIST:
6581    case AR_CMD_REMOVE:
6582    case AR_CMD_UPDATE:
6583    case AR_CMD_INSERT:
6584    case AR_CMD_HELP:
6585      if( pAr->eCmd ){
6586        return arErrorMsg(pAr, "multiple command options");
6587      }
6588      pAr->eCmd = eSwitch;
6589      break;
6590
6591    case AR_SWITCH_DRYRUN:
6592      pAr->bDryRun = 1;
6593      break;
6594    case AR_SWITCH_GLOB:
6595      pAr->bGlob = 1;
6596      break;
6597    case AR_SWITCH_VERBOSE:
6598      pAr->bVerbose = 1;
6599      break;
6600    case AR_SWITCH_APPEND:
6601      pAr->bAppend = 1;
6602      /* Fall thru into --file */
6603    case AR_SWITCH_FILE:
6604      pAr->zFile = zArg;
6605      break;
6606    case AR_SWITCH_DIRECTORY:
6607      pAr->zDir = zArg;
6608      break;
6609  }
6610
6611  return SQLITE_OK;
6612}
6613
6614/*
6615** Parse the command line for an ".ar" command. The results are written into
6616** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6617** successfully, otherwise an error message is written to stderr and
6618** SQLITE_ERROR returned.
6619*/
6620static int arParseCommand(
6621  char **azArg,                   /* Array of arguments passed to dot command */
6622  int nArg,                       /* Number of entries in azArg[] */
6623  ArCommand *pAr                  /* Populate this object */
6624){
6625  struct ArSwitch {
6626    const char *zLong;
6627    char cShort;
6628    u8 eSwitch;
6629    u8 bArg;
6630  } aSwitch[] = {
6631    { "create",    'c', AR_CMD_CREATE,       0 },
6632    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6633    { "insert",    'i', AR_CMD_INSERT,       0 },
6634    { "list",      't', AR_CMD_LIST,         0 },
6635    { "remove",    'r', AR_CMD_REMOVE,       0 },
6636    { "update",    'u', AR_CMD_UPDATE,       0 },
6637    { "help",      'h', AR_CMD_HELP,         0 },
6638    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6639    { "file",      'f', AR_SWITCH_FILE,      1 },
6640    { "append",    'a', AR_SWITCH_APPEND,    1 },
6641    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6642    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6643    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6644  };
6645  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6646  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6647
6648  if( nArg<=1 ){
6649    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6650    return arUsage(stderr);
6651  }else{
6652    char *z = azArg[1];
6653    if( z[0]!='-' ){
6654      /* Traditional style [tar] invocation */
6655      int i;
6656      int iArg = 2;
6657      for(i=0; z[i]; i++){
6658        const char *zArg = 0;
6659        struct ArSwitch *pOpt;
6660        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6661          if( z[i]==pOpt->cShort ) break;
6662        }
6663        if( pOpt==pEnd ){
6664          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6665        }
6666        if( pOpt->bArg ){
6667          if( iArg>=nArg ){
6668            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6669          }
6670          zArg = azArg[iArg++];
6671        }
6672        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6673      }
6674      pAr->nArg = nArg-iArg;
6675      if( pAr->nArg>0 ){
6676        pAr->azArg = &azArg[iArg];
6677      }
6678    }else{
6679      /* Non-traditional invocation */
6680      int iArg;
6681      for(iArg=1; iArg<nArg; iArg++){
6682        int n;
6683        z = azArg[iArg];
6684        if( z[0]!='-' ){
6685          /* All remaining command line words are command arguments. */
6686          pAr->azArg = &azArg[iArg];
6687          pAr->nArg = nArg-iArg;
6688          break;
6689        }
6690        n = strlen30(z);
6691
6692        if( z[1]!='-' ){
6693          int i;
6694          /* One or more short options */
6695          for(i=1; i<n; i++){
6696            const char *zArg = 0;
6697            struct ArSwitch *pOpt;
6698            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6699              if( z[i]==pOpt->cShort ) break;
6700            }
6701            if( pOpt==pEnd ){
6702              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6703            }
6704            if( pOpt->bArg ){
6705              if( i<(n-1) ){
6706                zArg = &z[i+1];
6707                i = n;
6708              }else{
6709                if( iArg>=(nArg-1) ){
6710                  return arErrorMsg(pAr, "option requires an argument: %c",
6711                                    z[i]);
6712                }
6713                zArg = azArg[++iArg];
6714              }
6715            }
6716            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6717          }
6718        }else if( z[2]=='\0' ){
6719          /* A -- option, indicating that all remaining command line words
6720          ** are command arguments.  */
6721          pAr->azArg = &azArg[iArg+1];
6722          pAr->nArg = nArg-iArg-1;
6723          break;
6724        }else{
6725          /* A long option */
6726          const char *zArg = 0;             /* Argument for option, if any */
6727          struct ArSwitch *pMatch = 0;      /* Matching option */
6728          struct ArSwitch *pOpt;            /* Iterator */
6729          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6730            const char *zLong = pOpt->zLong;
6731            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6732              if( pMatch ){
6733                return arErrorMsg(pAr, "ambiguous option: %s",z);
6734              }else{
6735                pMatch = pOpt;
6736              }
6737            }
6738          }
6739
6740          if( pMatch==0 ){
6741            return arErrorMsg(pAr, "unrecognized option: %s", z);
6742          }
6743          if( pMatch->bArg ){
6744            if( iArg>=(nArg-1) ){
6745              return arErrorMsg(pAr, "option requires an argument: %s", z);
6746            }
6747            zArg = azArg[++iArg];
6748          }
6749          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6750        }
6751      }
6752    }
6753  }
6754
6755  return SQLITE_OK;
6756}
6757
6758/*
6759** This function assumes that all arguments within the ArCommand.azArg[]
6760** array refer to archive members, as for the --extract, --list or --remove
6761** commands. It checks that each of them are "present". If any specified
6762** file is not present in the archive, an error is printed to stderr and an
6763** error code returned. Otherwise, if all specified arguments are present
6764** in the archive, SQLITE_OK is returned. Here, "present" means either an
6765** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6766** when pAr->bGlob is true.
6767**
6768** This function strips any trailing '/' characters from each argument.
6769** This is consistent with the way the [tar] command seems to work on
6770** Linux.
6771*/
6772static int arCheckEntries(ArCommand *pAr){
6773  int rc = SQLITE_OK;
6774  if( pAr->nArg ){
6775    int i, j;
6776    sqlite3_stmt *pTest = 0;
6777    const char *zSel = (pAr->bGlob)
6778      ? "SELECT name FROM %s WHERE glob($name,name)"
6779      : "SELECT name FROM %s WHERE name=$name";
6780
6781    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6782    j = sqlite3_bind_parameter_index(pTest, "$name");
6783    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6784      char *z = pAr->azArg[i];
6785      int n = strlen30(z);
6786      int bOk = 0;
6787      while( n>0 && z[n-1]=='/' ) n--;
6788      z[n] = '\0';
6789      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6790      if( SQLITE_ROW==sqlite3_step(pTest) ){
6791        bOk = 1;
6792      }
6793      shellReset(&rc, pTest);
6794      if( rc==SQLITE_OK && bOk==0 ){
6795        utf8_printf(stderr, "not found in archive: %s\n", z);
6796        rc = SQLITE_ERROR;
6797      }
6798    }
6799    shellFinalize(&rc, pTest);
6800  }
6801  return rc;
6802}
6803
6804/*
6805** Format a WHERE clause that can be used against the "sqlar" table to
6806** identify all archive members that match the command arguments held
6807** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6808** The caller is responsible for eventually calling sqlite3_free() on
6809** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6810** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6811*/
6812static void arWhereClause(
6813  int *pRc,
6814  ArCommand *pAr,
6815  char **pzWhere                  /* OUT: New WHERE clause */
6816){
6817  char *zWhere = 0;
6818  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6819  if( *pRc==SQLITE_OK ){
6820    if( pAr->nArg==0 ){
6821      zWhere = sqlite3_mprintf("1");
6822    }else{
6823      int i;
6824      const char *zSep = "";
6825      for(i=0; i<pAr->nArg; i++){
6826        const char *z = pAr->azArg[i];
6827        zWhere = sqlite3_mprintf(
6828          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6829          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6830        );
6831        if( zWhere==0 ){
6832          *pRc = SQLITE_NOMEM;
6833          break;
6834        }
6835        zSep = " OR ";
6836      }
6837    }
6838  }
6839  *pzWhere = zWhere;
6840}
6841
6842/*
6843** Implementation of .ar "lisT" command.
6844*/
6845static int arListCommand(ArCommand *pAr){
6846  const char *zSql = "SELECT %s FROM %s WHERE %s";
6847  const char *azCols[] = {
6848    "name",
6849    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6850  };
6851
6852  char *zWhere = 0;
6853  sqlite3_stmt *pSql = 0;
6854  int rc;
6855
6856  rc = arCheckEntries(pAr);
6857  arWhereClause(&rc, pAr, &zWhere);
6858
6859  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6860                     pAr->zSrcTable, zWhere);
6861  if( pAr->bDryRun ){
6862    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6863  }else{
6864    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6865      if( pAr->bVerbose ){
6866        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6867            sqlite3_column_text(pSql, 0),
6868            sqlite3_column_int(pSql, 1),
6869            sqlite3_column_text(pSql, 2),
6870            sqlite3_column_text(pSql, 3)
6871        );
6872      }else{
6873        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6874      }
6875    }
6876  }
6877  shellFinalize(&rc, pSql);
6878  sqlite3_free(zWhere);
6879  return rc;
6880}
6881
6882
6883/*
6884** Implementation of .ar "Remove" command.
6885*/
6886static int arRemoveCommand(ArCommand *pAr){
6887  int rc = 0;
6888  char *zSql = 0;
6889  char *zWhere = 0;
6890
6891  if( pAr->nArg ){
6892    /* Verify that args actually exist within the archive before proceeding.
6893    ** And formulate a WHERE clause to match them.  */
6894    rc = arCheckEntries(pAr);
6895    arWhereClause(&rc, pAr, &zWhere);
6896  }
6897  if( rc==SQLITE_OK ){
6898    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6899                           pAr->zSrcTable, zWhere);
6900    if( pAr->bDryRun ){
6901      utf8_printf(pAr->p->out, "%s\n", zSql);
6902    }else{
6903      char *zErr = 0;
6904      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6905      if( rc==SQLITE_OK ){
6906        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6907        if( rc!=SQLITE_OK ){
6908          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6909        }else{
6910          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6911        }
6912      }
6913      if( zErr ){
6914        utf8_printf(stdout, "ERROR: %s\n", zErr);
6915        sqlite3_free(zErr);
6916      }
6917    }
6918  }
6919  sqlite3_free(zWhere);
6920  sqlite3_free(zSql);
6921  return rc;
6922}
6923
6924/*
6925** Implementation of .ar "eXtract" command.
6926*/
6927static int arExtractCommand(ArCommand *pAr){
6928  const char *zSql1 =
6929    "SELECT "
6930    " ($dir || name),"
6931    " writefile(($dir || name), %s, mode, mtime) "
6932    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6933    " AND name NOT GLOB '*..[/\\]*'";
6934
6935  const char *azExtraArg[] = {
6936    "sqlar_uncompress(data, sz)",
6937    "data"
6938  };
6939
6940  sqlite3_stmt *pSql = 0;
6941  int rc = SQLITE_OK;
6942  char *zDir = 0;
6943  char *zWhere = 0;
6944  int i, j;
6945
6946  /* If arguments are specified, check that they actually exist within
6947  ** the archive before proceeding. And formulate a WHERE clause to
6948  ** match them.  */
6949  rc = arCheckEntries(pAr);
6950  arWhereClause(&rc, pAr, &zWhere);
6951
6952  if( rc==SQLITE_OK ){
6953    if( pAr->zDir ){
6954      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6955    }else{
6956      zDir = sqlite3_mprintf("");
6957    }
6958    if( zDir==0 ) rc = SQLITE_NOMEM;
6959  }
6960
6961  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6962      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6963  );
6964
6965  if( rc==SQLITE_OK ){
6966    j = sqlite3_bind_parameter_index(pSql, "$dir");
6967    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6968
6969    /* Run the SELECT statement twice. The first time, writefile() is called
6970    ** for all archive members that should be extracted. The second time,
6971    ** only for the directories. This is because the timestamps for
6972    ** extracted directories must be reset after they are populated (as
6973    ** populating them changes the timestamp).  */
6974    for(i=0; i<2; i++){
6975      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6976      sqlite3_bind_int(pSql, j, i);
6977      if( pAr->bDryRun ){
6978        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6979      }else{
6980        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6981          if( i==0 && pAr->bVerbose ){
6982            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6983          }
6984        }
6985      }
6986      shellReset(&rc, pSql);
6987    }
6988    shellFinalize(&rc, pSql);
6989  }
6990
6991  sqlite3_free(zDir);
6992  sqlite3_free(zWhere);
6993  return rc;
6994}
6995
6996/*
6997** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6998*/
6999static int arExecSql(ArCommand *pAr, const char *zSql){
7000  int rc;
7001  if( pAr->bDryRun ){
7002    utf8_printf(pAr->p->out, "%s\n", zSql);
7003    rc = SQLITE_OK;
7004  }else{
7005    char *zErr = 0;
7006    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7007    if( zErr ){
7008      utf8_printf(stdout, "ERROR: %s\n", zErr);
7009      sqlite3_free(zErr);
7010    }
7011  }
7012  return rc;
7013}
7014
7015
7016/*
7017** Implementation of .ar "create", "insert", and "update" commands.
7018**
7019**     create    ->     Create a new SQL archive
7020**     insert    ->     Insert or reinsert all files listed
7021**     update    ->     Insert files that have changed or that were not
7022**                      previously in the archive
7023**
7024** Create the "sqlar" table in the database if it does not already exist.
7025** Then add each file in the azFile[] array to the archive. Directories
7026** are added recursively. If argument bVerbose is non-zero, a message is
7027** printed on stdout for each file archived.
7028**
7029** The create command is the same as update, except that it drops
7030** any existing "sqlar" table before beginning.  The "insert" command
7031** always overwrites every file named on the command-line, where as
7032** "update" only overwrites if the size or mtime or mode has changed.
7033*/
7034static int arCreateOrUpdateCommand(
7035  ArCommand *pAr,                 /* Command arguments and options */
7036  int bUpdate,                    /* true for a --create. */
7037  int bOnlyIfChanged              /* Only update if file has changed */
7038){
7039  const char *zCreate =
7040      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7041      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7042      "  mode INT,               -- access permissions\n"
7043      "  mtime INT,              -- last modification time\n"
7044      "  sz INT,                 -- original file size\n"
7045      "  data BLOB               -- compressed content\n"
7046      ")";
7047  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7048  const char *zInsertFmt[2] = {
7049     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7050     "  SELECT\n"
7051     "    %s,\n"
7052     "    mode,\n"
7053     "    mtime,\n"
7054     "    CASE substr(lsmode(mode),1,1)\n"
7055     "      WHEN '-' THEN length(data)\n"
7056     "      WHEN 'd' THEN 0\n"
7057     "      ELSE -1 END,\n"
7058     "    sqlar_compress(data)\n"
7059     "  FROM fsdir(%Q,%Q) AS disk\n"
7060     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7061     ,
7062     "REPLACE INTO %s(name,mode,mtime,data)\n"
7063     "  SELECT\n"
7064     "    %s,\n"
7065     "    mode,\n"
7066     "    mtime,\n"
7067     "    data\n"
7068     "  FROM fsdir(%Q,%Q) AS disk\n"
7069     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7070  };
7071  int i;                          /* For iterating through azFile[] */
7072  int rc;                         /* Return code */
7073  const char *zTab = 0;           /* SQL table into which to insert */
7074  char *zSql;
7075  char zTemp[50];
7076  char *zExists = 0;
7077
7078  arExecSql(pAr, "PRAGMA page_size=512");
7079  rc = arExecSql(pAr, "SAVEPOINT ar;");
7080  if( rc!=SQLITE_OK ) return rc;
7081  zTemp[0] = 0;
7082  if( pAr->bZip ){
7083    /* Initialize the zipfile virtual table, if necessary */
7084    if( pAr->zFile ){
7085      sqlite3_uint64 r;
7086      sqlite3_randomness(sizeof(r),&r);
7087      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7088      zTab = zTemp;
7089      zSql = sqlite3_mprintf(
7090         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7091         zTab, pAr->zFile
7092      );
7093      rc = arExecSql(pAr, zSql);
7094      sqlite3_free(zSql);
7095    }else{
7096      zTab = "zip";
7097    }
7098  }else{
7099    /* Initialize the table for an SQLAR */
7100    zTab = "sqlar";
7101    if( bUpdate==0 ){
7102      rc = arExecSql(pAr, zDrop);
7103      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7104    }
7105    rc = arExecSql(pAr, zCreate);
7106  }
7107  if( bOnlyIfChanged ){
7108    zExists = sqlite3_mprintf(
7109      " AND NOT EXISTS("
7110          "SELECT 1 FROM %s AS mem"
7111          " WHERE mem.name=disk.name"
7112          " AND mem.mtime=disk.mtime"
7113          " AND mem.mode=disk.mode)", zTab);
7114  }else{
7115    zExists = sqlite3_mprintf("");
7116  }
7117  if( zExists==0 ) rc = SQLITE_NOMEM;
7118  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7119    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7120        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7121        pAr->azArg[i], pAr->zDir, zExists);
7122    rc = arExecSql(pAr, zSql2);
7123    sqlite3_free(zSql2);
7124  }
7125end_ar_transaction:
7126  if( rc!=SQLITE_OK ){
7127    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7128  }else{
7129    rc = arExecSql(pAr, "RELEASE ar;");
7130    if( pAr->bZip && pAr->zFile ){
7131      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7132      arExecSql(pAr, zSql);
7133      sqlite3_free(zSql);
7134    }
7135  }
7136  sqlite3_free(zExists);
7137  return rc;
7138}
7139
7140/*
7141** Implementation of ".ar" dot command.
7142*/
7143static int arDotCommand(
7144  ShellState *pState,          /* Current shell tool state */
7145  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7146  char **azArg,                /* Array of arguments passed to dot command */
7147  int nArg                     /* Number of entries in azArg[] */
7148){
7149  ArCommand cmd;
7150  int rc;
7151  memset(&cmd, 0, sizeof(cmd));
7152  cmd.fromCmdLine = fromCmdLine;
7153  rc = arParseCommand(azArg, nArg, &cmd);
7154  if( rc==SQLITE_OK ){
7155    int eDbType = SHELL_OPEN_UNSPEC;
7156    cmd.p = pState;
7157    cmd.db = pState->db;
7158    if( cmd.zFile ){
7159      eDbType = deduceDatabaseType(cmd.zFile, 1);
7160    }else{
7161      eDbType = pState->openMode;
7162    }
7163    if( eDbType==SHELL_OPEN_ZIPFILE ){
7164      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7165        if( cmd.zFile==0 ){
7166          cmd.zSrcTable = sqlite3_mprintf("zip");
7167        }else{
7168          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7169        }
7170      }
7171      cmd.bZip = 1;
7172    }else if( cmd.zFile ){
7173      int flags;
7174      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7175      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7176           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7177        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7178      }else{
7179        flags = SQLITE_OPEN_READONLY;
7180      }
7181      cmd.db = 0;
7182      if( cmd.bDryRun ){
7183        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7184             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7185      }
7186      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7187             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7188      if( rc!=SQLITE_OK ){
7189        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7190            cmd.zFile, sqlite3_errmsg(cmd.db)
7191        );
7192        goto end_ar_command;
7193      }
7194      sqlite3_fileio_init(cmd.db, 0, 0);
7195      sqlite3_sqlar_init(cmd.db, 0, 0);
7196      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7197                              shellPutsFunc, 0, 0);
7198
7199    }
7200    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7201      if( cmd.eCmd!=AR_CMD_CREATE
7202       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7203      ){
7204        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7205        rc = SQLITE_ERROR;
7206        goto end_ar_command;
7207      }
7208      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7209    }
7210
7211    switch( cmd.eCmd ){
7212      case AR_CMD_CREATE:
7213        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7214        break;
7215
7216      case AR_CMD_EXTRACT:
7217        rc = arExtractCommand(&cmd);
7218        break;
7219
7220      case AR_CMD_LIST:
7221        rc = arListCommand(&cmd);
7222        break;
7223
7224      case AR_CMD_HELP:
7225        arUsage(pState->out);
7226        break;
7227
7228      case AR_CMD_INSERT:
7229        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7230        break;
7231
7232      case AR_CMD_REMOVE:
7233        rc = arRemoveCommand(&cmd);
7234        break;
7235
7236      default:
7237        assert( cmd.eCmd==AR_CMD_UPDATE );
7238        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7239        break;
7240    }
7241  }
7242end_ar_command:
7243  if( cmd.db!=pState->db ){
7244    close_db(cmd.db);
7245  }
7246  sqlite3_free(cmd.zSrcTable);
7247
7248  return rc;
7249}
7250/* End of the ".archive" or ".ar" command logic
7251*******************************************************************************/
7252#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7253
7254#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7255/*
7256** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7257** Otherwise, the SQL statement or statements in zSql are executed using
7258** database connection db and the error code written to *pRc before
7259** this function returns.
7260*/
7261static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7262  int rc = *pRc;
7263  if( rc==SQLITE_OK ){
7264    char *zErr = 0;
7265    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7266    if( rc!=SQLITE_OK ){
7267      raw_printf(stderr, "SQL error: %s\n", zErr);
7268    }
7269    sqlite3_free(zErr);
7270    *pRc = rc;
7271  }
7272}
7273
7274/*
7275** Like shellExec(), except that zFmt is a printf() style format string.
7276*/
7277static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7278  char *z = 0;
7279  if( *pRc==SQLITE_OK ){
7280    va_list ap;
7281    va_start(ap, zFmt);
7282    z = sqlite3_vmprintf(zFmt, ap);
7283    va_end(ap);
7284    if( z==0 ){
7285      *pRc = SQLITE_NOMEM;
7286    }else{
7287      shellExec(db, pRc, z);
7288    }
7289    sqlite3_free(z);
7290  }
7291}
7292
7293/*
7294** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7295** Otherwise, an attempt is made to allocate, zero and return a pointer
7296** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7297** to SQLITE_NOMEM and NULL returned.
7298*/
7299static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7300  void *pRet = 0;
7301  if( *pRc==SQLITE_OK ){
7302    pRet = sqlite3_malloc64(nByte);
7303    if( pRet==0 ){
7304      *pRc = SQLITE_NOMEM;
7305    }else{
7306      memset(pRet, 0, nByte);
7307    }
7308  }
7309  return pRet;
7310}
7311
7312/*
7313** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7314** Otherwise, zFmt is treated as a printf() style string. The result of
7315** formatting it along with any trailing arguments is written into a
7316** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7317** It is the responsibility of the caller to eventually free this buffer
7318** using a call to sqlite3_free().
7319**
7320** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7321** pointer returned.
7322*/
7323static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7324  char *z = 0;
7325  if( *pRc==SQLITE_OK ){
7326    va_list ap;
7327    va_start(ap, zFmt);
7328    z = sqlite3_vmprintf(zFmt, ap);
7329    va_end(ap);
7330    if( z==0 ){
7331      *pRc = SQLITE_NOMEM;
7332    }
7333  }
7334  return z;
7335}
7336
7337
7338/*
7339** When running the ".recover" command, each output table, and the special
7340** orphaned row table if it is required, is represented by an instance
7341** of the following struct.
7342*/
7343typedef struct RecoverTable RecoverTable;
7344struct RecoverTable {
7345  char *zQuoted;                  /* Quoted version of table name */
7346  int nCol;                       /* Number of columns in table */
7347  char **azlCol;                  /* Array of column lists */
7348  int iPk;                        /* Index of IPK column */
7349};
7350
7351/*
7352** Free a RecoverTable object allocated by recoverFindTable() or
7353** recoverOrphanTable().
7354*/
7355static void recoverFreeTable(RecoverTable *pTab){
7356  if( pTab ){
7357    sqlite3_free(pTab->zQuoted);
7358    if( pTab->azlCol ){
7359      int i;
7360      for(i=0; i<=pTab->nCol; i++){
7361        sqlite3_free(pTab->azlCol[i]);
7362      }
7363      sqlite3_free(pTab->azlCol);
7364    }
7365    sqlite3_free(pTab);
7366  }
7367}
7368
7369/*
7370** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7371** Otherwise, it allocates and returns a RecoverTable object based on the
7372** final four arguments passed to this function. It is the responsibility
7373** of the caller to eventually free the returned object using
7374** recoverFreeTable().
7375*/
7376static RecoverTable *recoverNewTable(
7377  int *pRc,                       /* IN/OUT: Error code */
7378  const char *zName,              /* Name of table */
7379  const char *zSql,               /* CREATE TABLE statement */
7380  int bIntkey,
7381  int nCol
7382){
7383  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7384  int rc = *pRc;
7385  RecoverTable *pTab = 0;
7386
7387  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7388  if( rc==SQLITE_OK ){
7389    int nSqlCol = 0;
7390    int bSqlIntkey = 0;
7391    sqlite3_stmt *pStmt = 0;
7392
7393    rc = sqlite3_open("", &dbtmp);
7394    if( rc==SQLITE_OK ){
7395      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7396                              shellIdQuote, 0, 0);
7397    }
7398    if( rc==SQLITE_OK ){
7399      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7400    }
7401    if( rc==SQLITE_OK ){
7402      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7403      if( rc==SQLITE_ERROR ){
7404        rc = SQLITE_OK;
7405        goto finished;
7406      }
7407    }
7408    shellPreparePrintf(dbtmp, &rc, &pStmt,
7409        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7410    );
7411    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7412      nSqlCol = sqlite3_column_int(pStmt, 0);
7413    }
7414    shellFinalize(&rc, pStmt);
7415
7416    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7417      goto finished;
7418    }
7419
7420    shellPreparePrintf(dbtmp, &rc, &pStmt,
7421      "SELECT ("
7422      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7423      ") FROM sqlite_schema WHERE name = %Q", zName
7424    );
7425    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7426      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7427    }
7428    shellFinalize(&rc, pStmt);
7429
7430    if( bIntkey==bSqlIntkey ){
7431      int i;
7432      const char *zPk = "_rowid_";
7433      sqlite3_stmt *pPkFinder = 0;
7434
7435      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7436      ** set zPk to the name of the PK column, and pTab->iPk to the index
7437      ** of the column, where columns are 0-numbered from left to right.
7438      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7439      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7440      pTab->iPk = -2;
7441      if( bIntkey ){
7442        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7443          "SELECT cid, name FROM pragma_table_info(%Q) "
7444          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7445          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7446          , zName, zName
7447        );
7448        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7449          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7450          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7451          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7452        }
7453      }
7454
7455      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7456      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7457      pTab->nCol = nSqlCol;
7458
7459      if( bIntkey ){
7460        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7461      }else{
7462        pTab->azlCol[0] = shellMPrintf(&rc, "");
7463      }
7464      i = 1;
7465      shellPreparePrintf(dbtmp, &rc, &pStmt,
7466          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7467          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7468          "FROM pragma_table_info(%Q)",
7469          bIntkey ? ", " : "", pTab->iPk,
7470          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7471          zName
7472      );
7473      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7474        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7475        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7476        i++;
7477      }
7478      shellFinalize(&rc, pStmt);
7479
7480      shellFinalize(&rc, pPkFinder);
7481    }
7482  }
7483
7484 finished:
7485  sqlite3_close(dbtmp);
7486  *pRc = rc;
7487  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7488    recoverFreeTable(pTab);
7489    pTab = 0;
7490  }
7491  return pTab;
7492}
7493
7494/*
7495** This function is called to search the schema recovered from the
7496** sqlite_schema table of the (possibly) corrupt database as part
7497** of a ".recover" command. Specifically, for a table with root page
7498** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7499** table must be a WITHOUT ROWID table, or if non-zero, not one of
7500** those.
7501**
7502** If a table is found, a (RecoverTable*) object is returned. Or, if
7503** no such table is found, but bIntkey is false and iRoot is the
7504** root page of an index in the recovered schema, then (*pbNoop) is
7505** set to true and NULL returned. Or, if there is no such table or
7506** index, NULL is returned and (*pbNoop) set to 0, indicating that
7507** the caller should write data to the orphans table.
7508*/
7509static RecoverTable *recoverFindTable(
7510  ShellState *pState,             /* Shell state object */
7511  int *pRc,                       /* IN/OUT: Error code */
7512  int iRoot,                      /* Root page of table */
7513  int bIntkey,                    /* True for an intkey table */
7514  int nCol,                       /* Number of columns in table */
7515  int *pbNoop                     /* OUT: True if iRoot is root of index */
7516){
7517  sqlite3_stmt *pStmt = 0;
7518  RecoverTable *pRet = 0;
7519  int bNoop = 0;
7520  const char *zSql = 0;
7521  const char *zName = 0;
7522
7523  /* Search the recovered schema for an object with root page iRoot. */
7524  shellPreparePrintf(pState->db, pRc, &pStmt,
7525      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7526  );
7527  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7528    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7529    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7530      bNoop = 1;
7531      break;
7532    }
7533    if( sqlite3_stricmp(zType, "table")==0 ){
7534      zName = (const char*)sqlite3_column_text(pStmt, 1);
7535      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7536      if( zName!=0 && zSql!=0 ){
7537        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7538        break;
7539      }
7540    }
7541  }
7542
7543  shellFinalize(pRc, pStmt);
7544  *pbNoop = bNoop;
7545  return pRet;
7546}
7547
7548/*
7549** Return a RecoverTable object representing the orphans table.
7550*/
7551static RecoverTable *recoverOrphanTable(
7552  ShellState *pState,             /* Shell state object */
7553  int *pRc,                       /* IN/OUT: Error code */
7554  const char *zLostAndFound,      /* Base name for orphans table */
7555  int nCol                        /* Number of user data columns */
7556){
7557  RecoverTable *pTab = 0;
7558  if( nCol>=0 && *pRc==SQLITE_OK ){
7559    int i;
7560
7561    /* This block determines the name of the orphan table. The prefered
7562    ** name is zLostAndFound. But if that clashes with another name
7563    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7564    ** and so on until a non-clashing name is found.  */
7565    int iTab = 0;
7566    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7567    sqlite3_stmt *pTest = 0;
7568    shellPrepare(pState->db, pRc,
7569        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7570    );
7571    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7572    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7573      shellReset(pRc, pTest);
7574      sqlite3_free(zTab);
7575      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7576      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7577    }
7578    shellFinalize(pRc, pTest);
7579
7580    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7581    if( pTab ){
7582      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7583      pTab->nCol = nCol;
7584      pTab->iPk = -2;
7585      if( nCol>0 ){
7586        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7587        if( pTab->azlCol ){
7588          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7589          for(i=nCol-1; i>=0; i--){
7590            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7591          }
7592        }
7593      }
7594
7595      if( *pRc!=SQLITE_OK ){
7596        recoverFreeTable(pTab);
7597        pTab = 0;
7598      }else{
7599        raw_printf(pState->out,
7600            "CREATE TABLE %s(rootpgno INTEGER, "
7601            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7602        );
7603        for(i=0; i<nCol; i++){
7604          raw_printf(pState->out, ", c%d", i);
7605        }
7606        raw_printf(pState->out, ");\n");
7607      }
7608    }
7609    sqlite3_free(zTab);
7610  }
7611  return pTab;
7612}
7613
7614/*
7615** This function is called to recover data from the database. A script
7616** to construct a new database containing all recovered data is output
7617** on stream pState->out.
7618*/
7619static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7620  int rc = SQLITE_OK;
7621  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7622  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7623  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7624  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7625  const char *zLostAndFound = "lost_and_found";
7626  int i;
7627  int nOrphan = -1;
7628  RecoverTable *pOrphan = 0;
7629
7630  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7631  int bRowids = 1;                /* 0 if --no-rowids */
7632  for(i=1; i<nArg; i++){
7633    char *z = azArg[i];
7634    int n;
7635    if( z[0]=='-' && z[1]=='-' ) z++;
7636    n = strlen30(z);
7637    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7638      bFreelist = 0;
7639    }else
7640    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7641      i++;
7642      zRecoveryDb = azArg[i];
7643    }else
7644    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7645      i++;
7646      zLostAndFound = azArg[i];
7647    }else
7648    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7649      bRowids = 0;
7650    }
7651    else{
7652      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7653      showHelp(pState->out, azArg[0]);
7654      return 1;
7655    }
7656  }
7657
7658  shellExecPrintf(pState->db, &rc,
7659    /* Attach an in-memory database named 'recovery'. Create an indexed
7660    ** cache of the sqlite_dbptr virtual table. */
7661    "PRAGMA writable_schema = on;"
7662    "ATTACH %Q AS recovery;"
7663    "DROP TABLE IF EXISTS recovery.dbptr;"
7664    "DROP TABLE IF EXISTS recovery.freelist;"
7665    "DROP TABLE IF EXISTS recovery.map;"
7666    "DROP TABLE IF EXISTS recovery.schema;"
7667    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7668  );
7669
7670  if( bFreelist ){
7671    shellExec(pState->db, &rc,
7672      "WITH trunk(pgno) AS ("
7673      "  SELECT shell_int32("
7674      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7675      "      WHERE x>0"
7676      "    UNION"
7677      "  SELECT shell_int32("
7678      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7679      "      FROM trunk WHERE x>0"
7680      "),"
7681      "freelist(data, n, freepgno) AS ("
7682      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7683      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7684      "    UNION ALL"
7685      "  SELECT data, n-1, shell_int32(data, 2+n) "
7686      "      FROM freelist WHERE n>=0"
7687      ")"
7688      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7689    );
7690  }
7691
7692  /* If this is an auto-vacuum database, add all pointer-map pages to
7693  ** the freelist table. Do this regardless of whether or not
7694  ** --freelist-corrupt was specified.  */
7695  shellExec(pState->db, &rc,
7696    "WITH ptrmap(pgno) AS ("
7697    "  SELECT 2 WHERE shell_int32("
7698    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7699    "  )"
7700    "    UNION ALL "
7701    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7702    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7703    ")"
7704    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7705  );
7706
7707  shellExec(pState->db, &rc,
7708    "CREATE TABLE recovery.dbptr("
7709    "      pgno, child, PRIMARY KEY(child, pgno)"
7710    ") WITHOUT ROWID;"
7711    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7712    "    SELECT * FROM sqlite_dbptr"
7713    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7714
7715    /* Delete any pointer to page 1. This ensures that page 1 is considered
7716    ** a root page, regardless of how corrupt the db is. */
7717    "DELETE FROM recovery.dbptr WHERE child = 1;"
7718
7719    /* Delete all pointers to any pages that have more than one pointer
7720    ** to them. Such pages will be treated as root pages when recovering
7721    ** data.  */
7722    "DELETE FROM recovery.dbptr WHERE child IN ("
7723    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7724    ");"
7725
7726    /* Create the "map" table that will (eventually) contain instructions
7727    ** for dealing with each page in the db that contains one or more
7728    ** records. */
7729    "CREATE TABLE recovery.map("
7730      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7731    ");"
7732
7733    /* Populate table [map]. If there are circular loops of pages in the
7734    ** database, the following adds all pages in such a loop to the map
7735    ** as individual root pages. This could be handled better.  */
7736    "WITH pages(i, maxlen) AS ("
7737    "  SELECT page_count, ("
7738    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7739    "  ) FROM pragma_page_count WHERE page_count>0"
7740    "    UNION ALL"
7741    "  SELECT i-1, ("
7742    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7743    "  ) FROM pages WHERE i>=2"
7744    ")"
7745    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7746    "  SELECT i, maxlen, NULL, ("
7747    "    WITH p(orig, pgno, parent) AS ("
7748    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7749    "        UNION "
7750    "      SELECT i, p.parent, "
7751    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7752    "    )"
7753    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7754    ") "
7755    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7756    "UPDATE recovery.map AS o SET intkey = ("
7757    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7758    ");"
7759
7760    /* Extract data from page 1 and any linked pages into table
7761    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7762    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7763    "INSERT INTO recovery.schema SELECT "
7764    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7765    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7766    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7767    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7768    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7769    "FROM sqlite_dbdata WHERE pgno IN ("
7770    "  SELECT pgno FROM recovery.map WHERE root=1"
7771    ")"
7772    "GROUP BY pgno, cell;"
7773    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7774  );
7775
7776  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7777  ** CREATE TABLE statements that extracted from the existing schema.  */
7778  if( rc==SQLITE_OK ){
7779    sqlite3_stmt *pStmt = 0;
7780    /* ".recover" might output content in an order which causes immediate
7781    ** foreign key constraints to be violated. So disable foreign-key
7782    ** constraint enforcement to prevent problems when running the output
7783    ** script. */
7784    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7785    raw_printf(pState->out, "BEGIN;\n");
7786    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7787    shellPrepare(pState->db, &rc,
7788        "SELECT sql FROM recovery.schema "
7789        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7790    );
7791    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7792      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7793      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7794          &zCreateTable[12]
7795      );
7796    }
7797    shellFinalize(&rc, pStmt);
7798  }
7799
7800  /* Figure out if an orphan table will be required. And if so, how many
7801  ** user columns it should contain */
7802  shellPrepare(pState->db, &rc,
7803      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7804      , &pLoop
7805  );
7806  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7807    nOrphan = sqlite3_column_int(pLoop, 0);
7808  }
7809  shellFinalize(&rc, pLoop);
7810  pLoop = 0;
7811
7812  shellPrepare(pState->db, &rc,
7813      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7814  );
7815
7816  shellPrepare(pState->db, &rc,
7817      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7818      "(case when (? AND field<0) then NULL else value end)"
7819      "), ', ')"
7820      ", min(field) "
7821      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7822      "GROUP BY cell", &pCells
7823  );
7824
7825  /* Loop through each root page. */
7826  shellPrepare(pState->db, &rc,
7827      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7828      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7829      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7830      ")", &pLoop
7831  );
7832  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7833    int iRoot = sqlite3_column_int(pLoop, 0);
7834    int bIntkey = sqlite3_column_int(pLoop, 1);
7835    int nCol = sqlite3_column_int(pLoop, 2);
7836    int bNoop = 0;
7837    RecoverTable *pTab;
7838
7839    assert( bIntkey==0 || bIntkey==1 );
7840    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7841    if( bNoop || rc ) continue;
7842    if( pTab==0 ){
7843      if( pOrphan==0 ){
7844        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7845      }
7846      pTab = pOrphan;
7847      if( pTab==0 ) break;
7848    }
7849
7850    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7851      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7852    }
7853    sqlite3_bind_int(pPages, 1, iRoot);
7854    if( bRowids==0 && pTab->iPk<0 ){
7855      sqlite3_bind_int(pCells, 1, 1);
7856    }else{
7857      sqlite3_bind_int(pCells, 1, 0);
7858    }
7859    sqlite3_bind_int(pCells, 3, pTab->iPk);
7860
7861    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7862      int iPgno = sqlite3_column_int(pPages, 0);
7863      sqlite3_bind_int(pCells, 2, iPgno);
7864      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7865        int nField = sqlite3_column_int(pCells, 0);
7866        int iMin = sqlite3_column_int(pCells, 2);
7867        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7868
7869        RecoverTable *pTab2 = pTab;
7870        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7871          if( pOrphan==0 ){
7872            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7873          }
7874          pTab2 = pOrphan;
7875          if( pTab2==0 ) break;
7876        }
7877
7878        nField = nField+1;
7879        if( pTab2==pOrphan ){
7880          raw_printf(pState->out,
7881              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7882              pTab2->zQuoted, iRoot, iPgno, nField,
7883              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7884          );
7885        }else{
7886          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7887              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7888          );
7889        }
7890      }
7891      shellReset(&rc, pCells);
7892    }
7893    shellReset(&rc, pPages);
7894    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7895  }
7896  shellFinalize(&rc, pLoop);
7897  shellFinalize(&rc, pPages);
7898  shellFinalize(&rc, pCells);
7899  recoverFreeTable(pOrphan);
7900
7901  /* The rest of the schema */
7902  if( rc==SQLITE_OK ){
7903    sqlite3_stmt *pStmt = 0;
7904    shellPrepare(pState->db, &rc,
7905        "SELECT sql, name FROM recovery.schema "
7906        "WHERE sql NOT LIKE 'create table%'", &pStmt
7907    );
7908    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7909      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7910      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7911        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7912        char *zPrint = shellMPrintf(&rc,
7913          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7914          zName, zName, zSql
7915        );
7916        raw_printf(pState->out, "%s;\n", zPrint);
7917        sqlite3_free(zPrint);
7918      }else{
7919        raw_printf(pState->out, "%s;\n", zSql);
7920      }
7921    }
7922    shellFinalize(&rc, pStmt);
7923  }
7924
7925  if( rc==SQLITE_OK ){
7926    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7927    raw_printf(pState->out, "COMMIT;\n");
7928  }
7929  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7930  return rc;
7931}
7932#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7933
7934
7935/*
7936 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7937 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7938 *   close db and set it to 0, and return the columns spec, to later
7939 *   be sqlite3_free()'ed by the caller.
7940 * The return is 0 when either:
7941 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7942 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7943 * The 3rd argument, pRenamed, references an out parameter. If the
7944 * pointer is non-zero, its referent will be set to a summary of renames
7945 * done if renaming was necessary, or set to 0 if none was done. The out
7946 * string (if any) must be sqlite3_free()'ed by the caller.
7947 */
7948#ifdef SHELL_DEBUG
7949#define rc_err_oom_die(rc) \
7950  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7951  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7952    fprintf(stderr,"E:%d\n",rc), assert(0)
7953#else
7954static void rc_err_oom_die(int rc){
7955  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7956  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7957}
7958#endif
7959
7960#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7961static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7962#else  /* Otherwise, memory is faster/better for the transient DB. */
7963static const char *zCOL_DB = ":memory:";
7964#endif
7965
7966/* Define character (as C string) to separate generated column ordinal
7967 * from protected part of incoming column names. This defaults to "_"
7968 * so that incoming column identifiers that did not need not be quoted
7969 * remain usable without being quoted. It must be one character.
7970 */
7971#ifndef SHELL_AUTOCOLUMN_SEP
7972# define AUTOCOLUMN_SEP "_"
7973#else
7974# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7975#endif
7976
7977static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7978  /* Queries and D{D,M}L used here */
7979  static const char * const zTabMake = "\
7980CREATE TABLE ColNames(\
7981 cpos INTEGER PRIMARY KEY,\
7982 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7983CREATE VIEW RepeatedNames AS \
7984SELECT DISTINCT t.name FROM ColNames t \
7985WHERE t.name COLLATE NOCASE IN (\
7986 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7987);\
7988";
7989  static const char * const zTabFill = "\
7990INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7991 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7992";
7993  static const char * const zHasDupes = "\
7994SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7995 <count(name) FROM ColNames\
7996";
7997#ifdef SHELL_COLUMN_RENAME_CLEAN
7998  static const char * const zDedoctor = "\
7999UPDATE ColNames SET chop=iif(\
8000  (substring(name,nlen,1) BETWEEN '0' AND '9')\
8001  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
8002 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
8003 0\
8004)\
8005";
8006#endif
8007  static const char * const zSetReps = "\
8008UPDATE ColNames AS t SET reps=\
8009(SELECT count(*) FROM ColNames d \
8010 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
8011 COLLATE NOCASE\
8012)\
8013";
8014#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
8015  static const char * const zColDigits = "\
8016SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
8017";
8018#else
8019  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
8020  static const char * const zColDigits = "\
8021SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
8022 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
8023 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
8024";
8025#endif
8026  static const char * const zRenameRank =
8027#ifdef SHELL_COLUMN_RENAME_CLEAN
8028    "UPDATE ColNames AS t SET suff="
8029    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
8030#else /* ...RENAME_MINIMAL_ONE_PASS */
8031"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
8032"  SELECT 0 AS nlz"
8033"  UNION"
8034"  SELECT nlz+1 AS nlz FROM Lzn"
8035"  WHERE EXISTS("
8036"   SELECT 1"
8037"   FROM ColNames t, ColNames o"
8038"   WHERE"
8039"    iif(t.name IN (SELECT * FROM RepeatedNames),"
8040"     printf('%s"AUTOCOLUMN_SEP"%s',"
8041"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8042"     t.name"
8043"    )"
8044"    ="
8045"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8046"     printf('%s"AUTOCOLUMN_SEP"%s',"
8047"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8048"     o.name"
8049"    )"
8050"    COLLATE NOCASE"
8051"    AND o.cpos<>t.cpos"
8052"   GROUP BY t.cpos"
8053"  )"
8054") UPDATE Colnames AS t SET"
8055" chop = 0," /* No chopping, never touch incoming names. */
8056" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8057"  printf('"AUTOCOLUMN_SEP"%s', substring("
8058"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8059"  ''"
8060" )"
8061#endif
8062    ;
8063  static const char * const zCollectVar = "\
8064SELECT\
8065 '('||x'0a'\
8066 || group_concat(\
8067  cname||' TEXT',\
8068  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8069 ||')' AS ColsSpec \
8070FROM (\
8071 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8072 FROM ColNames ORDER BY cpos\
8073)";
8074  static const char * const zRenamesDone =
8075    "SELECT group_concat("
8076    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8077    " ','||x'0a')"
8078    "FROM ColNames WHERE suff<>'' OR chop!=0"
8079    ;
8080  int rc;
8081  sqlite3_stmt *pStmt = 0;
8082  assert(pDb!=0);
8083  if( zColNew ){
8084    /* Add initial or additional column. Init db if necessary. */
8085    if( *pDb==0 ){
8086      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8087#ifdef SHELL_COLFIX_DB
8088      if(*zCOL_DB!=':')
8089        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8090                     "drop view if exists RepeatedNames;",0,0,0);
8091#endif
8092      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8093      rc_err_oom_die(rc);
8094    }
8095    assert(*pDb!=0);
8096    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8097    rc_err_oom_die(rc);
8098    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8099    rc_err_oom_die(rc);
8100    rc = sqlite3_step(pStmt);
8101    rc_err_oom_die(rc);
8102    sqlite3_finalize(pStmt);
8103    return 0;
8104  }else if( *pDb==0 ){
8105    return 0;
8106  }else{
8107    /* Formulate the columns spec, close the DB, zero *pDb. */
8108    char *zColsSpec = 0;
8109    int hasDupes = db_int(*pDb, zHasDupes);
8110    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8111    if( hasDupes ){
8112#ifdef SHELL_COLUMN_RENAME_CLEAN
8113      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8114      rc_err_oom_die(rc);
8115#endif
8116      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8117      rc_err_oom_die(rc);
8118      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8119      rc_err_oom_die(rc);
8120      sqlite3_bind_int(pStmt, 1, nDigits);
8121      rc = sqlite3_step(pStmt);
8122      sqlite3_finalize(pStmt);
8123      assert(rc==SQLITE_DONE);
8124    }
8125    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8126    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8127    rc_err_oom_die(rc);
8128    rc = sqlite3_step(pStmt);
8129    if( rc==SQLITE_ROW ){
8130      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8131    }else{
8132      zColsSpec = 0;
8133    }
8134    if( pzRenamed!=0 ){
8135      if( !hasDupes ) *pzRenamed = 0;
8136      else{
8137        sqlite3_finalize(pStmt);
8138        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8139            && SQLITE_ROW==sqlite3_step(pStmt) ){
8140          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8141        }else
8142          *pzRenamed = 0;
8143      }
8144    }
8145    sqlite3_finalize(pStmt);
8146    sqlite3_close(*pDb);
8147    *pDb = 0;
8148    return zColsSpec;
8149  }
8150}
8151
8152/*
8153** If an input line begins with "." then invoke this routine to
8154** process that line.
8155**
8156** Return 1 on error, 2 to exit, and 0 otherwise.
8157*/
8158static int do_meta_command(char *zLine, ShellState *p){
8159  int h = 1;
8160  int nArg = 0;
8161  int n, c;
8162  int rc = 0;
8163  char *azArg[52];
8164
8165#ifndef SQLITE_OMIT_VIRTUALTABLE
8166  if( p->expert.pExpert ){
8167    expertFinish(p, 1, 0);
8168  }
8169#endif
8170
8171  /* Parse the input line into tokens.
8172  */
8173  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8174    while( IsSpace(zLine[h]) ){ h++; }
8175    if( zLine[h]==0 ) break;
8176    if( zLine[h]=='\'' || zLine[h]=='"' ){
8177      int delim = zLine[h++];
8178      azArg[nArg++] = &zLine[h];
8179      while( zLine[h] && zLine[h]!=delim ){
8180        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8181        h++;
8182      }
8183      if( zLine[h]==delim ){
8184        zLine[h++] = 0;
8185      }
8186      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8187    }else{
8188      azArg[nArg++] = &zLine[h];
8189      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8190      if( zLine[h] ) zLine[h++] = 0;
8191      resolve_backslashes(azArg[nArg-1]);
8192    }
8193  }
8194  azArg[nArg] = 0;
8195
8196  /* Process the input line.
8197  */
8198  if( nArg==0 ) return 0; /* no tokens, no error */
8199  n = strlen30(azArg[0]);
8200  c = azArg[0][0];
8201  clearTempFile(p);
8202
8203#ifndef SQLITE_OMIT_AUTHORIZATION
8204  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8205    if( nArg!=2 ){
8206      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8207      rc = 1;
8208      goto meta_command_exit;
8209    }
8210    open_db(p, 0);
8211    if( booleanValue(azArg[1]) ){
8212      sqlite3_set_authorizer(p->db, shellAuth, p);
8213    }else if( p->bSafeModePersist ){
8214      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8215    }else{
8216      sqlite3_set_authorizer(p->db, 0, 0);
8217    }
8218  }else
8219#endif
8220
8221#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8222  && !defined(SQLITE_SHELL_FIDDLE)
8223  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8224    open_db(p, 0);
8225    failIfSafeMode(p, "cannot run .archive in safe mode");
8226    rc = arDotCommand(p, 0, azArg, nArg);
8227  }else
8228#endif
8229
8230#ifndef SQLITE_SHELL_FIDDLE
8231  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8232   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8233  ){
8234    const char *zDestFile = 0;
8235    const char *zDb = 0;
8236    sqlite3 *pDest;
8237    sqlite3_backup *pBackup;
8238    int j;
8239    int bAsync = 0;
8240    const char *zVfs = 0;
8241    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8242    for(j=1; j<nArg; j++){
8243      const char *z = azArg[j];
8244      if( z[0]=='-' ){
8245        if( z[1]=='-' ) z++;
8246        if( strcmp(z, "-append")==0 ){
8247          zVfs = "apndvfs";
8248        }else
8249        if( strcmp(z, "-async")==0 ){
8250          bAsync = 1;
8251        }else
8252        {
8253          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8254          return 1;
8255        }
8256      }else if( zDestFile==0 ){
8257        zDestFile = azArg[j];
8258      }else if( zDb==0 ){
8259        zDb = zDestFile;
8260        zDestFile = azArg[j];
8261      }else{
8262        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8263        return 1;
8264      }
8265    }
8266    if( zDestFile==0 ){
8267      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8268      return 1;
8269    }
8270    if( zDb==0 ) zDb = "main";
8271    rc = sqlite3_open_v2(zDestFile, &pDest,
8272                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8273    if( rc!=SQLITE_OK ){
8274      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8275      close_db(pDest);
8276      return 1;
8277    }
8278    if( bAsync ){
8279      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8280                   0, 0, 0);
8281    }
8282    open_db(p, 0);
8283    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8284    if( pBackup==0 ){
8285      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8286      close_db(pDest);
8287      return 1;
8288    }
8289    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8290    sqlite3_backup_finish(pBackup);
8291    if( rc==SQLITE_DONE ){
8292      rc = 0;
8293    }else{
8294      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8295      rc = 1;
8296    }
8297    close_db(pDest);
8298  }else
8299#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8300
8301  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8302    if( nArg==2 ){
8303      bail_on_error = booleanValue(azArg[1]);
8304    }else{
8305      raw_printf(stderr, "Usage: .bail on|off\n");
8306      rc = 1;
8307    }
8308  }else
8309
8310  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8311    if( nArg==2 ){
8312      if( booleanValue(azArg[1]) ){
8313        setBinaryMode(p->out, 1);
8314      }else{
8315        setTextMode(p->out, 1);
8316      }
8317    }else{
8318      raw_printf(stderr, "Usage: .binary on|off\n");
8319      rc = 1;
8320    }
8321  }else
8322
8323  /* The undocumented ".breakpoint" command causes a call to the no-op
8324  ** routine named test_breakpoint().
8325  */
8326  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8327    test_breakpoint();
8328  }else
8329
8330#ifndef SQLITE_SHELL_FIDDLE
8331  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8332    failIfSafeMode(p, "cannot run .cd in safe mode");
8333    if( nArg==2 ){
8334#if defined(_WIN32) || defined(WIN32)
8335      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8336      rc = !SetCurrentDirectoryW(z);
8337      sqlite3_free(z);
8338#else
8339      rc = chdir(azArg[1]);
8340#endif
8341      if( rc ){
8342        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8343        rc = 1;
8344      }
8345    }else{
8346      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8347      rc = 1;
8348    }
8349  }else
8350#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8351
8352  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8353    if( nArg==2 ){
8354      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8355    }else{
8356      raw_printf(stderr, "Usage: .changes on|off\n");
8357      rc = 1;
8358    }
8359  }else
8360
8361#ifndef SQLITE_SHELL_FIDDLE
8362  /* Cancel output redirection, if it is currently set (by .testcase)
8363  ** Then read the content of the testcase-out.txt file and compare against
8364  ** azArg[1].  If there are differences, report an error and exit.
8365  */
8366  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8367    char *zRes = 0;
8368    output_reset(p);
8369    if( nArg!=2 ){
8370      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8371      rc = 2;
8372    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8373      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8374      rc = 2;
8375    }else if( testcase_glob(azArg[1],zRes)==0 ){
8376      utf8_printf(stderr,
8377                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8378                 p->zTestcase, azArg[1], zRes);
8379      rc = 1;
8380    }else{
8381      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8382      p->nCheck++;
8383    }
8384    sqlite3_free(zRes);
8385  }else
8386#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8387
8388#ifndef SQLITE_SHELL_FIDDLE
8389  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8390    failIfSafeMode(p, "cannot run .clone in safe mode");
8391    if( nArg==2 ){
8392      tryToClone(p, azArg[1]);
8393    }else{
8394      raw_printf(stderr, "Usage: .clone FILENAME\n");
8395      rc = 1;
8396    }
8397  }else
8398#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8399
8400  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8401    if( nArg==1 ){
8402      /* List available connections */
8403      int i;
8404      for(i=0; i<ArraySize(p->aAuxDb); i++){
8405        const char *zFile = p->aAuxDb[i].zDbFilename;
8406        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8407          zFile = "(not open)";
8408        }else if( zFile==0 ){
8409          zFile = "(memory)";
8410        }else if( zFile[0]==0 ){
8411          zFile = "(temporary-file)";
8412        }
8413        if( p->pAuxDb == &p->aAuxDb[i] ){
8414          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8415        }else if( p->aAuxDb[i].db!=0 ){
8416          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8417        }
8418      }
8419    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8420      int i = azArg[1][0] - '0';
8421      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8422        p->pAuxDb->db = p->db;
8423        p->pAuxDb = &p->aAuxDb[i];
8424        globalDb = p->db = p->pAuxDb->db;
8425        p->pAuxDb->db = 0;
8426      }
8427    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8428           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8429      int i = azArg[2][0] - '0';
8430      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8431        /* No-op */
8432      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8433        raw_printf(stderr, "cannot close the active database connection\n");
8434        rc = 1;
8435      }else if( p->aAuxDb[i].db ){
8436        session_close_all(p, i);
8437        close_db(p->aAuxDb[i].db);
8438        p->aAuxDb[i].db = 0;
8439      }
8440    }else{
8441      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8442      rc = 1;
8443    }
8444  }else
8445
8446  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8447    char **azName = 0;
8448    int nName = 0;
8449    sqlite3_stmt *pStmt;
8450    int i;
8451    open_db(p, 0);
8452    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8453    if( rc ){
8454      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8455      rc = 1;
8456    }else{
8457      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8458        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8459        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8460        if( zSchema==0 || zFile==0 ) continue;
8461        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8462        shell_check_oom(azName);
8463        azName[nName*2] = strdup(zSchema);
8464        azName[nName*2+1] = strdup(zFile);
8465        nName++;
8466      }
8467    }
8468    sqlite3_finalize(pStmt);
8469    for(i=0; i<nName; i++){
8470      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8471      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8472      const char *z = azName[i*2+1];
8473      utf8_printf(p->out, "%s: %s %s%s\n",
8474         azName[i*2],
8475         z && z[0] ? z : "\"\"",
8476         bRdonly ? "r/o" : "r/w",
8477         eTxn==SQLITE_TXN_NONE ? "" :
8478            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8479      free(azName[i*2]);
8480      free(azName[i*2+1]);
8481    }
8482    sqlite3_free(azName);
8483  }else
8484
8485  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8486    static const struct DbConfigChoices {
8487      const char *zName;
8488      int op;
8489    } aDbConfig[] = {
8490        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8491        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8492        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8493        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8494        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8495        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8496        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8497        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8498        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8499        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8500        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8501        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8502        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8503        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8504        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8505        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8506    };
8507    int ii, v;
8508    open_db(p, 0);
8509    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8510      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8511      if( nArg>=3 ){
8512        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8513      }
8514      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8515      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8516      if( nArg>1 ) break;
8517    }
8518    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8519      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8520      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8521    }
8522  }else
8523
8524#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8525  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8526    rc = shell_dbinfo_command(p, nArg, azArg);
8527  }else
8528
8529  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8530    open_db(p, 0);
8531    rc = recoverDatabaseCmd(p, nArg, azArg);
8532  }else
8533#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8534
8535  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8536    char *zLike = 0;
8537    char *zSql;
8538    int i;
8539    int savedShowHeader = p->showHeader;
8540    int savedShellFlags = p->shellFlgs;
8541    ShellClearFlag(p,
8542       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8543       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8544    for(i=1; i<nArg; i++){
8545      if( azArg[i][0]=='-' ){
8546        const char *z = azArg[i]+1;
8547        if( z[0]=='-' ) z++;
8548        if( strcmp(z,"preserve-rowids")==0 ){
8549#ifdef SQLITE_OMIT_VIRTUALTABLE
8550          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8551                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8552          rc = 1;
8553          sqlite3_free(zLike);
8554          goto meta_command_exit;
8555#else
8556          ShellSetFlag(p, SHFLG_PreserveRowid);
8557#endif
8558        }else
8559        if( strcmp(z,"newlines")==0 ){
8560          ShellSetFlag(p, SHFLG_Newlines);
8561        }else
8562        if( strcmp(z,"data-only")==0 ){
8563          ShellSetFlag(p, SHFLG_DumpDataOnly);
8564        }else
8565        if( strcmp(z,"nosys")==0 ){
8566          ShellSetFlag(p, SHFLG_DumpNoSys);
8567        }else
8568        {
8569          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8570          rc = 1;
8571          sqlite3_free(zLike);
8572          goto meta_command_exit;
8573        }
8574      }else{
8575        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8576        ** only dump data for tables for which either the table name matches
8577        ** the LIKE pattern, or the table appears to be a shadow table of
8578        ** a virtual table for which the name matches the LIKE pattern.
8579        */
8580        char *zExpr = sqlite3_mprintf(
8581            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8582            "  SELECT 1 FROM sqlite_schema WHERE "
8583            "    name LIKE %Q ESCAPE '\\' AND"
8584            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8585            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8586            ")", azArg[i], azArg[i]
8587        );
8588
8589        if( zLike ){
8590          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8591        }else{
8592          zLike = zExpr;
8593        }
8594      }
8595    }
8596
8597    open_db(p, 0);
8598
8599    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8600      /* When playing back a "dump", the content might appear in an order
8601      ** which causes immediate foreign key constraints to be violated.
8602      ** So disable foreign-key constraint enforcement to prevent problems. */
8603      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8604      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8605    }
8606    p->writableSchema = 0;
8607    p->showHeader = 0;
8608    /* Set writable_schema=ON since doing so forces SQLite to initialize
8609    ** as much of the schema as it can even if the sqlite_schema table is
8610    ** corrupt. */
8611    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8612    p->nErr = 0;
8613    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8614    zSql = sqlite3_mprintf(
8615      "SELECT name, type, sql FROM sqlite_schema AS o "
8616      "WHERE (%s) AND type=='table'"
8617      "  AND sql NOT NULL"
8618      " ORDER BY tbl_name='sqlite_sequence', rowid",
8619      zLike
8620    );
8621    run_schema_dump_query(p,zSql);
8622    sqlite3_free(zSql);
8623    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8624      zSql = sqlite3_mprintf(
8625        "SELECT sql FROM sqlite_schema AS o "
8626        "WHERE (%s) AND sql NOT NULL"
8627        "  AND type IN ('index','trigger','view')",
8628        zLike
8629      );
8630      run_table_dump_query(p, zSql);
8631      sqlite3_free(zSql);
8632    }
8633    sqlite3_free(zLike);
8634    if( p->writableSchema ){
8635      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8636      p->writableSchema = 0;
8637    }
8638    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8639    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8640    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8641      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8642    }
8643    p->showHeader = savedShowHeader;
8644    p->shellFlgs = savedShellFlags;
8645  }else
8646
8647  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8648    if( nArg==2 ){
8649      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8650    }else{
8651      raw_printf(stderr, "Usage: .echo on|off\n");
8652      rc = 1;
8653    }
8654  }else
8655
8656  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8657    if( nArg==2 ){
8658      p->autoEQPtest = 0;
8659      if( p->autoEQPtrace ){
8660        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8661        p->autoEQPtrace = 0;
8662      }
8663      if( strcmp(azArg[1],"full")==0 ){
8664        p->autoEQP = AUTOEQP_full;
8665      }else if( strcmp(azArg[1],"trigger")==0 ){
8666        p->autoEQP = AUTOEQP_trigger;
8667#ifdef SQLITE_DEBUG
8668      }else if( strcmp(azArg[1],"test")==0 ){
8669        p->autoEQP = AUTOEQP_on;
8670        p->autoEQPtest = 1;
8671      }else if( strcmp(azArg[1],"trace")==0 ){
8672        p->autoEQP = AUTOEQP_full;
8673        p->autoEQPtrace = 1;
8674        open_db(p, 0);
8675        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8676        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8677#endif
8678      }else{
8679        p->autoEQP = (u8)booleanValue(azArg[1]);
8680      }
8681    }else{
8682      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8683      rc = 1;
8684    }
8685  }else
8686
8687#ifndef SQLITE_SHELL_FIDDLE
8688  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8689    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8690    rc = 2;
8691  }else
8692#endif
8693
8694  /* The ".explain" command is automatic now.  It is largely pointless.  It
8695  ** retained purely for backwards compatibility */
8696  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8697    int val = 1;
8698    if( nArg>=2 ){
8699      if( strcmp(azArg[1],"auto")==0 ){
8700        val = 99;
8701      }else{
8702        val =  booleanValue(azArg[1]);
8703      }
8704    }
8705    if( val==1 && p->mode!=MODE_Explain ){
8706      p->normalMode = p->mode;
8707      p->mode = MODE_Explain;
8708      p->autoExplain = 0;
8709    }else if( val==0 ){
8710      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8711      p->autoExplain = 0;
8712    }else if( val==99 ){
8713      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8714      p->autoExplain = 1;
8715    }
8716  }else
8717
8718#ifndef SQLITE_OMIT_VIRTUALTABLE
8719  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8720    if( p->bSafeMode ){
8721      raw_printf(stderr,
8722        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8723        azArg[0]);
8724      rc = 1;
8725    }else{
8726      open_db(p, 0);
8727      expertDotCommand(p, azArg, nArg);
8728    }
8729  }else
8730#endif
8731
8732  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8733    static const struct {
8734       const char *zCtrlName;   /* Name of a test-control option */
8735       int ctrlCode;            /* Integer code for that option */
8736       const char *zUsage;      /* Usage notes */
8737    } aCtrl[] = {
8738      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8739      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8740      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8741      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8742      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8743   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8744      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8745      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8746      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8747      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8748   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8749    };
8750    int filectrl = -1;
8751    int iCtrl = -1;
8752    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8753    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8754    int n2, i;
8755    const char *zCmd = 0;
8756    const char *zSchema = 0;
8757
8758    open_db(p, 0);
8759    zCmd = nArg>=2 ? azArg[1] : "help";
8760
8761    if( zCmd[0]=='-'
8762     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8763     && nArg>=4
8764    ){
8765      zSchema = azArg[2];
8766      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8767      nArg -= 2;
8768      zCmd = azArg[1];
8769    }
8770
8771    /* The argument can optionally begin with "-" or "--" */
8772    if( zCmd[0]=='-' && zCmd[1] ){
8773      zCmd++;
8774      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8775    }
8776
8777    /* --help lists all file-controls */
8778    if( strcmp(zCmd,"help")==0 ){
8779      utf8_printf(p->out, "Available file-controls:\n");
8780      for(i=0; i<ArraySize(aCtrl); i++){
8781        utf8_printf(p->out, "  .filectrl %s %s\n",
8782                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8783      }
8784      rc = 1;
8785      goto meta_command_exit;
8786    }
8787
8788    /* convert filectrl text option to value. allow any unique prefix
8789    ** of the option name, or a numerical value. */
8790    n2 = strlen30(zCmd);
8791    for(i=0; i<ArraySize(aCtrl); i++){
8792      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8793        if( filectrl<0 ){
8794          filectrl = aCtrl[i].ctrlCode;
8795          iCtrl = i;
8796        }else{
8797          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8798                              "Use \".filectrl --help\" for help\n", zCmd);
8799          rc = 1;
8800          goto meta_command_exit;
8801        }
8802      }
8803    }
8804    if( filectrl<0 ){
8805      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8806                         "Use \".filectrl --help\" for help\n", zCmd);
8807    }else{
8808      switch(filectrl){
8809        case SQLITE_FCNTL_SIZE_LIMIT: {
8810          if( nArg!=2 && nArg!=3 ) break;
8811          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8812          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8813          isOk = 1;
8814          break;
8815        }
8816        case SQLITE_FCNTL_LOCK_TIMEOUT:
8817        case SQLITE_FCNTL_CHUNK_SIZE: {
8818          int x;
8819          if( nArg!=3 ) break;
8820          x = (int)integerValue(azArg[2]);
8821          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8822          isOk = 2;
8823          break;
8824        }
8825        case SQLITE_FCNTL_PERSIST_WAL:
8826        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8827          int x;
8828          if( nArg!=2 && nArg!=3 ) break;
8829          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8830          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8831          iRes = x;
8832          isOk = 1;
8833          break;
8834        }
8835        case SQLITE_FCNTL_DATA_VERSION:
8836        case SQLITE_FCNTL_HAS_MOVED: {
8837          int x;
8838          if( nArg!=2 ) break;
8839          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8840          iRes = x;
8841          isOk = 1;
8842          break;
8843        }
8844        case SQLITE_FCNTL_TEMPFILENAME: {
8845          char *z = 0;
8846          if( nArg!=2 ) break;
8847          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8848          if( z ){
8849            utf8_printf(p->out, "%s\n", z);
8850            sqlite3_free(z);
8851          }
8852          isOk = 2;
8853          break;
8854        }
8855        case SQLITE_FCNTL_RESERVE_BYTES: {
8856          int x;
8857          if( nArg>=3 ){
8858            x = atoi(azArg[2]);
8859            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8860          }
8861          x = -1;
8862          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8863          utf8_printf(p->out,"%d\n", x);
8864          isOk = 2;
8865          break;
8866        }
8867      }
8868    }
8869    if( isOk==0 && iCtrl>=0 ){
8870      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8871      rc = 1;
8872    }else if( isOk==1 ){
8873      char zBuf[100];
8874      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8875      raw_printf(p->out, "%s\n", zBuf);
8876    }
8877  }else
8878
8879  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8880    ShellState data;
8881    int doStats = 0;
8882    memcpy(&data, p, sizeof(data));
8883    data.showHeader = 0;
8884    data.cMode = data.mode = MODE_Semi;
8885    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8886      data.cMode = data.mode = MODE_Pretty;
8887      nArg = 1;
8888    }
8889    if( nArg!=1 ){
8890      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8891      rc = 1;
8892      goto meta_command_exit;
8893    }
8894    open_db(p, 0);
8895    rc = sqlite3_exec(p->db,
8896       "SELECT sql FROM"
8897       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8898       "     FROM sqlite_schema UNION ALL"
8899       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8900       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8901       "ORDER BY x",
8902       callback, &data, 0
8903    );
8904    if( rc==SQLITE_OK ){
8905      sqlite3_stmt *pStmt;
8906      rc = sqlite3_prepare_v2(p->db,
8907               "SELECT rowid FROM sqlite_schema"
8908               " WHERE name GLOB 'sqlite_stat[134]'",
8909               -1, &pStmt, 0);
8910      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8911      sqlite3_finalize(pStmt);
8912    }
8913    if( doStats==0 ){
8914      raw_printf(p->out, "/* No STAT tables available */\n");
8915    }else{
8916      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8917      data.cMode = data.mode = MODE_Insert;
8918      data.zDestTable = "sqlite_stat1";
8919      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8920      data.zDestTable = "sqlite_stat4";
8921      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8922      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8923    }
8924  }else
8925
8926  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8927    if( nArg==2 ){
8928      p->showHeader = booleanValue(azArg[1]);
8929      p->shellFlgs |= SHFLG_HeaderSet;
8930    }else{
8931      raw_printf(stderr, "Usage: .headers on|off\n");
8932      rc = 1;
8933    }
8934  }else
8935
8936  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8937    if( nArg>=2 ){
8938      n = showHelp(p->out, azArg[1]);
8939      if( n==0 ){
8940        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8941      }
8942    }else{
8943      showHelp(p->out, 0);
8944    }
8945  }else
8946
8947#ifndef SQLITE_SHELL_FIDDLE
8948  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8949    char *zTable = 0;           /* Insert data into this table */
8950    char *zSchema = 0;          /* within this schema (may default to "main") */
8951    char *zFile = 0;            /* Name of file to extra content from */
8952    sqlite3_stmt *pStmt = NULL; /* A statement */
8953    int nCol;                   /* Number of columns in the table */
8954    int nByte;                  /* Number of bytes in an SQL string */
8955    int i, j;                   /* Loop counters */
8956    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8957    int nSep;                   /* Number of bytes in p->colSeparator[] */
8958    char *zSql;                 /* An SQL statement */
8959    char *zFullTabName;         /* Table name with schema if applicable */
8960    ImportCtx sCtx;             /* Reader context */
8961    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8962    int eVerbose = 0;           /* Larger for more console output */
8963    int nSkip = 0;              /* Initial lines to skip */
8964    int useOutputMode = 1;      /* Use output mode to determine separators */
8965    char *zCreate = 0;          /* CREATE TABLE statement text */
8966
8967    failIfSafeMode(p, "cannot run .import in safe mode");
8968    memset(&sCtx, 0, sizeof(sCtx));
8969    if( p->mode==MODE_Ascii ){
8970      xRead = ascii_read_one_field;
8971    }else{
8972      xRead = csv_read_one_field;
8973    }
8974    rc = 1;
8975    for(i=1; i<nArg; i++){
8976      char *z = azArg[i];
8977      if( z[0]=='-' && z[1]=='-' ) z++;
8978      if( z[0]!='-' ){
8979        if( zFile==0 ){
8980          zFile = z;
8981        }else if( zTable==0 ){
8982          zTable = z;
8983        }else{
8984          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8985          showHelp(p->out, "import");
8986          goto meta_command_exit;
8987        }
8988      }else if( strcmp(z,"-v")==0 ){
8989        eVerbose++;
8990      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8991        zSchema = azArg[++i];
8992      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8993        nSkip = integerValue(azArg[++i]);
8994      }else if( strcmp(z,"-ascii")==0 ){
8995        sCtx.cColSep = SEP_Unit[0];
8996        sCtx.cRowSep = SEP_Record[0];
8997        xRead = ascii_read_one_field;
8998        useOutputMode = 0;
8999      }else if( strcmp(z,"-csv")==0 ){
9000        sCtx.cColSep = ',';
9001        sCtx.cRowSep = '\n';
9002        xRead = csv_read_one_field;
9003        useOutputMode = 0;
9004      }else{
9005        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
9006        showHelp(p->out, "import");
9007        goto meta_command_exit;
9008      }
9009    }
9010    if( zTable==0 ){
9011      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
9012                  zFile==0 ? "FILE" : "TABLE");
9013      showHelp(p->out, "import");
9014      goto meta_command_exit;
9015    }
9016    seenInterrupt = 0;
9017    open_db(p, 0);
9018    if( useOutputMode ){
9019      /* If neither the --csv or --ascii options are specified, then set
9020      ** the column and row separator characters from the output mode. */
9021      nSep = strlen30(p->colSeparator);
9022      if( nSep==0 ){
9023        raw_printf(stderr,
9024                   "Error: non-null column separator required for import\n");
9025        goto meta_command_exit;
9026      }
9027      if( nSep>1 ){
9028        raw_printf(stderr,
9029              "Error: multi-character column separators not allowed"
9030              " for import\n");
9031        goto meta_command_exit;
9032      }
9033      nSep = strlen30(p->rowSeparator);
9034      if( nSep==0 ){
9035        raw_printf(stderr,
9036            "Error: non-null row separator required for import\n");
9037        goto meta_command_exit;
9038      }
9039      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9040        /* When importing CSV (only), if the row separator is set to the
9041        ** default output row separator, change it to the default input
9042        ** row separator.  This avoids having to maintain different input
9043        ** and output row separators. */
9044        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9045        nSep = strlen30(p->rowSeparator);
9046      }
9047      if( nSep>1 ){
9048        raw_printf(stderr, "Error: multi-character row separators not allowed"
9049                           " for import\n");
9050        goto meta_command_exit;
9051      }
9052      sCtx.cColSep = p->colSeparator[0];
9053      sCtx.cRowSep = p->rowSeparator[0];
9054    }
9055    sCtx.zFile = zFile;
9056    sCtx.nLine = 1;
9057    if( sCtx.zFile[0]=='|' ){
9058#ifdef SQLITE_OMIT_POPEN
9059      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9060      goto meta_command_exit;
9061#else
9062      sCtx.in = popen(sCtx.zFile+1, "r");
9063      sCtx.zFile = "<pipe>";
9064      sCtx.xCloser = pclose;
9065#endif
9066    }else{
9067      sCtx.in = fopen(sCtx.zFile, "rb");
9068      sCtx.xCloser = fclose;
9069    }
9070    if( sCtx.in==0 ){
9071      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9072      goto meta_command_exit;
9073    }
9074    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9075      char zSep[2];
9076      zSep[1] = 0;
9077      zSep[0] = sCtx.cColSep;
9078      utf8_printf(p->out, "Column separator ");
9079      output_c_string(p->out, zSep);
9080      utf8_printf(p->out, ", row separator ");
9081      zSep[0] = sCtx.cRowSep;
9082      output_c_string(p->out, zSep);
9083      utf8_printf(p->out, "\n");
9084    }
9085    sCtx.z = sqlite3_malloc64(120);
9086    if( sCtx.z==0 ){
9087      import_cleanup(&sCtx);
9088      shell_out_of_memory();
9089    }
9090    /* Below, resources must be freed before exit. */
9091    while( (nSkip--)>0 ){
9092      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9093    }
9094    if( zSchema!=0 ){
9095      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9096    }else{
9097      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9098    }
9099    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9100    if( zSql==0 || zFullTabName==0 ){
9101      import_cleanup(&sCtx);
9102      shell_out_of_memory();
9103    }
9104    nByte = strlen30(zSql);
9105    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9106    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9107    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9108      sqlite3 *dbCols = 0;
9109      char *zRenames = 0;
9110      char *zColDefs;
9111      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9112      while( xRead(&sCtx) ){
9113        zAutoColumn(sCtx.z, &dbCols, 0);
9114        if( sCtx.cTerm!=sCtx.cColSep ) break;
9115      }
9116      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9117      if( zRenames!=0 ){
9118        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9119                    "Columns renamed during .import %s due to duplicates:\n"
9120                    "%s\n", sCtx.zFile, zRenames);
9121        sqlite3_free(zRenames);
9122      }
9123      assert(dbCols==0);
9124      if( zColDefs==0 ){
9125        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9126      import_fail:
9127        sqlite3_free(zCreate);
9128        sqlite3_free(zSql);
9129        sqlite3_free(zFullTabName);
9130        import_cleanup(&sCtx);
9131        rc = 1;
9132        goto meta_command_exit;
9133      }
9134      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9135      if( eVerbose>=1 ){
9136        utf8_printf(p->out, "%s\n", zCreate);
9137      }
9138      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9139      if( rc ){
9140        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9141        goto import_fail;
9142      }
9143      sqlite3_free(zCreate);
9144      zCreate = 0;
9145      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9146    }
9147    if( rc ){
9148      if (pStmt) sqlite3_finalize(pStmt);
9149      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9150      goto import_fail;
9151    }
9152    sqlite3_free(zSql);
9153    nCol = sqlite3_column_count(pStmt);
9154    sqlite3_finalize(pStmt);
9155    pStmt = 0;
9156    if( nCol==0 ) return 0; /* no columns, no error */
9157    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9158    if( zSql==0 ){
9159      import_cleanup(&sCtx);
9160      shell_out_of_memory();
9161    }
9162    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9163    j = strlen30(zSql);
9164    for(i=1; i<nCol; i++){
9165      zSql[j++] = ',';
9166      zSql[j++] = '?';
9167    }
9168    zSql[j++] = ')';
9169    zSql[j] = 0;
9170    if( eVerbose>=2 ){
9171      utf8_printf(p->out, "Insert using: %s\n", zSql);
9172    }
9173    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9174    if( rc ){
9175      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9176      if (pStmt) sqlite3_finalize(pStmt);
9177      goto import_fail;
9178    }
9179    sqlite3_free(zSql);
9180    sqlite3_free(zFullTabName);
9181    needCommit = sqlite3_get_autocommit(p->db);
9182    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9183    do{
9184      int startLine = sCtx.nLine;
9185      for(i=0; i<nCol; i++){
9186        char *z = xRead(&sCtx);
9187        /*
9188        ** Did we reach end-of-file before finding any columns?
9189        ** If so, stop instead of NULL filling the remaining columns.
9190        */
9191        if( z==0 && i==0 ) break;
9192        /*
9193        ** Did we reach end-of-file OR end-of-line before finding any
9194        ** columns in ASCII mode?  If so, stop instead of NULL filling
9195        ** the remaining columns.
9196        */
9197        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9198        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9199        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9200          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9201                          "filling the rest with NULL\n",
9202                          sCtx.zFile, startLine, nCol, i+1);
9203          i += 2;
9204          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9205        }
9206      }
9207      if( sCtx.cTerm==sCtx.cColSep ){
9208        do{
9209          xRead(&sCtx);
9210          i++;
9211        }while( sCtx.cTerm==sCtx.cColSep );
9212        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9213                        "extras ignored\n",
9214                        sCtx.zFile, startLine, nCol, i);
9215      }
9216      if( i>=nCol ){
9217        sqlite3_step(pStmt);
9218        rc = sqlite3_reset(pStmt);
9219        if( rc!=SQLITE_OK ){
9220          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9221                      startLine, sqlite3_errmsg(p->db));
9222          sCtx.nErr++;
9223        }else{
9224          sCtx.nRow++;
9225        }
9226      }
9227    }while( sCtx.cTerm!=EOF );
9228
9229    import_cleanup(&sCtx);
9230    sqlite3_finalize(pStmt);
9231    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9232    if( eVerbose>0 ){
9233      utf8_printf(p->out,
9234          "Added %d rows with %d errors using %d lines of input\n",
9235          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9236    }
9237  }else
9238#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9239
9240#ifndef SQLITE_UNTESTABLE
9241  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9242    char *zSql;
9243    char *zCollist = 0;
9244    sqlite3_stmt *pStmt;
9245    int tnum = 0;
9246    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9247    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9248    int i;
9249    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9250      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9251                          "       .imposter off\n");
9252      /* Also allowed, but not documented:
9253      **
9254      **    .imposter TABLE IMPOSTER
9255      **
9256      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9257      ** imposter is another WITHOUT ROWID table with the columns in
9258      ** storage order. */
9259      rc = 1;
9260      goto meta_command_exit;
9261    }
9262    open_db(p, 0);
9263    if( nArg==2 ){
9264      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9265      goto meta_command_exit;
9266    }
9267    zSql = sqlite3_mprintf(
9268      "SELECT rootpage, 0 FROM sqlite_schema"
9269      " WHERE name='%q' AND type='index'"
9270      "UNION ALL "
9271      "SELECT rootpage, 1 FROM sqlite_schema"
9272      " WHERE name='%q' AND type='table'"
9273      "   AND sql LIKE '%%without%%rowid%%'",
9274      azArg[1], azArg[1]
9275    );
9276    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9277    sqlite3_free(zSql);
9278    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9279      tnum = sqlite3_column_int(pStmt, 0);
9280      isWO = sqlite3_column_int(pStmt, 1);
9281    }
9282    sqlite3_finalize(pStmt);
9283    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9284    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9285    sqlite3_free(zSql);
9286    i = 0;
9287    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9288      char zLabel[20];
9289      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9290      i++;
9291      if( zCol==0 ){
9292        if( sqlite3_column_int(pStmt,1)==-1 ){
9293          zCol = "_ROWID_";
9294        }else{
9295          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9296          zCol = zLabel;
9297        }
9298      }
9299      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9300        lenPK = (int)strlen(zCollist);
9301      }
9302      if( zCollist==0 ){
9303        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9304      }else{
9305        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9306      }
9307    }
9308    sqlite3_finalize(pStmt);
9309    if( i==0 || tnum==0 ){
9310      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9311      rc = 1;
9312      sqlite3_free(zCollist);
9313      goto meta_command_exit;
9314    }
9315    if( lenPK==0 ) lenPK = 100000;
9316    zSql = sqlite3_mprintf(
9317          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9318          azArg[2], zCollist, lenPK, zCollist);
9319    sqlite3_free(zCollist);
9320    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9321    if( rc==SQLITE_OK ){
9322      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9323      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9324      if( rc ){
9325        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9326      }else{
9327        utf8_printf(stdout, "%s;\n", zSql);
9328        raw_printf(stdout,
9329          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9330          azArg[1], isWO ? "table" : "index"
9331        );
9332      }
9333    }else{
9334      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9335      rc = 1;
9336    }
9337    sqlite3_free(zSql);
9338  }else
9339#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9340
9341#ifdef SQLITE_ENABLE_IOTRACE
9342  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9343    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9344    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9345    iotrace = 0;
9346    if( nArg<2 ){
9347      sqlite3IoTrace = 0;
9348    }else if( strcmp(azArg[1], "-")==0 ){
9349      sqlite3IoTrace = iotracePrintf;
9350      iotrace = stdout;
9351    }else{
9352      iotrace = fopen(azArg[1], "w");
9353      if( iotrace==0 ){
9354        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9355        sqlite3IoTrace = 0;
9356        rc = 1;
9357      }else{
9358        sqlite3IoTrace = iotracePrintf;
9359      }
9360    }
9361  }else
9362#endif
9363
9364  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9365    static const struct {
9366       const char *zLimitName;   /* Name of a limit */
9367       int limitCode;            /* Integer code for that limit */
9368    } aLimit[] = {
9369      { "length",                SQLITE_LIMIT_LENGTH                    },
9370      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9371      { "column",                SQLITE_LIMIT_COLUMN                    },
9372      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9373      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9374      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9375      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9376      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9377      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9378      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9379      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9380      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9381    };
9382    int i, n2;
9383    open_db(p, 0);
9384    if( nArg==1 ){
9385      for(i=0; i<ArraySize(aLimit); i++){
9386        printf("%20s %d\n", aLimit[i].zLimitName,
9387               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9388      }
9389    }else if( nArg>3 ){
9390      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9391      rc = 1;
9392      goto meta_command_exit;
9393    }else{
9394      int iLimit = -1;
9395      n2 = strlen30(azArg[1]);
9396      for(i=0; i<ArraySize(aLimit); i++){
9397        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9398          if( iLimit<0 ){
9399            iLimit = i;
9400          }else{
9401            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9402            rc = 1;
9403            goto meta_command_exit;
9404          }
9405        }
9406      }
9407      if( iLimit<0 ){
9408        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9409                        "enter \".limits\" with no arguments for a list.\n",
9410                         azArg[1]);
9411        rc = 1;
9412        goto meta_command_exit;
9413      }
9414      if( nArg==3 ){
9415        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9416                      (int)integerValue(azArg[2]));
9417      }
9418      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9419             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9420    }
9421  }else
9422
9423  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9424    open_db(p, 0);
9425    lintDotCommand(p, azArg, nArg);
9426  }else
9427
9428#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9429  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9430    const char *zFile, *zProc;
9431    char *zErrMsg = 0;
9432    failIfSafeMode(p, "cannot run .load in safe mode");
9433    if( nArg<2 ){
9434      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9435      rc = 1;
9436      goto meta_command_exit;
9437    }
9438    zFile = azArg[1];
9439    zProc = nArg>=3 ? azArg[2] : 0;
9440    open_db(p, 0);
9441    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9442    if( rc!=SQLITE_OK ){
9443      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9444      sqlite3_free(zErrMsg);
9445      rc = 1;
9446    }
9447  }else
9448#endif
9449
9450#ifndef SQLITE_SHELL_FIDDLE
9451  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9452    failIfSafeMode(p, "cannot run .log in safe mode");
9453    if( nArg!=2 ){
9454      raw_printf(stderr, "Usage: .log FILENAME\n");
9455      rc = 1;
9456    }else{
9457      const char *zFile = azArg[1];
9458      output_file_close(p->pLog);
9459      p->pLog = output_file_open(zFile, 0);
9460    }
9461  }else
9462#endif
9463
9464  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9465    const char *zMode = 0;
9466    const char *zTabname = 0;
9467    int i, n2;
9468    ColModeOpts cmOpts = ColModeOpts_default;
9469    for(i=1; i<nArg; i++){
9470      const char *z = azArg[i];
9471      if( optionMatch(z,"wrap") && i+1<nArg ){
9472        cmOpts.iWrap = integerValue(azArg[++i]);
9473      }else if( optionMatch(z,"ww") ){
9474        cmOpts.bWordWrap = 1;
9475      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9476        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9477      }else if( optionMatch(z,"quote") ){
9478        cmOpts.bQuote = 1;
9479      }else if( optionMatch(z,"noquote") ){
9480        cmOpts.bQuote = 0;
9481      }else if( zMode==0 ){
9482        zMode = z;
9483        /* Apply defaults for qbox pseudo-mods. If that
9484         * overwrites already-set values, user was informed of this.
9485         */
9486        if( strcmp(z, "qbox")==0 ){
9487          ColModeOpts cmo = ColModeOpts_default_qbox;
9488          zMode = "box";
9489          cmOpts = cmo;
9490        }
9491      }else if( zTabname==0 ){
9492        zTabname = z;
9493      }else if( z[0]=='-' ){
9494        utf8_printf(stderr, "unknown option: %s\n", z);
9495        utf8_printf(stderr, "options:\n"
9496                            "  --noquote\n"
9497                            "  --quote\n"
9498                            "  --wordwrap on/off\n"
9499                            "  --wrap N\n"
9500                            "  --ww\n");
9501        rc = 1;
9502        goto meta_command_exit;
9503      }else{
9504        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9505        rc = 1;
9506        goto meta_command_exit;
9507      }
9508    }
9509    if( zMode==0 ){
9510      if( p->mode==MODE_Column
9511       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9512      ){
9513        raw_printf
9514          (p->out,
9515           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9516           modeDescr[p->mode], p->cmOpts.iWrap,
9517           p->cmOpts.bWordWrap ? "on" : "off",
9518           p->cmOpts.bQuote ? "" : "no");
9519      }else{
9520        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9521      }
9522      zMode = modeDescr[p->mode];
9523    }
9524    n2 = strlen30(zMode);
9525    if( strncmp(zMode,"lines",n2)==0 ){
9526      p->mode = MODE_Line;
9527      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9528    }else if( strncmp(zMode,"columns",n2)==0 ){
9529      p->mode = MODE_Column;
9530      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9531        p->showHeader = 1;
9532      }
9533      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9534      p->cmOpts = cmOpts;
9535    }else if( strncmp(zMode,"list",n2)==0 ){
9536      p->mode = MODE_List;
9537      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9538      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9539    }else if( strncmp(zMode,"html",n2)==0 ){
9540      p->mode = MODE_Html;
9541    }else if( strncmp(zMode,"tcl",n2)==0 ){
9542      p->mode = MODE_Tcl;
9543      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9544      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9545    }else if( strncmp(zMode,"csv",n2)==0 ){
9546      p->mode = MODE_Csv;
9547      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9548      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9549    }else if( strncmp(zMode,"tabs",n2)==0 ){
9550      p->mode = MODE_List;
9551      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9552    }else if( strncmp(zMode,"insert",n2)==0 ){
9553      p->mode = MODE_Insert;
9554      set_table_name(p, zTabname ? zTabname : "table");
9555    }else if( strncmp(zMode,"quote",n2)==0 ){
9556      p->mode = MODE_Quote;
9557      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9558      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9559    }else if( strncmp(zMode,"ascii",n2)==0 ){
9560      p->mode = MODE_Ascii;
9561      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9562      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9563    }else if( strncmp(zMode,"markdown",n2)==0 ){
9564      p->mode = MODE_Markdown;
9565      p->cmOpts = cmOpts;
9566    }else if( strncmp(zMode,"table",n2)==0 ){
9567      p->mode = MODE_Table;
9568      p->cmOpts = cmOpts;
9569    }else if( strncmp(zMode,"box",n2)==0 ){
9570      p->mode = MODE_Box;
9571      p->cmOpts = cmOpts;
9572    }else if( strncmp(zMode,"count",n2)==0 ){
9573      p->mode = MODE_Count;
9574    }else if( strncmp(zMode,"off",n2)==0 ){
9575      p->mode = MODE_Off;
9576    }else if( strncmp(zMode,"json",n2)==0 ){
9577      p->mode = MODE_Json;
9578    }else{
9579      raw_printf(stderr, "Error: mode should be one of: "
9580         "ascii box column csv html insert json line list markdown "
9581         "qbox quote table tabs tcl\n");
9582      rc = 1;
9583    }
9584    p->cMode = p->mode;
9585  }else
9586
9587#ifndef SQLITE_SHELL_FIDDLE
9588  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9589    if( nArg!=2 ){
9590      raw_printf(stderr, "Usage: .nonce NONCE\n");
9591      rc = 1;
9592    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9593      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9594                 p->lineno, azArg[1]);
9595      exit(1);
9596    }else{
9597      p->bSafeMode = 0;
9598      return 0;  /* Return immediately to bypass the safe mode reset
9599                 ** at the end of this procedure */
9600    }
9601  }else
9602#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9603
9604  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9605    if( nArg==2 ){
9606      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9607                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9608    }else{
9609      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9610      rc = 1;
9611    }
9612  }else
9613
9614  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9615    const char *zFN = 0;     /* Pointer to constant filename */
9616    char *zNewFilename = 0;  /* Name of the database file to open */
9617    int iName = 1;           /* Index in azArg[] of the filename */
9618    int newFlag = 0;         /* True to delete file before opening */
9619    int openMode = SHELL_OPEN_UNSPEC;
9620
9621    /* Check for command-line arguments */
9622    for(iName=1; iName<nArg; iName++){
9623      const char *z = azArg[iName];
9624#ifndef SQLITE_SHELL_FIDDLE
9625      if( optionMatch(z,"new") ){
9626        newFlag = 1;
9627#ifdef SQLITE_HAVE_ZLIB
9628      }else if( optionMatch(z, "zip") ){
9629        openMode = SHELL_OPEN_ZIPFILE;
9630#endif
9631      }else if( optionMatch(z, "append") ){
9632        openMode = SHELL_OPEN_APPENDVFS;
9633      }else if( optionMatch(z, "readonly") ){
9634        openMode = SHELL_OPEN_READONLY;
9635      }else if( optionMatch(z, "nofollow") ){
9636        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9637#ifndef SQLITE_OMIT_DESERIALIZE
9638      }else if( optionMatch(z, "deserialize") ){
9639        openMode = SHELL_OPEN_DESERIALIZE;
9640      }else if( optionMatch(z, "hexdb") ){
9641        openMode = SHELL_OPEN_HEXDB;
9642      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9643        p->szMax = integerValue(azArg[++iName]);
9644#endif /* SQLITE_OMIT_DESERIALIZE */
9645      }else
9646#endif /* !SQLITE_SHELL_FIDDLE */
9647      if( z[0]=='-' ){
9648        utf8_printf(stderr, "unknown option: %s\n", z);
9649        rc = 1;
9650        goto meta_command_exit;
9651      }else if( zFN ){
9652        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9653        rc = 1;
9654        goto meta_command_exit;
9655      }else{
9656        zFN = z;
9657      }
9658    }
9659
9660    /* Close the existing database */
9661    session_close_all(p, -1);
9662    close_db(p->db);
9663    p->db = 0;
9664    p->pAuxDb->zDbFilename = 0;
9665    sqlite3_free(p->pAuxDb->zFreeOnClose);
9666    p->pAuxDb->zFreeOnClose = 0;
9667    p->openMode = openMode;
9668    p->openFlags = 0;
9669    p->szMax = 0;
9670
9671    /* If a filename is specified, try to open it first */
9672    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9673      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9674#ifndef SQLITE_SHELL_FIDDLE
9675      if( p->bSafeMode
9676       && p->openMode!=SHELL_OPEN_HEXDB
9677       && zFN
9678       && strcmp(zFN,":memory:")!=0
9679      ){
9680        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9681      }
9682#else
9683      /* WASM mode has its own sandboxed pseudo-filesystem. */
9684#endif
9685      if( zFN ){
9686        zNewFilename = sqlite3_mprintf("%s", zFN);
9687        shell_check_oom(zNewFilename);
9688      }else{
9689        zNewFilename = 0;
9690      }
9691      p->pAuxDb->zDbFilename = zNewFilename;
9692      open_db(p, OPEN_DB_KEEPALIVE);
9693      if( p->db==0 ){
9694        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9695        sqlite3_free(zNewFilename);
9696      }else{
9697        p->pAuxDb->zFreeOnClose = zNewFilename;
9698      }
9699    }
9700    if( p->db==0 ){
9701      /* As a fall-back open a TEMP database */
9702      p->pAuxDb->zDbFilename = 0;
9703      open_db(p, 0);
9704    }
9705  }else
9706
9707#ifndef SQLITE_SHELL_FIDDLE
9708  if( (c=='o'
9709        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9710   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9711  ){
9712    char *zFile = 0;
9713    int bTxtMode = 0;
9714    int i;
9715    int eMode = 0;
9716    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9717    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9718
9719    zBOM[0] = 0;
9720    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9721    if( c=='e' ){
9722      eMode = 'x';
9723      bOnce = 2;
9724    }else if( strncmp(azArg[0],"once",n)==0 ){
9725      bOnce = 1;
9726    }
9727    for(i=1; i<nArg; i++){
9728      char *z = azArg[i];
9729      if( z[0]=='-' ){
9730        if( z[1]=='-' ) z++;
9731        if( strcmp(z,"-bom")==0 ){
9732          zBOM[0] = 0xef;
9733          zBOM[1] = 0xbb;
9734          zBOM[2] = 0xbf;
9735          zBOM[3] = 0;
9736        }else if( c!='e' && strcmp(z,"-x")==0 ){
9737          eMode = 'x';  /* spreadsheet */
9738        }else if( c!='e' && strcmp(z,"-e")==0 ){
9739          eMode = 'e';  /* text editor */
9740        }else{
9741          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9742                      azArg[i]);
9743          showHelp(p->out, azArg[0]);
9744          rc = 1;
9745          goto meta_command_exit;
9746        }
9747      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9748        zFile = sqlite3_mprintf("%s", z);
9749        if( zFile && zFile[0]=='|' ){
9750          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9751          break;
9752        }
9753      }else{
9754        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9755                    azArg[i]);
9756        showHelp(p->out, azArg[0]);
9757        rc = 1;
9758        sqlite3_free(zFile);
9759        goto meta_command_exit;
9760      }
9761    }
9762    if( zFile==0 ){
9763      zFile = sqlite3_mprintf("stdout");
9764    }
9765    if( bOnce ){
9766      p->outCount = 2;
9767    }else{
9768      p->outCount = 0;
9769    }
9770    output_reset(p);
9771#ifndef SQLITE_NOHAVE_SYSTEM
9772    if( eMode=='e' || eMode=='x' ){
9773      p->doXdgOpen = 1;
9774      outputModePush(p);
9775      if( eMode=='x' ){
9776        /* spreadsheet mode.  Output as CSV. */
9777        newTempFile(p, "csv");
9778        ShellClearFlag(p, SHFLG_Echo);
9779        p->mode = MODE_Csv;
9780        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9781        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9782      }else{
9783        /* text editor mode */
9784        newTempFile(p, "txt");
9785        bTxtMode = 1;
9786      }
9787      sqlite3_free(zFile);
9788      zFile = sqlite3_mprintf("%s", p->zTempFile);
9789    }
9790#endif /* SQLITE_NOHAVE_SYSTEM */
9791    shell_check_oom(zFile);
9792    if( zFile[0]=='|' ){
9793#ifdef SQLITE_OMIT_POPEN
9794      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9795      rc = 1;
9796      p->out = stdout;
9797#else
9798      p->out = popen(zFile + 1, "w");
9799      if( p->out==0 ){
9800        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9801        p->out = stdout;
9802        rc = 1;
9803      }else{
9804        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9805        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9806      }
9807#endif
9808    }else{
9809      p->out = output_file_open(zFile, bTxtMode);
9810      if( p->out==0 ){
9811        if( strcmp(zFile,"off")!=0 ){
9812          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9813        }
9814        p->out = stdout;
9815        rc = 1;
9816      } else {
9817        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9818        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9819      }
9820    }
9821    sqlite3_free(zFile);
9822  }else
9823#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9824
9825  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9826    open_db(p,0);
9827    if( nArg<=1 ) goto parameter_syntax_error;
9828
9829    /* .parameter clear
9830    ** Clear all bind parameters by dropping the TEMP table that holds them.
9831    */
9832    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9833      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9834                   0, 0, 0);
9835    }else
9836
9837    /* .parameter list
9838    ** List all bind parameters.
9839    */
9840    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9841      sqlite3_stmt *pStmt = 0;
9842      int rx;
9843      int len = 0;
9844      rx = sqlite3_prepare_v2(p->db,
9845             "SELECT max(length(key)) "
9846             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9847      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9848        len = sqlite3_column_int(pStmt, 0);
9849        if( len>40 ) len = 40;
9850      }
9851      sqlite3_finalize(pStmt);
9852      pStmt = 0;
9853      if( len ){
9854        rx = sqlite3_prepare_v2(p->db,
9855             "SELECT key, quote(value) "
9856             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9857        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9858          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9859                      sqlite3_column_text(pStmt,1));
9860        }
9861        sqlite3_finalize(pStmt);
9862      }
9863    }else
9864
9865    /* .parameter init
9866    ** Make sure the TEMP table used to hold bind parameters exists.
9867    ** Create it if necessary.
9868    */
9869    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9870      bind_table_init(p);
9871    }else
9872
9873    /* .parameter set NAME VALUE
9874    ** Set or reset a bind parameter.  NAME should be the full parameter
9875    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9876    ** VALUE can be in either SQL literal notation, or if not it will be
9877    ** understood to be a text string.
9878    */
9879    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9880      int rx;
9881      char *zSql;
9882      sqlite3_stmt *pStmt;
9883      const char *zKey = azArg[2];
9884      const char *zValue = azArg[3];
9885      bind_table_init(p);
9886      zSql = sqlite3_mprintf(
9887                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9888                  "VALUES(%Q,%s);", zKey, zValue);
9889      shell_check_oom(zSql);
9890      pStmt = 0;
9891      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9892      sqlite3_free(zSql);
9893      if( rx!=SQLITE_OK ){
9894        sqlite3_finalize(pStmt);
9895        pStmt = 0;
9896        zSql = sqlite3_mprintf(
9897                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9898                   "VALUES(%Q,%Q);", zKey, zValue);
9899        shell_check_oom(zSql);
9900        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9901        sqlite3_free(zSql);
9902        if( rx!=SQLITE_OK ){
9903          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9904          sqlite3_finalize(pStmt);
9905          pStmt = 0;
9906          rc = 1;
9907        }
9908      }
9909      sqlite3_step(pStmt);
9910      sqlite3_finalize(pStmt);
9911    }else
9912
9913    /* .parameter unset NAME
9914    ** Remove the NAME binding from the parameter binding table, if it
9915    ** exists.
9916    */
9917    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9918      char *zSql = sqlite3_mprintf(
9919          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9920      shell_check_oom(zSql);
9921      sqlite3_exec(p->db, zSql, 0, 0, 0);
9922      sqlite3_free(zSql);
9923    }else
9924    /* If no command name matches, show a syntax error */
9925    parameter_syntax_error:
9926    showHelp(p->out, "parameter");
9927  }else
9928
9929  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9930    int i;
9931    for(i=1; i<nArg; i++){
9932      if( i>1 ) raw_printf(p->out, " ");
9933      utf8_printf(p->out, "%s", azArg[i]);
9934    }
9935    raw_printf(p->out, "\n");
9936  }else
9937
9938#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9939  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9940    int i;
9941    int nn = 0;
9942    p->flgProgress = 0;
9943    p->mxProgress = 0;
9944    p->nProgress = 0;
9945    for(i=1; i<nArg; i++){
9946      const char *z = azArg[i];
9947      if( z[0]=='-' ){
9948        z++;
9949        if( z[0]=='-' ) z++;
9950        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9951          p->flgProgress |= SHELL_PROGRESS_QUIET;
9952          continue;
9953        }
9954        if( strcmp(z,"reset")==0 ){
9955          p->flgProgress |= SHELL_PROGRESS_RESET;
9956          continue;
9957        }
9958        if( strcmp(z,"once")==0 ){
9959          p->flgProgress |= SHELL_PROGRESS_ONCE;
9960          continue;
9961        }
9962        if( strcmp(z,"limit")==0 ){
9963          if( i+1>=nArg ){
9964            utf8_printf(stderr, "Error: missing argument on --limit\n");
9965            rc = 1;
9966            goto meta_command_exit;
9967          }else{
9968            p->mxProgress = (int)integerValue(azArg[++i]);
9969          }
9970          continue;
9971        }
9972        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9973        rc = 1;
9974        goto meta_command_exit;
9975      }else{
9976        nn = (int)integerValue(z);
9977      }
9978    }
9979    open_db(p, 0);
9980    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9981  }else
9982#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9983
9984  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9985    if( nArg >= 2) {
9986      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9987    }
9988    if( nArg >= 3) {
9989      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9990    }
9991  }else
9992
9993#ifndef SQLITE_SHELL_FIDDLE
9994  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9995    rc = 2;
9996  }else
9997#endif
9998
9999#ifndef SQLITE_SHELL_FIDDLE
10000  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
10001    FILE *inSaved = p->in;
10002    int savedLineno = p->lineno;
10003    failIfSafeMode(p, "cannot run .read in safe mode");
10004    if( nArg!=2 ){
10005      raw_printf(stderr, "Usage: .read FILE\n");
10006      rc = 1;
10007      goto meta_command_exit;
10008    }
10009    if( azArg[1][0]=='|' ){
10010#ifdef SQLITE_OMIT_POPEN
10011      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
10012      rc = 1;
10013      p->out = stdout;
10014#else
10015      p->in = popen(azArg[1]+1, "r");
10016      if( p->in==0 ){
10017        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
10018        rc = 1;
10019      }else{
10020        rc = process_input(p);
10021        pclose(p->in);
10022      }
10023#endif
10024    }else if( (p->in = openChrSource(azArg[1]))==0 ){
10025      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
10026      rc = 1;
10027    }else{
10028      rc = process_input(p);
10029      fclose(p->in);
10030    }
10031    p->in = inSaved;
10032    p->lineno = savedLineno;
10033  }else
10034#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10035
10036#ifndef SQLITE_SHELL_FIDDLE
10037  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10038    const char *zSrcFile;
10039    const char *zDb;
10040    sqlite3 *pSrc;
10041    sqlite3_backup *pBackup;
10042    int nTimeout = 0;
10043
10044    failIfSafeMode(p, "cannot run .restore in safe mode");
10045    if( nArg==2 ){
10046      zSrcFile = azArg[1];
10047      zDb = "main";
10048    }else if( nArg==3 ){
10049      zSrcFile = azArg[2];
10050      zDb = azArg[1];
10051    }else{
10052      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10053      rc = 1;
10054      goto meta_command_exit;
10055    }
10056    rc = sqlite3_open(zSrcFile, &pSrc);
10057    if( rc!=SQLITE_OK ){
10058      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10059      close_db(pSrc);
10060      return 1;
10061    }
10062    open_db(p, 0);
10063    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10064    if( pBackup==0 ){
10065      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10066      close_db(pSrc);
10067      return 1;
10068    }
10069    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10070          || rc==SQLITE_BUSY  ){
10071      if( rc==SQLITE_BUSY ){
10072        if( nTimeout++ >= 3 ) break;
10073        sqlite3_sleep(100);
10074      }
10075    }
10076    sqlite3_backup_finish(pBackup);
10077    if( rc==SQLITE_DONE ){
10078      rc = 0;
10079    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10080      raw_printf(stderr, "Error: source database is busy\n");
10081      rc = 1;
10082    }else{
10083      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10084      rc = 1;
10085    }
10086    close_db(pSrc);
10087  }else
10088#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10089
10090  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10091    if( nArg==2 ){
10092      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10093#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10094      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10095#endif
10096    }else{
10097      raw_printf(stderr, "Usage: .scanstats on|off\n");
10098      rc = 1;
10099    }
10100  }else
10101
10102  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10103    ShellText sSelect;
10104    ShellState data;
10105    char *zErrMsg = 0;
10106    const char *zDiv = "(";
10107    const char *zName = 0;
10108    int iSchema = 0;
10109    int bDebug = 0;
10110    int bNoSystemTabs = 0;
10111    int ii;
10112
10113    open_db(p, 0);
10114    memcpy(&data, p, sizeof(data));
10115    data.showHeader = 0;
10116    data.cMode = data.mode = MODE_Semi;
10117    initText(&sSelect);
10118    for(ii=1; ii<nArg; ii++){
10119      if( optionMatch(azArg[ii],"indent") ){
10120        data.cMode = data.mode = MODE_Pretty;
10121      }else if( optionMatch(azArg[ii],"debug") ){
10122        bDebug = 1;
10123      }else if( optionMatch(azArg[ii],"nosys") ){
10124        bNoSystemTabs = 1;
10125      }else if( azArg[ii][0]=='-' ){
10126        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10127        rc = 1;
10128        goto meta_command_exit;
10129      }else if( zName==0 ){
10130        zName = azArg[ii];
10131      }else{
10132        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10133        rc = 1;
10134        goto meta_command_exit;
10135      }
10136    }
10137    if( zName!=0 ){
10138      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10139                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10140                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10141                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10142      if( isSchema ){
10143        char *new_argv[2], *new_colv[2];
10144        new_argv[0] = sqlite3_mprintf(
10145                      "CREATE TABLE %s (\n"
10146                      "  type text,\n"
10147                      "  name text,\n"
10148                      "  tbl_name text,\n"
10149                      "  rootpage integer,\n"
10150                      "  sql text\n"
10151                      ")", zName);
10152        shell_check_oom(new_argv[0]);
10153        new_argv[1] = 0;
10154        new_colv[0] = "sql";
10155        new_colv[1] = 0;
10156        callback(&data, 1, new_argv, new_colv);
10157        sqlite3_free(new_argv[0]);
10158      }
10159    }
10160    if( zDiv ){
10161      sqlite3_stmt *pStmt = 0;
10162      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10163                              -1, &pStmt, 0);
10164      if( rc ){
10165        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10166        sqlite3_finalize(pStmt);
10167        rc = 1;
10168        goto meta_command_exit;
10169      }
10170      appendText(&sSelect, "SELECT sql FROM", 0);
10171      iSchema = 0;
10172      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10173        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10174        char zScNum[30];
10175        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10176        appendText(&sSelect, zDiv, 0);
10177        zDiv = " UNION ALL ";
10178        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10179        if( sqlite3_stricmp(zDb, "main")!=0 ){
10180          appendText(&sSelect, zDb, '\'');
10181        }else{
10182          appendText(&sSelect, "NULL", 0);
10183        }
10184        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10185        appendText(&sSelect, zScNum, 0);
10186        appendText(&sSelect, " AS snum, ", 0);
10187        appendText(&sSelect, zDb, '\'');
10188        appendText(&sSelect, " AS sname FROM ", 0);
10189        appendText(&sSelect, zDb, quoteChar(zDb));
10190        appendText(&sSelect, ".sqlite_schema", 0);
10191      }
10192      sqlite3_finalize(pStmt);
10193#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10194      if( zName ){
10195        appendText(&sSelect,
10196           " UNION ALL SELECT shell_module_schema(name),"
10197           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10198        0);
10199      }
10200#endif
10201      appendText(&sSelect, ") WHERE ", 0);
10202      if( zName ){
10203        char *zQarg = sqlite3_mprintf("%Q", zName);
10204        int bGlob;
10205        shell_check_oom(zQarg);
10206        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10207                strchr(zName, '[') != 0;
10208        if( strchr(zName, '.') ){
10209          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10210        }else{
10211          appendText(&sSelect, "lower(tbl_name)", 0);
10212        }
10213        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10214        appendText(&sSelect, zQarg, 0);
10215        if( !bGlob ){
10216          appendText(&sSelect, " ESCAPE '\\' ", 0);
10217        }
10218        appendText(&sSelect, " AND ", 0);
10219        sqlite3_free(zQarg);
10220      }
10221      if( bNoSystemTabs ){
10222        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10223      }
10224      appendText(&sSelect, "sql IS NOT NULL"
10225                           " ORDER BY snum, rowid", 0);
10226      if( bDebug ){
10227        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10228      }else{
10229        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10230      }
10231      freeText(&sSelect);
10232    }
10233    if( zErrMsg ){
10234      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10235      sqlite3_free(zErrMsg);
10236      rc = 1;
10237    }else if( rc != SQLITE_OK ){
10238      raw_printf(stderr,"Error: querying schema information\n");
10239      rc = 1;
10240    }else{
10241      rc = 0;
10242    }
10243  }else
10244
10245  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10246   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10247  ){
10248    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10249    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10250  }else
10251
10252#if defined(SQLITE_ENABLE_SESSION)
10253  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10254    struct AuxDb *pAuxDb = p->pAuxDb;
10255    OpenSession *pSession = &pAuxDb->aSession[0];
10256    char **azCmd = &azArg[1];
10257    int iSes = 0;
10258    int nCmd = nArg - 1;
10259    int i;
10260    if( nArg<=1 ) goto session_syntax_error;
10261    open_db(p, 0);
10262    if( nArg>=3 ){
10263      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10264        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10265      }
10266      if( iSes<pAuxDb->nSession ){
10267        pSession = &pAuxDb->aSession[iSes];
10268        azCmd++;
10269        nCmd--;
10270      }else{
10271        pSession = &pAuxDb->aSession[0];
10272        iSes = 0;
10273      }
10274    }
10275
10276    /* .session attach TABLE
10277    ** Invoke the sqlite3session_attach() interface to attach a particular
10278    ** table so that it is never filtered.
10279    */
10280    if( strcmp(azCmd[0],"attach")==0 ){
10281      if( nCmd!=2 ) goto session_syntax_error;
10282      if( pSession->p==0 ){
10283        session_not_open:
10284        raw_printf(stderr, "ERROR: No sessions are open\n");
10285      }else{
10286        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10287        if( rc ){
10288          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10289          rc = 0;
10290        }
10291      }
10292    }else
10293
10294    /* .session changeset FILE
10295    ** .session patchset FILE
10296    ** Write a changeset or patchset into a file.  The file is overwritten.
10297    */
10298    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10299      FILE *out = 0;
10300      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10301      if( nCmd!=2 ) goto session_syntax_error;
10302      if( pSession->p==0 ) goto session_not_open;
10303      out = fopen(azCmd[1], "wb");
10304      if( out==0 ){
10305        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10306                    azCmd[1]);
10307      }else{
10308        int szChng;
10309        void *pChng;
10310        if( azCmd[0][0]=='c' ){
10311          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10312        }else{
10313          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10314        }
10315        if( rc ){
10316          printf("Error: error code %d\n", rc);
10317          rc = 0;
10318        }
10319        if( pChng
10320          && fwrite(pChng, szChng, 1, out)!=1 ){
10321          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10322                  szChng);
10323        }
10324        sqlite3_free(pChng);
10325        fclose(out);
10326      }
10327    }else
10328
10329    /* .session close
10330    ** Close the identified session
10331    */
10332    if( strcmp(azCmd[0], "close")==0 ){
10333      if( nCmd!=1 ) goto session_syntax_error;
10334      if( pAuxDb->nSession ){
10335        session_close(pSession);
10336        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10337      }
10338    }else
10339
10340    /* .session enable ?BOOLEAN?
10341    ** Query or set the enable flag
10342    */
10343    if( strcmp(azCmd[0], "enable")==0 ){
10344      int ii;
10345      if( nCmd>2 ) goto session_syntax_error;
10346      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10347      if( pAuxDb->nSession ){
10348        ii = sqlite3session_enable(pSession->p, ii);
10349        utf8_printf(p->out, "session %s enable flag = %d\n",
10350                    pSession->zName, ii);
10351      }
10352    }else
10353
10354    /* .session filter GLOB ....
10355    ** Set a list of GLOB patterns of table names to be excluded.
10356    */
10357    if( strcmp(azCmd[0], "filter")==0 ){
10358      int ii, nByte;
10359      if( nCmd<2 ) goto session_syntax_error;
10360      if( pAuxDb->nSession ){
10361        for(ii=0; ii<pSession->nFilter; ii++){
10362          sqlite3_free(pSession->azFilter[ii]);
10363        }
10364        sqlite3_free(pSession->azFilter);
10365        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10366        pSession->azFilter = sqlite3_malloc( nByte );
10367        if( pSession->azFilter==0 ){
10368          raw_printf(stderr, "Error: out or memory\n");
10369          exit(1);
10370        }
10371        for(ii=1; ii<nCmd; ii++){
10372          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10373          shell_check_oom(x);
10374        }
10375        pSession->nFilter = ii-1;
10376      }
10377    }else
10378
10379    /* .session indirect ?BOOLEAN?
10380    ** Query or set the indirect flag
10381    */
10382    if( strcmp(azCmd[0], "indirect")==0 ){
10383      int ii;
10384      if( nCmd>2 ) goto session_syntax_error;
10385      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10386      if( pAuxDb->nSession ){
10387        ii = sqlite3session_indirect(pSession->p, ii);
10388        utf8_printf(p->out, "session %s indirect flag = %d\n",
10389                    pSession->zName, ii);
10390      }
10391    }else
10392
10393    /* .session isempty
10394    ** Determine if the session is empty
10395    */
10396    if( strcmp(azCmd[0], "isempty")==0 ){
10397      int ii;
10398      if( nCmd!=1 ) goto session_syntax_error;
10399      if( pAuxDb->nSession ){
10400        ii = sqlite3session_isempty(pSession->p);
10401        utf8_printf(p->out, "session %s isempty flag = %d\n",
10402                    pSession->zName, ii);
10403      }
10404    }else
10405
10406    /* .session list
10407    ** List all currently open sessions
10408    */
10409    if( strcmp(azCmd[0],"list")==0 ){
10410      for(i=0; i<pAuxDb->nSession; i++){
10411        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10412      }
10413    }else
10414
10415    /* .session open DB NAME
10416    ** Open a new session called NAME on the attached database DB.
10417    ** DB is normally "main".
10418    */
10419    if( strcmp(azCmd[0],"open")==0 ){
10420      char *zName;
10421      if( nCmd!=3 ) goto session_syntax_error;
10422      zName = azCmd[2];
10423      if( zName[0]==0 ) goto session_syntax_error;
10424      for(i=0; i<pAuxDb->nSession; i++){
10425        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10426          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10427          goto meta_command_exit;
10428        }
10429      }
10430      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10431        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10432        goto meta_command_exit;
10433      }
10434      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10435      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10436      if( rc ){
10437        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10438        rc = 0;
10439        goto meta_command_exit;
10440      }
10441      pSession->nFilter = 0;
10442      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10443      pAuxDb->nSession++;
10444      pSession->zName = sqlite3_mprintf("%s", zName);
10445      shell_check_oom(pSession->zName);
10446    }else
10447    /* If no command name matches, show a syntax error */
10448    session_syntax_error:
10449    showHelp(p->out, "session");
10450  }else
10451#endif
10452
10453#ifdef SQLITE_DEBUG
10454  /* Undocumented commands for internal testing.  Subject to change
10455  ** without notice. */
10456  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10457    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10458      int i, v;
10459      for(i=1; i<nArg; i++){
10460        v = booleanValue(azArg[i]);
10461        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10462      }
10463    }
10464    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10465      int i; sqlite3_int64 v;
10466      for(i=1; i<nArg; i++){
10467        char zBuf[200];
10468        v = integerValue(azArg[i]);
10469        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10470        utf8_printf(p->out, "%s", zBuf);
10471      }
10472    }
10473  }else
10474#endif
10475
10476  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10477    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10478    int bVerbose = 0;        /* Verbose output */
10479    int bSelftestExists;     /* True if SELFTEST already exists */
10480    int i, k;                /* Loop counters */
10481    int nTest = 0;           /* Number of tests runs */
10482    int nErr = 0;            /* Number of errors seen */
10483    ShellText str;           /* Answer for a query */
10484    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10485
10486    open_db(p,0);
10487    for(i=1; i<nArg; i++){
10488      const char *z = azArg[i];
10489      if( z[0]=='-' && z[1]=='-' ) z++;
10490      if( strcmp(z,"-init")==0 ){
10491        bIsInit = 1;
10492      }else
10493      if( strcmp(z,"-v")==0 ){
10494        bVerbose++;
10495      }else
10496      {
10497        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10498                    azArg[i], azArg[0]);
10499        raw_printf(stderr, "Should be one of: --init -v\n");
10500        rc = 1;
10501        goto meta_command_exit;
10502      }
10503    }
10504    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10505           != SQLITE_OK ){
10506      bSelftestExists = 0;
10507    }else{
10508      bSelftestExists = 1;
10509    }
10510    if( bIsInit ){
10511      createSelftestTable(p);
10512      bSelftestExists = 1;
10513    }
10514    initText(&str);
10515    appendText(&str, "x", 0);
10516    for(k=bSelftestExists; k>=0; k--){
10517      if( k==1 ){
10518        rc = sqlite3_prepare_v2(p->db,
10519            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10520            -1, &pStmt, 0);
10521      }else{
10522        rc = sqlite3_prepare_v2(p->db,
10523          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10524          "      (1,'run','PRAGMA integrity_check','ok')",
10525          -1, &pStmt, 0);
10526      }
10527      if( rc ){
10528        raw_printf(stderr, "Error querying the selftest table\n");
10529        rc = 1;
10530        sqlite3_finalize(pStmt);
10531        goto meta_command_exit;
10532      }
10533      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10534        int tno = sqlite3_column_int(pStmt, 0);
10535        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10536        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10537        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10538
10539        if( zOp==0 ) continue;
10540        if( zSql==0 ) continue;
10541        if( zAns==0 ) continue;
10542        k = 0;
10543        if( bVerbose>0 ){
10544          printf("%d: %s %s\n", tno, zOp, zSql);
10545        }
10546        if( strcmp(zOp,"memo")==0 ){
10547          utf8_printf(p->out, "%s\n", zSql);
10548        }else
10549        if( strcmp(zOp,"run")==0 ){
10550          char *zErrMsg = 0;
10551          str.n = 0;
10552          str.z[0] = 0;
10553          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10554          nTest++;
10555          if( bVerbose ){
10556            utf8_printf(p->out, "Result: %s\n", str.z);
10557          }
10558          if( rc || zErrMsg ){
10559            nErr++;
10560            rc = 1;
10561            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10562            sqlite3_free(zErrMsg);
10563          }else if( strcmp(zAns,str.z)!=0 ){
10564            nErr++;
10565            rc = 1;
10566            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10567            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10568          }
10569        }else
10570        {
10571          utf8_printf(stderr,
10572            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10573          rc = 1;
10574          break;
10575        }
10576      } /* End loop over rows of content from SELFTEST */
10577      sqlite3_finalize(pStmt);
10578    } /* End loop over k */
10579    freeText(&str);
10580    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10581  }else
10582
10583  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10584    if( nArg<2 || nArg>3 ){
10585      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10586      rc = 1;
10587    }
10588    if( nArg>=2 ){
10589      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10590                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10591    }
10592    if( nArg>=3 ){
10593      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10594                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10595    }
10596  }else
10597
10598  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10599    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10600    int i;                   /* Loop counter */
10601    int bSchema = 0;         /* Also hash the schema */
10602    int bSeparate = 0;       /* Hash each table separately */
10603    int iSize = 224;         /* Hash algorithm to use */
10604    int bDebug = 0;          /* Only show the query that would have run */
10605    sqlite3_stmt *pStmt;     /* For querying tables names */
10606    char *zSql;              /* SQL to be run */
10607    char *zSep;              /* Separator */
10608    ShellText sSql;          /* Complete SQL for the query to run the hash */
10609    ShellText sQuery;        /* Set of queries used to read all content */
10610    open_db(p, 0);
10611    for(i=1; i<nArg; i++){
10612      const char *z = azArg[i];
10613      if( z[0]=='-' ){
10614        z++;
10615        if( z[0]=='-' ) z++;
10616        if( strcmp(z,"schema")==0 ){
10617          bSchema = 1;
10618        }else
10619        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10620         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10621        ){
10622          iSize = atoi(&z[5]);
10623        }else
10624        if( strcmp(z,"debug")==0 ){
10625          bDebug = 1;
10626        }else
10627        {
10628          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10629                      azArg[i], azArg[0]);
10630          showHelp(p->out, azArg[0]);
10631          rc = 1;
10632          goto meta_command_exit;
10633        }
10634      }else if( zLike ){
10635        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10636        rc = 1;
10637        goto meta_command_exit;
10638      }else{
10639        zLike = z;
10640        bSeparate = 1;
10641        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10642      }
10643    }
10644    if( bSchema ){
10645      zSql = "SELECT lower(name) FROM sqlite_schema"
10646             " WHERE type='table' AND coalesce(rootpage,0)>1"
10647             " UNION ALL SELECT 'sqlite_schema'"
10648             " ORDER BY 1 collate nocase";
10649    }else{
10650      zSql = "SELECT lower(name) FROM sqlite_schema"
10651             " WHERE type='table' AND coalesce(rootpage,0)>1"
10652             " AND name NOT LIKE 'sqlite_%'"
10653             " ORDER BY 1 collate nocase";
10654    }
10655    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10656    initText(&sQuery);
10657    initText(&sSql);
10658    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10659    zSep = "VALUES(";
10660    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10661      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10662      if( zTab==0 ) continue;
10663      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10664      if( strncmp(zTab, "sqlite_",7)!=0 ){
10665        appendText(&sQuery,"SELECT * FROM ", 0);
10666        appendText(&sQuery,zTab,'"');
10667        appendText(&sQuery," NOT INDEXED;", 0);
10668      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10669        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10670                           " ORDER BY name;", 0);
10671      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10672        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10673                           " ORDER BY name;", 0);
10674      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10675        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10676                           " ORDER BY tbl,idx;", 0);
10677      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10678        appendText(&sQuery, "SELECT * FROM ", 0);
10679        appendText(&sQuery, zTab, 0);
10680        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10681      }
10682      appendText(&sSql, zSep, 0);
10683      appendText(&sSql, sQuery.z, '\'');
10684      sQuery.n = 0;
10685      appendText(&sSql, ",", 0);
10686      appendText(&sSql, zTab, '\'');
10687      zSep = "),(";
10688    }
10689    sqlite3_finalize(pStmt);
10690    if( bSeparate ){
10691      zSql = sqlite3_mprintf(
10692          "%s))"
10693          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10694          "   FROM [sha3sum$query]",
10695          sSql.z, iSize);
10696    }else{
10697      zSql = sqlite3_mprintf(
10698          "%s))"
10699          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10700          "   FROM [sha3sum$query]",
10701          sSql.z, iSize);
10702    }
10703    shell_check_oom(zSql);
10704    freeText(&sQuery);
10705    freeText(&sSql);
10706    if( bDebug ){
10707      utf8_printf(p->out, "%s\n", zSql);
10708    }else{
10709      shell_exec(p, zSql, 0);
10710    }
10711    sqlite3_free(zSql);
10712  }else
10713
10714#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10715  if( c=='s'
10716   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10717  ){
10718    char *zCmd;
10719    int i, x;
10720    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10721    if( nArg<2 ){
10722      raw_printf(stderr, "Usage: .system COMMAND\n");
10723      rc = 1;
10724      goto meta_command_exit;
10725    }
10726    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10727    for(i=2; i<nArg && zCmd!=0; i++){
10728      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10729                             zCmd, azArg[i]);
10730    }
10731    x = zCmd!=0 ? system(zCmd) : 1;
10732    sqlite3_free(zCmd);
10733    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10734  }else
10735#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10736
10737  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10738    static const char *azBool[] = { "off", "on", "trigger", "full"};
10739    const char *zOut;
10740    int i;
10741    if( nArg!=1 ){
10742      raw_printf(stderr, "Usage: .show\n");
10743      rc = 1;
10744      goto meta_command_exit;
10745    }
10746    utf8_printf(p->out, "%12.12s: %s\n","echo",
10747                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10748    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10749    utf8_printf(p->out, "%12.12s: %s\n","explain",
10750         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10751    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10752    if( p->mode==MODE_Column
10753     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10754    ){
10755      utf8_printf
10756        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10757         modeDescr[p->mode], p->cmOpts.iWrap,
10758         p->cmOpts.bWordWrap ? "on" : "off",
10759         p->cmOpts.bQuote ? "" : "no");
10760    }else{
10761      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10762    }
10763    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10764      output_c_string(p->out, p->nullValue);
10765      raw_printf(p->out, "\n");
10766    utf8_printf(p->out,"%12.12s: %s\n","output",
10767            strlen30(p->outfile) ? p->outfile : "stdout");
10768    utf8_printf(p->out,"%12.12s: ", "colseparator");
10769      output_c_string(p->out, p->colSeparator);
10770      raw_printf(p->out, "\n");
10771    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10772      output_c_string(p->out, p->rowSeparator);
10773      raw_printf(p->out, "\n");
10774    switch( p->statsOn ){
10775      case 0:  zOut = "off";     break;
10776      default: zOut = "on";      break;
10777      case 2:  zOut = "stmt";    break;
10778      case 3:  zOut = "vmstep";  break;
10779    }
10780    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10781    utf8_printf(p->out, "%12.12s: ", "width");
10782    for (i=0;i<p->nWidth;i++) {
10783      raw_printf(p->out, "%d ", p->colWidth[i]);
10784    }
10785    raw_printf(p->out, "\n");
10786    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10787                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10788  }else
10789
10790  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10791    if( nArg==2 ){
10792      if( strcmp(azArg[1],"stmt")==0 ){
10793        p->statsOn = 2;
10794      }else if( strcmp(azArg[1],"vmstep")==0 ){
10795        p->statsOn = 3;
10796      }else{
10797        p->statsOn = (u8)booleanValue(azArg[1]);
10798      }
10799    }else if( nArg==1 ){
10800      display_stats(p->db, p, 0);
10801    }else{
10802      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10803      rc = 1;
10804    }
10805  }else
10806
10807  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10808   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10809                 || strncmp(azArg[0], "indexes", n)==0) )
10810  ){
10811    sqlite3_stmt *pStmt;
10812    char **azResult;
10813    int nRow, nAlloc;
10814    int ii;
10815    ShellText s;
10816    initText(&s);
10817    open_db(p, 0);
10818    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10819    if( rc ){
10820      sqlite3_finalize(pStmt);
10821      return shellDatabaseError(p->db);
10822    }
10823
10824    if( nArg>2 && c=='i' ){
10825      /* It is an historical accident that the .indexes command shows an error
10826      ** when called with the wrong number of arguments whereas the .tables
10827      ** command does not. */
10828      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10829      rc = 1;
10830      sqlite3_finalize(pStmt);
10831      goto meta_command_exit;
10832    }
10833    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10834      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10835      if( zDbName==0 ) continue;
10836      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10837      if( sqlite3_stricmp(zDbName, "main")==0 ){
10838        appendText(&s, "SELECT name FROM ", 0);
10839      }else{
10840        appendText(&s, "SELECT ", 0);
10841        appendText(&s, zDbName, '\'');
10842        appendText(&s, "||'.'||name FROM ", 0);
10843      }
10844      appendText(&s, zDbName, '"');
10845      appendText(&s, ".sqlite_schema ", 0);
10846      if( c=='t' ){
10847        appendText(&s," WHERE type IN ('table','view')"
10848                      "   AND name NOT LIKE 'sqlite_%'"
10849                      "   AND name LIKE ?1", 0);
10850      }else{
10851        appendText(&s," WHERE type='index'"
10852                      "   AND tbl_name LIKE ?1", 0);
10853      }
10854    }
10855    rc = sqlite3_finalize(pStmt);
10856    if( rc==SQLITE_OK ){
10857      appendText(&s, " ORDER BY 1", 0);
10858      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10859    }
10860    freeText(&s);
10861    if( rc ) return shellDatabaseError(p->db);
10862
10863    /* Run the SQL statement prepared by the above block. Store the results
10864    ** as an array of nul-terminated strings in azResult[].  */
10865    nRow = nAlloc = 0;
10866    azResult = 0;
10867    if( nArg>1 ){
10868      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10869    }else{
10870      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10871    }
10872    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10873      if( nRow>=nAlloc ){
10874        char **azNew;
10875        int n2 = nAlloc*2 + 10;
10876        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10877        shell_check_oom(azNew);
10878        nAlloc = n2;
10879        azResult = azNew;
10880      }
10881      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10882      shell_check_oom(azResult[nRow]);
10883      nRow++;
10884    }
10885    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10886      rc = shellDatabaseError(p->db);
10887    }
10888
10889    /* Pretty-print the contents of array azResult[] to the output */
10890    if( rc==0 && nRow>0 ){
10891      int len, maxlen = 0;
10892      int i, j;
10893      int nPrintCol, nPrintRow;
10894      for(i=0; i<nRow; i++){
10895        len = strlen30(azResult[i]);
10896        if( len>maxlen ) maxlen = len;
10897      }
10898      nPrintCol = 80/(maxlen+2);
10899      if( nPrintCol<1 ) nPrintCol = 1;
10900      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10901      for(i=0; i<nPrintRow; i++){
10902        for(j=i; j<nRow; j+=nPrintRow){
10903          char *zSp = j<nPrintRow ? "" : "  ";
10904          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10905                      azResult[j] ? azResult[j]:"");
10906        }
10907        raw_printf(p->out, "\n");
10908      }
10909    }
10910
10911    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10912    sqlite3_free(azResult);
10913  }else
10914
10915#ifndef SQLITE_SHELL_FIDDLE
10916  /* Begin redirecting output to the file "testcase-out.txt" */
10917  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10918    output_reset(p);
10919    p->out = output_file_open("testcase-out.txt", 0);
10920    if( p->out==0 ){
10921      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10922    }
10923    if( nArg>=2 ){
10924      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10925    }else{
10926      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10927    }
10928  }else
10929#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10930
10931#ifndef SQLITE_UNTESTABLE
10932  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10933    static const struct {
10934       const char *zCtrlName;   /* Name of a test-control option */
10935       int ctrlCode;            /* Integer code for that option */
10936       int unSafe;              /* Not valid for --safe mode */
10937       const char *zUsage;      /* Usage notes */
10938    } aCtrl[] = {
10939      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10940      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10941    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10942    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10943      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10944      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10945    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10946      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10947      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10948      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10949      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10950      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10951#ifdef YYCOVERAGE
10952      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10953#endif
10954      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10955      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10956      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10957      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10958      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10959      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10960      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10961    };
10962    int testctrl = -1;
10963    int iCtrl = -1;
10964    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10965    int isOk = 0;
10966    int i, n2;
10967    const char *zCmd = 0;
10968
10969    open_db(p, 0);
10970    zCmd = nArg>=2 ? azArg[1] : "help";
10971
10972    /* The argument can optionally begin with "-" or "--" */
10973    if( zCmd[0]=='-' && zCmd[1] ){
10974      zCmd++;
10975      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10976    }
10977
10978    /* --help lists all test-controls */
10979    if( strcmp(zCmd,"help")==0 ){
10980      utf8_printf(p->out, "Available test-controls:\n");
10981      for(i=0; i<ArraySize(aCtrl); i++){
10982        utf8_printf(p->out, "  .testctrl %s %s\n",
10983                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10984      }
10985      rc = 1;
10986      goto meta_command_exit;
10987    }
10988
10989    /* convert testctrl text option to value. allow any unique prefix
10990    ** of the option name, or a numerical value. */
10991    n2 = strlen30(zCmd);
10992    for(i=0; i<ArraySize(aCtrl); i++){
10993      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10994        if( testctrl<0 ){
10995          testctrl = aCtrl[i].ctrlCode;
10996          iCtrl = i;
10997        }else{
10998          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10999                              "Use \".testctrl --help\" for help\n", zCmd);
11000          rc = 1;
11001          goto meta_command_exit;
11002        }
11003      }
11004    }
11005    if( testctrl<0 ){
11006      utf8_printf(stderr,"Error: unknown test-control: %s\n"
11007                         "Use \".testctrl --help\" for help\n", zCmd);
11008    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
11009      utf8_printf(stderr,
11010         "line %d: \".testctrl %s\" may not be used in safe mode\n",
11011         p->lineno, aCtrl[iCtrl].zCtrlName);
11012      exit(1);
11013    }else{
11014      switch(testctrl){
11015
11016        /* sqlite3_test_control(int, db, int) */
11017        case SQLITE_TESTCTRL_OPTIMIZATIONS:
11018          if( nArg==3 ){
11019            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
11020            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11021            isOk = 3;
11022          }
11023          break;
11024
11025        /* sqlite3_test_control(int) */
11026        case SQLITE_TESTCTRL_PRNG_SAVE:
11027        case SQLITE_TESTCTRL_PRNG_RESTORE:
11028        case SQLITE_TESTCTRL_BYTEORDER:
11029          if( nArg==2 ){
11030            rc2 = sqlite3_test_control(testctrl);
11031            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
11032          }
11033          break;
11034
11035        /* sqlite3_test_control(int, uint) */
11036        case SQLITE_TESTCTRL_PENDING_BYTE:
11037          if( nArg==3 ){
11038            unsigned int opt = (unsigned int)integerValue(azArg[2]);
11039            rc2 = sqlite3_test_control(testctrl, opt);
11040            isOk = 3;
11041          }
11042          break;
11043
11044        /* sqlite3_test_control(int, int, sqlite3*) */
11045        case SQLITE_TESTCTRL_PRNG_SEED:
11046          if( nArg==3 || nArg==4 ){
11047            int ii = (int)integerValue(azArg[2]);
11048            sqlite3 *db;
11049            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11050              sqlite3_randomness(sizeof(ii),&ii);
11051              printf("-- random seed: %d\n", ii);
11052            }
11053            if( nArg==3 ){
11054              db = 0;
11055            }else{
11056              db = p->db;
11057              /* Make sure the schema has been loaded */
11058              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11059            }
11060            rc2 = sqlite3_test_control(testctrl, ii, db);
11061            isOk = 3;
11062          }
11063          break;
11064
11065        /* sqlite3_test_control(int, int) */
11066        case SQLITE_TESTCTRL_ASSERT:
11067        case SQLITE_TESTCTRL_ALWAYS:
11068          if( nArg==3 ){
11069            int opt = booleanValue(azArg[2]);
11070            rc2 = sqlite3_test_control(testctrl, opt);
11071            isOk = 1;
11072          }
11073          break;
11074
11075        /* sqlite3_test_control(int, int) */
11076        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11077        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11078          if( nArg==3 ){
11079            int opt = booleanValue(azArg[2]);
11080            rc2 = sqlite3_test_control(testctrl, opt);
11081            isOk = 3;
11082          }
11083          break;
11084
11085        /* sqlite3_test_control(sqlite3*) */
11086        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11087          rc2 = sqlite3_test_control(testctrl, p->db);
11088          isOk = 3;
11089          break;
11090
11091        case SQLITE_TESTCTRL_IMPOSTER:
11092          if( nArg==5 ){
11093            rc2 = sqlite3_test_control(testctrl, p->db,
11094                          azArg[2],
11095                          integerValue(azArg[3]),
11096                          integerValue(azArg[4]));
11097            isOk = 3;
11098          }
11099          break;
11100
11101        case SQLITE_TESTCTRL_SEEK_COUNT: {
11102          u64 x = 0;
11103          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11104          utf8_printf(p->out, "%llu\n", x);
11105          isOk = 3;
11106          break;
11107        }
11108
11109#ifdef YYCOVERAGE
11110        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11111          if( nArg==2 ){
11112            sqlite3_test_control(testctrl, p->out);
11113            isOk = 3;
11114          }
11115          break;
11116        }
11117#endif
11118#ifdef SQLITE_DEBUG
11119        case SQLITE_TESTCTRL_TUNE: {
11120          if( nArg==4 ){
11121            int id = (int)integerValue(azArg[2]);
11122            int val = (int)integerValue(azArg[3]);
11123            sqlite3_test_control(testctrl, id, &val);
11124            isOk = 3;
11125          }else if( nArg==3 ){
11126            int id = (int)integerValue(azArg[2]);
11127            sqlite3_test_control(testctrl, -id, &rc2);
11128            isOk = 1;
11129          }else if( nArg==2 ){
11130            int id = 1;
11131            while(1){
11132              int val = 0;
11133              rc2 = sqlite3_test_control(testctrl, -id, &val);
11134              if( rc2!=SQLITE_OK ) break;
11135              if( id>1 ) utf8_printf(p->out, "  ");
11136              utf8_printf(p->out, "%d: %d", id, val);
11137              id++;
11138            }
11139            if( id>1 ) utf8_printf(p->out, "\n");
11140            isOk = 3;
11141          }
11142          break;
11143        }
11144#endif
11145        case SQLITE_TESTCTRL_SORTER_MMAP:
11146          if( nArg==3 ){
11147            int opt = (unsigned int)integerValue(azArg[2]);
11148            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11149            isOk = 3;
11150          }
11151          break;
11152      }
11153    }
11154    if( isOk==0 && iCtrl>=0 ){
11155      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11156      rc = 1;
11157    }else if( isOk==1 ){
11158      raw_printf(p->out, "%d\n", rc2);
11159    }else if( isOk==2 ){
11160      raw_printf(p->out, "0x%08x\n", rc2);
11161    }
11162  }else
11163#endif /* !defined(SQLITE_UNTESTABLE) */
11164
11165  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11166    open_db(p, 0);
11167    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11168  }else
11169
11170  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11171    if( nArg==2 ){
11172      enableTimer = booleanValue(azArg[1]);
11173      if( enableTimer && !HAS_TIMER ){
11174        raw_printf(stderr, "Error: timer not available on this system.\n");
11175        enableTimer = 0;
11176      }
11177    }else{
11178      raw_printf(stderr, "Usage: .timer on|off\n");
11179      rc = 1;
11180    }
11181  }else
11182
11183#ifndef SQLITE_OMIT_TRACE
11184  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11185    int mType = 0;
11186    int jj;
11187    open_db(p, 0);
11188    for(jj=1; jj<nArg; jj++){
11189      const char *z = azArg[jj];
11190      if( z[0]=='-' ){
11191        if( optionMatch(z, "expanded") ){
11192          p->eTraceType = SHELL_TRACE_EXPANDED;
11193        }
11194#ifdef SQLITE_ENABLE_NORMALIZE
11195        else if( optionMatch(z, "normalized") ){
11196          p->eTraceType = SHELL_TRACE_NORMALIZED;
11197        }
11198#endif
11199        else if( optionMatch(z, "plain") ){
11200          p->eTraceType = SHELL_TRACE_PLAIN;
11201        }
11202        else if( optionMatch(z, "profile") ){
11203          mType |= SQLITE_TRACE_PROFILE;
11204        }
11205        else if( optionMatch(z, "row") ){
11206          mType |= SQLITE_TRACE_ROW;
11207        }
11208        else if( optionMatch(z, "stmt") ){
11209          mType |= SQLITE_TRACE_STMT;
11210        }
11211        else if( optionMatch(z, "close") ){
11212          mType |= SQLITE_TRACE_CLOSE;
11213        }
11214        else {
11215          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11216          rc = 1;
11217          goto meta_command_exit;
11218        }
11219      }else{
11220        output_file_close(p->traceOut);
11221        p->traceOut = output_file_open(azArg[1], 0);
11222      }
11223    }
11224    if( p->traceOut==0 ){
11225      sqlite3_trace_v2(p->db, 0, 0, 0);
11226    }else{
11227      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11228      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11229    }
11230  }else
11231#endif /* !defined(SQLITE_OMIT_TRACE) */
11232
11233#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11234  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11235    int ii;
11236    int lenOpt;
11237    char *zOpt;
11238    if( nArg<2 ){
11239      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11240      rc = 1;
11241      goto meta_command_exit;
11242    }
11243    open_db(p, 0);
11244    zOpt = azArg[1];
11245    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11246    lenOpt = (int)strlen(zOpt);
11247    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11248      assert( azArg[nArg]==0 );
11249      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11250    }else{
11251      for(ii=1; ii<nArg; ii++){
11252        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11253      }
11254    }
11255  }else
11256#endif
11257
11258#if SQLITE_USER_AUTHENTICATION
11259  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11260    if( nArg<2 ){
11261      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11262      rc = 1;
11263      goto meta_command_exit;
11264    }
11265    open_db(p, 0);
11266    if( strcmp(azArg[1],"login")==0 ){
11267      if( nArg!=4 ){
11268        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11269        rc = 1;
11270        goto meta_command_exit;
11271      }
11272      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11273                                     strlen30(azArg[3]));
11274      if( rc ){
11275        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11276        rc = 1;
11277      }
11278    }else if( strcmp(azArg[1],"add")==0 ){
11279      if( nArg!=5 ){
11280        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11281        rc = 1;
11282        goto meta_command_exit;
11283      }
11284      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11285                            booleanValue(azArg[4]));
11286      if( rc ){
11287        raw_printf(stderr, "User-Add failed: %d\n", rc);
11288        rc = 1;
11289      }
11290    }else if( strcmp(azArg[1],"edit")==0 ){
11291      if( nArg!=5 ){
11292        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11293        rc = 1;
11294        goto meta_command_exit;
11295      }
11296      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11297                              booleanValue(azArg[4]));
11298      if( rc ){
11299        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11300        rc = 1;
11301      }
11302    }else if( strcmp(azArg[1],"delete")==0 ){
11303      if( nArg!=3 ){
11304        raw_printf(stderr, "Usage: .user delete USER\n");
11305        rc = 1;
11306        goto meta_command_exit;
11307      }
11308      rc = sqlite3_user_delete(p->db, azArg[2]);
11309      if( rc ){
11310        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11311        rc = 1;
11312      }
11313    }else{
11314      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11315      rc = 1;
11316      goto meta_command_exit;
11317    }
11318  }else
11319#endif /* SQLITE_USER_AUTHENTICATION */
11320
11321  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11322    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11323        sqlite3_libversion(), sqlite3_sourceid());
11324#if SQLITE_HAVE_ZLIB
11325    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11326#endif
11327#define CTIMEOPT_VAL_(opt) #opt
11328#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11329#if defined(__clang__) && defined(__clang_major__)
11330    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11331                    CTIMEOPT_VAL(__clang_minor__) "."
11332                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11333#elif defined(_MSC_VER)
11334    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11335#elif defined(__GNUC__) && defined(__VERSION__)
11336    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11337#endif
11338  }else
11339
11340  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11341    const char *zDbName = nArg==2 ? azArg[1] : "main";
11342    sqlite3_vfs *pVfs = 0;
11343    if( p->db ){
11344      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11345      if( pVfs ){
11346        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11347        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11348        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11349        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11350      }
11351    }
11352  }else
11353
11354  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11355    sqlite3_vfs *pVfs;
11356    sqlite3_vfs *pCurrent = 0;
11357    if( p->db ){
11358      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11359    }
11360    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11361      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11362           pVfs==pCurrent ? "  <--- CURRENT" : "");
11363      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11364      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11365      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11366      if( pVfs->pNext ){
11367        raw_printf(p->out, "-----------------------------------\n");
11368      }
11369    }
11370  }else
11371
11372  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11373    const char *zDbName = nArg==2 ? azArg[1] : "main";
11374    char *zVfsName = 0;
11375    if( p->db ){
11376      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11377      if( zVfsName ){
11378        utf8_printf(p->out, "%s\n", zVfsName);
11379        sqlite3_free(zVfsName);
11380      }
11381    }
11382  }else
11383
11384  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11385    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11386    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11387  }else
11388
11389  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11390    int j;
11391    assert( nArg<=ArraySize(azArg) );
11392    p->nWidth = nArg-1;
11393    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11394    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11395    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11396    for(j=1; j<nArg; j++){
11397      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11398    }
11399  }else
11400
11401  {
11402    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11403      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11404    rc = 1;
11405  }
11406
11407meta_command_exit:
11408  if( p->outCount ){
11409    p->outCount--;
11410    if( p->outCount==0 ) output_reset(p);
11411  }
11412  p->bSafeMode = p->bSafeModePersist;
11413  return rc;
11414}
11415
11416/* Line scan result and intermediate states (supporting scan resumption)
11417*/
11418#ifndef CHAR_BIT
11419# define CHAR_BIT 8
11420#endif
11421typedef enum {
11422  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11423  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11424  QSS_Start = 0
11425} QuickScanState;
11426#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11427#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11428#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11429#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11430#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11431
11432/*
11433** Scan line for classification to guide shell's handling.
11434** The scan is resumable for subsequent lines when prior
11435** return values are passed as the 2nd argument.
11436*/
11437static QuickScanState quickscan(char *zLine, QuickScanState qss){
11438  char cin;
11439  char cWait = (char)qss; /* intentional narrowing loss */
11440  if( cWait==0 ){
11441  PlainScan:
11442    assert( cWait==0 );
11443    while( (cin = *zLine++)!=0 ){
11444      if( IsSpace(cin) )
11445        continue;
11446      switch (cin){
11447      case '-':
11448        if( *zLine!='-' )
11449          break;
11450        while((cin = *++zLine)!=0 )
11451          if( cin=='\n')
11452            goto PlainScan;
11453        return qss;
11454      case ';':
11455        qss |= QSS_EndingSemi;
11456        continue;
11457      case '/':
11458        if( *zLine=='*' ){
11459          ++zLine;
11460          cWait = '*';
11461          qss = QSS_SETV(qss, cWait);
11462          goto TermScan;
11463        }
11464        break;
11465      case '[':
11466        cin = ']';
11467        /* fall thru */
11468      case '`': case '\'': case '"':
11469        cWait = cin;
11470        qss = QSS_HasDark | cWait;
11471        goto TermScan;
11472      default:
11473        break;
11474      }
11475      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11476    }
11477  }else{
11478  TermScan:
11479    while( (cin = *zLine++)!=0 ){
11480      if( cin==cWait ){
11481        switch( cWait ){
11482        case '*':
11483          if( *zLine != '/' )
11484            continue;
11485          ++zLine;
11486          cWait = 0;
11487          qss = QSS_SETV(qss, 0);
11488          goto PlainScan;
11489        case '`': case '\'': case '"':
11490          if(*zLine==cWait){
11491            ++zLine;
11492            continue;
11493          }
11494          /* fall thru */
11495        case ']':
11496          cWait = 0;
11497          qss = QSS_SETV(qss, 0);
11498          goto PlainScan;
11499        default: assert(0);
11500        }
11501      }
11502    }
11503  }
11504  return qss;
11505}
11506
11507/*
11508** Return TRUE if the line typed in is an SQL command terminator other
11509** than a semi-colon.  The SQL Server style "go" command is understood
11510** as is the Oracle "/".
11511*/
11512static int line_is_command_terminator(char *zLine){
11513  while( IsSpace(zLine[0]) ){ zLine++; };
11514  if( zLine[0]=='/' )
11515    zLine += 1; /* Oracle */
11516  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11517    zLine += 2; /* SQL Server */
11518  else
11519    return 0;
11520  return quickscan(zLine, QSS_Start)==QSS_Start;
11521}
11522
11523/*
11524** We need a default sqlite3_complete() implementation to use in case
11525** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11526** any arbitrary text is a complete SQL statement.  This is not very
11527** user-friendly, but it does seem to work.
11528*/
11529#ifdef SQLITE_OMIT_COMPLETE
11530#define sqlite3_complete(x) 1
11531#endif
11532
11533/*
11534** Return true if zSql is a complete SQL statement.  Return false if it
11535** ends in the middle of a string literal or C-style comment.
11536*/
11537static int line_is_complete(char *zSql, int nSql){
11538  int rc;
11539  if( zSql==0 ) return 1;
11540  zSql[nSql] = ';';
11541  zSql[nSql+1] = 0;
11542  rc = sqlite3_complete(zSql);
11543  zSql[nSql] = 0;
11544  return rc;
11545}
11546
11547/*
11548** Run a single line of SQL.  Return the number of errors.
11549*/
11550static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11551  int rc;
11552  char *zErrMsg = 0;
11553
11554  open_db(p, 0);
11555  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11556  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11557  BEGIN_TIMER;
11558  rc = shell_exec(p, zSql, &zErrMsg);
11559  END_TIMER;
11560  if( rc || zErrMsg ){
11561    char zPrefix[100];
11562    const char *zErrorTail;
11563    const char *zErrorType;
11564    if( zErrMsg==0 ){
11565      zErrorType = "Error";
11566      zErrorTail = sqlite3_errmsg(p->db);
11567    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11568      zErrorType = "Parse error";
11569      zErrorTail = &zErrMsg[12];
11570    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11571      zErrorType = "Runtime error";
11572      zErrorTail = &zErrMsg[10];
11573    }else{
11574      zErrorType = "Error";
11575      zErrorTail = zErrMsg;
11576    }
11577    if( in!=0 || !stdin_is_interactive ){
11578      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11579                       "%s near line %d:", zErrorType, startline);
11580    }else{
11581      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11582    }
11583    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11584    sqlite3_free(zErrMsg);
11585    zErrMsg = 0;
11586    return 1;
11587  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11588    char zLineBuf[2000];
11589    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11590            "changes: %lld   total_changes: %lld",
11591            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11592    raw_printf(p->out, "%s\n", zLineBuf);
11593  }
11594  return 0;
11595}
11596
11597static void echo_group_input(ShellState *p, const char *zDo){
11598  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11599}
11600
11601#ifdef SQLITE_SHELL_FIDDLE
11602/*
11603** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11604** because we need the global shellState and cannot access it from that function
11605** without moving lots of code around (creating a larger/messier diff).
11606*/
11607static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11608  /* Parse the next line from shellState.wasm.zInput. */
11609  const char *zBegin = shellState.wasm.zPos;
11610  const char *z = zBegin;
11611  char *zLine = 0;
11612  int nZ = 0;
11613
11614  UNUSED_PARAMETER(in);
11615  UNUSED_PARAMETER(isContinuation);
11616  if(!z || !*z){
11617    return 0;
11618  }
11619  while(*z && isspace(*z)) ++z;
11620  zBegin = z;
11621  for(; *z && '\n'!=*z; ++nZ, ++z){}
11622  if(nZ>0 && '\r'==zBegin[nZ-1]){
11623    --nZ;
11624  }
11625  shellState.wasm.zPos = z;
11626  zLine = realloc(zPrior, nZ+1);
11627  shell_check_oom(zLine);
11628  memcpy(zLine, zBegin, (size_t)nZ);
11629  zLine[nZ] = 0;
11630  return zLine;
11631}
11632#endif /* SQLITE_SHELL_FIDDLE */
11633
11634/*
11635** Read input from *in and process it.  If *in==0 then input
11636** is interactive - the user is typing it it.  Otherwise, input
11637** is coming from a file or device.  A prompt is issued and history
11638** is saved only if input is interactive.  An interrupt signal will
11639** cause this routine to exit immediately, unless input is interactive.
11640**
11641** Return the number of errors.
11642*/
11643static int process_input(ShellState *p){
11644  char *zLine = 0;          /* A single input line */
11645  char *zSql = 0;           /* Accumulated SQL text */
11646  int nLine;                /* Length of current line */
11647  int nSql = 0;             /* Bytes of zSql[] used */
11648  int nAlloc = 0;           /* Allocated zSql[] space */
11649  int rc;                   /* Error code */
11650  int errCnt = 0;           /* Number of errors seen */
11651  int startline = 0;        /* Line number for start of current input */
11652  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11653
11654  if( p->inputNesting==MAX_INPUT_NESTING ){
11655    /* This will be more informative in a later version. */
11656    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11657                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11658    return 1;
11659  }
11660  ++p->inputNesting;
11661  p->lineno = 0;
11662  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11663    fflush(p->out);
11664    zLine = one_input_line(p->in, zLine, nSql>0);
11665    if( zLine==0 ){
11666      /* End of input */
11667      if( p->in==0 && stdin_is_interactive ) printf("\n");
11668      break;
11669    }
11670    if( seenInterrupt ){
11671      if( p->in!=0 ) break;
11672      seenInterrupt = 0;
11673    }
11674    p->lineno++;
11675    if( QSS_INPLAIN(qss)
11676        && line_is_command_terminator(zLine)
11677        && line_is_complete(zSql, nSql) ){
11678      memcpy(zLine,";",2);
11679    }
11680    qss = quickscan(zLine, qss);
11681    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11682      /* Just swallow single-line whitespace */
11683      echo_group_input(p, zLine);
11684      qss = QSS_Start;
11685      continue;
11686    }
11687    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11688      echo_group_input(p, zLine);
11689      if( zLine[0]=='.' ){
11690        rc = do_meta_command(zLine, p);
11691        if( rc==2 ){ /* exit requested */
11692          break;
11693        }else if( rc ){
11694          errCnt++;
11695        }
11696      }
11697      qss = QSS_Start;
11698      continue;
11699    }
11700    /* No single-line dispositions remain; accumulate line(s). */
11701    nLine = strlen30(zLine);
11702    if( nSql+nLine+2>=nAlloc ){
11703      /* Grow buffer by half-again increments when big. */
11704      nAlloc = nSql+(nSql>>1)+nLine+100;
11705      zSql = realloc(zSql, nAlloc);
11706      shell_check_oom(zSql);
11707    }
11708    if( nSql==0 ){
11709      int i;
11710      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11711      assert( nAlloc>0 && zSql!=0 );
11712      memcpy(zSql, zLine+i, nLine+1-i);
11713      startline = p->lineno;
11714      nSql = nLine-i;
11715    }else{
11716      zSql[nSql++] = '\n';
11717      memcpy(zSql+nSql, zLine, nLine+1);
11718      nSql += nLine;
11719    }
11720    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11721      echo_group_input(p, zSql);
11722      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11723      nSql = 0;
11724      if( p->outCount ){
11725        output_reset(p);
11726        p->outCount = 0;
11727      }else{
11728        clearTempFile(p);
11729      }
11730      p->bSafeMode = p->bSafeModePersist;
11731      qss = QSS_Start;
11732    }else if( nSql && QSS_PLAINWHITE(qss) ){
11733      echo_group_input(p, zSql);
11734      nSql = 0;
11735      qss = QSS_Start;
11736    }
11737  }
11738  if( nSql ){
11739    /* This may be incomplete. Let the SQL parser deal with that. */
11740    echo_group_input(p, zSql);
11741    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11742  }
11743  free(zSql);
11744  free(zLine);
11745  --p->inputNesting;
11746  return errCnt>0;
11747}
11748
11749/*
11750** Return a pathname which is the user's home directory.  A
11751** 0 return indicates an error of some kind.
11752*/
11753static char *find_home_dir(int clearFlag){
11754  static char *home_dir = NULL;
11755  if( clearFlag ){
11756    free(home_dir);
11757    home_dir = 0;
11758    return 0;
11759  }
11760  if( home_dir ) return home_dir;
11761
11762#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11763     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11764  {
11765    struct passwd *pwent;
11766    uid_t uid = getuid();
11767    if( (pwent=getpwuid(uid)) != NULL) {
11768      home_dir = pwent->pw_dir;
11769    }
11770  }
11771#endif
11772
11773#if defined(_WIN32_WCE)
11774  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11775   */
11776  home_dir = "/";
11777#else
11778
11779#if defined(_WIN32) || defined(WIN32)
11780  if (!home_dir) {
11781    home_dir = getenv("USERPROFILE");
11782  }
11783#endif
11784
11785  if (!home_dir) {
11786    home_dir = getenv("HOME");
11787  }
11788
11789#if defined(_WIN32) || defined(WIN32)
11790  if (!home_dir) {
11791    char *zDrive, *zPath;
11792    int n;
11793    zDrive = getenv("HOMEDRIVE");
11794    zPath = getenv("HOMEPATH");
11795    if( zDrive && zPath ){
11796      n = strlen30(zDrive) + strlen30(zPath) + 1;
11797      home_dir = malloc( n );
11798      if( home_dir==0 ) return 0;
11799      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11800      return home_dir;
11801    }
11802    home_dir = "c:\\";
11803  }
11804#endif
11805
11806#endif /* !_WIN32_WCE */
11807
11808  if( home_dir ){
11809    int n = strlen30(home_dir) + 1;
11810    char *z = malloc( n );
11811    if( z ) memcpy(z, home_dir, n);
11812    home_dir = z;
11813  }
11814
11815  return home_dir;
11816}
11817
11818/*
11819** Read input from the file given by sqliterc_override.  Or if that
11820** parameter is NULL, take input from ~/.sqliterc
11821**
11822** Returns the number of errors.
11823*/
11824static void process_sqliterc(
11825  ShellState *p,                  /* Configuration data */
11826  const char *sqliterc_override   /* Name of config file. NULL to use default */
11827){
11828  char *home_dir = NULL;
11829  const char *sqliterc = sqliterc_override;
11830  char *zBuf = 0;
11831  FILE *inSaved = p->in;
11832  int savedLineno = p->lineno;
11833
11834  if (sqliterc == NULL) {
11835    home_dir = find_home_dir(0);
11836    if( home_dir==0 ){
11837      raw_printf(stderr, "-- warning: cannot find home directory;"
11838                      " cannot read ~/.sqliterc\n");
11839      return;
11840    }
11841    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11842    shell_check_oom(zBuf);
11843    sqliterc = zBuf;
11844  }
11845  p->in = fopen(sqliterc,"rb");
11846  if( p->in ){
11847    if( stdin_is_interactive ){
11848      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11849    }
11850    if( process_input(p) && bail_on_error ) exit(1);
11851    fclose(p->in);
11852  }else if( sqliterc_override!=0 ){
11853    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11854    if( bail_on_error ) exit(1);
11855  }
11856  p->in = inSaved;
11857  p->lineno = savedLineno;
11858  sqlite3_free(zBuf);
11859}
11860
11861/*
11862** Show available command line options
11863*/
11864static const char zOptions[] =
11865#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11866  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11867#endif
11868  "   -append              append the database to the end of the file\n"
11869  "   -ascii               set output mode to 'ascii'\n"
11870  "   -bail                stop after hitting an error\n"
11871  "   -batch               force batch I/O\n"
11872  "   -box                 set output mode to 'box'\n"
11873  "   -column              set output mode to 'column'\n"
11874  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11875  "   -csv                 set output mode to 'csv'\n"
11876#if !defined(SQLITE_OMIT_DESERIALIZE)
11877  "   -deserialize         open the database using sqlite3_deserialize()\n"
11878#endif
11879  "   -echo                print inputs before execution\n"
11880  "   -init FILENAME       read/process named file\n"
11881  "   -[no]header          turn headers on or off\n"
11882#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11883  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11884#endif
11885  "   -help                show this message\n"
11886  "   -html                set output mode to HTML\n"
11887  "   -interactive         force interactive I/O\n"
11888  "   -json                set output mode to 'json'\n"
11889  "   -line                set output mode to 'line'\n"
11890  "   -list                set output mode to 'list'\n"
11891  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11892  "   -markdown            set output mode to 'markdown'\n"
11893#if !defined(SQLITE_OMIT_DESERIALIZE)
11894  "   -maxsize N           maximum size for a --deserialize database\n"
11895#endif
11896  "   -memtrace            trace all memory allocations and deallocations\n"
11897  "   -mmap N              default mmap size set to N\n"
11898#ifdef SQLITE_ENABLE_MULTIPLEX
11899  "   -multiplex           enable the multiplexor VFS\n"
11900#endif
11901  "   -newline SEP         set output row separator. Default: '\\n'\n"
11902  "   -nofollow            refuse to open symbolic links to database files\n"
11903  "   -nonce STRING        set the safe-mode escape nonce\n"
11904  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11905  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11906  "   -quote               set output mode to 'quote'\n"
11907  "   -readonly            open the database read-only\n"
11908  "   -safe                enable safe-mode\n"
11909  "   -separator SEP       set output column separator. Default: '|'\n"
11910#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11911  "   -sorterref SIZE      sorter references threshold size\n"
11912#endif
11913  "   -stats               print memory stats before each finalize\n"
11914  "   -table               set output mode to 'table'\n"
11915  "   -tabs                set output mode to 'tabs'\n"
11916  "   -version             show SQLite version\n"
11917  "   -vfs NAME            use NAME as the default VFS\n"
11918#ifdef SQLITE_ENABLE_VFSTRACE
11919  "   -vfstrace            enable tracing of all VFS calls\n"
11920#endif
11921#ifdef SQLITE_HAVE_ZLIB
11922  "   -zip                 open the file as a ZIP Archive\n"
11923#endif
11924;
11925static void usage(int showDetail){
11926  utf8_printf(stderr,
11927      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11928      "FILENAME is the name of an SQLite database. A new database is created\n"
11929      "if the file does not previously exist.\n", Argv0);
11930  if( showDetail ){
11931    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11932  }else{
11933    raw_printf(stderr, "Use the -help option for additional information\n");
11934  }
11935  exit(1);
11936}
11937
11938/*
11939** Internal check:  Verify that the SQLite is uninitialized.  Print a
11940** error message if it is initialized.
11941*/
11942static void verify_uninitialized(void){
11943  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11944    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11945                        " initialization.\n");
11946  }
11947}
11948
11949/*
11950** Initialize the state information in data
11951*/
11952static void main_init(ShellState *data) {
11953  memset(data, 0, sizeof(*data));
11954  data->normalMode = data->cMode = data->mode = MODE_List;
11955  data->autoExplain = 1;
11956  data->pAuxDb = &data->aAuxDb[0];
11957  memcpy(data->colSeparator,SEP_Column, 2);
11958  memcpy(data->rowSeparator,SEP_Row, 2);
11959  data->showHeader = 0;
11960  data->shellFlgs = SHFLG_Lookaside;
11961  verify_uninitialized();
11962  sqlite3_config(SQLITE_CONFIG_URI, 1);
11963  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11964  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11965  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11966  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11967}
11968
11969/*
11970** Output text to the console in a font that attracts extra attention.
11971*/
11972#ifdef _WIN32
11973static void printBold(const char *zText){
11974#if !SQLITE_OS_WINRT
11975  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11976  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11977  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11978  SetConsoleTextAttribute(out,
11979         FOREGROUND_RED|FOREGROUND_INTENSITY
11980  );
11981#endif
11982  printf("%s", zText);
11983#if !SQLITE_OS_WINRT
11984  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11985#endif
11986}
11987#else
11988static void printBold(const char *zText){
11989  printf("\033[1m%s\033[0m", zText);
11990}
11991#endif
11992
11993/*
11994** Get the argument to an --option.  Throw an error and die if no argument
11995** is available.
11996*/
11997static char *cmdline_option_value(int argc, char **argv, int i){
11998  if( i==argc ){
11999    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
12000            argv[0], argv[argc-1]);
12001    exit(1);
12002  }
12003  return argv[i];
12004}
12005
12006#ifndef SQLITE_SHELL_IS_UTF8
12007#  if (defined(_WIN32) || defined(WIN32)) \
12008   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12009#    define SQLITE_SHELL_IS_UTF8          (0)
12010#  else
12011#    define SQLITE_SHELL_IS_UTF8          (1)
12012#  endif
12013#endif
12014
12015#ifdef SQLITE_SHELL_FIDDLE
12016#  define main fiddle_main
12017#endif
12018
12019#if SQLITE_SHELL_IS_UTF8
12020int SQLITE_CDECL main(int argc, char **argv){
12021#else
12022int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12023  char **argv;
12024#endif
12025#ifdef SQLITE_DEBUG
12026  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
12027#endif
12028  char *zErrMsg = 0;
12029#ifdef SQLITE_SHELL_FIDDLE
12030#  define data shellState
12031#else
12032  ShellState data;
12033#endif
12034  const char *zInitFile = 0;
12035  int i;
12036  int rc = 0;
12037  int warnInmemoryDb = 0;
12038  int readStdin = 1;
12039  int nCmd = 0;
12040  char **azCmd = 0;
12041  const char *zVfs = 0;           /* Value of -vfs command-line option */
12042#if !SQLITE_SHELL_IS_UTF8
12043  char **argvToFree = 0;
12044  int argcToFree = 0;
12045#endif
12046
12047  setBinaryMode(stdin, 0);
12048  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12049#ifdef SQLITE_SHELL_FIDDLE
12050  stdin_is_interactive = 0;
12051  stdout_is_console = 1;
12052#else
12053  stdin_is_interactive = isatty(0);
12054  stdout_is_console = isatty(1);
12055#endif
12056
12057#if !defined(_WIN32_WCE)
12058  if( getenv("SQLITE_DEBUG_BREAK") ){
12059    if( isatty(0) && isatty(2) ){
12060      fprintf(stderr,
12061          "attach debugger to process %d and press any key to continue.\n",
12062          GETPID());
12063      fgetc(stdin);
12064    }else{
12065#if defined(_WIN32) || defined(WIN32)
12066#if SQLITE_OS_WINRT
12067      __debugbreak();
12068#else
12069      DebugBreak();
12070#endif
12071#elif defined(SIGTRAP)
12072      raise(SIGTRAP);
12073#endif
12074    }
12075  }
12076#endif
12077
12078#if USE_SYSTEM_SQLITE+0!=1
12079  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12080    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12081            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12082    exit(1);
12083  }
12084#endif
12085  main_init(&data);
12086
12087  /* On Windows, we must translate command-line arguments into UTF-8.
12088  ** The SQLite memory allocator subsystem has to be enabled in order to
12089  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12090  ** subsequent sqlite3_config() calls will work.  So copy all results into
12091  ** memory that does not come from the SQLite memory allocator.
12092  */
12093#if !SQLITE_SHELL_IS_UTF8
12094  sqlite3_initialize();
12095  argvToFree = malloc(sizeof(argv[0])*argc*2);
12096  shell_check_oom(argvToFree);
12097  argcToFree = argc;
12098  argv = argvToFree + argc;
12099  for(i=0; i<argc; i++){
12100    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12101    int n;
12102    shell_check_oom(z);
12103    n = (int)strlen(z);
12104    argv[i] = malloc( n+1 );
12105    shell_check_oom(argv[i]);
12106    memcpy(argv[i], z, n+1);
12107    argvToFree[i] = argv[i];
12108    sqlite3_free(z);
12109  }
12110  sqlite3_shutdown();
12111#endif
12112
12113  assert( argc>=1 && argv && argv[0] );
12114  Argv0 = argv[0];
12115
12116  /* Make sure we have a valid signal handler early, before anything
12117  ** else is done.
12118  */
12119#ifdef SIGINT
12120  signal(SIGINT, interrupt_handler);
12121#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12122  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12123#endif
12124
12125#ifdef SQLITE_SHELL_DBNAME_PROC
12126  {
12127    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12128    ** of a C-function that will provide the name of the database file.  Use
12129    ** this compile-time option to embed this shell program in larger
12130    ** applications. */
12131    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12132    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12133    warnInmemoryDb = 0;
12134  }
12135#endif
12136
12137  /* Do an initial pass through the command-line argument to locate
12138  ** the name of the database file, the name of the initialization file,
12139  ** the size of the alternative malloc heap,
12140  ** and the first command to execute.
12141  */
12142  verify_uninitialized();
12143  for(i=1; i<argc; i++){
12144    char *z;
12145    z = argv[i];
12146    if( z[0]!='-' ){
12147      if( data.aAuxDb->zDbFilename==0 ){
12148        data.aAuxDb->zDbFilename = z;
12149      }else{
12150        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12151        ** mean that nothing is read from stdin */
12152        readStdin = 0;
12153        nCmd++;
12154        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12155        shell_check_oom(azCmd);
12156        azCmd[nCmd-1] = z;
12157      }
12158    }
12159    if( z[1]=='-' ) z++;
12160    if( strcmp(z,"-separator")==0
12161     || strcmp(z,"-nullvalue")==0
12162     || strcmp(z,"-newline")==0
12163     || strcmp(z,"-cmd")==0
12164    ){
12165      (void)cmdline_option_value(argc, argv, ++i);
12166    }else if( strcmp(z,"-init")==0 ){
12167      zInitFile = cmdline_option_value(argc, argv, ++i);
12168    }else if( strcmp(z,"-batch")==0 ){
12169      /* Need to check for batch mode here to so we can avoid printing
12170      ** informational messages (like from process_sqliterc) before
12171      ** we do the actual processing of arguments later in a second pass.
12172      */
12173      stdin_is_interactive = 0;
12174    }else if( strcmp(z,"-heap")==0 ){
12175#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12176      const char *zSize;
12177      sqlite3_int64 szHeap;
12178
12179      zSize = cmdline_option_value(argc, argv, ++i);
12180      szHeap = integerValue(zSize);
12181      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12182      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12183#else
12184      (void)cmdline_option_value(argc, argv, ++i);
12185#endif
12186    }else if( strcmp(z,"-pagecache")==0 ){
12187      sqlite3_int64 n, sz;
12188      sz = integerValue(cmdline_option_value(argc,argv,++i));
12189      if( sz>70000 ) sz = 70000;
12190      if( sz<0 ) sz = 0;
12191      n = integerValue(cmdline_option_value(argc,argv,++i));
12192      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12193        n = 0xffffffffffffLL/sz;
12194      }
12195      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12196                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12197      data.shellFlgs |= SHFLG_Pagecache;
12198    }else if( strcmp(z,"-lookaside")==0 ){
12199      int n, sz;
12200      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12201      if( sz<0 ) sz = 0;
12202      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12203      if( n<0 ) n = 0;
12204      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12205      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12206    }else if( strcmp(z,"-threadsafe")==0 ){
12207      int n;
12208      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12209      switch( n ){
12210         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12211         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12212         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12213      }
12214#ifdef SQLITE_ENABLE_VFSTRACE
12215    }else if( strcmp(z,"-vfstrace")==0 ){
12216      extern int vfstrace_register(
12217         const char *zTraceName,
12218         const char *zOldVfsName,
12219         int (*xOut)(const char*,void*),
12220         void *pOutArg,
12221         int makeDefault
12222      );
12223      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12224#endif
12225#ifdef SQLITE_ENABLE_MULTIPLEX
12226    }else if( strcmp(z,"-multiplex")==0 ){
12227      extern int sqlite3_multiple_initialize(const char*,int);
12228      sqlite3_multiplex_initialize(0, 1);
12229#endif
12230    }else if( strcmp(z,"-mmap")==0 ){
12231      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12232      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12233#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12234    }else if( strcmp(z,"-sorterref")==0 ){
12235      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12236      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12237#endif
12238    }else if( strcmp(z,"-vfs")==0 ){
12239      zVfs = cmdline_option_value(argc, argv, ++i);
12240#ifdef SQLITE_HAVE_ZLIB
12241    }else if( strcmp(z,"-zip")==0 ){
12242      data.openMode = SHELL_OPEN_ZIPFILE;
12243#endif
12244    }else if( strcmp(z,"-append")==0 ){
12245      data.openMode = SHELL_OPEN_APPENDVFS;
12246#ifndef SQLITE_OMIT_DESERIALIZE
12247    }else if( strcmp(z,"-deserialize")==0 ){
12248      data.openMode = SHELL_OPEN_DESERIALIZE;
12249    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12250      data.szMax = integerValue(argv[++i]);
12251#endif
12252    }else if( strcmp(z,"-readonly")==0 ){
12253      data.openMode = SHELL_OPEN_READONLY;
12254    }else if( strcmp(z,"-nofollow")==0 ){
12255      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12256#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12257    }else if( strncmp(z, "-A",2)==0 ){
12258      /* All remaining command-line arguments are passed to the ".archive"
12259      ** command, so ignore them */
12260      break;
12261#endif
12262    }else if( strcmp(z, "-memtrace")==0 ){
12263      sqlite3MemTraceActivate(stderr);
12264    }else if( strcmp(z,"-bail")==0 ){
12265      bail_on_error = 1;
12266    }else if( strcmp(z,"-nonce")==0 ){
12267      free(data.zNonce);
12268      data.zNonce = strdup(argv[++i]);
12269    }else if( strcmp(z,"-safe")==0 ){
12270      /* no-op - catch this on the second pass */
12271    }
12272  }
12273  verify_uninitialized();
12274
12275
12276#ifdef SQLITE_SHELL_INIT_PROC
12277  {
12278    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12279    ** of a C-function that will perform initialization actions on SQLite that
12280    ** occur just before or after sqlite3_initialize(). Use this compile-time
12281    ** option to embed this shell program in larger applications. */
12282    extern void SQLITE_SHELL_INIT_PROC(void);
12283    SQLITE_SHELL_INIT_PROC();
12284  }
12285#else
12286  /* All the sqlite3_config() calls have now been made. So it is safe
12287  ** to call sqlite3_initialize() and process any command line -vfs option. */
12288  sqlite3_initialize();
12289#endif
12290
12291  if( zVfs ){
12292    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12293    if( pVfs ){
12294      sqlite3_vfs_register(pVfs, 1);
12295    }else{
12296      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12297      exit(1);
12298    }
12299  }
12300
12301  if( data.pAuxDb->zDbFilename==0 ){
12302#ifndef SQLITE_OMIT_MEMORYDB
12303    data.pAuxDb->zDbFilename = ":memory:";
12304    warnInmemoryDb = argc==1;
12305#else
12306    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12307    return 1;
12308#endif
12309  }
12310  data.out = stdout;
12311#ifndef SQLITE_SHELL_FIDDLE
12312  sqlite3_appendvfs_init(0,0,0);
12313#endif
12314
12315  /* Go ahead and open the database file if it already exists.  If the
12316  ** file does not exist, delay opening it.  This prevents empty database
12317  ** files from being created if a user mistypes the database name argument
12318  ** to the sqlite command-line tool.
12319  */
12320  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12321    open_db(&data, 0);
12322  }
12323
12324  /* Process the initialization file if there is one.  If no -init option
12325  ** is given on the command line, look for a file named ~/.sqliterc and
12326  ** try to process it.
12327  */
12328  process_sqliterc(&data,zInitFile);
12329
12330  /* Make a second pass through the command-line argument and set
12331  ** options.  This second pass is delayed until after the initialization
12332  ** file is processed so that the command-line arguments will override
12333  ** settings in the initialization file.
12334  */
12335  for(i=1; i<argc; i++){
12336    char *z = argv[i];
12337    if( z[0]!='-' ) continue;
12338    if( z[1]=='-' ){ z++; }
12339    if( strcmp(z,"-init")==0 ){
12340      i++;
12341    }else if( strcmp(z,"-html")==0 ){
12342      data.mode = MODE_Html;
12343    }else if( strcmp(z,"-list")==0 ){
12344      data.mode = MODE_List;
12345    }else if( strcmp(z,"-quote")==0 ){
12346      data.mode = MODE_Quote;
12347      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12348      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12349    }else if( strcmp(z,"-line")==0 ){
12350      data.mode = MODE_Line;
12351    }else if( strcmp(z,"-column")==0 ){
12352      data.mode = MODE_Column;
12353    }else if( strcmp(z,"-json")==0 ){
12354      data.mode = MODE_Json;
12355    }else if( strcmp(z,"-markdown")==0 ){
12356      data.mode = MODE_Markdown;
12357    }else if( strcmp(z,"-table")==0 ){
12358      data.mode = MODE_Table;
12359    }else if( strcmp(z,"-box")==0 ){
12360      data.mode = MODE_Box;
12361    }else if( strcmp(z,"-csv")==0 ){
12362      data.mode = MODE_Csv;
12363      memcpy(data.colSeparator,",",2);
12364#ifdef SQLITE_HAVE_ZLIB
12365    }else if( strcmp(z,"-zip")==0 ){
12366      data.openMode = SHELL_OPEN_ZIPFILE;
12367#endif
12368    }else if( strcmp(z,"-append")==0 ){
12369      data.openMode = SHELL_OPEN_APPENDVFS;
12370#ifndef SQLITE_OMIT_DESERIALIZE
12371    }else if( strcmp(z,"-deserialize")==0 ){
12372      data.openMode = SHELL_OPEN_DESERIALIZE;
12373    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12374      data.szMax = integerValue(argv[++i]);
12375#endif
12376    }else if( strcmp(z,"-readonly")==0 ){
12377      data.openMode = SHELL_OPEN_READONLY;
12378    }else if( strcmp(z,"-nofollow")==0 ){
12379      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12380    }else if( strcmp(z,"-ascii")==0 ){
12381      data.mode = MODE_Ascii;
12382      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12383      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12384    }else if( strcmp(z,"-tabs")==0 ){
12385      data.mode = MODE_List;
12386      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12387      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12388    }else if( strcmp(z,"-separator")==0 ){
12389      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12390                       "%s",cmdline_option_value(argc,argv,++i));
12391    }else if( strcmp(z,"-newline")==0 ){
12392      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12393                       "%s",cmdline_option_value(argc,argv,++i));
12394    }else if( strcmp(z,"-nullvalue")==0 ){
12395      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12396                       "%s",cmdline_option_value(argc,argv,++i));
12397    }else if( strcmp(z,"-header")==0 ){
12398      data.showHeader = 1;
12399      ShellSetFlag(&data, SHFLG_HeaderSet);
12400     }else if( strcmp(z,"-noheader")==0 ){
12401      data.showHeader = 0;
12402      ShellSetFlag(&data, SHFLG_HeaderSet);
12403    }else if( strcmp(z,"-echo")==0 ){
12404      ShellSetFlag(&data, SHFLG_Echo);
12405    }else if( strcmp(z,"-eqp")==0 ){
12406      data.autoEQP = AUTOEQP_on;
12407    }else if( strcmp(z,"-eqpfull")==0 ){
12408      data.autoEQP = AUTOEQP_full;
12409    }else if( strcmp(z,"-stats")==0 ){
12410      data.statsOn = 1;
12411    }else if( strcmp(z,"-scanstats")==0 ){
12412      data.scanstatsOn = 1;
12413    }else if( strcmp(z,"-backslash")==0 ){
12414      /* Undocumented command-line option: -backslash
12415      ** Causes C-style backslash escapes to be evaluated in SQL statements
12416      ** prior to sending the SQL into SQLite.  Useful for injecting
12417      ** crazy bytes in the middle of SQL statements for testing and debugging.
12418      */
12419      ShellSetFlag(&data, SHFLG_Backslash);
12420    }else if( strcmp(z,"-bail")==0 ){
12421      /* No-op.  The bail_on_error flag should already be set. */
12422    }else if( strcmp(z,"-version")==0 ){
12423      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12424      return 0;
12425    }else if( strcmp(z,"-interactive")==0 ){
12426      stdin_is_interactive = 1;
12427    }else if( strcmp(z,"-batch")==0 ){
12428      stdin_is_interactive = 0;
12429    }else if( strcmp(z,"-heap")==0 ){
12430      i++;
12431    }else if( strcmp(z,"-pagecache")==0 ){
12432      i+=2;
12433    }else if( strcmp(z,"-lookaside")==0 ){
12434      i+=2;
12435    }else if( strcmp(z,"-threadsafe")==0 ){
12436      i+=2;
12437    }else if( strcmp(z,"-nonce")==0 ){
12438      i += 2;
12439    }else if( strcmp(z,"-mmap")==0 ){
12440      i++;
12441    }else if( strcmp(z,"-memtrace")==0 ){
12442      i++;
12443#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12444    }else if( strcmp(z,"-sorterref")==0 ){
12445      i++;
12446#endif
12447    }else if( strcmp(z,"-vfs")==0 ){
12448      i++;
12449#ifdef SQLITE_ENABLE_VFSTRACE
12450    }else if( strcmp(z,"-vfstrace")==0 ){
12451      i++;
12452#endif
12453#ifdef SQLITE_ENABLE_MULTIPLEX
12454    }else if( strcmp(z,"-multiplex")==0 ){
12455      i++;
12456#endif
12457    }else if( strcmp(z,"-help")==0 ){
12458      usage(1);
12459    }else if( strcmp(z,"-cmd")==0 ){
12460      /* Run commands that follow -cmd first and separately from commands
12461      ** that simply appear on the command-line.  This seems goofy.  It would
12462      ** be better if all commands ran in the order that they appear.  But
12463      ** we retain the goofy behavior for historical compatibility. */
12464      if( i==argc-1 ) break;
12465      z = cmdline_option_value(argc,argv,++i);
12466      if( z[0]=='.' ){
12467        rc = do_meta_command(z, &data);
12468        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12469      }else{
12470        open_db(&data, 0);
12471        rc = shell_exec(&data, z, &zErrMsg);
12472        if( zErrMsg!=0 ){
12473          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12474          if( bail_on_error ) return rc!=0 ? rc : 1;
12475        }else if( rc!=0 ){
12476          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12477          if( bail_on_error ) return rc;
12478        }
12479      }
12480#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12481    }else if( strncmp(z, "-A", 2)==0 ){
12482      if( nCmd>0 ){
12483        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12484                            " with \"%s\"\n", z);
12485        return 1;
12486      }
12487      open_db(&data, OPEN_DB_ZIPFILE);
12488      if( z[2] ){
12489        argv[i] = &z[2];
12490        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12491      }else{
12492        arDotCommand(&data, 1, argv+i, argc-i);
12493      }
12494      readStdin = 0;
12495      break;
12496#endif
12497    }else if( strcmp(z,"-safe")==0 ){
12498      data.bSafeMode = data.bSafeModePersist = 1;
12499    }else{
12500      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12501      raw_printf(stderr,"Use -help for a list of options.\n");
12502      return 1;
12503    }
12504    data.cMode = data.mode;
12505  }
12506
12507  if( !readStdin ){
12508    /* Run all arguments that do not begin with '-' as if they were separate
12509    ** command-line inputs, except for the argToSkip argument which contains
12510    ** the database filename.
12511    */
12512    for(i=0; i<nCmd; i++){
12513      if( azCmd[i][0]=='.' ){
12514        rc = do_meta_command(azCmd[i], &data);
12515        if( rc ){
12516          free(azCmd);
12517          return rc==2 ? 0 : rc;
12518        }
12519      }else{
12520        open_db(&data, 0);
12521        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12522        if( zErrMsg || rc ){
12523          if( zErrMsg!=0 ){
12524            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12525          }else{
12526            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12527          }
12528          sqlite3_free(zErrMsg);
12529          free(azCmd);
12530          return rc!=0 ? rc : 1;
12531        }
12532      }
12533    }
12534  }else{
12535    /* Run commands received from standard input
12536    */
12537    if( stdin_is_interactive ){
12538      char *zHome;
12539      char *zHistory;
12540      int nHistory;
12541      printf(
12542        "SQLite version %s %.19s\n" /*extra-version-info*/
12543        "Enter \".help\" for usage hints.\n",
12544        sqlite3_libversion(), sqlite3_sourceid()
12545      );
12546      if( warnInmemoryDb ){
12547        printf("Connected to a ");
12548        printBold("transient in-memory database");
12549        printf(".\nUse \".open FILENAME\" to reopen on a "
12550               "persistent database.\n");
12551      }
12552      zHistory = getenv("SQLITE_HISTORY");
12553      if( zHistory ){
12554        zHistory = strdup(zHistory);
12555      }else if( (zHome = find_home_dir(0))!=0 ){
12556        nHistory = strlen30(zHome) + 20;
12557        if( (zHistory = malloc(nHistory))!=0 ){
12558          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12559        }
12560      }
12561      if( zHistory ){ shell_read_history(zHistory); }
12562#if HAVE_READLINE || HAVE_EDITLINE
12563      rl_attempted_completion_function = readline_completion;
12564#elif HAVE_LINENOISE
12565      linenoiseSetCompletionCallback(linenoise_completion);
12566#endif
12567      data.in = 0;
12568      rc = process_input(&data);
12569      if( zHistory ){
12570        shell_stifle_history(2000);
12571        shell_write_history(zHistory);
12572        free(zHistory);
12573      }
12574    }else{
12575      data.in = stdin;
12576      rc = process_input(&data);
12577    }
12578  }
12579#ifndef SQLITE_SHELL_FIDDLE
12580  /* In WASM mode we have to leave the db state in place so that
12581  ** client code can "push" SQL into it after this call returns. */
12582  free(azCmd);
12583  set_table_name(&data, 0);
12584  if( data.db ){
12585    session_close_all(&data, -1);
12586    close_db(data.db);
12587  }
12588  for(i=0; i<ArraySize(data.aAuxDb); i++){
12589    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12590    if( data.aAuxDb[i].db ){
12591      session_close_all(&data, i);
12592      close_db(data.aAuxDb[i].db);
12593    }
12594  }
12595  find_home_dir(1);
12596  output_reset(&data);
12597  data.doXdgOpen = 0;
12598  clearTempFile(&data);
12599#if !SQLITE_SHELL_IS_UTF8
12600  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12601  free(argvToFree);
12602#endif
12603  free(data.colWidth);
12604  free(data.zNonce);
12605  /* Clear the global data structure so that valgrind will detect memory
12606  ** leaks */
12607  memset(&data, 0, sizeof(data));
12608#ifdef SQLITE_DEBUG
12609  if( sqlite3_memory_used()>mem_main_enter ){
12610    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12611                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12612  }
12613#endif
12614#endif /* !SQLITE_SHELL_FIDDLE */
12615  return rc;
12616}
12617
12618
12619#ifdef SQLITE_SHELL_FIDDLE
12620/* Only for emcc experimentation purposes. */
12621int fiddle_experiment(int a,int b){
12622   return a + b;
12623}
12624
12625/* Only for emcc experimentation purposes.
12626
12627  Define this function in JS using:
12628
12629  emcc ... --js-library somefile.js
12630
12631  containing:
12632
12633mergeInto(LibraryManager.library, {
12634    my_foo: function(){
12635        console.debug("my_foo()",arguments);
12636    }
12637});
12638*/
12639/*extern void my_foo(sqlite3 *);*/
12640/* Only for emcc experimentation purposes. */
12641sqlite3 * fiddle_the_db(){
12642    printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12643    /*my_foo(globalDb);*/
12644    return globalDb;
12645}
12646/* Only for emcc experimentation purposes. */
12647sqlite3 * fiddle_db_arg(sqlite3 *arg){
12648    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12649    return arg;
12650}
12651
12652/*
12653** Intended to be called via a SharedWorker() while a separate
12654** SharedWorker() (which manages the wasm module) is performing work
12655** which should be interrupted. Unfortunately, SharedWorker is not
12656** portable enough to make real use of.
12657*/
12658void fiddle_interrupt(void){
12659  if(globalDb) sqlite3_interrupt(globalDb);
12660}
12661
12662/*
12663** Returns the filename of the given db name, assuming "main" if
12664** zDbName is NULL. Returns NULL if globalDb is not opened.
12665*/
12666const char * fiddle_db_filename(const char * zDbName){
12667    return globalDb
12668      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12669      : NULL;
12670}
12671
12672/*
12673** Closes, unlinks, and reopens the db using its current filename (or
12674** the default if the db is currently closed). It is assumed, for
12675** purposes of the fiddle build, that the file is in a transient
12676** virtual filesystem within the browser.
12677*/
12678void fiddle_reset_db(void){
12679  char *zFilename = 0;
12680  if(0==globalDb){
12681    shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12682  }else{
12683    zFilename =
12684      sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12685    shell_check_oom(zFilename);
12686    close_db(globalDb);
12687    shellDeleteFile(zFilename);
12688    shellState.db = 0;
12689    shellState.pAuxDb->zDbFilename = zFilename;
12690  }
12691  open_db(&shellState, 0);
12692  sqlite3_free(zFilename);
12693}
12694
12695/*
12696** Trivial exportable function for emscripten. Needs to be exported using:
12697**
12698** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12699**
12700** (Note the underscore before the function name.) It processes zSql
12701** as if it were input to the sqlite3 shell and redirects all output
12702** to the wasm binding.
12703*/
12704void fiddle_exec(const char * zSql){
12705  static int once = 0;
12706  int rc = 0;
12707  if(!once){
12708    /* Simulate an argv array for main() */
12709    static char * argv[] = {"fiddle",
12710                            "-bail",
12711                            "-safe"};
12712    rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12713    once = rc ? -1 : 1;
12714    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12715    printf(
12716        "SQLite version %s %.19s\n" /*extra-version-info*/,
12717        sqlite3_libversion(), sqlite3_sourceid()
12718    );
12719    puts("WASM shell");
12720    puts("Enter \".help\" for usage hints.");
12721    if(once>0){
12722      fiddle_reset_db();
12723    }
12724    if(shellState.db){
12725      printf("Connected to %s.\n", fiddle_db_filename(NULL));
12726    }else{
12727      fprintf(stderr,"ERROR initializing db!\n");
12728      return;
12729    }
12730  }
12731  if(once<0){
12732    puts("DB init failed. Not executing SQL.");
12733  }else if(zSql && *zSql){
12734    shellState.wasm.zInput = zSql;
12735    shellState.wasm.zPos = zSql;
12736    process_input(&shellState);
12737    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12738  }
12739}
12740#endif /* SQLITE_SHELL_FIDDLE */
12741