xref: /sqlite-3.40.0/src/shell.c.in (revision 78ed74ef)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26# define SHELL_STRINGIFY_(f) #f
27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28#ifdef SQLITE_CUSTOM_INCLUDE
29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
42** somewhat for use as a WASM module in a web browser. This flag
43** should only be used when building the "fiddle" web application, as
44** the browser-mode build has much different user input requirements
45** and this build mode rewires the user input subsystem to account for
46** that.
47*/
48
49/*
50** Warning pragmas copied from msvc.h in the core.
51*/
52#if defined(_MSC_VER)
53#pragma warning(disable : 4054)
54#pragma warning(disable : 4055)
55#pragma warning(disable : 4100)
56#pragma warning(disable : 4127)
57#pragma warning(disable : 4130)
58#pragma warning(disable : 4152)
59#pragma warning(disable : 4189)
60#pragma warning(disable : 4206)
61#pragma warning(disable : 4210)
62#pragma warning(disable : 4232)
63#pragma warning(disable : 4244)
64#pragma warning(disable : 4305)
65#pragma warning(disable : 4306)
66#pragma warning(disable : 4702)
67#pragma warning(disable : 4706)
68#endif /* defined(_MSC_VER) */
69
70/*
71** No support for loadable extensions in VxWorks.
72*/
73#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
74# define SQLITE_OMIT_LOAD_EXTENSION 1
75#endif
76
77/*
78** Enable large-file support for fopen() and friends on unix.
79*/
80#ifndef SQLITE_DISABLE_LFS
81# define _LARGE_FILE       1
82# ifndef _FILE_OFFSET_BITS
83#   define _FILE_OFFSET_BITS 64
84# endif
85# define _LARGEFILE_SOURCE 1
86#endif
87
88#include <stdlib.h>
89#include <string.h>
90#include <stdio.h>
91#include <assert.h>
92#include "sqlite3.h"
93typedef sqlite3_int64 i64;
94typedef sqlite3_uint64 u64;
95typedef unsigned char u8;
96#if SQLITE_USER_AUTHENTICATION
97# include "sqlite3userauth.h"
98#endif
99#include <ctype.h>
100#include <stdarg.h>
101
102#if !defined(_WIN32) && !defined(WIN32)
103# include <signal.h>
104# if !defined(__RTP__) && !defined(_WRS_KERNEL)
105#  include <pwd.h>
106# endif
107#endif
108#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
109# include <unistd.h>
110# include <dirent.h>
111# define GETPID getpid
112# if defined(__MINGW32__)
113#  define DIRENT dirent
114#  ifndef S_ISLNK
115#   define S_ISLNK(mode) (0)
116#  endif
117# endif
118#else
119# define GETPID (int)GetCurrentProcessId
120#endif
121#include <sys/types.h>
122#include <sys/stat.h>
123
124#if HAVE_READLINE
125# include <readline/readline.h>
126# include <readline/history.h>
127#endif
128
129#if HAVE_EDITLINE
130# include <editline/readline.h>
131#endif
132
133#if HAVE_EDITLINE || HAVE_READLINE
134
135# define shell_add_history(X) add_history(X)
136# define shell_read_history(X) read_history(X)
137# define shell_write_history(X) write_history(X)
138# define shell_stifle_history(X) stifle_history(X)
139# define shell_readline(X) readline(X)
140
141#elif HAVE_LINENOISE
142
143# include "linenoise.h"
144# define shell_add_history(X) linenoiseHistoryAdd(X)
145# define shell_read_history(X) linenoiseHistoryLoad(X)
146# define shell_write_history(X) linenoiseHistorySave(X)
147# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
148# define shell_readline(X) linenoise(X)
149
150#else
151
152# define shell_read_history(X)
153# define shell_write_history(X)
154# define shell_stifle_history(X)
155
156# define SHELL_USE_LOCAL_GETLINE 1
157#endif
158
159
160#if defined(_WIN32) || defined(WIN32)
161# if SQLITE_OS_WINRT
162#  define SQLITE_OMIT_POPEN 1
163# else
164#  include <io.h>
165#  include <fcntl.h>
166#  define isatty(h) _isatty(h)
167#  ifndef access
168#   define access(f,m) _access((f),(m))
169#  endif
170#  ifndef unlink
171#   define unlink _unlink
172#  endif
173#  ifndef strdup
174#   define strdup _strdup
175#  endif
176#  undef popen
177#  define popen _popen
178#  undef pclose
179#  define pclose _pclose
180# endif
181#else
182 /* Make sure isatty() has a prototype. */
183 extern int isatty(int);
184
185# if !defined(__RTP__) && !defined(_WRS_KERNEL)
186  /* popen and pclose are not C89 functions and so are
187  ** sometimes omitted from the <stdio.h> header */
188   extern FILE *popen(const char*,const char*);
189   extern int pclose(FILE*);
190# else
191#  define SQLITE_OMIT_POPEN 1
192# endif
193#endif
194
195#if defined(_WIN32_WCE)
196/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
197 * thus we always assume that we have a console. That can be
198 * overridden with the -batch command line option.
199 */
200#define isatty(x) 1
201#endif
202
203/* ctype macros that work with signed characters */
204#define IsSpace(X)  isspace((unsigned char)X)
205#define IsDigit(X)  isdigit((unsigned char)X)
206#define ToLower(X)  (char)tolower((unsigned char)X)
207
208#if defined(_WIN32) || defined(WIN32)
209#if SQLITE_OS_WINRT
210#include <intrin.h>
211#endif
212#include <windows.h>
213
214/* string conversion routines only needed on Win32 */
215extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
216extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
217extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
218extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
219#endif
220
221/* On Windows, we normally run with output mode of TEXT so that \n characters
222** are automatically translated into \r\n.  However, this behavior needs
223** to be disabled in some cases (ex: when generating CSV output and when
224** rendering quoted strings that contain \n characters).  The following
225** routines take care of that.
226*/
227#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
228static void setBinaryMode(FILE *file, int isOutput){
229  if( isOutput ) fflush(file);
230  _setmode(_fileno(file), _O_BINARY);
231}
232static void setTextMode(FILE *file, int isOutput){
233  if( isOutput ) fflush(file);
234  _setmode(_fileno(file), _O_TEXT);
235}
236#else
237# define setBinaryMode(X,Y)
238# define setTextMode(X,Y)
239#endif
240
241/* True if the timer is enabled */
242static int enableTimer = 0;
243
244/* Return the current wall-clock time */
245static sqlite3_int64 timeOfDay(void){
246  static sqlite3_vfs *clockVfs = 0;
247  sqlite3_int64 t;
248  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
249  if( clockVfs==0 ) return 0;  /* Never actually happens */
250  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
251    clockVfs->xCurrentTimeInt64(clockVfs, &t);
252  }else{
253    double r;
254    clockVfs->xCurrentTime(clockVfs, &r);
255    t = (sqlite3_int64)(r*86400000.0);
256  }
257  return t;
258}
259
260#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
261#include <sys/time.h>
262#include <sys/resource.h>
263
264/* VxWorks does not support getrusage() as far as we can determine */
265#if defined(_WRS_KERNEL) || defined(__RTP__)
266struct rusage {
267  struct timeval ru_utime; /* user CPU time used */
268  struct timeval ru_stime; /* system CPU time used */
269};
270#define getrusage(A,B) memset(B,0,sizeof(*B))
271#endif
272
273/* Saved resource information for the beginning of an operation */
274static struct rusage sBegin;  /* CPU time at start */
275static sqlite3_int64 iBegin;  /* Wall-clock time at start */
276
277/*
278** Begin timing an operation
279*/
280static void beginTimer(void){
281  if( enableTimer ){
282    getrusage(RUSAGE_SELF, &sBegin);
283    iBegin = timeOfDay();
284  }
285}
286
287/* Return the difference of two time_structs in seconds */
288static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
289  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
290         (double)(pEnd->tv_sec - pStart->tv_sec);
291}
292
293/*
294** Print the timing results.
295*/
296static void endTimer(void){
297  if( enableTimer ){
298    sqlite3_int64 iEnd = timeOfDay();
299    struct rusage sEnd;
300    getrusage(RUSAGE_SELF, &sEnd);
301    printf("Run Time: real %.3f user %f sys %f\n",
302       (iEnd - iBegin)*0.001,
303       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
304       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
305  }
306}
307
308#define BEGIN_TIMER beginTimer()
309#define END_TIMER endTimer()
310#define HAS_TIMER 1
311
312#elif (defined(_WIN32) || defined(WIN32))
313
314/* Saved resource information for the beginning of an operation */
315static HANDLE hProcess;
316static FILETIME ftKernelBegin;
317static FILETIME ftUserBegin;
318static sqlite3_int64 ftWallBegin;
319typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
320                                    LPFILETIME, LPFILETIME);
321static GETPROCTIMES getProcessTimesAddr = NULL;
322
323/*
324** Check to see if we have timer support.  Return 1 if necessary
325** support found (or found previously).
326*/
327static int hasTimer(void){
328  if( getProcessTimesAddr ){
329    return 1;
330  } else {
331#if !SQLITE_OS_WINRT
332    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
333    ** versions. See if the version we are running on has it, and if it
334    ** does, save off a pointer to it and the current process handle.
335    */
336    hProcess = GetCurrentProcess();
337    if( hProcess ){
338      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
339      if( NULL != hinstLib ){
340        getProcessTimesAddr =
341            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
342        if( NULL != getProcessTimesAddr ){
343          return 1;
344        }
345        FreeLibrary(hinstLib);
346      }
347    }
348#endif
349  }
350  return 0;
351}
352
353/*
354** Begin timing an operation
355*/
356static void beginTimer(void){
357  if( enableTimer && getProcessTimesAddr ){
358    FILETIME ftCreation, ftExit;
359    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
360                        &ftKernelBegin,&ftUserBegin);
361    ftWallBegin = timeOfDay();
362  }
363}
364
365/* Return the difference of two FILETIME structs in seconds */
366static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
367  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
368  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
369  return (double) ((i64End - i64Start) / 10000000.0);
370}
371
372/*
373** Print the timing results.
374*/
375static void endTimer(void){
376  if( enableTimer && getProcessTimesAddr){
377    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
378    sqlite3_int64 ftWallEnd = timeOfDay();
379    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
380    printf("Run Time: real %.3f user %f sys %f\n",
381       (ftWallEnd - ftWallBegin)*0.001,
382       timeDiff(&ftUserBegin, &ftUserEnd),
383       timeDiff(&ftKernelBegin, &ftKernelEnd));
384  }
385}
386
387#define BEGIN_TIMER beginTimer()
388#define END_TIMER endTimer()
389#define HAS_TIMER hasTimer()
390
391#else
392#define BEGIN_TIMER
393#define END_TIMER
394#define HAS_TIMER 0
395#endif
396
397/*
398** Used to prevent warnings about unused parameters
399*/
400#define UNUSED_PARAMETER(x) (void)(x)
401
402/*
403** Number of elements in an array
404*/
405#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
406
407/*
408** If the following flag is set, then command execution stops
409** at an error if we are not interactive.
410*/
411static int bail_on_error = 0;
412
413/*
414** Threat stdin as an interactive input if the following variable
415** is true.  Otherwise, assume stdin is connected to a file or pipe.
416*/
417static int stdin_is_interactive = 1;
418
419/*
420** On Windows systems we have to know if standard output is a console
421** in order to translate UTF-8 into MBCS.  The following variable is
422** true if translation is required.
423*/
424static int stdout_is_console = 1;
425
426/*
427** The following is the open SQLite database.  We make a pointer
428** to this database a static variable so that it can be accessed
429** by the SIGINT handler to interrupt database processing.
430*/
431static sqlite3 *globalDb = 0;
432
433/*
434** True if an interrupt (Control-C) has been received.
435*/
436static volatile int seenInterrupt = 0;
437
438/*
439** This is the name of our program. It is set in main(), used
440** in a number of other places, mostly for error messages.
441*/
442static char *Argv0;
443
444/*
445** Prompt strings. Initialized in main. Settable with
446**   .prompt main continue
447*/
448static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
449static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
450
451/*
452** Render output like fprintf().  Except, if the output is going to the
453** console and if this is running on a Windows machine, translate the
454** output from UTF-8 into MBCS.
455*/
456#if defined(_WIN32) || defined(WIN32)
457void utf8_printf(FILE *out, const char *zFormat, ...){
458  va_list ap;
459  va_start(ap, zFormat);
460  if( stdout_is_console && (out==stdout || out==stderr) ){
461    char *z1 = sqlite3_vmprintf(zFormat, ap);
462    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
463    sqlite3_free(z1);
464    fputs(z2, out);
465    sqlite3_free(z2);
466  }else{
467    vfprintf(out, zFormat, ap);
468  }
469  va_end(ap);
470}
471#elif !defined(utf8_printf)
472# define utf8_printf fprintf
473#endif
474
475/*
476** Render output like fprintf().  This should not be used on anything that
477** includes string formatting (e.g. "%s").
478*/
479#if !defined(raw_printf)
480# define raw_printf fprintf
481#endif
482
483/* Indicate out-of-memory and exit. */
484static void shell_out_of_memory(void){
485  raw_printf(stderr,"Error: out of memory\n");
486  exit(1);
487}
488
489/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
490** out-of-memory error.
491*/
492static void shell_check_oom(void *p){
493  if( p==0 ) shell_out_of_memory();
494}
495
496/*
497** Write I/O traces to the following stream.
498*/
499#ifdef SQLITE_ENABLE_IOTRACE
500static FILE *iotrace = 0;
501#endif
502
503/*
504** This routine works like printf in that its first argument is a
505** format string and subsequent arguments are values to be substituted
506** in place of % fields.  The result of formatting this string
507** is written to iotrace.
508*/
509#ifdef SQLITE_ENABLE_IOTRACE
510static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
511  va_list ap;
512  char *z;
513  if( iotrace==0 ) return;
514  va_start(ap, zFormat);
515  z = sqlite3_vmprintf(zFormat, ap);
516  va_end(ap);
517  utf8_printf(iotrace, "%s", z);
518  sqlite3_free(z);
519}
520#endif
521
522/*
523** Output string zUtf to stream pOut as w characters.  If w is negative,
524** then right-justify the text.  W is the width in UTF-8 characters, not
525** in bytes.  This is different from the %*.*s specification in printf
526** since with %*.*s the width is measured in bytes, not characters.
527*/
528static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
529  int i;
530  int n;
531  int aw = w<0 ? -w : w;
532  for(i=n=0; zUtf[i]; i++){
533    if( (zUtf[i]&0xc0)!=0x80 ){
534      n++;
535      if( n==aw ){
536        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
537        break;
538      }
539    }
540  }
541  if( n>=aw ){
542    utf8_printf(pOut, "%.*s", i, zUtf);
543  }else if( w<0 ){
544    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
545  }else{
546    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
547  }
548}
549
550
551/*
552** Determines if a string is a number of not.
553*/
554static int isNumber(const char *z, int *realnum){
555  if( *z=='-' || *z=='+' ) z++;
556  if( !IsDigit(*z) ){
557    return 0;
558  }
559  z++;
560  if( realnum ) *realnum = 0;
561  while( IsDigit(*z) ){ z++; }
562  if( *z=='.' ){
563    z++;
564    if( !IsDigit(*z) ) return 0;
565    while( IsDigit(*z) ){ z++; }
566    if( realnum ) *realnum = 1;
567  }
568  if( *z=='e' || *z=='E' ){
569    z++;
570    if( *z=='+' || *z=='-' ) z++;
571    if( !IsDigit(*z) ) return 0;
572    while( IsDigit(*z) ){ z++; }
573    if( realnum ) *realnum = 1;
574  }
575  return *z==0;
576}
577
578/*
579** Compute a string length that is limited to what can be stored in
580** lower 30 bits of a 32-bit signed integer.
581*/
582static int strlen30(const char *z){
583  const char *z2 = z;
584  while( *z2 ){ z2++; }
585  return 0x3fffffff & (int)(z2 - z);
586}
587
588/*
589** Return the length of a string in characters.  Multibyte UTF8 characters
590** count as a single character.
591*/
592static int strlenChar(const char *z){
593  int n = 0;
594  while( *z ){
595    if( (0xc0&*(z++))!=0x80 ) n++;
596  }
597  return n;
598}
599
600/*
601** Return open FILE * if zFile exists, can be opened for read
602** and is an ordinary file or a character stream source.
603** Otherwise return 0.
604*/
605static FILE * openChrSource(const char *zFile){
606#ifdef _WIN32
607  struct _stat x = {0};
608# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
609  /* On Windows, open first, then check the stream nature. This order
610  ** is necessary because _stat() and sibs, when checking a named pipe,
611  ** effectively break the pipe as its supplier sees it. */
612  FILE *rv = fopen(zFile, "rb");
613  if( rv==0 ) return 0;
614  if( _fstat(_fileno(rv), &x) != 0
615      || !STAT_CHR_SRC(x.st_mode)){
616    fclose(rv);
617    rv = 0;
618  }
619  return rv;
620#else
621  struct stat x = {0};
622  int rc = stat(zFile, &x);
623# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
624  if( rc!=0 ) return 0;
625  if( STAT_CHR_SRC(x.st_mode) ){
626    return fopen(zFile, "rb");
627  }else{
628    return 0;
629  }
630#endif
631#undef STAT_CHR_SRC
632}
633
634/*
635** This routine reads a line of text from FILE in, stores
636** the text in memory obtained from malloc() and returns a pointer
637** to the text.  NULL is returned at end of file, or if malloc()
638** fails.
639**
640** If zLine is not NULL then it is a malloced buffer returned from
641** a previous call to this routine that may be reused.
642*/
643static char *local_getline(char *zLine, FILE *in){
644  int nLine = zLine==0 ? 0 : 100;
645  int n = 0;
646
647  while( 1 ){
648    if( n+100>nLine ){
649      nLine = nLine*2 + 100;
650      zLine = realloc(zLine, nLine);
651      shell_check_oom(zLine);
652    }
653    if( fgets(&zLine[n], nLine - n, in)==0 ){
654      if( n==0 ){
655        free(zLine);
656        return 0;
657      }
658      zLine[n] = 0;
659      break;
660    }
661    while( zLine[n] ) n++;
662    if( n>0 && zLine[n-1]=='\n' ){
663      n--;
664      if( n>0 && zLine[n-1]=='\r' ) n--;
665      zLine[n] = 0;
666      break;
667    }
668  }
669#if defined(_WIN32) || defined(WIN32)
670  /* For interactive input on Windows systems, translate the
671  ** multi-byte characterset characters into UTF-8. */
672  if( stdin_is_interactive && in==stdin ){
673    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
674    if( zTrans ){
675      int nTrans = strlen30(zTrans)+1;
676      if( nTrans>nLine ){
677        zLine = realloc(zLine, nTrans);
678        shell_check_oom(zLine);
679      }
680      memcpy(zLine, zTrans, nTrans);
681      sqlite3_free(zTrans);
682    }
683  }
684#endif /* defined(_WIN32) || defined(WIN32) */
685  return zLine;
686}
687
688/*
689** Retrieve a single line of input text.
690**
691** If in==0 then read from standard input and prompt before each line.
692** If isContinuation is true, then a continuation prompt is appropriate.
693** If isContinuation is zero, then the main prompt should be used.
694**
695** If zPrior is not NULL then it is a buffer from a prior call to this
696** routine that can be reused.
697**
698** The result is stored in space obtained from malloc() and must either
699** be freed by the caller or else passed back into this routine via the
700** zPrior argument for reuse.
701*/
702#ifndef SQLITE_SHELL_FIDDLE
703static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
704  char *zPrompt;
705  char *zResult;
706  if( in!=0 ){
707    zResult = local_getline(zPrior, in);
708  }else{
709    zPrompt = isContinuation ? continuePrompt : mainPrompt;
710#if SHELL_USE_LOCAL_GETLINE
711    printf("%s", zPrompt);
712    fflush(stdout);
713    zResult = local_getline(zPrior, stdin);
714#else
715    free(zPrior);
716    zResult = shell_readline(zPrompt);
717    if( zResult && *zResult ) shell_add_history(zResult);
718#endif
719  }
720  return zResult;
721}
722#endif /* !SQLITE_SHELL_FIDDLE */
723
724/*
725** Return the value of a hexadecimal digit.  Return -1 if the input
726** is not a hex digit.
727*/
728static int hexDigitValue(char c){
729  if( c>='0' && c<='9' ) return c - '0';
730  if( c>='a' && c<='f' ) return c - 'a' + 10;
731  if( c>='A' && c<='F' ) return c - 'A' + 10;
732  return -1;
733}
734
735/*
736** Interpret zArg as an integer value, possibly with suffixes.
737*/
738static sqlite3_int64 integerValue(const char *zArg){
739  sqlite3_int64 v = 0;
740  static const struct { char *zSuffix; int iMult; } aMult[] = {
741    { "KiB", 1024 },
742    { "MiB", 1024*1024 },
743    { "GiB", 1024*1024*1024 },
744    { "KB",  1000 },
745    { "MB",  1000000 },
746    { "GB",  1000000000 },
747    { "K",   1000 },
748    { "M",   1000000 },
749    { "G",   1000000000 },
750  };
751  int i;
752  int isNeg = 0;
753  if( zArg[0]=='-' ){
754    isNeg = 1;
755    zArg++;
756  }else if( zArg[0]=='+' ){
757    zArg++;
758  }
759  if( zArg[0]=='0' && zArg[1]=='x' ){
760    int x;
761    zArg += 2;
762    while( (x = hexDigitValue(zArg[0]))>=0 ){
763      v = (v<<4) + x;
764      zArg++;
765    }
766  }else{
767    while( IsDigit(zArg[0]) ){
768      v = v*10 + zArg[0] - '0';
769      zArg++;
770    }
771  }
772  for(i=0; i<ArraySize(aMult); i++){
773    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
774      v *= aMult[i].iMult;
775      break;
776    }
777  }
778  return isNeg? -v : v;
779}
780
781/*
782** A variable length string to which one can append text.
783*/
784typedef struct ShellText ShellText;
785struct ShellText {
786  char *z;
787  int n;
788  int nAlloc;
789};
790
791/*
792** Initialize and destroy a ShellText object
793*/
794static void initText(ShellText *p){
795  memset(p, 0, sizeof(*p));
796}
797static void freeText(ShellText *p){
798  free(p->z);
799  initText(p);
800}
801
802/* zIn is either a pointer to a NULL-terminated string in memory obtained
803** from malloc(), or a NULL pointer. The string pointed to by zAppend is
804** added to zIn, and the result returned in memory obtained from malloc().
805** zIn, if it was not NULL, is freed.
806**
807** If the third argument, quote, is not '\0', then it is used as a
808** quote character for zAppend.
809*/
810static void appendText(ShellText *p, const char *zAppend, char quote){
811  int len;
812  int i;
813  int nAppend = strlen30(zAppend);
814
815  len = nAppend+p->n+1;
816  if( quote ){
817    len += 2;
818    for(i=0; i<nAppend; i++){
819      if( zAppend[i]==quote ) len++;
820    }
821  }
822
823  if( p->z==0 || p->n+len>=p->nAlloc ){
824    p->nAlloc = p->nAlloc*2 + len + 20;
825    p->z = realloc(p->z, p->nAlloc);
826    shell_check_oom(p->z);
827  }
828
829  if( quote ){
830    char *zCsr = p->z+p->n;
831    *zCsr++ = quote;
832    for(i=0; i<nAppend; i++){
833      *zCsr++ = zAppend[i];
834      if( zAppend[i]==quote ) *zCsr++ = quote;
835    }
836    *zCsr++ = quote;
837    p->n = (int)(zCsr - p->z);
838    *zCsr = '\0';
839  }else{
840    memcpy(p->z+p->n, zAppend, nAppend);
841    p->n += nAppend;
842    p->z[p->n] = '\0';
843  }
844}
845
846/*
847** Attempt to determine if identifier zName needs to be quoted, either
848** because it contains non-alphanumeric characters, or because it is an
849** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
850** that quoting is required.
851**
852** Return '"' if quoting is required.  Return 0 if no quoting is required.
853*/
854static char quoteChar(const char *zName){
855  int i;
856  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
857  for(i=0; zName[i]; i++){
858    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
859  }
860  return sqlite3_keyword_check(zName, i) ? '"' : 0;
861}
862
863/*
864** Construct a fake object name and column list to describe the structure
865** of the view, virtual table, or table valued function zSchema.zName.
866*/
867static char *shellFakeSchema(
868  sqlite3 *db,            /* The database connection containing the vtab */
869  const char *zSchema,    /* Schema of the database holding the vtab */
870  const char *zName       /* The name of the virtual table */
871){
872  sqlite3_stmt *pStmt = 0;
873  char *zSql;
874  ShellText s;
875  char cQuote;
876  char *zDiv = "(";
877  int nRow = 0;
878
879  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
880                         zSchema ? zSchema : "main", zName);
881  shell_check_oom(zSql);
882  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
883  sqlite3_free(zSql);
884  initText(&s);
885  if( zSchema ){
886    cQuote = quoteChar(zSchema);
887    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
888    appendText(&s, zSchema, cQuote);
889    appendText(&s, ".", 0);
890  }
891  cQuote = quoteChar(zName);
892  appendText(&s, zName, cQuote);
893  while( sqlite3_step(pStmt)==SQLITE_ROW ){
894    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
895    nRow++;
896    appendText(&s, zDiv, 0);
897    zDiv = ",";
898    if( zCol==0 ) zCol = "";
899    cQuote = quoteChar(zCol);
900    appendText(&s, zCol, cQuote);
901  }
902  appendText(&s, ")", 0);
903  sqlite3_finalize(pStmt);
904  if( nRow==0 ){
905    freeText(&s);
906    s.z = 0;
907  }
908  return s.z;
909}
910
911/*
912** SQL function:  shell_module_schema(X)
913**
914** Return a fake schema for the table-valued function or eponymous virtual
915** table X.
916*/
917static void shellModuleSchema(
918  sqlite3_context *pCtx,
919  int nVal,
920  sqlite3_value **apVal
921){
922  const char *zName;
923  char *zFake;
924  UNUSED_PARAMETER(nVal);
925  zName = (const char*)sqlite3_value_text(apVal[0]);
926  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
927  if( zFake ){
928    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
929                        -1, sqlite3_free);
930    free(zFake);
931  }
932}
933
934/*
935** SQL function:  shell_add_schema(S,X)
936**
937** Add the schema name X to the CREATE statement in S and return the result.
938** Examples:
939**
940**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
941**
942** Also works on
943**
944**    CREATE INDEX
945**    CREATE UNIQUE INDEX
946**    CREATE VIEW
947**    CREATE TRIGGER
948**    CREATE VIRTUAL TABLE
949**
950** This UDF is used by the .schema command to insert the schema name of
951** attached databases into the middle of the sqlite_schema.sql field.
952*/
953static void shellAddSchemaName(
954  sqlite3_context *pCtx,
955  int nVal,
956  sqlite3_value **apVal
957){
958  static const char *aPrefix[] = {
959     "TABLE",
960     "INDEX",
961     "UNIQUE INDEX",
962     "VIEW",
963     "TRIGGER",
964     "VIRTUAL TABLE"
965  };
966  int i = 0;
967  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
968  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
969  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
970  sqlite3 *db = sqlite3_context_db_handle(pCtx);
971  UNUSED_PARAMETER(nVal);
972  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
973    for(i=0; i<ArraySize(aPrefix); i++){
974      int n = strlen30(aPrefix[i]);
975      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
976        char *z = 0;
977        char *zFake = 0;
978        if( zSchema ){
979          char cQuote = quoteChar(zSchema);
980          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
981            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
982          }else{
983            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
984          }
985        }
986        if( zName
987         && aPrefix[i][0]=='V'
988         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
989        ){
990          if( z==0 ){
991            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
992          }else{
993            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
994          }
995          free(zFake);
996        }
997        if( z ){
998          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
999          return;
1000        }
1001      }
1002    }
1003  }
1004  sqlite3_result_value(pCtx, apVal[0]);
1005}
1006
1007/*
1008** The source code for several run-time loadable extensions is inserted
1009** below by the ../tool/mkshellc.tcl script.  Before processing that included
1010** code, we need to override some macros to make the included program code
1011** work here in the middle of this regular program.
1012*/
1013#define SQLITE_EXTENSION_INIT1
1014#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1015
1016#if defined(_WIN32) && defined(_MSC_VER)
1017INCLUDE test_windirent.h
1018INCLUDE test_windirent.c
1019#define dirent DIRENT
1020#endif
1021INCLUDE ../ext/misc/memtrace.c
1022INCLUDE ../ext/misc/shathree.c
1023INCLUDE ../ext/misc/uint.c
1024INCLUDE ../ext/misc/decimal.c
1025INCLUDE ../ext/misc/ieee754.c
1026INCLUDE ../ext/misc/series.c
1027INCLUDE ../ext/misc/regexp.c
1028#ifndef SQLITE_SHELL_FIDDLE
1029INCLUDE ../ext/misc/fileio.c
1030INCLUDE ../ext/misc/completion.c
1031INCLUDE ../ext/misc/appendvfs.c
1032#endif
1033#ifdef SQLITE_HAVE_ZLIB
1034INCLUDE ../ext/misc/zipfile.c
1035INCLUDE ../ext/misc/sqlar.c
1036#endif
1037INCLUDE ../ext/expert/sqlite3expert.h
1038INCLUDE ../ext/expert/sqlite3expert.c
1039
1040#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1041INCLUDE ../ext/misc/dbdata.c
1042#endif
1043
1044#if defined(SQLITE_ENABLE_SESSION)
1045/*
1046** State information for a single open session
1047*/
1048typedef struct OpenSession OpenSession;
1049struct OpenSession {
1050  char *zName;             /* Symbolic name for this session */
1051  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1052  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1053  sqlite3_session *p;      /* The open session */
1054};
1055#endif
1056
1057typedef struct ExpertInfo ExpertInfo;
1058struct ExpertInfo {
1059  sqlite3expert *pExpert;
1060  int bVerbose;
1061};
1062
1063/* A single line in the EQP output */
1064typedef struct EQPGraphRow EQPGraphRow;
1065struct EQPGraphRow {
1066  int iEqpId;           /* ID for this row */
1067  int iParentId;        /* ID of the parent row */
1068  EQPGraphRow *pNext;   /* Next row in sequence */
1069  char zText[1];        /* Text to display for this row */
1070};
1071
1072/* All EQP output is collected into an instance of the following */
1073typedef struct EQPGraph EQPGraph;
1074struct EQPGraph {
1075  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1076  EQPGraphRow *pLast;   /* Last element of the pRow list */
1077  char zPrefix[100];    /* Graph prefix */
1078};
1079
1080/* Parameters affecting columnar mode result display (defaulting together) */
1081typedef struct ColModeOpts {
1082  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1083  u8 bQuote;            /* Quote results for .mode box and table */
1084  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1085} ColModeOpts;
1086#define ColModeOpts_default { 60, 0, 0 }
1087#define ColModeOpts_default_qbox { 60, 1, 0 }
1088
1089/*
1090** State information about the database connection is contained in an
1091** instance of the following structure.
1092*/
1093typedef struct ShellState ShellState;
1094struct ShellState {
1095  sqlite3 *db;           /* The database */
1096  u8 autoExplain;        /* Automatically turn on .explain mode */
1097  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1098  u8 autoEQPtest;        /* autoEQP is in test mode */
1099  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1100  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1101  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1102  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1103  u8 nEqpLevel;          /* Depth of the EQP output graph */
1104  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1105  u8 bSafeMode;          /* True to prohibit unsafe operations */
1106  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1107  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1108  unsigned statsOn;      /* True to display memory stats before each finalize */
1109  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1110  int inputNesting;      /* Track nesting level of .read and other redirects */
1111  int outCount;          /* Revert to stdout when reaching zero */
1112  int cnt;               /* Number of records displayed so far */
1113  int lineno;            /* Line number of last line read from in */
1114  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1115  FILE *in;              /* Read commands from this stream */
1116  FILE *out;             /* Write results here */
1117  FILE *traceOut;        /* Output for sqlite3_trace() */
1118  int nErr;              /* Number of errors seen */
1119  int mode;              /* An output mode setting */
1120  int modePrior;         /* Saved mode */
1121  int cMode;             /* temporary output mode for the current query */
1122  int normalMode;        /* Output mode before ".explain on" */
1123  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1124  int showHeader;        /* True to show column names in List or Column mode */
1125  int nCheck;            /* Number of ".check" commands run */
1126  unsigned nProgress;    /* Number of progress callbacks encountered */
1127  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1128  unsigned flgProgress;  /* Flags for the progress callback */
1129  unsigned shellFlgs;    /* Various flags */
1130  unsigned priorShFlgs;  /* Saved copy of flags */
1131  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1132  char *zDestTable;      /* Name of destination table when MODE_Insert */
1133  char *zTempFile;       /* Temporary file that might need deleting */
1134  char zTestcase[30];    /* Name of current test case */
1135  char colSeparator[20]; /* Column separator character for several modes */
1136  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1137  char colSepPrior[20];  /* Saved column separator */
1138  char rowSepPrior[20];  /* Saved row separator */
1139  int *colWidth;         /* Requested width of each column in columnar modes */
1140  int *actualWidth;      /* Actual width of each column */
1141  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1142  char nullValue[20];    /* The text to print when a NULL comes back from
1143                         ** the database */
1144  char outfile[FILENAME_MAX]; /* Filename for *out */
1145  sqlite3_stmt *pStmt;   /* Current statement if any. */
1146  FILE *pLog;            /* Write log output here */
1147  struct AuxDb {         /* Storage space for auxiliary database connections */
1148    sqlite3 *db;               /* Connection pointer */
1149    const char *zDbFilename;   /* Filename used to open the connection */
1150    char *zFreeOnClose;        /* Free this memory allocation on close */
1151#if defined(SQLITE_ENABLE_SESSION)
1152    int nSession;              /* Number of active sessions */
1153    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1154#endif
1155  } aAuxDb[5],           /* Array of all database connections */
1156    *pAuxDb;             /* Currently active database connection */
1157  int *aiIndent;         /* Array of indents used in MODE_Explain */
1158  int nIndent;           /* Size of array aiIndent[] */
1159  int iIndent;           /* Index of current op in aiIndent[] */
1160  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1161  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1162  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1163#ifdef SQLITE_SHELL_FIDDLE
1164  struct {
1165    const char * zInput; /* Input string from wasm/JS proxy */
1166    const char * zPos;   /* Cursor pos into zInput */
1167  } wasm;
1168#endif
1169};
1170
1171#ifdef SQLITE_SHELL_FIDDLE
1172static ShellState shellState;
1173#endif
1174
1175
1176/* Allowed values for ShellState.autoEQP
1177*/
1178#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1179#define AUTOEQP_on       1           /* Automatic EQP is on */
1180#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1181#define AUTOEQP_full     3           /* Show full EXPLAIN */
1182
1183/* Allowed values for ShellState.openMode
1184*/
1185#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1186#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1187#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1188#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1189#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1190#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1191#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1192
1193/* Allowed values for ShellState.eTraceType
1194*/
1195#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1196#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1197#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1198
1199/* Bits in the ShellState.flgProgress variable */
1200#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1201#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1202                                   ** callback limit is reached, and for each
1203                                   ** top-level SQL statement */
1204#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1205
1206/*
1207** These are the allowed shellFlgs values
1208*/
1209#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1210#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1211#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1212#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1213#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1214#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1215#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1216#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1217#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1218#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1219
1220/*
1221** Macros for testing and setting shellFlgs
1222*/
1223#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1224#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1225#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1226
1227/*
1228** These are the allowed modes.
1229*/
1230#define MODE_Line     0  /* One column per line.  Blank line between records */
1231#define MODE_Column   1  /* One record per line in neat columns */
1232#define MODE_List     2  /* One record per line with a separator */
1233#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1234#define MODE_Html     4  /* Generate an XHTML table */
1235#define MODE_Insert   5  /* Generate SQL "insert" statements */
1236#define MODE_Quote    6  /* Quote values as for SQL */
1237#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1238#define MODE_Csv      8  /* Quote strings, numbers are plain */
1239#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1240#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1241#define MODE_Pretty  11  /* Pretty-print schemas */
1242#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1243#define MODE_Json    13  /* Output JSON */
1244#define MODE_Markdown 14 /* Markdown formatting */
1245#define MODE_Table   15  /* MySQL-style table formatting */
1246#define MODE_Box     16  /* Unicode box-drawing characters */
1247#define MODE_Count   17  /* Output only a count of the rows of output */
1248#define MODE_Off     18  /* No query output shown */
1249
1250static const char *modeDescr[] = {
1251  "line",
1252  "column",
1253  "list",
1254  "semi",
1255  "html",
1256  "insert",
1257  "quote",
1258  "tcl",
1259  "csv",
1260  "explain",
1261  "ascii",
1262  "prettyprint",
1263  "eqp",
1264  "json",
1265  "markdown",
1266  "table",
1267  "box",
1268  "count",
1269  "off"
1270};
1271
1272/*
1273** These are the column/row/line separators used by the various
1274** import/export modes.
1275*/
1276#define SEP_Column    "|"
1277#define SEP_Row       "\n"
1278#define SEP_Tab       "\t"
1279#define SEP_Space     " "
1280#define SEP_Comma     ","
1281#define SEP_CrLf      "\r\n"
1282#define SEP_Unit      "\x1F"
1283#define SEP_Record    "\x1E"
1284
1285/*
1286** Limit input nesting via .read or any other input redirect.
1287** It's not too expensive, so a generous allowance can be made.
1288*/
1289#define MAX_INPUT_NESTING 25
1290
1291/*
1292** A callback for the sqlite3_log() interface.
1293*/
1294static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1295  ShellState *p = (ShellState*)pArg;
1296  if( p->pLog==0 ) return;
1297  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1298  fflush(p->pLog);
1299}
1300
1301/*
1302** SQL function:  shell_putsnl(X)
1303**
1304** Write the text X to the screen (or whatever output is being directed)
1305** adding a newline at the end, and then return X.
1306*/
1307static void shellPutsFunc(
1308  sqlite3_context *pCtx,
1309  int nVal,
1310  sqlite3_value **apVal
1311){
1312  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1313  (void)nVal;
1314  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1315  sqlite3_result_value(pCtx, apVal[0]);
1316}
1317
1318/*
1319** If in safe mode, print an error message described by the arguments
1320** and exit immediately.
1321*/
1322static void failIfSafeMode(
1323  ShellState *p,
1324  const char *zErrMsg,
1325  ...
1326){
1327  if( p->bSafeMode ){
1328    va_list ap;
1329    char *zMsg;
1330    va_start(ap, zErrMsg);
1331    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1332    va_end(ap);
1333    raw_printf(stderr, "line %d: ", p->lineno);
1334    utf8_printf(stderr, "%s\n", zMsg);
1335    exit(1);
1336  }
1337}
1338
1339/*
1340** SQL function:   edit(VALUE)
1341**                 edit(VALUE,EDITOR)
1342**
1343** These steps:
1344**
1345**     (1) Write VALUE into a temporary file.
1346**     (2) Run program EDITOR on that temporary file.
1347**     (3) Read the temporary file back and return its content as the result.
1348**     (4) Delete the temporary file
1349**
1350** If the EDITOR argument is omitted, use the value in the VISUAL
1351** environment variable.  If still there is no EDITOR, through an error.
1352**
1353** Also throw an error if the EDITOR program returns a non-zero exit code.
1354*/
1355#ifndef SQLITE_NOHAVE_SYSTEM
1356static void editFunc(
1357  sqlite3_context *context,
1358  int argc,
1359  sqlite3_value **argv
1360){
1361  const char *zEditor;
1362  char *zTempFile = 0;
1363  sqlite3 *db;
1364  char *zCmd = 0;
1365  int bBin;
1366  int rc;
1367  int hasCRNL = 0;
1368  FILE *f = 0;
1369  sqlite3_int64 sz;
1370  sqlite3_int64 x;
1371  unsigned char *p = 0;
1372
1373  if( argc==2 ){
1374    zEditor = (const char*)sqlite3_value_text(argv[1]);
1375  }else{
1376    zEditor = getenv("VISUAL");
1377  }
1378  if( zEditor==0 ){
1379    sqlite3_result_error(context, "no editor for edit()", -1);
1380    return;
1381  }
1382  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1383    sqlite3_result_error(context, "NULL input to edit()", -1);
1384    return;
1385  }
1386  db = sqlite3_context_db_handle(context);
1387  zTempFile = 0;
1388  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1389  if( zTempFile==0 ){
1390    sqlite3_uint64 r = 0;
1391    sqlite3_randomness(sizeof(r), &r);
1392    zTempFile = sqlite3_mprintf("temp%llx", r);
1393    if( zTempFile==0 ){
1394      sqlite3_result_error_nomem(context);
1395      return;
1396    }
1397  }
1398  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1399  /* When writing the file to be edited, do \n to \r\n conversions on systems
1400  ** that want \r\n line endings */
1401  f = fopen(zTempFile, bBin ? "wb" : "w");
1402  if( f==0 ){
1403    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1404    goto edit_func_end;
1405  }
1406  sz = sqlite3_value_bytes(argv[0]);
1407  if( bBin ){
1408    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1409  }else{
1410    const char *z = (const char*)sqlite3_value_text(argv[0]);
1411    /* Remember whether or not the value originally contained \r\n */
1412    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1413    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1414  }
1415  fclose(f);
1416  f = 0;
1417  if( x!=sz ){
1418    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1419    goto edit_func_end;
1420  }
1421  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1422  if( zCmd==0 ){
1423    sqlite3_result_error_nomem(context);
1424    goto edit_func_end;
1425  }
1426  rc = system(zCmd);
1427  sqlite3_free(zCmd);
1428  if( rc ){
1429    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1430    goto edit_func_end;
1431  }
1432  f = fopen(zTempFile, "rb");
1433  if( f==0 ){
1434    sqlite3_result_error(context,
1435      "edit() cannot reopen temp file after edit", -1);
1436    goto edit_func_end;
1437  }
1438  fseek(f, 0, SEEK_END);
1439  sz = ftell(f);
1440  rewind(f);
1441  p = sqlite3_malloc64( sz+1 );
1442  if( p==0 ){
1443    sqlite3_result_error_nomem(context);
1444    goto edit_func_end;
1445  }
1446  x = fread(p, 1, (size_t)sz, f);
1447  fclose(f);
1448  f = 0;
1449  if( x!=sz ){
1450    sqlite3_result_error(context, "could not read back the whole file", -1);
1451    goto edit_func_end;
1452  }
1453  if( bBin ){
1454    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1455  }else{
1456    sqlite3_int64 i, j;
1457    if( hasCRNL ){
1458      /* If the original contains \r\n then do no conversions back to \n */
1459    }else{
1460      /* If the file did not originally contain \r\n then convert any new
1461      ** \r\n back into \n */
1462      for(i=j=0; i<sz; i++){
1463        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1464        p[j++] = p[i];
1465      }
1466      sz = j;
1467      p[sz] = 0;
1468    }
1469    sqlite3_result_text64(context, (const char*)p, sz,
1470                          sqlite3_free, SQLITE_UTF8);
1471  }
1472  p = 0;
1473
1474edit_func_end:
1475  if( f ) fclose(f);
1476  unlink(zTempFile);
1477  sqlite3_free(zTempFile);
1478  sqlite3_free(p);
1479}
1480#endif /* SQLITE_NOHAVE_SYSTEM */
1481
1482/*
1483** Save or restore the current output mode
1484*/
1485static void outputModePush(ShellState *p){
1486  p->modePrior = p->mode;
1487  p->priorShFlgs = p->shellFlgs;
1488  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1489  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1490}
1491static void outputModePop(ShellState *p){
1492  p->mode = p->modePrior;
1493  p->shellFlgs = p->priorShFlgs;
1494  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1495  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1496}
1497
1498/*
1499** Output the given string as a hex-encoded blob (eg. X'1234' )
1500*/
1501static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1502  int i;
1503  char *zBlob = (char *)pBlob;
1504  raw_printf(out,"X'");
1505  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1506  raw_printf(out,"'");
1507}
1508
1509/*
1510** Find a string that is not found anywhere in z[].  Return a pointer
1511** to that string.
1512**
1513** Try to use zA and zB first.  If both of those are already found in z[]
1514** then make up some string and store it in the buffer zBuf.
1515*/
1516static const char *unused_string(
1517  const char *z,                    /* Result must not appear anywhere in z */
1518  const char *zA, const char *zB,   /* Try these first */
1519  char *zBuf                        /* Space to store a generated string */
1520){
1521  unsigned i = 0;
1522  if( strstr(z, zA)==0 ) return zA;
1523  if( strstr(z, zB)==0 ) return zB;
1524  do{
1525    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1526  }while( strstr(z,zBuf)!=0 );
1527  return zBuf;
1528}
1529
1530/*
1531** Output the given string as a quoted string using SQL quoting conventions.
1532**
1533** See also: output_quoted_escaped_string()
1534*/
1535static void output_quoted_string(FILE *out, const char *z){
1536  int i;
1537  char c;
1538  setBinaryMode(out, 1);
1539  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1540  if( c==0 ){
1541    utf8_printf(out,"'%s'",z);
1542  }else{
1543    raw_printf(out, "'");
1544    while( *z ){
1545      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1546      if( c=='\'' ) i++;
1547      if( i ){
1548        utf8_printf(out, "%.*s", i, z);
1549        z += i;
1550      }
1551      if( c=='\'' ){
1552        raw_printf(out, "'");
1553        continue;
1554      }
1555      if( c==0 ){
1556        break;
1557      }
1558      z++;
1559    }
1560    raw_printf(out, "'");
1561  }
1562  setTextMode(out, 1);
1563}
1564
1565/*
1566** Output the given string as a quoted string using SQL quoting conventions.
1567** Additionallly , escape the "\n" and "\r" characters so that they do not
1568** get corrupted by end-of-line translation facilities in some operating
1569** systems.
1570**
1571** This is like output_quoted_string() but with the addition of the \r\n
1572** escape mechanism.
1573*/
1574static void output_quoted_escaped_string(FILE *out, const char *z){
1575  int i;
1576  char c;
1577  setBinaryMode(out, 1);
1578  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1579  if( c==0 ){
1580    utf8_printf(out,"'%s'",z);
1581  }else{
1582    const char *zNL = 0;
1583    const char *zCR = 0;
1584    int nNL = 0;
1585    int nCR = 0;
1586    char zBuf1[20], zBuf2[20];
1587    for(i=0; z[i]; i++){
1588      if( z[i]=='\n' ) nNL++;
1589      if( z[i]=='\r' ) nCR++;
1590    }
1591    if( nNL ){
1592      raw_printf(out, "replace(");
1593      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1594    }
1595    if( nCR ){
1596      raw_printf(out, "replace(");
1597      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1598    }
1599    raw_printf(out, "'");
1600    while( *z ){
1601      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1602      if( c=='\'' ) i++;
1603      if( i ){
1604        utf8_printf(out, "%.*s", i, z);
1605        z += i;
1606      }
1607      if( c=='\'' ){
1608        raw_printf(out, "'");
1609        continue;
1610      }
1611      if( c==0 ){
1612        break;
1613      }
1614      z++;
1615      if( c=='\n' ){
1616        raw_printf(out, "%s", zNL);
1617        continue;
1618      }
1619      raw_printf(out, "%s", zCR);
1620    }
1621    raw_printf(out, "'");
1622    if( nCR ){
1623      raw_printf(out, ",'%s',char(13))", zCR);
1624    }
1625    if( nNL ){
1626      raw_printf(out, ",'%s',char(10))", zNL);
1627    }
1628  }
1629  setTextMode(out, 1);
1630}
1631
1632/*
1633** Output the given string as a quoted according to C or TCL quoting rules.
1634*/
1635static void output_c_string(FILE *out, const char *z){
1636  unsigned int c;
1637  fputc('"', out);
1638  while( (c = *(z++))!=0 ){
1639    if( c=='\\' ){
1640      fputc(c, out);
1641      fputc(c, out);
1642    }else if( c=='"' ){
1643      fputc('\\', out);
1644      fputc('"', out);
1645    }else if( c=='\t' ){
1646      fputc('\\', out);
1647      fputc('t', out);
1648    }else if( c=='\n' ){
1649      fputc('\\', out);
1650      fputc('n', out);
1651    }else if( c=='\r' ){
1652      fputc('\\', out);
1653      fputc('r', out);
1654    }else if( !isprint(c&0xff) ){
1655      raw_printf(out, "\\%03o", c&0xff);
1656    }else{
1657      fputc(c, out);
1658    }
1659  }
1660  fputc('"', out);
1661}
1662
1663/*
1664** Output the given string as a quoted according to JSON quoting rules.
1665*/
1666static void output_json_string(FILE *out, const char *z, int n){
1667  unsigned int c;
1668  if( n<0 ) n = (int)strlen(z);
1669  fputc('"', out);
1670  while( n-- ){
1671    c = *(z++);
1672    if( c=='\\' || c=='"' ){
1673      fputc('\\', out);
1674      fputc(c, out);
1675    }else if( c<=0x1f ){
1676      fputc('\\', out);
1677      if( c=='\b' ){
1678        fputc('b', out);
1679      }else if( c=='\f' ){
1680        fputc('f', out);
1681      }else if( c=='\n' ){
1682        fputc('n', out);
1683      }else if( c=='\r' ){
1684        fputc('r', out);
1685      }else if( c=='\t' ){
1686        fputc('t', out);
1687      }else{
1688         raw_printf(out, "u%04x",c);
1689      }
1690    }else{
1691      fputc(c, out);
1692    }
1693  }
1694  fputc('"', out);
1695}
1696
1697/*
1698** Output the given string with characters that are special to
1699** HTML escaped.
1700*/
1701static void output_html_string(FILE *out, const char *z){
1702  int i;
1703  if( z==0 ) z = "";
1704  while( *z ){
1705    for(i=0;   z[i]
1706            && z[i]!='<'
1707            && z[i]!='&'
1708            && z[i]!='>'
1709            && z[i]!='\"'
1710            && z[i]!='\'';
1711        i++){}
1712    if( i>0 ){
1713      utf8_printf(out,"%.*s",i,z);
1714    }
1715    if( z[i]=='<' ){
1716      raw_printf(out,"&lt;");
1717    }else if( z[i]=='&' ){
1718      raw_printf(out,"&amp;");
1719    }else if( z[i]=='>' ){
1720      raw_printf(out,"&gt;");
1721    }else if( z[i]=='\"' ){
1722      raw_printf(out,"&quot;");
1723    }else if( z[i]=='\'' ){
1724      raw_printf(out,"&#39;");
1725    }else{
1726      break;
1727    }
1728    z += i + 1;
1729  }
1730}
1731
1732/*
1733** If a field contains any character identified by a 1 in the following
1734** array, then the string must be quoted for CSV.
1735*/
1736static const char needCsvQuote[] = {
1737  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1738  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1739  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1740  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1741  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1742  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1743  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1744  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1745  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1746  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1747  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1748  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1749  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1750  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1751  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1752  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1753};
1754
1755/*
1756** Output a single term of CSV.  Actually, p->colSeparator is used for
1757** the separator, which may or may not be a comma.  p->nullValue is
1758** the null value.  Strings are quoted if necessary.  The separator
1759** is only issued if bSep is true.
1760*/
1761static void output_csv(ShellState *p, const char *z, int bSep){
1762  FILE *out = p->out;
1763  if( z==0 ){
1764    utf8_printf(out,"%s",p->nullValue);
1765  }else{
1766    unsigned i;
1767    for(i=0; z[i]; i++){
1768      if( needCsvQuote[((unsigned char*)z)[i]] ){
1769        i = 0;
1770        break;
1771      }
1772    }
1773    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1774      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1775      shell_check_oom(zQuoted);
1776      utf8_printf(out, "%s", zQuoted);
1777      sqlite3_free(zQuoted);
1778    }else{
1779      utf8_printf(out, "%s", z);
1780    }
1781  }
1782  if( bSep ){
1783    utf8_printf(p->out, "%s", p->colSeparator);
1784  }
1785}
1786
1787/*
1788** This routine runs when the user presses Ctrl-C
1789*/
1790static void interrupt_handler(int NotUsed){
1791  UNUSED_PARAMETER(NotUsed);
1792  seenInterrupt++;
1793  if( seenInterrupt>2 ) exit(1);
1794  if( globalDb ) sqlite3_interrupt(globalDb);
1795}
1796
1797#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1798/*
1799** This routine runs for console events (e.g. Ctrl-C) on Win32
1800*/
1801static BOOL WINAPI ConsoleCtrlHandler(
1802  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1803){
1804  if( dwCtrlType==CTRL_C_EVENT ){
1805    interrupt_handler(0);
1806    return TRUE;
1807  }
1808  return FALSE;
1809}
1810#endif
1811
1812#ifndef SQLITE_OMIT_AUTHORIZATION
1813/*
1814** This authorizer runs in safe mode.
1815*/
1816static int safeModeAuth(
1817  void *pClientData,
1818  int op,
1819  const char *zA1,
1820  const char *zA2,
1821  const char *zA3,
1822  const char *zA4
1823){
1824  ShellState *p = (ShellState*)pClientData;
1825  static const char *azProhibitedFunctions[] = {
1826    "edit",
1827    "fts3_tokenizer",
1828    "load_extension",
1829    "readfile",
1830    "writefile",
1831    "zipfile",
1832    "zipfile_cds",
1833  };
1834  UNUSED_PARAMETER(zA2);
1835  UNUSED_PARAMETER(zA3);
1836  UNUSED_PARAMETER(zA4);
1837  switch( op ){
1838    case SQLITE_ATTACH: {
1839#ifndef SQLITE_SHELL_FIDDLE
1840      /* In WASM builds the filesystem is a virtual sandbox, so
1841      ** there's no harm in using ATTACH. */
1842      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1843#endif
1844      break;
1845    }
1846    case SQLITE_FUNCTION: {
1847      int i;
1848      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1849        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1850          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1851                         azProhibitedFunctions[i]);
1852        }
1853      }
1854      break;
1855    }
1856  }
1857  return SQLITE_OK;
1858}
1859
1860/*
1861** When the ".auth ON" is set, the following authorizer callback is
1862** invoked.  It always returns SQLITE_OK.
1863*/
1864static int shellAuth(
1865  void *pClientData,
1866  int op,
1867  const char *zA1,
1868  const char *zA2,
1869  const char *zA3,
1870  const char *zA4
1871){
1872  ShellState *p = (ShellState*)pClientData;
1873  static const char *azAction[] = { 0,
1874     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1875     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1876     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1877     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1878     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1879     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1880     "PRAGMA",               "READ",                 "SELECT",
1881     "TRANSACTION",          "UPDATE",               "ATTACH",
1882     "DETACH",               "ALTER_TABLE",          "REINDEX",
1883     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1884     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1885  };
1886  int i;
1887  const char *az[4];
1888  az[0] = zA1;
1889  az[1] = zA2;
1890  az[2] = zA3;
1891  az[3] = zA4;
1892  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1893  for(i=0; i<4; i++){
1894    raw_printf(p->out, " ");
1895    if( az[i] ){
1896      output_c_string(p->out, az[i]);
1897    }else{
1898      raw_printf(p->out, "NULL");
1899    }
1900  }
1901  raw_printf(p->out, "\n");
1902  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1903  return SQLITE_OK;
1904}
1905#endif
1906
1907/*
1908** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1909**
1910** This routine converts some CREATE TABLE statements for shadow tables
1911** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1912**
1913** If the schema statement in z[] contains a start-of-comment and if
1914** sqlite3_complete() returns false, try to terminate the comment before
1915** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
1916*/
1917static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1918  char *zToFree = 0;
1919  if( z==0 ) return;
1920  if( zTail==0 ) return;
1921  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
1922    const char *zOrig = z;
1923    static const char *azTerm[] = { "", "*/", "\n" };
1924    int i;
1925    for(i=0; i<ArraySize(azTerm); i++){
1926      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
1927      if( sqlite3_complete(zNew) ){
1928        size_t n = strlen(zNew);
1929        zNew[n-1] = 0;
1930        zToFree = zNew;
1931        z = zNew;
1932        break;
1933      }
1934      sqlite3_free(zNew);
1935    }
1936  }
1937  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1938    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1939  }else{
1940    utf8_printf(out, "%s%s", z, zTail);
1941  }
1942  sqlite3_free(zToFree);
1943}
1944static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1945  char c = z[n];
1946  z[n] = 0;
1947  printSchemaLine(out, z, zTail);
1948  z[n] = c;
1949}
1950
1951/*
1952** Return true if string z[] has nothing but whitespace and comments to the
1953** end of the first line.
1954*/
1955static int wsToEol(const char *z){
1956  int i;
1957  for(i=0; z[i]; i++){
1958    if( z[i]=='\n' ) return 1;
1959    if( IsSpace(z[i]) ) continue;
1960    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1961    return 0;
1962  }
1963  return 1;
1964}
1965
1966/*
1967** Add a new entry to the EXPLAIN QUERY PLAN data
1968*/
1969static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1970  EQPGraphRow *pNew;
1971  int nText = strlen30(zText);
1972  if( p->autoEQPtest ){
1973    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1974  }
1975  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1976  shell_check_oom(pNew);
1977  pNew->iEqpId = iEqpId;
1978  pNew->iParentId = p2;
1979  memcpy(pNew->zText, zText, nText+1);
1980  pNew->pNext = 0;
1981  if( p->sGraph.pLast ){
1982    p->sGraph.pLast->pNext = pNew;
1983  }else{
1984    p->sGraph.pRow = pNew;
1985  }
1986  p->sGraph.pLast = pNew;
1987}
1988
1989/*
1990** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1991** in p->sGraph.
1992*/
1993static void eqp_reset(ShellState *p){
1994  EQPGraphRow *pRow, *pNext;
1995  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1996    pNext = pRow->pNext;
1997    sqlite3_free(pRow);
1998  }
1999  memset(&p->sGraph, 0, sizeof(p->sGraph));
2000}
2001
2002/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2003** pOld, or return the first such line if pOld is NULL
2004*/
2005static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2006  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2007  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2008  return pRow;
2009}
2010
2011/* Render a single level of the graph that has iEqpId as its parent.  Called
2012** recursively to render sublevels.
2013*/
2014static void eqp_render_level(ShellState *p, int iEqpId){
2015  EQPGraphRow *pRow, *pNext;
2016  int n = strlen30(p->sGraph.zPrefix);
2017  char *z;
2018  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2019    pNext = eqp_next_row(p, iEqpId, pRow);
2020    z = pRow->zText;
2021    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2022                pNext ? "|--" : "`--", z);
2023    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2024      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2025      eqp_render_level(p, pRow->iEqpId);
2026      p->sGraph.zPrefix[n] = 0;
2027    }
2028  }
2029}
2030
2031/*
2032** Display and reset the EXPLAIN QUERY PLAN data
2033*/
2034static void eqp_render(ShellState *p){
2035  EQPGraphRow *pRow = p->sGraph.pRow;
2036  if( pRow ){
2037    if( pRow->zText[0]=='-' ){
2038      if( pRow->pNext==0 ){
2039        eqp_reset(p);
2040        return;
2041      }
2042      utf8_printf(p->out, "%s\n", pRow->zText+3);
2043      p->sGraph.pRow = pRow->pNext;
2044      sqlite3_free(pRow);
2045    }else{
2046      utf8_printf(p->out, "QUERY PLAN\n");
2047    }
2048    p->sGraph.zPrefix[0] = 0;
2049    eqp_render_level(p, 0);
2050    eqp_reset(p);
2051  }
2052}
2053
2054#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2055/*
2056** Progress handler callback.
2057*/
2058static int progress_handler(void *pClientData) {
2059  ShellState *p = (ShellState*)pClientData;
2060  p->nProgress++;
2061  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2062    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2063    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2064    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2065    return 1;
2066  }
2067  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2068    raw_printf(p->out, "Progress %u\n", p->nProgress);
2069  }
2070  return 0;
2071}
2072#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2073
2074/*
2075** Print N dashes
2076*/
2077static void print_dashes(FILE *out, int N){
2078  const char zDash[] = "--------------------------------------------------";
2079  const int nDash = sizeof(zDash) - 1;
2080  while( N>nDash ){
2081    fputs(zDash, out);
2082    N -= nDash;
2083  }
2084  raw_printf(out, "%.*s", N, zDash);
2085}
2086
2087/*
2088** Print a markdown or table-style row separator using ascii-art
2089*/
2090static void print_row_separator(
2091  ShellState *p,
2092  int nArg,
2093  const char *zSep
2094){
2095  int i;
2096  if( nArg>0 ){
2097    fputs(zSep, p->out);
2098    print_dashes(p->out, p->actualWidth[0]+2);
2099    for(i=1; i<nArg; i++){
2100      fputs(zSep, p->out);
2101      print_dashes(p->out, p->actualWidth[i]+2);
2102    }
2103    fputs(zSep, p->out);
2104  }
2105  fputs("\n", p->out);
2106}
2107
2108/*
2109** This is the callback routine that the shell
2110** invokes for each row of a query result.
2111*/
2112static int shell_callback(
2113  void *pArg,
2114  int nArg,        /* Number of result columns */
2115  char **azArg,    /* Text of each result column */
2116  char **azCol,    /* Column names */
2117  int *aiType      /* Column types.  Might be NULL */
2118){
2119  int i;
2120  ShellState *p = (ShellState*)pArg;
2121
2122  if( azArg==0 ) return 0;
2123  switch( p->cMode ){
2124    case MODE_Count:
2125    case MODE_Off: {
2126      break;
2127    }
2128    case MODE_Line: {
2129      int w = 5;
2130      if( azArg==0 ) break;
2131      for(i=0; i<nArg; i++){
2132        int len = strlen30(azCol[i] ? azCol[i] : "");
2133        if( len>w ) w = len;
2134      }
2135      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2136      for(i=0; i<nArg; i++){
2137        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2138                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2139      }
2140      break;
2141    }
2142    case MODE_Explain: {
2143      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2144      if( nArg>ArraySize(aExplainWidth) ){
2145        nArg = ArraySize(aExplainWidth);
2146      }
2147      if( p->cnt++==0 ){
2148        for(i=0; i<nArg; i++){
2149          int w = aExplainWidth[i];
2150          utf8_width_print(p->out, w, azCol[i]);
2151          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2152        }
2153        for(i=0; i<nArg; i++){
2154          int w = aExplainWidth[i];
2155          print_dashes(p->out, w);
2156          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2157        }
2158      }
2159      if( azArg==0 ) break;
2160      for(i=0; i<nArg; i++){
2161        int w = aExplainWidth[i];
2162        if( i==nArg-1 ) w = 0;
2163        if( azArg[i] && strlenChar(azArg[i])>w ){
2164          w = strlenChar(azArg[i]);
2165        }
2166        if( i==1 && p->aiIndent && p->pStmt ){
2167          if( p->iIndent<p->nIndent ){
2168            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2169          }
2170          p->iIndent++;
2171        }
2172        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2173        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2174      }
2175      break;
2176    }
2177    case MODE_Semi: {   /* .schema and .fullschema output */
2178      printSchemaLine(p->out, azArg[0], ";\n");
2179      break;
2180    }
2181    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2182      char *z;
2183      int j;
2184      int nParen = 0;
2185      char cEnd = 0;
2186      char c;
2187      int nLine = 0;
2188      assert( nArg==1 );
2189      if( azArg[0]==0 ) break;
2190      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2191       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2192      ){
2193        utf8_printf(p->out, "%s;\n", azArg[0]);
2194        break;
2195      }
2196      z = sqlite3_mprintf("%s", azArg[0]);
2197      shell_check_oom(z);
2198      j = 0;
2199      for(i=0; IsSpace(z[i]); i++){}
2200      for(; (c = z[i])!=0; i++){
2201        if( IsSpace(c) ){
2202          if( z[j-1]=='\r' ) z[j-1] = '\n';
2203          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2204        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2205          j--;
2206        }
2207        z[j++] = c;
2208      }
2209      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2210      z[j] = 0;
2211      if( strlen30(z)>=79 ){
2212        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2213          if( c==cEnd ){
2214            cEnd = 0;
2215          }else if( c=='"' || c=='\'' || c=='`' ){
2216            cEnd = c;
2217          }else if( c=='[' ){
2218            cEnd = ']';
2219          }else if( c=='-' && z[i+1]=='-' ){
2220            cEnd = '\n';
2221          }else if( c=='(' ){
2222            nParen++;
2223          }else if( c==')' ){
2224            nParen--;
2225            if( nLine>0 && nParen==0 && j>0 ){
2226              printSchemaLineN(p->out, z, j, "\n");
2227              j = 0;
2228            }
2229          }
2230          z[j++] = c;
2231          if( nParen==1 && cEnd==0
2232           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2233          ){
2234            if( c=='\n' ) j--;
2235            printSchemaLineN(p->out, z, j, "\n  ");
2236            j = 0;
2237            nLine++;
2238            while( IsSpace(z[i+1]) ){ i++; }
2239          }
2240        }
2241        z[j] = 0;
2242      }
2243      printSchemaLine(p->out, z, ";\n");
2244      sqlite3_free(z);
2245      break;
2246    }
2247    case MODE_List: {
2248      if( p->cnt++==0 && p->showHeader ){
2249        for(i=0; i<nArg; i++){
2250          utf8_printf(p->out,"%s%s",azCol[i],
2251                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2252        }
2253      }
2254      if( azArg==0 ) break;
2255      for(i=0; i<nArg; i++){
2256        char *z = azArg[i];
2257        if( z==0 ) z = p->nullValue;
2258        utf8_printf(p->out, "%s", z);
2259        if( i<nArg-1 ){
2260          utf8_printf(p->out, "%s", p->colSeparator);
2261        }else{
2262          utf8_printf(p->out, "%s", p->rowSeparator);
2263        }
2264      }
2265      break;
2266    }
2267    case MODE_Html: {
2268      if( p->cnt++==0 && p->showHeader ){
2269        raw_printf(p->out,"<TR>");
2270        for(i=0; i<nArg; i++){
2271          raw_printf(p->out,"<TH>");
2272          output_html_string(p->out, azCol[i]);
2273          raw_printf(p->out,"</TH>\n");
2274        }
2275        raw_printf(p->out,"</TR>\n");
2276      }
2277      if( azArg==0 ) break;
2278      raw_printf(p->out,"<TR>");
2279      for(i=0; i<nArg; i++){
2280        raw_printf(p->out,"<TD>");
2281        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2282        raw_printf(p->out,"</TD>\n");
2283      }
2284      raw_printf(p->out,"</TR>\n");
2285      break;
2286    }
2287    case MODE_Tcl: {
2288      if( p->cnt++==0 && p->showHeader ){
2289        for(i=0; i<nArg; i++){
2290          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2291          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2292        }
2293        utf8_printf(p->out, "%s", p->rowSeparator);
2294      }
2295      if( azArg==0 ) break;
2296      for(i=0; i<nArg; i++){
2297        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2298        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2299      }
2300      utf8_printf(p->out, "%s", p->rowSeparator);
2301      break;
2302    }
2303    case MODE_Csv: {
2304      setBinaryMode(p->out, 1);
2305      if( p->cnt++==0 && p->showHeader ){
2306        for(i=0; i<nArg; i++){
2307          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2308        }
2309        utf8_printf(p->out, "%s", p->rowSeparator);
2310      }
2311      if( nArg>0 ){
2312        for(i=0; i<nArg; i++){
2313          output_csv(p, azArg[i], i<nArg-1);
2314        }
2315        utf8_printf(p->out, "%s", p->rowSeparator);
2316      }
2317      setTextMode(p->out, 1);
2318      break;
2319    }
2320    case MODE_Insert: {
2321      if( azArg==0 ) break;
2322      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2323      if( p->showHeader ){
2324        raw_printf(p->out,"(");
2325        for(i=0; i<nArg; i++){
2326          if( i>0 ) raw_printf(p->out, ",");
2327          if( quoteChar(azCol[i]) ){
2328            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2329            shell_check_oom(z);
2330            utf8_printf(p->out, "%s", z);
2331            sqlite3_free(z);
2332          }else{
2333            raw_printf(p->out, "%s", azCol[i]);
2334          }
2335        }
2336        raw_printf(p->out,")");
2337      }
2338      p->cnt++;
2339      for(i=0; i<nArg; i++){
2340        raw_printf(p->out, i>0 ? "," : " VALUES(");
2341        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2342          utf8_printf(p->out,"NULL");
2343        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2344          if( ShellHasFlag(p, SHFLG_Newlines) ){
2345            output_quoted_string(p->out, azArg[i]);
2346          }else{
2347            output_quoted_escaped_string(p->out, azArg[i]);
2348          }
2349        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2350          utf8_printf(p->out,"%s", azArg[i]);
2351        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2352          char z[50];
2353          double r = sqlite3_column_double(p->pStmt, i);
2354          sqlite3_uint64 ur;
2355          memcpy(&ur,&r,sizeof(r));
2356          if( ur==0x7ff0000000000000LL ){
2357            raw_printf(p->out, "1e999");
2358          }else if( ur==0xfff0000000000000LL ){
2359            raw_printf(p->out, "-1e999");
2360          }else{
2361            sqlite3_int64 ir = (sqlite3_int64)r;
2362            if( r==(double)ir ){
2363              sqlite3_snprintf(50,z,"%lld.0", ir);
2364            }else{
2365              sqlite3_snprintf(50,z,"%!.20g", r);
2366            }
2367            raw_printf(p->out, "%s", z);
2368          }
2369        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2370          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2371          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2372          output_hex_blob(p->out, pBlob, nBlob);
2373        }else if( isNumber(azArg[i], 0) ){
2374          utf8_printf(p->out,"%s", azArg[i]);
2375        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2376          output_quoted_string(p->out, azArg[i]);
2377        }else{
2378          output_quoted_escaped_string(p->out, azArg[i]);
2379        }
2380      }
2381      raw_printf(p->out,");\n");
2382      break;
2383    }
2384    case MODE_Json: {
2385      if( azArg==0 ) break;
2386      if( p->cnt==0 ){
2387        fputs("[{", p->out);
2388      }else{
2389        fputs(",\n{", p->out);
2390      }
2391      p->cnt++;
2392      for(i=0; i<nArg; i++){
2393        output_json_string(p->out, azCol[i], -1);
2394        putc(':', p->out);
2395        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2396          fputs("null",p->out);
2397        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2398          char z[50];
2399          double r = sqlite3_column_double(p->pStmt, i);
2400          sqlite3_uint64 ur;
2401          memcpy(&ur,&r,sizeof(r));
2402          if( ur==0x7ff0000000000000LL ){
2403            raw_printf(p->out, "1e999");
2404          }else if( ur==0xfff0000000000000LL ){
2405            raw_printf(p->out, "-1e999");
2406          }else{
2407            sqlite3_snprintf(50,z,"%!.20g", r);
2408            raw_printf(p->out, "%s", z);
2409          }
2410        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2411          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2412          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2413          output_json_string(p->out, pBlob, nBlob);
2414        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2415          output_json_string(p->out, azArg[i], -1);
2416        }else{
2417          utf8_printf(p->out,"%s", azArg[i]);
2418        }
2419        if( i<nArg-1 ){
2420          putc(',', p->out);
2421        }
2422      }
2423      putc('}', p->out);
2424      break;
2425    }
2426    case MODE_Quote: {
2427      if( azArg==0 ) break;
2428      if( p->cnt==0 && p->showHeader ){
2429        for(i=0; i<nArg; i++){
2430          if( i>0 ) fputs(p->colSeparator, p->out);
2431          output_quoted_string(p->out, azCol[i]);
2432        }
2433        fputs(p->rowSeparator, p->out);
2434      }
2435      p->cnt++;
2436      for(i=0; i<nArg; i++){
2437        if( i>0 ) fputs(p->colSeparator, p->out);
2438        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2439          utf8_printf(p->out,"NULL");
2440        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2441          output_quoted_string(p->out, azArg[i]);
2442        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2443          utf8_printf(p->out,"%s", azArg[i]);
2444        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2445          char z[50];
2446          double r = sqlite3_column_double(p->pStmt, i);
2447          sqlite3_snprintf(50,z,"%!.20g", r);
2448          raw_printf(p->out, "%s", z);
2449        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2450          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2451          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2452          output_hex_blob(p->out, pBlob, nBlob);
2453        }else if( isNumber(azArg[i], 0) ){
2454          utf8_printf(p->out,"%s", azArg[i]);
2455        }else{
2456          output_quoted_string(p->out, azArg[i]);
2457        }
2458      }
2459      fputs(p->rowSeparator, p->out);
2460      break;
2461    }
2462    case MODE_Ascii: {
2463      if( p->cnt++==0 && p->showHeader ){
2464        for(i=0; i<nArg; i++){
2465          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2466          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2467        }
2468        utf8_printf(p->out, "%s", p->rowSeparator);
2469      }
2470      if( azArg==0 ) break;
2471      for(i=0; i<nArg; i++){
2472        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2473        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2474      }
2475      utf8_printf(p->out, "%s", p->rowSeparator);
2476      break;
2477    }
2478    case MODE_EQP: {
2479      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2480      break;
2481    }
2482  }
2483  return 0;
2484}
2485
2486/*
2487** This is the callback routine that the SQLite library
2488** invokes for each row of a query result.
2489*/
2490static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2491  /* since we don't have type info, call the shell_callback with a NULL value */
2492  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2493}
2494
2495/*
2496** This is the callback routine from sqlite3_exec() that appends all
2497** output onto the end of a ShellText object.
2498*/
2499static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2500  ShellText *p = (ShellText*)pArg;
2501  int i;
2502  UNUSED_PARAMETER(az);
2503  if( azArg==0 ) return 0;
2504  if( p->n ) appendText(p, "|", 0);
2505  for(i=0; i<nArg; i++){
2506    if( i ) appendText(p, ",", 0);
2507    if( azArg[i] ) appendText(p, azArg[i], 0);
2508  }
2509  return 0;
2510}
2511
2512/*
2513** Generate an appropriate SELFTEST table in the main database.
2514*/
2515static void createSelftestTable(ShellState *p){
2516  char *zErrMsg = 0;
2517  sqlite3_exec(p->db,
2518    "SAVEPOINT selftest_init;\n"
2519    "CREATE TABLE IF NOT EXISTS selftest(\n"
2520    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2521    "  op TEXT,\n"                   /* Operator:  memo run */
2522    "  cmd TEXT,\n"                  /* Command text */
2523    "  ans TEXT\n"                   /* Desired answer */
2524    ");"
2525    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2526    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2527    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2528    "         'memo','Tests generated by --init');\n"
2529    "INSERT INTO [_shell$self]\n"
2530    "  SELECT 'run',\n"
2531    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2532                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2533    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2534                          "FROM sqlite_schema ORDER BY 2',224));\n"
2535    "INSERT INTO [_shell$self]\n"
2536    "  SELECT 'run',"
2537    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2538    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2539    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2540    "  FROM (\n"
2541    "    SELECT name FROM sqlite_schema\n"
2542    "     WHERE type='table'\n"
2543    "       AND name<>'selftest'\n"
2544    "       AND coalesce(rootpage,0)>0\n"
2545    "  )\n"
2546    " ORDER BY name;\n"
2547    "INSERT INTO [_shell$self]\n"
2548    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2549    "INSERT INTO selftest(tno,op,cmd,ans)"
2550    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2551    "DROP TABLE [_shell$self];"
2552    ,0,0,&zErrMsg);
2553  if( zErrMsg ){
2554    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2555    sqlite3_free(zErrMsg);
2556  }
2557  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2558}
2559
2560
2561/*
2562** Set the destination table field of the ShellState structure to
2563** the name of the table given.  Escape any quote characters in the
2564** table name.
2565*/
2566static void set_table_name(ShellState *p, const char *zName){
2567  int i, n;
2568  char cQuote;
2569  char *z;
2570
2571  if( p->zDestTable ){
2572    free(p->zDestTable);
2573    p->zDestTable = 0;
2574  }
2575  if( zName==0 ) return;
2576  cQuote = quoteChar(zName);
2577  n = strlen30(zName);
2578  if( cQuote ) n += n+2;
2579  z = p->zDestTable = malloc( n+1 );
2580  shell_check_oom(z);
2581  n = 0;
2582  if( cQuote ) z[n++] = cQuote;
2583  for(i=0; zName[i]; i++){
2584    z[n++] = zName[i];
2585    if( zName[i]==cQuote ) z[n++] = cQuote;
2586  }
2587  if( cQuote ) z[n++] = cQuote;
2588  z[n] = 0;
2589}
2590
2591/*
2592** Maybe construct two lines of text that point out the position of a
2593** syntax error.  Return a pointer to the text, in memory obtained from
2594** sqlite3_malloc().  Or, if the most recent error does not involve a
2595** specific token that we can point to, return an empty string.
2596**
2597** In all cases, the memory returned is obtained from sqlite3_malloc64()
2598** and should be released by the caller invoking sqlite3_free().
2599*/
2600static char *shell_error_context(const char *zSql, sqlite3 *db){
2601  int iOffset;
2602  size_t len;
2603  char *zCode;
2604  char *zMsg;
2605  int i;
2606  if( db==0
2607   || zSql==0
2608   || (iOffset = sqlite3_error_offset(db))<0
2609  ){
2610    return sqlite3_mprintf("");
2611  }
2612  while( iOffset>50 ){
2613    iOffset--;
2614    zSql++;
2615    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2616  }
2617  len = strlen(zSql);
2618  if( len>78 ){
2619    len = 78;
2620    while( (zSql[len]&0xc0)==0x80 ) len--;
2621  }
2622  zCode = sqlite3_mprintf("%.*s", len, zSql);
2623  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2624  if( iOffset<25 ){
2625    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2626  }else{
2627    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2628  }
2629  return zMsg;
2630}
2631
2632
2633/*
2634** Execute a query statement that will generate SQL output.  Print
2635** the result columns, comma-separated, on a line and then add a
2636** semicolon terminator to the end of that line.
2637**
2638** If the number of columns is 1 and that column contains text "--"
2639** then write the semicolon on a separate line.  That way, if a
2640** "--" comment occurs at the end of the statement, the comment
2641** won't consume the semicolon terminator.
2642*/
2643static int run_table_dump_query(
2644  ShellState *p,           /* Query context */
2645  const char *zSelect      /* SELECT statement to extract content */
2646){
2647  sqlite3_stmt *pSelect;
2648  int rc;
2649  int nResult;
2650  int i;
2651  const char *z;
2652  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2653  if( rc!=SQLITE_OK || !pSelect ){
2654    char *zContext = shell_error_context(zSelect, p->db);
2655    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2656                sqlite3_errmsg(p->db), zContext);
2657    sqlite3_free(zContext);
2658    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2659    return rc;
2660  }
2661  rc = sqlite3_step(pSelect);
2662  nResult = sqlite3_column_count(pSelect);
2663  while( rc==SQLITE_ROW ){
2664    z = (const char*)sqlite3_column_text(pSelect, 0);
2665    utf8_printf(p->out, "%s", z);
2666    for(i=1; i<nResult; i++){
2667      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2668    }
2669    if( z==0 ) z = "";
2670    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2671    if( z[0] ){
2672      raw_printf(p->out, "\n;\n");
2673    }else{
2674      raw_printf(p->out, ";\n");
2675    }
2676    rc = sqlite3_step(pSelect);
2677  }
2678  rc = sqlite3_finalize(pSelect);
2679  if( rc!=SQLITE_OK ){
2680    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2681                sqlite3_errmsg(p->db));
2682    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2683  }
2684  return rc;
2685}
2686
2687/*
2688** Allocate space and save off string indicating current error.
2689*/
2690static char *save_err_msg(
2691  sqlite3 *db,           /* Database to query */
2692  const char *zPhase,    /* When the error occcurs */
2693  int rc,                /* Error code returned from API */
2694  const char *zSql       /* SQL string, or NULL */
2695){
2696  char *zErr;
2697  char *zContext;
2698  sqlite3_str *pStr = sqlite3_str_new(0);
2699  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2700  if( rc>1 ){
2701    sqlite3_str_appendf(pStr, " (%d)", rc);
2702  }
2703  zContext = shell_error_context(zSql, db);
2704  if( zContext ){
2705    sqlite3_str_appendall(pStr, zContext);
2706    sqlite3_free(zContext);
2707  }
2708  zErr = sqlite3_str_finish(pStr);
2709  shell_check_oom(zErr);
2710  return zErr;
2711}
2712
2713#ifdef __linux__
2714/*
2715** Attempt to display I/O stats on Linux using /proc/PID/io
2716*/
2717static void displayLinuxIoStats(FILE *out){
2718  FILE *in;
2719  char z[200];
2720  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2721  in = fopen(z, "rb");
2722  if( in==0 ) return;
2723  while( fgets(z, sizeof(z), in)!=0 ){
2724    static const struct {
2725      const char *zPattern;
2726      const char *zDesc;
2727    } aTrans[] = {
2728      { "rchar: ",                  "Bytes received by read():" },
2729      { "wchar: ",                  "Bytes sent to write():"    },
2730      { "syscr: ",                  "Read() system calls:"      },
2731      { "syscw: ",                  "Write() system calls:"     },
2732      { "read_bytes: ",             "Bytes read from storage:"  },
2733      { "write_bytes: ",            "Bytes written to storage:" },
2734      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2735    };
2736    int i;
2737    for(i=0; i<ArraySize(aTrans); i++){
2738      int n = strlen30(aTrans[i].zPattern);
2739      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2740        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2741        break;
2742      }
2743    }
2744  }
2745  fclose(in);
2746}
2747#endif
2748
2749/*
2750** Display a single line of status using 64-bit values.
2751*/
2752static void displayStatLine(
2753  ShellState *p,            /* The shell context */
2754  char *zLabel,             /* Label for this one line */
2755  char *zFormat,            /* Format for the result */
2756  int iStatusCtrl,          /* Which status to display */
2757  int bReset                /* True to reset the stats */
2758){
2759  sqlite3_int64 iCur = -1;
2760  sqlite3_int64 iHiwtr = -1;
2761  int i, nPercent;
2762  char zLine[200];
2763  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2764  for(i=0, nPercent=0; zFormat[i]; i++){
2765    if( zFormat[i]=='%' ) nPercent++;
2766  }
2767  if( nPercent>1 ){
2768    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2769  }else{
2770    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2771  }
2772  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2773}
2774
2775/*
2776** Display memory stats.
2777*/
2778static int display_stats(
2779  sqlite3 *db,                /* Database to query */
2780  ShellState *pArg,           /* Pointer to ShellState */
2781  int bReset                  /* True to reset the stats */
2782){
2783  int iCur;
2784  int iHiwtr;
2785  FILE *out;
2786  if( pArg==0 || pArg->out==0 ) return 0;
2787  out = pArg->out;
2788
2789  if( pArg->pStmt && pArg->statsOn==2 ){
2790    int nCol, i, x;
2791    sqlite3_stmt *pStmt = pArg->pStmt;
2792    char z[100];
2793    nCol = sqlite3_column_count(pStmt);
2794    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2795    for(i=0; i<nCol; i++){
2796      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2797      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2798#ifndef SQLITE_OMIT_DECLTYPE
2799      sqlite3_snprintf(30, z+x, "declared type:");
2800      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2801#endif
2802#ifdef SQLITE_ENABLE_COLUMN_METADATA
2803      sqlite3_snprintf(30, z+x, "database name:");
2804      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2805      sqlite3_snprintf(30, z+x, "table name:");
2806      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2807      sqlite3_snprintf(30, z+x, "origin name:");
2808      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2809#endif
2810    }
2811  }
2812
2813  if( pArg->statsOn==3 ){
2814    if( pArg->pStmt ){
2815      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2816      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2817    }
2818    return 0;
2819  }
2820
2821  displayStatLine(pArg, "Memory Used:",
2822     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2823  displayStatLine(pArg, "Number of Outstanding Allocations:",
2824     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2825  if( pArg->shellFlgs & SHFLG_Pagecache ){
2826    displayStatLine(pArg, "Number of Pcache Pages Used:",
2827       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2828  }
2829  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2830     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2831  displayStatLine(pArg, "Largest Allocation:",
2832     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2833  displayStatLine(pArg, "Largest Pcache Allocation:",
2834     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2835#ifdef YYTRACKMAXSTACKDEPTH
2836  displayStatLine(pArg, "Deepest Parser Stack:",
2837     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2838#endif
2839
2840  if( db ){
2841    if( pArg->shellFlgs & SHFLG_Lookaside ){
2842      iHiwtr = iCur = -1;
2843      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2844                        &iCur, &iHiwtr, bReset);
2845      raw_printf(pArg->out,
2846              "Lookaside Slots Used:                %d (max %d)\n",
2847              iCur, iHiwtr);
2848      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2849                        &iCur, &iHiwtr, bReset);
2850      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2851              iHiwtr);
2852      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2853                        &iCur, &iHiwtr, bReset);
2854      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2855              iHiwtr);
2856      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2857                        &iCur, &iHiwtr, bReset);
2858      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2859              iHiwtr);
2860    }
2861    iHiwtr = iCur = -1;
2862    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2863    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2864            iCur);
2865    iHiwtr = iCur = -1;
2866    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2867    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2868    iHiwtr = iCur = -1;
2869    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2870    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2871    iHiwtr = iCur = -1;
2872    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2873    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2874    iHiwtr = iCur = -1;
2875    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2876    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2877    iHiwtr = iCur = -1;
2878    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2879    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2880            iCur);
2881    iHiwtr = iCur = -1;
2882    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2883    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2884            iCur);
2885  }
2886
2887  if( pArg->pStmt ){
2888    int iHit, iMiss;
2889    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2890                               bReset);
2891    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2892    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2893    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2894    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2895    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2896    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2897    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2898    if( iHit || iMiss ){
2899      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2900            iHit, iHit+iMiss);
2901    }
2902    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2903    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2904    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2905    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2906    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2907    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2908    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2909    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2910  }
2911
2912#ifdef __linux__
2913  displayLinuxIoStats(pArg->out);
2914#endif
2915
2916  /* Do not remove this machine readable comment: extra-stats-output-here */
2917
2918  return 0;
2919}
2920
2921/*
2922** Display scan stats.
2923*/
2924static void display_scanstats(
2925  sqlite3 *db,                    /* Database to query */
2926  ShellState *pArg                /* Pointer to ShellState */
2927){
2928#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2929  UNUSED_PARAMETER(db);
2930  UNUSED_PARAMETER(pArg);
2931#else
2932  int i, k, n, mx;
2933  raw_printf(pArg->out, "-------- scanstats --------\n");
2934  mx = 0;
2935  for(k=0; k<=mx; k++){
2936    double rEstLoop = 1.0;
2937    for(i=n=0; 1; i++){
2938      sqlite3_stmt *p = pArg->pStmt;
2939      sqlite3_int64 nLoop, nVisit;
2940      double rEst;
2941      int iSid;
2942      const char *zExplain;
2943      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2944        break;
2945      }
2946      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2947      if( iSid>mx ) mx = iSid;
2948      if( iSid!=k ) continue;
2949      if( n==0 ){
2950        rEstLoop = (double)nLoop;
2951        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2952      }
2953      n++;
2954      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2955      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2956      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2957      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2958      rEstLoop *= rEst;
2959      raw_printf(pArg->out,
2960          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2961          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2962      );
2963    }
2964  }
2965  raw_printf(pArg->out, "---------------------------\n");
2966#endif
2967}
2968
2969/*
2970** Parameter azArray points to a zero-terminated array of strings. zStr
2971** points to a single nul-terminated string. Return non-zero if zStr
2972** is equal, according to strcmp(), to any of the strings in the array.
2973** Otherwise, return zero.
2974*/
2975static int str_in_array(const char *zStr, const char **azArray){
2976  int i;
2977  for(i=0; azArray[i]; i++){
2978    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2979  }
2980  return 0;
2981}
2982
2983/*
2984** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2985** and populate the ShellState.aiIndent[] array with the number of
2986** spaces each opcode should be indented before it is output.
2987**
2988** The indenting rules are:
2989**
2990**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2991**       all opcodes that occur between the p2 jump destination and the opcode
2992**       itself by 2 spaces.
2993**
2994**     * Do the previous for "Return" instructions for when P2 is positive.
2995**       See tag-20220407a in wherecode.c and vdbe.c.
2996**
2997**     * For each "Goto", if the jump destination is earlier in the program
2998**       and ends on one of:
2999**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
3000**       or if the P1 parameter is one instead of zero,
3001**       then indent all opcodes between the earlier instruction
3002**       and "Goto" by 2 spaces.
3003*/
3004static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3005  const char *zSql;               /* The text of the SQL statement */
3006  const char *z;                  /* Used to check if this is an EXPLAIN */
3007  int *abYield = 0;               /* True if op is an OP_Yield */
3008  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
3009  int iOp;                        /* Index of operation in p->aiIndent[] */
3010
3011  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3012                           "Return", 0 };
3013  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3014                            "Rewind", 0 };
3015  const char *azGoto[] = { "Goto", 0 };
3016
3017  /* Try to figure out if this is really an EXPLAIN statement. If this
3018  ** cannot be verified, return early.  */
3019  if( sqlite3_column_count(pSql)!=8 ){
3020    p->cMode = p->mode;
3021    return;
3022  }
3023  zSql = sqlite3_sql(pSql);
3024  if( zSql==0 ) return;
3025  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3026  if( sqlite3_strnicmp(z, "explain", 7) ){
3027    p->cMode = p->mode;
3028    return;
3029  }
3030
3031  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3032    int i;
3033    int iAddr = sqlite3_column_int(pSql, 0);
3034    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3035
3036    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3037    ** p2 is an instruction address, set variable p2op to the index of that
3038    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3039    ** the current instruction is part of a sub-program generated by an
3040    ** SQL trigger or foreign key.  */
3041    int p2 = sqlite3_column_int(pSql, 3);
3042    int p2op = (p2 + (iOp-iAddr));
3043
3044    /* Grow the p->aiIndent array as required */
3045    if( iOp>=nAlloc ){
3046      if( iOp==0 ){
3047        /* Do further verfication that this is explain output.  Abort if
3048        ** it is not */
3049        static const char *explainCols[] = {
3050           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3051        int jj;
3052        for(jj=0; jj<ArraySize(explainCols); jj++){
3053          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3054            p->cMode = p->mode;
3055            sqlite3_reset(pSql);
3056            return;
3057          }
3058        }
3059      }
3060      nAlloc += 100;
3061      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3062      shell_check_oom(p->aiIndent);
3063      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3064      shell_check_oom(abYield);
3065    }
3066    abYield[iOp] = str_in_array(zOp, azYield);
3067    p->aiIndent[iOp] = 0;
3068    p->nIndent = iOp+1;
3069
3070    if( str_in_array(zOp, azNext) && p2op>0 ){
3071      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3072    }
3073    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3074     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3075    ){
3076      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3077    }
3078  }
3079
3080  p->iIndent = 0;
3081  sqlite3_free(abYield);
3082  sqlite3_reset(pSql);
3083}
3084
3085/*
3086** Free the array allocated by explain_data_prepare().
3087*/
3088static void explain_data_delete(ShellState *p){
3089  sqlite3_free(p->aiIndent);
3090  p->aiIndent = 0;
3091  p->nIndent = 0;
3092  p->iIndent = 0;
3093}
3094
3095/*
3096** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3097*/
3098static unsigned int savedSelectTrace;
3099static unsigned int savedWhereTrace;
3100static void disable_debug_trace_modes(void){
3101  unsigned int zero = 0;
3102  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3103  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3104  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3105  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3106}
3107static void restore_debug_trace_modes(void){
3108  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3109  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3110}
3111
3112/* Create the TEMP table used to store parameter bindings */
3113static void bind_table_init(ShellState *p){
3114  int wrSchema = 0;
3115  int defensiveMode = 0;
3116  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3117  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3118  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3119  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3120  sqlite3_exec(p->db,
3121    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3122    "  key TEXT PRIMARY KEY,\n"
3123    "  value\n"
3124    ") WITHOUT ROWID;",
3125    0, 0, 0);
3126  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3127  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3128}
3129
3130/*
3131** Bind parameters on a prepared statement.
3132**
3133** Parameter bindings are taken from a TEMP table of the form:
3134**
3135**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3136**    WITHOUT ROWID;
3137**
3138** No bindings occur if this table does not exist.  The name of the table
3139** begins with "sqlite_" so that it will not collide with ordinary application
3140** tables.  The table must be in the TEMP schema.
3141*/
3142static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3143  int nVar;
3144  int i;
3145  int rc;
3146  sqlite3_stmt *pQ = 0;
3147
3148  nVar = sqlite3_bind_parameter_count(pStmt);
3149  if( nVar==0 ) return;  /* Nothing to do */
3150  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3151                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3152    return; /* Parameter table does not exist */
3153  }
3154  rc = sqlite3_prepare_v2(pArg->db,
3155          "SELECT value FROM temp.sqlite_parameters"
3156          " WHERE key=?1", -1, &pQ, 0);
3157  if( rc || pQ==0 ) return;
3158  for(i=1; i<=nVar; i++){
3159    char zNum[30];
3160    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3161    if( zVar==0 ){
3162      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3163      zVar = zNum;
3164    }
3165    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3166    if( sqlite3_step(pQ)==SQLITE_ROW ){
3167      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3168    }else{
3169      sqlite3_bind_null(pStmt, i);
3170    }
3171    sqlite3_reset(pQ);
3172  }
3173  sqlite3_finalize(pQ);
3174}
3175
3176/*
3177** UTF8 box-drawing characters.  Imagine box lines like this:
3178**
3179**           1
3180**           |
3181**       4 --+-- 2
3182**           |
3183**           3
3184**
3185** Each box characters has between 2 and 4 of the lines leading from
3186** the center.  The characters are here identified by the numbers of
3187** their corresponding lines.
3188*/
3189#define BOX_24   "\342\224\200"  /* U+2500 --- */
3190#define BOX_13   "\342\224\202"  /* U+2502  |  */
3191#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3192#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3193#define BOX_12   "\342\224\224"  /* U+2514  '- */
3194#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3195#define BOX_123  "\342\224\234"  /* U+251c  |- */
3196#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3197#define BOX_234  "\342\224\254"  /* U+252c -,- */
3198#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3199#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3200
3201/* Draw horizontal line N characters long using unicode box
3202** characters
3203*/
3204static void print_box_line(FILE *out, int N){
3205  const char zDash[] =
3206      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3207      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3208  const int nDash = sizeof(zDash) - 1;
3209  N *= 3;
3210  while( N>nDash ){
3211    utf8_printf(out, zDash);
3212    N -= nDash;
3213  }
3214  utf8_printf(out, "%.*s", N, zDash);
3215}
3216
3217/*
3218** Draw a horizontal separator for a MODE_Box table.
3219*/
3220static void print_box_row_separator(
3221  ShellState *p,
3222  int nArg,
3223  const char *zSep1,
3224  const char *zSep2,
3225  const char *zSep3
3226){
3227  int i;
3228  if( nArg>0 ){
3229    utf8_printf(p->out, "%s", zSep1);
3230    print_box_line(p->out, p->actualWidth[0]+2);
3231    for(i=1; i<nArg; i++){
3232      utf8_printf(p->out, "%s", zSep2);
3233      print_box_line(p->out, p->actualWidth[i]+2);
3234    }
3235    utf8_printf(p->out, "%s", zSep3);
3236  }
3237  fputs("\n", p->out);
3238}
3239
3240/*
3241** z[] is a line of text that is to be displayed the .mode box or table or
3242** similar tabular formats.  z[] might contain control characters such
3243** as \n, \t, \f, or \r.
3244**
3245** Compute characters to display on the first line of z[].  Stop at the
3246** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3247** from malloc()) of that first line, which caller should free sometime.
3248** Write anything to display on the next line into *pzTail.  If this is
3249** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3250*/
3251static char *translateForDisplayAndDup(
3252  const unsigned char *z,            /* Input text to be transformed */
3253  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3254  int mxWidth,                       /* Max width.  0 means no limit */
3255  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3256){
3257  int i;                 /* Input bytes consumed */
3258  int j;                 /* Output bytes generated */
3259  int k;                 /* Input bytes to be displayed */
3260  int n;                 /* Output column number */
3261  unsigned char *zOut;   /* Output text */
3262
3263  if( z==0 ){
3264    *pzTail = 0;
3265    return 0;
3266  }
3267  if( mxWidth<0 ) mxWidth = -mxWidth;
3268  if( mxWidth==0 ) mxWidth = 1000000;
3269  i = j = n = 0;
3270  while( n<mxWidth ){
3271    if( z[i]>=' ' ){
3272      n++;
3273      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3274      continue;
3275    }
3276    if( z[i]=='\t' ){
3277      do{
3278        n++;
3279        j++;
3280      }while( (n&7)!=0 && n<mxWidth );
3281      i++;
3282      continue;
3283    }
3284    break;
3285  }
3286  if( n>=mxWidth && bWordWrap  ){
3287    /* Perhaps try to back up to a better place to break the line */
3288    for(k=i; k>i/2; k--){
3289      if( isspace(z[k-1]) ) break;
3290    }
3291    if( k<=i/2 ){
3292      for(k=i; k>i/2; k--){
3293        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3294      }
3295    }
3296    if( k<=i/2 ){
3297      k = i;
3298    }else{
3299      i = k;
3300      while( z[i]==' ' ) i++;
3301    }
3302  }else{
3303    k = i;
3304  }
3305  if( n>=mxWidth && z[i]>=' ' ){
3306   *pzTail = &z[i];
3307  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3308    *pzTail = z[i+2] ? &z[i+2] : 0;
3309  }else if( z[i]==0 || z[i+1]==0 ){
3310    *pzTail = 0;
3311  }else{
3312    *pzTail = &z[i+1];
3313  }
3314  zOut = malloc( j+1 );
3315  shell_check_oom(zOut);
3316  i = j = n = 0;
3317  while( i<k ){
3318    if( z[i]>=' ' ){
3319      n++;
3320      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3321      continue;
3322    }
3323    if( z[i]=='\t' ){
3324      do{
3325        n++;
3326        zOut[j++] = ' ';
3327      }while( (n&7)!=0 && n<mxWidth );
3328      i++;
3329      continue;
3330    }
3331    break;
3332  }
3333  zOut[j] = 0;
3334  return (char*)zOut;
3335}
3336
3337/* Extract the value of the i-th current column for pStmt as an SQL literal
3338** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3339** the caller.
3340*/
3341static char *quoted_column(sqlite3_stmt *pStmt, int i){
3342  switch( sqlite3_column_type(pStmt, i) ){
3343    case SQLITE_NULL: {
3344      return sqlite3_mprintf("NULL");
3345    }
3346    case SQLITE_INTEGER:
3347    case SQLITE_FLOAT: {
3348      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3349    }
3350    case SQLITE_TEXT: {
3351      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3352    }
3353    case SQLITE_BLOB: {
3354      int j;
3355      sqlite3_str *pStr = sqlite3_str_new(0);
3356      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3357      int n = sqlite3_column_bytes(pStmt,i);
3358      sqlite3_str_append(pStr, "x'", 2);
3359      for(j=0; j<n; j++){
3360        sqlite3_str_appendf(pStr, "%02x", a[j]);
3361      }
3362      sqlite3_str_append(pStr, "'", 1);
3363      return sqlite3_str_finish(pStr);
3364    }
3365  }
3366  return 0; /* Not reached */
3367}
3368
3369/*
3370** Run a prepared statement and output the result in one of the
3371** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3372** or MODE_Box.
3373**
3374** This is different from ordinary exec_prepared_stmt() in that
3375** it has to run the entire query and gather the results into memory
3376** first, in order to determine column widths, before providing
3377** any output.
3378*/
3379static void exec_prepared_stmt_columnar(
3380  ShellState *p,                        /* Pointer to ShellState */
3381  sqlite3_stmt *pStmt                   /* Statment to run */
3382){
3383  sqlite3_int64 nRow = 0;
3384  int nColumn = 0;
3385  char **azData = 0;
3386  sqlite3_int64 nAlloc = 0;
3387  char *abRowDiv = 0;
3388  const unsigned char *uz;
3389  const char *z;
3390  char **azQuoted = 0;
3391  int rc;
3392  sqlite3_int64 i, nData;
3393  int j, nTotal, w, n;
3394  const char *colSep = 0;
3395  const char *rowSep = 0;
3396  const unsigned char **azNextLine = 0;
3397  int bNextLine = 0;
3398  int bMultiLineRowExists = 0;
3399  int bw = p->cmOpts.bWordWrap;
3400  const char *zEmpty = "";
3401  const char *zShowNull = p->nullValue;
3402
3403  rc = sqlite3_step(pStmt);
3404  if( rc!=SQLITE_ROW ) return;
3405  nColumn = sqlite3_column_count(pStmt);
3406  nAlloc = nColumn*4;
3407  if( nAlloc<=0 ) nAlloc = 1;
3408  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3409  shell_check_oom(azData);
3410  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3411  shell_check_oom((void*)azNextLine);
3412  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3413  if( p->cmOpts.bQuote ){
3414    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3415    shell_check_oom(azQuoted);
3416    memset(azQuoted, 0, nColumn*sizeof(char*) );
3417  }
3418  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3419  shell_check_oom(abRowDiv);
3420  if( nColumn>p->nWidth ){
3421    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3422    shell_check_oom(p->colWidth);
3423    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3424    p->nWidth = nColumn;
3425    p->actualWidth = &p->colWidth[nColumn];
3426  }
3427  memset(p->actualWidth, 0, nColumn*sizeof(int));
3428  for(i=0; i<nColumn; i++){
3429    w = p->colWidth[i];
3430    if( w<0 ) w = -w;
3431    p->actualWidth[i] = w;
3432  }
3433  for(i=0; i<nColumn; i++){
3434    const unsigned char *zNotUsed;
3435    int wx = p->colWidth[i];
3436    if( wx==0 ){
3437      wx = p->cmOpts.iWrap;
3438    }
3439    if( wx<0 ) wx = -wx;
3440    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3441    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3442  }
3443  do{
3444    int useNextLine = bNextLine;
3445    bNextLine = 0;
3446    if( (nRow+2)*nColumn >= nAlloc ){
3447      nAlloc *= 2;
3448      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3449      shell_check_oom(azData);
3450      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3451      shell_check_oom(abRowDiv);
3452    }
3453    abRowDiv[nRow] = 1;
3454    nRow++;
3455    for(i=0; i<nColumn; i++){
3456      int wx = p->colWidth[i];
3457      if( wx==0 ){
3458        wx = p->cmOpts.iWrap;
3459      }
3460      if( wx<0 ) wx = -wx;
3461      if( useNextLine ){
3462        uz = azNextLine[i];
3463        if( uz==0 ) uz = (u8*)zEmpty;
3464      }else if( p->cmOpts.bQuote ){
3465        sqlite3_free(azQuoted[i]);
3466        azQuoted[i] = quoted_column(pStmt,i);
3467        uz = (const unsigned char*)azQuoted[i];
3468      }else{
3469        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3470        if( uz==0 ) uz = (u8*)zShowNull;
3471      }
3472      azData[nRow*nColumn + i]
3473        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3474      if( azNextLine[i] ){
3475        bNextLine = 1;
3476        abRowDiv[nRow-1] = 0;
3477        bMultiLineRowExists = 1;
3478      }
3479    }
3480  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3481  nTotal = nColumn*(nRow+1);
3482  for(i=0; i<nTotal; i++){
3483    z = azData[i];
3484    if( z==0 ) z = (char*)zEmpty;
3485    n = strlenChar(z);
3486    j = i%nColumn;
3487    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3488  }
3489  if( seenInterrupt ) goto columnar_end;
3490  if( nColumn==0 ) goto columnar_end;
3491  switch( p->cMode ){
3492    case MODE_Column: {
3493      colSep = "  ";
3494      rowSep = "\n";
3495      if( p->showHeader ){
3496        for(i=0; i<nColumn; i++){
3497          w = p->actualWidth[i];
3498          if( p->colWidth[i]<0 ) w = -w;
3499          utf8_width_print(p->out, w, azData[i]);
3500          fputs(i==nColumn-1?"\n":"  ", p->out);
3501        }
3502        for(i=0; i<nColumn; i++){
3503          print_dashes(p->out, p->actualWidth[i]);
3504          fputs(i==nColumn-1?"\n":"  ", p->out);
3505        }
3506      }
3507      break;
3508    }
3509    case MODE_Table: {
3510      colSep = " | ";
3511      rowSep = " |\n";
3512      print_row_separator(p, nColumn, "+");
3513      fputs("| ", p->out);
3514      for(i=0; i<nColumn; i++){
3515        w = p->actualWidth[i];
3516        n = strlenChar(azData[i]);
3517        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3518        fputs(i==nColumn-1?" |\n":" | ", p->out);
3519      }
3520      print_row_separator(p, nColumn, "+");
3521      break;
3522    }
3523    case MODE_Markdown: {
3524      colSep = " | ";
3525      rowSep = " |\n";
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_Box: {
3537      colSep = " " BOX_13 " ";
3538      rowSep = " " BOX_13 "\n";
3539      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3540      utf8_printf(p->out, BOX_13 " ");
3541      for(i=0; i<nColumn; i++){
3542        w = p->actualWidth[i];
3543        n = strlenChar(azData[i]);
3544        utf8_printf(p->out, "%*s%s%*s%s",
3545            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3546            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3547      }
3548      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3549      break;
3550    }
3551  }
3552  for(i=nColumn, j=0; i<nTotal; i++, j++){
3553    if( j==0 && p->cMode!=MODE_Column ){
3554      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3555    }
3556    z = azData[i];
3557    if( z==0 ) z = p->nullValue;
3558    w = p->actualWidth[j];
3559    if( p->colWidth[j]<0 ) w = -w;
3560    utf8_width_print(p->out, w, z);
3561    if( j==nColumn-1 ){
3562      utf8_printf(p->out, "%s", rowSep);
3563      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3564        if( p->cMode==MODE_Table ){
3565          print_row_separator(p, nColumn, "+");
3566        }else if( p->cMode==MODE_Box ){
3567          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3568        }else if( p->cMode==MODE_Column ){
3569          raw_printf(p->out, "\n");
3570        }
3571      }
3572      j = -1;
3573      if( seenInterrupt ) goto columnar_end;
3574    }else{
3575      utf8_printf(p->out, "%s", colSep);
3576    }
3577  }
3578  if( p->cMode==MODE_Table ){
3579    print_row_separator(p, nColumn, "+");
3580  }else if( p->cMode==MODE_Box ){
3581    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3582  }
3583columnar_end:
3584  if( seenInterrupt ){
3585    utf8_printf(p->out, "Interrupt\n");
3586  }
3587  nData = (nRow+1)*nColumn;
3588  for(i=0; i<nData; i++){
3589    z = azData[i];
3590    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3591  }
3592  sqlite3_free(azData);
3593  sqlite3_free((void*)azNextLine);
3594  sqlite3_free(abRowDiv);
3595  if( azQuoted ){
3596    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3597    sqlite3_free(azQuoted);
3598  }
3599}
3600
3601/*
3602** Run a prepared statement
3603*/
3604static void exec_prepared_stmt(
3605  ShellState *pArg,                                /* Pointer to ShellState */
3606  sqlite3_stmt *pStmt                              /* Statment to run */
3607){
3608  int rc;
3609  sqlite3_uint64 nRow = 0;
3610
3611  if( pArg->cMode==MODE_Column
3612   || pArg->cMode==MODE_Table
3613   || pArg->cMode==MODE_Box
3614   || pArg->cMode==MODE_Markdown
3615  ){
3616    exec_prepared_stmt_columnar(pArg, pStmt);
3617    return;
3618  }
3619
3620  /* perform the first step.  this will tell us if we
3621  ** have a result set or not and how wide it is.
3622  */
3623  rc = sqlite3_step(pStmt);
3624  /* if we have a result set... */
3625  if( SQLITE_ROW == rc ){
3626    /* allocate space for col name ptr, value ptr, and type */
3627    int nCol = sqlite3_column_count(pStmt);
3628    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3629    if( !pData ){
3630      shell_out_of_memory();
3631    }else{
3632      char **azCols = (char **)pData;      /* Names of result columns */
3633      char **azVals = &azCols[nCol];       /* Results */
3634      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3635      int i, x;
3636      assert(sizeof(int) <= sizeof(char *));
3637      /* save off ptrs to column names */
3638      for(i=0; i<nCol; i++){
3639        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3640      }
3641      do{
3642        nRow++;
3643        /* extract the data and data types */
3644        for(i=0; i<nCol; i++){
3645          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3646          if( x==SQLITE_BLOB
3647           && pArg
3648           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3649          ){
3650            azVals[i] = "";
3651          }else{
3652            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3653          }
3654          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3655            rc = SQLITE_NOMEM;
3656            break; /* from for */
3657          }
3658        } /* end for */
3659
3660        /* if data and types extracted successfully... */
3661        if( SQLITE_ROW == rc ){
3662          /* call the supplied callback with the result row data */
3663          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3664            rc = SQLITE_ABORT;
3665          }else{
3666            rc = sqlite3_step(pStmt);
3667          }
3668        }
3669      } while( SQLITE_ROW == rc );
3670      sqlite3_free(pData);
3671      if( pArg->cMode==MODE_Json ){
3672        fputs("]\n", pArg->out);
3673      }else if( pArg->cMode==MODE_Count ){
3674        char zBuf[200];
3675        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3676                         nRow, nRow!=1 ? "s" : "");
3677        printf("%s", zBuf);
3678      }
3679    }
3680  }
3681}
3682
3683#ifndef SQLITE_OMIT_VIRTUALTABLE
3684/*
3685** This function is called to process SQL if the previous shell command
3686** was ".expert". It passes the SQL in the second argument directly to
3687** the sqlite3expert object.
3688**
3689** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3690** code. In this case, (*pzErr) may be set to point to a buffer containing
3691** an English language error message. It is the responsibility of the
3692** caller to eventually free this buffer using sqlite3_free().
3693*/
3694static int expertHandleSQL(
3695  ShellState *pState,
3696  const char *zSql,
3697  char **pzErr
3698){
3699  assert( pState->expert.pExpert );
3700  assert( pzErr==0 || *pzErr==0 );
3701  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3702}
3703
3704/*
3705** This function is called either to silently clean up the object
3706** created by the ".expert" command (if bCancel==1), or to generate a
3707** report from it and then clean it up (if bCancel==0).
3708**
3709** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3710** code. In this case, (*pzErr) may be set to point to a buffer containing
3711** an English language error message. It is the responsibility of the
3712** caller to eventually free this buffer using sqlite3_free().
3713*/
3714static int expertFinish(
3715  ShellState *pState,
3716  int bCancel,
3717  char **pzErr
3718){
3719  int rc = SQLITE_OK;
3720  sqlite3expert *p = pState->expert.pExpert;
3721  assert( p );
3722  assert( bCancel || pzErr==0 || *pzErr==0 );
3723  if( bCancel==0 ){
3724    FILE *out = pState->out;
3725    int bVerbose = pState->expert.bVerbose;
3726
3727    rc = sqlite3_expert_analyze(p, pzErr);
3728    if( rc==SQLITE_OK ){
3729      int nQuery = sqlite3_expert_count(p);
3730      int i;
3731
3732      if( bVerbose ){
3733        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3734        raw_printf(out, "-- Candidates -----------------------------\n");
3735        raw_printf(out, "%s\n", zCand);
3736      }
3737      for(i=0; i<nQuery; i++){
3738        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3739        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3740        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3741        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3742        if( bVerbose ){
3743          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3744          raw_printf(out, "%s\n\n", zSql);
3745        }
3746        raw_printf(out, "%s\n", zIdx);
3747        raw_printf(out, "%s\n", zEQP);
3748      }
3749    }
3750  }
3751  sqlite3_expert_destroy(p);
3752  pState->expert.pExpert = 0;
3753  return rc;
3754}
3755
3756/*
3757** Implementation of ".expert" dot command.
3758*/
3759static int expertDotCommand(
3760  ShellState *pState,             /* Current shell tool state */
3761  char **azArg,                   /* Array of arguments passed to dot command */
3762  int nArg                        /* Number of entries in azArg[] */
3763){
3764  int rc = SQLITE_OK;
3765  char *zErr = 0;
3766  int i;
3767  int iSample = 0;
3768
3769  assert( pState->expert.pExpert==0 );
3770  memset(&pState->expert, 0, sizeof(ExpertInfo));
3771
3772  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3773    char *z = azArg[i];
3774    int n;
3775    if( z[0]=='-' && z[1]=='-' ) z++;
3776    n = strlen30(z);
3777    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3778      pState->expert.bVerbose = 1;
3779    }
3780    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3781      if( i==(nArg-1) ){
3782        raw_printf(stderr, "option requires an argument: %s\n", z);
3783        rc = SQLITE_ERROR;
3784      }else{
3785        iSample = (int)integerValue(azArg[++i]);
3786        if( iSample<0 || iSample>100 ){
3787          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3788          rc = SQLITE_ERROR;
3789        }
3790      }
3791    }
3792    else{
3793      raw_printf(stderr, "unknown option: %s\n", z);
3794      rc = SQLITE_ERROR;
3795    }
3796  }
3797
3798  if( rc==SQLITE_OK ){
3799    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3800    if( pState->expert.pExpert==0 ){
3801      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3802      rc = SQLITE_ERROR;
3803    }else{
3804      sqlite3_expert_config(
3805          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3806      );
3807    }
3808  }
3809  sqlite3_free(zErr);
3810
3811  return rc;
3812}
3813#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3814
3815/*
3816** Execute a statement or set of statements.  Print
3817** any result rows/columns depending on the current mode
3818** set via the supplied callback.
3819**
3820** This is very similar to SQLite's built-in sqlite3_exec()
3821** function except it takes a slightly different callback
3822** and callback data argument.
3823*/
3824static int shell_exec(
3825  ShellState *pArg,                         /* Pointer to ShellState */
3826  const char *zSql,                         /* SQL to be evaluated */
3827  char **pzErrMsg                           /* Error msg written here */
3828){
3829  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3830  int rc = SQLITE_OK;             /* Return Code */
3831  int rc2;
3832  const char *zLeftover;          /* Tail of unprocessed SQL */
3833  sqlite3 *db = pArg->db;
3834
3835  if( pzErrMsg ){
3836    *pzErrMsg = NULL;
3837  }
3838
3839#ifndef SQLITE_OMIT_VIRTUALTABLE
3840  if( pArg->expert.pExpert ){
3841    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3842    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3843  }
3844#endif
3845
3846  while( zSql[0] && (SQLITE_OK == rc) ){
3847    static const char *zStmtSql;
3848    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3849    if( SQLITE_OK != rc ){
3850      if( pzErrMsg ){
3851        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3852      }
3853    }else{
3854      if( !pStmt ){
3855        /* this happens for a comment or white-space */
3856        zSql = zLeftover;
3857        while( IsSpace(zSql[0]) ) zSql++;
3858        continue;
3859      }
3860      zStmtSql = sqlite3_sql(pStmt);
3861      if( zStmtSql==0 ) zStmtSql = "";
3862      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3863
3864      /* save off the prepared statment handle and reset row count */
3865      if( pArg ){
3866        pArg->pStmt = pStmt;
3867        pArg->cnt = 0;
3868      }
3869
3870      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3871      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3872        sqlite3_stmt *pExplain;
3873        char *zEQP;
3874        int triggerEQP = 0;
3875        disable_debug_trace_modes();
3876        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3877        if( pArg->autoEQP>=AUTOEQP_trigger ){
3878          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3879        }
3880        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3881        shell_check_oom(zEQP);
3882        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3883        if( rc==SQLITE_OK ){
3884          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3885            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3886            int iEqpId = sqlite3_column_int(pExplain, 0);
3887            int iParentId = sqlite3_column_int(pExplain, 1);
3888            if( zEQPLine==0 ) zEQPLine = "";
3889            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3890            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3891          }
3892          eqp_render(pArg);
3893        }
3894        sqlite3_finalize(pExplain);
3895        sqlite3_free(zEQP);
3896        if( pArg->autoEQP>=AUTOEQP_full ){
3897          /* Also do an EXPLAIN for ".eqp full" mode */
3898          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3899          shell_check_oom(zEQP);
3900          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3901          if( rc==SQLITE_OK ){
3902            pArg->cMode = MODE_Explain;
3903            explain_data_prepare(pArg, pExplain);
3904            exec_prepared_stmt(pArg, pExplain);
3905            explain_data_delete(pArg);
3906          }
3907          sqlite3_finalize(pExplain);
3908          sqlite3_free(zEQP);
3909        }
3910        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3911          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3912          /* Reprepare pStmt before reactiving trace modes */
3913          sqlite3_finalize(pStmt);
3914          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3915          if( pArg ) pArg->pStmt = pStmt;
3916        }
3917        restore_debug_trace_modes();
3918      }
3919
3920      if( pArg ){
3921        pArg->cMode = pArg->mode;
3922        if( pArg->autoExplain ){
3923          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3924            pArg->cMode = MODE_Explain;
3925          }
3926          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3927            pArg->cMode = MODE_EQP;
3928          }
3929        }
3930
3931        /* If the shell is currently in ".explain" mode, gather the extra
3932        ** data required to add indents to the output.*/
3933        if( pArg->cMode==MODE_Explain ){
3934          explain_data_prepare(pArg, pStmt);
3935        }
3936      }
3937
3938      bind_prepared_stmt(pArg, pStmt);
3939      exec_prepared_stmt(pArg, pStmt);
3940      explain_data_delete(pArg);
3941      eqp_render(pArg);
3942
3943      /* print usage stats if stats on */
3944      if( pArg && pArg->statsOn ){
3945        display_stats(db, pArg, 0);
3946      }
3947
3948      /* print loop-counters if required */
3949      if( pArg && pArg->scanstatsOn ){
3950        display_scanstats(db, pArg);
3951      }
3952
3953      /* Finalize the statement just executed. If this fails, save a
3954      ** copy of the error message. Otherwise, set zSql to point to the
3955      ** next statement to execute. */
3956      rc2 = sqlite3_finalize(pStmt);
3957      if( rc!=SQLITE_NOMEM ) rc = rc2;
3958      if( rc==SQLITE_OK ){
3959        zSql = zLeftover;
3960        while( IsSpace(zSql[0]) ) zSql++;
3961      }else if( pzErrMsg ){
3962        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3963      }
3964
3965      /* clear saved stmt handle */
3966      if( pArg ){
3967        pArg->pStmt = NULL;
3968      }
3969    }
3970  } /* end while */
3971
3972  return rc;
3973}
3974
3975/*
3976** Release memory previously allocated by tableColumnList().
3977*/
3978static void freeColumnList(char **azCol){
3979  int i;
3980  for(i=1; azCol[i]; i++){
3981    sqlite3_free(azCol[i]);
3982  }
3983  /* azCol[0] is a static string */
3984  sqlite3_free(azCol);
3985}
3986
3987/*
3988** Return a list of pointers to strings which are the names of all
3989** columns in table zTab.   The memory to hold the names is dynamically
3990** allocated and must be released by the caller using a subsequent call
3991** to freeColumnList().
3992**
3993** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3994** value that needs to be preserved, then azCol[0] is filled in with the
3995** name of the rowid column.
3996**
3997** The first regular column in the table is azCol[1].  The list is terminated
3998** by an entry with azCol[i]==0.
3999*/
4000static char **tableColumnList(ShellState *p, const char *zTab){
4001  char **azCol = 0;
4002  sqlite3_stmt *pStmt;
4003  char *zSql;
4004  int nCol = 0;
4005  int nAlloc = 0;
4006  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
4007  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
4008  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4009  int rc;
4010
4011  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4012  shell_check_oom(zSql);
4013  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4014  sqlite3_free(zSql);
4015  if( rc ) return 0;
4016  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4017    if( nCol>=nAlloc-2 ){
4018      nAlloc = nAlloc*2 + nCol + 10;
4019      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4020      shell_check_oom(azCol);
4021    }
4022    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4023    shell_check_oom(azCol[nCol]);
4024    if( sqlite3_column_int(pStmt, 5) ){
4025      nPK++;
4026      if( nPK==1
4027       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4028                          "INTEGER")==0
4029      ){
4030        isIPK = 1;
4031      }else{
4032        isIPK = 0;
4033      }
4034    }
4035  }
4036  sqlite3_finalize(pStmt);
4037  if( azCol==0 ) return 0;
4038  azCol[0] = 0;
4039  azCol[nCol+1] = 0;
4040
4041  /* The decision of whether or not a rowid really needs to be preserved
4042  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4043  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4044  ** rowids on tables where the rowid is inaccessible because there are other
4045  ** columns in the table named "rowid", "_rowid_", and "oid".
4046  */
4047  if( preserveRowid && isIPK ){
4048    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4049    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4050    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4051    ** ROWID aliases.  To distinguish these cases, check to see if
4052    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4053    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4054    */
4055    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4056                           " WHERE origin='pk'", zTab);
4057    shell_check_oom(zSql);
4058    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4059    sqlite3_free(zSql);
4060    if( rc ){
4061      freeColumnList(azCol);
4062      return 0;
4063    }
4064    rc = sqlite3_step(pStmt);
4065    sqlite3_finalize(pStmt);
4066    preserveRowid = rc==SQLITE_ROW;
4067  }
4068  if( preserveRowid ){
4069    /* Only preserve the rowid if we can find a name to use for the
4070    ** rowid */
4071    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4072    int i, j;
4073    for(j=0; j<3; j++){
4074      for(i=1; i<=nCol; i++){
4075        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4076      }
4077      if( i>nCol ){
4078        /* At this point, we know that azRowid[j] is not the name of any
4079        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4080        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4081        ** tables will fail this last check */
4082        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4083        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4084        break;
4085      }
4086    }
4087  }
4088  return azCol;
4089}
4090
4091/*
4092** Toggle the reverse_unordered_selects setting.
4093*/
4094static void toggleSelectOrder(sqlite3 *db){
4095  sqlite3_stmt *pStmt = 0;
4096  int iSetting = 0;
4097  char zStmt[100];
4098  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4099  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4100    iSetting = sqlite3_column_int(pStmt, 0);
4101  }
4102  sqlite3_finalize(pStmt);
4103  sqlite3_snprintf(sizeof(zStmt), zStmt,
4104       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4105  sqlite3_exec(db, zStmt, 0, 0, 0);
4106}
4107
4108/*
4109** This is a different callback routine used for dumping the database.
4110** Each row received by this callback consists of a table name,
4111** the table type ("index" or "table") and SQL to create the table.
4112** This routine should print text sufficient to recreate the table.
4113*/
4114static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4115  int rc;
4116  const char *zTable;
4117  const char *zType;
4118  const char *zSql;
4119  ShellState *p = (ShellState *)pArg;
4120  int dataOnly;
4121  int noSys;
4122
4123  UNUSED_PARAMETER(azNotUsed);
4124  if( nArg!=3 || azArg==0 ) return 0;
4125  zTable = azArg[0];
4126  zType = azArg[1];
4127  zSql = azArg[2];
4128  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4129  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4130
4131  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4132    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4133  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4134    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4135  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4136    return 0;
4137  }else if( dataOnly ){
4138    /* no-op */
4139  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4140    char *zIns;
4141    if( !p->writableSchema ){
4142      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4143      p->writableSchema = 1;
4144    }
4145    zIns = sqlite3_mprintf(
4146       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4147       "VALUES('table','%q','%q',0,'%q');",
4148       zTable, zTable, zSql);
4149    shell_check_oom(zIns);
4150    utf8_printf(p->out, "%s\n", zIns);
4151    sqlite3_free(zIns);
4152    return 0;
4153  }else{
4154    printSchemaLine(p->out, zSql, ";\n");
4155  }
4156
4157  if( strcmp(zType, "table")==0 ){
4158    ShellText sSelect;
4159    ShellText sTable;
4160    char **azCol;
4161    int i;
4162    char *savedDestTable;
4163    int savedMode;
4164
4165    azCol = tableColumnList(p, zTable);
4166    if( azCol==0 ){
4167      p->nErr++;
4168      return 0;
4169    }
4170
4171    /* Always quote the table name, even if it appears to be pure ascii,
4172    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4173    initText(&sTable);
4174    appendText(&sTable, zTable, quoteChar(zTable));
4175    /* If preserving the rowid, add a column list after the table name.
4176    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4177    ** instead of the usual "INSERT INTO tab VALUES(...)".
4178    */
4179    if( azCol[0] ){
4180      appendText(&sTable, "(", 0);
4181      appendText(&sTable, azCol[0], 0);
4182      for(i=1; azCol[i]; i++){
4183        appendText(&sTable, ",", 0);
4184        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4185      }
4186      appendText(&sTable, ")", 0);
4187    }
4188
4189    /* Build an appropriate SELECT statement */
4190    initText(&sSelect);
4191    appendText(&sSelect, "SELECT ", 0);
4192    if( azCol[0] ){
4193      appendText(&sSelect, azCol[0], 0);
4194      appendText(&sSelect, ",", 0);
4195    }
4196    for(i=1; azCol[i]; i++){
4197      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4198      if( azCol[i+1] ){
4199        appendText(&sSelect, ",", 0);
4200      }
4201    }
4202    freeColumnList(azCol);
4203    appendText(&sSelect, " FROM ", 0);
4204    appendText(&sSelect, zTable, quoteChar(zTable));
4205
4206    savedDestTable = p->zDestTable;
4207    savedMode = p->mode;
4208    p->zDestTable = sTable.z;
4209    p->mode = p->cMode = MODE_Insert;
4210    rc = shell_exec(p, sSelect.z, 0);
4211    if( (rc&0xff)==SQLITE_CORRUPT ){
4212      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4213      toggleSelectOrder(p->db);
4214      shell_exec(p, sSelect.z, 0);
4215      toggleSelectOrder(p->db);
4216    }
4217    p->zDestTable = savedDestTable;
4218    p->mode = savedMode;
4219    freeText(&sTable);
4220    freeText(&sSelect);
4221    if( rc ) p->nErr++;
4222  }
4223  return 0;
4224}
4225
4226/*
4227** Run zQuery.  Use dump_callback() as the callback routine so that
4228** the contents of the query are output as SQL statements.
4229**
4230** If we get a SQLITE_CORRUPT error, rerun the query after appending
4231** "ORDER BY rowid DESC" to the end.
4232*/
4233static int run_schema_dump_query(
4234  ShellState *p,
4235  const char *zQuery
4236){
4237  int rc;
4238  char *zErr = 0;
4239  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4240  if( rc==SQLITE_CORRUPT ){
4241    char *zQ2;
4242    int len = strlen30(zQuery);
4243    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4244    if( zErr ){
4245      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4246      sqlite3_free(zErr);
4247      zErr = 0;
4248    }
4249    zQ2 = malloc( len+100 );
4250    if( zQ2==0 ) return rc;
4251    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4252    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4253    if( rc ){
4254      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4255    }else{
4256      rc = SQLITE_CORRUPT;
4257    }
4258    sqlite3_free(zErr);
4259    free(zQ2);
4260  }
4261  return rc;
4262}
4263
4264/*
4265** Text of help messages.
4266**
4267** The help text for each individual command begins with a line that starts
4268** with ".".  Subsequent lines are supplemental information.
4269**
4270** There must be two or more spaces between the end of the command and the
4271** start of the description of what that command does.
4272*/
4273static const char *(azHelp[]) = {
4274#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4275  && !defined(SQLITE_SHELL_FIDDLE)
4276  ".archive ...             Manage SQL archives",
4277  "   Each command must have exactly one of the following options:",
4278  "     -c, --create               Create a new archive",
4279  "     -u, --update               Add or update files with changed mtime",
4280  "     -i, --insert               Like -u but always add even if unchanged",
4281  "     -r, --remove               Remove files from archive",
4282  "     -t, --list                 List contents of archive",
4283  "     -x, --extract              Extract files from archive",
4284  "   Optional arguments:",
4285  "     -v, --verbose              Print each filename as it is processed",
4286  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4287  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4288  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4289  "     -g, --glob                 Use glob matching for names in archive",
4290  "     -n, --dryrun               Show the SQL that would have occurred",
4291  "   Examples:",
4292  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4293  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4294  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4295  "   See also:",
4296  "      http://sqlite.org/cli.html#sqlite_archive_support",
4297#endif
4298#ifndef SQLITE_OMIT_AUTHORIZATION
4299  ".auth ON|OFF             Show authorizer callbacks",
4300#endif
4301#ifndef SQLITE_SHELL_FIDDLE
4302  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4303  "   Options:",
4304  "       --append            Use the appendvfs",
4305  "       --async             Write to FILE without journal and fsync()",
4306#endif
4307  ".bail on|off             Stop after hitting an error.  Default OFF",
4308  ".binary on|off           Turn binary output on or off.  Default OFF",
4309#ifndef SQLITE_SHELL_FIDDLE
4310  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4311#endif
4312  ".changes on|off          Show number of rows changed by SQL",
4313#ifndef SQLITE_SHELL_FIDDLE
4314  ".check GLOB              Fail if output since .testcase does not match",
4315  ".clone NEWDB             Clone data into NEWDB from the existing database",
4316#endif
4317  ".connection [close] [#]  Open or close an auxiliary database connection",
4318  ".databases               List names and files of attached databases",
4319  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4320#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4321  ".dbinfo ?DB?             Show status information about the database",
4322#endif
4323  ".dump ?OBJECTS?          Render database content as SQL",
4324  "   Options:",
4325  "     --data-only            Output only INSERT statements",
4326  "     --newlines             Allow unescaped newline characters in output",
4327  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4328  "     --preserve-rowids      Include ROWID values in the output",
4329  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4330  "   Additional LIKE patterns can be given in subsequent arguments",
4331  ".echo on|off             Turn command echo on or off",
4332  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4333  "   Other Modes:",
4334#ifdef SQLITE_DEBUG
4335  "      test                  Show raw EXPLAIN QUERY PLAN output",
4336  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4337#endif
4338  "      trigger               Like \"full\" but also show trigger bytecode",
4339#ifndef SQLITE_SHELL_FIDDLE
4340  ".excel                   Display the output of next command in spreadsheet",
4341  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4342#endif
4343#ifndef SQLITE_SHELL_FIDDLE
4344  ".exit ?CODE?             Exit this program with return-code CODE",
4345#endif
4346  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4347  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4348  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4349  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4350  "   --help                  Show CMD details",
4351  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4352  ".headers on|off          Turn display of headers on or off",
4353  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4354#ifndef SQLITE_SHELL_FIDDLE
4355  ".import FILE TABLE       Import data from FILE into TABLE",
4356  "   Options:",
4357  "     --ascii               Use \\037 and \\036 as column and row separators",
4358  "     --csv                 Use , and \\n as column and row separators",
4359  "     --skip N              Skip the first N rows of input",
4360  "     --schema S            Target table to be S.TABLE",
4361  "     -v                    \"Verbose\" - increase auxiliary output",
4362  "   Notes:",
4363  "     *  If TABLE does not exist, it is created.  The first row of input",
4364  "        determines the column names.",
4365  "     *  If neither --csv or --ascii are used, the input mode is derived",
4366  "        from the \".mode\" output mode",
4367  "     *  If FILE begins with \"|\" then it is a command that generates the",
4368  "        input text.",
4369#endif
4370#ifndef SQLITE_OMIT_TEST_CONTROL
4371  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4372#endif
4373  ".indexes ?TABLE?         Show names of indexes",
4374  "                           If TABLE is specified, only show indexes for",
4375  "                           tables matching TABLE using the LIKE operator.",
4376#ifdef SQLITE_ENABLE_IOTRACE
4377  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4378#endif
4379  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4380  ".lint OPTIONS            Report potential schema issues.",
4381  "     Options:",
4382  "        fkey-indexes     Find missing foreign key indexes",
4383#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4384  ".load FILE ?ENTRY?       Load an extension library",
4385#endif
4386#ifndef SQLITE_SHELL_FIDDLE
4387  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4388#endif
4389  ".mode MODE ?OPTIONS?     Set output mode",
4390  "   MODE is one of:",
4391  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4392  "     box         Tables using unicode box-drawing characters",
4393  "     csv         Comma-separated values",
4394  "     column      Output in columns.  (See .width)",
4395  "     html        HTML <table> code",
4396  "     insert      SQL insert statements for TABLE",
4397  "     json        Results in a JSON array",
4398  "     line        One value per line",
4399  "     list        Values delimited by \"|\"",
4400  "     markdown    Markdown table format",
4401  "     qbox        Shorthand for \"box --width 60 --quote\"",
4402  "     quote       Escape answers as for SQL",
4403  "     table       ASCII-art table",
4404  "     tabs        Tab-separated values",
4405  "     tcl         TCL list elements",
4406  "   OPTIONS: (for columnar modes or insert mode):",
4407  "     --wrap N       Wrap output lines to no longer than N characters",
4408  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4409  "     --ww           Shorthand for \"--wordwrap 1\"",
4410  "     --quote        Quote output text as SQL literals",
4411  "     --noquote      Do not quote output text",
4412  "     TABLE          The name of SQL table used for \"insert\" mode",
4413#ifndef SQLITE_SHELL_FIDDLE
4414  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4415#endif
4416  ".nullvalue STRING        Use STRING in place of NULL values",
4417#ifndef SQLITE_SHELL_FIDDLE
4418  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4419  "     If FILE begins with '|' then open as a pipe",
4420  "       --bom  Put a UTF8 byte-order mark at the beginning",
4421  "       -e     Send output to the system text editor",
4422  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4423  /* Note that .open is (partially) available in WASM builds but is
4424  ** currently only intended to be used by the fiddle tool, not
4425  ** end users, so is "undocumented." */
4426  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4427  "     Options:",
4428  "        --append        Use appendvfs to append database to the end of FILE",
4429#endif
4430#ifndef SQLITE_OMIT_DESERIALIZE
4431  "        --deserialize   Load into memory using sqlite3_deserialize()",
4432  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4433  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4434#endif
4435  "        --new           Initialize FILE to an empty database",
4436  "        --nofollow      Do not follow symbolic links",
4437  "        --readonly      Open FILE readonly",
4438  "        --zip           FILE is a ZIP archive",
4439#ifndef SQLITE_SHELL_FIDDLE
4440  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4441  "   If FILE begins with '|' then open it as a pipe.",
4442  "   Options:",
4443  "     --bom                 Prefix output with a UTF8 byte-order mark",
4444  "     -e                    Send output to the system text editor",
4445  "     -x                    Send output as CSV to a spreadsheet",
4446#endif
4447  ".parameter CMD ...       Manage SQL parameter bindings",
4448  "   clear                   Erase all bindings",
4449  "   init                    Initialize the TEMP table that holds bindings",
4450  "   list                    List the current parameter bindings",
4451  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4452  "                           PARAMETER should start with one of: $ : @ ?",
4453  "   unset PARAMETER         Remove PARAMETER from the binding table",
4454  ".print STRING...         Print literal STRING",
4455#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4456  ".progress N              Invoke progress handler after every N opcodes",
4457  "   --limit N                 Interrupt after N progress callbacks",
4458  "   --once                    Do no more than one progress interrupt",
4459  "   --quiet|-q                No output except at interrupts",
4460  "   --reset                   Reset the count for each input and interrupt",
4461#endif
4462  ".prompt MAIN CONTINUE    Replace the standard prompts",
4463#ifndef SQLITE_SHELL_FIDDLE
4464  ".quit                    Exit this program",
4465  ".read FILE               Read input from FILE or command output",
4466  "    If FILE begins with \"|\", it is a command that generates the input.",
4467#endif
4468#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4469  ".recover                 Recover as much data as possible from corrupt db.",
4470  "   --freelist-corrupt       Assume the freelist is corrupt",
4471  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4472  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4473  "   --no-rowids              Do not attempt to recover rowid values",
4474  "                            that are not also INTEGER PRIMARY KEYs",
4475#endif
4476#ifndef SQLITE_SHELL_FIDDLE
4477  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4478  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4479#endif
4480  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4481  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4482  "   Options:",
4483  "      --indent             Try to pretty-print the schema",
4484  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4485  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4486  "    Options:",
4487  "       --init               Create a new SELFTEST table",
4488  "       -v                   Verbose output",
4489  ".separator COL ?ROW?     Change the column and row separators",
4490#if defined(SQLITE_ENABLE_SESSION)
4491  ".session ?NAME? CMD ...  Create or control sessions",
4492  "   Subcommands:",
4493  "     attach TABLE             Attach TABLE",
4494  "     changeset FILE           Write a changeset into FILE",
4495  "     close                    Close one session",
4496  "     enable ?BOOLEAN?         Set or query the enable bit",
4497  "     filter GLOB...           Reject tables matching GLOBs",
4498  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4499  "     isempty                  Query whether the session is empty",
4500  "     list                     List currently open session names",
4501  "     open DB NAME             Open a new session on DB",
4502  "     patchset FILE            Write a patchset into FILE",
4503  "   If ?NAME? is omitted, the first defined session is used.",
4504#endif
4505  ".sha3sum ...             Compute a SHA3 hash of database content",
4506  "    Options:",
4507  "      --schema              Also hash the sqlite_schema table",
4508  "      --sha3-224            Use the sha3-224 algorithm",
4509  "      --sha3-256            Use the sha3-256 algorithm (default)",
4510  "      --sha3-384            Use the sha3-384 algorithm",
4511  "      --sha3-512            Use the sha3-512 algorithm",
4512  "    Any other argument is a LIKE pattern for tables to hash",
4513#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4514  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4515#endif
4516  ".show                    Show the current values for various settings",
4517  ".stats ?ARG?             Show stats or turn stats on or off",
4518  "   off                      Turn off automatic stat display",
4519  "   on                       Turn on automatic stat display",
4520  "   stmt                     Show statement stats",
4521  "   vmstep                   Show the virtual machine step count only",
4522#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4523  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4524#endif
4525  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4526#ifndef SQLITE_SHELL_FIDDLE
4527  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4528#endif
4529  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4530  "                           Run \".testctrl\" with no arguments for details",
4531  ".timeout MS              Try opening locked tables for MS milliseconds",
4532  ".timer on|off            Turn SQL timer on or off",
4533#ifndef SQLITE_OMIT_TRACE
4534  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4535  "    FILE                    Send output to FILE",
4536  "    stdout                  Send output to stdout",
4537  "    stderr                  Send output to stderr",
4538  "    off                     Disable tracing",
4539  "    --expanded              Expand query parameters",
4540#ifdef SQLITE_ENABLE_NORMALIZE
4541  "    --normalized            Normal the SQL statements",
4542#endif
4543  "    --plain                 Show SQL as it is input",
4544  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4545  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4546  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4547  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4548#endif /* SQLITE_OMIT_TRACE */
4549#ifdef SQLITE_DEBUG
4550  ".unmodule NAME ...       Unregister virtual table modules",
4551  "    --allexcept             Unregister everything except those named",
4552#endif
4553  ".vfsinfo ?AUX?           Information about the top-level VFS",
4554  ".vfslist                 List all available VFSes",
4555  ".vfsname ?AUX?           Print the name of the VFS stack",
4556  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4557  "     Negative values right-justify",
4558};
4559
4560/*
4561** Output help text.
4562**
4563** zPattern describes the set of commands for which help text is provided.
4564** If zPattern is NULL, then show all commands, but only give a one-line
4565** description of each.
4566**
4567** Return the number of matches.
4568*/
4569static int showHelp(FILE *out, const char *zPattern){
4570  int i = 0;
4571  int j = 0;
4572  int n = 0;
4573  char *zPat;
4574  if( zPattern==0
4575   || zPattern[0]=='0'
4576   || strcmp(zPattern,"-a")==0
4577   || strcmp(zPattern,"-all")==0
4578   || strcmp(zPattern,"--all")==0
4579  ){
4580    /* Show all commands, but only one line per command */
4581    if( zPattern==0 ) zPattern = "";
4582    for(i=0; i<ArraySize(azHelp); i++){
4583      if( azHelp[i][0]=='.' || zPattern[0] ){
4584        utf8_printf(out, "%s\n", azHelp[i]);
4585        n++;
4586      }
4587    }
4588  }else{
4589    /* Look for commands that for which zPattern is an exact prefix */
4590    zPat = sqlite3_mprintf(".%s*", zPattern);
4591    shell_check_oom(zPat);
4592    for(i=0; i<ArraySize(azHelp); i++){
4593      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4594        utf8_printf(out, "%s\n", azHelp[i]);
4595        j = i+1;
4596        n++;
4597      }
4598    }
4599    sqlite3_free(zPat);
4600    if( n ){
4601      if( n==1 ){
4602        /* when zPattern is a prefix of exactly one command, then include the
4603        ** details of that command, which should begin at offset j */
4604        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4605          utf8_printf(out, "%s\n", azHelp[j]);
4606          j++;
4607        }
4608      }
4609      return n;
4610    }
4611    /* Look for commands that contain zPattern anywhere.  Show the complete
4612    ** text of all commands that match. */
4613    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4614    shell_check_oom(zPat);
4615    for(i=0; i<ArraySize(azHelp); i++){
4616      if( azHelp[i][0]=='.' ) j = i;
4617      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4618        utf8_printf(out, "%s\n", azHelp[j]);
4619        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4620          j++;
4621          utf8_printf(out, "%s\n", azHelp[j]);
4622        }
4623        i = j;
4624        n++;
4625      }
4626    }
4627    sqlite3_free(zPat);
4628  }
4629  return n;
4630}
4631
4632/* Forward reference */
4633static int process_input(ShellState *p);
4634
4635/*
4636** Read the content of file zName into memory obtained from sqlite3_malloc64()
4637** and return a pointer to the buffer. The caller is responsible for freeing
4638** the memory.
4639**
4640** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4641** read.
4642**
4643** For convenience, a nul-terminator byte is always appended to the data read
4644** from the file before the buffer is returned. This byte is not included in
4645** the final value of (*pnByte), if applicable.
4646**
4647** NULL is returned if any error is encountered. The final value of *pnByte
4648** is undefined in this case.
4649*/
4650static char *readFile(const char *zName, int *pnByte){
4651  FILE *in = fopen(zName, "rb");
4652  long nIn;
4653  size_t nRead;
4654  char *pBuf;
4655  if( in==0 ) return 0;
4656  fseek(in, 0, SEEK_END);
4657  nIn = ftell(in);
4658  rewind(in);
4659  pBuf = sqlite3_malloc64( nIn+1 );
4660  if( pBuf==0 ){ fclose(in); return 0; }
4661  nRead = fread(pBuf, nIn, 1, in);
4662  fclose(in);
4663  if( nRead!=1 ){
4664    sqlite3_free(pBuf);
4665    return 0;
4666  }
4667  pBuf[nIn] = 0;
4668  if( pnByte ) *pnByte = nIn;
4669  return pBuf;
4670}
4671
4672#if defined(SQLITE_ENABLE_SESSION)
4673/*
4674** Close a single OpenSession object and release all of its associated
4675** resources.
4676*/
4677static void session_close(OpenSession *pSession){
4678  int i;
4679  sqlite3session_delete(pSession->p);
4680  sqlite3_free(pSession->zName);
4681  for(i=0; i<pSession->nFilter; i++){
4682    sqlite3_free(pSession->azFilter[i]);
4683  }
4684  sqlite3_free(pSession->azFilter);
4685  memset(pSession, 0, sizeof(OpenSession));
4686}
4687#endif
4688
4689/*
4690** Close all OpenSession objects and release all associated resources.
4691*/
4692#if defined(SQLITE_ENABLE_SESSION)
4693static void session_close_all(ShellState *p, int i){
4694  int j;
4695  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4696  for(j=0; j<pAuxDb->nSession; j++){
4697    session_close(&pAuxDb->aSession[j]);
4698  }
4699  pAuxDb->nSession = 0;
4700}
4701#else
4702# define session_close_all(X,Y)
4703#endif
4704
4705/*
4706** Implementation of the xFilter function for an open session.  Omit
4707** any tables named by ".session filter" but let all other table through.
4708*/
4709#if defined(SQLITE_ENABLE_SESSION)
4710static int session_filter(void *pCtx, const char *zTab){
4711  OpenSession *pSession = (OpenSession*)pCtx;
4712  int i;
4713  for(i=0; i<pSession->nFilter; i++){
4714    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4715  }
4716  return 1;
4717}
4718#endif
4719
4720/*
4721** Try to deduce the type of file for zName based on its content.  Return
4722** one of the SHELL_OPEN_* constants.
4723**
4724** If the file does not exist or is empty but its name looks like a ZIP
4725** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4726** Otherwise, assume an ordinary database regardless of the filename if
4727** the type cannot be determined from content.
4728*/
4729int deduceDatabaseType(const char *zName, int dfltZip){
4730  FILE *f = fopen(zName, "rb");
4731  size_t n;
4732  int rc = SHELL_OPEN_UNSPEC;
4733  char zBuf[100];
4734  if( f==0 ){
4735    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4736       return SHELL_OPEN_ZIPFILE;
4737    }else{
4738       return SHELL_OPEN_NORMAL;
4739    }
4740  }
4741  n = fread(zBuf, 16, 1, f);
4742  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4743    fclose(f);
4744    return SHELL_OPEN_NORMAL;
4745  }
4746  fseek(f, -25, SEEK_END);
4747  n = fread(zBuf, 25, 1, f);
4748  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4749    rc = SHELL_OPEN_APPENDVFS;
4750  }else{
4751    fseek(f, -22, SEEK_END);
4752    n = fread(zBuf, 22, 1, f);
4753    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4754       && zBuf[3]==0x06 ){
4755      rc = SHELL_OPEN_ZIPFILE;
4756    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4757      rc = SHELL_OPEN_ZIPFILE;
4758    }
4759  }
4760  fclose(f);
4761  return rc;
4762}
4763
4764#ifndef SQLITE_OMIT_DESERIALIZE
4765/*
4766** Reconstruct an in-memory database using the output from the "dbtotxt"
4767** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4768** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4769*/
4770static unsigned char *readHexDb(ShellState *p, int *pnData){
4771  unsigned char *a = 0;
4772  int nLine;
4773  int n = 0;
4774  int pgsz = 0;
4775  int iOffset = 0;
4776  int j, k;
4777  int rc;
4778  FILE *in;
4779  const char *zDbFilename = p->pAuxDb->zDbFilename;
4780  unsigned int x[16];
4781  char zLine[1000];
4782  if( zDbFilename ){
4783    in = fopen(zDbFilename, "r");
4784    if( in==0 ){
4785      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4786      return 0;
4787    }
4788    nLine = 0;
4789  }else{
4790    in = p->in;
4791    nLine = p->lineno;
4792    if( in==0 ) in = stdin;
4793  }
4794  *pnData = 0;
4795  nLine++;
4796  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4797  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4798  if( rc!=2 ) goto readHexDb_error;
4799  if( n<0 ) goto readHexDb_error;
4800  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4801  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4802  a = sqlite3_malloc( n ? n : 1 );
4803  shell_check_oom(a);
4804  memset(a, 0, n);
4805  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4806    utf8_printf(stderr, "invalid pagesize\n");
4807    goto readHexDb_error;
4808  }
4809  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4810    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4811    if( rc==2 ){
4812      iOffset = k;
4813      continue;
4814    }
4815    if( strncmp(zLine, "| end ", 6)==0 ){
4816      break;
4817    }
4818    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4819                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4820                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4821    if( rc==17 ){
4822      k = iOffset+j;
4823      if( k+16<=n && k>=0 ){
4824        int ii;
4825        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4826      }
4827    }
4828  }
4829  *pnData = n;
4830  if( in!=p->in ){
4831    fclose(in);
4832  }else{
4833    p->lineno = nLine;
4834  }
4835  return a;
4836
4837readHexDb_error:
4838  if( in!=p->in ){
4839    fclose(in);
4840  }else{
4841    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4842      nLine++;
4843      if(strncmp(zLine, "| end ", 6)==0 ) break;
4844    }
4845    p->lineno = nLine;
4846  }
4847  sqlite3_free(a);
4848  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4849  return 0;
4850}
4851#endif /* SQLITE_OMIT_DESERIALIZE */
4852
4853/*
4854** Scalar function "shell_int32". The first argument to this function
4855** must be a blob. The second a non-negative integer. This function
4856** reads and returns a 32-bit big-endian integer from byte
4857** offset (4*<arg2>) of the blob.
4858*/
4859static void shellInt32(
4860  sqlite3_context *context,
4861  int argc,
4862  sqlite3_value **argv
4863){
4864  const unsigned char *pBlob;
4865  int nBlob;
4866  int iInt;
4867
4868  UNUSED_PARAMETER(argc);
4869  nBlob = sqlite3_value_bytes(argv[0]);
4870  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4871  iInt = sqlite3_value_int(argv[1]);
4872
4873  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4874    const unsigned char *a = &pBlob[iInt*4];
4875    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4876                       + ((sqlite3_int64)a[1]<<16)
4877                       + ((sqlite3_int64)a[2]<< 8)
4878                       + ((sqlite3_int64)a[3]<< 0);
4879    sqlite3_result_int64(context, iVal);
4880  }
4881}
4882
4883/*
4884** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4885** using "..." with internal double-quote characters doubled.
4886*/
4887static void shellIdQuote(
4888  sqlite3_context *context,
4889  int argc,
4890  sqlite3_value **argv
4891){
4892  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4893  UNUSED_PARAMETER(argc);
4894  if( zName ){
4895    char *z = sqlite3_mprintf("\"%w\"", zName);
4896    sqlite3_result_text(context, z, -1, sqlite3_free);
4897  }
4898}
4899
4900/*
4901** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4902*/
4903static void shellUSleepFunc(
4904  sqlite3_context *context,
4905  int argcUnused,
4906  sqlite3_value **argv
4907){
4908  int sleep = sqlite3_value_int(argv[0]);
4909  (void)argcUnused;
4910  sqlite3_sleep(sleep/1000);
4911  sqlite3_result_int(context, sleep);
4912}
4913
4914/*
4915** Scalar function "shell_escape_crnl" used by the .recover command.
4916** The argument passed to this function is the output of built-in
4917** function quote(). If the first character of the input is "'",
4918** indicating that the value passed to quote() was a text value,
4919** then this function searches the input for "\n" and "\r" characters
4920** and adds a wrapper similar to the following:
4921**
4922**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4923**
4924** Or, if the first character of the input is not "'", then a copy
4925** of the input is returned.
4926*/
4927static void shellEscapeCrnl(
4928  sqlite3_context *context,
4929  int argc,
4930  sqlite3_value **argv
4931){
4932  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4933  UNUSED_PARAMETER(argc);
4934  if( zText && zText[0]=='\'' ){
4935    int nText = sqlite3_value_bytes(argv[0]);
4936    int i;
4937    char zBuf1[20];
4938    char zBuf2[20];
4939    const char *zNL = 0;
4940    const char *zCR = 0;
4941    int nCR = 0;
4942    int nNL = 0;
4943
4944    for(i=0; zText[i]; i++){
4945      if( zNL==0 && zText[i]=='\n' ){
4946        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4947        nNL = (int)strlen(zNL);
4948      }
4949      if( zCR==0 && zText[i]=='\r' ){
4950        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4951        nCR = (int)strlen(zCR);
4952      }
4953    }
4954
4955    if( zNL || zCR ){
4956      int iOut = 0;
4957      i64 nMax = (nNL > nCR) ? nNL : nCR;
4958      i64 nAlloc = nMax * nText + (nMax+64)*2;
4959      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4960      if( zOut==0 ){
4961        sqlite3_result_error_nomem(context);
4962        return;
4963      }
4964
4965      if( zNL && zCR ){
4966        memcpy(&zOut[iOut], "replace(replace(", 16);
4967        iOut += 16;
4968      }else{
4969        memcpy(&zOut[iOut], "replace(", 8);
4970        iOut += 8;
4971      }
4972      for(i=0; zText[i]; i++){
4973        if( zText[i]=='\n' ){
4974          memcpy(&zOut[iOut], zNL, nNL);
4975          iOut += nNL;
4976        }else if( zText[i]=='\r' ){
4977          memcpy(&zOut[iOut], zCR, nCR);
4978          iOut += nCR;
4979        }else{
4980          zOut[iOut] = zText[i];
4981          iOut++;
4982        }
4983      }
4984
4985      if( zNL ){
4986        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4987        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4988        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4989      }
4990      if( zCR ){
4991        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4992        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4993        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4994      }
4995
4996      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4997      sqlite3_free(zOut);
4998      return;
4999    }
5000  }
5001
5002  sqlite3_result_value(context, argv[0]);
5003}
5004
5005/* Flags for open_db().
5006**
5007** The default behavior of open_db() is to exit(1) if the database fails to
5008** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5009** but still returns without calling exit.
5010**
5011** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5012** ZIP archive if the file does not exist or is empty and its name matches
5013** the *.zip pattern.
5014*/
5015#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5016#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5017
5018/*
5019** Make sure the database is open.  If it is not, then open it.  If
5020** the database fails to open, print an error message and exit.
5021*/
5022static void open_db(ShellState *p, int openFlags){
5023  if( p->db==0 ){
5024    const char *zDbFilename = p->pAuxDb->zDbFilename;
5025    if( p->openMode==SHELL_OPEN_UNSPEC ){
5026      if( zDbFilename==0 || zDbFilename[0]==0 ){
5027        p->openMode = SHELL_OPEN_NORMAL;
5028      }else{
5029        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5030                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5031      }
5032    }
5033    switch( p->openMode ){
5034      case SHELL_OPEN_APPENDVFS: {
5035        sqlite3_open_v2(zDbFilename, &p->db,
5036           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5037        break;
5038      }
5039      case SHELL_OPEN_HEXDB:
5040      case SHELL_OPEN_DESERIALIZE: {
5041        sqlite3_open(0, &p->db);
5042        break;
5043      }
5044      case SHELL_OPEN_ZIPFILE: {
5045        sqlite3_open(":memory:", &p->db);
5046        break;
5047      }
5048      case SHELL_OPEN_READONLY: {
5049        sqlite3_open_v2(zDbFilename, &p->db,
5050            SQLITE_OPEN_READONLY|p->openFlags, 0);
5051        break;
5052      }
5053      case SHELL_OPEN_UNSPEC:
5054      case SHELL_OPEN_NORMAL: {
5055        sqlite3_open_v2(zDbFilename, &p->db,
5056           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5057        break;
5058      }
5059    }
5060    globalDb = p->db;
5061    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5062      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5063          zDbFilename, sqlite3_errmsg(p->db));
5064      if( openFlags & OPEN_DB_KEEPALIVE ){
5065        sqlite3_open(":memory:", &p->db);
5066        return;
5067      }
5068      exit(1);
5069    }
5070#ifndef SQLITE_OMIT_LOAD_EXTENSION
5071    sqlite3_enable_load_extension(p->db, 1);
5072#endif
5073    sqlite3_shathree_init(p->db, 0, 0);
5074    sqlite3_uint_init(p->db, 0, 0);
5075    sqlite3_decimal_init(p->db, 0, 0);
5076    sqlite3_regexp_init(p->db, 0, 0);
5077    sqlite3_ieee_init(p->db, 0, 0);
5078    sqlite3_series_init(p->db, 0, 0);
5079#ifndef SQLITE_SHELL_FIDDLE
5080    sqlite3_fileio_init(p->db, 0, 0);
5081    sqlite3_completion_init(p->db, 0, 0);
5082#endif
5083#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5084    sqlite3_dbdata_init(p->db, 0, 0);
5085#endif
5086#ifdef SQLITE_HAVE_ZLIB
5087    if( !p->bSafeModePersist ){
5088      sqlite3_zipfile_init(p->db, 0, 0);
5089      sqlite3_sqlar_init(p->db, 0, 0);
5090    }
5091#endif
5092    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5093                            shellAddSchemaName, 0, 0);
5094    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5095                            shellModuleSchema, 0, 0);
5096    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5097                            shellPutsFunc, 0, 0);
5098    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5099                            shellEscapeCrnl, 0, 0);
5100    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5101                            shellInt32, 0, 0);
5102    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5103                            shellIdQuote, 0, 0);
5104    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5105                            shellUSleepFunc, 0, 0);
5106#ifndef SQLITE_NOHAVE_SYSTEM
5107    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5108                            editFunc, 0, 0);
5109    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5110                            editFunc, 0, 0);
5111#endif
5112    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5113      char *zSql = sqlite3_mprintf(
5114         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5115      shell_check_oom(zSql);
5116      sqlite3_exec(p->db, zSql, 0, 0, 0);
5117      sqlite3_free(zSql);
5118    }
5119#ifndef SQLITE_OMIT_DESERIALIZE
5120    else
5121    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5122      int rc;
5123      int nData = 0;
5124      unsigned char *aData;
5125      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5126        aData = (unsigned char*)readFile(zDbFilename, &nData);
5127      }else{
5128        aData = readHexDb(p, &nData);
5129        if( aData==0 ){
5130          return;
5131        }
5132      }
5133      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5134                   SQLITE_DESERIALIZE_RESIZEABLE |
5135                   SQLITE_DESERIALIZE_FREEONCLOSE);
5136      if( rc ){
5137        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5138      }
5139      if( p->szMax>0 ){
5140        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5141      }
5142    }
5143#endif
5144  }
5145  if( p->bSafeModePersist && p->db!=0 ){
5146    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5147  }
5148}
5149
5150/*
5151** Attempt to close the databaes connection.  Report errors.
5152*/
5153void close_db(sqlite3 *db){
5154  int rc = sqlite3_close(db);
5155  if( rc ){
5156    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5157        rc, sqlite3_errmsg(db));
5158  }
5159}
5160
5161#if HAVE_READLINE || HAVE_EDITLINE
5162/*
5163** Readline completion callbacks
5164*/
5165static char *readline_completion_generator(const char *text, int state){
5166  static sqlite3_stmt *pStmt = 0;
5167  char *zRet;
5168  if( state==0 ){
5169    char *zSql;
5170    sqlite3_finalize(pStmt);
5171    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5172                           "  FROM completion(%Q) ORDER BY 1", text);
5173    shell_check_oom(zSql);
5174    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5175    sqlite3_free(zSql);
5176  }
5177  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5178    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5179    zRet = z ? strdup(z) : 0;
5180  }else{
5181    sqlite3_finalize(pStmt);
5182    pStmt = 0;
5183    zRet = 0;
5184  }
5185  return zRet;
5186}
5187static char **readline_completion(const char *zText, int iStart, int iEnd){
5188  rl_attempted_completion_over = 1;
5189  return rl_completion_matches(zText, readline_completion_generator);
5190}
5191
5192#elif HAVE_LINENOISE
5193/*
5194** Linenoise completion callback
5195*/
5196static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5197  int nLine = strlen30(zLine);
5198  int i, iStart;
5199  sqlite3_stmt *pStmt = 0;
5200  char *zSql;
5201  char zBuf[1000];
5202
5203  if( nLine>sizeof(zBuf)-30 ) return;
5204  if( zLine[0]=='.' || zLine[0]=='#') return;
5205  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5206  if( i==nLine-1 ) return;
5207  iStart = i+1;
5208  memcpy(zBuf, zLine, iStart);
5209  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5210                         "  FROM completion(%Q,%Q) ORDER BY 1",
5211                         &zLine[iStart], zLine);
5212  shell_check_oom(zSql);
5213  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5214  sqlite3_free(zSql);
5215  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5216  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5217    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5218    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5219    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5220      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5221      linenoiseAddCompletion(lc, zBuf);
5222    }
5223  }
5224  sqlite3_finalize(pStmt);
5225}
5226#endif
5227
5228/*
5229** Do C-language style dequoting.
5230**
5231**    \a    -> alarm
5232**    \b    -> backspace
5233**    \t    -> tab
5234**    \n    -> newline
5235**    \v    -> vertical tab
5236**    \f    -> form feed
5237**    \r    -> carriage return
5238**    \s    -> space
5239**    \"    -> "
5240**    \'    -> '
5241**    \\    -> backslash
5242**    \NNN  -> ascii character NNN in octal
5243*/
5244static void resolve_backslashes(char *z){
5245  int i, j;
5246  char c;
5247  while( *z && *z!='\\' ) z++;
5248  for(i=j=0; (c = z[i])!=0; i++, j++){
5249    if( c=='\\' && z[i+1]!=0 ){
5250      c = z[++i];
5251      if( c=='a' ){
5252        c = '\a';
5253      }else if( c=='b' ){
5254        c = '\b';
5255      }else if( c=='t' ){
5256        c = '\t';
5257      }else if( c=='n' ){
5258        c = '\n';
5259      }else if( c=='v' ){
5260        c = '\v';
5261      }else if( c=='f' ){
5262        c = '\f';
5263      }else if( c=='r' ){
5264        c = '\r';
5265      }else if( c=='"' ){
5266        c = '"';
5267      }else if( c=='\'' ){
5268        c = '\'';
5269      }else if( c=='\\' ){
5270        c = '\\';
5271      }else if( c>='0' && c<='7' ){
5272        c -= '0';
5273        if( z[i+1]>='0' && z[i+1]<='7' ){
5274          i++;
5275          c = (c<<3) + z[i] - '0';
5276          if( z[i+1]>='0' && z[i+1]<='7' ){
5277            i++;
5278            c = (c<<3) + z[i] - '0';
5279          }
5280        }
5281      }
5282    }
5283    z[j] = c;
5284  }
5285  if( j<i ) z[j] = 0;
5286}
5287
5288/*
5289** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5290** for TRUE and FALSE.  Return the integer value if appropriate.
5291*/
5292static int booleanValue(const char *zArg){
5293  int i;
5294  if( zArg[0]=='0' && zArg[1]=='x' ){
5295    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5296  }else{
5297    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5298  }
5299  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5300  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5301    return 1;
5302  }
5303  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5304    return 0;
5305  }
5306  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5307          zArg);
5308  return 0;
5309}
5310
5311/*
5312** Set or clear a shell flag according to a boolean value.
5313*/
5314static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5315  if( booleanValue(zArg) ){
5316    ShellSetFlag(p, mFlag);
5317  }else{
5318    ShellClearFlag(p, mFlag);
5319  }
5320}
5321
5322/*
5323** Close an output file, assuming it is not stderr or stdout
5324*/
5325static void output_file_close(FILE *f){
5326  if( f && f!=stdout && f!=stderr ) fclose(f);
5327}
5328
5329/*
5330** Try to open an output file.   The names "stdout" and "stderr" are
5331** recognized and do the right thing.  NULL is returned if the output
5332** filename is "off".
5333*/
5334static FILE *output_file_open(const char *zFile, int bTextMode){
5335  FILE *f;
5336  if( strcmp(zFile,"stdout")==0 ){
5337    f = stdout;
5338  }else if( strcmp(zFile, "stderr")==0 ){
5339    f = stderr;
5340  }else if( strcmp(zFile, "off")==0 ){
5341    f = 0;
5342  }else{
5343    f = fopen(zFile, bTextMode ? "w" : "wb");
5344    if( f==0 ){
5345      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5346    }
5347  }
5348  return f;
5349}
5350
5351#ifndef SQLITE_OMIT_TRACE
5352/*
5353** A routine for handling output from sqlite3_trace().
5354*/
5355static int sql_trace_callback(
5356  unsigned mType,         /* The trace type */
5357  void *pArg,             /* The ShellState pointer */
5358  void *pP,               /* Usually a pointer to sqlite_stmt */
5359  void *pX                /* Auxiliary output */
5360){
5361  ShellState *p = (ShellState*)pArg;
5362  sqlite3_stmt *pStmt;
5363  const char *zSql;
5364  int nSql;
5365  if( p->traceOut==0 ) return 0;
5366  if( mType==SQLITE_TRACE_CLOSE ){
5367    utf8_printf(p->traceOut, "-- closing database connection\n");
5368    return 0;
5369  }
5370  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5371    zSql = (const char*)pX;
5372  }else{
5373    pStmt = (sqlite3_stmt*)pP;
5374    switch( p->eTraceType ){
5375      case SHELL_TRACE_EXPANDED: {
5376        zSql = sqlite3_expanded_sql(pStmt);
5377        break;
5378      }
5379#ifdef SQLITE_ENABLE_NORMALIZE
5380      case SHELL_TRACE_NORMALIZED: {
5381        zSql = sqlite3_normalized_sql(pStmt);
5382        break;
5383      }
5384#endif
5385      default: {
5386        zSql = sqlite3_sql(pStmt);
5387        break;
5388      }
5389    }
5390  }
5391  if( zSql==0 ) return 0;
5392  nSql = strlen30(zSql);
5393  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5394  switch( mType ){
5395    case SQLITE_TRACE_ROW:
5396    case SQLITE_TRACE_STMT: {
5397      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5398      break;
5399    }
5400    case SQLITE_TRACE_PROFILE: {
5401      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5402      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5403      break;
5404    }
5405  }
5406  return 0;
5407}
5408#endif
5409
5410/*
5411** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5412** a useful spot to set a debugger breakpoint.
5413*/
5414static void test_breakpoint(void){
5415  static int nCall = 0;
5416  nCall++;
5417}
5418
5419/*
5420** An object used to read a CSV and other files for import.
5421*/
5422typedef struct ImportCtx ImportCtx;
5423struct ImportCtx {
5424  const char *zFile;  /* Name of the input file */
5425  FILE *in;           /* Read the CSV text from this input stream */
5426  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5427  char *z;            /* Accumulated text for a field */
5428  int n;              /* Number of bytes in z */
5429  int nAlloc;         /* Space allocated for z[] */
5430  int nLine;          /* Current line number */
5431  int nRow;           /* Number of rows imported */
5432  int nErr;           /* Number of errors encountered */
5433  int bNotFirst;      /* True if one or more bytes already read */
5434  int cTerm;          /* Character that terminated the most recent field */
5435  int cColSep;        /* The column separator character.  (Usually ",") */
5436  int cRowSep;        /* The row separator character.  (Usually "\n") */
5437};
5438
5439/* Clean up resourced used by an ImportCtx */
5440static void import_cleanup(ImportCtx *p){
5441  if( p->in!=0 && p->xCloser!=0 ){
5442    p->xCloser(p->in);
5443    p->in = 0;
5444  }
5445  sqlite3_free(p->z);
5446  p->z = 0;
5447}
5448
5449/* Append a single byte to z[] */
5450static void import_append_char(ImportCtx *p, int c){
5451  if( p->n+1>=p->nAlloc ){
5452    p->nAlloc += p->nAlloc + 100;
5453    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5454    shell_check_oom(p->z);
5455  }
5456  p->z[p->n++] = (char)c;
5457}
5458
5459/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5460** with the option of having a separator other than ",".
5461**
5462**   +  Input comes from p->in.
5463**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5464**      from sqlite3_malloc64().
5465**   +  Use p->cSep as the column separator.  The default is ",".
5466**   +  Use p->rSep as the row separator.  The default is "\n".
5467**   +  Keep track of the line number in p->nLine.
5468**   +  Store the character that terminates the field in p->cTerm.  Store
5469**      EOF on end-of-file.
5470**   +  Report syntax errors on stderr
5471*/
5472static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5473  int c;
5474  int cSep = p->cColSep;
5475  int rSep = p->cRowSep;
5476  p->n = 0;
5477  c = fgetc(p->in);
5478  if( c==EOF || seenInterrupt ){
5479    p->cTerm = EOF;
5480    return 0;
5481  }
5482  if( c=='"' ){
5483    int pc, ppc;
5484    int startLine = p->nLine;
5485    int cQuote = c;
5486    pc = ppc = 0;
5487    while( 1 ){
5488      c = fgetc(p->in);
5489      if( c==rSep ) p->nLine++;
5490      if( c==cQuote ){
5491        if( pc==cQuote ){
5492          pc = 0;
5493          continue;
5494        }
5495      }
5496      if( (c==cSep && pc==cQuote)
5497       || (c==rSep && pc==cQuote)
5498       || (c==rSep && pc=='\r' && ppc==cQuote)
5499       || (c==EOF && pc==cQuote)
5500      ){
5501        do{ p->n--; }while( p->z[p->n]!=cQuote );
5502        p->cTerm = c;
5503        break;
5504      }
5505      if( pc==cQuote && c!='\r' ){
5506        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5507                p->zFile, p->nLine, cQuote);
5508      }
5509      if( c==EOF ){
5510        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5511                p->zFile, startLine, cQuote);
5512        p->cTerm = c;
5513        break;
5514      }
5515      import_append_char(p, c);
5516      ppc = pc;
5517      pc = c;
5518    }
5519  }else{
5520    /* If this is the first field being parsed and it begins with the
5521    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5522    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5523      import_append_char(p, c);
5524      c = fgetc(p->in);
5525      if( (c&0xff)==0xbb ){
5526        import_append_char(p, c);
5527        c = fgetc(p->in);
5528        if( (c&0xff)==0xbf ){
5529          p->bNotFirst = 1;
5530          p->n = 0;
5531          return csv_read_one_field(p);
5532        }
5533      }
5534    }
5535    while( c!=EOF && c!=cSep && c!=rSep ){
5536      import_append_char(p, c);
5537      c = fgetc(p->in);
5538    }
5539    if( c==rSep ){
5540      p->nLine++;
5541      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5542    }
5543    p->cTerm = c;
5544  }
5545  if( p->z ) p->z[p->n] = 0;
5546  p->bNotFirst = 1;
5547  return p->z;
5548}
5549
5550/* Read a single field of ASCII delimited text.
5551**
5552**   +  Input comes from p->in.
5553**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5554**      from sqlite3_malloc64().
5555**   +  Use p->cSep as the column separator.  The default is "\x1F".
5556**   +  Use p->rSep as the row separator.  The default is "\x1E".
5557**   +  Keep track of the row number in p->nLine.
5558**   +  Store the character that terminates the field in p->cTerm.  Store
5559**      EOF on end-of-file.
5560**   +  Report syntax errors on stderr
5561*/
5562static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5563  int c;
5564  int cSep = p->cColSep;
5565  int rSep = p->cRowSep;
5566  p->n = 0;
5567  c = fgetc(p->in);
5568  if( c==EOF || seenInterrupt ){
5569    p->cTerm = EOF;
5570    return 0;
5571  }
5572  while( c!=EOF && c!=cSep && c!=rSep ){
5573    import_append_char(p, c);
5574    c = fgetc(p->in);
5575  }
5576  if( c==rSep ){
5577    p->nLine++;
5578  }
5579  p->cTerm = c;
5580  if( p->z ) p->z[p->n] = 0;
5581  return p->z;
5582}
5583
5584/*
5585** Try to transfer data for table zTable.  If an error is seen while
5586** moving forward, try to go backwards.  The backwards movement won't
5587** work for WITHOUT ROWID tables.
5588*/
5589static void tryToCloneData(
5590  ShellState *p,
5591  sqlite3 *newDb,
5592  const char *zTable
5593){
5594  sqlite3_stmt *pQuery = 0;
5595  sqlite3_stmt *pInsert = 0;
5596  char *zQuery = 0;
5597  char *zInsert = 0;
5598  int rc;
5599  int i, j, n;
5600  int nTable = strlen30(zTable);
5601  int k = 0;
5602  int cnt = 0;
5603  const int spinRate = 10000;
5604
5605  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5606  shell_check_oom(zQuery);
5607  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5608  if( rc ){
5609    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5610            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5611            zQuery);
5612    goto end_data_xfer;
5613  }
5614  n = sqlite3_column_count(pQuery);
5615  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5616  shell_check_oom(zInsert);
5617  sqlite3_snprintf(200+nTable,zInsert,
5618                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5619  i = strlen30(zInsert);
5620  for(j=1; j<n; j++){
5621    memcpy(zInsert+i, ",?", 2);
5622    i += 2;
5623  }
5624  memcpy(zInsert+i, ");", 3);
5625  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5626  if( rc ){
5627    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5628            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5629            zQuery);
5630    goto end_data_xfer;
5631  }
5632  for(k=0; k<2; k++){
5633    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5634      for(i=0; i<n; i++){
5635        switch( sqlite3_column_type(pQuery, i) ){
5636          case SQLITE_NULL: {
5637            sqlite3_bind_null(pInsert, i+1);
5638            break;
5639          }
5640          case SQLITE_INTEGER: {
5641            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5642            break;
5643          }
5644          case SQLITE_FLOAT: {
5645            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5646            break;
5647          }
5648          case SQLITE_TEXT: {
5649            sqlite3_bind_text(pInsert, i+1,
5650                             (const char*)sqlite3_column_text(pQuery,i),
5651                             -1, SQLITE_STATIC);
5652            break;
5653          }
5654          case SQLITE_BLOB: {
5655            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5656                                            sqlite3_column_bytes(pQuery,i),
5657                                            SQLITE_STATIC);
5658            break;
5659          }
5660        }
5661      } /* End for */
5662      rc = sqlite3_step(pInsert);
5663      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5664        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5665                        sqlite3_errmsg(newDb));
5666      }
5667      sqlite3_reset(pInsert);
5668      cnt++;
5669      if( (cnt%spinRate)==0 ){
5670        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5671        fflush(stdout);
5672      }
5673    } /* End while */
5674    if( rc==SQLITE_DONE ) break;
5675    sqlite3_finalize(pQuery);
5676    sqlite3_free(zQuery);
5677    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5678                             zTable);
5679    shell_check_oom(zQuery);
5680    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5681    if( rc ){
5682      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5683      break;
5684    }
5685  } /* End for(k=0...) */
5686
5687end_data_xfer:
5688  sqlite3_finalize(pQuery);
5689  sqlite3_finalize(pInsert);
5690  sqlite3_free(zQuery);
5691  sqlite3_free(zInsert);
5692}
5693
5694
5695/*
5696** Try to transfer all rows of the schema that match zWhere.  For
5697** each row, invoke xForEach() on the object defined by that row.
5698** If an error is encountered while moving forward through the
5699** sqlite_schema table, try again moving backwards.
5700*/
5701static void tryToCloneSchema(
5702  ShellState *p,
5703  sqlite3 *newDb,
5704  const char *zWhere,
5705  void (*xForEach)(ShellState*,sqlite3*,const char*)
5706){
5707  sqlite3_stmt *pQuery = 0;
5708  char *zQuery = 0;
5709  int rc;
5710  const unsigned char *zName;
5711  const unsigned char *zSql;
5712  char *zErrMsg = 0;
5713
5714  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5715                           " WHERE %s", zWhere);
5716  shell_check_oom(zQuery);
5717  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5718  if( rc ){
5719    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5720                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5721                    zQuery);
5722    goto end_schema_xfer;
5723  }
5724  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5725    zName = sqlite3_column_text(pQuery, 0);
5726    zSql = sqlite3_column_text(pQuery, 1);
5727    if( zName==0 || zSql==0 ) continue;
5728    printf("%s... ", zName); fflush(stdout);
5729    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5730    if( zErrMsg ){
5731      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5732      sqlite3_free(zErrMsg);
5733      zErrMsg = 0;
5734    }
5735    if( xForEach ){
5736      xForEach(p, newDb, (const char*)zName);
5737    }
5738    printf("done\n");
5739  }
5740  if( rc!=SQLITE_DONE ){
5741    sqlite3_finalize(pQuery);
5742    sqlite3_free(zQuery);
5743    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5744                             " WHERE %s ORDER BY rowid DESC", zWhere);
5745    shell_check_oom(zQuery);
5746    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5747    if( rc ){
5748      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5749                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5750                      zQuery);
5751      goto end_schema_xfer;
5752    }
5753    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5754      zName = sqlite3_column_text(pQuery, 0);
5755      zSql = sqlite3_column_text(pQuery, 1);
5756      if( zName==0 || zSql==0 ) continue;
5757      printf("%s... ", zName); fflush(stdout);
5758      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5759      if( zErrMsg ){
5760        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5761        sqlite3_free(zErrMsg);
5762        zErrMsg = 0;
5763      }
5764      if( xForEach ){
5765        xForEach(p, newDb, (const char*)zName);
5766      }
5767      printf("done\n");
5768    }
5769  }
5770end_schema_xfer:
5771  sqlite3_finalize(pQuery);
5772  sqlite3_free(zQuery);
5773}
5774
5775/*
5776** Open a new database file named "zNewDb".  Try to recover as much information
5777** as possible out of the main database (which might be corrupt) and write it
5778** into zNewDb.
5779*/
5780static void tryToClone(ShellState *p, const char *zNewDb){
5781  int rc;
5782  sqlite3 *newDb = 0;
5783  if( access(zNewDb,0)==0 ){
5784    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5785    return;
5786  }
5787  rc = sqlite3_open(zNewDb, &newDb);
5788  if( rc ){
5789    utf8_printf(stderr, "Cannot create output database: %s\n",
5790            sqlite3_errmsg(newDb));
5791  }else{
5792    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5793    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5794    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5795    tryToCloneSchema(p, newDb, "type!='table'", 0);
5796    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5797    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5798  }
5799  close_db(newDb);
5800}
5801
5802/*
5803** Change the output file back to stdout.
5804**
5805** If the p->doXdgOpen flag is set, that means the output was being
5806** redirected to a temporary file named by p->zTempFile.  In that case,
5807** launch start/open/xdg-open on that temporary file.
5808*/
5809static void output_reset(ShellState *p){
5810  if( p->outfile[0]=='|' ){
5811#ifndef SQLITE_OMIT_POPEN
5812    pclose(p->out);
5813#endif
5814  }else{
5815    output_file_close(p->out);
5816#ifndef SQLITE_NOHAVE_SYSTEM
5817    if( p->doXdgOpen ){
5818      const char *zXdgOpenCmd =
5819#if defined(_WIN32)
5820      "start";
5821#elif defined(__APPLE__)
5822      "open";
5823#else
5824      "xdg-open";
5825#endif
5826      char *zCmd;
5827      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5828      if( system(zCmd) ){
5829        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5830      }else{
5831        /* Give the start/open/xdg-open command some time to get
5832        ** going before we continue, and potential delete the
5833        ** p->zTempFile data file out from under it */
5834        sqlite3_sleep(2000);
5835      }
5836      sqlite3_free(zCmd);
5837      outputModePop(p);
5838      p->doXdgOpen = 0;
5839    }
5840#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5841  }
5842  p->outfile[0] = 0;
5843  p->out = stdout;
5844}
5845
5846/*
5847** Run an SQL command and return the single integer result.
5848*/
5849static int db_int(sqlite3 *db, const char *zSql){
5850  sqlite3_stmt *pStmt;
5851  int res = 0;
5852  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5853  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5854    res = sqlite3_column_int(pStmt,0);
5855  }
5856  sqlite3_finalize(pStmt);
5857  return res;
5858}
5859
5860#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5861/*
5862** Convert a 2-byte or 4-byte big-endian integer into a native integer
5863*/
5864static unsigned int get2byteInt(unsigned char *a){
5865  return (a[0]<<8) + a[1];
5866}
5867static unsigned int get4byteInt(unsigned char *a){
5868  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5869}
5870
5871/*
5872** Implementation of the ".dbinfo" command.
5873**
5874** Return 1 on error, 2 to exit, and 0 otherwise.
5875*/
5876static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5877  static const struct { const char *zName; int ofst; } aField[] = {
5878     { "file change counter:",  24  },
5879     { "database page count:",  28  },
5880     { "freelist page count:",  36  },
5881     { "schema cookie:",        40  },
5882     { "schema format:",        44  },
5883     { "default cache size:",   48  },
5884     { "autovacuum top root:",  52  },
5885     { "incremental vacuum:",   64  },
5886     { "text encoding:",        56  },
5887     { "user version:",         60  },
5888     { "application id:",       68  },
5889     { "software version:",     96  },
5890  };
5891  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5892     { "number of tables:",
5893       "SELECT count(*) FROM %s WHERE type='table'" },
5894     { "number of indexes:",
5895       "SELECT count(*) FROM %s WHERE type='index'" },
5896     { "number of triggers:",
5897       "SELECT count(*) FROM %s WHERE type='trigger'" },
5898     { "number of views:",
5899       "SELECT count(*) FROM %s WHERE type='view'" },
5900     { "schema size:",
5901       "SELECT total(length(sql)) FROM %s" },
5902  };
5903  int i, rc;
5904  unsigned iDataVersion;
5905  char *zSchemaTab;
5906  char *zDb = nArg>=2 ? azArg[1] : "main";
5907  sqlite3_stmt *pStmt = 0;
5908  unsigned char aHdr[100];
5909  open_db(p, 0);
5910  if( p->db==0 ) return 1;
5911  rc = sqlite3_prepare_v2(p->db,
5912             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5913             -1, &pStmt, 0);
5914  if( rc ){
5915    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5916    sqlite3_finalize(pStmt);
5917    return 1;
5918  }
5919  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5920  if( sqlite3_step(pStmt)==SQLITE_ROW
5921   && sqlite3_column_bytes(pStmt,0)>100
5922  ){
5923    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5924    sqlite3_finalize(pStmt);
5925  }else{
5926    raw_printf(stderr, "unable to read database header\n");
5927    sqlite3_finalize(pStmt);
5928    return 1;
5929  }
5930  i = get2byteInt(aHdr+16);
5931  if( i==1 ) i = 65536;
5932  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5933  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5934  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5935  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5936  for(i=0; i<ArraySize(aField); i++){
5937    int ofst = aField[i].ofst;
5938    unsigned int val = get4byteInt(aHdr + ofst);
5939    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5940    switch( ofst ){
5941      case 56: {
5942        if( val==1 ) raw_printf(p->out, " (utf8)");
5943        if( val==2 ) raw_printf(p->out, " (utf16le)");
5944        if( val==3 ) raw_printf(p->out, " (utf16be)");
5945      }
5946    }
5947    raw_printf(p->out, "\n");
5948  }
5949  if( zDb==0 ){
5950    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5951  }else if( strcmp(zDb,"temp")==0 ){
5952    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5953  }else{
5954    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5955  }
5956  for(i=0; i<ArraySize(aQuery); i++){
5957    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5958    int val = db_int(p->db, zSql);
5959    sqlite3_free(zSql);
5960    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5961  }
5962  sqlite3_free(zSchemaTab);
5963  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5964  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5965  return 0;
5966}
5967#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5968          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5969
5970/*
5971** Print the current sqlite3_errmsg() value to stderr and return 1.
5972*/
5973static int shellDatabaseError(sqlite3 *db){
5974  const char *zErr = sqlite3_errmsg(db);
5975  utf8_printf(stderr, "Error: %s\n", zErr);
5976  return 1;
5977}
5978
5979/*
5980** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5981** if they match and FALSE (0) if they do not match.
5982**
5983** Globbing rules:
5984**
5985**      '*'       Matches any sequence of zero or more characters.
5986**
5987**      '?'       Matches exactly one character.
5988**
5989**     [...]      Matches one character from the enclosed list of
5990**                characters.
5991**
5992**     [^...]     Matches one character not in the enclosed list.
5993**
5994**      '#'       Matches any sequence of one or more digits with an
5995**                optional + or - sign in front
5996**
5997**      ' '       Any span of whitespace matches any other span of
5998**                whitespace.
5999**
6000** Extra whitespace at the end of z[] is ignored.
6001*/
6002static int testcase_glob(const char *zGlob, const char *z){
6003  int c, c2;
6004  int invert;
6005  int seen;
6006
6007  while( (c = (*(zGlob++)))!=0 ){
6008    if( IsSpace(c) ){
6009      if( !IsSpace(*z) ) return 0;
6010      while( IsSpace(*zGlob) ) zGlob++;
6011      while( IsSpace(*z) ) z++;
6012    }else if( c=='*' ){
6013      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6014        if( c=='?' && (*(z++))==0 ) return 0;
6015      }
6016      if( c==0 ){
6017        return 1;
6018      }else if( c=='[' ){
6019        while( *z && testcase_glob(zGlob-1,z)==0 ){
6020          z++;
6021        }
6022        return (*z)!=0;
6023      }
6024      while( (c2 = (*(z++)))!=0 ){
6025        while( c2!=c ){
6026          c2 = *(z++);
6027          if( c2==0 ) return 0;
6028        }
6029        if( testcase_glob(zGlob,z) ) return 1;
6030      }
6031      return 0;
6032    }else if( c=='?' ){
6033      if( (*(z++))==0 ) return 0;
6034    }else if( c=='[' ){
6035      int prior_c = 0;
6036      seen = 0;
6037      invert = 0;
6038      c = *(z++);
6039      if( c==0 ) return 0;
6040      c2 = *(zGlob++);
6041      if( c2=='^' ){
6042        invert = 1;
6043        c2 = *(zGlob++);
6044      }
6045      if( c2==']' ){
6046        if( c==']' ) seen = 1;
6047        c2 = *(zGlob++);
6048      }
6049      while( c2 && c2!=']' ){
6050        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6051          c2 = *(zGlob++);
6052          if( c>=prior_c && c<=c2 ) seen = 1;
6053          prior_c = 0;
6054        }else{
6055          if( c==c2 ){
6056            seen = 1;
6057          }
6058          prior_c = c2;
6059        }
6060        c2 = *(zGlob++);
6061      }
6062      if( c2==0 || (seen ^ invert)==0 ) return 0;
6063    }else if( c=='#' ){
6064      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6065      if( !IsDigit(z[0]) ) return 0;
6066      z++;
6067      while( IsDigit(z[0]) ){ z++; }
6068    }else{
6069      if( c!=(*(z++)) ) return 0;
6070    }
6071  }
6072  while( IsSpace(*z) ){ z++; }
6073  return *z==0;
6074}
6075
6076
6077/*
6078** Compare the string as a command-line option with either one or two
6079** initial "-" characters.
6080*/
6081static int optionMatch(const char *zStr, const char *zOpt){
6082  if( zStr[0]!='-' ) return 0;
6083  zStr++;
6084  if( zStr[0]=='-' ) zStr++;
6085  return strcmp(zStr, zOpt)==0;
6086}
6087
6088/*
6089** Delete a file.
6090*/
6091int shellDeleteFile(const char *zFilename){
6092  int rc;
6093#ifdef _WIN32
6094  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6095  rc = _wunlink(z);
6096  sqlite3_free(z);
6097#else
6098  rc = unlink(zFilename);
6099#endif
6100  return rc;
6101}
6102
6103/*
6104** Try to delete the temporary file (if there is one) and free the
6105** memory used to hold the name of the temp file.
6106*/
6107static void clearTempFile(ShellState *p){
6108  if( p->zTempFile==0 ) return;
6109  if( p->doXdgOpen ) return;
6110  if( shellDeleteFile(p->zTempFile) ) return;
6111  sqlite3_free(p->zTempFile);
6112  p->zTempFile = 0;
6113}
6114
6115/*
6116** Create a new temp file name with the given suffix.
6117*/
6118static void newTempFile(ShellState *p, const char *zSuffix){
6119  clearTempFile(p);
6120  sqlite3_free(p->zTempFile);
6121  p->zTempFile = 0;
6122  if( p->db ){
6123    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6124  }
6125  if( p->zTempFile==0 ){
6126    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6127    ** will not work and we will need to fallback to guessing */
6128    char *zTemp;
6129    sqlite3_uint64 r;
6130    sqlite3_randomness(sizeof(r), &r);
6131    zTemp = getenv("TEMP");
6132    if( zTemp==0 ) zTemp = getenv("TMP");
6133    if( zTemp==0 ){
6134#ifdef _WIN32
6135      zTemp = "\\tmp";
6136#else
6137      zTemp = "/tmp";
6138#endif
6139    }
6140    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6141  }else{
6142    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6143  }
6144  shell_check_oom(p->zTempFile);
6145}
6146
6147
6148/*
6149** The implementation of SQL scalar function fkey_collate_clause(), used
6150** by the ".lint fkey-indexes" command. This scalar function is always
6151** called with four arguments - the parent table name, the parent column name,
6152** the child table name and the child column name.
6153**
6154**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6155**
6156** If either of the named tables or columns do not exist, this function
6157** returns an empty string. An empty string is also returned if both tables
6158** and columns exist but have the same default collation sequence. Or,
6159** if both exist but the default collation sequences are different, this
6160** function returns the string " COLLATE <parent-collation>", where
6161** <parent-collation> is the default collation sequence of the parent column.
6162*/
6163static void shellFkeyCollateClause(
6164  sqlite3_context *pCtx,
6165  int nVal,
6166  sqlite3_value **apVal
6167){
6168  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6169  const char *zParent;
6170  const char *zParentCol;
6171  const char *zParentSeq;
6172  const char *zChild;
6173  const char *zChildCol;
6174  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6175  int rc;
6176
6177  assert( nVal==4 );
6178  zParent = (const char*)sqlite3_value_text(apVal[0]);
6179  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6180  zChild = (const char*)sqlite3_value_text(apVal[2]);
6181  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6182
6183  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6184  rc = sqlite3_table_column_metadata(
6185      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6186  );
6187  if( rc==SQLITE_OK ){
6188    rc = sqlite3_table_column_metadata(
6189        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6190    );
6191  }
6192
6193  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6194    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6195    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6196    sqlite3_free(z);
6197  }
6198}
6199
6200
6201/*
6202** The implementation of dot-command ".lint fkey-indexes".
6203*/
6204static int lintFkeyIndexes(
6205  ShellState *pState,             /* Current shell tool state */
6206  char **azArg,                   /* Array of arguments passed to dot command */
6207  int nArg                        /* Number of entries in azArg[] */
6208){
6209  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6210  FILE *out = pState->out;        /* Stream to write non-error output to */
6211  int bVerbose = 0;               /* If -verbose is present */
6212  int bGroupByParent = 0;         /* If -groupbyparent is present */
6213  int i;                          /* To iterate through azArg[] */
6214  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6215  int rc;                         /* Return code */
6216  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6217
6218  /*
6219  ** This SELECT statement returns one row for each foreign key constraint
6220  ** in the schema of the main database. The column values are:
6221  **
6222  ** 0. The text of an SQL statement similar to:
6223  **
6224  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6225  **
6226  **    This SELECT is similar to the one that the foreign keys implementation
6227  **    needs to run internally on child tables. If there is an index that can
6228  **    be used to optimize this query, then it can also be used by the FK
6229  **    implementation to optimize DELETE or UPDATE statements on the parent
6230  **    table.
6231  **
6232  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6233  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6234  **    contains an index that can be used to optimize the query.
6235  **
6236  ** 2. Human readable text that describes the child table and columns. e.g.
6237  **
6238  **       "child_table(child_key1, child_key2)"
6239  **
6240  ** 3. Human readable text that describes the parent table and columns. e.g.
6241  **
6242  **       "parent_table(parent_key1, parent_key2)"
6243  **
6244  ** 4. A full CREATE INDEX statement for an index that could be used to
6245  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6246  **
6247  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6248  **
6249  ** 5. The name of the parent table.
6250  **
6251  ** These six values are used by the C logic below to generate the report.
6252  */
6253  const char *zSql =
6254  "SELECT "
6255    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6256    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6257    "  || fkey_collate_clause("
6258    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6259    ", "
6260    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6261    "  || group_concat('*=?', ' AND ') || ')'"
6262    ", "
6263    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6264    ", "
6265    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6266    ", "
6267    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6268    "  || ' ON ' || quote(s.name) || '('"
6269    "  || group_concat(quote(f.[from]) ||"
6270    "        fkey_collate_clause("
6271    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6272    "  || ');'"
6273    ", "
6274    "     f.[table] "
6275    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6276    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6277    "GROUP BY s.name, f.id "
6278    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6279  ;
6280  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6281
6282  for(i=2; i<nArg; i++){
6283    int n = strlen30(azArg[i]);
6284    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6285      bVerbose = 1;
6286    }
6287    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6288      bGroupByParent = 1;
6289      zIndent = "    ";
6290    }
6291    else{
6292      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6293          azArg[0], azArg[1]
6294      );
6295      return SQLITE_ERROR;
6296    }
6297  }
6298
6299  /* Register the fkey_collate_clause() SQL function */
6300  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6301      0, shellFkeyCollateClause, 0, 0
6302  );
6303
6304
6305  if( rc==SQLITE_OK ){
6306    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6307  }
6308  if( rc==SQLITE_OK ){
6309    sqlite3_bind_int(pSql, 1, bGroupByParent);
6310  }
6311
6312  if( rc==SQLITE_OK ){
6313    int rc2;
6314    char *zPrev = 0;
6315    while( SQLITE_ROW==sqlite3_step(pSql) ){
6316      int res = -1;
6317      sqlite3_stmt *pExplain = 0;
6318      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6319      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6320      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6321      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6322      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6323      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6324
6325      if( zEQP==0 ) continue;
6326      if( zGlob==0 ) continue;
6327      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6328      if( rc!=SQLITE_OK ) break;
6329      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6330        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6331        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6332                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6333      }
6334      rc = sqlite3_finalize(pExplain);
6335      if( rc!=SQLITE_OK ) break;
6336
6337      if( res<0 ){
6338        raw_printf(stderr, "Error: internal error");
6339        break;
6340      }else{
6341        if( bGroupByParent
6342        && (bVerbose || res==0)
6343        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6344        ){
6345          raw_printf(out, "-- Parent table %s\n", zParent);
6346          sqlite3_free(zPrev);
6347          zPrev = sqlite3_mprintf("%s", zParent);
6348        }
6349
6350        if( res==0 ){
6351          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6352        }else if( bVerbose ){
6353          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6354              zIndent, zFrom, zTarget
6355          );
6356        }
6357      }
6358    }
6359    sqlite3_free(zPrev);
6360
6361    if( rc!=SQLITE_OK ){
6362      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6363    }
6364
6365    rc2 = sqlite3_finalize(pSql);
6366    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6367      rc = rc2;
6368      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6369    }
6370  }else{
6371    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6372  }
6373
6374  return rc;
6375}
6376
6377/*
6378** Implementation of ".lint" dot command.
6379*/
6380static int lintDotCommand(
6381  ShellState *pState,             /* Current shell tool state */
6382  char **azArg,                   /* Array of arguments passed to dot command */
6383  int nArg                        /* Number of entries in azArg[] */
6384){
6385  int n;
6386  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6387  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6388  return lintFkeyIndexes(pState, azArg, nArg);
6389
6390 usage:
6391  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6392  raw_printf(stderr, "Where sub-commands are:\n");
6393  raw_printf(stderr, "    fkey-indexes\n");
6394  return SQLITE_ERROR;
6395}
6396
6397#if !defined SQLITE_OMIT_VIRTUALTABLE
6398static void shellPrepare(
6399  sqlite3 *db,
6400  int *pRc,
6401  const char *zSql,
6402  sqlite3_stmt **ppStmt
6403){
6404  *ppStmt = 0;
6405  if( *pRc==SQLITE_OK ){
6406    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6407    if( rc!=SQLITE_OK ){
6408      raw_printf(stderr, "sql error: %s (%d)\n",
6409          sqlite3_errmsg(db), sqlite3_errcode(db)
6410      );
6411      *pRc = rc;
6412    }
6413  }
6414}
6415
6416/*
6417** Create a prepared statement using printf-style arguments for the SQL.
6418**
6419** This routine is could be marked "static".  But it is not always used,
6420** depending on compile-time options.  By omitting the "static", we avoid
6421** nuisance compiler warnings about "defined but not used".
6422*/
6423void shellPreparePrintf(
6424  sqlite3 *db,
6425  int *pRc,
6426  sqlite3_stmt **ppStmt,
6427  const char *zFmt,
6428  ...
6429){
6430  *ppStmt = 0;
6431  if( *pRc==SQLITE_OK ){
6432    va_list ap;
6433    char *z;
6434    va_start(ap, zFmt);
6435    z = sqlite3_vmprintf(zFmt, ap);
6436    va_end(ap);
6437    if( z==0 ){
6438      *pRc = SQLITE_NOMEM;
6439    }else{
6440      shellPrepare(db, pRc, z, ppStmt);
6441      sqlite3_free(z);
6442    }
6443  }
6444}
6445
6446/* Finalize the prepared statement created using shellPreparePrintf().
6447**
6448** This routine is could be marked "static".  But it is not always used,
6449** depending on compile-time options.  By omitting the "static", we avoid
6450** nuisance compiler warnings about "defined but not used".
6451*/
6452void shellFinalize(
6453  int *pRc,
6454  sqlite3_stmt *pStmt
6455){
6456  if( pStmt ){
6457    sqlite3 *db = sqlite3_db_handle(pStmt);
6458    int rc = sqlite3_finalize(pStmt);
6459    if( *pRc==SQLITE_OK ){
6460      if( rc!=SQLITE_OK ){
6461        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6462      }
6463      *pRc = rc;
6464    }
6465  }
6466}
6467
6468/* Reset the prepared statement created using shellPreparePrintf().
6469**
6470** This routine is could be marked "static".  But it is not always used,
6471** depending on compile-time options.  By omitting the "static", we avoid
6472** nuisance compiler warnings about "defined but not used".
6473*/
6474void shellReset(
6475  int *pRc,
6476  sqlite3_stmt *pStmt
6477){
6478  int rc = sqlite3_reset(pStmt);
6479  if( *pRc==SQLITE_OK ){
6480    if( rc!=SQLITE_OK ){
6481      sqlite3 *db = sqlite3_db_handle(pStmt);
6482      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6483    }
6484    *pRc = rc;
6485  }
6486}
6487#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6488
6489#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6490/******************************************************************************
6491** The ".archive" or ".ar" command.
6492*/
6493/*
6494** Structure representing a single ".ar" command.
6495*/
6496typedef struct ArCommand ArCommand;
6497struct ArCommand {
6498  u8 eCmd;                        /* An AR_CMD_* value */
6499  u8 bVerbose;                    /* True if --verbose */
6500  u8 bZip;                        /* True if the archive is a ZIP */
6501  u8 bDryRun;                     /* True if --dry-run */
6502  u8 bAppend;                     /* True if --append */
6503  u8 bGlob;                       /* True if --glob */
6504  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6505  int nArg;                       /* Number of command arguments */
6506  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6507  const char *zFile;              /* --file argument, or NULL */
6508  const char *zDir;               /* --directory argument, or NULL */
6509  char **azArg;                   /* Array of command arguments */
6510  ShellState *p;                  /* Shell state */
6511  sqlite3 *db;                    /* Database containing the archive */
6512};
6513
6514/*
6515** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6516*/
6517static int arUsage(FILE *f){
6518  showHelp(f,"archive");
6519  return SQLITE_ERROR;
6520}
6521
6522/*
6523** Print an error message for the .ar command to stderr and return
6524** SQLITE_ERROR.
6525*/
6526static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6527  va_list ap;
6528  char *z;
6529  va_start(ap, zFmt);
6530  z = sqlite3_vmprintf(zFmt, ap);
6531  va_end(ap);
6532  utf8_printf(stderr, "Error: %s\n", z);
6533  if( pAr->fromCmdLine ){
6534    utf8_printf(stderr, "Use \"-A\" for more help\n");
6535  }else{
6536    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6537  }
6538  sqlite3_free(z);
6539  return SQLITE_ERROR;
6540}
6541
6542/*
6543** Values for ArCommand.eCmd.
6544*/
6545#define AR_CMD_CREATE       1
6546#define AR_CMD_UPDATE       2
6547#define AR_CMD_INSERT       3
6548#define AR_CMD_EXTRACT      4
6549#define AR_CMD_LIST         5
6550#define AR_CMD_HELP         6
6551#define AR_CMD_REMOVE       7
6552
6553/*
6554** Other (non-command) switches.
6555*/
6556#define AR_SWITCH_VERBOSE     8
6557#define AR_SWITCH_FILE        9
6558#define AR_SWITCH_DIRECTORY  10
6559#define AR_SWITCH_APPEND     11
6560#define AR_SWITCH_DRYRUN     12
6561#define AR_SWITCH_GLOB       13
6562
6563static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6564  switch( eSwitch ){
6565    case AR_CMD_CREATE:
6566    case AR_CMD_EXTRACT:
6567    case AR_CMD_LIST:
6568    case AR_CMD_REMOVE:
6569    case AR_CMD_UPDATE:
6570    case AR_CMD_INSERT:
6571    case AR_CMD_HELP:
6572      if( pAr->eCmd ){
6573        return arErrorMsg(pAr, "multiple command options");
6574      }
6575      pAr->eCmd = eSwitch;
6576      break;
6577
6578    case AR_SWITCH_DRYRUN:
6579      pAr->bDryRun = 1;
6580      break;
6581    case AR_SWITCH_GLOB:
6582      pAr->bGlob = 1;
6583      break;
6584    case AR_SWITCH_VERBOSE:
6585      pAr->bVerbose = 1;
6586      break;
6587    case AR_SWITCH_APPEND:
6588      pAr->bAppend = 1;
6589      /* Fall thru into --file */
6590    case AR_SWITCH_FILE:
6591      pAr->zFile = zArg;
6592      break;
6593    case AR_SWITCH_DIRECTORY:
6594      pAr->zDir = zArg;
6595      break;
6596  }
6597
6598  return SQLITE_OK;
6599}
6600
6601/*
6602** Parse the command line for an ".ar" command. The results are written into
6603** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6604** successfully, otherwise an error message is written to stderr and
6605** SQLITE_ERROR returned.
6606*/
6607static int arParseCommand(
6608  char **azArg,                   /* Array of arguments passed to dot command */
6609  int nArg,                       /* Number of entries in azArg[] */
6610  ArCommand *pAr                  /* Populate this object */
6611){
6612  struct ArSwitch {
6613    const char *zLong;
6614    char cShort;
6615    u8 eSwitch;
6616    u8 bArg;
6617  } aSwitch[] = {
6618    { "create",    'c', AR_CMD_CREATE,       0 },
6619    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6620    { "insert",    'i', AR_CMD_INSERT,       0 },
6621    { "list",      't', AR_CMD_LIST,         0 },
6622    { "remove",    'r', AR_CMD_REMOVE,       0 },
6623    { "update",    'u', AR_CMD_UPDATE,       0 },
6624    { "help",      'h', AR_CMD_HELP,         0 },
6625    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6626    { "file",      'f', AR_SWITCH_FILE,      1 },
6627    { "append",    'a', AR_SWITCH_APPEND,    1 },
6628    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6629    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6630    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6631  };
6632  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6633  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6634
6635  if( nArg<=1 ){
6636    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6637    return arUsage(stderr);
6638  }else{
6639    char *z = azArg[1];
6640    if( z[0]!='-' ){
6641      /* Traditional style [tar] invocation */
6642      int i;
6643      int iArg = 2;
6644      for(i=0; z[i]; i++){
6645        const char *zArg = 0;
6646        struct ArSwitch *pOpt;
6647        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6648          if( z[i]==pOpt->cShort ) break;
6649        }
6650        if( pOpt==pEnd ){
6651          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6652        }
6653        if( pOpt->bArg ){
6654          if( iArg>=nArg ){
6655            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6656          }
6657          zArg = azArg[iArg++];
6658        }
6659        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6660      }
6661      pAr->nArg = nArg-iArg;
6662      if( pAr->nArg>0 ){
6663        pAr->azArg = &azArg[iArg];
6664      }
6665    }else{
6666      /* Non-traditional invocation */
6667      int iArg;
6668      for(iArg=1; iArg<nArg; iArg++){
6669        int n;
6670        z = azArg[iArg];
6671        if( z[0]!='-' ){
6672          /* All remaining command line words are command arguments. */
6673          pAr->azArg = &azArg[iArg];
6674          pAr->nArg = nArg-iArg;
6675          break;
6676        }
6677        n = strlen30(z);
6678
6679        if( z[1]!='-' ){
6680          int i;
6681          /* One or more short options */
6682          for(i=1; i<n; i++){
6683            const char *zArg = 0;
6684            struct ArSwitch *pOpt;
6685            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6686              if( z[i]==pOpt->cShort ) break;
6687            }
6688            if( pOpt==pEnd ){
6689              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6690            }
6691            if( pOpt->bArg ){
6692              if( i<(n-1) ){
6693                zArg = &z[i+1];
6694                i = n;
6695              }else{
6696                if( iArg>=(nArg-1) ){
6697                  return arErrorMsg(pAr, "option requires an argument: %c",
6698                                    z[i]);
6699                }
6700                zArg = azArg[++iArg];
6701              }
6702            }
6703            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6704          }
6705        }else if( z[2]=='\0' ){
6706          /* A -- option, indicating that all remaining command line words
6707          ** are command arguments.  */
6708          pAr->azArg = &azArg[iArg+1];
6709          pAr->nArg = nArg-iArg-1;
6710          break;
6711        }else{
6712          /* A long option */
6713          const char *zArg = 0;             /* Argument for option, if any */
6714          struct ArSwitch *pMatch = 0;      /* Matching option */
6715          struct ArSwitch *pOpt;            /* Iterator */
6716          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6717            const char *zLong = pOpt->zLong;
6718            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6719              if( pMatch ){
6720                return arErrorMsg(pAr, "ambiguous option: %s",z);
6721              }else{
6722                pMatch = pOpt;
6723              }
6724            }
6725          }
6726
6727          if( pMatch==0 ){
6728            return arErrorMsg(pAr, "unrecognized option: %s", z);
6729          }
6730          if( pMatch->bArg ){
6731            if( iArg>=(nArg-1) ){
6732              return arErrorMsg(pAr, "option requires an argument: %s", z);
6733            }
6734            zArg = azArg[++iArg];
6735          }
6736          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6737        }
6738      }
6739    }
6740  }
6741
6742  return SQLITE_OK;
6743}
6744
6745/*
6746** This function assumes that all arguments within the ArCommand.azArg[]
6747** array refer to archive members, as for the --extract, --list or --remove
6748** commands. It checks that each of them are "present". If any specified
6749** file is not present in the archive, an error is printed to stderr and an
6750** error code returned. Otherwise, if all specified arguments are present
6751** in the archive, SQLITE_OK is returned. Here, "present" means either an
6752** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6753** when pAr->bGlob is true.
6754**
6755** This function strips any trailing '/' characters from each argument.
6756** This is consistent with the way the [tar] command seems to work on
6757** Linux.
6758*/
6759static int arCheckEntries(ArCommand *pAr){
6760  int rc = SQLITE_OK;
6761  if( pAr->nArg ){
6762    int i, j;
6763    sqlite3_stmt *pTest = 0;
6764    const char *zSel = (pAr->bGlob)
6765      ? "SELECT name FROM %s WHERE glob($name,name)"
6766      : "SELECT name FROM %s WHERE name=$name";
6767
6768    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6769    j = sqlite3_bind_parameter_index(pTest, "$name");
6770    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6771      char *z = pAr->azArg[i];
6772      int n = strlen30(z);
6773      int bOk = 0;
6774      while( n>0 && z[n-1]=='/' ) n--;
6775      z[n] = '\0';
6776      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6777      if( SQLITE_ROW==sqlite3_step(pTest) ){
6778        bOk = 1;
6779      }
6780      shellReset(&rc, pTest);
6781      if( rc==SQLITE_OK && bOk==0 ){
6782        utf8_printf(stderr, "not found in archive: %s\n", z);
6783        rc = SQLITE_ERROR;
6784      }
6785    }
6786    shellFinalize(&rc, pTest);
6787  }
6788  return rc;
6789}
6790
6791/*
6792** Format a WHERE clause that can be used against the "sqlar" table to
6793** identify all archive members that match the command arguments held
6794** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6795** The caller is responsible for eventually calling sqlite3_free() on
6796** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6797** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6798*/
6799static void arWhereClause(
6800  int *pRc,
6801  ArCommand *pAr,
6802  char **pzWhere                  /* OUT: New WHERE clause */
6803){
6804  char *zWhere = 0;
6805  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6806  if( *pRc==SQLITE_OK ){
6807    if( pAr->nArg==0 ){
6808      zWhere = sqlite3_mprintf("1");
6809    }else{
6810      int i;
6811      const char *zSep = "";
6812      for(i=0; i<pAr->nArg; i++){
6813        const char *z = pAr->azArg[i];
6814        zWhere = sqlite3_mprintf(
6815          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6816          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6817        );
6818        if( zWhere==0 ){
6819          *pRc = SQLITE_NOMEM;
6820          break;
6821        }
6822        zSep = " OR ";
6823      }
6824    }
6825  }
6826  *pzWhere = zWhere;
6827}
6828
6829/*
6830** Implementation of .ar "lisT" command.
6831*/
6832static int arListCommand(ArCommand *pAr){
6833  const char *zSql = "SELECT %s FROM %s WHERE %s";
6834  const char *azCols[] = {
6835    "name",
6836    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6837  };
6838
6839  char *zWhere = 0;
6840  sqlite3_stmt *pSql = 0;
6841  int rc;
6842
6843  rc = arCheckEntries(pAr);
6844  arWhereClause(&rc, pAr, &zWhere);
6845
6846  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6847                     pAr->zSrcTable, zWhere);
6848  if( pAr->bDryRun ){
6849    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6850  }else{
6851    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6852      if( pAr->bVerbose ){
6853        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6854            sqlite3_column_text(pSql, 0),
6855            sqlite3_column_int(pSql, 1),
6856            sqlite3_column_text(pSql, 2),
6857            sqlite3_column_text(pSql, 3)
6858        );
6859      }else{
6860        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6861      }
6862    }
6863  }
6864  shellFinalize(&rc, pSql);
6865  sqlite3_free(zWhere);
6866  return rc;
6867}
6868
6869
6870/*
6871** Implementation of .ar "Remove" command.
6872*/
6873static int arRemoveCommand(ArCommand *pAr){
6874  int rc = 0;
6875  char *zSql = 0;
6876  char *zWhere = 0;
6877
6878  if( pAr->nArg ){
6879    /* Verify that args actually exist within the archive before proceeding.
6880    ** And formulate a WHERE clause to match them.  */
6881    rc = arCheckEntries(pAr);
6882    arWhereClause(&rc, pAr, &zWhere);
6883  }
6884  if( rc==SQLITE_OK ){
6885    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6886                           pAr->zSrcTable, zWhere);
6887    if( pAr->bDryRun ){
6888      utf8_printf(pAr->p->out, "%s\n", zSql);
6889    }else{
6890      char *zErr = 0;
6891      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6892      if( rc==SQLITE_OK ){
6893        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6894        if( rc!=SQLITE_OK ){
6895          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6896        }else{
6897          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6898        }
6899      }
6900      if( zErr ){
6901        utf8_printf(stdout, "ERROR: %s\n", zErr);
6902        sqlite3_free(zErr);
6903      }
6904    }
6905  }
6906  sqlite3_free(zWhere);
6907  sqlite3_free(zSql);
6908  return rc;
6909}
6910
6911/*
6912** Implementation of .ar "eXtract" command.
6913*/
6914static int arExtractCommand(ArCommand *pAr){
6915  const char *zSql1 =
6916    "SELECT "
6917    " ($dir || name),"
6918    " writefile(($dir || name), %s, mode, mtime) "
6919    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6920    " AND name NOT GLOB '*..[/\\]*'";
6921
6922  const char *azExtraArg[] = {
6923    "sqlar_uncompress(data, sz)",
6924    "data"
6925  };
6926
6927  sqlite3_stmt *pSql = 0;
6928  int rc = SQLITE_OK;
6929  char *zDir = 0;
6930  char *zWhere = 0;
6931  int i, j;
6932
6933  /* If arguments are specified, check that they actually exist within
6934  ** the archive before proceeding. And formulate a WHERE clause to
6935  ** match them.  */
6936  rc = arCheckEntries(pAr);
6937  arWhereClause(&rc, pAr, &zWhere);
6938
6939  if( rc==SQLITE_OK ){
6940    if( pAr->zDir ){
6941      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6942    }else{
6943      zDir = sqlite3_mprintf("");
6944    }
6945    if( zDir==0 ) rc = SQLITE_NOMEM;
6946  }
6947
6948  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6949      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6950  );
6951
6952  if( rc==SQLITE_OK ){
6953    j = sqlite3_bind_parameter_index(pSql, "$dir");
6954    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6955
6956    /* Run the SELECT statement twice. The first time, writefile() is called
6957    ** for all archive members that should be extracted. The second time,
6958    ** only for the directories. This is because the timestamps for
6959    ** extracted directories must be reset after they are populated (as
6960    ** populating them changes the timestamp).  */
6961    for(i=0; i<2; i++){
6962      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6963      sqlite3_bind_int(pSql, j, i);
6964      if( pAr->bDryRun ){
6965        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6966      }else{
6967        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6968          if( i==0 && pAr->bVerbose ){
6969            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6970          }
6971        }
6972      }
6973      shellReset(&rc, pSql);
6974    }
6975    shellFinalize(&rc, pSql);
6976  }
6977
6978  sqlite3_free(zDir);
6979  sqlite3_free(zWhere);
6980  return rc;
6981}
6982
6983/*
6984** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6985*/
6986static int arExecSql(ArCommand *pAr, const char *zSql){
6987  int rc;
6988  if( pAr->bDryRun ){
6989    utf8_printf(pAr->p->out, "%s\n", zSql);
6990    rc = SQLITE_OK;
6991  }else{
6992    char *zErr = 0;
6993    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6994    if( zErr ){
6995      utf8_printf(stdout, "ERROR: %s\n", zErr);
6996      sqlite3_free(zErr);
6997    }
6998  }
6999  return rc;
7000}
7001
7002
7003/*
7004** Implementation of .ar "create", "insert", and "update" commands.
7005**
7006**     create    ->     Create a new SQL archive
7007**     insert    ->     Insert or reinsert all files listed
7008**     update    ->     Insert files that have changed or that were not
7009**                      previously in the archive
7010**
7011** Create the "sqlar" table in the database if it does not already exist.
7012** Then add each file in the azFile[] array to the archive. Directories
7013** are added recursively. If argument bVerbose is non-zero, a message is
7014** printed on stdout for each file archived.
7015**
7016** The create command is the same as update, except that it drops
7017** any existing "sqlar" table before beginning.  The "insert" command
7018** always overwrites every file named on the command-line, where as
7019** "update" only overwrites if the size or mtime or mode has changed.
7020*/
7021static int arCreateOrUpdateCommand(
7022  ArCommand *pAr,                 /* Command arguments and options */
7023  int bUpdate,                    /* true for a --create. */
7024  int bOnlyIfChanged              /* Only update if file has changed */
7025){
7026  const char *zCreate =
7027      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7028      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7029      "  mode INT,               -- access permissions\n"
7030      "  mtime INT,              -- last modification time\n"
7031      "  sz INT,                 -- original file size\n"
7032      "  data BLOB               -- compressed content\n"
7033      ")";
7034  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7035  const char *zInsertFmt[2] = {
7036     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7037     "  SELECT\n"
7038     "    %s,\n"
7039     "    mode,\n"
7040     "    mtime,\n"
7041     "    CASE substr(lsmode(mode),1,1)\n"
7042     "      WHEN '-' THEN length(data)\n"
7043     "      WHEN 'd' THEN 0\n"
7044     "      ELSE -1 END,\n"
7045     "    sqlar_compress(data)\n"
7046     "  FROM fsdir(%Q,%Q) AS disk\n"
7047     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7048     ,
7049     "REPLACE INTO %s(name,mode,mtime,data)\n"
7050     "  SELECT\n"
7051     "    %s,\n"
7052     "    mode,\n"
7053     "    mtime,\n"
7054     "    data\n"
7055     "  FROM fsdir(%Q,%Q) AS disk\n"
7056     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7057  };
7058  int i;                          /* For iterating through azFile[] */
7059  int rc;                         /* Return code */
7060  const char *zTab = 0;           /* SQL table into which to insert */
7061  char *zSql;
7062  char zTemp[50];
7063  char *zExists = 0;
7064
7065  arExecSql(pAr, "PRAGMA page_size=512");
7066  rc = arExecSql(pAr, "SAVEPOINT ar;");
7067  if( rc!=SQLITE_OK ) return rc;
7068  zTemp[0] = 0;
7069  if( pAr->bZip ){
7070    /* Initialize the zipfile virtual table, if necessary */
7071    if( pAr->zFile ){
7072      sqlite3_uint64 r;
7073      sqlite3_randomness(sizeof(r),&r);
7074      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7075      zTab = zTemp;
7076      zSql = sqlite3_mprintf(
7077         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7078         zTab, pAr->zFile
7079      );
7080      rc = arExecSql(pAr, zSql);
7081      sqlite3_free(zSql);
7082    }else{
7083      zTab = "zip";
7084    }
7085  }else{
7086    /* Initialize the table for an SQLAR */
7087    zTab = "sqlar";
7088    if( bUpdate==0 ){
7089      rc = arExecSql(pAr, zDrop);
7090      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7091    }
7092    rc = arExecSql(pAr, zCreate);
7093  }
7094  if( bOnlyIfChanged ){
7095    zExists = sqlite3_mprintf(
7096      " AND NOT EXISTS("
7097          "SELECT 1 FROM %s AS mem"
7098          " WHERE mem.name=disk.name"
7099          " AND mem.mtime=disk.mtime"
7100          " AND mem.mode=disk.mode)", zTab);
7101  }else{
7102    zExists = sqlite3_mprintf("");
7103  }
7104  if( zExists==0 ) rc = SQLITE_NOMEM;
7105  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7106    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7107        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7108        pAr->azArg[i], pAr->zDir, zExists);
7109    rc = arExecSql(pAr, zSql2);
7110    sqlite3_free(zSql2);
7111  }
7112end_ar_transaction:
7113  if( rc!=SQLITE_OK ){
7114    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7115  }else{
7116    rc = arExecSql(pAr, "RELEASE ar;");
7117    if( pAr->bZip && pAr->zFile ){
7118      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7119      arExecSql(pAr, zSql);
7120      sqlite3_free(zSql);
7121    }
7122  }
7123  sqlite3_free(zExists);
7124  return rc;
7125}
7126
7127/*
7128** Implementation of ".ar" dot command.
7129*/
7130static int arDotCommand(
7131  ShellState *pState,          /* Current shell tool state */
7132  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7133  char **azArg,                /* Array of arguments passed to dot command */
7134  int nArg                     /* Number of entries in azArg[] */
7135){
7136  ArCommand cmd;
7137  int rc;
7138  memset(&cmd, 0, sizeof(cmd));
7139  cmd.fromCmdLine = fromCmdLine;
7140  rc = arParseCommand(azArg, nArg, &cmd);
7141  if( rc==SQLITE_OK ){
7142    int eDbType = SHELL_OPEN_UNSPEC;
7143    cmd.p = pState;
7144    cmd.db = pState->db;
7145    if( cmd.zFile ){
7146      eDbType = deduceDatabaseType(cmd.zFile, 1);
7147    }else{
7148      eDbType = pState->openMode;
7149    }
7150    if( eDbType==SHELL_OPEN_ZIPFILE ){
7151      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7152        if( cmd.zFile==0 ){
7153          cmd.zSrcTable = sqlite3_mprintf("zip");
7154        }else{
7155          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7156        }
7157      }
7158      cmd.bZip = 1;
7159    }else if( cmd.zFile ){
7160      int flags;
7161      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7162      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7163           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7164        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7165      }else{
7166        flags = SQLITE_OPEN_READONLY;
7167      }
7168      cmd.db = 0;
7169      if( cmd.bDryRun ){
7170        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7171             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7172      }
7173      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7174             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7175      if( rc!=SQLITE_OK ){
7176        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7177            cmd.zFile, sqlite3_errmsg(cmd.db)
7178        );
7179        goto end_ar_command;
7180      }
7181      sqlite3_fileio_init(cmd.db, 0, 0);
7182      sqlite3_sqlar_init(cmd.db, 0, 0);
7183      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7184                              shellPutsFunc, 0, 0);
7185
7186    }
7187    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7188      if( cmd.eCmd!=AR_CMD_CREATE
7189       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7190      ){
7191        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7192        rc = SQLITE_ERROR;
7193        goto end_ar_command;
7194      }
7195      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7196    }
7197
7198    switch( cmd.eCmd ){
7199      case AR_CMD_CREATE:
7200        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7201        break;
7202
7203      case AR_CMD_EXTRACT:
7204        rc = arExtractCommand(&cmd);
7205        break;
7206
7207      case AR_CMD_LIST:
7208        rc = arListCommand(&cmd);
7209        break;
7210
7211      case AR_CMD_HELP:
7212        arUsage(pState->out);
7213        break;
7214
7215      case AR_CMD_INSERT:
7216        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7217        break;
7218
7219      case AR_CMD_REMOVE:
7220        rc = arRemoveCommand(&cmd);
7221        break;
7222
7223      default:
7224        assert( cmd.eCmd==AR_CMD_UPDATE );
7225        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7226        break;
7227    }
7228  }
7229end_ar_command:
7230  if( cmd.db!=pState->db ){
7231    close_db(cmd.db);
7232  }
7233  sqlite3_free(cmd.zSrcTable);
7234
7235  return rc;
7236}
7237/* End of the ".archive" or ".ar" command logic
7238*******************************************************************************/
7239#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7240
7241#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7242/*
7243** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7244** Otherwise, the SQL statement or statements in zSql are executed using
7245** database connection db and the error code written to *pRc before
7246** this function returns.
7247*/
7248static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7249  int rc = *pRc;
7250  if( rc==SQLITE_OK ){
7251    char *zErr = 0;
7252    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7253    if( rc!=SQLITE_OK ){
7254      raw_printf(stderr, "SQL error: %s\n", zErr);
7255    }
7256    sqlite3_free(zErr);
7257    *pRc = rc;
7258  }
7259}
7260
7261/*
7262** Like shellExec(), except that zFmt is a printf() style format string.
7263*/
7264static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7265  char *z = 0;
7266  if( *pRc==SQLITE_OK ){
7267    va_list ap;
7268    va_start(ap, zFmt);
7269    z = sqlite3_vmprintf(zFmt, ap);
7270    va_end(ap);
7271    if( z==0 ){
7272      *pRc = SQLITE_NOMEM;
7273    }else{
7274      shellExec(db, pRc, z);
7275    }
7276    sqlite3_free(z);
7277  }
7278}
7279
7280/*
7281** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7282** Otherwise, an attempt is made to allocate, zero and return a pointer
7283** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7284** to SQLITE_NOMEM and NULL returned.
7285*/
7286static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7287  void *pRet = 0;
7288  if( *pRc==SQLITE_OK ){
7289    pRet = sqlite3_malloc64(nByte);
7290    if( pRet==0 ){
7291      *pRc = SQLITE_NOMEM;
7292    }else{
7293      memset(pRet, 0, nByte);
7294    }
7295  }
7296  return pRet;
7297}
7298
7299/*
7300** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7301** Otherwise, zFmt is treated as a printf() style string. The result of
7302** formatting it along with any trailing arguments is written into a
7303** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7304** It is the responsibility of the caller to eventually free this buffer
7305** using a call to sqlite3_free().
7306**
7307** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7308** pointer returned.
7309*/
7310static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7311  char *z = 0;
7312  if( *pRc==SQLITE_OK ){
7313    va_list ap;
7314    va_start(ap, zFmt);
7315    z = sqlite3_vmprintf(zFmt, ap);
7316    va_end(ap);
7317    if( z==0 ){
7318      *pRc = SQLITE_NOMEM;
7319    }
7320  }
7321  return z;
7322}
7323
7324
7325/*
7326** When running the ".recover" command, each output table, and the special
7327** orphaned row table if it is required, is represented by an instance
7328** of the following struct.
7329*/
7330typedef struct RecoverTable RecoverTable;
7331struct RecoverTable {
7332  char *zQuoted;                  /* Quoted version of table name */
7333  int nCol;                       /* Number of columns in table */
7334  char **azlCol;                  /* Array of column lists */
7335  int iPk;                        /* Index of IPK column */
7336};
7337
7338/*
7339** Free a RecoverTable object allocated by recoverFindTable() or
7340** recoverOrphanTable().
7341*/
7342static void recoverFreeTable(RecoverTable *pTab){
7343  if( pTab ){
7344    sqlite3_free(pTab->zQuoted);
7345    if( pTab->azlCol ){
7346      int i;
7347      for(i=0; i<=pTab->nCol; i++){
7348        sqlite3_free(pTab->azlCol[i]);
7349      }
7350      sqlite3_free(pTab->azlCol);
7351    }
7352    sqlite3_free(pTab);
7353  }
7354}
7355
7356/*
7357** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7358** Otherwise, it allocates and returns a RecoverTable object based on the
7359** final four arguments passed to this function. It is the responsibility
7360** of the caller to eventually free the returned object using
7361** recoverFreeTable().
7362*/
7363static RecoverTable *recoverNewTable(
7364  int *pRc,                       /* IN/OUT: Error code */
7365  const char *zName,              /* Name of table */
7366  const char *zSql,               /* CREATE TABLE statement */
7367  int bIntkey,
7368  int nCol
7369){
7370  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7371  int rc = *pRc;
7372  RecoverTable *pTab = 0;
7373
7374  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7375  if( rc==SQLITE_OK ){
7376    int nSqlCol = 0;
7377    int bSqlIntkey = 0;
7378    sqlite3_stmt *pStmt = 0;
7379
7380    rc = sqlite3_open("", &dbtmp);
7381    if( rc==SQLITE_OK ){
7382      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7383                              shellIdQuote, 0, 0);
7384    }
7385    if( rc==SQLITE_OK ){
7386      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7387    }
7388    if( rc==SQLITE_OK ){
7389      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7390      if( rc==SQLITE_ERROR ){
7391        rc = SQLITE_OK;
7392        goto finished;
7393      }
7394    }
7395    shellPreparePrintf(dbtmp, &rc, &pStmt,
7396        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7397    );
7398    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7399      nSqlCol = sqlite3_column_int(pStmt, 0);
7400    }
7401    shellFinalize(&rc, pStmt);
7402
7403    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7404      goto finished;
7405    }
7406
7407    shellPreparePrintf(dbtmp, &rc, &pStmt,
7408      "SELECT ("
7409      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7410      ") FROM sqlite_schema WHERE name = %Q", zName
7411    );
7412    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7413      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7414    }
7415    shellFinalize(&rc, pStmt);
7416
7417    if( bIntkey==bSqlIntkey ){
7418      int i;
7419      const char *zPk = "_rowid_";
7420      sqlite3_stmt *pPkFinder = 0;
7421
7422      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7423      ** set zPk to the name of the PK column, and pTab->iPk to the index
7424      ** of the column, where columns are 0-numbered from left to right.
7425      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7426      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7427      pTab->iPk = -2;
7428      if( bIntkey ){
7429        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7430          "SELECT cid, name FROM pragma_table_info(%Q) "
7431          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7432          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7433          , zName, zName
7434        );
7435        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7436          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7437          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7438          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7439        }
7440      }
7441
7442      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7443      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7444      pTab->nCol = nSqlCol;
7445
7446      if( bIntkey ){
7447        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7448      }else{
7449        pTab->azlCol[0] = shellMPrintf(&rc, "");
7450      }
7451      i = 1;
7452      shellPreparePrintf(dbtmp, &rc, &pStmt,
7453          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7454          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7455          "FROM pragma_table_info(%Q)",
7456          bIntkey ? ", " : "", pTab->iPk,
7457          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7458          zName
7459      );
7460      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7461        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7462        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7463        i++;
7464      }
7465      shellFinalize(&rc, pStmt);
7466
7467      shellFinalize(&rc, pPkFinder);
7468    }
7469  }
7470
7471 finished:
7472  sqlite3_close(dbtmp);
7473  *pRc = rc;
7474  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7475    recoverFreeTable(pTab);
7476    pTab = 0;
7477  }
7478  return pTab;
7479}
7480
7481/*
7482** This function is called to search the schema recovered from the
7483** sqlite_schema table of the (possibly) corrupt database as part
7484** of a ".recover" command. Specifically, for a table with root page
7485** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7486** table must be a WITHOUT ROWID table, or if non-zero, not one of
7487** those.
7488**
7489** If a table is found, a (RecoverTable*) object is returned. Or, if
7490** no such table is found, but bIntkey is false and iRoot is the
7491** root page of an index in the recovered schema, then (*pbNoop) is
7492** set to true and NULL returned. Or, if there is no such table or
7493** index, NULL is returned and (*pbNoop) set to 0, indicating that
7494** the caller should write data to the orphans table.
7495*/
7496static RecoverTable *recoverFindTable(
7497  ShellState *pState,             /* Shell state object */
7498  int *pRc,                       /* IN/OUT: Error code */
7499  int iRoot,                      /* Root page of table */
7500  int bIntkey,                    /* True for an intkey table */
7501  int nCol,                       /* Number of columns in table */
7502  int *pbNoop                     /* OUT: True if iRoot is root of index */
7503){
7504  sqlite3_stmt *pStmt = 0;
7505  RecoverTable *pRet = 0;
7506  int bNoop = 0;
7507  const char *zSql = 0;
7508  const char *zName = 0;
7509
7510  /* Search the recovered schema for an object with root page iRoot. */
7511  shellPreparePrintf(pState->db, pRc, &pStmt,
7512      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7513  );
7514  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7515    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7516    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7517      bNoop = 1;
7518      break;
7519    }
7520    if( sqlite3_stricmp(zType, "table")==0 ){
7521      zName = (const char*)sqlite3_column_text(pStmt, 1);
7522      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7523      if( zName!=0 && zSql!=0 ){
7524        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7525        break;
7526      }
7527    }
7528  }
7529
7530  shellFinalize(pRc, pStmt);
7531  *pbNoop = bNoop;
7532  return pRet;
7533}
7534
7535/*
7536** Return a RecoverTable object representing the orphans table.
7537*/
7538static RecoverTable *recoverOrphanTable(
7539  ShellState *pState,             /* Shell state object */
7540  int *pRc,                       /* IN/OUT: Error code */
7541  const char *zLostAndFound,      /* Base name for orphans table */
7542  int nCol                        /* Number of user data columns */
7543){
7544  RecoverTable *pTab = 0;
7545  if( nCol>=0 && *pRc==SQLITE_OK ){
7546    int i;
7547
7548    /* This block determines the name of the orphan table. The prefered
7549    ** name is zLostAndFound. But if that clashes with another name
7550    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7551    ** and so on until a non-clashing name is found.  */
7552    int iTab = 0;
7553    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7554    sqlite3_stmt *pTest = 0;
7555    shellPrepare(pState->db, pRc,
7556        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7557    );
7558    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7559    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7560      shellReset(pRc, pTest);
7561      sqlite3_free(zTab);
7562      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7563      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7564    }
7565    shellFinalize(pRc, pTest);
7566
7567    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7568    if( pTab ){
7569      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7570      pTab->nCol = nCol;
7571      pTab->iPk = -2;
7572      if( nCol>0 ){
7573        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7574        if( pTab->azlCol ){
7575          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7576          for(i=nCol-1; i>=0; i--){
7577            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7578          }
7579        }
7580      }
7581
7582      if( *pRc!=SQLITE_OK ){
7583        recoverFreeTable(pTab);
7584        pTab = 0;
7585      }else{
7586        raw_printf(pState->out,
7587            "CREATE TABLE %s(rootpgno INTEGER, "
7588            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7589        );
7590        for(i=0; i<nCol; i++){
7591          raw_printf(pState->out, ", c%d", i);
7592        }
7593        raw_printf(pState->out, ");\n");
7594      }
7595    }
7596    sqlite3_free(zTab);
7597  }
7598  return pTab;
7599}
7600
7601/*
7602** This function is called to recover data from the database. A script
7603** to construct a new database containing all recovered data is output
7604** on stream pState->out.
7605*/
7606static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7607  int rc = SQLITE_OK;
7608  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7609  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7610  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7611  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7612  const char *zLostAndFound = "lost_and_found";
7613  int i;
7614  int nOrphan = -1;
7615  RecoverTable *pOrphan = 0;
7616
7617  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7618  int bRowids = 1;                /* 0 if --no-rowids */
7619  for(i=1; i<nArg; i++){
7620    char *z = azArg[i];
7621    int n;
7622    if( z[0]=='-' && z[1]=='-' ) z++;
7623    n = strlen30(z);
7624    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7625      bFreelist = 0;
7626    }else
7627    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7628      i++;
7629      zRecoveryDb = azArg[i];
7630    }else
7631    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7632      i++;
7633      zLostAndFound = azArg[i];
7634    }else
7635    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7636      bRowids = 0;
7637    }
7638    else{
7639      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7640      showHelp(pState->out, azArg[0]);
7641      return 1;
7642    }
7643  }
7644
7645  shellExecPrintf(pState->db, &rc,
7646    /* Attach an in-memory database named 'recovery'. Create an indexed
7647    ** cache of the sqlite_dbptr virtual table. */
7648    "PRAGMA writable_schema = on;"
7649    "ATTACH %Q AS recovery;"
7650    "DROP TABLE IF EXISTS recovery.dbptr;"
7651    "DROP TABLE IF EXISTS recovery.freelist;"
7652    "DROP TABLE IF EXISTS recovery.map;"
7653    "DROP TABLE IF EXISTS recovery.schema;"
7654    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7655  );
7656
7657  if( bFreelist ){
7658    shellExec(pState->db, &rc,
7659      "WITH trunk(pgno) AS ("
7660      "  SELECT shell_int32("
7661      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7662      "      WHERE x>0"
7663      "    UNION"
7664      "  SELECT shell_int32("
7665      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7666      "      FROM trunk WHERE x>0"
7667      "),"
7668      "freelist(data, n, freepgno) AS ("
7669      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7670      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7671      "    UNION ALL"
7672      "  SELECT data, n-1, shell_int32(data, 2+n) "
7673      "      FROM freelist WHERE n>=0"
7674      ")"
7675      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7676    );
7677  }
7678
7679  /* If this is an auto-vacuum database, add all pointer-map pages to
7680  ** the freelist table. Do this regardless of whether or not
7681  ** --freelist-corrupt was specified.  */
7682  shellExec(pState->db, &rc,
7683    "WITH ptrmap(pgno) AS ("
7684    "  SELECT 2 WHERE shell_int32("
7685    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7686    "  )"
7687    "    UNION ALL "
7688    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7689    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7690    ")"
7691    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7692  );
7693
7694  shellExec(pState->db, &rc,
7695    "CREATE TABLE recovery.dbptr("
7696    "      pgno, child, PRIMARY KEY(child, pgno)"
7697    ") WITHOUT ROWID;"
7698    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7699    "    SELECT * FROM sqlite_dbptr"
7700    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7701
7702    /* Delete any pointer to page 1. This ensures that page 1 is considered
7703    ** a root page, regardless of how corrupt the db is. */
7704    "DELETE FROM recovery.dbptr WHERE child = 1;"
7705
7706    /* Delete all pointers to any pages that have more than one pointer
7707    ** to them. Such pages will be treated as root pages when recovering
7708    ** data.  */
7709    "DELETE FROM recovery.dbptr WHERE child IN ("
7710    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7711    ");"
7712
7713    /* Create the "map" table that will (eventually) contain instructions
7714    ** for dealing with each page in the db that contains one or more
7715    ** records. */
7716    "CREATE TABLE recovery.map("
7717      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7718    ");"
7719
7720    /* Populate table [map]. If there are circular loops of pages in the
7721    ** database, the following adds all pages in such a loop to the map
7722    ** as individual root pages. This could be handled better.  */
7723    "WITH pages(i, maxlen) AS ("
7724    "  SELECT page_count, ("
7725    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7726    "  ) FROM pragma_page_count WHERE page_count>0"
7727    "    UNION ALL"
7728    "  SELECT i-1, ("
7729    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7730    "  ) FROM pages WHERE i>=2"
7731    ")"
7732    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7733    "  SELECT i, maxlen, NULL, ("
7734    "    WITH p(orig, pgno, parent) AS ("
7735    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7736    "        UNION "
7737    "      SELECT i, p.parent, "
7738    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7739    "    )"
7740    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7741    ") "
7742    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7743    "UPDATE recovery.map AS o SET intkey = ("
7744    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7745    ");"
7746
7747    /* Extract data from page 1 and any linked pages into table
7748    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7749    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7750    "INSERT INTO recovery.schema SELECT "
7751    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7752    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7753    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7754    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7755    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7756    "FROM sqlite_dbdata WHERE pgno IN ("
7757    "  SELECT pgno FROM recovery.map WHERE root=1"
7758    ")"
7759    "GROUP BY pgno, cell;"
7760    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7761  );
7762
7763  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7764  ** CREATE TABLE statements that extracted from the existing schema.  */
7765  if( rc==SQLITE_OK ){
7766    sqlite3_stmt *pStmt = 0;
7767    /* ".recover" might output content in an order which causes immediate
7768    ** foreign key constraints to be violated. So disable foreign-key
7769    ** constraint enforcement to prevent problems when running the output
7770    ** script. */
7771    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7772    raw_printf(pState->out, "BEGIN;\n");
7773    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7774    shellPrepare(pState->db, &rc,
7775        "SELECT sql FROM recovery.schema "
7776        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7777    );
7778    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7779      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7780      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7781          &zCreateTable[12]
7782      );
7783    }
7784    shellFinalize(&rc, pStmt);
7785  }
7786
7787  /* Figure out if an orphan table will be required. And if so, how many
7788  ** user columns it should contain */
7789  shellPrepare(pState->db, &rc,
7790      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7791      , &pLoop
7792  );
7793  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7794    nOrphan = sqlite3_column_int(pLoop, 0);
7795  }
7796  shellFinalize(&rc, pLoop);
7797  pLoop = 0;
7798
7799  shellPrepare(pState->db, &rc,
7800      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7801  );
7802
7803  shellPrepare(pState->db, &rc,
7804      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7805      "(case when (? AND field<0) then NULL else value end)"
7806      "), ', ')"
7807      ", min(field) "
7808      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7809      "GROUP BY cell", &pCells
7810  );
7811
7812  /* Loop through each root page. */
7813  shellPrepare(pState->db, &rc,
7814      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7815      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7816      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7817      ")", &pLoop
7818  );
7819  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7820    int iRoot = sqlite3_column_int(pLoop, 0);
7821    int bIntkey = sqlite3_column_int(pLoop, 1);
7822    int nCol = sqlite3_column_int(pLoop, 2);
7823    int bNoop = 0;
7824    RecoverTable *pTab;
7825
7826    assert( bIntkey==0 || bIntkey==1 );
7827    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7828    if( bNoop || rc ) continue;
7829    if( pTab==0 ){
7830      if( pOrphan==0 ){
7831        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7832      }
7833      pTab = pOrphan;
7834      if( pTab==0 ) break;
7835    }
7836
7837    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7838      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7839    }
7840    sqlite3_bind_int(pPages, 1, iRoot);
7841    if( bRowids==0 && pTab->iPk<0 ){
7842      sqlite3_bind_int(pCells, 1, 1);
7843    }else{
7844      sqlite3_bind_int(pCells, 1, 0);
7845    }
7846    sqlite3_bind_int(pCells, 3, pTab->iPk);
7847
7848    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7849      int iPgno = sqlite3_column_int(pPages, 0);
7850      sqlite3_bind_int(pCells, 2, iPgno);
7851      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7852        int nField = sqlite3_column_int(pCells, 0);
7853        int iMin = sqlite3_column_int(pCells, 2);
7854        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7855
7856        RecoverTable *pTab2 = pTab;
7857        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7858          if( pOrphan==0 ){
7859            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7860          }
7861          pTab2 = pOrphan;
7862          if( pTab2==0 ) break;
7863        }
7864
7865        nField = nField+1;
7866        if( pTab2==pOrphan ){
7867          raw_printf(pState->out,
7868              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7869              pTab2->zQuoted, iRoot, iPgno, nField,
7870              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7871          );
7872        }else{
7873          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7874              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7875          );
7876        }
7877      }
7878      shellReset(&rc, pCells);
7879    }
7880    shellReset(&rc, pPages);
7881    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7882  }
7883  shellFinalize(&rc, pLoop);
7884  shellFinalize(&rc, pPages);
7885  shellFinalize(&rc, pCells);
7886  recoverFreeTable(pOrphan);
7887
7888  /* The rest of the schema */
7889  if( rc==SQLITE_OK ){
7890    sqlite3_stmt *pStmt = 0;
7891    shellPrepare(pState->db, &rc,
7892        "SELECT sql, name FROM recovery.schema "
7893        "WHERE sql NOT LIKE 'create table%'", &pStmt
7894    );
7895    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7896      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7897      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7898        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7899        char *zPrint = shellMPrintf(&rc,
7900          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7901          zName, zName, zSql
7902        );
7903        raw_printf(pState->out, "%s;\n", zPrint);
7904        sqlite3_free(zPrint);
7905      }else{
7906        raw_printf(pState->out, "%s;\n", zSql);
7907      }
7908    }
7909    shellFinalize(&rc, pStmt);
7910  }
7911
7912  if( rc==SQLITE_OK ){
7913    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7914    raw_printf(pState->out, "COMMIT;\n");
7915  }
7916  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7917  return rc;
7918}
7919#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7920
7921
7922/*
7923 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7924 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7925 *   close db and set it to 0, and return the columns spec, to later
7926 *   be sqlite3_free()'ed by the caller.
7927 * The return is 0 when either:
7928 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7929 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7930 * The 3rd argument, pRenamed, references an out parameter. If the
7931 * pointer is non-zero, its referent will be set to a summary of renames
7932 * done if renaming was necessary, or set to 0 if none was done. The out
7933 * string (if any) must be sqlite3_free()'ed by the caller.
7934 */
7935#ifdef SHELL_DEBUG
7936#define rc_err_oom_die(rc) \
7937  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7938  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7939    fprintf(stderr,"E:%d\n",rc), assert(0)
7940#else
7941static void rc_err_oom_die(int rc){
7942  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7943  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7944}
7945#endif
7946
7947#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7948static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7949#else  /* Otherwise, memory is faster/better for the transient DB. */
7950static const char *zCOL_DB = ":memory:";
7951#endif
7952
7953/* Define character (as C string) to separate generated column ordinal
7954 * from protected part of incoming column names. This defaults to "_"
7955 * so that incoming column identifiers that did not need not be quoted
7956 * remain usable without being quoted. It must be one character.
7957 */
7958#ifndef SHELL_AUTOCOLUMN_SEP
7959# define AUTOCOLUMN_SEP "_"
7960#else
7961# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7962#endif
7963
7964static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7965  /* Queries and D{D,M}L used here */
7966  static const char * const zTabMake = "\
7967CREATE TABLE ColNames(\
7968 cpos INTEGER PRIMARY KEY,\
7969 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7970CREATE VIEW RepeatedNames AS \
7971SELECT DISTINCT t.name FROM ColNames t \
7972WHERE t.name COLLATE NOCASE IN (\
7973 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7974);\
7975";
7976  static const char * const zTabFill = "\
7977INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7978 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7979";
7980  static const char * const zHasDupes = "\
7981SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7982 <count(name) FROM ColNames\
7983";
7984#ifdef SHELL_COLUMN_RENAME_CLEAN
7985  static const char * const zDedoctor = "\
7986UPDATE ColNames SET chop=iif(\
7987  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7988  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7989 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7990 0\
7991)\
7992";
7993#endif
7994  static const char * const zSetReps = "\
7995UPDATE ColNames AS t SET reps=\
7996(SELECT count(*) FROM ColNames d \
7997 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7998 COLLATE NOCASE\
7999)\
8000";
8001#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
8002  static const char * const zColDigits = "\
8003SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
8004";
8005#else
8006  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
8007  static const char * const zColDigits = "\
8008SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
8009 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
8010 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
8011";
8012#endif
8013  static const char * const zRenameRank =
8014#ifdef SHELL_COLUMN_RENAME_CLEAN
8015    "UPDATE ColNames AS t SET suff="
8016    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
8017#else /* ...RENAME_MINIMAL_ONE_PASS */
8018"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
8019"  SELECT 0 AS nlz"
8020"  UNION"
8021"  SELECT nlz+1 AS nlz FROM Lzn"
8022"  WHERE EXISTS("
8023"   SELECT 1"
8024"   FROM ColNames t, ColNames o"
8025"   WHERE"
8026"    iif(t.name IN (SELECT * FROM RepeatedNames),"
8027"     printf('%s"AUTOCOLUMN_SEP"%s',"
8028"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8029"     t.name"
8030"    )"
8031"    ="
8032"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8033"     printf('%s"AUTOCOLUMN_SEP"%s',"
8034"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8035"     o.name"
8036"    )"
8037"    COLLATE NOCASE"
8038"    AND o.cpos<>t.cpos"
8039"   GROUP BY t.cpos"
8040"  )"
8041") UPDATE Colnames AS t SET"
8042" chop = 0," /* No chopping, never touch incoming names. */
8043" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8044"  printf('"AUTOCOLUMN_SEP"%s', substring("
8045"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8046"  ''"
8047" )"
8048#endif
8049    ;
8050  static const char * const zCollectVar = "\
8051SELECT\
8052 '('||x'0a'\
8053 || group_concat(\
8054  cname||' TEXT',\
8055  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8056 ||')' AS ColsSpec \
8057FROM (\
8058 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8059 FROM ColNames ORDER BY cpos\
8060)";
8061  static const char * const zRenamesDone =
8062    "SELECT group_concat("
8063    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8064    " ','||x'0a')"
8065    "FROM ColNames WHERE suff<>'' OR chop!=0"
8066    ;
8067  int rc;
8068  sqlite3_stmt *pStmt = 0;
8069  assert(pDb!=0);
8070  if( zColNew ){
8071    /* Add initial or additional column. Init db if necessary. */
8072    if( *pDb==0 ){
8073      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8074#ifdef SHELL_COLFIX_DB
8075      if(*zCOL_DB!=':')
8076        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8077                     "drop view if exists RepeatedNames;",0,0,0);
8078#endif
8079      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8080      rc_err_oom_die(rc);
8081    }
8082    assert(*pDb!=0);
8083    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8084    rc_err_oom_die(rc);
8085    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8086    rc_err_oom_die(rc);
8087    rc = sqlite3_step(pStmt);
8088    rc_err_oom_die(rc);
8089    sqlite3_finalize(pStmt);
8090    return 0;
8091  }else if( *pDb==0 ){
8092    return 0;
8093  }else{
8094    /* Formulate the columns spec, close the DB, zero *pDb. */
8095    char *zColsSpec = 0;
8096    int hasDupes = db_int(*pDb, zHasDupes);
8097    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8098    if( hasDupes ){
8099#ifdef SHELL_COLUMN_RENAME_CLEAN
8100      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8101      rc_err_oom_die(rc);
8102#endif
8103      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8104      rc_err_oom_die(rc);
8105      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8106      rc_err_oom_die(rc);
8107      sqlite3_bind_int(pStmt, 1, nDigits);
8108      rc = sqlite3_step(pStmt);
8109      sqlite3_finalize(pStmt);
8110      assert(rc==SQLITE_DONE);
8111    }
8112    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8113    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8114    rc_err_oom_die(rc);
8115    rc = sqlite3_step(pStmt);
8116    if( rc==SQLITE_ROW ){
8117      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8118    }else{
8119      zColsSpec = 0;
8120    }
8121    if( pzRenamed!=0 ){
8122      if( !hasDupes ) *pzRenamed = 0;
8123      else{
8124        sqlite3_finalize(pStmt);
8125        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8126            && SQLITE_ROW==sqlite3_step(pStmt) ){
8127          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8128        }else
8129          *pzRenamed = 0;
8130      }
8131    }
8132    sqlite3_finalize(pStmt);
8133    sqlite3_close(*pDb);
8134    *pDb = 0;
8135    return zColsSpec;
8136  }
8137}
8138
8139/*
8140** If an input line begins with "." then invoke this routine to
8141** process that line.
8142**
8143** Return 1 on error, 2 to exit, and 0 otherwise.
8144*/
8145static int do_meta_command(char *zLine, ShellState *p){
8146  int h = 1;
8147  int nArg = 0;
8148  int n, c;
8149  int rc = 0;
8150  char *azArg[52];
8151
8152#ifndef SQLITE_OMIT_VIRTUALTABLE
8153  if( p->expert.pExpert ){
8154    expertFinish(p, 1, 0);
8155  }
8156#endif
8157
8158  /* Parse the input line into tokens.
8159  */
8160  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8161    while( IsSpace(zLine[h]) ){ h++; }
8162    if( zLine[h]==0 ) break;
8163    if( zLine[h]=='\'' || zLine[h]=='"' ){
8164      int delim = zLine[h++];
8165      azArg[nArg++] = &zLine[h];
8166      while( zLine[h] && zLine[h]!=delim ){
8167        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8168        h++;
8169      }
8170      if( zLine[h]==delim ){
8171        zLine[h++] = 0;
8172      }
8173      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8174    }else{
8175      azArg[nArg++] = &zLine[h];
8176      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8177      if( zLine[h] ) zLine[h++] = 0;
8178      resolve_backslashes(azArg[nArg-1]);
8179    }
8180  }
8181  azArg[nArg] = 0;
8182
8183  /* Process the input line.
8184  */
8185  if( nArg==0 ) return 0; /* no tokens, no error */
8186  n = strlen30(azArg[0]);
8187  c = azArg[0][0];
8188  clearTempFile(p);
8189
8190#ifndef SQLITE_OMIT_AUTHORIZATION
8191  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8192    if( nArg!=2 ){
8193      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8194      rc = 1;
8195      goto meta_command_exit;
8196    }
8197    open_db(p, 0);
8198    if( booleanValue(azArg[1]) ){
8199      sqlite3_set_authorizer(p->db, shellAuth, p);
8200    }else if( p->bSafeModePersist ){
8201      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8202    }else{
8203      sqlite3_set_authorizer(p->db, 0, 0);
8204    }
8205  }else
8206#endif
8207
8208#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8209  && !defined(SQLITE_SHELL_FIDDLE)
8210  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8211    open_db(p, 0);
8212    failIfSafeMode(p, "cannot run .archive in safe mode");
8213    rc = arDotCommand(p, 0, azArg, nArg);
8214  }else
8215#endif
8216
8217#ifndef SQLITE_SHELL_FIDDLE
8218  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8219   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8220  ){
8221    const char *zDestFile = 0;
8222    const char *zDb = 0;
8223    sqlite3 *pDest;
8224    sqlite3_backup *pBackup;
8225    int j;
8226    int bAsync = 0;
8227    const char *zVfs = 0;
8228    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8229    for(j=1; j<nArg; j++){
8230      const char *z = azArg[j];
8231      if( z[0]=='-' ){
8232        if( z[1]=='-' ) z++;
8233        if( strcmp(z, "-append")==0 ){
8234          zVfs = "apndvfs";
8235        }else
8236        if( strcmp(z, "-async")==0 ){
8237          bAsync = 1;
8238        }else
8239        {
8240          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8241          return 1;
8242        }
8243      }else if( zDestFile==0 ){
8244        zDestFile = azArg[j];
8245      }else if( zDb==0 ){
8246        zDb = zDestFile;
8247        zDestFile = azArg[j];
8248      }else{
8249        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8250        return 1;
8251      }
8252    }
8253    if( zDestFile==0 ){
8254      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8255      return 1;
8256    }
8257    if( zDb==0 ) zDb = "main";
8258    rc = sqlite3_open_v2(zDestFile, &pDest,
8259                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8260    if( rc!=SQLITE_OK ){
8261      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8262      close_db(pDest);
8263      return 1;
8264    }
8265    if( bAsync ){
8266      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8267                   0, 0, 0);
8268    }
8269    open_db(p, 0);
8270    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8271    if( pBackup==0 ){
8272      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8273      close_db(pDest);
8274      return 1;
8275    }
8276    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8277    sqlite3_backup_finish(pBackup);
8278    if( rc==SQLITE_DONE ){
8279      rc = 0;
8280    }else{
8281      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8282      rc = 1;
8283    }
8284    close_db(pDest);
8285  }else
8286#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8287
8288  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8289    if( nArg==2 ){
8290      bail_on_error = booleanValue(azArg[1]);
8291    }else{
8292      raw_printf(stderr, "Usage: .bail on|off\n");
8293      rc = 1;
8294    }
8295  }else
8296
8297  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8298    if( nArg==2 ){
8299      if( booleanValue(azArg[1]) ){
8300        setBinaryMode(p->out, 1);
8301      }else{
8302        setTextMode(p->out, 1);
8303      }
8304    }else{
8305      raw_printf(stderr, "Usage: .binary on|off\n");
8306      rc = 1;
8307    }
8308  }else
8309
8310  /* The undocumented ".breakpoint" command causes a call to the no-op
8311  ** routine named test_breakpoint().
8312  */
8313  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8314    test_breakpoint();
8315  }else
8316
8317#ifndef SQLITE_SHELL_FIDDLE
8318  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8319    failIfSafeMode(p, "cannot run .cd in safe mode");
8320    if( nArg==2 ){
8321#if defined(_WIN32) || defined(WIN32)
8322      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8323      rc = !SetCurrentDirectoryW(z);
8324      sqlite3_free(z);
8325#else
8326      rc = chdir(azArg[1]);
8327#endif
8328      if( rc ){
8329        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8330        rc = 1;
8331      }
8332    }else{
8333      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8334      rc = 1;
8335    }
8336  }else
8337#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8338
8339  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8340    if( nArg==2 ){
8341      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8342    }else{
8343      raw_printf(stderr, "Usage: .changes on|off\n");
8344      rc = 1;
8345    }
8346  }else
8347
8348#ifndef SQLITE_SHELL_FIDDLE
8349  /* Cancel output redirection, if it is currently set (by .testcase)
8350  ** Then read the content of the testcase-out.txt file and compare against
8351  ** azArg[1].  If there are differences, report an error and exit.
8352  */
8353  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8354    char *zRes = 0;
8355    output_reset(p);
8356    if( nArg!=2 ){
8357      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8358      rc = 2;
8359    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8360      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8361      rc = 2;
8362    }else if( testcase_glob(azArg[1],zRes)==0 ){
8363      utf8_printf(stderr,
8364                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8365                 p->zTestcase, azArg[1], zRes);
8366      rc = 1;
8367    }else{
8368      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8369      p->nCheck++;
8370    }
8371    sqlite3_free(zRes);
8372  }else
8373#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8374
8375#ifndef SQLITE_SHELL_FIDDLE
8376  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8377    failIfSafeMode(p, "cannot run .clone in safe mode");
8378    if( nArg==2 ){
8379      tryToClone(p, azArg[1]);
8380    }else{
8381      raw_printf(stderr, "Usage: .clone FILENAME\n");
8382      rc = 1;
8383    }
8384  }else
8385#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8386
8387  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8388    if( nArg==1 ){
8389      /* List available connections */
8390      int i;
8391      for(i=0; i<ArraySize(p->aAuxDb); i++){
8392        const char *zFile = p->aAuxDb[i].zDbFilename;
8393        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8394          zFile = "(not open)";
8395        }else if( zFile==0 ){
8396          zFile = "(memory)";
8397        }else if( zFile[0]==0 ){
8398          zFile = "(temporary-file)";
8399        }
8400        if( p->pAuxDb == &p->aAuxDb[i] ){
8401          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8402        }else if( p->aAuxDb[i].db!=0 ){
8403          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8404        }
8405      }
8406    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8407      int i = azArg[1][0] - '0';
8408      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8409        p->pAuxDb->db = p->db;
8410        p->pAuxDb = &p->aAuxDb[i];
8411        globalDb = p->db = p->pAuxDb->db;
8412        p->pAuxDb->db = 0;
8413      }
8414    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8415           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8416      int i = azArg[2][0] - '0';
8417      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8418        /* No-op */
8419      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8420        raw_printf(stderr, "cannot close the active database connection\n");
8421        rc = 1;
8422      }else if( p->aAuxDb[i].db ){
8423        session_close_all(p, i);
8424        close_db(p->aAuxDb[i].db);
8425        p->aAuxDb[i].db = 0;
8426      }
8427    }else{
8428      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8429      rc = 1;
8430    }
8431  }else
8432
8433  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8434    char **azName = 0;
8435    int nName = 0;
8436    sqlite3_stmt *pStmt;
8437    int i;
8438    open_db(p, 0);
8439    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8440    if( rc ){
8441      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8442      rc = 1;
8443    }else{
8444      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8445        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8446        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8447        if( zSchema==0 || zFile==0 ) continue;
8448        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8449        shell_check_oom(azName);
8450        azName[nName*2] = strdup(zSchema);
8451        azName[nName*2+1] = strdup(zFile);
8452        nName++;
8453      }
8454    }
8455    sqlite3_finalize(pStmt);
8456    for(i=0; i<nName; i++){
8457      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8458      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8459      const char *z = azName[i*2+1];
8460      utf8_printf(p->out, "%s: %s %s%s\n",
8461         azName[i*2],
8462         z && z[0] ? z : "\"\"",
8463         bRdonly ? "r/o" : "r/w",
8464         eTxn==SQLITE_TXN_NONE ? "" :
8465            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8466      free(azName[i*2]);
8467      free(azName[i*2+1]);
8468    }
8469    sqlite3_free(azName);
8470  }else
8471
8472  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8473    static const struct DbConfigChoices {
8474      const char *zName;
8475      int op;
8476    } aDbConfig[] = {
8477        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8478        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8479        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8480        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8481        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8482        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8483        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8484        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8485        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8486        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8487        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8488        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8489        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8490        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8491        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8492        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8493    };
8494    int ii, v;
8495    open_db(p, 0);
8496    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8497      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8498      if( nArg>=3 ){
8499        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8500      }
8501      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8502      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8503      if( nArg>1 ) break;
8504    }
8505    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8506      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8507      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8508    }
8509  }else
8510
8511#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8512  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8513    rc = shell_dbinfo_command(p, nArg, azArg);
8514  }else
8515
8516  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8517    open_db(p, 0);
8518    rc = recoverDatabaseCmd(p, nArg, azArg);
8519  }else
8520#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8521
8522  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8523    char *zLike = 0;
8524    char *zSql;
8525    int i;
8526    int savedShowHeader = p->showHeader;
8527    int savedShellFlags = p->shellFlgs;
8528    ShellClearFlag(p,
8529       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8530       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8531    for(i=1; i<nArg; i++){
8532      if( azArg[i][0]=='-' ){
8533        const char *z = azArg[i]+1;
8534        if( z[0]=='-' ) z++;
8535        if( strcmp(z,"preserve-rowids")==0 ){
8536#ifdef SQLITE_OMIT_VIRTUALTABLE
8537          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8538                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8539          rc = 1;
8540          sqlite3_free(zLike);
8541          goto meta_command_exit;
8542#else
8543          ShellSetFlag(p, SHFLG_PreserveRowid);
8544#endif
8545        }else
8546        if( strcmp(z,"newlines")==0 ){
8547          ShellSetFlag(p, SHFLG_Newlines);
8548        }else
8549        if( strcmp(z,"data-only")==0 ){
8550          ShellSetFlag(p, SHFLG_DumpDataOnly);
8551        }else
8552        if( strcmp(z,"nosys")==0 ){
8553          ShellSetFlag(p, SHFLG_DumpNoSys);
8554        }else
8555        {
8556          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8557          rc = 1;
8558          sqlite3_free(zLike);
8559          goto meta_command_exit;
8560        }
8561      }else{
8562        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8563        ** only dump data for tables for which either the table name matches
8564        ** the LIKE pattern, or the table appears to be a shadow table of
8565        ** a virtual table for which the name matches the LIKE pattern.
8566        */
8567        char *zExpr = sqlite3_mprintf(
8568            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8569            "  SELECT 1 FROM sqlite_schema WHERE "
8570            "    name LIKE %Q ESCAPE '\\' AND"
8571            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8572            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8573            ")", azArg[i], azArg[i]
8574        );
8575
8576        if( zLike ){
8577          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8578        }else{
8579          zLike = zExpr;
8580        }
8581      }
8582    }
8583
8584    open_db(p, 0);
8585
8586    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8587      /* When playing back a "dump", the content might appear in an order
8588      ** which causes immediate foreign key constraints to be violated.
8589      ** So disable foreign-key constraint enforcement to prevent problems. */
8590      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8591      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8592    }
8593    p->writableSchema = 0;
8594    p->showHeader = 0;
8595    /* Set writable_schema=ON since doing so forces SQLite to initialize
8596    ** as much of the schema as it can even if the sqlite_schema table is
8597    ** corrupt. */
8598    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8599    p->nErr = 0;
8600    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8601    zSql = sqlite3_mprintf(
8602      "SELECT name, type, sql FROM sqlite_schema AS o "
8603      "WHERE (%s) AND type=='table'"
8604      "  AND sql NOT NULL"
8605      " ORDER BY tbl_name='sqlite_sequence', rowid",
8606      zLike
8607    );
8608    run_schema_dump_query(p,zSql);
8609    sqlite3_free(zSql);
8610    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8611      zSql = sqlite3_mprintf(
8612        "SELECT sql FROM sqlite_schema AS o "
8613        "WHERE (%s) AND sql NOT NULL"
8614        "  AND type IN ('index','trigger','view')",
8615        zLike
8616      );
8617      run_table_dump_query(p, zSql);
8618      sqlite3_free(zSql);
8619    }
8620    sqlite3_free(zLike);
8621    if( p->writableSchema ){
8622      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8623      p->writableSchema = 0;
8624    }
8625    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8626    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8627    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8628      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8629    }
8630    p->showHeader = savedShowHeader;
8631    p->shellFlgs = savedShellFlags;
8632  }else
8633
8634  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8635    if( nArg==2 ){
8636      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8637    }else{
8638      raw_printf(stderr, "Usage: .echo on|off\n");
8639      rc = 1;
8640    }
8641  }else
8642
8643  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8644    if( nArg==2 ){
8645      p->autoEQPtest = 0;
8646      if( p->autoEQPtrace ){
8647        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8648        p->autoEQPtrace = 0;
8649      }
8650      if( strcmp(azArg[1],"full")==0 ){
8651        p->autoEQP = AUTOEQP_full;
8652      }else if( strcmp(azArg[1],"trigger")==0 ){
8653        p->autoEQP = AUTOEQP_trigger;
8654#ifdef SQLITE_DEBUG
8655      }else if( strcmp(azArg[1],"test")==0 ){
8656        p->autoEQP = AUTOEQP_on;
8657        p->autoEQPtest = 1;
8658      }else if( strcmp(azArg[1],"trace")==0 ){
8659        p->autoEQP = AUTOEQP_full;
8660        p->autoEQPtrace = 1;
8661        open_db(p, 0);
8662        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8663        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8664#endif
8665      }else{
8666        p->autoEQP = (u8)booleanValue(azArg[1]);
8667      }
8668    }else{
8669      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8670      rc = 1;
8671    }
8672  }else
8673
8674#ifndef SQLITE_SHELL_FIDDLE
8675  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8676    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8677    rc = 2;
8678  }else
8679#endif
8680
8681  /* The ".explain" command is automatic now.  It is largely pointless.  It
8682  ** retained purely for backwards compatibility */
8683  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8684    int val = 1;
8685    if( nArg>=2 ){
8686      if( strcmp(azArg[1],"auto")==0 ){
8687        val = 99;
8688      }else{
8689        val =  booleanValue(azArg[1]);
8690      }
8691    }
8692    if( val==1 && p->mode!=MODE_Explain ){
8693      p->normalMode = p->mode;
8694      p->mode = MODE_Explain;
8695      p->autoExplain = 0;
8696    }else if( val==0 ){
8697      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8698      p->autoExplain = 0;
8699    }else if( val==99 ){
8700      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8701      p->autoExplain = 1;
8702    }
8703  }else
8704
8705#ifndef SQLITE_OMIT_VIRTUALTABLE
8706  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8707    if( p->bSafeMode ){
8708      raw_printf(stderr,
8709        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8710        azArg[0]);
8711      rc = 1;
8712    }else{
8713      open_db(p, 0);
8714      expertDotCommand(p, azArg, nArg);
8715    }
8716  }else
8717#endif
8718
8719  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8720    static const struct {
8721       const char *zCtrlName;   /* Name of a test-control option */
8722       int ctrlCode;            /* Integer code for that option */
8723       const char *zUsage;      /* Usage notes */
8724    } aCtrl[] = {
8725      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8726      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8727      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8728      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8729      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8730   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8731      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8732      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8733      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8734      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8735   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8736    };
8737    int filectrl = -1;
8738    int iCtrl = -1;
8739    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8740    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8741    int n2, i;
8742    const char *zCmd = 0;
8743    const char *zSchema = 0;
8744
8745    open_db(p, 0);
8746    zCmd = nArg>=2 ? azArg[1] : "help";
8747
8748    if( zCmd[0]=='-'
8749     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8750     && nArg>=4
8751    ){
8752      zSchema = azArg[2];
8753      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8754      nArg -= 2;
8755      zCmd = azArg[1];
8756    }
8757
8758    /* The argument can optionally begin with "-" or "--" */
8759    if( zCmd[0]=='-' && zCmd[1] ){
8760      zCmd++;
8761      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8762    }
8763
8764    /* --help lists all file-controls */
8765    if( strcmp(zCmd,"help")==0 ){
8766      utf8_printf(p->out, "Available file-controls:\n");
8767      for(i=0; i<ArraySize(aCtrl); i++){
8768        utf8_printf(p->out, "  .filectrl %s %s\n",
8769                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8770      }
8771      rc = 1;
8772      goto meta_command_exit;
8773    }
8774
8775    /* convert filectrl text option to value. allow any unique prefix
8776    ** of the option name, or a numerical value. */
8777    n2 = strlen30(zCmd);
8778    for(i=0; i<ArraySize(aCtrl); i++){
8779      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8780        if( filectrl<0 ){
8781          filectrl = aCtrl[i].ctrlCode;
8782          iCtrl = i;
8783        }else{
8784          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8785                              "Use \".filectrl --help\" for help\n", zCmd);
8786          rc = 1;
8787          goto meta_command_exit;
8788        }
8789      }
8790    }
8791    if( filectrl<0 ){
8792      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8793                         "Use \".filectrl --help\" for help\n", zCmd);
8794    }else{
8795      switch(filectrl){
8796        case SQLITE_FCNTL_SIZE_LIMIT: {
8797          if( nArg!=2 && nArg!=3 ) break;
8798          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8799          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8800          isOk = 1;
8801          break;
8802        }
8803        case SQLITE_FCNTL_LOCK_TIMEOUT:
8804        case SQLITE_FCNTL_CHUNK_SIZE: {
8805          int x;
8806          if( nArg!=3 ) break;
8807          x = (int)integerValue(azArg[2]);
8808          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8809          isOk = 2;
8810          break;
8811        }
8812        case SQLITE_FCNTL_PERSIST_WAL:
8813        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8814          int x;
8815          if( nArg!=2 && nArg!=3 ) break;
8816          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8817          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8818          iRes = x;
8819          isOk = 1;
8820          break;
8821        }
8822        case SQLITE_FCNTL_DATA_VERSION:
8823        case SQLITE_FCNTL_HAS_MOVED: {
8824          int x;
8825          if( nArg!=2 ) break;
8826          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8827          iRes = x;
8828          isOk = 1;
8829          break;
8830        }
8831        case SQLITE_FCNTL_TEMPFILENAME: {
8832          char *z = 0;
8833          if( nArg!=2 ) break;
8834          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8835          if( z ){
8836            utf8_printf(p->out, "%s\n", z);
8837            sqlite3_free(z);
8838          }
8839          isOk = 2;
8840          break;
8841        }
8842        case SQLITE_FCNTL_RESERVE_BYTES: {
8843          int x;
8844          if( nArg>=3 ){
8845            x = atoi(azArg[2]);
8846            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8847          }
8848          x = -1;
8849          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8850          utf8_printf(p->out,"%d\n", x);
8851          isOk = 2;
8852          break;
8853        }
8854      }
8855    }
8856    if( isOk==0 && iCtrl>=0 ){
8857      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8858      rc = 1;
8859    }else if( isOk==1 ){
8860      char zBuf[100];
8861      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8862      raw_printf(p->out, "%s\n", zBuf);
8863    }
8864  }else
8865
8866  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8867    ShellState data;
8868    int doStats = 0;
8869    memcpy(&data, p, sizeof(data));
8870    data.showHeader = 0;
8871    data.cMode = data.mode = MODE_Semi;
8872    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8873      data.cMode = data.mode = MODE_Pretty;
8874      nArg = 1;
8875    }
8876    if( nArg!=1 ){
8877      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8878      rc = 1;
8879      goto meta_command_exit;
8880    }
8881    open_db(p, 0);
8882    rc = sqlite3_exec(p->db,
8883       "SELECT sql FROM"
8884       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8885       "     FROM sqlite_schema UNION ALL"
8886       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8887       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8888       "ORDER BY x",
8889       callback, &data, 0
8890    );
8891    if( rc==SQLITE_OK ){
8892      sqlite3_stmt *pStmt;
8893      rc = sqlite3_prepare_v2(p->db,
8894               "SELECT rowid FROM sqlite_schema"
8895               " WHERE name GLOB 'sqlite_stat[134]'",
8896               -1, &pStmt, 0);
8897      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8898      sqlite3_finalize(pStmt);
8899    }
8900    if( doStats==0 ){
8901      raw_printf(p->out, "/* No STAT tables available */\n");
8902    }else{
8903      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8904      data.cMode = data.mode = MODE_Insert;
8905      data.zDestTable = "sqlite_stat1";
8906      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8907      data.zDestTable = "sqlite_stat4";
8908      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8909      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8910    }
8911  }else
8912
8913  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8914    if( nArg==2 ){
8915      p->showHeader = booleanValue(azArg[1]);
8916      p->shellFlgs |= SHFLG_HeaderSet;
8917    }else{
8918      raw_printf(stderr, "Usage: .headers on|off\n");
8919      rc = 1;
8920    }
8921  }else
8922
8923  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8924    if( nArg>=2 ){
8925      n = showHelp(p->out, azArg[1]);
8926      if( n==0 ){
8927        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8928      }
8929    }else{
8930      showHelp(p->out, 0);
8931    }
8932  }else
8933
8934#ifndef SQLITE_SHELL_FIDDLE
8935  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8936    char *zTable = 0;           /* Insert data into this table */
8937    char *zSchema = 0;          /* within this schema (may default to "main") */
8938    char *zFile = 0;            /* Name of file to extra content from */
8939    sqlite3_stmt *pStmt = NULL; /* A statement */
8940    int nCol;                   /* Number of columns in the table */
8941    int nByte;                  /* Number of bytes in an SQL string */
8942    int i, j;                   /* Loop counters */
8943    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8944    int nSep;                   /* Number of bytes in p->colSeparator[] */
8945    char *zSql;                 /* An SQL statement */
8946    char *zFullTabName;         /* Table name with schema if applicable */
8947    ImportCtx sCtx;             /* Reader context */
8948    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8949    int eVerbose = 0;           /* Larger for more console output */
8950    int nSkip = 0;              /* Initial lines to skip */
8951    int useOutputMode = 1;      /* Use output mode to determine separators */
8952    char *zCreate = 0;          /* CREATE TABLE statement text */
8953
8954    failIfSafeMode(p, "cannot run .import in safe mode");
8955    memset(&sCtx, 0, sizeof(sCtx));
8956    if( p->mode==MODE_Ascii ){
8957      xRead = ascii_read_one_field;
8958    }else{
8959      xRead = csv_read_one_field;
8960    }
8961    rc = 1;
8962    for(i=1; i<nArg; i++){
8963      char *z = azArg[i];
8964      if( z[0]=='-' && z[1]=='-' ) z++;
8965      if( z[0]!='-' ){
8966        if( zFile==0 ){
8967          zFile = z;
8968        }else if( zTable==0 ){
8969          zTable = z;
8970        }else{
8971          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8972          showHelp(p->out, "import");
8973          goto meta_command_exit;
8974        }
8975      }else if( strcmp(z,"-v")==0 ){
8976        eVerbose++;
8977      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8978        zSchema = azArg[++i];
8979      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8980        nSkip = integerValue(azArg[++i]);
8981      }else if( strcmp(z,"-ascii")==0 ){
8982        sCtx.cColSep = SEP_Unit[0];
8983        sCtx.cRowSep = SEP_Record[0];
8984        xRead = ascii_read_one_field;
8985        useOutputMode = 0;
8986      }else if( strcmp(z,"-csv")==0 ){
8987        sCtx.cColSep = ',';
8988        sCtx.cRowSep = '\n';
8989        xRead = csv_read_one_field;
8990        useOutputMode = 0;
8991      }else{
8992        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8993        showHelp(p->out, "import");
8994        goto meta_command_exit;
8995      }
8996    }
8997    if( zTable==0 ){
8998      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8999                  zFile==0 ? "FILE" : "TABLE");
9000      showHelp(p->out, "import");
9001      goto meta_command_exit;
9002    }
9003    seenInterrupt = 0;
9004    open_db(p, 0);
9005    if( useOutputMode ){
9006      /* If neither the --csv or --ascii options are specified, then set
9007      ** the column and row separator characters from the output mode. */
9008      nSep = strlen30(p->colSeparator);
9009      if( nSep==0 ){
9010        raw_printf(stderr,
9011                   "Error: non-null column separator required for import\n");
9012        goto meta_command_exit;
9013      }
9014      if( nSep>1 ){
9015        raw_printf(stderr,
9016              "Error: multi-character column separators not allowed"
9017              " for import\n");
9018        goto meta_command_exit;
9019      }
9020      nSep = strlen30(p->rowSeparator);
9021      if( nSep==0 ){
9022        raw_printf(stderr,
9023            "Error: non-null row separator required for import\n");
9024        goto meta_command_exit;
9025      }
9026      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9027        /* When importing CSV (only), if the row separator is set to the
9028        ** default output row separator, change it to the default input
9029        ** row separator.  This avoids having to maintain different input
9030        ** and output row separators. */
9031        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9032        nSep = strlen30(p->rowSeparator);
9033      }
9034      if( nSep>1 ){
9035        raw_printf(stderr, "Error: multi-character row separators not allowed"
9036                           " for import\n");
9037        goto meta_command_exit;
9038      }
9039      sCtx.cColSep = p->colSeparator[0];
9040      sCtx.cRowSep = p->rowSeparator[0];
9041    }
9042    sCtx.zFile = zFile;
9043    sCtx.nLine = 1;
9044    if( sCtx.zFile[0]=='|' ){
9045#ifdef SQLITE_OMIT_POPEN
9046      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9047      goto meta_command_exit;
9048#else
9049      sCtx.in = popen(sCtx.zFile+1, "r");
9050      sCtx.zFile = "<pipe>";
9051      sCtx.xCloser = pclose;
9052#endif
9053    }else{
9054      sCtx.in = fopen(sCtx.zFile, "rb");
9055      sCtx.xCloser = fclose;
9056    }
9057    if( sCtx.in==0 ){
9058      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9059      goto meta_command_exit;
9060    }
9061    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9062      char zSep[2];
9063      zSep[1] = 0;
9064      zSep[0] = sCtx.cColSep;
9065      utf8_printf(p->out, "Column separator ");
9066      output_c_string(p->out, zSep);
9067      utf8_printf(p->out, ", row separator ");
9068      zSep[0] = sCtx.cRowSep;
9069      output_c_string(p->out, zSep);
9070      utf8_printf(p->out, "\n");
9071    }
9072    sCtx.z = sqlite3_malloc64(120);
9073    if( sCtx.z==0 ){
9074      import_cleanup(&sCtx);
9075      shell_out_of_memory();
9076    }
9077    /* Below, resources must be freed before exit. */
9078    while( (nSkip--)>0 ){
9079      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9080    }
9081    if( zSchema!=0 ){
9082      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9083    }else{
9084      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9085    }
9086    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9087    if( zSql==0 || zFullTabName==0 ){
9088      import_cleanup(&sCtx);
9089      shell_out_of_memory();
9090    }
9091    nByte = strlen30(zSql);
9092    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9093    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9094    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9095      sqlite3 *dbCols = 0;
9096      char *zRenames = 0;
9097      char *zColDefs;
9098      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9099      while( xRead(&sCtx) ){
9100        zAutoColumn(sCtx.z, &dbCols, 0);
9101        if( sCtx.cTerm!=sCtx.cColSep ) break;
9102      }
9103      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9104      if( zRenames!=0 ){
9105        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9106                    "Columns renamed during .import %s due to duplicates:\n"
9107                    "%s\n", sCtx.zFile, zRenames);
9108        sqlite3_free(zRenames);
9109      }
9110      assert(dbCols==0);
9111      if( zColDefs==0 ){
9112        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9113      import_fail:
9114        sqlite3_free(zCreate);
9115        sqlite3_free(zSql);
9116        sqlite3_free(zFullTabName);
9117        import_cleanup(&sCtx);
9118        rc = 1;
9119        goto meta_command_exit;
9120      }
9121      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9122      if( eVerbose>=1 ){
9123        utf8_printf(p->out, "%s\n", zCreate);
9124      }
9125      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9126      if( rc ){
9127        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9128        goto import_fail;
9129      }
9130      sqlite3_free(zCreate);
9131      zCreate = 0;
9132      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9133    }
9134    if( rc ){
9135      if (pStmt) sqlite3_finalize(pStmt);
9136      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9137      goto import_fail;
9138    }
9139    sqlite3_free(zSql);
9140    nCol = sqlite3_column_count(pStmt);
9141    sqlite3_finalize(pStmt);
9142    pStmt = 0;
9143    if( nCol==0 ) return 0; /* no columns, no error */
9144    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9145    if( zSql==0 ){
9146      import_cleanup(&sCtx);
9147      shell_out_of_memory();
9148    }
9149    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9150    j = strlen30(zSql);
9151    for(i=1; i<nCol; i++){
9152      zSql[j++] = ',';
9153      zSql[j++] = '?';
9154    }
9155    zSql[j++] = ')';
9156    zSql[j] = 0;
9157    if( eVerbose>=2 ){
9158      utf8_printf(p->out, "Insert using: %s\n", zSql);
9159    }
9160    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9161    if( rc ){
9162      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9163      if (pStmt) sqlite3_finalize(pStmt);
9164      goto import_fail;
9165    }
9166    sqlite3_free(zSql);
9167    sqlite3_free(zFullTabName);
9168    needCommit = sqlite3_get_autocommit(p->db);
9169    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9170    do{
9171      int startLine = sCtx.nLine;
9172      for(i=0; i<nCol; i++){
9173        char *z = xRead(&sCtx);
9174        /*
9175        ** Did we reach end-of-file before finding any columns?
9176        ** If so, stop instead of NULL filling the remaining columns.
9177        */
9178        if( z==0 && i==0 ) break;
9179        /*
9180        ** Did we reach end-of-file OR end-of-line before finding any
9181        ** columns in ASCII mode?  If so, stop instead of NULL filling
9182        ** the remaining columns.
9183        */
9184        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9185        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9186        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9187          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9188                          "filling the rest with NULL\n",
9189                          sCtx.zFile, startLine, nCol, i+1);
9190          i += 2;
9191          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9192        }
9193      }
9194      if( sCtx.cTerm==sCtx.cColSep ){
9195        do{
9196          xRead(&sCtx);
9197          i++;
9198        }while( sCtx.cTerm==sCtx.cColSep );
9199        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9200                        "extras ignored\n",
9201                        sCtx.zFile, startLine, nCol, i);
9202      }
9203      if( i>=nCol ){
9204        sqlite3_step(pStmt);
9205        rc = sqlite3_reset(pStmt);
9206        if( rc!=SQLITE_OK ){
9207          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9208                      startLine, sqlite3_errmsg(p->db));
9209          sCtx.nErr++;
9210        }else{
9211          sCtx.nRow++;
9212        }
9213      }
9214    }while( sCtx.cTerm!=EOF );
9215
9216    import_cleanup(&sCtx);
9217    sqlite3_finalize(pStmt);
9218    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9219    if( eVerbose>0 ){
9220      utf8_printf(p->out,
9221          "Added %d rows with %d errors using %d lines of input\n",
9222          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9223    }
9224  }else
9225#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9226
9227#ifndef SQLITE_UNTESTABLE
9228  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9229    char *zSql;
9230    char *zCollist = 0;
9231    sqlite3_stmt *pStmt;
9232    int tnum = 0;
9233    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9234    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9235    int i;
9236    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9237      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9238                          "       .imposter off\n");
9239      /* Also allowed, but not documented:
9240      **
9241      **    .imposter TABLE IMPOSTER
9242      **
9243      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9244      ** imposter is another WITHOUT ROWID table with the columns in
9245      ** storage order. */
9246      rc = 1;
9247      goto meta_command_exit;
9248    }
9249    open_db(p, 0);
9250    if( nArg==2 ){
9251      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9252      goto meta_command_exit;
9253    }
9254    zSql = sqlite3_mprintf(
9255      "SELECT rootpage, 0 FROM sqlite_schema"
9256      " WHERE name='%q' AND type='index'"
9257      "UNION ALL "
9258      "SELECT rootpage, 1 FROM sqlite_schema"
9259      " WHERE name='%q' AND type='table'"
9260      "   AND sql LIKE '%%without%%rowid%%'",
9261      azArg[1], azArg[1]
9262    );
9263    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9264    sqlite3_free(zSql);
9265    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9266      tnum = sqlite3_column_int(pStmt, 0);
9267      isWO = sqlite3_column_int(pStmt, 1);
9268    }
9269    sqlite3_finalize(pStmt);
9270    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9271    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9272    sqlite3_free(zSql);
9273    i = 0;
9274    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9275      char zLabel[20];
9276      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9277      i++;
9278      if( zCol==0 ){
9279        if( sqlite3_column_int(pStmt,1)==-1 ){
9280          zCol = "_ROWID_";
9281        }else{
9282          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9283          zCol = zLabel;
9284        }
9285      }
9286      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9287        lenPK = (int)strlen(zCollist);
9288      }
9289      if( zCollist==0 ){
9290        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9291      }else{
9292        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9293      }
9294    }
9295    sqlite3_finalize(pStmt);
9296    if( i==0 || tnum==0 ){
9297      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9298      rc = 1;
9299      sqlite3_free(zCollist);
9300      goto meta_command_exit;
9301    }
9302    if( lenPK==0 ) lenPK = 100000;
9303    zSql = sqlite3_mprintf(
9304          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9305          azArg[2], zCollist, lenPK, zCollist);
9306    sqlite3_free(zCollist);
9307    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9308    if( rc==SQLITE_OK ){
9309      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9310      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9311      if( rc ){
9312        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9313      }else{
9314        utf8_printf(stdout, "%s;\n", zSql);
9315        raw_printf(stdout,
9316          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9317          azArg[1], isWO ? "table" : "index"
9318        );
9319      }
9320    }else{
9321      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9322      rc = 1;
9323    }
9324    sqlite3_free(zSql);
9325  }else
9326#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9327
9328#ifdef SQLITE_ENABLE_IOTRACE
9329  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9330    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9331    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9332    iotrace = 0;
9333    if( nArg<2 ){
9334      sqlite3IoTrace = 0;
9335    }else if( strcmp(azArg[1], "-")==0 ){
9336      sqlite3IoTrace = iotracePrintf;
9337      iotrace = stdout;
9338    }else{
9339      iotrace = fopen(azArg[1], "w");
9340      if( iotrace==0 ){
9341        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9342        sqlite3IoTrace = 0;
9343        rc = 1;
9344      }else{
9345        sqlite3IoTrace = iotracePrintf;
9346      }
9347    }
9348  }else
9349#endif
9350
9351  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9352    static const struct {
9353       const char *zLimitName;   /* Name of a limit */
9354       int limitCode;            /* Integer code for that limit */
9355    } aLimit[] = {
9356      { "length",                SQLITE_LIMIT_LENGTH                    },
9357      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9358      { "column",                SQLITE_LIMIT_COLUMN                    },
9359      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9360      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9361      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9362      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9363      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9364      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9365      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9366      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9367      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9368    };
9369    int i, n2;
9370    open_db(p, 0);
9371    if( nArg==1 ){
9372      for(i=0; i<ArraySize(aLimit); i++){
9373        printf("%20s %d\n", aLimit[i].zLimitName,
9374               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9375      }
9376    }else if( nArg>3 ){
9377      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9378      rc = 1;
9379      goto meta_command_exit;
9380    }else{
9381      int iLimit = -1;
9382      n2 = strlen30(azArg[1]);
9383      for(i=0; i<ArraySize(aLimit); i++){
9384        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9385          if( iLimit<0 ){
9386            iLimit = i;
9387          }else{
9388            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9389            rc = 1;
9390            goto meta_command_exit;
9391          }
9392        }
9393      }
9394      if( iLimit<0 ){
9395        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9396                        "enter \".limits\" with no arguments for a list.\n",
9397                         azArg[1]);
9398        rc = 1;
9399        goto meta_command_exit;
9400      }
9401      if( nArg==3 ){
9402        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9403                      (int)integerValue(azArg[2]));
9404      }
9405      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9406             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9407    }
9408  }else
9409
9410  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9411    open_db(p, 0);
9412    lintDotCommand(p, azArg, nArg);
9413  }else
9414
9415#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9416  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9417    const char *zFile, *zProc;
9418    char *zErrMsg = 0;
9419    failIfSafeMode(p, "cannot run .load in safe mode");
9420    if( nArg<2 ){
9421      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9422      rc = 1;
9423      goto meta_command_exit;
9424    }
9425    zFile = azArg[1];
9426    zProc = nArg>=3 ? azArg[2] : 0;
9427    open_db(p, 0);
9428    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9429    if( rc!=SQLITE_OK ){
9430      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9431      sqlite3_free(zErrMsg);
9432      rc = 1;
9433    }
9434  }else
9435#endif
9436
9437#ifndef SQLITE_SHELL_FIDDLE
9438  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9439    failIfSafeMode(p, "cannot run .log in safe mode");
9440    if( nArg!=2 ){
9441      raw_printf(stderr, "Usage: .log FILENAME\n");
9442      rc = 1;
9443    }else{
9444      const char *zFile = azArg[1];
9445      output_file_close(p->pLog);
9446      p->pLog = output_file_open(zFile, 0);
9447    }
9448  }else
9449#endif
9450
9451  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9452    const char *zMode = 0;
9453    const char *zTabname = 0;
9454    int i, n2;
9455    ColModeOpts cmOpts = ColModeOpts_default;
9456    for(i=1; i<nArg; i++){
9457      const char *z = azArg[i];
9458      if( optionMatch(z,"wrap") && i+1<nArg ){
9459        cmOpts.iWrap = integerValue(azArg[++i]);
9460      }else if( optionMatch(z,"ww") ){
9461        cmOpts.bWordWrap = 1;
9462      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9463        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9464      }else if( optionMatch(z,"quote") ){
9465        cmOpts.bQuote = 1;
9466      }else if( optionMatch(z,"noquote") ){
9467        cmOpts.bQuote = 0;
9468      }else if( zMode==0 ){
9469        zMode = z;
9470        /* Apply defaults for qbox pseudo-mods. If that
9471         * overwrites already-set values, user was informed of this.
9472         */
9473        if( strcmp(z, "qbox")==0 ){
9474          ColModeOpts cmo = ColModeOpts_default_qbox;
9475          zMode = "box";
9476          cmOpts = cmo;
9477        }
9478      }else if( zTabname==0 ){
9479        zTabname = z;
9480      }else if( z[0]=='-' ){
9481        utf8_printf(stderr, "unknown option: %s\n", z);
9482        utf8_printf(stderr, "options:\n"
9483                            "  --noquote\n"
9484                            "  --quote\n"
9485                            "  --wordwrap on/off\n"
9486                            "  --wrap N\n"
9487                            "  --ww\n");
9488        rc = 1;
9489        goto meta_command_exit;
9490      }else{
9491        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9492        rc = 1;
9493        goto meta_command_exit;
9494      }
9495    }
9496    if( zMode==0 ){
9497      if( p->mode==MODE_Column
9498       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9499      ){
9500        raw_printf
9501          (p->out,
9502           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9503           modeDescr[p->mode], p->cmOpts.iWrap,
9504           p->cmOpts.bWordWrap ? "on" : "off",
9505           p->cmOpts.bQuote ? "" : "no");
9506      }else{
9507        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9508      }
9509      zMode = modeDescr[p->mode];
9510    }
9511    n2 = strlen30(zMode);
9512    if( strncmp(zMode,"lines",n2)==0 ){
9513      p->mode = MODE_Line;
9514      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9515    }else if( strncmp(zMode,"columns",n2)==0 ){
9516      p->mode = MODE_Column;
9517      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9518        p->showHeader = 1;
9519      }
9520      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9521      p->cmOpts = cmOpts;
9522    }else if( strncmp(zMode,"list",n2)==0 ){
9523      p->mode = MODE_List;
9524      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9525      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9526    }else if( strncmp(zMode,"html",n2)==0 ){
9527      p->mode = MODE_Html;
9528    }else if( strncmp(zMode,"tcl",n2)==0 ){
9529      p->mode = MODE_Tcl;
9530      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9531      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9532    }else if( strncmp(zMode,"csv",n2)==0 ){
9533      p->mode = MODE_Csv;
9534      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9535      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9536    }else if( strncmp(zMode,"tabs",n2)==0 ){
9537      p->mode = MODE_List;
9538      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9539    }else if( strncmp(zMode,"insert",n2)==0 ){
9540      p->mode = MODE_Insert;
9541      set_table_name(p, zTabname ? zTabname : "table");
9542    }else if( strncmp(zMode,"quote",n2)==0 ){
9543      p->mode = MODE_Quote;
9544      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9545      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9546    }else if( strncmp(zMode,"ascii",n2)==0 ){
9547      p->mode = MODE_Ascii;
9548      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9549      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9550    }else if( strncmp(zMode,"markdown",n2)==0 ){
9551      p->mode = MODE_Markdown;
9552      p->cmOpts = cmOpts;
9553    }else if( strncmp(zMode,"table",n2)==0 ){
9554      p->mode = MODE_Table;
9555      p->cmOpts = cmOpts;
9556    }else if( strncmp(zMode,"box",n2)==0 ){
9557      p->mode = MODE_Box;
9558      p->cmOpts = cmOpts;
9559    }else if( strncmp(zMode,"count",n2)==0 ){
9560      p->mode = MODE_Count;
9561    }else if( strncmp(zMode,"off",n2)==0 ){
9562      p->mode = MODE_Off;
9563    }else if( strncmp(zMode,"json",n2)==0 ){
9564      p->mode = MODE_Json;
9565    }else{
9566      raw_printf(stderr, "Error: mode should be one of: "
9567         "ascii box column csv html insert json line list markdown "
9568         "qbox quote table tabs tcl\n");
9569      rc = 1;
9570    }
9571    p->cMode = p->mode;
9572  }else
9573
9574#ifndef SQLITE_SHELL_FIDDLE
9575  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9576    if( nArg!=2 ){
9577      raw_printf(stderr, "Usage: .nonce NONCE\n");
9578      rc = 1;
9579    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9580      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9581                 p->lineno, azArg[1]);
9582      exit(1);
9583    }else{
9584      p->bSafeMode = 0;
9585      return 0;  /* Return immediately to bypass the safe mode reset
9586                 ** at the end of this procedure */
9587    }
9588  }else
9589#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9590
9591  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9592    if( nArg==2 ){
9593      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9594                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9595    }else{
9596      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9597      rc = 1;
9598    }
9599  }else
9600
9601  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9602    const char *zFN = 0;     /* Pointer to constant filename */
9603    char *zNewFilename = 0;  /* Name of the database file to open */
9604    int iName = 1;           /* Index in azArg[] of the filename */
9605    int newFlag = 0;         /* True to delete file before opening */
9606    int openMode = SHELL_OPEN_UNSPEC;
9607
9608    /* Check for command-line arguments */
9609    for(iName=1; iName<nArg; iName++){
9610      const char *z = azArg[iName];
9611#ifndef SQLITE_SHELL_FIDDLE
9612      if( optionMatch(z,"new") ){
9613        newFlag = 1;
9614#ifdef SQLITE_HAVE_ZLIB
9615      }else if( optionMatch(z, "zip") ){
9616        openMode = SHELL_OPEN_ZIPFILE;
9617#endif
9618      }else if( optionMatch(z, "append") ){
9619        openMode = SHELL_OPEN_APPENDVFS;
9620      }else if( optionMatch(z, "readonly") ){
9621        openMode = SHELL_OPEN_READONLY;
9622      }else if( optionMatch(z, "nofollow") ){
9623        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9624#ifndef SQLITE_OMIT_DESERIALIZE
9625      }else if( optionMatch(z, "deserialize") ){
9626        openMode = SHELL_OPEN_DESERIALIZE;
9627      }else if( optionMatch(z, "hexdb") ){
9628        openMode = SHELL_OPEN_HEXDB;
9629      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9630        p->szMax = integerValue(azArg[++iName]);
9631#endif /* SQLITE_OMIT_DESERIALIZE */
9632      }else
9633#endif /* !SQLITE_SHELL_FIDDLE */
9634      if( z[0]=='-' ){
9635        utf8_printf(stderr, "unknown option: %s\n", z);
9636        rc = 1;
9637        goto meta_command_exit;
9638      }else if( zFN ){
9639        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9640        rc = 1;
9641        goto meta_command_exit;
9642      }else{
9643        zFN = z;
9644      }
9645    }
9646
9647    /* Close the existing database */
9648    session_close_all(p, -1);
9649    close_db(p->db);
9650    p->db = 0;
9651    p->pAuxDb->zDbFilename = 0;
9652    sqlite3_free(p->pAuxDb->zFreeOnClose);
9653    p->pAuxDb->zFreeOnClose = 0;
9654    p->openMode = openMode;
9655    p->openFlags = 0;
9656    p->szMax = 0;
9657
9658    /* If a filename is specified, try to open it first */
9659    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9660      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9661#ifndef SQLITE_SHELL_FIDDLE
9662      if( p->bSafeMode
9663       && p->openMode!=SHELL_OPEN_HEXDB
9664       && zFN
9665       && strcmp(zFN,":memory:")!=0
9666      ){
9667        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9668      }
9669#else
9670      /* WASM mode has its own sandboxed pseudo-filesystem. */
9671#endif
9672      if( zFN ){
9673        zNewFilename = sqlite3_mprintf("%s", zFN);
9674        shell_check_oom(zNewFilename);
9675      }else{
9676        zNewFilename = 0;
9677      }
9678      p->pAuxDb->zDbFilename = zNewFilename;
9679      open_db(p, OPEN_DB_KEEPALIVE);
9680      if( p->db==0 ){
9681        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9682        sqlite3_free(zNewFilename);
9683      }else{
9684        p->pAuxDb->zFreeOnClose = zNewFilename;
9685      }
9686    }
9687    if( p->db==0 ){
9688      /* As a fall-back open a TEMP database */
9689      p->pAuxDb->zDbFilename = 0;
9690      open_db(p, 0);
9691    }
9692  }else
9693
9694#ifndef SQLITE_SHELL_FIDDLE
9695  if( (c=='o'
9696        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9697   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9698  ){
9699    char *zFile = 0;
9700    int bTxtMode = 0;
9701    int i;
9702    int eMode = 0;
9703    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9704    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9705
9706    zBOM[0] = 0;
9707    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9708    if( c=='e' ){
9709      eMode = 'x';
9710      bOnce = 2;
9711    }else if( strncmp(azArg[0],"once",n)==0 ){
9712      bOnce = 1;
9713    }
9714    for(i=1; i<nArg; i++){
9715      char *z = azArg[i];
9716      if( z[0]=='-' ){
9717        if( z[1]=='-' ) z++;
9718        if( strcmp(z,"-bom")==0 ){
9719          zBOM[0] = 0xef;
9720          zBOM[1] = 0xbb;
9721          zBOM[2] = 0xbf;
9722          zBOM[3] = 0;
9723        }else if( c!='e' && strcmp(z,"-x")==0 ){
9724          eMode = 'x';  /* spreadsheet */
9725        }else if( c!='e' && strcmp(z,"-e")==0 ){
9726          eMode = 'e';  /* text editor */
9727        }else{
9728          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9729                      azArg[i]);
9730          showHelp(p->out, azArg[0]);
9731          rc = 1;
9732          goto meta_command_exit;
9733        }
9734      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9735        zFile = sqlite3_mprintf("%s", z);
9736        if( zFile && zFile[0]=='|' ){
9737          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9738          break;
9739        }
9740      }else{
9741        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9742                    azArg[i]);
9743        showHelp(p->out, azArg[0]);
9744        rc = 1;
9745        sqlite3_free(zFile);
9746        goto meta_command_exit;
9747      }
9748    }
9749    if( zFile==0 ){
9750      zFile = sqlite3_mprintf("stdout");
9751    }
9752    if( bOnce ){
9753      p->outCount = 2;
9754    }else{
9755      p->outCount = 0;
9756    }
9757    output_reset(p);
9758#ifndef SQLITE_NOHAVE_SYSTEM
9759    if( eMode=='e' || eMode=='x' ){
9760      p->doXdgOpen = 1;
9761      outputModePush(p);
9762      if( eMode=='x' ){
9763        /* spreadsheet mode.  Output as CSV. */
9764        newTempFile(p, "csv");
9765        ShellClearFlag(p, SHFLG_Echo);
9766        p->mode = MODE_Csv;
9767        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9768        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9769      }else{
9770        /* text editor mode */
9771        newTempFile(p, "txt");
9772        bTxtMode = 1;
9773      }
9774      sqlite3_free(zFile);
9775      zFile = sqlite3_mprintf("%s", p->zTempFile);
9776    }
9777#endif /* SQLITE_NOHAVE_SYSTEM */
9778    shell_check_oom(zFile);
9779    if( zFile[0]=='|' ){
9780#ifdef SQLITE_OMIT_POPEN
9781      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9782      rc = 1;
9783      p->out = stdout;
9784#else
9785      p->out = popen(zFile + 1, "w");
9786      if( p->out==0 ){
9787        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9788        p->out = stdout;
9789        rc = 1;
9790      }else{
9791        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9792        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9793      }
9794#endif
9795    }else{
9796      p->out = output_file_open(zFile, bTxtMode);
9797      if( p->out==0 ){
9798        if( strcmp(zFile,"off")!=0 ){
9799          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9800        }
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    }
9808    sqlite3_free(zFile);
9809  }else
9810#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9811
9812  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9813    open_db(p,0);
9814    if( nArg<=1 ) goto parameter_syntax_error;
9815
9816    /* .parameter clear
9817    ** Clear all bind parameters by dropping the TEMP table that holds them.
9818    */
9819    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9820      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9821                   0, 0, 0);
9822    }else
9823
9824    /* .parameter list
9825    ** List all bind parameters.
9826    */
9827    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9828      sqlite3_stmt *pStmt = 0;
9829      int rx;
9830      int len = 0;
9831      rx = sqlite3_prepare_v2(p->db,
9832             "SELECT max(length(key)) "
9833             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9834      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9835        len = sqlite3_column_int(pStmt, 0);
9836        if( len>40 ) len = 40;
9837      }
9838      sqlite3_finalize(pStmt);
9839      pStmt = 0;
9840      if( len ){
9841        rx = sqlite3_prepare_v2(p->db,
9842             "SELECT key, quote(value) "
9843             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9844        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9845          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9846                      sqlite3_column_text(pStmt,1));
9847        }
9848        sqlite3_finalize(pStmt);
9849      }
9850    }else
9851
9852    /* .parameter init
9853    ** Make sure the TEMP table used to hold bind parameters exists.
9854    ** Create it if necessary.
9855    */
9856    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9857      bind_table_init(p);
9858    }else
9859
9860    /* .parameter set NAME VALUE
9861    ** Set or reset a bind parameter.  NAME should be the full parameter
9862    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9863    ** VALUE can be in either SQL literal notation, or if not it will be
9864    ** understood to be a text string.
9865    */
9866    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9867      int rx;
9868      char *zSql;
9869      sqlite3_stmt *pStmt;
9870      const char *zKey = azArg[2];
9871      const char *zValue = azArg[3];
9872      bind_table_init(p);
9873      zSql = sqlite3_mprintf(
9874                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9875                  "VALUES(%Q,%s);", zKey, zValue);
9876      shell_check_oom(zSql);
9877      pStmt = 0;
9878      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9879      sqlite3_free(zSql);
9880      if( rx!=SQLITE_OK ){
9881        sqlite3_finalize(pStmt);
9882        pStmt = 0;
9883        zSql = sqlite3_mprintf(
9884                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9885                   "VALUES(%Q,%Q);", zKey, zValue);
9886        shell_check_oom(zSql);
9887        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9888        sqlite3_free(zSql);
9889        if( rx!=SQLITE_OK ){
9890          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9891          sqlite3_finalize(pStmt);
9892          pStmt = 0;
9893          rc = 1;
9894        }
9895      }
9896      sqlite3_step(pStmt);
9897      sqlite3_finalize(pStmt);
9898    }else
9899
9900    /* .parameter unset NAME
9901    ** Remove the NAME binding from the parameter binding table, if it
9902    ** exists.
9903    */
9904    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9905      char *zSql = sqlite3_mprintf(
9906          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9907      shell_check_oom(zSql);
9908      sqlite3_exec(p->db, zSql, 0, 0, 0);
9909      sqlite3_free(zSql);
9910    }else
9911    /* If no command name matches, show a syntax error */
9912    parameter_syntax_error:
9913    showHelp(p->out, "parameter");
9914  }else
9915
9916  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9917    int i;
9918    for(i=1; i<nArg; i++){
9919      if( i>1 ) raw_printf(p->out, " ");
9920      utf8_printf(p->out, "%s", azArg[i]);
9921    }
9922    raw_printf(p->out, "\n");
9923  }else
9924
9925#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9926  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9927    int i;
9928    int nn = 0;
9929    p->flgProgress = 0;
9930    p->mxProgress = 0;
9931    p->nProgress = 0;
9932    for(i=1; i<nArg; i++){
9933      const char *z = azArg[i];
9934      if( z[0]=='-' ){
9935        z++;
9936        if( z[0]=='-' ) z++;
9937        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9938          p->flgProgress |= SHELL_PROGRESS_QUIET;
9939          continue;
9940        }
9941        if( strcmp(z,"reset")==0 ){
9942          p->flgProgress |= SHELL_PROGRESS_RESET;
9943          continue;
9944        }
9945        if( strcmp(z,"once")==0 ){
9946          p->flgProgress |= SHELL_PROGRESS_ONCE;
9947          continue;
9948        }
9949        if( strcmp(z,"limit")==0 ){
9950          if( i+1>=nArg ){
9951            utf8_printf(stderr, "Error: missing argument on --limit\n");
9952            rc = 1;
9953            goto meta_command_exit;
9954          }else{
9955            p->mxProgress = (int)integerValue(azArg[++i]);
9956          }
9957          continue;
9958        }
9959        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9960        rc = 1;
9961        goto meta_command_exit;
9962      }else{
9963        nn = (int)integerValue(z);
9964      }
9965    }
9966    open_db(p, 0);
9967    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9968  }else
9969#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9970
9971  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9972    if( nArg >= 2) {
9973      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9974    }
9975    if( nArg >= 3) {
9976      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9977    }
9978  }else
9979
9980#ifndef SQLITE_SHELL_FIDDLE
9981  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9982    rc = 2;
9983  }else
9984#endif
9985
9986#ifndef SQLITE_SHELL_FIDDLE
9987  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9988    FILE *inSaved = p->in;
9989    int savedLineno = p->lineno;
9990    failIfSafeMode(p, "cannot run .read in safe mode");
9991    if( nArg!=2 ){
9992      raw_printf(stderr, "Usage: .read FILE\n");
9993      rc = 1;
9994      goto meta_command_exit;
9995    }
9996    if( azArg[1][0]=='|' ){
9997#ifdef SQLITE_OMIT_POPEN
9998      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9999      rc = 1;
10000      p->out = stdout;
10001#else
10002      p->in = popen(azArg[1]+1, "r");
10003      if( p->in==0 ){
10004        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
10005        rc = 1;
10006      }else{
10007        rc = process_input(p);
10008        pclose(p->in);
10009      }
10010#endif
10011    }else if( (p->in = openChrSource(azArg[1]))==0 ){
10012      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
10013      rc = 1;
10014    }else{
10015      rc = process_input(p);
10016      fclose(p->in);
10017    }
10018    p->in = inSaved;
10019    p->lineno = savedLineno;
10020  }else
10021#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10022
10023#ifndef SQLITE_SHELL_FIDDLE
10024  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10025    const char *zSrcFile;
10026    const char *zDb;
10027    sqlite3 *pSrc;
10028    sqlite3_backup *pBackup;
10029    int nTimeout = 0;
10030
10031    failIfSafeMode(p, "cannot run .restore in safe mode");
10032    if( nArg==2 ){
10033      zSrcFile = azArg[1];
10034      zDb = "main";
10035    }else if( nArg==3 ){
10036      zSrcFile = azArg[2];
10037      zDb = azArg[1];
10038    }else{
10039      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10040      rc = 1;
10041      goto meta_command_exit;
10042    }
10043    rc = sqlite3_open(zSrcFile, &pSrc);
10044    if( rc!=SQLITE_OK ){
10045      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10046      close_db(pSrc);
10047      return 1;
10048    }
10049    open_db(p, 0);
10050    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10051    if( pBackup==0 ){
10052      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10053      close_db(pSrc);
10054      return 1;
10055    }
10056    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10057          || rc==SQLITE_BUSY  ){
10058      if( rc==SQLITE_BUSY ){
10059        if( nTimeout++ >= 3 ) break;
10060        sqlite3_sleep(100);
10061      }
10062    }
10063    sqlite3_backup_finish(pBackup);
10064    if( rc==SQLITE_DONE ){
10065      rc = 0;
10066    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10067      raw_printf(stderr, "Error: source database is busy\n");
10068      rc = 1;
10069    }else{
10070      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10071      rc = 1;
10072    }
10073    close_db(pSrc);
10074  }else
10075#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10076
10077  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10078    if( nArg==2 ){
10079      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10080#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10081      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10082#endif
10083    }else{
10084      raw_printf(stderr, "Usage: .scanstats on|off\n");
10085      rc = 1;
10086    }
10087  }else
10088
10089  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10090    ShellText sSelect;
10091    ShellState data;
10092    char *zErrMsg = 0;
10093    const char *zDiv = "(";
10094    const char *zName = 0;
10095    int iSchema = 0;
10096    int bDebug = 0;
10097    int bNoSystemTabs = 0;
10098    int ii;
10099
10100    open_db(p, 0);
10101    memcpy(&data, p, sizeof(data));
10102    data.showHeader = 0;
10103    data.cMode = data.mode = MODE_Semi;
10104    initText(&sSelect);
10105    for(ii=1; ii<nArg; ii++){
10106      if( optionMatch(azArg[ii],"indent") ){
10107        data.cMode = data.mode = MODE_Pretty;
10108      }else if( optionMatch(azArg[ii],"debug") ){
10109        bDebug = 1;
10110      }else if( optionMatch(azArg[ii],"nosys") ){
10111        bNoSystemTabs = 1;
10112      }else if( azArg[ii][0]=='-' ){
10113        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10114        rc = 1;
10115        goto meta_command_exit;
10116      }else if( zName==0 ){
10117        zName = azArg[ii];
10118      }else{
10119        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10120        rc = 1;
10121        goto meta_command_exit;
10122      }
10123    }
10124    if( zName!=0 ){
10125      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10126                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10127                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10128                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10129      if( isSchema ){
10130        char *new_argv[2], *new_colv[2];
10131        new_argv[0] = sqlite3_mprintf(
10132                      "CREATE TABLE %s (\n"
10133                      "  type text,\n"
10134                      "  name text,\n"
10135                      "  tbl_name text,\n"
10136                      "  rootpage integer,\n"
10137                      "  sql text\n"
10138                      ")", zName);
10139        shell_check_oom(new_argv[0]);
10140        new_argv[1] = 0;
10141        new_colv[0] = "sql";
10142        new_colv[1] = 0;
10143        callback(&data, 1, new_argv, new_colv);
10144        sqlite3_free(new_argv[0]);
10145      }
10146    }
10147    if( zDiv ){
10148      sqlite3_stmt *pStmt = 0;
10149      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10150                              -1, &pStmt, 0);
10151      if( rc ){
10152        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10153        sqlite3_finalize(pStmt);
10154        rc = 1;
10155        goto meta_command_exit;
10156      }
10157      appendText(&sSelect, "SELECT sql FROM", 0);
10158      iSchema = 0;
10159      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10160        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10161        char zScNum[30];
10162        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10163        appendText(&sSelect, zDiv, 0);
10164        zDiv = " UNION ALL ";
10165        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10166        if( sqlite3_stricmp(zDb, "main")!=0 ){
10167          appendText(&sSelect, zDb, '\'');
10168        }else{
10169          appendText(&sSelect, "NULL", 0);
10170        }
10171        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10172        appendText(&sSelect, zScNum, 0);
10173        appendText(&sSelect, " AS snum, ", 0);
10174        appendText(&sSelect, zDb, '\'');
10175        appendText(&sSelect, " AS sname FROM ", 0);
10176        appendText(&sSelect, zDb, quoteChar(zDb));
10177        appendText(&sSelect, ".sqlite_schema", 0);
10178      }
10179      sqlite3_finalize(pStmt);
10180#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10181      if( zName ){
10182        appendText(&sSelect,
10183           " UNION ALL SELECT shell_module_schema(name),"
10184           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10185        0);
10186      }
10187#endif
10188      appendText(&sSelect, ") WHERE ", 0);
10189      if( zName ){
10190        char *zQarg = sqlite3_mprintf("%Q", zName);
10191        int bGlob;
10192        shell_check_oom(zQarg);
10193        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10194                strchr(zName, '[') != 0;
10195        if( strchr(zName, '.') ){
10196          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10197        }else{
10198          appendText(&sSelect, "lower(tbl_name)", 0);
10199        }
10200        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10201        appendText(&sSelect, zQarg, 0);
10202        if( !bGlob ){
10203          appendText(&sSelect, " ESCAPE '\\' ", 0);
10204        }
10205        appendText(&sSelect, " AND ", 0);
10206        sqlite3_free(zQarg);
10207      }
10208      if( bNoSystemTabs ){
10209        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10210      }
10211      appendText(&sSelect, "sql IS NOT NULL"
10212                           " ORDER BY snum, rowid", 0);
10213      if( bDebug ){
10214        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10215      }else{
10216        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10217      }
10218      freeText(&sSelect);
10219    }
10220    if( zErrMsg ){
10221      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10222      sqlite3_free(zErrMsg);
10223      rc = 1;
10224    }else if( rc != SQLITE_OK ){
10225      raw_printf(stderr,"Error: querying schema information\n");
10226      rc = 1;
10227    }else{
10228      rc = 0;
10229    }
10230  }else
10231
10232  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10233   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10234  ){
10235    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10236    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10237  }else
10238
10239#if defined(SQLITE_ENABLE_SESSION)
10240  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10241    struct AuxDb *pAuxDb = p->pAuxDb;
10242    OpenSession *pSession = &pAuxDb->aSession[0];
10243    char **azCmd = &azArg[1];
10244    int iSes = 0;
10245    int nCmd = nArg - 1;
10246    int i;
10247    if( nArg<=1 ) goto session_syntax_error;
10248    open_db(p, 0);
10249    if( nArg>=3 ){
10250      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10251        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10252      }
10253      if( iSes<pAuxDb->nSession ){
10254        pSession = &pAuxDb->aSession[iSes];
10255        azCmd++;
10256        nCmd--;
10257      }else{
10258        pSession = &pAuxDb->aSession[0];
10259        iSes = 0;
10260      }
10261    }
10262
10263    /* .session attach TABLE
10264    ** Invoke the sqlite3session_attach() interface to attach a particular
10265    ** table so that it is never filtered.
10266    */
10267    if( strcmp(azCmd[0],"attach")==0 ){
10268      if( nCmd!=2 ) goto session_syntax_error;
10269      if( pSession->p==0 ){
10270        session_not_open:
10271        raw_printf(stderr, "ERROR: No sessions are open\n");
10272      }else{
10273        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10274        if( rc ){
10275          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10276          rc = 0;
10277        }
10278      }
10279    }else
10280
10281    /* .session changeset FILE
10282    ** .session patchset FILE
10283    ** Write a changeset or patchset into a file.  The file is overwritten.
10284    */
10285    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10286      FILE *out = 0;
10287      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10288      if( nCmd!=2 ) goto session_syntax_error;
10289      if( pSession->p==0 ) goto session_not_open;
10290      out = fopen(azCmd[1], "wb");
10291      if( out==0 ){
10292        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10293                    azCmd[1]);
10294      }else{
10295        int szChng;
10296        void *pChng;
10297        if( azCmd[0][0]=='c' ){
10298          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10299        }else{
10300          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10301        }
10302        if( rc ){
10303          printf("Error: error code %d\n", rc);
10304          rc = 0;
10305        }
10306        if( pChng
10307          && fwrite(pChng, szChng, 1, out)!=1 ){
10308          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10309                  szChng);
10310        }
10311        sqlite3_free(pChng);
10312        fclose(out);
10313      }
10314    }else
10315
10316    /* .session close
10317    ** Close the identified session
10318    */
10319    if( strcmp(azCmd[0], "close")==0 ){
10320      if( nCmd!=1 ) goto session_syntax_error;
10321      if( pAuxDb->nSession ){
10322        session_close(pSession);
10323        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10324      }
10325    }else
10326
10327    /* .session enable ?BOOLEAN?
10328    ** Query or set the enable flag
10329    */
10330    if( strcmp(azCmd[0], "enable")==0 ){
10331      int ii;
10332      if( nCmd>2 ) goto session_syntax_error;
10333      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10334      if( pAuxDb->nSession ){
10335        ii = sqlite3session_enable(pSession->p, ii);
10336        utf8_printf(p->out, "session %s enable flag = %d\n",
10337                    pSession->zName, ii);
10338      }
10339    }else
10340
10341    /* .session filter GLOB ....
10342    ** Set a list of GLOB patterns of table names to be excluded.
10343    */
10344    if( strcmp(azCmd[0], "filter")==0 ){
10345      int ii, nByte;
10346      if( nCmd<2 ) goto session_syntax_error;
10347      if( pAuxDb->nSession ){
10348        for(ii=0; ii<pSession->nFilter; ii++){
10349          sqlite3_free(pSession->azFilter[ii]);
10350        }
10351        sqlite3_free(pSession->azFilter);
10352        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10353        pSession->azFilter = sqlite3_malloc( nByte );
10354        if( pSession->azFilter==0 ){
10355          raw_printf(stderr, "Error: out or memory\n");
10356          exit(1);
10357        }
10358        for(ii=1; ii<nCmd; ii++){
10359          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10360          shell_check_oom(x);
10361        }
10362        pSession->nFilter = ii-1;
10363      }
10364    }else
10365
10366    /* .session indirect ?BOOLEAN?
10367    ** Query or set the indirect flag
10368    */
10369    if( strcmp(azCmd[0], "indirect")==0 ){
10370      int ii;
10371      if( nCmd>2 ) goto session_syntax_error;
10372      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10373      if( pAuxDb->nSession ){
10374        ii = sqlite3session_indirect(pSession->p, ii);
10375        utf8_printf(p->out, "session %s indirect flag = %d\n",
10376                    pSession->zName, ii);
10377      }
10378    }else
10379
10380    /* .session isempty
10381    ** Determine if the session is empty
10382    */
10383    if( strcmp(azCmd[0], "isempty")==0 ){
10384      int ii;
10385      if( nCmd!=1 ) goto session_syntax_error;
10386      if( pAuxDb->nSession ){
10387        ii = sqlite3session_isempty(pSession->p);
10388        utf8_printf(p->out, "session %s isempty flag = %d\n",
10389                    pSession->zName, ii);
10390      }
10391    }else
10392
10393    /* .session list
10394    ** List all currently open sessions
10395    */
10396    if( strcmp(azCmd[0],"list")==0 ){
10397      for(i=0; i<pAuxDb->nSession; i++){
10398        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10399      }
10400    }else
10401
10402    /* .session open DB NAME
10403    ** Open a new session called NAME on the attached database DB.
10404    ** DB is normally "main".
10405    */
10406    if( strcmp(azCmd[0],"open")==0 ){
10407      char *zName;
10408      if( nCmd!=3 ) goto session_syntax_error;
10409      zName = azCmd[2];
10410      if( zName[0]==0 ) goto session_syntax_error;
10411      for(i=0; i<pAuxDb->nSession; i++){
10412        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10413          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10414          goto meta_command_exit;
10415        }
10416      }
10417      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10418        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10419        goto meta_command_exit;
10420      }
10421      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10422      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10423      if( rc ){
10424        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10425        rc = 0;
10426        goto meta_command_exit;
10427      }
10428      pSession->nFilter = 0;
10429      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10430      pAuxDb->nSession++;
10431      pSession->zName = sqlite3_mprintf("%s", zName);
10432      shell_check_oom(pSession->zName);
10433    }else
10434    /* If no command name matches, show a syntax error */
10435    session_syntax_error:
10436    showHelp(p->out, "session");
10437  }else
10438#endif
10439
10440#ifdef SQLITE_DEBUG
10441  /* Undocumented commands for internal testing.  Subject to change
10442  ** without notice. */
10443  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10444    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10445      int i, v;
10446      for(i=1; i<nArg; i++){
10447        v = booleanValue(azArg[i]);
10448        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10449      }
10450    }
10451    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10452      int i; sqlite3_int64 v;
10453      for(i=1; i<nArg; i++){
10454        char zBuf[200];
10455        v = integerValue(azArg[i]);
10456        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10457        utf8_printf(p->out, "%s", zBuf);
10458      }
10459    }
10460  }else
10461#endif
10462
10463  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10464    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10465    int bVerbose = 0;        /* Verbose output */
10466    int bSelftestExists;     /* True if SELFTEST already exists */
10467    int i, k;                /* Loop counters */
10468    int nTest = 0;           /* Number of tests runs */
10469    int nErr = 0;            /* Number of errors seen */
10470    ShellText str;           /* Answer for a query */
10471    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10472
10473    open_db(p,0);
10474    for(i=1; i<nArg; i++){
10475      const char *z = azArg[i];
10476      if( z[0]=='-' && z[1]=='-' ) z++;
10477      if( strcmp(z,"-init")==0 ){
10478        bIsInit = 1;
10479      }else
10480      if( strcmp(z,"-v")==0 ){
10481        bVerbose++;
10482      }else
10483      {
10484        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10485                    azArg[i], azArg[0]);
10486        raw_printf(stderr, "Should be one of: --init -v\n");
10487        rc = 1;
10488        goto meta_command_exit;
10489      }
10490    }
10491    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10492           != SQLITE_OK ){
10493      bSelftestExists = 0;
10494    }else{
10495      bSelftestExists = 1;
10496    }
10497    if( bIsInit ){
10498      createSelftestTable(p);
10499      bSelftestExists = 1;
10500    }
10501    initText(&str);
10502    appendText(&str, "x", 0);
10503    for(k=bSelftestExists; k>=0; k--){
10504      if( k==1 ){
10505        rc = sqlite3_prepare_v2(p->db,
10506            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10507            -1, &pStmt, 0);
10508      }else{
10509        rc = sqlite3_prepare_v2(p->db,
10510          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10511          "      (1,'run','PRAGMA integrity_check','ok')",
10512          -1, &pStmt, 0);
10513      }
10514      if( rc ){
10515        raw_printf(stderr, "Error querying the selftest table\n");
10516        rc = 1;
10517        sqlite3_finalize(pStmt);
10518        goto meta_command_exit;
10519      }
10520      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10521        int tno = sqlite3_column_int(pStmt, 0);
10522        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10523        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10524        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10525
10526        if( zOp==0 ) continue;
10527        if( zSql==0 ) continue;
10528        if( zAns==0 ) continue;
10529        k = 0;
10530        if( bVerbose>0 ){
10531          printf("%d: %s %s\n", tno, zOp, zSql);
10532        }
10533        if( strcmp(zOp,"memo")==0 ){
10534          utf8_printf(p->out, "%s\n", zSql);
10535        }else
10536        if( strcmp(zOp,"run")==0 ){
10537          char *zErrMsg = 0;
10538          str.n = 0;
10539          str.z[0] = 0;
10540          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10541          nTest++;
10542          if( bVerbose ){
10543            utf8_printf(p->out, "Result: %s\n", str.z);
10544          }
10545          if( rc || zErrMsg ){
10546            nErr++;
10547            rc = 1;
10548            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10549            sqlite3_free(zErrMsg);
10550          }else if( strcmp(zAns,str.z)!=0 ){
10551            nErr++;
10552            rc = 1;
10553            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10554            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10555          }
10556        }else
10557        {
10558          utf8_printf(stderr,
10559            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10560          rc = 1;
10561          break;
10562        }
10563      } /* End loop over rows of content from SELFTEST */
10564      sqlite3_finalize(pStmt);
10565    } /* End loop over k */
10566    freeText(&str);
10567    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10568  }else
10569
10570  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10571    if( nArg<2 || nArg>3 ){
10572      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10573      rc = 1;
10574    }
10575    if( nArg>=2 ){
10576      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10577                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10578    }
10579    if( nArg>=3 ){
10580      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10581                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10582    }
10583  }else
10584
10585  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10586    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10587    int i;                   /* Loop counter */
10588    int bSchema = 0;         /* Also hash the schema */
10589    int bSeparate = 0;       /* Hash each table separately */
10590    int iSize = 224;         /* Hash algorithm to use */
10591    int bDebug = 0;          /* Only show the query that would have run */
10592    sqlite3_stmt *pStmt;     /* For querying tables names */
10593    char *zSql;              /* SQL to be run */
10594    char *zSep;              /* Separator */
10595    ShellText sSql;          /* Complete SQL for the query to run the hash */
10596    ShellText sQuery;        /* Set of queries used to read all content */
10597    open_db(p, 0);
10598    for(i=1; i<nArg; i++){
10599      const char *z = azArg[i];
10600      if( z[0]=='-' ){
10601        z++;
10602        if( z[0]=='-' ) z++;
10603        if( strcmp(z,"schema")==0 ){
10604          bSchema = 1;
10605        }else
10606        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10607         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10608        ){
10609          iSize = atoi(&z[5]);
10610        }else
10611        if( strcmp(z,"debug")==0 ){
10612          bDebug = 1;
10613        }else
10614        {
10615          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10616                      azArg[i], azArg[0]);
10617          showHelp(p->out, azArg[0]);
10618          rc = 1;
10619          goto meta_command_exit;
10620        }
10621      }else if( zLike ){
10622        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10623        rc = 1;
10624        goto meta_command_exit;
10625      }else{
10626        zLike = z;
10627        bSeparate = 1;
10628        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10629      }
10630    }
10631    if( bSchema ){
10632      zSql = "SELECT lower(name) FROM sqlite_schema"
10633             " WHERE type='table' AND coalesce(rootpage,0)>1"
10634             " UNION ALL SELECT 'sqlite_schema'"
10635             " ORDER BY 1 collate nocase";
10636    }else{
10637      zSql = "SELECT lower(name) FROM sqlite_schema"
10638             " WHERE type='table' AND coalesce(rootpage,0)>1"
10639             " AND name NOT LIKE 'sqlite_%'"
10640             " ORDER BY 1 collate nocase";
10641    }
10642    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10643    initText(&sQuery);
10644    initText(&sSql);
10645    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10646    zSep = "VALUES(";
10647    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10648      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10649      if( zTab==0 ) continue;
10650      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10651      if( strncmp(zTab, "sqlite_",7)!=0 ){
10652        appendText(&sQuery,"SELECT * FROM ", 0);
10653        appendText(&sQuery,zTab,'"');
10654        appendText(&sQuery," NOT INDEXED;", 0);
10655      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10656        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10657                           " ORDER BY name;", 0);
10658      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10659        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10660                           " ORDER BY name;", 0);
10661      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10662        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10663                           " ORDER BY tbl,idx;", 0);
10664      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10665        appendText(&sQuery, "SELECT * FROM ", 0);
10666        appendText(&sQuery, zTab, 0);
10667        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10668      }
10669      appendText(&sSql, zSep, 0);
10670      appendText(&sSql, sQuery.z, '\'');
10671      sQuery.n = 0;
10672      appendText(&sSql, ",", 0);
10673      appendText(&sSql, zTab, '\'');
10674      zSep = "),(";
10675    }
10676    sqlite3_finalize(pStmt);
10677    if( bSeparate ){
10678      zSql = sqlite3_mprintf(
10679          "%s))"
10680          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10681          "   FROM [sha3sum$query]",
10682          sSql.z, iSize);
10683    }else{
10684      zSql = sqlite3_mprintf(
10685          "%s))"
10686          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10687          "   FROM [sha3sum$query]",
10688          sSql.z, iSize);
10689    }
10690    shell_check_oom(zSql);
10691    freeText(&sQuery);
10692    freeText(&sSql);
10693    if( bDebug ){
10694      utf8_printf(p->out, "%s\n", zSql);
10695    }else{
10696      shell_exec(p, zSql, 0);
10697    }
10698    sqlite3_free(zSql);
10699  }else
10700
10701#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10702  if( c=='s'
10703   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10704  ){
10705    char *zCmd;
10706    int i, x;
10707    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10708    if( nArg<2 ){
10709      raw_printf(stderr, "Usage: .system COMMAND\n");
10710      rc = 1;
10711      goto meta_command_exit;
10712    }
10713    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10714    for(i=2; i<nArg && zCmd!=0; i++){
10715      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10716                             zCmd, azArg[i]);
10717    }
10718    x = zCmd!=0 ? system(zCmd) : 1;
10719    sqlite3_free(zCmd);
10720    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10721  }else
10722#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10723
10724  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10725    static const char *azBool[] = { "off", "on", "trigger", "full"};
10726    const char *zOut;
10727    int i;
10728    if( nArg!=1 ){
10729      raw_printf(stderr, "Usage: .show\n");
10730      rc = 1;
10731      goto meta_command_exit;
10732    }
10733    utf8_printf(p->out, "%12.12s: %s\n","echo",
10734                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10735    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10736    utf8_printf(p->out, "%12.12s: %s\n","explain",
10737         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10738    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10739    if( p->mode==MODE_Column
10740     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10741    ){
10742      utf8_printf
10743        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10744         modeDescr[p->mode], p->cmOpts.iWrap,
10745         p->cmOpts.bWordWrap ? "on" : "off",
10746         p->cmOpts.bQuote ? "" : "no");
10747    }else{
10748      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10749    }
10750    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10751      output_c_string(p->out, p->nullValue);
10752      raw_printf(p->out, "\n");
10753    utf8_printf(p->out,"%12.12s: %s\n","output",
10754            strlen30(p->outfile) ? p->outfile : "stdout");
10755    utf8_printf(p->out,"%12.12s: ", "colseparator");
10756      output_c_string(p->out, p->colSeparator);
10757      raw_printf(p->out, "\n");
10758    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10759      output_c_string(p->out, p->rowSeparator);
10760      raw_printf(p->out, "\n");
10761    switch( p->statsOn ){
10762      case 0:  zOut = "off";     break;
10763      default: zOut = "on";      break;
10764      case 2:  zOut = "stmt";    break;
10765      case 3:  zOut = "vmstep";  break;
10766    }
10767    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10768    utf8_printf(p->out, "%12.12s: ", "width");
10769    for (i=0;i<p->nWidth;i++) {
10770      raw_printf(p->out, "%d ", p->colWidth[i]);
10771    }
10772    raw_printf(p->out, "\n");
10773    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10774                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10775  }else
10776
10777  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10778    if( nArg==2 ){
10779      if( strcmp(azArg[1],"stmt")==0 ){
10780        p->statsOn = 2;
10781      }else if( strcmp(azArg[1],"vmstep")==0 ){
10782        p->statsOn = 3;
10783      }else{
10784        p->statsOn = (u8)booleanValue(azArg[1]);
10785      }
10786    }else if( nArg==1 ){
10787      display_stats(p->db, p, 0);
10788    }else{
10789      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10790      rc = 1;
10791    }
10792  }else
10793
10794  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10795   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10796                 || strncmp(azArg[0], "indexes", n)==0) )
10797  ){
10798    sqlite3_stmt *pStmt;
10799    char **azResult;
10800    int nRow, nAlloc;
10801    int ii;
10802    ShellText s;
10803    initText(&s);
10804    open_db(p, 0);
10805    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10806    if( rc ){
10807      sqlite3_finalize(pStmt);
10808      return shellDatabaseError(p->db);
10809    }
10810
10811    if( nArg>2 && c=='i' ){
10812      /* It is an historical accident that the .indexes command shows an error
10813      ** when called with the wrong number of arguments whereas the .tables
10814      ** command does not. */
10815      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10816      rc = 1;
10817      sqlite3_finalize(pStmt);
10818      goto meta_command_exit;
10819    }
10820    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10821      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10822      if( zDbName==0 ) continue;
10823      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10824      if( sqlite3_stricmp(zDbName, "main")==0 ){
10825        appendText(&s, "SELECT name FROM ", 0);
10826      }else{
10827        appendText(&s, "SELECT ", 0);
10828        appendText(&s, zDbName, '\'');
10829        appendText(&s, "||'.'||name FROM ", 0);
10830      }
10831      appendText(&s, zDbName, '"');
10832      appendText(&s, ".sqlite_schema ", 0);
10833      if( c=='t' ){
10834        appendText(&s," WHERE type IN ('table','view')"
10835                      "   AND name NOT LIKE 'sqlite_%'"
10836                      "   AND name LIKE ?1", 0);
10837      }else{
10838        appendText(&s," WHERE type='index'"
10839                      "   AND tbl_name LIKE ?1", 0);
10840      }
10841    }
10842    rc = sqlite3_finalize(pStmt);
10843    if( rc==SQLITE_OK ){
10844      appendText(&s, " ORDER BY 1", 0);
10845      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10846    }
10847    freeText(&s);
10848    if( rc ) return shellDatabaseError(p->db);
10849
10850    /* Run the SQL statement prepared by the above block. Store the results
10851    ** as an array of nul-terminated strings in azResult[].  */
10852    nRow = nAlloc = 0;
10853    azResult = 0;
10854    if( nArg>1 ){
10855      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10856    }else{
10857      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10858    }
10859    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10860      if( nRow>=nAlloc ){
10861        char **azNew;
10862        int n2 = nAlloc*2 + 10;
10863        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10864        shell_check_oom(azNew);
10865        nAlloc = n2;
10866        azResult = azNew;
10867      }
10868      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10869      shell_check_oom(azResult[nRow]);
10870      nRow++;
10871    }
10872    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10873      rc = shellDatabaseError(p->db);
10874    }
10875
10876    /* Pretty-print the contents of array azResult[] to the output */
10877    if( rc==0 && nRow>0 ){
10878      int len, maxlen = 0;
10879      int i, j;
10880      int nPrintCol, nPrintRow;
10881      for(i=0; i<nRow; i++){
10882        len = strlen30(azResult[i]);
10883        if( len>maxlen ) maxlen = len;
10884      }
10885      nPrintCol = 80/(maxlen+2);
10886      if( nPrintCol<1 ) nPrintCol = 1;
10887      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10888      for(i=0; i<nPrintRow; i++){
10889        for(j=i; j<nRow; j+=nPrintRow){
10890          char *zSp = j<nPrintRow ? "" : "  ";
10891          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10892                      azResult[j] ? azResult[j]:"");
10893        }
10894        raw_printf(p->out, "\n");
10895      }
10896    }
10897
10898    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10899    sqlite3_free(azResult);
10900  }else
10901
10902#ifndef SQLITE_SHELL_FIDDLE
10903  /* Begin redirecting output to the file "testcase-out.txt" */
10904  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10905    output_reset(p);
10906    p->out = output_file_open("testcase-out.txt", 0);
10907    if( p->out==0 ){
10908      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10909    }
10910    if( nArg>=2 ){
10911      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10912    }else{
10913      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10914    }
10915  }else
10916#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10917
10918#ifndef SQLITE_UNTESTABLE
10919  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10920    static const struct {
10921       const char *zCtrlName;   /* Name of a test-control option */
10922       int ctrlCode;            /* Integer code for that option */
10923       int unSafe;              /* Not valid for --safe mode */
10924       const char *zUsage;      /* Usage notes */
10925    } aCtrl[] = {
10926      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10927      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10928    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10929    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10930      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10931      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10932    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10933      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10934      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10935      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10936      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10937      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10938#ifdef YYCOVERAGE
10939      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10940#endif
10941      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10942      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10943      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10944      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10945      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10946      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10947      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10948    };
10949    int testctrl = -1;
10950    int iCtrl = -1;
10951    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10952    int isOk = 0;
10953    int i, n2;
10954    const char *zCmd = 0;
10955
10956    open_db(p, 0);
10957    zCmd = nArg>=2 ? azArg[1] : "help";
10958
10959    /* The argument can optionally begin with "-" or "--" */
10960    if( zCmd[0]=='-' && zCmd[1] ){
10961      zCmd++;
10962      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10963    }
10964
10965    /* --help lists all test-controls */
10966    if( strcmp(zCmd,"help")==0 ){
10967      utf8_printf(p->out, "Available test-controls:\n");
10968      for(i=0; i<ArraySize(aCtrl); i++){
10969        utf8_printf(p->out, "  .testctrl %s %s\n",
10970                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10971      }
10972      rc = 1;
10973      goto meta_command_exit;
10974    }
10975
10976    /* convert testctrl text option to value. allow any unique prefix
10977    ** of the option name, or a numerical value. */
10978    n2 = strlen30(zCmd);
10979    for(i=0; i<ArraySize(aCtrl); i++){
10980      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10981        if( testctrl<0 ){
10982          testctrl = aCtrl[i].ctrlCode;
10983          iCtrl = i;
10984        }else{
10985          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10986                              "Use \".testctrl --help\" for help\n", zCmd);
10987          rc = 1;
10988          goto meta_command_exit;
10989        }
10990      }
10991    }
10992    if( testctrl<0 ){
10993      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10994                         "Use \".testctrl --help\" for help\n", zCmd);
10995    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10996      utf8_printf(stderr,
10997         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10998         p->lineno, aCtrl[iCtrl].zCtrlName);
10999      exit(1);
11000    }else{
11001      switch(testctrl){
11002
11003        /* sqlite3_test_control(int, db, int) */
11004        case SQLITE_TESTCTRL_OPTIMIZATIONS:
11005          if( nArg==3 ){
11006            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
11007            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11008            isOk = 3;
11009          }
11010          break;
11011
11012        /* sqlite3_test_control(int) */
11013        case SQLITE_TESTCTRL_PRNG_SAVE:
11014        case SQLITE_TESTCTRL_PRNG_RESTORE:
11015        case SQLITE_TESTCTRL_BYTEORDER:
11016          if( nArg==2 ){
11017            rc2 = sqlite3_test_control(testctrl);
11018            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
11019          }
11020          break;
11021
11022        /* sqlite3_test_control(int, uint) */
11023        case SQLITE_TESTCTRL_PENDING_BYTE:
11024          if( nArg==3 ){
11025            unsigned int opt = (unsigned int)integerValue(azArg[2]);
11026            rc2 = sqlite3_test_control(testctrl, opt);
11027            isOk = 3;
11028          }
11029          break;
11030
11031        /* sqlite3_test_control(int, int, sqlite3*) */
11032        case SQLITE_TESTCTRL_PRNG_SEED:
11033          if( nArg==3 || nArg==4 ){
11034            int ii = (int)integerValue(azArg[2]);
11035            sqlite3 *db;
11036            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11037              sqlite3_randomness(sizeof(ii),&ii);
11038              printf("-- random seed: %d\n", ii);
11039            }
11040            if( nArg==3 ){
11041              db = 0;
11042            }else{
11043              db = p->db;
11044              /* Make sure the schema has been loaded */
11045              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11046            }
11047            rc2 = sqlite3_test_control(testctrl, ii, db);
11048            isOk = 3;
11049          }
11050          break;
11051
11052        /* sqlite3_test_control(int, int) */
11053        case SQLITE_TESTCTRL_ASSERT:
11054        case SQLITE_TESTCTRL_ALWAYS:
11055          if( nArg==3 ){
11056            int opt = booleanValue(azArg[2]);
11057            rc2 = sqlite3_test_control(testctrl, opt);
11058            isOk = 1;
11059          }
11060          break;
11061
11062        /* sqlite3_test_control(int, int) */
11063        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11064        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11065          if( nArg==3 ){
11066            int opt = booleanValue(azArg[2]);
11067            rc2 = sqlite3_test_control(testctrl, opt);
11068            isOk = 3;
11069          }
11070          break;
11071
11072        /* sqlite3_test_control(sqlite3*) */
11073        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11074          rc2 = sqlite3_test_control(testctrl, p->db);
11075          isOk = 3;
11076          break;
11077
11078        case SQLITE_TESTCTRL_IMPOSTER:
11079          if( nArg==5 ){
11080            rc2 = sqlite3_test_control(testctrl, p->db,
11081                          azArg[2],
11082                          integerValue(azArg[3]),
11083                          integerValue(azArg[4]));
11084            isOk = 3;
11085          }
11086          break;
11087
11088        case SQLITE_TESTCTRL_SEEK_COUNT: {
11089          u64 x = 0;
11090          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11091          utf8_printf(p->out, "%llu\n", x);
11092          isOk = 3;
11093          break;
11094        }
11095
11096#ifdef YYCOVERAGE
11097        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11098          if( nArg==2 ){
11099            sqlite3_test_control(testctrl, p->out);
11100            isOk = 3;
11101          }
11102          break;
11103        }
11104#endif
11105#ifdef SQLITE_DEBUG
11106        case SQLITE_TESTCTRL_TUNE: {
11107          if( nArg==4 ){
11108            int id = (int)integerValue(azArg[2]);
11109            int val = (int)integerValue(azArg[3]);
11110            sqlite3_test_control(testctrl, id, &val);
11111            isOk = 3;
11112          }else if( nArg==3 ){
11113            int id = (int)integerValue(azArg[2]);
11114            sqlite3_test_control(testctrl, -id, &rc2);
11115            isOk = 1;
11116          }else if( nArg==2 ){
11117            int id = 1;
11118            while(1){
11119              int val = 0;
11120              rc2 = sqlite3_test_control(testctrl, -id, &val);
11121              if( rc2!=SQLITE_OK ) break;
11122              if( id>1 ) utf8_printf(p->out, "  ");
11123              utf8_printf(p->out, "%d: %d", id, val);
11124              id++;
11125            }
11126            if( id>1 ) utf8_printf(p->out, "\n");
11127            isOk = 3;
11128          }
11129          break;
11130        }
11131#endif
11132        case SQLITE_TESTCTRL_SORTER_MMAP:
11133          if( nArg==3 ){
11134            int opt = (unsigned int)integerValue(azArg[2]);
11135            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11136            isOk = 3;
11137          }
11138          break;
11139      }
11140    }
11141    if( isOk==0 && iCtrl>=0 ){
11142      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11143      rc = 1;
11144    }else if( isOk==1 ){
11145      raw_printf(p->out, "%d\n", rc2);
11146    }else if( isOk==2 ){
11147      raw_printf(p->out, "0x%08x\n", rc2);
11148    }
11149  }else
11150#endif /* !defined(SQLITE_UNTESTABLE) */
11151
11152  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11153    open_db(p, 0);
11154    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11155  }else
11156
11157  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11158    if( nArg==2 ){
11159      enableTimer = booleanValue(azArg[1]);
11160      if( enableTimer && !HAS_TIMER ){
11161        raw_printf(stderr, "Error: timer not available on this system.\n");
11162        enableTimer = 0;
11163      }
11164    }else{
11165      raw_printf(stderr, "Usage: .timer on|off\n");
11166      rc = 1;
11167    }
11168  }else
11169
11170#ifndef SQLITE_OMIT_TRACE
11171  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11172    int mType = 0;
11173    int jj;
11174    open_db(p, 0);
11175    for(jj=1; jj<nArg; jj++){
11176      const char *z = azArg[jj];
11177      if( z[0]=='-' ){
11178        if( optionMatch(z, "expanded") ){
11179          p->eTraceType = SHELL_TRACE_EXPANDED;
11180        }
11181#ifdef SQLITE_ENABLE_NORMALIZE
11182        else if( optionMatch(z, "normalized") ){
11183          p->eTraceType = SHELL_TRACE_NORMALIZED;
11184        }
11185#endif
11186        else if( optionMatch(z, "plain") ){
11187          p->eTraceType = SHELL_TRACE_PLAIN;
11188        }
11189        else if( optionMatch(z, "profile") ){
11190          mType |= SQLITE_TRACE_PROFILE;
11191        }
11192        else if( optionMatch(z, "row") ){
11193          mType |= SQLITE_TRACE_ROW;
11194        }
11195        else if( optionMatch(z, "stmt") ){
11196          mType |= SQLITE_TRACE_STMT;
11197        }
11198        else if( optionMatch(z, "close") ){
11199          mType |= SQLITE_TRACE_CLOSE;
11200        }
11201        else {
11202          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11203          rc = 1;
11204          goto meta_command_exit;
11205        }
11206      }else{
11207        output_file_close(p->traceOut);
11208        p->traceOut = output_file_open(azArg[1], 0);
11209      }
11210    }
11211    if( p->traceOut==0 ){
11212      sqlite3_trace_v2(p->db, 0, 0, 0);
11213    }else{
11214      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11215      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11216    }
11217  }else
11218#endif /* !defined(SQLITE_OMIT_TRACE) */
11219
11220#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11221  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11222    int ii;
11223    int lenOpt;
11224    char *zOpt;
11225    if( nArg<2 ){
11226      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11227      rc = 1;
11228      goto meta_command_exit;
11229    }
11230    open_db(p, 0);
11231    zOpt = azArg[1];
11232    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11233    lenOpt = (int)strlen(zOpt);
11234    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11235      assert( azArg[nArg]==0 );
11236      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11237    }else{
11238      for(ii=1; ii<nArg; ii++){
11239        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11240      }
11241    }
11242  }else
11243#endif
11244
11245#if SQLITE_USER_AUTHENTICATION
11246  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11247    if( nArg<2 ){
11248      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11249      rc = 1;
11250      goto meta_command_exit;
11251    }
11252    open_db(p, 0);
11253    if( strcmp(azArg[1],"login")==0 ){
11254      if( nArg!=4 ){
11255        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11256        rc = 1;
11257        goto meta_command_exit;
11258      }
11259      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11260                                     strlen30(azArg[3]));
11261      if( rc ){
11262        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11263        rc = 1;
11264      }
11265    }else if( strcmp(azArg[1],"add")==0 ){
11266      if( nArg!=5 ){
11267        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11268        rc = 1;
11269        goto meta_command_exit;
11270      }
11271      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11272                            booleanValue(azArg[4]));
11273      if( rc ){
11274        raw_printf(stderr, "User-Add failed: %d\n", rc);
11275        rc = 1;
11276      }
11277    }else if( strcmp(azArg[1],"edit")==0 ){
11278      if( nArg!=5 ){
11279        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11280        rc = 1;
11281        goto meta_command_exit;
11282      }
11283      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11284                              booleanValue(azArg[4]));
11285      if( rc ){
11286        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11287        rc = 1;
11288      }
11289    }else if( strcmp(azArg[1],"delete")==0 ){
11290      if( nArg!=3 ){
11291        raw_printf(stderr, "Usage: .user delete USER\n");
11292        rc = 1;
11293        goto meta_command_exit;
11294      }
11295      rc = sqlite3_user_delete(p->db, azArg[2]);
11296      if( rc ){
11297        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11298        rc = 1;
11299      }
11300    }else{
11301      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11302      rc = 1;
11303      goto meta_command_exit;
11304    }
11305  }else
11306#endif /* SQLITE_USER_AUTHENTICATION */
11307
11308  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11309    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11310        sqlite3_libversion(), sqlite3_sourceid());
11311#if SQLITE_HAVE_ZLIB
11312    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11313#endif
11314#define CTIMEOPT_VAL_(opt) #opt
11315#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11316#if defined(__clang__) && defined(__clang_major__)
11317    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11318                    CTIMEOPT_VAL(__clang_minor__) "."
11319                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11320#elif defined(_MSC_VER)
11321    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11322#elif defined(__GNUC__) && defined(__VERSION__)
11323    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11324#endif
11325  }else
11326
11327  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11328    const char *zDbName = nArg==2 ? azArg[1] : "main";
11329    sqlite3_vfs *pVfs = 0;
11330    if( p->db ){
11331      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11332      if( pVfs ){
11333        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11334        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11335        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11336        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11337      }
11338    }
11339  }else
11340
11341  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11342    sqlite3_vfs *pVfs;
11343    sqlite3_vfs *pCurrent = 0;
11344    if( p->db ){
11345      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11346    }
11347    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11348      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11349           pVfs==pCurrent ? "  <--- CURRENT" : "");
11350      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11351      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11352      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11353      if( pVfs->pNext ){
11354        raw_printf(p->out, "-----------------------------------\n");
11355      }
11356    }
11357  }else
11358
11359  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11360    const char *zDbName = nArg==2 ? azArg[1] : "main";
11361    char *zVfsName = 0;
11362    if( p->db ){
11363      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11364      if( zVfsName ){
11365        utf8_printf(p->out, "%s\n", zVfsName);
11366        sqlite3_free(zVfsName);
11367      }
11368    }
11369  }else
11370
11371  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11372    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11373    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11374  }else
11375
11376  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11377    int j;
11378    assert( nArg<=ArraySize(azArg) );
11379    p->nWidth = nArg-1;
11380    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11381    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11382    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11383    for(j=1; j<nArg; j++){
11384      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11385    }
11386  }else
11387
11388  {
11389    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11390      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11391    rc = 1;
11392  }
11393
11394meta_command_exit:
11395  if( p->outCount ){
11396    p->outCount--;
11397    if( p->outCount==0 ) output_reset(p);
11398  }
11399  p->bSafeMode = p->bSafeModePersist;
11400  return rc;
11401}
11402
11403/* Line scan result and intermediate states (supporting scan resumption)
11404*/
11405#ifndef CHAR_BIT
11406# define CHAR_BIT 8
11407#endif
11408typedef enum {
11409  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11410  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11411  QSS_Start = 0
11412} QuickScanState;
11413#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11414#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11415#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11416#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11417#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11418
11419/*
11420** Scan line for classification to guide shell's handling.
11421** The scan is resumable for subsequent lines when prior
11422** return values are passed as the 2nd argument.
11423*/
11424static QuickScanState quickscan(char *zLine, QuickScanState qss){
11425  char cin;
11426  char cWait = (char)qss; /* intentional narrowing loss */
11427  if( cWait==0 ){
11428  PlainScan:
11429    assert( cWait==0 );
11430    while( (cin = *zLine++)!=0 ){
11431      if( IsSpace(cin) )
11432        continue;
11433      switch (cin){
11434      case '-':
11435        if( *zLine!='-' )
11436          break;
11437        while((cin = *++zLine)!=0 )
11438          if( cin=='\n')
11439            goto PlainScan;
11440        return qss;
11441      case ';':
11442        qss |= QSS_EndingSemi;
11443        continue;
11444      case '/':
11445        if( *zLine=='*' ){
11446          ++zLine;
11447          cWait = '*';
11448          qss = QSS_SETV(qss, cWait);
11449          goto TermScan;
11450        }
11451        break;
11452      case '[':
11453        cin = ']';
11454        /* fall thru */
11455      case '`': case '\'': case '"':
11456        cWait = cin;
11457        qss = QSS_HasDark | cWait;
11458        goto TermScan;
11459      default:
11460        break;
11461      }
11462      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11463    }
11464  }else{
11465  TermScan:
11466    while( (cin = *zLine++)!=0 ){
11467      if( cin==cWait ){
11468        switch( cWait ){
11469        case '*':
11470          if( *zLine != '/' )
11471            continue;
11472          ++zLine;
11473          cWait = 0;
11474          qss = QSS_SETV(qss, 0);
11475          goto PlainScan;
11476        case '`': case '\'': case '"':
11477          if(*zLine==cWait){
11478            ++zLine;
11479            continue;
11480          }
11481          /* fall thru */
11482        case ']':
11483          cWait = 0;
11484          qss = QSS_SETV(qss, 0);
11485          goto PlainScan;
11486        default: assert(0);
11487        }
11488      }
11489    }
11490  }
11491  return qss;
11492}
11493
11494/*
11495** Return TRUE if the line typed in is an SQL command terminator other
11496** than a semi-colon.  The SQL Server style "go" command is understood
11497** as is the Oracle "/".
11498*/
11499static int line_is_command_terminator(char *zLine){
11500  while( IsSpace(zLine[0]) ){ zLine++; };
11501  if( zLine[0]=='/' )
11502    zLine += 1; /* Oracle */
11503  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11504    zLine += 2; /* SQL Server */
11505  else
11506    return 0;
11507  return quickscan(zLine, QSS_Start)==QSS_Start;
11508}
11509
11510/*
11511** We need a default sqlite3_complete() implementation to use in case
11512** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11513** any arbitrary text is a complete SQL statement.  This is not very
11514** user-friendly, but it does seem to work.
11515*/
11516#ifdef SQLITE_OMIT_COMPLETE
11517#define sqlite3_complete(x) 1
11518#endif
11519
11520/*
11521** Return true if zSql is a complete SQL statement.  Return false if it
11522** ends in the middle of a string literal or C-style comment.
11523*/
11524static int line_is_complete(char *zSql, int nSql){
11525  int rc;
11526  if( zSql==0 ) return 1;
11527  zSql[nSql] = ';';
11528  zSql[nSql+1] = 0;
11529  rc = sqlite3_complete(zSql);
11530  zSql[nSql] = 0;
11531  return rc;
11532}
11533
11534/*
11535** Run a single line of SQL.  Return the number of errors.
11536*/
11537static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11538  int rc;
11539  char *zErrMsg = 0;
11540
11541  open_db(p, 0);
11542  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11543  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11544  BEGIN_TIMER;
11545  rc = shell_exec(p, zSql, &zErrMsg);
11546  END_TIMER;
11547  if( rc || zErrMsg ){
11548    char zPrefix[100];
11549    const char *zErrorTail;
11550    const char *zErrorType;
11551    if( zErrMsg==0 ){
11552      zErrorType = "Error";
11553      zErrorTail = sqlite3_errmsg(p->db);
11554    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11555      zErrorType = "Parse error";
11556      zErrorTail = &zErrMsg[12];
11557    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11558      zErrorType = "Runtime error";
11559      zErrorTail = &zErrMsg[10];
11560    }else{
11561      zErrorType = "Error";
11562      zErrorTail = zErrMsg;
11563    }
11564    if( in!=0 || !stdin_is_interactive ){
11565      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11566                       "%s near line %d:", zErrorType, startline);
11567    }else{
11568      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11569    }
11570    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11571    sqlite3_free(zErrMsg);
11572    zErrMsg = 0;
11573    return 1;
11574  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11575    char zLineBuf[2000];
11576    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11577            "changes: %lld   total_changes: %lld",
11578            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11579    raw_printf(p->out, "%s\n", zLineBuf);
11580  }
11581  return 0;
11582}
11583
11584static void echo_group_input(ShellState *p, const char *zDo){
11585  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11586}
11587
11588#ifdef SQLITE_SHELL_FIDDLE
11589/*
11590** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11591** because we need the global shellState and cannot access it from that function
11592** without moving lots of code around (creating a larger/messier diff).
11593*/
11594static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11595  /* Parse the next line from shellState.wasm.zInput. */
11596  const char *zBegin = shellState.wasm.zPos;
11597  const char *z = zBegin;
11598  char *zLine = 0;
11599  int nZ = 0;
11600
11601  UNUSED_PARAMETER(in);
11602  UNUSED_PARAMETER(isContinuation);
11603  if(!z || !*z){
11604    return 0;
11605  }
11606  while(*z && isspace(*z)) ++z;
11607  zBegin = z;
11608  for(; *z && '\n'!=*z; ++nZ, ++z){}
11609  if(nZ>0 && '\r'==zBegin[nZ-1]){
11610    --nZ;
11611  }
11612  shellState.wasm.zPos = z;
11613  zLine = realloc(zPrior, nZ+1);
11614  shell_check_oom(zLine);
11615  memcpy(zLine, zBegin, (size_t)nZ);
11616  zLine[nZ] = 0;
11617  return zLine;
11618}
11619#endif /* SQLITE_SHELL_FIDDLE */
11620
11621/*
11622** Read input from *in and process it.  If *in==0 then input
11623** is interactive - the user is typing it it.  Otherwise, input
11624** is coming from a file or device.  A prompt is issued and history
11625** is saved only if input is interactive.  An interrupt signal will
11626** cause this routine to exit immediately, unless input is interactive.
11627**
11628** Return the number of errors.
11629*/
11630static int process_input(ShellState *p){
11631  char *zLine = 0;          /* A single input line */
11632  char *zSql = 0;           /* Accumulated SQL text */
11633  int nLine;                /* Length of current line */
11634  int nSql = 0;             /* Bytes of zSql[] used */
11635  int nAlloc = 0;           /* Allocated zSql[] space */
11636  int rc;                   /* Error code */
11637  int errCnt = 0;           /* Number of errors seen */
11638  int startline = 0;        /* Line number for start of current input */
11639  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11640
11641  if( p->inputNesting==MAX_INPUT_NESTING ){
11642    /* This will be more informative in a later version. */
11643    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11644                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11645    return 1;
11646  }
11647  ++p->inputNesting;
11648  p->lineno = 0;
11649  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11650    fflush(p->out);
11651    zLine = one_input_line(p->in, zLine, nSql>0);
11652    if( zLine==0 ){
11653      /* End of input */
11654      if( p->in==0 && stdin_is_interactive ) printf("\n");
11655      break;
11656    }
11657    if( seenInterrupt ){
11658      if( p->in!=0 ) break;
11659      seenInterrupt = 0;
11660    }
11661    p->lineno++;
11662    if( QSS_INPLAIN(qss)
11663        && line_is_command_terminator(zLine)
11664        && line_is_complete(zSql, nSql) ){
11665      memcpy(zLine,";",2);
11666    }
11667    qss = quickscan(zLine, qss);
11668    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11669      /* Just swallow single-line whitespace */
11670      echo_group_input(p, zLine);
11671      qss = QSS_Start;
11672      continue;
11673    }
11674    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11675      echo_group_input(p, zLine);
11676      if( zLine[0]=='.' ){
11677        rc = do_meta_command(zLine, p);
11678        if( rc==2 ){ /* exit requested */
11679          break;
11680        }else if( rc ){
11681          errCnt++;
11682        }
11683      }
11684      qss = QSS_Start;
11685      continue;
11686    }
11687    /* No single-line dispositions remain; accumulate line(s). */
11688    nLine = strlen30(zLine);
11689    if( nSql+nLine+2>=nAlloc ){
11690      /* Grow buffer by half-again increments when big. */
11691      nAlloc = nSql+(nSql>>1)+nLine+100;
11692      zSql = realloc(zSql, nAlloc);
11693      shell_check_oom(zSql);
11694    }
11695    if( nSql==0 ){
11696      int i;
11697      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11698      assert( nAlloc>0 && zSql!=0 );
11699      memcpy(zSql, zLine+i, nLine+1-i);
11700      startline = p->lineno;
11701      nSql = nLine-i;
11702    }else{
11703      zSql[nSql++] = '\n';
11704      memcpy(zSql+nSql, zLine, nLine+1);
11705      nSql += nLine;
11706    }
11707    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11708      echo_group_input(p, zSql);
11709      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11710      nSql = 0;
11711      if( p->outCount ){
11712        output_reset(p);
11713        p->outCount = 0;
11714      }else{
11715        clearTempFile(p);
11716      }
11717      p->bSafeMode = p->bSafeModePersist;
11718      qss = QSS_Start;
11719    }else if( nSql && QSS_PLAINWHITE(qss) ){
11720      echo_group_input(p, zSql);
11721      nSql = 0;
11722      qss = QSS_Start;
11723    }
11724  }
11725  if( nSql ){
11726    /* This may be incomplete. Let the SQL parser deal with that. */
11727    echo_group_input(p, zSql);
11728    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11729  }
11730  free(zSql);
11731  free(zLine);
11732  --p->inputNesting;
11733  return errCnt>0;
11734}
11735
11736/*
11737** Return a pathname which is the user's home directory.  A
11738** 0 return indicates an error of some kind.
11739*/
11740static char *find_home_dir(int clearFlag){
11741  static char *home_dir = NULL;
11742  if( clearFlag ){
11743    free(home_dir);
11744    home_dir = 0;
11745    return 0;
11746  }
11747  if( home_dir ) return home_dir;
11748
11749#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11750     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11751  {
11752    struct passwd *pwent;
11753    uid_t uid = getuid();
11754    if( (pwent=getpwuid(uid)) != NULL) {
11755      home_dir = pwent->pw_dir;
11756    }
11757  }
11758#endif
11759
11760#if defined(_WIN32_WCE)
11761  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11762   */
11763  home_dir = "/";
11764#else
11765
11766#if defined(_WIN32) || defined(WIN32)
11767  if (!home_dir) {
11768    home_dir = getenv("USERPROFILE");
11769  }
11770#endif
11771
11772  if (!home_dir) {
11773    home_dir = getenv("HOME");
11774  }
11775
11776#if defined(_WIN32) || defined(WIN32)
11777  if (!home_dir) {
11778    char *zDrive, *zPath;
11779    int n;
11780    zDrive = getenv("HOMEDRIVE");
11781    zPath = getenv("HOMEPATH");
11782    if( zDrive && zPath ){
11783      n = strlen30(zDrive) + strlen30(zPath) + 1;
11784      home_dir = malloc( n );
11785      if( home_dir==0 ) return 0;
11786      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11787      return home_dir;
11788    }
11789    home_dir = "c:\\";
11790  }
11791#endif
11792
11793#endif /* !_WIN32_WCE */
11794
11795  if( home_dir ){
11796    int n = strlen30(home_dir) + 1;
11797    char *z = malloc( n );
11798    if( z ) memcpy(z, home_dir, n);
11799    home_dir = z;
11800  }
11801
11802  return home_dir;
11803}
11804
11805/*
11806** Read input from the file given by sqliterc_override.  Or if that
11807** parameter is NULL, take input from ~/.sqliterc
11808**
11809** Returns the number of errors.
11810*/
11811static void process_sqliterc(
11812  ShellState *p,                  /* Configuration data */
11813  const char *sqliterc_override   /* Name of config file. NULL to use default */
11814){
11815  char *home_dir = NULL;
11816  const char *sqliterc = sqliterc_override;
11817  char *zBuf = 0;
11818  FILE *inSaved = p->in;
11819  int savedLineno = p->lineno;
11820
11821  if (sqliterc == NULL) {
11822    home_dir = find_home_dir(0);
11823    if( home_dir==0 ){
11824      raw_printf(stderr, "-- warning: cannot find home directory;"
11825                      " cannot read ~/.sqliterc\n");
11826      return;
11827    }
11828    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11829    shell_check_oom(zBuf);
11830    sqliterc = zBuf;
11831  }
11832  p->in = fopen(sqliterc,"rb");
11833  if( p->in ){
11834    if( stdin_is_interactive ){
11835      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11836    }
11837    if( process_input(p) && bail_on_error ) exit(1);
11838    fclose(p->in);
11839  }else if( sqliterc_override!=0 ){
11840    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11841    if( bail_on_error ) exit(1);
11842  }
11843  p->in = inSaved;
11844  p->lineno = savedLineno;
11845  sqlite3_free(zBuf);
11846}
11847
11848/*
11849** Show available command line options
11850*/
11851static const char zOptions[] =
11852#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11853  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11854#endif
11855  "   -append              append the database to the end of the file\n"
11856  "   -ascii               set output mode to 'ascii'\n"
11857  "   -bail                stop after hitting an error\n"
11858  "   -batch               force batch I/O\n"
11859  "   -box                 set output mode to 'box'\n"
11860  "   -column              set output mode to 'column'\n"
11861  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11862  "   -csv                 set output mode to 'csv'\n"
11863#if !defined(SQLITE_OMIT_DESERIALIZE)
11864  "   -deserialize         open the database using sqlite3_deserialize()\n"
11865#endif
11866  "   -echo                print inputs before execution\n"
11867  "   -init FILENAME       read/process named file\n"
11868  "   -[no]header          turn headers on or off\n"
11869#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11870  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11871#endif
11872  "   -help                show this message\n"
11873  "   -html                set output mode to HTML\n"
11874  "   -interactive         force interactive I/O\n"
11875  "   -json                set output mode to 'json'\n"
11876  "   -line                set output mode to 'line'\n"
11877  "   -list                set output mode to 'list'\n"
11878  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11879  "   -markdown            set output mode to 'markdown'\n"
11880#if !defined(SQLITE_OMIT_DESERIALIZE)
11881  "   -maxsize N           maximum size for a --deserialize database\n"
11882#endif
11883  "   -memtrace            trace all memory allocations and deallocations\n"
11884  "   -mmap N              default mmap size set to N\n"
11885#ifdef SQLITE_ENABLE_MULTIPLEX
11886  "   -multiplex           enable the multiplexor VFS\n"
11887#endif
11888  "   -newline SEP         set output row separator. Default: '\\n'\n"
11889  "   -nofollow            refuse to open symbolic links to database files\n"
11890  "   -nonce STRING        set the safe-mode escape nonce\n"
11891  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11892  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11893  "   -quote               set output mode to 'quote'\n"
11894  "   -readonly            open the database read-only\n"
11895  "   -safe                enable safe-mode\n"
11896  "   -separator SEP       set output column separator. Default: '|'\n"
11897#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11898  "   -sorterref SIZE      sorter references threshold size\n"
11899#endif
11900  "   -stats               print memory stats before each finalize\n"
11901  "   -table               set output mode to 'table'\n"
11902  "   -tabs                set output mode to 'tabs'\n"
11903  "   -version             show SQLite version\n"
11904  "   -vfs NAME            use NAME as the default VFS\n"
11905#ifdef SQLITE_ENABLE_VFSTRACE
11906  "   -vfstrace            enable tracing of all VFS calls\n"
11907#endif
11908#ifdef SQLITE_HAVE_ZLIB
11909  "   -zip                 open the file as a ZIP Archive\n"
11910#endif
11911;
11912static void usage(int showDetail){
11913  utf8_printf(stderr,
11914      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11915      "FILENAME is the name of an SQLite database. A new database is created\n"
11916      "if the file does not previously exist.\n", Argv0);
11917  if( showDetail ){
11918    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11919  }else{
11920    raw_printf(stderr, "Use the -help option for additional information\n");
11921  }
11922  exit(1);
11923}
11924
11925/*
11926** Internal check:  Verify that the SQLite is uninitialized.  Print a
11927** error message if it is initialized.
11928*/
11929static void verify_uninitialized(void){
11930  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11931    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11932                        " initialization.\n");
11933  }
11934}
11935
11936/*
11937** Initialize the state information in data
11938*/
11939static void main_init(ShellState *data) {
11940  memset(data, 0, sizeof(*data));
11941  data->normalMode = data->cMode = data->mode = MODE_List;
11942  data->autoExplain = 1;
11943  data->pAuxDb = &data->aAuxDb[0];
11944  memcpy(data->colSeparator,SEP_Column, 2);
11945  memcpy(data->rowSeparator,SEP_Row, 2);
11946  data->showHeader = 0;
11947  data->shellFlgs = SHFLG_Lookaside;
11948  verify_uninitialized();
11949  sqlite3_config(SQLITE_CONFIG_URI, 1);
11950  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11951  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11952  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11953  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11954}
11955
11956/*
11957** Output text to the console in a font that attracts extra attention.
11958*/
11959#ifdef _WIN32
11960static void printBold(const char *zText){
11961#if !SQLITE_OS_WINRT
11962  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11963  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11964  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11965  SetConsoleTextAttribute(out,
11966         FOREGROUND_RED|FOREGROUND_INTENSITY
11967  );
11968#endif
11969  printf("%s", zText);
11970#if !SQLITE_OS_WINRT
11971  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11972#endif
11973}
11974#else
11975static void printBold(const char *zText){
11976  printf("\033[1m%s\033[0m", zText);
11977}
11978#endif
11979
11980/*
11981** Get the argument to an --option.  Throw an error and die if no argument
11982** is available.
11983*/
11984static char *cmdline_option_value(int argc, char **argv, int i){
11985  if( i==argc ){
11986    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11987            argv[0], argv[argc-1]);
11988    exit(1);
11989  }
11990  return argv[i];
11991}
11992
11993#ifndef SQLITE_SHELL_IS_UTF8
11994#  if (defined(_WIN32) || defined(WIN32)) \
11995   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11996#    define SQLITE_SHELL_IS_UTF8          (0)
11997#  else
11998#    define SQLITE_SHELL_IS_UTF8          (1)
11999#  endif
12000#endif
12001
12002#ifdef SQLITE_SHELL_FIDDLE
12003#  define main fiddle_main
12004#endif
12005
12006#if SQLITE_SHELL_IS_UTF8
12007int SQLITE_CDECL main(int argc, char **argv){
12008#else
12009int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12010  char **argv;
12011#endif
12012#ifdef SQLITE_DEBUG
12013  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
12014#endif
12015  char *zErrMsg = 0;
12016#ifdef SQLITE_SHELL_FIDDLE
12017#  define data shellState
12018#else
12019  ShellState data;
12020#endif
12021  const char *zInitFile = 0;
12022  int i;
12023  int rc = 0;
12024  int warnInmemoryDb = 0;
12025  int readStdin = 1;
12026  int nCmd = 0;
12027  char **azCmd = 0;
12028  const char *zVfs = 0;           /* Value of -vfs command-line option */
12029#if !SQLITE_SHELL_IS_UTF8
12030  char **argvToFree = 0;
12031  int argcToFree = 0;
12032#endif
12033
12034  setBinaryMode(stdin, 0);
12035  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12036#ifdef SQLITE_SHELL_FIDDLE
12037  stdin_is_interactive = 0;
12038  stdout_is_console = 1;
12039#else
12040  stdin_is_interactive = isatty(0);
12041  stdout_is_console = isatty(1);
12042#endif
12043
12044#if !defined(_WIN32_WCE)
12045  if( getenv("SQLITE_DEBUG_BREAK") ){
12046    if( isatty(0) && isatty(2) ){
12047      fprintf(stderr,
12048          "attach debugger to process %d and press any key to continue.\n",
12049          GETPID());
12050      fgetc(stdin);
12051    }else{
12052#if defined(_WIN32) || defined(WIN32)
12053#if SQLITE_OS_WINRT
12054      __debugbreak();
12055#else
12056      DebugBreak();
12057#endif
12058#elif defined(SIGTRAP)
12059      raise(SIGTRAP);
12060#endif
12061    }
12062  }
12063#endif
12064
12065#if USE_SYSTEM_SQLITE+0!=1
12066  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12067    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12068            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12069    exit(1);
12070  }
12071#endif
12072  main_init(&data);
12073
12074  /* On Windows, we must translate command-line arguments into UTF-8.
12075  ** The SQLite memory allocator subsystem has to be enabled in order to
12076  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12077  ** subsequent sqlite3_config() calls will work.  So copy all results into
12078  ** memory that does not come from the SQLite memory allocator.
12079  */
12080#if !SQLITE_SHELL_IS_UTF8
12081  sqlite3_initialize();
12082  argvToFree = malloc(sizeof(argv[0])*argc*2);
12083  shell_check_oom(argvToFree);
12084  argcToFree = argc;
12085  argv = argvToFree + argc;
12086  for(i=0; i<argc; i++){
12087    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12088    int n;
12089    shell_check_oom(z);
12090    n = (int)strlen(z);
12091    argv[i] = malloc( n+1 );
12092    shell_check_oom(argv[i]);
12093    memcpy(argv[i], z, n+1);
12094    argvToFree[i] = argv[i];
12095    sqlite3_free(z);
12096  }
12097  sqlite3_shutdown();
12098#endif
12099
12100  assert( argc>=1 && argv && argv[0] );
12101  Argv0 = argv[0];
12102
12103  /* Make sure we have a valid signal handler early, before anything
12104  ** else is done.
12105  */
12106#ifdef SIGINT
12107  signal(SIGINT, interrupt_handler);
12108#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12109  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12110#endif
12111
12112#ifdef SQLITE_SHELL_DBNAME_PROC
12113  {
12114    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12115    ** of a C-function that will provide the name of the database file.  Use
12116    ** this compile-time option to embed this shell program in larger
12117    ** applications. */
12118    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12119    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12120    warnInmemoryDb = 0;
12121  }
12122#endif
12123
12124  /* Do an initial pass through the command-line argument to locate
12125  ** the name of the database file, the name of the initialization file,
12126  ** the size of the alternative malloc heap,
12127  ** and the first command to execute.
12128  */
12129  verify_uninitialized();
12130  for(i=1; i<argc; i++){
12131    char *z;
12132    z = argv[i];
12133    if( z[0]!='-' ){
12134      if( data.aAuxDb->zDbFilename==0 ){
12135        data.aAuxDb->zDbFilename = z;
12136      }else{
12137        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12138        ** mean that nothing is read from stdin */
12139        readStdin = 0;
12140        nCmd++;
12141        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12142        shell_check_oom(azCmd);
12143        azCmd[nCmd-1] = z;
12144      }
12145    }
12146    if( z[1]=='-' ) z++;
12147    if( strcmp(z,"-separator")==0
12148     || strcmp(z,"-nullvalue")==0
12149     || strcmp(z,"-newline")==0
12150     || strcmp(z,"-cmd")==0
12151    ){
12152      (void)cmdline_option_value(argc, argv, ++i);
12153    }else if( strcmp(z,"-init")==0 ){
12154      zInitFile = cmdline_option_value(argc, argv, ++i);
12155    }else if( strcmp(z,"-batch")==0 ){
12156      /* Need to check for batch mode here to so we can avoid printing
12157      ** informational messages (like from process_sqliterc) before
12158      ** we do the actual processing of arguments later in a second pass.
12159      */
12160      stdin_is_interactive = 0;
12161    }else if( strcmp(z,"-heap")==0 ){
12162#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12163      const char *zSize;
12164      sqlite3_int64 szHeap;
12165
12166      zSize = cmdline_option_value(argc, argv, ++i);
12167      szHeap = integerValue(zSize);
12168      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12169      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12170#else
12171      (void)cmdline_option_value(argc, argv, ++i);
12172#endif
12173    }else if( strcmp(z,"-pagecache")==0 ){
12174      sqlite3_int64 n, sz;
12175      sz = integerValue(cmdline_option_value(argc,argv,++i));
12176      if( sz>70000 ) sz = 70000;
12177      if( sz<0 ) sz = 0;
12178      n = integerValue(cmdline_option_value(argc,argv,++i));
12179      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12180        n = 0xffffffffffffLL/sz;
12181      }
12182      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12183                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12184      data.shellFlgs |= SHFLG_Pagecache;
12185    }else if( strcmp(z,"-lookaside")==0 ){
12186      int n, sz;
12187      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12188      if( sz<0 ) sz = 0;
12189      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12190      if( n<0 ) n = 0;
12191      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12192      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12193    }else if( strcmp(z,"-threadsafe")==0 ){
12194      int n;
12195      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12196      switch( n ){
12197         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12198         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12199         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12200      }
12201#ifdef SQLITE_ENABLE_VFSTRACE
12202    }else if( strcmp(z,"-vfstrace")==0 ){
12203      extern int vfstrace_register(
12204         const char *zTraceName,
12205         const char *zOldVfsName,
12206         int (*xOut)(const char*,void*),
12207         void *pOutArg,
12208         int makeDefault
12209      );
12210      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12211#endif
12212#ifdef SQLITE_ENABLE_MULTIPLEX
12213    }else if( strcmp(z,"-multiplex")==0 ){
12214      extern int sqlite3_multiple_initialize(const char*,int);
12215      sqlite3_multiplex_initialize(0, 1);
12216#endif
12217    }else if( strcmp(z,"-mmap")==0 ){
12218      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12219      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12220#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12221    }else if( strcmp(z,"-sorterref")==0 ){
12222      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12223      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12224#endif
12225    }else if( strcmp(z,"-vfs")==0 ){
12226      zVfs = cmdline_option_value(argc, argv, ++i);
12227#ifdef SQLITE_HAVE_ZLIB
12228    }else if( strcmp(z,"-zip")==0 ){
12229      data.openMode = SHELL_OPEN_ZIPFILE;
12230#endif
12231    }else if( strcmp(z,"-append")==0 ){
12232      data.openMode = SHELL_OPEN_APPENDVFS;
12233#ifndef SQLITE_OMIT_DESERIALIZE
12234    }else if( strcmp(z,"-deserialize")==0 ){
12235      data.openMode = SHELL_OPEN_DESERIALIZE;
12236    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12237      data.szMax = integerValue(argv[++i]);
12238#endif
12239    }else if( strcmp(z,"-readonly")==0 ){
12240      data.openMode = SHELL_OPEN_READONLY;
12241    }else if( strcmp(z,"-nofollow")==0 ){
12242      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12243#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12244    }else if( strncmp(z, "-A",2)==0 ){
12245      /* All remaining command-line arguments are passed to the ".archive"
12246      ** command, so ignore them */
12247      break;
12248#endif
12249    }else if( strcmp(z, "-memtrace")==0 ){
12250      sqlite3MemTraceActivate(stderr);
12251    }else if( strcmp(z,"-bail")==0 ){
12252      bail_on_error = 1;
12253    }else if( strcmp(z,"-nonce")==0 ){
12254      free(data.zNonce);
12255      data.zNonce = strdup(argv[++i]);
12256    }else if( strcmp(z,"-safe")==0 ){
12257      /* no-op - catch this on the second pass */
12258    }
12259  }
12260  verify_uninitialized();
12261
12262
12263#ifdef SQLITE_SHELL_INIT_PROC
12264  {
12265    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12266    ** of a C-function that will perform initialization actions on SQLite that
12267    ** occur just before or after sqlite3_initialize(). Use this compile-time
12268    ** option to embed this shell program in larger applications. */
12269    extern void SQLITE_SHELL_INIT_PROC(void);
12270    SQLITE_SHELL_INIT_PROC();
12271  }
12272#else
12273  /* All the sqlite3_config() calls have now been made. So it is safe
12274  ** to call sqlite3_initialize() and process any command line -vfs option. */
12275  sqlite3_initialize();
12276#endif
12277
12278  if( zVfs ){
12279    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12280    if( pVfs ){
12281      sqlite3_vfs_register(pVfs, 1);
12282    }else{
12283      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12284      exit(1);
12285    }
12286  }
12287
12288  if( data.pAuxDb->zDbFilename==0 ){
12289#ifndef SQLITE_OMIT_MEMORYDB
12290    data.pAuxDb->zDbFilename = ":memory:";
12291    warnInmemoryDb = argc==1;
12292#else
12293    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12294    return 1;
12295#endif
12296  }
12297  data.out = stdout;
12298#ifndef SQLITE_SHELL_FIDDLE
12299  sqlite3_appendvfs_init(0,0,0);
12300#endif
12301
12302  /* Go ahead and open the database file if it already exists.  If the
12303  ** file does not exist, delay opening it.  This prevents empty database
12304  ** files from being created if a user mistypes the database name argument
12305  ** to the sqlite command-line tool.
12306  */
12307  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12308    open_db(&data, 0);
12309  }
12310
12311  /* Process the initialization file if there is one.  If no -init option
12312  ** is given on the command line, look for a file named ~/.sqliterc and
12313  ** try to process it.
12314  */
12315  process_sqliterc(&data,zInitFile);
12316
12317  /* Make a second pass through the command-line argument and set
12318  ** options.  This second pass is delayed until after the initialization
12319  ** file is processed so that the command-line arguments will override
12320  ** settings in the initialization file.
12321  */
12322  for(i=1; i<argc; i++){
12323    char *z = argv[i];
12324    if( z[0]!='-' ) continue;
12325    if( z[1]=='-' ){ z++; }
12326    if( strcmp(z,"-init")==0 ){
12327      i++;
12328    }else if( strcmp(z,"-html")==0 ){
12329      data.mode = MODE_Html;
12330    }else if( strcmp(z,"-list")==0 ){
12331      data.mode = MODE_List;
12332    }else if( strcmp(z,"-quote")==0 ){
12333      data.mode = MODE_Quote;
12334      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12335      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12336    }else if( strcmp(z,"-line")==0 ){
12337      data.mode = MODE_Line;
12338    }else if( strcmp(z,"-column")==0 ){
12339      data.mode = MODE_Column;
12340    }else if( strcmp(z,"-json")==0 ){
12341      data.mode = MODE_Json;
12342    }else if( strcmp(z,"-markdown")==0 ){
12343      data.mode = MODE_Markdown;
12344    }else if( strcmp(z,"-table")==0 ){
12345      data.mode = MODE_Table;
12346    }else if( strcmp(z,"-box")==0 ){
12347      data.mode = MODE_Box;
12348    }else if( strcmp(z,"-csv")==0 ){
12349      data.mode = MODE_Csv;
12350      memcpy(data.colSeparator,",",2);
12351#ifdef SQLITE_HAVE_ZLIB
12352    }else if( strcmp(z,"-zip")==0 ){
12353      data.openMode = SHELL_OPEN_ZIPFILE;
12354#endif
12355    }else if( strcmp(z,"-append")==0 ){
12356      data.openMode = SHELL_OPEN_APPENDVFS;
12357#ifndef SQLITE_OMIT_DESERIALIZE
12358    }else if( strcmp(z,"-deserialize")==0 ){
12359      data.openMode = SHELL_OPEN_DESERIALIZE;
12360    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12361      data.szMax = integerValue(argv[++i]);
12362#endif
12363    }else if( strcmp(z,"-readonly")==0 ){
12364      data.openMode = SHELL_OPEN_READONLY;
12365    }else if( strcmp(z,"-nofollow")==0 ){
12366      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12367    }else if( strcmp(z,"-ascii")==0 ){
12368      data.mode = MODE_Ascii;
12369      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12370      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12371    }else if( strcmp(z,"-tabs")==0 ){
12372      data.mode = MODE_List;
12373      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12374      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12375    }else if( strcmp(z,"-separator")==0 ){
12376      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12377                       "%s",cmdline_option_value(argc,argv,++i));
12378    }else if( strcmp(z,"-newline")==0 ){
12379      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12380                       "%s",cmdline_option_value(argc,argv,++i));
12381    }else if( strcmp(z,"-nullvalue")==0 ){
12382      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12383                       "%s",cmdline_option_value(argc,argv,++i));
12384    }else if( strcmp(z,"-header")==0 ){
12385      data.showHeader = 1;
12386      ShellSetFlag(&data, SHFLG_HeaderSet);
12387     }else if( strcmp(z,"-noheader")==0 ){
12388      data.showHeader = 0;
12389      ShellSetFlag(&data, SHFLG_HeaderSet);
12390    }else if( strcmp(z,"-echo")==0 ){
12391      ShellSetFlag(&data, SHFLG_Echo);
12392    }else if( strcmp(z,"-eqp")==0 ){
12393      data.autoEQP = AUTOEQP_on;
12394    }else if( strcmp(z,"-eqpfull")==0 ){
12395      data.autoEQP = AUTOEQP_full;
12396    }else if( strcmp(z,"-stats")==0 ){
12397      data.statsOn = 1;
12398    }else if( strcmp(z,"-scanstats")==0 ){
12399      data.scanstatsOn = 1;
12400    }else if( strcmp(z,"-backslash")==0 ){
12401      /* Undocumented command-line option: -backslash
12402      ** Causes C-style backslash escapes to be evaluated in SQL statements
12403      ** prior to sending the SQL into SQLite.  Useful for injecting
12404      ** crazy bytes in the middle of SQL statements for testing and debugging.
12405      */
12406      ShellSetFlag(&data, SHFLG_Backslash);
12407    }else if( strcmp(z,"-bail")==0 ){
12408      /* No-op.  The bail_on_error flag should already be set. */
12409    }else if( strcmp(z,"-version")==0 ){
12410      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12411      return 0;
12412    }else if( strcmp(z,"-interactive")==0 ){
12413      stdin_is_interactive = 1;
12414    }else if( strcmp(z,"-batch")==0 ){
12415      stdin_is_interactive = 0;
12416    }else if( strcmp(z,"-heap")==0 ){
12417      i++;
12418    }else if( strcmp(z,"-pagecache")==0 ){
12419      i+=2;
12420    }else if( strcmp(z,"-lookaside")==0 ){
12421      i+=2;
12422    }else if( strcmp(z,"-threadsafe")==0 ){
12423      i+=2;
12424    }else if( strcmp(z,"-nonce")==0 ){
12425      i += 2;
12426    }else if( strcmp(z,"-mmap")==0 ){
12427      i++;
12428    }else if( strcmp(z,"-memtrace")==0 ){
12429      i++;
12430#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12431    }else if( strcmp(z,"-sorterref")==0 ){
12432      i++;
12433#endif
12434    }else if( strcmp(z,"-vfs")==0 ){
12435      i++;
12436#ifdef SQLITE_ENABLE_VFSTRACE
12437    }else if( strcmp(z,"-vfstrace")==0 ){
12438      i++;
12439#endif
12440#ifdef SQLITE_ENABLE_MULTIPLEX
12441    }else if( strcmp(z,"-multiplex")==0 ){
12442      i++;
12443#endif
12444    }else if( strcmp(z,"-help")==0 ){
12445      usage(1);
12446    }else if( strcmp(z,"-cmd")==0 ){
12447      /* Run commands that follow -cmd first and separately from commands
12448      ** that simply appear on the command-line.  This seems goofy.  It would
12449      ** be better if all commands ran in the order that they appear.  But
12450      ** we retain the goofy behavior for historical compatibility. */
12451      if( i==argc-1 ) break;
12452      z = cmdline_option_value(argc,argv,++i);
12453      if( z[0]=='.' ){
12454        rc = do_meta_command(z, &data);
12455        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12456      }else{
12457        open_db(&data, 0);
12458        rc = shell_exec(&data, z, &zErrMsg);
12459        if( zErrMsg!=0 ){
12460          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12461          if( bail_on_error ) return rc!=0 ? rc : 1;
12462        }else if( rc!=0 ){
12463          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12464          if( bail_on_error ) return rc;
12465        }
12466      }
12467#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12468    }else if( strncmp(z, "-A", 2)==0 ){
12469      if( nCmd>0 ){
12470        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12471                            " with \"%s\"\n", z);
12472        return 1;
12473      }
12474      open_db(&data, OPEN_DB_ZIPFILE);
12475      if( z[2] ){
12476        argv[i] = &z[2];
12477        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12478      }else{
12479        arDotCommand(&data, 1, argv+i, argc-i);
12480      }
12481      readStdin = 0;
12482      break;
12483#endif
12484    }else if( strcmp(z,"-safe")==0 ){
12485      data.bSafeMode = data.bSafeModePersist = 1;
12486    }else{
12487      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12488      raw_printf(stderr,"Use -help for a list of options.\n");
12489      return 1;
12490    }
12491    data.cMode = data.mode;
12492  }
12493
12494  if( !readStdin ){
12495    /* Run all arguments that do not begin with '-' as if they were separate
12496    ** command-line inputs, except for the argToSkip argument which contains
12497    ** the database filename.
12498    */
12499    for(i=0; i<nCmd; i++){
12500      if( azCmd[i][0]=='.' ){
12501        rc = do_meta_command(azCmd[i], &data);
12502        if( rc ){
12503          free(azCmd);
12504          return rc==2 ? 0 : rc;
12505        }
12506      }else{
12507        open_db(&data, 0);
12508        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12509        if( zErrMsg || rc ){
12510          if( zErrMsg!=0 ){
12511            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12512          }else{
12513            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12514          }
12515          sqlite3_free(zErrMsg);
12516          free(azCmd);
12517          return rc!=0 ? rc : 1;
12518        }
12519      }
12520    }
12521  }else{
12522    /* Run commands received from standard input
12523    */
12524    if( stdin_is_interactive ){
12525      char *zHome;
12526      char *zHistory;
12527      int nHistory;
12528      printf(
12529        "SQLite version %s %.19s\n" /*extra-version-info*/
12530        "Enter \".help\" for usage hints.\n",
12531        sqlite3_libversion(), sqlite3_sourceid()
12532      );
12533      if( warnInmemoryDb ){
12534        printf("Connected to a ");
12535        printBold("transient in-memory database");
12536        printf(".\nUse \".open FILENAME\" to reopen on a "
12537               "persistent database.\n");
12538      }
12539      zHistory = getenv("SQLITE_HISTORY");
12540      if( zHistory ){
12541        zHistory = strdup(zHistory);
12542      }else if( (zHome = find_home_dir(0))!=0 ){
12543        nHistory = strlen30(zHome) + 20;
12544        if( (zHistory = malloc(nHistory))!=0 ){
12545          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12546        }
12547      }
12548      if( zHistory ){ shell_read_history(zHistory); }
12549#if HAVE_READLINE || HAVE_EDITLINE
12550      rl_attempted_completion_function = readline_completion;
12551#elif HAVE_LINENOISE
12552      linenoiseSetCompletionCallback(linenoise_completion);
12553#endif
12554      data.in = 0;
12555      rc = process_input(&data);
12556      if( zHistory ){
12557        shell_stifle_history(2000);
12558        shell_write_history(zHistory);
12559        free(zHistory);
12560      }
12561    }else{
12562      data.in = stdin;
12563      rc = process_input(&data);
12564    }
12565  }
12566#ifndef SQLITE_SHELL_FIDDLE
12567  /* In WASM mode we have to leave the db state in place so that
12568  ** client code can "push" SQL into it after this call returns. */
12569  free(azCmd);
12570  set_table_name(&data, 0);
12571  if( data.db ){
12572    session_close_all(&data, -1);
12573    close_db(data.db);
12574  }
12575  for(i=0; i<ArraySize(data.aAuxDb); i++){
12576    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12577    if( data.aAuxDb[i].db ){
12578      session_close_all(&data, i);
12579      close_db(data.aAuxDb[i].db);
12580    }
12581  }
12582  find_home_dir(1);
12583  output_reset(&data);
12584  data.doXdgOpen = 0;
12585  clearTempFile(&data);
12586#if !SQLITE_SHELL_IS_UTF8
12587  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12588  free(argvToFree);
12589#endif
12590  free(data.colWidth);
12591  free(data.zNonce);
12592  /* Clear the global data structure so that valgrind will detect memory
12593  ** leaks */
12594  memset(&data, 0, sizeof(data));
12595#ifdef SQLITE_DEBUG
12596  if( sqlite3_memory_used()>mem_main_enter ){
12597    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12598                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12599  }
12600#endif
12601#endif /* !SQLITE_SHELL_FIDDLE */
12602  return rc;
12603}
12604
12605
12606#ifdef SQLITE_SHELL_FIDDLE
12607/* Only for emcc experimentation purposes. */
12608int fiddle_experiment(int a,int b){
12609   return a + b;
12610}
12611
12612/* Only for emcc experimentation purposes.
12613
12614  Define this function in JS using:
12615
12616  emcc ... --js-library somefile.js
12617
12618  containing:
12619
12620mergeInto(LibraryManager.library, {
12621    my_foo: function(){
12622        console.debug("my_foo()",arguments);
12623    }
12624});
12625*/
12626/*extern void my_foo(sqlite3 *);*/
12627/* Only for emcc experimentation purposes. */
12628sqlite3 * fiddle_the_db(){
12629    printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12630    /*my_foo(globalDb);*/
12631    return globalDb;
12632}
12633/* Only for emcc experimentation purposes. */
12634sqlite3 * fiddle_db_arg(sqlite3 *arg){
12635    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12636    return arg;
12637}
12638
12639/*
12640** Intended to be called via a SharedWorker() while a separate
12641** SharedWorker() (which manages the wasm module) is performing work
12642** which should be interrupted. Unfortunately, SharedWorker is not
12643** portable enough to make real use of.
12644*/
12645void fiddle_interrupt(void){
12646  if(globalDb) sqlite3_interrupt(globalDb);
12647}
12648
12649/*
12650** Returns the filename of the given db name, assuming "main" if
12651** zDbName is NULL. Returns NULL if globalDb is not opened.
12652*/
12653const char * fiddle_db_filename(const char * zDbName){
12654    return globalDb
12655      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12656      : NULL;
12657}
12658
12659/*
12660** Closes, unlinks, and reopens the db using its current filename (or
12661** the default if the db is currently closed). It is assumed, for
12662** purposes of the fiddle build, that the file is in a transient
12663** virtual filesystem within the browser.
12664*/
12665void fiddle_reset_db(void){
12666  char *zFilename = 0;
12667  if(0==globalDb){
12668    shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12669  }else{
12670    zFilename =
12671      sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12672    shell_check_oom(zFilename);
12673    close_db(globalDb);
12674    shellDeleteFile(zFilename);
12675    shellState.db = 0;
12676    shellState.pAuxDb->zDbFilename = zFilename;
12677  }
12678  open_db(&shellState, 0);
12679  sqlite3_free(zFilename);
12680}
12681
12682/*
12683** Trivial exportable function for emscripten. Needs to be exported using:
12684**
12685** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12686**
12687** (Note the underscore before the function name.) It processes zSql
12688** as if it were input to the sqlite3 shell and redirects all output
12689** to the wasm binding.
12690*/
12691void fiddle_exec(const char * zSql){
12692  static int once = 0;
12693  int rc = 0;
12694  if(!once){
12695    /* Simulate an argv array for main() */
12696    static char * argv[] = {"fiddle",
12697                            "-bail",
12698                            "-safe"};
12699    rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12700    once = rc ? -1 : 1;
12701    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12702    printf(
12703        "SQLite version %s %.19s\n" /*extra-version-info*/,
12704        sqlite3_libversion(), sqlite3_sourceid()
12705    );
12706    puts("WASM shell");
12707    puts("Enter \".help\" for usage hints.");
12708    if(once>0){
12709      fiddle_reset_db();
12710    }
12711    if(shellState.db){
12712      printf("Connected to %s.\n", fiddle_db_filename(NULL));
12713    }else{
12714      fprintf(stderr,"ERROR initializing db!\n");
12715      return;
12716    }
12717  }
12718  if(once<0){
12719    puts("DB init failed. Not executing SQL.");
12720  }else if(zSql && *zSql){
12721    shellState.wasm.zInput = zSql;
12722    shellState.wasm.zPos = zSql;
12723    process_input(&shellState);
12724    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12725  }
12726}
12727#endif /* SQLITE_SHELL_FIDDLE */
12728