xref: /sqlite-3.40.0/src/shell.c.in (revision d85d0839)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26# define SHELL_STRINGIFY_(f) #f
27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28#ifdef SQLITE_CUSTOM_INCLUDE
29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
42** somewhat for use as a WASM module in a web browser. This flag
43** should only be used when building the "fiddle" web application, as
44** the browser-mode build has much different user input requirements
45** and this build mode rewires the user input subsystem to account for
46** that.
47*/
48
49/*
50** Warning pragmas copied from msvc.h in the core.
51*/
52#if defined(_MSC_VER)
53#pragma warning(disable : 4054)
54#pragma warning(disable : 4055)
55#pragma warning(disable : 4100)
56#pragma warning(disable : 4127)
57#pragma warning(disable : 4130)
58#pragma warning(disable : 4152)
59#pragma warning(disable : 4189)
60#pragma warning(disable : 4206)
61#pragma warning(disable : 4210)
62#pragma warning(disable : 4232)
63#pragma warning(disable : 4244)
64#pragma warning(disable : 4305)
65#pragma warning(disable : 4306)
66#pragma warning(disable : 4702)
67#pragma warning(disable : 4706)
68#endif /* defined(_MSC_VER) */
69
70/*
71** No support for loadable extensions in VxWorks.
72*/
73#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
74# define SQLITE_OMIT_LOAD_EXTENSION 1
75#endif
76
77/*
78** Enable large-file support for fopen() and friends on unix.
79*/
80#ifndef SQLITE_DISABLE_LFS
81# define _LARGE_FILE       1
82# ifndef _FILE_OFFSET_BITS
83#   define _FILE_OFFSET_BITS 64
84# endif
85# define _LARGEFILE_SOURCE 1
86#endif
87
88#if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
89/*
90** emcc requires _POSIX_SOURCE (or one of several similar defines)
91** to expose strdup().
92*/
93# define _POSIX_SOURCE
94#endif
95
96#include <stdlib.h>
97#include <string.h>
98#include <stdio.h>
99#include <assert.h>
100#include "sqlite3.h"
101typedef sqlite3_int64 i64;
102typedef sqlite3_uint64 u64;
103typedef unsigned char u8;
104#if SQLITE_USER_AUTHENTICATION
105# include "sqlite3userauth.h"
106#endif
107#include <ctype.h>
108#include <stdarg.h>
109
110#if !defined(_WIN32) && !defined(WIN32)
111# include <signal.h>
112# if !defined(__RTP__) && !defined(_WRS_KERNEL)
113#  include <pwd.h>
114# endif
115#endif
116#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
117# include <unistd.h>
118# include <dirent.h>
119# define GETPID getpid
120# if defined(__MINGW32__)
121#  define DIRENT dirent
122#  ifndef S_ISLNK
123#   define S_ISLNK(mode) (0)
124#  endif
125# endif
126#else
127# define GETPID (int)GetCurrentProcessId
128#endif
129#include <sys/types.h>
130#include <sys/stat.h>
131
132#if HAVE_READLINE
133# include <readline/readline.h>
134# include <readline/history.h>
135#endif
136
137#if HAVE_EDITLINE
138# include <editline/readline.h>
139#endif
140
141#if HAVE_EDITLINE || HAVE_READLINE
142
143# define shell_add_history(X) add_history(X)
144# define shell_read_history(X) read_history(X)
145# define shell_write_history(X) write_history(X)
146# define shell_stifle_history(X) stifle_history(X)
147# define shell_readline(X) readline(X)
148
149#elif HAVE_LINENOISE
150
151# include "linenoise.h"
152# define shell_add_history(X) linenoiseHistoryAdd(X)
153# define shell_read_history(X) linenoiseHistoryLoad(X)
154# define shell_write_history(X) linenoiseHistorySave(X)
155# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
156# define shell_readline(X) linenoise(X)
157
158#else
159
160# define shell_read_history(X)
161# define shell_write_history(X)
162# define shell_stifle_history(X)
163
164# define SHELL_USE_LOCAL_GETLINE 1
165#endif
166
167
168#if defined(_WIN32) || defined(WIN32)
169# if SQLITE_OS_WINRT
170#  define SQLITE_OMIT_POPEN 1
171# else
172#  include <io.h>
173#  include <fcntl.h>
174#  define isatty(h) _isatty(h)
175#  ifndef access
176#   define access(f,m) _access((f),(m))
177#  endif
178#  ifndef unlink
179#   define unlink _unlink
180#  endif
181#  ifndef strdup
182#   define strdup _strdup
183#  endif
184#  undef popen
185#  define popen _popen
186#  undef pclose
187#  define pclose _pclose
188# endif
189#else
190 /* Make sure isatty() has a prototype. */
191 extern int isatty(int);
192
193# if !defined(__RTP__) && !defined(_WRS_KERNEL)
194  /* popen and pclose are not C89 functions and so are
195  ** sometimes omitted from the <stdio.h> header */
196   extern FILE *popen(const char*,const char*);
197   extern int pclose(FILE*);
198# else
199#  define SQLITE_OMIT_POPEN 1
200# endif
201#endif
202
203#if defined(_WIN32_WCE)
204/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
205 * thus we always assume that we have a console. That can be
206 * overridden with the -batch command line option.
207 */
208#define isatty(x) 1
209#endif
210
211/* ctype macros that work with signed characters */
212#define IsSpace(X)  isspace((unsigned char)X)
213#define IsDigit(X)  isdigit((unsigned char)X)
214#define ToLower(X)  (char)tolower((unsigned char)X)
215
216#if defined(_WIN32) || defined(WIN32)
217#if SQLITE_OS_WINRT
218#include <intrin.h>
219#endif
220#include <windows.h>
221
222/* string conversion routines only needed on Win32 */
223extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
224extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
225extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
226extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
227#endif
228
229/* On Windows, we normally run with output mode of TEXT so that \n characters
230** are automatically translated into \r\n.  However, this behavior needs
231** to be disabled in some cases (ex: when generating CSV output and when
232** rendering quoted strings that contain \n characters).  The following
233** routines take care of that.
234*/
235#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
236static void setBinaryMode(FILE *file, int isOutput){
237  if( isOutput ) fflush(file);
238  _setmode(_fileno(file), _O_BINARY);
239}
240static void setTextMode(FILE *file, int isOutput){
241  if( isOutput ) fflush(file);
242  _setmode(_fileno(file), _O_TEXT);
243}
244#else
245# define setBinaryMode(X,Y)
246# define setTextMode(X,Y)
247#endif
248
249/* True if the timer is enabled */
250static int enableTimer = 0;
251
252/* Return the current wall-clock time */
253static sqlite3_int64 timeOfDay(void){
254  static sqlite3_vfs *clockVfs = 0;
255  sqlite3_int64 t;
256  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
257  if( clockVfs==0 ) return 0;  /* Never actually happens */
258  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
259    clockVfs->xCurrentTimeInt64(clockVfs, &t);
260  }else{
261    double r;
262    clockVfs->xCurrentTime(clockVfs, &r);
263    t = (sqlite3_int64)(r*86400000.0);
264  }
265  return t;
266}
267
268#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
269#include <sys/time.h>
270#include <sys/resource.h>
271
272/* VxWorks does not support getrusage() as far as we can determine */
273#if defined(_WRS_KERNEL) || defined(__RTP__)
274struct rusage {
275  struct timeval ru_utime; /* user CPU time used */
276  struct timeval ru_stime; /* system CPU time used */
277};
278#define getrusage(A,B) memset(B,0,sizeof(*B))
279#endif
280
281/* Saved resource information for the beginning of an operation */
282static struct rusage sBegin;  /* CPU time at start */
283static sqlite3_int64 iBegin;  /* Wall-clock time at start */
284
285/*
286** Begin timing an operation
287*/
288static void beginTimer(void){
289  if( enableTimer ){
290    getrusage(RUSAGE_SELF, &sBegin);
291    iBegin = timeOfDay();
292  }
293}
294
295/* Return the difference of two time_structs in seconds */
296static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
297  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
298         (double)(pEnd->tv_sec - pStart->tv_sec);
299}
300
301/*
302** Print the timing results.
303*/
304static void endTimer(void){
305  if( enableTimer ){
306    sqlite3_int64 iEnd = timeOfDay();
307    struct rusage sEnd;
308    getrusage(RUSAGE_SELF, &sEnd);
309    printf("Run Time: real %.3f user %f sys %f\n",
310       (iEnd - iBegin)*0.001,
311       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
312       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
313  }
314}
315
316#define BEGIN_TIMER beginTimer()
317#define END_TIMER endTimer()
318#define HAS_TIMER 1
319
320#elif (defined(_WIN32) || defined(WIN32))
321
322/* Saved resource information for the beginning of an operation */
323static HANDLE hProcess;
324static FILETIME ftKernelBegin;
325static FILETIME ftUserBegin;
326static sqlite3_int64 ftWallBegin;
327typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
328                                    LPFILETIME, LPFILETIME);
329static GETPROCTIMES getProcessTimesAddr = NULL;
330
331/*
332** Check to see if we have timer support.  Return 1 if necessary
333** support found (or found previously).
334*/
335static int hasTimer(void){
336  if( getProcessTimesAddr ){
337    return 1;
338  } else {
339#if !SQLITE_OS_WINRT
340    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
341    ** versions. See if the version we are running on has it, and if it
342    ** does, save off a pointer to it and the current process handle.
343    */
344    hProcess = GetCurrentProcess();
345    if( hProcess ){
346      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
347      if( NULL != hinstLib ){
348        getProcessTimesAddr =
349            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
350        if( NULL != getProcessTimesAddr ){
351          return 1;
352        }
353        FreeLibrary(hinstLib);
354      }
355    }
356#endif
357  }
358  return 0;
359}
360
361/*
362** Begin timing an operation
363*/
364static void beginTimer(void){
365  if( enableTimer && getProcessTimesAddr ){
366    FILETIME ftCreation, ftExit;
367    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
368                        &ftKernelBegin,&ftUserBegin);
369    ftWallBegin = timeOfDay();
370  }
371}
372
373/* Return the difference of two FILETIME structs in seconds */
374static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
375  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
376  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
377  return (double) ((i64End - i64Start) / 10000000.0);
378}
379
380/*
381** Print the timing results.
382*/
383static void endTimer(void){
384  if( enableTimer && getProcessTimesAddr){
385    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
386    sqlite3_int64 ftWallEnd = timeOfDay();
387    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
388    printf("Run Time: real %.3f user %f sys %f\n",
389       (ftWallEnd - ftWallBegin)*0.001,
390       timeDiff(&ftUserBegin, &ftUserEnd),
391       timeDiff(&ftKernelBegin, &ftKernelEnd));
392  }
393}
394
395#define BEGIN_TIMER beginTimer()
396#define END_TIMER endTimer()
397#define HAS_TIMER hasTimer()
398
399#else
400#define BEGIN_TIMER
401#define END_TIMER
402#define HAS_TIMER 0
403#endif
404
405/*
406** Used to prevent warnings about unused parameters
407*/
408#define UNUSED_PARAMETER(x) (void)(x)
409
410/*
411** Number of elements in an array
412*/
413#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
414
415/*
416** If the following flag is set, then command execution stops
417** at an error if we are not interactive.
418*/
419static int bail_on_error = 0;
420
421/*
422** Threat stdin as an interactive input if the following variable
423** is true.  Otherwise, assume stdin is connected to a file or pipe.
424*/
425static int stdin_is_interactive = 1;
426
427/*
428** On Windows systems we have to know if standard output is a console
429** in order to translate UTF-8 into MBCS.  The following variable is
430** true if translation is required.
431*/
432static int stdout_is_console = 1;
433
434/*
435** The following is the open SQLite database.  We make a pointer
436** to this database a static variable so that it can be accessed
437** by the SIGINT handler to interrupt database processing.
438*/
439static sqlite3 *globalDb = 0;
440
441/*
442** True if an interrupt (Control-C) has been received.
443*/
444static volatile int seenInterrupt = 0;
445
446/*
447** This is the name of our program. It is set in main(), used
448** in a number of other places, mostly for error messages.
449*/
450static char *Argv0;
451
452/*
453** Prompt strings. Initialized in main. Settable with
454**   .prompt main continue
455*/
456static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
457static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
458
459/*
460** Render output like fprintf().  Except, if the output is going to the
461** console and if this is running on a Windows machine, translate the
462** output from UTF-8 into MBCS.
463*/
464#if defined(_WIN32) || defined(WIN32)
465void utf8_printf(FILE *out, const char *zFormat, ...){
466  va_list ap;
467  va_start(ap, zFormat);
468  if( stdout_is_console && (out==stdout || out==stderr) ){
469    char *z1 = sqlite3_vmprintf(zFormat, ap);
470    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
471    sqlite3_free(z1);
472    fputs(z2, out);
473    sqlite3_free(z2);
474  }else{
475    vfprintf(out, zFormat, ap);
476  }
477  va_end(ap);
478}
479#elif !defined(utf8_printf)
480# define utf8_printf fprintf
481#endif
482
483/*
484** Render output like fprintf().  This should not be used on anything that
485** includes string formatting (e.g. "%s").
486*/
487#if !defined(raw_printf)
488# define raw_printf fprintf
489#endif
490
491/* Indicate out-of-memory and exit. */
492static void shell_out_of_memory(void){
493  raw_printf(stderr,"Error: out of memory\n");
494  exit(1);
495}
496
497/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
498** out-of-memory error.
499*/
500static void shell_check_oom(void *p){
501  if( p==0 ) shell_out_of_memory();
502}
503
504/*
505** Write I/O traces to the following stream.
506*/
507#ifdef SQLITE_ENABLE_IOTRACE
508static FILE *iotrace = 0;
509#endif
510
511/*
512** This routine works like printf in that its first argument is a
513** format string and subsequent arguments are values to be substituted
514** in place of % fields.  The result of formatting this string
515** is written to iotrace.
516*/
517#ifdef SQLITE_ENABLE_IOTRACE
518static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
519  va_list ap;
520  char *z;
521  if( iotrace==0 ) return;
522  va_start(ap, zFormat);
523  z = sqlite3_vmprintf(zFormat, ap);
524  va_end(ap);
525  utf8_printf(iotrace, "%s", z);
526  sqlite3_free(z);
527}
528#endif
529
530/*
531** Output string zUtf to stream pOut as w characters.  If w is negative,
532** then right-justify the text.  W is the width in UTF-8 characters, not
533** in bytes.  This is different from the %*.*s specification in printf
534** since with %*.*s the width is measured in bytes, not characters.
535*/
536static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
537  int i;
538  int n;
539  int aw = w<0 ? -w : w;
540  for(i=n=0; zUtf[i]; i++){
541    if( (zUtf[i]&0xc0)!=0x80 ){
542      n++;
543      if( n==aw ){
544        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
545        break;
546      }
547    }
548  }
549  if( n>=aw ){
550    utf8_printf(pOut, "%.*s", i, zUtf);
551  }else if( w<0 ){
552    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
553  }else{
554    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
555  }
556}
557
558
559/*
560** Determines if a string is a number of not.
561*/
562static int isNumber(const char *z, int *realnum){
563  if( *z=='-' || *z=='+' ) z++;
564  if( !IsDigit(*z) ){
565    return 0;
566  }
567  z++;
568  if( realnum ) *realnum = 0;
569  while( IsDigit(*z) ){ z++; }
570  if( *z=='.' ){
571    z++;
572    if( !IsDigit(*z) ) return 0;
573    while( IsDigit(*z) ){ z++; }
574    if( realnum ) *realnum = 1;
575  }
576  if( *z=='e' || *z=='E' ){
577    z++;
578    if( *z=='+' || *z=='-' ) z++;
579    if( !IsDigit(*z) ) return 0;
580    while( IsDigit(*z) ){ z++; }
581    if( realnum ) *realnum = 1;
582  }
583  return *z==0;
584}
585
586/*
587** Compute a string length that is limited to what can be stored in
588** lower 30 bits of a 32-bit signed integer.
589*/
590static int strlen30(const char *z){
591  const char *z2 = z;
592  while( *z2 ){ z2++; }
593  return 0x3fffffff & (int)(z2 - z);
594}
595
596/*
597** Return the length of a string in characters.  Multibyte UTF8 characters
598** count as a single character.
599*/
600static int strlenChar(const char *z){
601  int n = 0;
602  while( *z ){
603    if( (0xc0&*(z++))!=0x80 ) n++;
604  }
605  return n;
606}
607
608/*
609** Return open FILE * if zFile exists, can be opened for read
610** and is an ordinary file or a character stream source.
611** Otherwise return 0.
612*/
613static FILE * openChrSource(const char *zFile){
614#ifdef _WIN32
615  struct _stat x = {0};
616# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
617  /* On Windows, open first, then check the stream nature. This order
618  ** is necessary because _stat() and sibs, when checking a named pipe,
619  ** effectively break the pipe as its supplier sees it. */
620  FILE *rv = fopen(zFile, "rb");
621  if( rv==0 ) return 0;
622  if( _fstat(_fileno(rv), &x) != 0
623      || !STAT_CHR_SRC(x.st_mode)){
624    fclose(rv);
625    rv = 0;
626  }
627  return rv;
628#else
629  struct stat x = {0};
630  int rc = stat(zFile, &x);
631# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
632  if( rc!=0 ) return 0;
633  if( STAT_CHR_SRC(x.st_mode) ){
634    return fopen(zFile, "rb");
635  }else{
636    return 0;
637  }
638#endif
639#undef STAT_CHR_SRC
640}
641
642/*
643** This routine reads a line of text from FILE in, stores
644** the text in memory obtained from malloc() and returns a pointer
645** to the text.  NULL is returned at end of file, or if malloc()
646** fails.
647**
648** If zLine is not NULL then it is a malloced buffer returned from
649** a previous call to this routine that may be reused.
650*/
651static char *local_getline(char *zLine, FILE *in){
652  int nLine = zLine==0 ? 0 : 100;
653  int n = 0;
654
655  while( 1 ){
656    if( n+100>nLine ){
657      nLine = nLine*2 + 100;
658      zLine = realloc(zLine, nLine);
659      shell_check_oom(zLine);
660    }
661    if( fgets(&zLine[n], nLine - n, in)==0 ){
662      if( n==0 ){
663        free(zLine);
664        return 0;
665      }
666      zLine[n] = 0;
667      break;
668    }
669    while( zLine[n] ) n++;
670    if( n>0 && zLine[n-1]=='\n' ){
671      n--;
672      if( n>0 && zLine[n-1]=='\r' ) n--;
673      zLine[n] = 0;
674      break;
675    }
676  }
677#if defined(_WIN32) || defined(WIN32)
678  /* For interactive input on Windows systems, translate the
679  ** multi-byte characterset characters into UTF-8. */
680  if( stdin_is_interactive && in==stdin ){
681    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
682    if( zTrans ){
683      i64 nTrans = strlen(zTrans)+1;
684      if( nTrans>nLine ){
685        zLine = realloc(zLine, nTrans);
686        shell_check_oom(zLine);
687      }
688      memcpy(zLine, zTrans, nTrans);
689      sqlite3_free(zTrans);
690    }
691  }
692#endif /* defined(_WIN32) || defined(WIN32) */
693  return zLine;
694}
695
696/*
697** Retrieve a single line of input text.
698**
699** If in==0 then read from standard input and prompt before each line.
700** If isContinuation is true, then a continuation prompt is appropriate.
701** If isContinuation is zero, then the main prompt should be used.
702**
703** If zPrior is not NULL then it is a buffer from a prior call to this
704** routine that can be reused.
705**
706** The result is stored in space obtained from malloc() and must either
707** be freed by the caller or else passed back into this routine via the
708** zPrior argument for reuse.
709*/
710#ifndef SQLITE_SHELL_FIDDLE
711static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
712  char *zPrompt;
713  char *zResult;
714  if( in!=0 ){
715    zResult = local_getline(zPrior, in);
716  }else{
717    zPrompt = isContinuation ? continuePrompt : mainPrompt;
718#if SHELL_USE_LOCAL_GETLINE
719    printf("%s", zPrompt);
720    fflush(stdout);
721    zResult = local_getline(zPrior, stdin);
722#else
723    free(zPrior);
724    zResult = shell_readline(zPrompt);
725    if( zResult && *zResult ) shell_add_history(zResult);
726#endif
727  }
728  return zResult;
729}
730#endif /* !SQLITE_SHELL_FIDDLE */
731
732/*
733** Return the value of a hexadecimal digit.  Return -1 if the input
734** is not a hex digit.
735*/
736static int hexDigitValue(char c){
737  if( c>='0' && c<='9' ) return c - '0';
738  if( c>='a' && c<='f' ) return c - 'a' + 10;
739  if( c>='A' && c<='F' ) return c - 'A' + 10;
740  return -1;
741}
742
743/*
744** Interpret zArg as an integer value, possibly with suffixes.
745*/
746static sqlite3_int64 integerValue(const char *zArg){
747  sqlite3_int64 v = 0;
748  static const struct { char *zSuffix; int iMult; } aMult[] = {
749    { "KiB", 1024 },
750    { "MiB", 1024*1024 },
751    { "GiB", 1024*1024*1024 },
752    { "KB",  1000 },
753    { "MB",  1000000 },
754    { "GB",  1000000000 },
755    { "K",   1000 },
756    { "M",   1000000 },
757    { "G",   1000000000 },
758  };
759  int i;
760  int isNeg = 0;
761  if( zArg[0]=='-' ){
762    isNeg = 1;
763    zArg++;
764  }else if( zArg[0]=='+' ){
765    zArg++;
766  }
767  if( zArg[0]=='0' && zArg[1]=='x' ){
768    int x;
769    zArg += 2;
770    while( (x = hexDigitValue(zArg[0]))>=0 ){
771      v = (v<<4) + x;
772      zArg++;
773    }
774  }else{
775    while( IsDigit(zArg[0]) ){
776      v = v*10 + zArg[0] - '0';
777      zArg++;
778    }
779  }
780  for(i=0; i<ArraySize(aMult); i++){
781    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
782      v *= aMult[i].iMult;
783      break;
784    }
785  }
786  return isNeg? -v : v;
787}
788
789/*
790** A variable length string to which one can append text.
791*/
792typedef struct ShellText ShellText;
793struct ShellText {
794  char *z;
795  int n;
796  int nAlloc;
797};
798
799/*
800** Initialize and destroy a ShellText object
801*/
802static void initText(ShellText *p){
803  memset(p, 0, sizeof(*p));
804}
805static void freeText(ShellText *p){
806  free(p->z);
807  initText(p);
808}
809
810/* zIn is either a pointer to a NULL-terminated string in memory obtained
811** from malloc(), or a NULL pointer. The string pointed to by zAppend is
812** added to zIn, and the result returned in memory obtained from malloc().
813** zIn, if it was not NULL, is freed.
814**
815** If the third argument, quote, is not '\0', then it is used as a
816** quote character for zAppend.
817*/
818static void appendText(ShellText *p, const char *zAppend, char quote){
819  i64 len;
820  i64 i;
821  i64 nAppend = strlen30(zAppend);
822
823  len = nAppend+p->n+1;
824  if( quote ){
825    len += 2;
826    for(i=0; i<nAppend; i++){
827      if( zAppend[i]==quote ) len++;
828    }
829  }
830
831  if( p->z==0 || p->n+len>=p->nAlloc ){
832    p->nAlloc = p->nAlloc*2 + len + 20;
833    p->z = realloc(p->z, p->nAlloc);
834    shell_check_oom(p->z);
835  }
836
837  if( quote ){
838    char *zCsr = p->z+p->n;
839    *zCsr++ = quote;
840    for(i=0; i<nAppend; i++){
841      *zCsr++ = zAppend[i];
842      if( zAppend[i]==quote ) *zCsr++ = quote;
843    }
844    *zCsr++ = quote;
845    p->n = (int)(zCsr - p->z);
846    *zCsr = '\0';
847  }else{
848    memcpy(p->z+p->n, zAppend, nAppend);
849    p->n += nAppend;
850    p->z[p->n] = '\0';
851  }
852}
853
854/*
855** Attempt to determine if identifier zName needs to be quoted, either
856** because it contains non-alphanumeric characters, or because it is an
857** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
858** that quoting is required.
859**
860** Return '"' if quoting is required.  Return 0 if no quoting is required.
861*/
862static char quoteChar(const char *zName){
863  int i;
864  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
865  for(i=0; zName[i]; i++){
866    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
867  }
868  return sqlite3_keyword_check(zName, i) ? '"' : 0;
869}
870
871/*
872** Construct a fake object name and column list to describe the structure
873** of the view, virtual table, or table valued function zSchema.zName.
874*/
875static char *shellFakeSchema(
876  sqlite3 *db,            /* The database connection containing the vtab */
877  const char *zSchema,    /* Schema of the database holding the vtab */
878  const char *zName       /* The name of the virtual table */
879){
880  sqlite3_stmt *pStmt = 0;
881  char *zSql;
882  ShellText s;
883  char cQuote;
884  char *zDiv = "(";
885  int nRow = 0;
886
887  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
888                         zSchema ? zSchema : "main", zName);
889  shell_check_oom(zSql);
890  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
891  sqlite3_free(zSql);
892  initText(&s);
893  if( zSchema ){
894    cQuote = quoteChar(zSchema);
895    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
896    appendText(&s, zSchema, cQuote);
897    appendText(&s, ".", 0);
898  }
899  cQuote = quoteChar(zName);
900  appendText(&s, zName, cQuote);
901  while( sqlite3_step(pStmt)==SQLITE_ROW ){
902    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
903    nRow++;
904    appendText(&s, zDiv, 0);
905    zDiv = ",";
906    if( zCol==0 ) zCol = "";
907    cQuote = quoteChar(zCol);
908    appendText(&s, zCol, cQuote);
909  }
910  appendText(&s, ")", 0);
911  sqlite3_finalize(pStmt);
912  if( nRow==0 ){
913    freeText(&s);
914    s.z = 0;
915  }
916  return s.z;
917}
918
919/*
920** SQL function:  shell_module_schema(X)
921**
922** Return a fake schema for the table-valued function or eponymous virtual
923** table X.
924*/
925static void shellModuleSchema(
926  sqlite3_context *pCtx,
927  int nVal,
928  sqlite3_value **apVal
929){
930  const char *zName;
931  char *zFake;
932  UNUSED_PARAMETER(nVal);
933  zName = (const char*)sqlite3_value_text(apVal[0]);
934  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
935  if( zFake ){
936    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
937                        -1, sqlite3_free);
938    free(zFake);
939  }
940}
941
942/*
943** SQL function:  shell_add_schema(S,X)
944**
945** Add the schema name X to the CREATE statement in S and return the result.
946** Examples:
947**
948**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
949**
950** Also works on
951**
952**    CREATE INDEX
953**    CREATE UNIQUE INDEX
954**    CREATE VIEW
955**    CREATE TRIGGER
956**    CREATE VIRTUAL TABLE
957**
958** This UDF is used by the .schema command to insert the schema name of
959** attached databases into the middle of the sqlite_schema.sql field.
960*/
961static void shellAddSchemaName(
962  sqlite3_context *pCtx,
963  int nVal,
964  sqlite3_value **apVal
965){
966  static const char *aPrefix[] = {
967     "TABLE",
968     "INDEX",
969     "UNIQUE INDEX",
970     "VIEW",
971     "TRIGGER",
972     "VIRTUAL TABLE"
973  };
974  int i = 0;
975  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
976  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
977  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
978  sqlite3 *db = sqlite3_context_db_handle(pCtx);
979  UNUSED_PARAMETER(nVal);
980  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
981    for(i=0; i<ArraySize(aPrefix); i++){
982      int n = strlen30(aPrefix[i]);
983      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
984        char *z = 0;
985        char *zFake = 0;
986        if( zSchema ){
987          char cQuote = quoteChar(zSchema);
988          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
989            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
990          }else{
991            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
992          }
993        }
994        if( zName
995         && aPrefix[i][0]=='V'
996         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
997        ){
998          if( z==0 ){
999            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1000          }else{
1001            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1002          }
1003          free(zFake);
1004        }
1005        if( z ){
1006          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1007          return;
1008        }
1009      }
1010    }
1011  }
1012  sqlite3_result_value(pCtx, apVal[0]);
1013}
1014
1015/*
1016** The source code for several run-time loadable extensions is inserted
1017** below by the ../tool/mkshellc.tcl script.  Before processing that included
1018** code, we need to override some macros to make the included program code
1019** work here in the middle of this regular program.
1020*/
1021#define SQLITE_EXTENSION_INIT1
1022#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1023
1024#if defined(_WIN32) && defined(_MSC_VER)
1025INCLUDE test_windirent.h
1026INCLUDE test_windirent.c
1027#define dirent DIRENT
1028#endif
1029INCLUDE ../ext/misc/memtrace.c
1030INCLUDE ../ext/misc/shathree.c
1031INCLUDE ../ext/misc/uint.c
1032INCLUDE ../ext/misc/decimal.c
1033INCLUDE ../ext/misc/ieee754.c
1034INCLUDE ../ext/misc/series.c
1035INCLUDE ../ext/misc/regexp.c
1036#ifndef SQLITE_SHELL_FIDDLE
1037INCLUDE ../ext/misc/fileio.c
1038INCLUDE ../ext/misc/completion.c
1039INCLUDE ../ext/misc/appendvfs.c
1040#endif
1041#ifdef SQLITE_HAVE_ZLIB
1042INCLUDE ../ext/misc/zipfile.c
1043INCLUDE ../ext/misc/sqlar.c
1044#endif
1045INCLUDE ../ext/expert/sqlite3expert.h
1046INCLUDE ../ext/expert/sqlite3expert.c
1047
1048#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1049INCLUDE ../ext/misc/dbdata.c
1050#endif
1051
1052#if defined(SQLITE_ENABLE_SESSION)
1053/*
1054** State information for a single open session
1055*/
1056typedef struct OpenSession OpenSession;
1057struct OpenSession {
1058  char *zName;             /* Symbolic name for this session */
1059  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1060  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1061  sqlite3_session *p;      /* The open session */
1062};
1063#endif
1064
1065typedef struct ExpertInfo ExpertInfo;
1066struct ExpertInfo {
1067  sqlite3expert *pExpert;
1068  int bVerbose;
1069};
1070
1071/* A single line in the EQP output */
1072typedef struct EQPGraphRow EQPGraphRow;
1073struct EQPGraphRow {
1074  int iEqpId;           /* ID for this row */
1075  int iParentId;        /* ID of the parent row */
1076  EQPGraphRow *pNext;   /* Next row in sequence */
1077  char zText[1];        /* Text to display for this row */
1078};
1079
1080/* All EQP output is collected into an instance of the following */
1081typedef struct EQPGraph EQPGraph;
1082struct EQPGraph {
1083  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1084  EQPGraphRow *pLast;   /* Last element of the pRow list */
1085  char zPrefix[100];    /* Graph prefix */
1086};
1087
1088/* Parameters affecting columnar mode result display (defaulting together) */
1089typedef struct ColModeOpts {
1090  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1091  u8 bQuote;            /* Quote results for .mode box and table */
1092  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1093} ColModeOpts;
1094#define ColModeOpts_default { 60, 0, 0 }
1095#define ColModeOpts_default_qbox { 60, 1, 0 }
1096
1097/*
1098** State information about the database connection is contained in an
1099** instance of the following structure.
1100*/
1101typedef struct ShellState ShellState;
1102struct ShellState {
1103  sqlite3 *db;           /* The database */
1104  u8 autoExplain;        /* Automatically turn on .explain mode */
1105  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1106  u8 autoEQPtest;        /* autoEQP is in test mode */
1107  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1108  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1109  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1110  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1111  u8 nEqpLevel;          /* Depth of the EQP output graph */
1112  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1113  u8 bSafeMode;          /* True to prohibit unsafe operations */
1114  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1115  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1116  unsigned statsOn;      /* True to display memory stats before each finalize */
1117  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1118  int inputNesting;      /* Track nesting level of .read and other redirects */
1119  int outCount;          /* Revert to stdout when reaching zero */
1120  int cnt;               /* Number of records displayed so far */
1121  int lineno;            /* Line number of last line read from in */
1122  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1123  FILE *in;              /* Read commands from this stream */
1124  FILE *out;             /* Write results here */
1125  FILE *traceOut;        /* Output for sqlite3_trace() */
1126  int nErr;              /* Number of errors seen */
1127  int mode;              /* An output mode setting */
1128  int modePrior;         /* Saved mode */
1129  int cMode;             /* temporary output mode for the current query */
1130  int normalMode;        /* Output mode before ".explain on" */
1131  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1132  int showHeader;        /* True to show column names in List or Column mode */
1133  int nCheck;            /* Number of ".check" commands run */
1134  unsigned nProgress;    /* Number of progress callbacks encountered */
1135  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1136  unsigned flgProgress;  /* Flags for the progress callback */
1137  unsigned shellFlgs;    /* Various flags */
1138  unsigned priorShFlgs;  /* Saved copy of flags */
1139  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1140  char *zDestTable;      /* Name of destination table when MODE_Insert */
1141  char *zTempFile;       /* Temporary file that might need deleting */
1142  char zTestcase[30];    /* Name of current test case */
1143  char colSeparator[20]; /* Column separator character for several modes */
1144  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1145  char colSepPrior[20];  /* Saved column separator */
1146  char rowSepPrior[20];  /* Saved row separator */
1147  int *colWidth;         /* Requested width of each column in columnar modes */
1148  int *actualWidth;      /* Actual width of each column */
1149  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1150  char nullValue[20];    /* The text to print when a NULL comes back from
1151                         ** the database */
1152  char outfile[FILENAME_MAX]; /* Filename for *out */
1153  sqlite3_stmt *pStmt;   /* Current statement if any. */
1154  FILE *pLog;            /* Write log output here */
1155  struct AuxDb {         /* Storage space for auxiliary database connections */
1156    sqlite3 *db;               /* Connection pointer */
1157    const char *zDbFilename;   /* Filename used to open the connection */
1158    char *zFreeOnClose;        /* Free this memory allocation on close */
1159#if defined(SQLITE_ENABLE_SESSION)
1160    int nSession;              /* Number of active sessions */
1161    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1162#endif
1163  } aAuxDb[5],           /* Array of all database connections */
1164    *pAuxDb;             /* Currently active database connection */
1165  int *aiIndent;         /* Array of indents used in MODE_Explain */
1166  int nIndent;           /* Size of array aiIndent[] */
1167  int iIndent;           /* Index of current op in aiIndent[] */
1168  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1169  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1170  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1171#ifdef SQLITE_SHELL_FIDDLE
1172  struct {
1173    const char * zInput; /* Input string from wasm/JS proxy */
1174    const char * zPos;   /* Cursor pos into zInput */
1175    const char * zDefaultDbName; /* Default name for db file */
1176  } wasm;
1177#endif
1178};
1179
1180#ifdef SQLITE_SHELL_FIDDLE
1181static ShellState shellState;
1182#endif
1183
1184
1185/* Allowed values for ShellState.autoEQP
1186*/
1187#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1188#define AUTOEQP_on       1           /* Automatic EQP is on */
1189#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1190#define AUTOEQP_full     3           /* Show full EXPLAIN */
1191
1192/* Allowed values for ShellState.openMode
1193*/
1194#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1195#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1196#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1197#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1198#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1199#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1200#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1201
1202/* Allowed values for ShellState.eTraceType
1203*/
1204#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1205#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1206#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1207
1208/* Bits in the ShellState.flgProgress variable */
1209#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1210#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1211                                   ** callback limit is reached, and for each
1212                                   ** top-level SQL statement */
1213#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1214
1215/*
1216** These are the allowed shellFlgs values
1217*/
1218#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1219#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1220#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1221#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1222#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1223#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1224#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1225#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1226#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1227#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1228
1229/*
1230** Macros for testing and setting shellFlgs
1231*/
1232#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1233#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1234#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1235
1236/*
1237** These are the allowed modes.
1238*/
1239#define MODE_Line     0  /* One column per line.  Blank line between records */
1240#define MODE_Column   1  /* One record per line in neat columns */
1241#define MODE_List     2  /* One record per line with a separator */
1242#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1243#define MODE_Html     4  /* Generate an XHTML table */
1244#define MODE_Insert   5  /* Generate SQL "insert" statements */
1245#define MODE_Quote    6  /* Quote values as for SQL */
1246#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1247#define MODE_Csv      8  /* Quote strings, numbers are plain */
1248#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1249#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1250#define MODE_Pretty  11  /* Pretty-print schemas */
1251#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1252#define MODE_Json    13  /* Output JSON */
1253#define MODE_Markdown 14 /* Markdown formatting */
1254#define MODE_Table   15  /* MySQL-style table formatting */
1255#define MODE_Box     16  /* Unicode box-drawing characters */
1256#define MODE_Count   17  /* Output only a count of the rows of output */
1257#define MODE_Off     18  /* No query output shown */
1258
1259static const char *modeDescr[] = {
1260  "line",
1261  "column",
1262  "list",
1263  "semi",
1264  "html",
1265  "insert",
1266  "quote",
1267  "tcl",
1268  "csv",
1269  "explain",
1270  "ascii",
1271  "prettyprint",
1272  "eqp",
1273  "json",
1274  "markdown",
1275  "table",
1276  "box",
1277  "count",
1278  "off"
1279};
1280
1281/*
1282** These are the column/row/line separators used by the various
1283** import/export modes.
1284*/
1285#define SEP_Column    "|"
1286#define SEP_Row       "\n"
1287#define SEP_Tab       "\t"
1288#define SEP_Space     " "
1289#define SEP_Comma     ","
1290#define SEP_CrLf      "\r\n"
1291#define SEP_Unit      "\x1F"
1292#define SEP_Record    "\x1E"
1293
1294/*
1295** Limit input nesting via .read or any other input redirect.
1296** It's not too expensive, so a generous allowance can be made.
1297*/
1298#define MAX_INPUT_NESTING 25
1299
1300/*
1301** A callback for the sqlite3_log() interface.
1302*/
1303static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1304  ShellState *p = (ShellState*)pArg;
1305  if( p->pLog==0 ) return;
1306  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1307  fflush(p->pLog);
1308}
1309
1310/*
1311** SQL function:  shell_putsnl(X)
1312**
1313** Write the text X to the screen (or whatever output is being directed)
1314** adding a newline at the end, and then return X.
1315*/
1316static void shellPutsFunc(
1317  sqlite3_context *pCtx,
1318  int nVal,
1319  sqlite3_value **apVal
1320){
1321  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1322  (void)nVal;
1323  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1324  sqlite3_result_value(pCtx, apVal[0]);
1325}
1326
1327/*
1328** If in safe mode, print an error message described by the arguments
1329** and exit immediately.
1330*/
1331static void failIfSafeMode(
1332  ShellState *p,
1333  const char *zErrMsg,
1334  ...
1335){
1336  if( p->bSafeMode ){
1337    va_list ap;
1338    char *zMsg;
1339    va_start(ap, zErrMsg);
1340    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1341    va_end(ap);
1342    raw_printf(stderr, "line %d: ", p->lineno);
1343    utf8_printf(stderr, "%s\n", zMsg);
1344    exit(1);
1345  }
1346}
1347
1348/*
1349** SQL function:   edit(VALUE)
1350**                 edit(VALUE,EDITOR)
1351**
1352** These steps:
1353**
1354**     (1) Write VALUE into a temporary file.
1355**     (2) Run program EDITOR on that temporary file.
1356**     (3) Read the temporary file back and return its content as the result.
1357**     (4) Delete the temporary file
1358**
1359** If the EDITOR argument is omitted, use the value in the VISUAL
1360** environment variable.  If still there is no EDITOR, through an error.
1361**
1362** Also throw an error if the EDITOR program returns a non-zero exit code.
1363*/
1364#ifndef SQLITE_NOHAVE_SYSTEM
1365static void editFunc(
1366  sqlite3_context *context,
1367  int argc,
1368  sqlite3_value **argv
1369){
1370  const char *zEditor;
1371  char *zTempFile = 0;
1372  sqlite3 *db;
1373  char *zCmd = 0;
1374  int bBin;
1375  int rc;
1376  int hasCRNL = 0;
1377  FILE *f = 0;
1378  sqlite3_int64 sz;
1379  sqlite3_int64 x;
1380  unsigned char *p = 0;
1381
1382  if( argc==2 ){
1383    zEditor = (const char*)sqlite3_value_text(argv[1]);
1384  }else{
1385    zEditor = getenv("VISUAL");
1386  }
1387  if( zEditor==0 ){
1388    sqlite3_result_error(context, "no editor for edit()", -1);
1389    return;
1390  }
1391  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1392    sqlite3_result_error(context, "NULL input to edit()", -1);
1393    return;
1394  }
1395  db = sqlite3_context_db_handle(context);
1396  zTempFile = 0;
1397  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1398  if( zTempFile==0 ){
1399    sqlite3_uint64 r = 0;
1400    sqlite3_randomness(sizeof(r), &r);
1401    zTempFile = sqlite3_mprintf("temp%llx", r);
1402    if( zTempFile==0 ){
1403      sqlite3_result_error_nomem(context);
1404      return;
1405    }
1406  }
1407  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1408  /* When writing the file to be edited, do \n to \r\n conversions on systems
1409  ** that want \r\n line endings */
1410  f = fopen(zTempFile, bBin ? "wb" : "w");
1411  if( f==0 ){
1412    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1413    goto edit_func_end;
1414  }
1415  sz = sqlite3_value_bytes(argv[0]);
1416  if( bBin ){
1417    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1418  }else{
1419    const char *z = (const char*)sqlite3_value_text(argv[0]);
1420    /* Remember whether or not the value originally contained \r\n */
1421    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1422    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1423  }
1424  fclose(f);
1425  f = 0;
1426  if( x!=sz ){
1427    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1428    goto edit_func_end;
1429  }
1430  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1431  if( zCmd==0 ){
1432    sqlite3_result_error_nomem(context);
1433    goto edit_func_end;
1434  }
1435  rc = system(zCmd);
1436  sqlite3_free(zCmd);
1437  if( rc ){
1438    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1439    goto edit_func_end;
1440  }
1441  f = fopen(zTempFile, "rb");
1442  if( f==0 ){
1443    sqlite3_result_error(context,
1444      "edit() cannot reopen temp file after edit", -1);
1445    goto edit_func_end;
1446  }
1447  fseek(f, 0, SEEK_END);
1448  sz = ftell(f);
1449  rewind(f);
1450  p = sqlite3_malloc64( sz+1 );
1451  if( p==0 ){
1452    sqlite3_result_error_nomem(context);
1453    goto edit_func_end;
1454  }
1455  x = fread(p, 1, (size_t)sz, f);
1456  fclose(f);
1457  f = 0;
1458  if( x!=sz ){
1459    sqlite3_result_error(context, "could not read back the whole file", -1);
1460    goto edit_func_end;
1461  }
1462  if( bBin ){
1463    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1464  }else{
1465    sqlite3_int64 i, j;
1466    if( hasCRNL ){
1467      /* If the original contains \r\n then do no conversions back to \n */
1468    }else{
1469      /* If the file did not originally contain \r\n then convert any new
1470      ** \r\n back into \n */
1471      for(i=j=0; i<sz; i++){
1472        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1473        p[j++] = p[i];
1474      }
1475      sz = j;
1476      p[sz] = 0;
1477    }
1478    sqlite3_result_text64(context, (const char*)p, sz,
1479                          sqlite3_free, SQLITE_UTF8);
1480  }
1481  p = 0;
1482
1483edit_func_end:
1484  if( f ) fclose(f);
1485  unlink(zTempFile);
1486  sqlite3_free(zTempFile);
1487  sqlite3_free(p);
1488}
1489#endif /* SQLITE_NOHAVE_SYSTEM */
1490
1491/*
1492** Save or restore the current output mode
1493*/
1494static void outputModePush(ShellState *p){
1495  p->modePrior = p->mode;
1496  p->priorShFlgs = p->shellFlgs;
1497  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1498  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1499}
1500static void outputModePop(ShellState *p){
1501  p->mode = p->modePrior;
1502  p->shellFlgs = p->priorShFlgs;
1503  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1504  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1505}
1506
1507/*
1508** Output the given string as a hex-encoded blob (eg. X'1234' )
1509*/
1510static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1511  int i;
1512  unsigned char *aBlob = (unsigned char*)pBlob;
1513
1514  char *zStr = sqlite3_malloc(nBlob*2 + 1);
1515  shell_check_oom(zStr);
1516
1517  for(i=0; i<nBlob; i++){
1518    static const char aHex[] = {
1519        '0', '1', '2', '3', '4', '5', '6', '7',
1520        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1521    };
1522    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1523    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1524  }
1525  zStr[i*2] = '\0';
1526
1527  raw_printf(out,"X'%s'", zStr);
1528  sqlite3_free(zStr);
1529}
1530
1531/*
1532** Find a string that is not found anywhere in z[].  Return a pointer
1533** to that string.
1534**
1535** Try to use zA and zB first.  If both of those are already found in z[]
1536** then make up some string and store it in the buffer zBuf.
1537*/
1538static const char *unused_string(
1539  const char *z,                    /* Result must not appear anywhere in z */
1540  const char *zA, const char *zB,   /* Try these first */
1541  char *zBuf                        /* Space to store a generated string */
1542){
1543  unsigned i = 0;
1544  if( strstr(z, zA)==0 ) return zA;
1545  if( strstr(z, zB)==0 ) return zB;
1546  do{
1547    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1548  }while( strstr(z,zBuf)!=0 );
1549  return zBuf;
1550}
1551
1552/*
1553** Output the given string as a quoted string using SQL quoting conventions.
1554**
1555** See also: output_quoted_escaped_string()
1556*/
1557static void output_quoted_string(FILE *out, const char *z){
1558  int i;
1559  char c;
1560  setBinaryMode(out, 1);
1561  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1562  if( c==0 ){
1563    utf8_printf(out,"'%s'",z);
1564  }else{
1565    raw_printf(out, "'");
1566    while( *z ){
1567      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1568      if( c=='\'' ) i++;
1569      if( i ){
1570        utf8_printf(out, "%.*s", i, z);
1571        z += i;
1572      }
1573      if( c=='\'' ){
1574        raw_printf(out, "'");
1575        continue;
1576      }
1577      if( c==0 ){
1578        break;
1579      }
1580      z++;
1581    }
1582    raw_printf(out, "'");
1583  }
1584  setTextMode(out, 1);
1585}
1586
1587/*
1588** Output the given string as a quoted string using SQL quoting conventions.
1589** Additionallly , escape the "\n" and "\r" characters so that they do not
1590** get corrupted by end-of-line translation facilities in some operating
1591** systems.
1592**
1593** This is like output_quoted_string() but with the addition of the \r\n
1594** escape mechanism.
1595*/
1596static void output_quoted_escaped_string(FILE *out, const char *z){
1597  int i;
1598  char c;
1599  setBinaryMode(out, 1);
1600  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1601  if( c==0 ){
1602    utf8_printf(out,"'%s'",z);
1603  }else{
1604    const char *zNL = 0;
1605    const char *zCR = 0;
1606    int nNL = 0;
1607    int nCR = 0;
1608    char zBuf1[20], zBuf2[20];
1609    for(i=0; z[i]; i++){
1610      if( z[i]=='\n' ) nNL++;
1611      if( z[i]=='\r' ) nCR++;
1612    }
1613    if( nNL ){
1614      raw_printf(out, "replace(");
1615      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1616    }
1617    if( nCR ){
1618      raw_printf(out, "replace(");
1619      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1620    }
1621    raw_printf(out, "'");
1622    while( *z ){
1623      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1624      if( c=='\'' ) i++;
1625      if( i ){
1626        utf8_printf(out, "%.*s", i, z);
1627        z += i;
1628      }
1629      if( c=='\'' ){
1630        raw_printf(out, "'");
1631        continue;
1632      }
1633      if( c==0 ){
1634        break;
1635      }
1636      z++;
1637      if( c=='\n' ){
1638        raw_printf(out, "%s", zNL);
1639        continue;
1640      }
1641      raw_printf(out, "%s", zCR);
1642    }
1643    raw_printf(out, "'");
1644    if( nCR ){
1645      raw_printf(out, ",'%s',char(13))", zCR);
1646    }
1647    if( nNL ){
1648      raw_printf(out, ",'%s',char(10))", zNL);
1649    }
1650  }
1651  setTextMode(out, 1);
1652}
1653
1654/*
1655** Output the given string as a quoted according to C or TCL quoting rules.
1656*/
1657static void output_c_string(FILE *out, const char *z){
1658  unsigned int c;
1659  fputc('"', out);
1660  while( (c = *(z++))!=0 ){
1661    if( c=='\\' ){
1662      fputc(c, out);
1663      fputc(c, out);
1664    }else if( c=='"' ){
1665      fputc('\\', out);
1666      fputc('"', out);
1667    }else if( c=='\t' ){
1668      fputc('\\', out);
1669      fputc('t', out);
1670    }else if( c=='\n' ){
1671      fputc('\\', out);
1672      fputc('n', out);
1673    }else if( c=='\r' ){
1674      fputc('\\', out);
1675      fputc('r', out);
1676    }else if( !isprint(c&0xff) ){
1677      raw_printf(out, "\\%03o", c&0xff);
1678    }else{
1679      fputc(c, out);
1680    }
1681  }
1682  fputc('"', out);
1683}
1684
1685/*
1686** Output the given string as a quoted according to JSON quoting rules.
1687*/
1688static void output_json_string(FILE *out, const char *z, i64 n){
1689  unsigned int c;
1690  if( n<0 ) n = strlen(z);
1691  fputc('"', out);
1692  while( n-- ){
1693    c = *(z++);
1694    if( c=='\\' || c=='"' ){
1695      fputc('\\', out);
1696      fputc(c, out);
1697    }else if( c<=0x1f ){
1698      fputc('\\', out);
1699      if( c=='\b' ){
1700        fputc('b', out);
1701      }else if( c=='\f' ){
1702        fputc('f', out);
1703      }else if( c=='\n' ){
1704        fputc('n', out);
1705      }else if( c=='\r' ){
1706        fputc('r', out);
1707      }else if( c=='\t' ){
1708        fputc('t', out);
1709      }else{
1710         raw_printf(out, "u%04x",c);
1711      }
1712    }else{
1713      fputc(c, out);
1714    }
1715  }
1716  fputc('"', out);
1717}
1718
1719/*
1720** Output the given string with characters that are special to
1721** HTML escaped.
1722*/
1723static void output_html_string(FILE *out, const char *z){
1724  int i;
1725  if( z==0 ) z = "";
1726  while( *z ){
1727    for(i=0;   z[i]
1728            && z[i]!='<'
1729            && z[i]!='&'
1730            && z[i]!='>'
1731            && z[i]!='\"'
1732            && z[i]!='\'';
1733        i++){}
1734    if( i>0 ){
1735      utf8_printf(out,"%.*s",i,z);
1736    }
1737    if( z[i]=='<' ){
1738      raw_printf(out,"&lt;");
1739    }else if( z[i]=='&' ){
1740      raw_printf(out,"&amp;");
1741    }else if( z[i]=='>' ){
1742      raw_printf(out,"&gt;");
1743    }else if( z[i]=='\"' ){
1744      raw_printf(out,"&quot;");
1745    }else if( z[i]=='\'' ){
1746      raw_printf(out,"&#39;");
1747    }else{
1748      break;
1749    }
1750    z += i + 1;
1751  }
1752}
1753
1754/*
1755** If a field contains any character identified by a 1 in the following
1756** array, then the string must be quoted for CSV.
1757*/
1758static const char needCsvQuote[] = {
1759  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1760  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1761  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1762  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1763  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1764  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1765  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1766  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1767  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1768  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1769  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1770  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1771  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1772  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1773  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1774  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1775};
1776
1777/*
1778** Output a single term of CSV.  Actually, p->colSeparator is used for
1779** the separator, which may or may not be a comma.  p->nullValue is
1780** the null value.  Strings are quoted if necessary.  The separator
1781** is only issued if bSep is true.
1782*/
1783static void output_csv(ShellState *p, const char *z, int bSep){
1784  FILE *out = p->out;
1785  if( z==0 ){
1786    utf8_printf(out,"%s",p->nullValue);
1787  }else{
1788    unsigned i;
1789    for(i=0; z[i]; i++){
1790      if( needCsvQuote[((unsigned char*)z)[i]] ){
1791        i = 0;
1792        break;
1793      }
1794    }
1795    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1796      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1797      shell_check_oom(zQuoted);
1798      utf8_printf(out, "%s", zQuoted);
1799      sqlite3_free(zQuoted);
1800    }else{
1801      utf8_printf(out, "%s", z);
1802    }
1803  }
1804  if( bSep ){
1805    utf8_printf(p->out, "%s", p->colSeparator);
1806  }
1807}
1808
1809/*
1810** This routine runs when the user presses Ctrl-C
1811*/
1812static void interrupt_handler(int NotUsed){
1813  UNUSED_PARAMETER(NotUsed);
1814  seenInterrupt++;
1815  if( seenInterrupt>2 ) exit(1);
1816  if( globalDb ) sqlite3_interrupt(globalDb);
1817}
1818
1819#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1820/*
1821** This routine runs for console events (e.g. Ctrl-C) on Win32
1822*/
1823static BOOL WINAPI ConsoleCtrlHandler(
1824  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1825){
1826  if( dwCtrlType==CTRL_C_EVENT ){
1827    interrupt_handler(0);
1828    return TRUE;
1829  }
1830  return FALSE;
1831}
1832#endif
1833
1834#ifndef SQLITE_OMIT_AUTHORIZATION
1835/*
1836** This authorizer runs in safe mode.
1837*/
1838static int safeModeAuth(
1839  void *pClientData,
1840  int op,
1841  const char *zA1,
1842  const char *zA2,
1843  const char *zA3,
1844  const char *zA4
1845){
1846  ShellState *p = (ShellState*)pClientData;
1847  static const char *azProhibitedFunctions[] = {
1848    "edit",
1849    "fts3_tokenizer",
1850    "load_extension",
1851    "readfile",
1852    "writefile",
1853    "zipfile",
1854    "zipfile_cds",
1855  };
1856  UNUSED_PARAMETER(zA2);
1857  UNUSED_PARAMETER(zA3);
1858  UNUSED_PARAMETER(zA4);
1859  switch( op ){
1860    case SQLITE_ATTACH: {
1861#ifndef SQLITE_SHELL_FIDDLE
1862      /* In WASM builds the filesystem is a virtual sandbox, so
1863      ** there's no harm in using ATTACH. */
1864      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1865#endif
1866      break;
1867    }
1868    case SQLITE_FUNCTION: {
1869      int i;
1870      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1871        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1872          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1873                         azProhibitedFunctions[i]);
1874        }
1875      }
1876      break;
1877    }
1878  }
1879  return SQLITE_OK;
1880}
1881
1882/*
1883** When the ".auth ON" is set, the following authorizer callback is
1884** invoked.  It always returns SQLITE_OK.
1885*/
1886static int shellAuth(
1887  void *pClientData,
1888  int op,
1889  const char *zA1,
1890  const char *zA2,
1891  const char *zA3,
1892  const char *zA4
1893){
1894  ShellState *p = (ShellState*)pClientData;
1895  static const char *azAction[] = { 0,
1896     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1897     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1898     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1899     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1900     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1901     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1902     "PRAGMA",               "READ",                 "SELECT",
1903     "TRANSACTION",          "UPDATE",               "ATTACH",
1904     "DETACH",               "ALTER_TABLE",          "REINDEX",
1905     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1906     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1907  };
1908  int i;
1909  const char *az[4];
1910  az[0] = zA1;
1911  az[1] = zA2;
1912  az[2] = zA3;
1913  az[3] = zA4;
1914  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1915  for(i=0; i<4; i++){
1916    raw_printf(p->out, " ");
1917    if( az[i] ){
1918      output_c_string(p->out, az[i]);
1919    }else{
1920      raw_printf(p->out, "NULL");
1921    }
1922  }
1923  raw_printf(p->out, "\n");
1924  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1925  return SQLITE_OK;
1926}
1927#endif
1928
1929/*
1930** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1931**
1932** This routine converts some CREATE TABLE statements for shadow tables
1933** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1934**
1935** If the schema statement in z[] contains a start-of-comment and if
1936** sqlite3_complete() returns false, try to terminate the comment before
1937** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
1938*/
1939static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1940  char *zToFree = 0;
1941  if( z==0 ) return;
1942  if( zTail==0 ) return;
1943  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
1944    const char *zOrig = z;
1945    static const char *azTerm[] = { "", "*/", "\n" };
1946    int i;
1947    for(i=0; i<ArraySize(azTerm); i++){
1948      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
1949      if( sqlite3_complete(zNew) ){
1950        size_t n = strlen(zNew);
1951        zNew[n-1] = 0;
1952        zToFree = zNew;
1953        z = zNew;
1954        break;
1955      }
1956      sqlite3_free(zNew);
1957    }
1958  }
1959  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1960    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1961  }else{
1962    utf8_printf(out, "%s%s", z, zTail);
1963  }
1964  sqlite3_free(zToFree);
1965}
1966static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1967  char c = z[n];
1968  z[n] = 0;
1969  printSchemaLine(out, z, zTail);
1970  z[n] = c;
1971}
1972
1973/*
1974** Return true if string z[] has nothing but whitespace and comments to the
1975** end of the first line.
1976*/
1977static int wsToEol(const char *z){
1978  int i;
1979  for(i=0; z[i]; i++){
1980    if( z[i]=='\n' ) return 1;
1981    if( IsSpace(z[i]) ) continue;
1982    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1983    return 0;
1984  }
1985  return 1;
1986}
1987
1988/*
1989** Add a new entry to the EXPLAIN QUERY PLAN data
1990*/
1991static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1992  EQPGraphRow *pNew;
1993  i64 nText = strlen(zText);
1994  if( p->autoEQPtest ){
1995    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1996  }
1997  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1998  shell_check_oom(pNew);
1999  pNew->iEqpId = iEqpId;
2000  pNew->iParentId = p2;
2001  memcpy(pNew->zText, zText, nText+1);
2002  pNew->pNext = 0;
2003  if( p->sGraph.pLast ){
2004    p->sGraph.pLast->pNext = pNew;
2005  }else{
2006    p->sGraph.pRow = pNew;
2007  }
2008  p->sGraph.pLast = pNew;
2009}
2010
2011/*
2012** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2013** in p->sGraph.
2014*/
2015static void eqp_reset(ShellState *p){
2016  EQPGraphRow *pRow, *pNext;
2017  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2018    pNext = pRow->pNext;
2019    sqlite3_free(pRow);
2020  }
2021  memset(&p->sGraph, 0, sizeof(p->sGraph));
2022}
2023
2024/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2025** pOld, or return the first such line if pOld is NULL
2026*/
2027static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2028  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2029  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2030  return pRow;
2031}
2032
2033/* Render a single level of the graph that has iEqpId as its parent.  Called
2034** recursively to render sublevels.
2035*/
2036static void eqp_render_level(ShellState *p, int iEqpId){
2037  EQPGraphRow *pRow, *pNext;
2038  i64 n = strlen(p->sGraph.zPrefix);
2039  char *z;
2040  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2041    pNext = eqp_next_row(p, iEqpId, pRow);
2042    z = pRow->zText;
2043    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2044                pNext ? "|--" : "`--", z);
2045    if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
2046      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2047      eqp_render_level(p, pRow->iEqpId);
2048      p->sGraph.zPrefix[n] = 0;
2049    }
2050  }
2051}
2052
2053/*
2054** Display and reset the EXPLAIN QUERY PLAN data
2055*/
2056static void eqp_render(ShellState *p){
2057  EQPGraphRow *pRow = p->sGraph.pRow;
2058  if( pRow ){
2059    if( pRow->zText[0]=='-' ){
2060      if( pRow->pNext==0 ){
2061        eqp_reset(p);
2062        return;
2063      }
2064      utf8_printf(p->out, "%s\n", pRow->zText+3);
2065      p->sGraph.pRow = pRow->pNext;
2066      sqlite3_free(pRow);
2067    }else{
2068      utf8_printf(p->out, "QUERY PLAN\n");
2069    }
2070    p->sGraph.zPrefix[0] = 0;
2071    eqp_render_level(p, 0);
2072    eqp_reset(p);
2073  }
2074}
2075
2076#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2077/*
2078** Progress handler callback.
2079*/
2080static int progress_handler(void *pClientData) {
2081  ShellState *p = (ShellState*)pClientData;
2082  p->nProgress++;
2083  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2084    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2085    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2086    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2087    return 1;
2088  }
2089  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2090    raw_printf(p->out, "Progress %u\n", p->nProgress);
2091  }
2092  return 0;
2093}
2094#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2095
2096/*
2097** Print N dashes
2098*/
2099static void print_dashes(FILE *out, int N){
2100  const char zDash[] = "--------------------------------------------------";
2101  const int nDash = sizeof(zDash) - 1;
2102  while( N>nDash ){
2103    fputs(zDash, out);
2104    N -= nDash;
2105  }
2106  raw_printf(out, "%.*s", N, zDash);
2107}
2108
2109/*
2110** Print a markdown or table-style row separator using ascii-art
2111*/
2112static void print_row_separator(
2113  ShellState *p,
2114  int nArg,
2115  const char *zSep
2116){
2117  int i;
2118  if( nArg>0 ){
2119    fputs(zSep, p->out);
2120    print_dashes(p->out, p->actualWidth[0]+2);
2121    for(i=1; i<nArg; i++){
2122      fputs(zSep, p->out);
2123      print_dashes(p->out, p->actualWidth[i]+2);
2124    }
2125    fputs(zSep, p->out);
2126  }
2127  fputs("\n", p->out);
2128}
2129
2130/*
2131** This is the callback routine that the shell
2132** invokes for each row of a query result.
2133*/
2134static int shell_callback(
2135  void *pArg,
2136  int nArg,        /* Number of result columns */
2137  char **azArg,    /* Text of each result column */
2138  char **azCol,    /* Column names */
2139  int *aiType      /* Column types.  Might be NULL */
2140){
2141  int i;
2142  ShellState *p = (ShellState*)pArg;
2143
2144  if( azArg==0 ) return 0;
2145  switch( p->cMode ){
2146    case MODE_Count:
2147    case MODE_Off: {
2148      break;
2149    }
2150    case MODE_Line: {
2151      int w = 5;
2152      if( azArg==0 ) break;
2153      for(i=0; i<nArg; i++){
2154        int len = strlen30(azCol[i] ? azCol[i] : "");
2155        if( len>w ) w = len;
2156      }
2157      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2158      for(i=0; i<nArg; i++){
2159        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2160                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2161      }
2162      break;
2163    }
2164    case MODE_Explain: {
2165      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2166      if( nArg>ArraySize(aExplainWidth) ){
2167        nArg = ArraySize(aExplainWidth);
2168      }
2169      if( p->cnt++==0 ){
2170        for(i=0; i<nArg; i++){
2171          int w = aExplainWidth[i];
2172          utf8_width_print(p->out, w, azCol[i]);
2173          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2174        }
2175        for(i=0; i<nArg; i++){
2176          int w = aExplainWidth[i];
2177          print_dashes(p->out, w);
2178          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2179        }
2180      }
2181      if( azArg==0 ) break;
2182      for(i=0; i<nArg; i++){
2183        int w = aExplainWidth[i];
2184        if( i==nArg-1 ) w = 0;
2185        if( azArg[i] && strlenChar(azArg[i])>w ){
2186          w = strlenChar(azArg[i]);
2187        }
2188        if( i==1 && p->aiIndent && p->pStmt ){
2189          if( p->iIndent<p->nIndent ){
2190            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2191          }
2192          p->iIndent++;
2193        }
2194        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2195        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2196      }
2197      break;
2198    }
2199    case MODE_Semi: {   /* .schema and .fullschema output */
2200      printSchemaLine(p->out, azArg[0], ";\n");
2201      break;
2202    }
2203    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2204      char *z;
2205      int j;
2206      int nParen = 0;
2207      char cEnd = 0;
2208      char c;
2209      int nLine = 0;
2210      assert( nArg==1 );
2211      if( azArg[0]==0 ) break;
2212      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2213       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2214      ){
2215        utf8_printf(p->out, "%s;\n", azArg[0]);
2216        break;
2217      }
2218      z = sqlite3_mprintf("%s", azArg[0]);
2219      shell_check_oom(z);
2220      j = 0;
2221      for(i=0; IsSpace(z[i]); i++){}
2222      for(; (c = z[i])!=0; i++){
2223        if( IsSpace(c) ){
2224          if( z[j-1]=='\r' ) z[j-1] = '\n';
2225          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2226        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2227          j--;
2228        }
2229        z[j++] = c;
2230      }
2231      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2232      z[j] = 0;
2233      if( strlen30(z)>=79 ){
2234        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2235          if( c==cEnd ){
2236            cEnd = 0;
2237          }else if( c=='"' || c=='\'' || c=='`' ){
2238            cEnd = c;
2239          }else if( c=='[' ){
2240            cEnd = ']';
2241          }else if( c=='-' && z[i+1]=='-' ){
2242            cEnd = '\n';
2243          }else if( c=='(' ){
2244            nParen++;
2245          }else if( c==')' ){
2246            nParen--;
2247            if( nLine>0 && nParen==0 && j>0 ){
2248              printSchemaLineN(p->out, z, j, "\n");
2249              j = 0;
2250            }
2251          }
2252          z[j++] = c;
2253          if( nParen==1 && cEnd==0
2254           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2255          ){
2256            if( c=='\n' ) j--;
2257            printSchemaLineN(p->out, z, j, "\n  ");
2258            j = 0;
2259            nLine++;
2260            while( IsSpace(z[i+1]) ){ i++; }
2261          }
2262        }
2263        z[j] = 0;
2264      }
2265      printSchemaLine(p->out, z, ";\n");
2266      sqlite3_free(z);
2267      break;
2268    }
2269    case MODE_List: {
2270      if( p->cnt++==0 && p->showHeader ){
2271        for(i=0; i<nArg; i++){
2272          utf8_printf(p->out,"%s%s",azCol[i],
2273                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2274        }
2275      }
2276      if( azArg==0 ) break;
2277      for(i=0; i<nArg; i++){
2278        char *z = azArg[i];
2279        if( z==0 ) z = p->nullValue;
2280        utf8_printf(p->out, "%s", z);
2281        if( i<nArg-1 ){
2282          utf8_printf(p->out, "%s", p->colSeparator);
2283        }else{
2284          utf8_printf(p->out, "%s", p->rowSeparator);
2285        }
2286      }
2287      break;
2288    }
2289    case MODE_Html: {
2290      if( p->cnt++==0 && p->showHeader ){
2291        raw_printf(p->out,"<TR>");
2292        for(i=0; i<nArg; i++){
2293          raw_printf(p->out,"<TH>");
2294          output_html_string(p->out, azCol[i]);
2295          raw_printf(p->out,"</TH>\n");
2296        }
2297        raw_printf(p->out,"</TR>\n");
2298      }
2299      if( azArg==0 ) break;
2300      raw_printf(p->out,"<TR>");
2301      for(i=0; i<nArg; i++){
2302        raw_printf(p->out,"<TD>");
2303        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2304        raw_printf(p->out,"</TD>\n");
2305      }
2306      raw_printf(p->out,"</TR>\n");
2307      break;
2308    }
2309    case MODE_Tcl: {
2310      if( p->cnt++==0 && p->showHeader ){
2311        for(i=0; i<nArg; i++){
2312          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2313          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2314        }
2315        utf8_printf(p->out, "%s", p->rowSeparator);
2316      }
2317      if( azArg==0 ) break;
2318      for(i=0; i<nArg; i++){
2319        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2320        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2321      }
2322      utf8_printf(p->out, "%s", p->rowSeparator);
2323      break;
2324    }
2325    case MODE_Csv: {
2326      setBinaryMode(p->out, 1);
2327      if( p->cnt++==0 && p->showHeader ){
2328        for(i=0; i<nArg; i++){
2329          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2330        }
2331        utf8_printf(p->out, "%s", p->rowSeparator);
2332      }
2333      if( nArg>0 ){
2334        for(i=0; i<nArg; i++){
2335          output_csv(p, azArg[i], i<nArg-1);
2336        }
2337        utf8_printf(p->out, "%s", p->rowSeparator);
2338      }
2339      setTextMode(p->out, 1);
2340      break;
2341    }
2342    case MODE_Insert: {
2343      if( azArg==0 ) break;
2344      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2345      if( p->showHeader ){
2346        raw_printf(p->out,"(");
2347        for(i=0; i<nArg; i++){
2348          if( i>0 ) raw_printf(p->out, ",");
2349          if( quoteChar(azCol[i]) ){
2350            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2351            shell_check_oom(z);
2352            utf8_printf(p->out, "%s", z);
2353            sqlite3_free(z);
2354          }else{
2355            raw_printf(p->out, "%s", azCol[i]);
2356          }
2357        }
2358        raw_printf(p->out,")");
2359      }
2360      p->cnt++;
2361      for(i=0; i<nArg; i++){
2362        raw_printf(p->out, i>0 ? "," : " VALUES(");
2363        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2364          utf8_printf(p->out,"NULL");
2365        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2366          if( ShellHasFlag(p, SHFLG_Newlines) ){
2367            output_quoted_string(p->out, azArg[i]);
2368          }else{
2369            output_quoted_escaped_string(p->out, azArg[i]);
2370          }
2371        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2372          utf8_printf(p->out,"%s", azArg[i]);
2373        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2374          char z[50];
2375          double r = sqlite3_column_double(p->pStmt, i);
2376          sqlite3_uint64 ur;
2377          memcpy(&ur,&r,sizeof(r));
2378          if( ur==0x7ff0000000000000LL ){
2379            raw_printf(p->out, "1e999");
2380          }else if( ur==0xfff0000000000000LL ){
2381            raw_printf(p->out, "-1e999");
2382          }else{
2383            sqlite3_int64 ir = (sqlite3_int64)r;
2384            if( r==(double)ir ){
2385              sqlite3_snprintf(50,z,"%lld.0", ir);
2386            }else{
2387              sqlite3_snprintf(50,z,"%!.20g", r);
2388            }
2389            raw_printf(p->out, "%s", z);
2390          }
2391        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2392          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2393          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2394          output_hex_blob(p->out, pBlob, nBlob);
2395        }else if( isNumber(azArg[i], 0) ){
2396          utf8_printf(p->out,"%s", azArg[i]);
2397        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2398          output_quoted_string(p->out, azArg[i]);
2399        }else{
2400          output_quoted_escaped_string(p->out, azArg[i]);
2401        }
2402      }
2403      raw_printf(p->out,");\n");
2404      break;
2405    }
2406    case MODE_Json: {
2407      if( azArg==0 ) break;
2408      if( p->cnt==0 ){
2409        fputs("[{", p->out);
2410      }else{
2411        fputs(",\n{", p->out);
2412      }
2413      p->cnt++;
2414      for(i=0; i<nArg; i++){
2415        output_json_string(p->out, azCol[i], -1);
2416        putc(':', p->out);
2417        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2418          fputs("null",p->out);
2419        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2420          char z[50];
2421          double r = sqlite3_column_double(p->pStmt, i);
2422          sqlite3_uint64 ur;
2423          memcpy(&ur,&r,sizeof(r));
2424          if( ur==0x7ff0000000000000LL ){
2425            raw_printf(p->out, "1e999");
2426          }else if( ur==0xfff0000000000000LL ){
2427            raw_printf(p->out, "-1e999");
2428          }else{
2429            sqlite3_snprintf(50,z,"%!.20g", r);
2430            raw_printf(p->out, "%s", z);
2431          }
2432        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2433          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2434          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2435          output_json_string(p->out, pBlob, nBlob);
2436        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2437          output_json_string(p->out, azArg[i], -1);
2438        }else{
2439          utf8_printf(p->out,"%s", azArg[i]);
2440        }
2441        if( i<nArg-1 ){
2442          putc(',', p->out);
2443        }
2444      }
2445      putc('}', p->out);
2446      break;
2447    }
2448    case MODE_Quote: {
2449      if( azArg==0 ) break;
2450      if( p->cnt==0 && p->showHeader ){
2451        for(i=0; i<nArg; i++){
2452          if( i>0 ) fputs(p->colSeparator, p->out);
2453          output_quoted_string(p->out, azCol[i]);
2454        }
2455        fputs(p->rowSeparator, p->out);
2456      }
2457      p->cnt++;
2458      for(i=0; i<nArg; i++){
2459        if( i>0 ) fputs(p->colSeparator, p->out);
2460        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2461          utf8_printf(p->out,"NULL");
2462        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2463          output_quoted_string(p->out, azArg[i]);
2464        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2465          utf8_printf(p->out,"%s", azArg[i]);
2466        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2467          char z[50];
2468          double r = sqlite3_column_double(p->pStmt, i);
2469          sqlite3_snprintf(50,z,"%!.20g", r);
2470          raw_printf(p->out, "%s", z);
2471        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2472          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2473          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2474          output_hex_blob(p->out, pBlob, nBlob);
2475        }else if( isNumber(azArg[i], 0) ){
2476          utf8_printf(p->out,"%s", azArg[i]);
2477        }else{
2478          output_quoted_string(p->out, azArg[i]);
2479        }
2480      }
2481      fputs(p->rowSeparator, p->out);
2482      break;
2483    }
2484    case MODE_Ascii: {
2485      if( p->cnt++==0 && p->showHeader ){
2486        for(i=0; i<nArg; i++){
2487          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2488          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2489        }
2490        utf8_printf(p->out, "%s", p->rowSeparator);
2491      }
2492      if( azArg==0 ) break;
2493      for(i=0; i<nArg; i++){
2494        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2495        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2496      }
2497      utf8_printf(p->out, "%s", p->rowSeparator);
2498      break;
2499    }
2500    case MODE_EQP: {
2501      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2502      break;
2503    }
2504  }
2505  return 0;
2506}
2507
2508/*
2509** This is the callback routine that the SQLite library
2510** invokes for each row of a query result.
2511*/
2512static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2513  /* since we don't have type info, call the shell_callback with a NULL value */
2514  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2515}
2516
2517/*
2518** This is the callback routine from sqlite3_exec() that appends all
2519** output onto the end of a ShellText object.
2520*/
2521static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2522  ShellText *p = (ShellText*)pArg;
2523  int i;
2524  UNUSED_PARAMETER(az);
2525  if( azArg==0 ) return 0;
2526  if( p->n ) appendText(p, "|", 0);
2527  for(i=0; i<nArg; i++){
2528    if( i ) appendText(p, ",", 0);
2529    if( azArg[i] ) appendText(p, azArg[i], 0);
2530  }
2531  return 0;
2532}
2533
2534/*
2535** Generate an appropriate SELFTEST table in the main database.
2536*/
2537static void createSelftestTable(ShellState *p){
2538  char *zErrMsg = 0;
2539  sqlite3_exec(p->db,
2540    "SAVEPOINT selftest_init;\n"
2541    "CREATE TABLE IF NOT EXISTS selftest(\n"
2542    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2543    "  op TEXT,\n"                   /* Operator:  memo run */
2544    "  cmd TEXT,\n"                  /* Command text */
2545    "  ans TEXT\n"                   /* Desired answer */
2546    ");"
2547    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2548    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2549    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2550    "         'memo','Tests generated by --init');\n"
2551    "INSERT INTO [_shell$self]\n"
2552    "  SELECT 'run',\n"
2553    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2554                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2555    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2556                          "FROM sqlite_schema ORDER BY 2',224));\n"
2557    "INSERT INTO [_shell$self]\n"
2558    "  SELECT 'run',"
2559    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2560    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2561    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2562    "  FROM (\n"
2563    "    SELECT name FROM sqlite_schema\n"
2564    "     WHERE type='table'\n"
2565    "       AND name<>'selftest'\n"
2566    "       AND coalesce(rootpage,0)>0\n"
2567    "  )\n"
2568    " ORDER BY name;\n"
2569    "INSERT INTO [_shell$self]\n"
2570    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2571    "INSERT INTO selftest(tno,op,cmd,ans)"
2572    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2573    "DROP TABLE [_shell$self];"
2574    ,0,0,&zErrMsg);
2575  if( zErrMsg ){
2576    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2577    sqlite3_free(zErrMsg);
2578  }
2579  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2580}
2581
2582
2583/*
2584** Set the destination table field of the ShellState structure to
2585** the name of the table given.  Escape any quote characters in the
2586** table name.
2587*/
2588static void set_table_name(ShellState *p, const char *zName){
2589  int i, n;
2590  char cQuote;
2591  char *z;
2592
2593  if( p->zDestTable ){
2594    free(p->zDestTable);
2595    p->zDestTable = 0;
2596  }
2597  if( zName==0 ) return;
2598  cQuote = quoteChar(zName);
2599  n = strlen30(zName);
2600  if( cQuote ) n += n+2;
2601  z = p->zDestTable = malloc( n+1 );
2602  shell_check_oom(z);
2603  n = 0;
2604  if( cQuote ) z[n++] = cQuote;
2605  for(i=0; zName[i]; i++){
2606    z[n++] = zName[i];
2607    if( zName[i]==cQuote ) z[n++] = cQuote;
2608  }
2609  if( cQuote ) z[n++] = cQuote;
2610  z[n] = 0;
2611}
2612
2613/*
2614** Maybe construct two lines of text that point out the position of a
2615** syntax error.  Return a pointer to the text, in memory obtained from
2616** sqlite3_malloc().  Or, if the most recent error does not involve a
2617** specific token that we can point to, return an empty string.
2618**
2619** In all cases, the memory returned is obtained from sqlite3_malloc64()
2620** and should be released by the caller invoking sqlite3_free().
2621*/
2622static char *shell_error_context(const char *zSql, sqlite3 *db){
2623  int iOffset;
2624  size_t len;
2625  char *zCode;
2626  char *zMsg;
2627  int i;
2628  if( db==0
2629   || zSql==0
2630   || (iOffset = sqlite3_error_offset(db))<0
2631  ){
2632    return sqlite3_mprintf("");
2633  }
2634  while( iOffset>50 ){
2635    iOffset--;
2636    zSql++;
2637    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2638  }
2639  len = strlen(zSql);
2640  if( len>78 ){
2641    len = 78;
2642    while( (zSql[len]&0xc0)==0x80 ) len--;
2643  }
2644  zCode = sqlite3_mprintf("%.*s", len, zSql);
2645  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2646  if( iOffset<25 ){
2647    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2648  }else{
2649    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2650  }
2651  return zMsg;
2652}
2653
2654
2655/*
2656** Execute a query statement that will generate SQL output.  Print
2657** the result columns, comma-separated, on a line and then add a
2658** semicolon terminator to the end of that line.
2659**
2660** If the number of columns is 1 and that column contains text "--"
2661** then write the semicolon on a separate line.  That way, if a
2662** "--" comment occurs at the end of the statement, the comment
2663** won't consume the semicolon terminator.
2664*/
2665static int run_table_dump_query(
2666  ShellState *p,           /* Query context */
2667  const char *zSelect      /* SELECT statement to extract content */
2668){
2669  sqlite3_stmt *pSelect;
2670  int rc;
2671  int nResult;
2672  int i;
2673  const char *z;
2674  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2675  if( rc!=SQLITE_OK || !pSelect ){
2676    char *zContext = shell_error_context(zSelect, p->db);
2677    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2678                sqlite3_errmsg(p->db), zContext);
2679    sqlite3_free(zContext);
2680    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2681    return rc;
2682  }
2683  rc = sqlite3_step(pSelect);
2684  nResult = sqlite3_column_count(pSelect);
2685  while( rc==SQLITE_ROW ){
2686    z = (const char*)sqlite3_column_text(pSelect, 0);
2687    utf8_printf(p->out, "%s", z);
2688    for(i=1; i<nResult; i++){
2689      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2690    }
2691    if( z==0 ) z = "";
2692    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2693    if( z[0] ){
2694      raw_printf(p->out, "\n;\n");
2695    }else{
2696      raw_printf(p->out, ";\n");
2697    }
2698    rc = sqlite3_step(pSelect);
2699  }
2700  rc = sqlite3_finalize(pSelect);
2701  if( rc!=SQLITE_OK ){
2702    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2703                sqlite3_errmsg(p->db));
2704    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2705  }
2706  return rc;
2707}
2708
2709/*
2710** Allocate space and save off string indicating current error.
2711*/
2712static char *save_err_msg(
2713  sqlite3 *db,           /* Database to query */
2714  const char *zPhase,    /* When the error occcurs */
2715  int rc,                /* Error code returned from API */
2716  const char *zSql       /* SQL string, or NULL */
2717){
2718  char *zErr;
2719  char *zContext;
2720  sqlite3_str *pStr = sqlite3_str_new(0);
2721  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2722  if( rc>1 ){
2723    sqlite3_str_appendf(pStr, " (%d)", rc);
2724  }
2725  zContext = shell_error_context(zSql, db);
2726  if( zContext ){
2727    sqlite3_str_appendall(pStr, zContext);
2728    sqlite3_free(zContext);
2729  }
2730  zErr = sqlite3_str_finish(pStr);
2731  shell_check_oom(zErr);
2732  return zErr;
2733}
2734
2735#ifdef __linux__
2736/*
2737** Attempt to display I/O stats on Linux using /proc/PID/io
2738*/
2739static void displayLinuxIoStats(FILE *out){
2740  FILE *in;
2741  char z[200];
2742  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2743  in = fopen(z, "rb");
2744  if( in==0 ) return;
2745  while( fgets(z, sizeof(z), in)!=0 ){
2746    static const struct {
2747      const char *zPattern;
2748      const char *zDesc;
2749    } aTrans[] = {
2750      { "rchar: ",                  "Bytes received by read():" },
2751      { "wchar: ",                  "Bytes sent to write():"    },
2752      { "syscr: ",                  "Read() system calls:"      },
2753      { "syscw: ",                  "Write() system calls:"     },
2754      { "read_bytes: ",             "Bytes read from storage:"  },
2755      { "write_bytes: ",            "Bytes written to storage:" },
2756      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2757    };
2758    int i;
2759    for(i=0; i<ArraySize(aTrans); i++){
2760      int n = strlen30(aTrans[i].zPattern);
2761      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2762        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2763        break;
2764      }
2765    }
2766  }
2767  fclose(in);
2768}
2769#endif
2770
2771/*
2772** Display a single line of status using 64-bit values.
2773*/
2774static void displayStatLine(
2775  ShellState *p,            /* The shell context */
2776  char *zLabel,             /* Label for this one line */
2777  char *zFormat,            /* Format for the result */
2778  int iStatusCtrl,          /* Which status to display */
2779  int bReset                /* True to reset the stats */
2780){
2781  sqlite3_int64 iCur = -1;
2782  sqlite3_int64 iHiwtr = -1;
2783  int i, nPercent;
2784  char zLine[200];
2785  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2786  for(i=0, nPercent=0; zFormat[i]; i++){
2787    if( zFormat[i]=='%' ) nPercent++;
2788  }
2789  if( nPercent>1 ){
2790    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2791  }else{
2792    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2793  }
2794  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2795}
2796
2797/*
2798** Display memory stats.
2799*/
2800static int display_stats(
2801  sqlite3 *db,                /* Database to query */
2802  ShellState *pArg,           /* Pointer to ShellState */
2803  int bReset                  /* True to reset the stats */
2804){
2805  int iCur;
2806  int iHiwtr;
2807  FILE *out;
2808  if( pArg==0 || pArg->out==0 ) return 0;
2809  out = pArg->out;
2810
2811  if( pArg->pStmt && pArg->statsOn==2 ){
2812    int nCol, i, x;
2813    sqlite3_stmt *pStmt = pArg->pStmt;
2814    char z[100];
2815    nCol = sqlite3_column_count(pStmt);
2816    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2817    for(i=0; i<nCol; i++){
2818      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2819      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2820#ifndef SQLITE_OMIT_DECLTYPE
2821      sqlite3_snprintf(30, z+x, "declared type:");
2822      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2823#endif
2824#ifdef SQLITE_ENABLE_COLUMN_METADATA
2825      sqlite3_snprintf(30, z+x, "database name:");
2826      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2827      sqlite3_snprintf(30, z+x, "table name:");
2828      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2829      sqlite3_snprintf(30, z+x, "origin name:");
2830      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2831#endif
2832    }
2833  }
2834
2835  if( pArg->statsOn==3 ){
2836    if( pArg->pStmt ){
2837      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2838      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2839    }
2840    return 0;
2841  }
2842
2843  displayStatLine(pArg, "Memory Used:",
2844     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2845  displayStatLine(pArg, "Number of Outstanding Allocations:",
2846     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2847  if( pArg->shellFlgs & SHFLG_Pagecache ){
2848    displayStatLine(pArg, "Number of Pcache Pages Used:",
2849       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2850  }
2851  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2852     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2853  displayStatLine(pArg, "Largest Allocation:",
2854     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2855  displayStatLine(pArg, "Largest Pcache Allocation:",
2856     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2857#ifdef YYTRACKMAXSTACKDEPTH
2858  displayStatLine(pArg, "Deepest Parser Stack:",
2859     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2860#endif
2861
2862  if( db ){
2863    if( pArg->shellFlgs & SHFLG_Lookaside ){
2864      iHiwtr = iCur = -1;
2865      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2866                        &iCur, &iHiwtr, bReset);
2867      raw_printf(pArg->out,
2868              "Lookaside Slots Used:                %d (max %d)\n",
2869              iCur, iHiwtr);
2870      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2871                        &iCur, &iHiwtr, bReset);
2872      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2873              iHiwtr);
2874      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2875                        &iCur, &iHiwtr, bReset);
2876      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2877              iHiwtr);
2878      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2879                        &iCur, &iHiwtr, bReset);
2880      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2881              iHiwtr);
2882    }
2883    iHiwtr = iCur = -1;
2884    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2885    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2886            iCur);
2887    iHiwtr = iCur = -1;
2888    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2889    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2890    iHiwtr = iCur = -1;
2891    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2892    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2893    iHiwtr = iCur = -1;
2894    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2895    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2896    iHiwtr = iCur = -1;
2897    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2898    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2899    iHiwtr = iCur = -1;
2900    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2901    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2902            iCur);
2903    iHiwtr = iCur = -1;
2904    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2905    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2906            iCur);
2907  }
2908
2909  if( pArg->pStmt ){
2910    int iHit, iMiss;
2911    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2912                               bReset);
2913    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2914    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2915    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2916    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2917    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2918    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2919    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2920    if( iHit || iMiss ){
2921      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2922            iHit, iHit+iMiss);
2923    }
2924    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2925    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2926    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2927    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2928    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2929    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2930    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2931    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2932  }
2933
2934#ifdef __linux__
2935  displayLinuxIoStats(pArg->out);
2936#endif
2937
2938  /* Do not remove this machine readable comment: extra-stats-output-here */
2939
2940  return 0;
2941}
2942
2943/*
2944** Display scan stats.
2945*/
2946static void display_scanstats(
2947  sqlite3 *db,                    /* Database to query */
2948  ShellState *pArg                /* Pointer to ShellState */
2949){
2950#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2951  UNUSED_PARAMETER(db);
2952  UNUSED_PARAMETER(pArg);
2953#else
2954  int i, k, n, mx;
2955  raw_printf(pArg->out, "-------- scanstats --------\n");
2956  mx = 0;
2957  for(k=0; k<=mx; k++){
2958    double rEstLoop = 1.0;
2959    for(i=n=0; 1; i++){
2960      sqlite3_stmt *p = pArg->pStmt;
2961      sqlite3_int64 nLoop, nVisit;
2962      double rEst;
2963      int iSid;
2964      const char *zExplain;
2965      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2966        break;
2967      }
2968      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2969      if( iSid>mx ) mx = iSid;
2970      if( iSid!=k ) continue;
2971      if( n==0 ){
2972        rEstLoop = (double)nLoop;
2973        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2974      }
2975      n++;
2976      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2977      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2978      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2979      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2980      rEstLoop *= rEst;
2981      raw_printf(pArg->out,
2982          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2983          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2984      );
2985    }
2986  }
2987  raw_printf(pArg->out, "---------------------------\n");
2988#endif
2989}
2990
2991/*
2992** Parameter azArray points to a zero-terminated array of strings. zStr
2993** points to a single nul-terminated string. Return non-zero if zStr
2994** is equal, according to strcmp(), to any of the strings in the array.
2995** Otherwise, return zero.
2996*/
2997static int str_in_array(const char *zStr, const char **azArray){
2998  int i;
2999  for(i=0; azArray[i]; i++){
3000    if( 0==strcmp(zStr, azArray[i]) ) return 1;
3001  }
3002  return 0;
3003}
3004
3005/*
3006** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3007** and populate the ShellState.aiIndent[] array with the number of
3008** spaces each opcode should be indented before it is output.
3009**
3010** The indenting rules are:
3011**
3012**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3013**       all opcodes that occur between the p2 jump destination and the opcode
3014**       itself by 2 spaces.
3015**
3016**     * Do the previous for "Return" instructions for when P2 is positive.
3017**       See tag-20220407a in wherecode.c and vdbe.c.
3018**
3019**     * For each "Goto", if the jump destination is earlier in the program
3020**       and ends on one of:
3021**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
3022**       or if the P1 parameter is one instead of zero,
3023**       then indent all opcodes between the earlier instruction
3024**       and "Goto" by 2 spaces.
3025*/
3026static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3027  const char *zSql;               /* The text of the SQL statement */
3028  const char *z;                  /* Used to check if this is an EXPLAIN */
3029  int *abYield = 0;               /* True if op is an OP_Yield */
3030  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
3031  int iOp;                        /* Index of operation in p->aiIndent[] */
3032
3033  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3034                           "Return", 0 };
3035  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3036                            "Rewind", 0 };
3037  const char *azGoto[] = { "Goto", 0 };
3038
3039  /* Try to figure out if this is really an EXPLAIN statement. If this
3040  ** cannot be verified, return early.  */
3041  if( sqlite3_column_count(pSql)!=8 ){
3042    p->cMode = p->mode;
3043    return;
3044  }
3045  zSql = sqlite3_sql(pSql);
3046  if( zSql==0 ) return;
3047  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3048  if( sqlite3_strnicmp(z, "explain", 7) ){
3049    p->cMode = p->mode;
3050    return;
3051  }
3052
3053  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3054    int i;
3055    int iAddr = sqlite3_column_int(pSql, 0);
3056    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3057
3058    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3059    ** p2 is an instruction address, set variable p2op to the index of that
3060    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3061    ** the current instruction is part of a sub-program generated by an
3062    ** SQL trigger or foreign key.  */
3063    int p2 = sqlite3_column_int(pSql, 3);
3064    int p2op = (p2 + (iOp-iAddr));
3065
3066    /* Grow the p->aiIndent array as required */
3067    if( iOp>=nAlloc ){
3068      if( iOp==0 ){
3069        /* Do further verfication that this is explain output.  Abort if
3070        ** it is not */
3071        static const char *explainCols[] = {
3072           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3073        int jj;
3074        for(jj=0; jj<ArraySize(explainCols); jj++){
3075          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3076            p->cMode = p->mode;
3077            sqlite3_reset(pSql);
3078            return;
3079          }
3080        }
3081      }
3082      nAlloc += 100;
3083      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3084      shell_check_oom(p->aiIndent);
3085      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3086      shell_check_oom(abYield);
3087    }
3088    abYield[iOp] = str_in_array(zOp, azYield);
3089    p->aiIndent[iOp] = 0;
3090    p->nIndent = iOp+1;
3091
3092    if( str_in_array(zOp, azNext) && p2op>0 ){
3093      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3094    }
3095    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3096     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3097    ){
3098      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3099    }
3100  }
3101
3102  p->iIndent = 0;
3103  sqlite3_free(abYield);
3104  sqlite3_reset(pSql);
3105}
3106
3107/*
3108** Free the array allocated by explain_data_prepare().
3109*/
3110static void explain_data_delete(ShellState *p){
3111  sqlite3_free(p->aiIndent);
3112  p->aiIndent = 0;
3113  p->nIndent = 0;
3114  p->iIndent = 0;
3115}
3116
3117/*
3118** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3119*/
3120static unsigned int savedSelectTrace;
3121static unsigned int savedWhereTrace;
3122static void disable_debug_trace_modes(void){
3123  unsigned int zero = 0;
3124  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3125  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3126  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3127  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3128}
3129static void restore_debug_trace_modes(void){
3130  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3131  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3132}
3133
3134/* Create the TEMP table used to store parameter bindings */
3135static void bind_table_init(ShellState *p){
3136  int wrSchema = 0;
3137  int defensiveMode = 0;
3138  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3139  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3140  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3141  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3142  sqlite3_exec(p->db,
3143    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3144    "  key TEXT PRIMARY KEY,\n"
3145    "  value\n"
3146    ") WITHOUT ROWID;",
3147    0, 0, 0);
3148  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3149  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3150}
3151
3152/*
3153** Bind parameters on a prepared statement.
3154**
3155** Parameter bindings are taken from a TEMP table of the form:
3156**
3157**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3158**    WITHOUT ROWID;
3159**
3160** No bindings occur if this table does not exist.  The name of the table
3161** begins with "sqlite_" so that it will not collide with ordinary application
3162** tables.  The table must be in the TEMP schema.
3163*/
3164static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3165  int nVar;
3166  int i;
3167  int rc;
3168  sqlite3_stmt *pQ = 0;
3169
3170  nVar = sqlite3_bind_parameter_count(pStmt);
3171  if( nVar==0 ) return;  /* Nothing to do */
3172  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3173                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3174    return; /* Parameter table does not exist */
3175  }
3176  rc = sqlite3_prepare_v2(pArg->db,
3177          "SELECT value FROM temp.sqlite_parameters"
3178          " WHERE key=?1", -1, &pQ, 0);
3179  if( rc || pQ==0 ) return;
3180  for(i=1; i<=nVar; i++){
3181    char zNum[30];
3182    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3183    if( zVar==0 ){
3184      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3185      zVar = zNum;
3186    }
3187    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3188    if( sqlite3_step(pQ)==SQLITE_ROW ){
3189      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3190    }else{
3191      sqlite3_bind_null(pStmt, i);
3192    }
3193    sqlite3_reset(pQ);
3194  }
3195  sqlite3_finalize(pQ);
3196}
3197
3198/*
3199** UTF8 box-drawing characters.  Imagine box lines like this:
3200**
3201**           1
3202**           |
3203**       4 --+-- 2
3204**           |
3205**           3
3206**
3207** Each box characters has between 2 and 4 of the lines leading from
3208** the center.  The characters are here identified by the numbers of
3209** their corresponding lines.
3210*/
3211#define BOX_24   "\342\224\200"  /* U+2500 --- */
3212#define BOX_13   "\342\224\202"  /* U+2502  |  */
3213#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3214#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3215#define BOX_12   "\342\224\224"  /* U+2514  '- */
3216#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3217#define BOX_123  "\342\224\234"  /* U+251c  |- */
3218#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3219#define BOX_234  "\342\224\254"  /* U+252c -,- */
3220#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3221#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3222
3223/* Draw horizontal line N characters long using unicode box
3224** characters
3225*/
3226static void print_box_line(FILE *out, int N){
3227  const char zDash[] =
3228      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3229      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3230  const int nDash = sizeof(zDash) - 1;
3231  N *= 3;
3232  while( N>nDash ){
3233    utf8_printf(out, zDash);
3234    N -= nDash;
3235  }
3236  utf8_printf(out, "%.*s", N, zDash);
3237}
3238
3239/*
3240** Draw a horizontal separator for a MODE_Box table.
3241*/
3242static void print_box_row_separator(
3243  ShellState *p,
3244  int nArg,
3245  const char *zSep1,
3246  const char *zSep2,
3247  const char *zSep3
3248){
3249  int i;
3250  if( nArg>0 ){
3251    utf8_printf(p->out, "%s", zSep1);
3252    print_box_line(p->out, p->actualWidth[0]+2);
3253    for(i=1; i<nArg; i++){
3254      utf8_printf(p->out, "%s", zSep2);
3255      print_box_line(p->out, p->actualWidth[i]+2);
3256    }
3257    utf8_printf(p->out, "%s", zSep3);
3258  }
3259  fputs("\n", p->out);
3260}
3261
3262/*
3263** z[] is a line of text that is to be displayed the .mode box or table or
3264** similar tabular formats.  z[] might contain control characters such
3265** as \n, \t, \f, or \r.
3266**
3267** Compute characters to display on the first line of z[].  Stop at the
3268** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3269** from malloc()) of that first line, which caller should free sometime.
3270** Write anything to display on the next line into *pzTail.  If this is
3271** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3272*/
3273static char *translateForDisplayAndDup(
3274  const unsigned char *z,            /* Input text to be transformed */
3275  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3276  int mxWidth,                       /* Max width.  0 means no limit */
3277  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3278){
3279  int i;                 /* Input bytes consumed */
3280  int j;                 /* Output bytes generated */
3281  int k;                 /* Input bytes to be displayed */
3282  int n;                 /* Output column number */
3283  unsigned char *zOut;   /* Output text */
3284
3285  if( z==0 ){
3286    *pzTail = 0;
3287    return 0;
3288  }
3289  if( mxWidth<0 ) mxWidth = -mxWidth;
3290  if( mxWidth==0 ) mxWidth = 1000000;
3291  i = j = n = 0;
3292  while( n<mxWidth ){
3293    if( z[i]>=' ' ){
3294      n++;
3295      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3296      continue;
3297    }
3298    if( z[i]=='\t' ){
3299      do{
3300        n++;
3301        j++;
3302      }while( (n&7)!=0 && n<mxWidth );
3303      i++;
3304      continue;
3305    }
3306    break;
3307  }
3308  if( n>=mxWidth && bWordWrap  ){
3309    /* Perhaps try to back up to a better place to break the line */
3310    for(k=i; k>i/2; k--){
3311      if( isspace(z[k-1]) ) break;
3312    }
3313    if( k<=i/2 ){
3314      for(k=i; k>i/2; k--){
3315        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3316      }
3317    }
3318    if( k<=i/2 ){
3319      k = i;
3320    }else{
3321      i = k;
3322      while( z[i]==' ' ) i++;
3323    }
3324  }else{
3325    k = i;
3326  }
3327  if( n>=mxWidth && z[i]>=' ' ){
3328   *pzTail = &z[i];
3329  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3330    *pzTail = z[i+2] ? &z[i+2] : 0;
3331  }else if( z[i]==0 || z[i+1]==0 ){
3332    *pzTail = 0;
3333  }else{
3334    *pzTail = &z[i+1];
3335  }
3336  zOut = malloc( j+1 );
3337  shell_check_oom(zOut);
3338  i = j = n = 0;
3339  while( i<k ){
3340    if( z[i]>=' ' ){
3341      n++;
3342      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3343      continue;
3344    }
3345    if( z[i]=='\t' ){
3346      do{
3347        n++;
3348        zOut[j++] = ' ';
3349      }while( (n&7)!=0 && n<mxWidth );
3350      i++;
3351      continue;
3352    }
3353    break;
3354  }
3355  zOut[j] = 0;
3356  return (char*)zOut;
3357}
3358
3359/* Extract the value of the i-th current column for pStmt as an SQL literal
3360** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3361** the caller.
3362*/
3363static char *quoted_column(sqlite3_stmt *pStmt, int i){
3364  switch( sqlite3_column_type(pStmt, i) ){
3365    case SQLITE_NULL: {
3366      return sqlite3_mprintf("NULL");
3367    }
3368    case SQLITE_INTEGER:
3369    case SQLITE_FLOAT: {
3370      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3371    }
3372    case SQLITE_TEXT: {
3373      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3374    }
3375    case SQLITE_BLOB: {
3376      int j;
3377      sqlite3_str *pStr = sqlite3_str_new(0);
3378      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3379      int n = sqlite3_column_bytes(pStmt,i);
3380      sqlite3_str_append(pStr, "x'", 2);
3381      for(j=0; j<n; j++){
3382        sqlite3_str_appendf(pStr, "%02x", a[j]);
3383      }
3384      sqlite3_str_append(pStr, "'", 1);
3385      return sqlite3_str_finish(pStr);
3386    }
3387  }
3388  return 0; /* Not reached */
3389}
3390
3391/*
3392** Run a prepared statement and output the result in one of the
3393** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3394** or MODE_Box.
3395**
3396** This is different from ordinary exec_prepared_stmt() in that
3397** it has to run the entire query and gather the results into memory
3398** first, in order to determine column widths, before providing
3399** any output.
3400*/
3401static void exec_prepared_stmt_columnar(
3402  ShellState *p,                        /* Pointer to ShellState */
3403  sqlite3_stmt *pStmt                   /* Statment to run */
3404){
3405  sqlite3_int64 nRow = 0;
3406  int nColumn = 0;
3407  char **azData = 0;
3408  sqlite3_int64 nAlloc = 0;
3409  char *abRowDiv = 0;
3410  const unsigned char *uz;
3411  const char *z;
3412  char **azQuoted = 0;
3413  int rc;
3414  sqlite3_int64 i, nData;
3415  int j, nTotal, w, n;
3416  const char *colSep = 0;
3417  const char *rowSep = 0;
3418  const unsigned char **azNextLine = 0;
3419  int bNextLine = 0;
3420  int bMultiLineRowExists = 0;
3421  int bw = p->cmOpts.bWordWrap;
3422  const char *zEmpty = "";
3423  const char *zShowNull = p->nullValue;
3424
3425  rc = sqlite3_step(pStmt);
3426  if( rc!=SQLITE_ROW ) return;
3427  nColumn = sqlite3_column_count(pStmt);
3428  nAlloc = nColumn*4;
3429  if( nAlloc<=0 ) nAlloc = 1;
3430  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3431  shell_check_oom(azData);
3432  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3433  shell_check_oom((void*)azNextLine);
3434  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3435  if( p->cmOpts.bQuote ){
3436    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3437    shell_check_oom(azQuoted);
3438    memset(azQuoted, 0, nColumn*sizeof(char*) );
3439  }
3440  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3441  shell_check_oom(abRowDiv);
3442  if( nColumn>p->nWidth ){
3443    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3444    shell_check_oom(p->colWidth);
3445    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3446    p->nWidth = nColumn;
3447    p->actualWidth = &p->colWidth[nColumn];
3448  }
3449  memset(p->actualWidth, 0, nColumn*sizeof(int));
3450  for(i=0; i<nColumn; i++){
3451    w = p->colWidth[i];
3452    if( w<0 ) w = -w;
3453    p->actualWidth[i] = w;
3454  }
3455  for(i=0; i<nColumn; i++){
3456    const unsigned char *zNotUsed;
3457    int wx = p->colWidth[i];
3458    if( wx==0 ){
3459      wx = p->cmOpts.iWrap;
3460    }
3461    if( wx<0 ) wx = -wx;
3462    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3463    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3464  }
3465  do{
3466    int useNextLine = bNextLine;
3467    bNextLine = 0;
3468    if( (nRow+2)*nColumn >= nAlloc ){
3469      nAlloc *= 2;
3470      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3471      shell_check_oom(azData);
3472      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3473      shell_check_oom(abRowDiv);
3474    }
3475    abRowDiv[nRow] = 1;
3476    nRow++;
3477    for(i=0; i<nColumn; i++){
3478      int wx = p->colWidth[i];
3479      if( wx==0 ){
3480        wx = p->cmOpts.iWrap;
3481      }
3482      if( wx<0 ) wx = -wx;
3483      if( useNextLine ){
3484        uz = azNextLine[i];
3485        if( uz==0 ) uz = (u8*)zEmpty;
3486      }else if( p->cmOpts.bQuote ){
3487        sqlite3_free(azQuoted[i]);
3488        azQuoted[i] = quoted_column(pStmt,i);
3489        uz = (const unsigned char*)azQuoted[i];
3490      }else{
3491        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3492        if( uz==0 ) uz = (u8*)zShowNull;
3493      }
3494      azData[nRow*nColumn + i]
3495        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3496      if( azNextLine[i] ){
3497        bNextLine = 1;
3498        abRowDiv[nRow-1] = 0;
3499        bMultiLineRowExists = 1;
3500      }
3501    }
3502  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3503  nTotal = nColumn*(nRow+1);
3504  for(i=0; i<nTotal; i++){
3505    z = azData[i];
3506    if( z==0 ) z = (char*)zEmpty;
3507    n = strlenChar(z);
3508    j = i%nColumn;
3509    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3510  }
3511  if( seenInterrupt ) goto columnar_end;
3512  if( nColumn==0 ) goto columnar_end;
3513  switch( p->cMode ){
3514    case MODE_Column: {
3515      colSep = "  ";
3516      rowSep = "\n";
3517      if( p->showHeader ){
3518        for(i=0; i<nColumn; i++){
3519          w = p->actualWidth[i];
3520          if( p->colWidth[i]<0 ) w = -w;
3521          utf8_width_print(p->out, w, azData[i]);
3522          fputs(i==nColumn-1?"\n":"  ", p->out);
3523        }
3524        for(i=0; i<nColumn; i++){
3525          print_dashes(p->out, p->actualWidth[i]);
3526          fputs(i==nColumn-1?"\n":"  ", p->out);
3527        }
3528      }
3529      break;
3530    }
3531    case MODE_Table: {
3532      colSep = " | ";
3533      rowSep = " |\n";
3534      print_row_separator(p, nColumn, "+");
3535      fputs("| ", p->out);
3536      for(i=0; i<nColumn; i++){
3537        w = p->actualWidth[i];
3538        n = strlenChar(azData[i]);
3539        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3540        fputs(i==nColumn-1?" |\n":" | ", p->out);
3541      }
3542      print_row_separator(p, nColumn, "+");
3543      break;
3544    }
3545    case MODE_Markdown: {
3546      colSep = " | ";
3547      rowSep = " |\n";
3548      fputs("| ", p->out);
3549      for(i=0; i<nColumn; i++){
3550        w = p->actualWidth[i];
3551        n = strlenChar(azData[i]);
3552        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3553        fputs(i==nColumn-1?" |\n":" | ", p->out);
3554      }
3555      print_row_separator(p, nColumn, "|");
3556      break;
3557    }
3558    case MODE_Box: {
3559      colSep = " " BOX_13 " ";
3560      rowSep = " " BOX_13 "\n";
3561      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3562      utf8_printf(p->out, BOX_13 " ");
3563      for(i=0; i<nColumn; i++){
3564        w = p->actualWidth[i];
3565        n = strlenChar(azData[i]);
3566        utf8_printf(p->out, "%*s%s%*s%s",
3567            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3568            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3569      }
3570      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3571      break;
3572    }
3573  }
3574  for(i=nColumn, j=0; i<nTotal; i++, j++){
3575    if( j==0 && p->cMode!=MODE_Column ){
3576      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3577    }
3578    z = azData[i];
3579    if( z==0 ) z = p->nullValue;
3580    w = p->actualWidth[j];
3581    if( p->colWidth[j]<0 ) w = -w;
3582    utf8_width_print(p->out, w, z);
3583    if( j==nColumn-1 ){
3584      utf8_printf(p->out, "%s", rowSep);
3585      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3586        if( p->cMode==MODE_Table ){
3587          print_row_separator(p, nColumn, "+");
3588        }else if( p->cMode==MODE_Box ){
3589          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3590        }else if( p->cMode==MODE_Column ){
3591          raw_printf(p->out, "\n");
3592        }
3593      }
3594      j = -1;
3595      if( seenInterrupt ) goto columnar_end;
3596    }else{
3597      utf8_printf(p->out, "%s", colSep);
3598    }
3599  }
3600  if( p->cMode==MODE_Table ){
3601    print_row_separator(p, nColumn, "+");
3602  }else if( p->cMode==MODE_Box ){
3603    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3604  }
3605columnar_end:
3606  if( seenInterrupt ){
3607    utf8_printf(p->out, "Interrupt\n");
3608  }
3609  nData = (nRow+1)*nColumn;
3610  for(i=0; i<nData; i++){
3611    z = azData[i];
3612    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3613  }
3614  sqlite3_free(azData);
3615  sqlite3_free((void*)azNextLine);
3616  sqlite3_free(abRowDiv);
3617  if( azQuoted ){
3618    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3619    sqlite3_free(azQuoted);
3620  }
3621}
3622
3623/*
3624** Run a prepared statement
3625*/
3626static void exec_prepared_stmt(
3627  ShellState *pArg,                                /* Pointer to ShellState */
3628  sqlite3_stmt *pStmt                              /* Statment to run */
3629){
3630  int rc;
3631  sqlite3_uint64 nRow = 0;
3632
3633  if( pArg->cMode==MODE_Column
3634   || pArg->cMode==MODE_Table
3635   || pArg->cMode==MODE_Box
3636   || pArg->cMode==MODE_Markdown
3637  ){
3638    exec_prepared_stmt_columnar(pArg, pStmt);
3639    return;
3640  }
3641
3642  /* perform the first step.  this will tell us if we
3643  ** have a result set or not and how wide it is.
3644  */
3645  rc = sqlite3_step(pStmt);
3646  /* if we have a result set... */
3647  if( SQLITE_ROW == rc ){
3648    /* allocate space for col name ptr, value ptr, and type */
3649    int nCol = sqlite3_column_count(pStmt);
3650    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3651    if( !pData ){
3652      shell_out_of_memory();
3653    }else{
3654      char **azCols = (char **)pData;      /* Names of result columns */
3655      char **azVals = &azCols[nCol];       /* Results */
3656      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3657      int i, x;
3658      assert(sizeof(int) <= sizeof(char *));
3659      /* save off ptrs to column names */
3660      for(i=0; i<nCol; i++){
3661        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3662      }
3663      do{
3664        nRow++;
3665        /* extract the data and data types */
3666        for(i=0; i<nCol; i++){
3667          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3668          if( x==SQLITE_BLOB
3669           && pArg
3670           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3671          ){
3672            azVals[i] = "";
3673          }else{
3674            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3675          }
3676          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3677            rc = SQLITE_NOMEM;
3678            break; /* from for */
3679          }
3680        } /* end for */
3681
3682        /* if data and types extracted successfully... */
3683        if( SQLITE_ROW == rc ){
3684          /* call the supplied callback with the result row data */
3685          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3686            rc = SQLITE_ABORT;
3687          }else{
3688            rc = sqlite3_step(pStmt);
3689          }
3690        }
3691      } while( SQLITE_ROW == rc );
3692      sqlite3_free(pData);
3693      if( pArg->cMode==MODE_Json ){
3694        fputs("]\n", pArg->out);
3695      }else if( pArg->cMode==MODE_Count ){
3696        char zBuf[200];
3697        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3698                         nRow, nRow!=1 ? "s" : "");
3699        printf("%s", zBuf);
3700      }
3701    }
3702  }
3703}
3704
3705#ifndef SQLITE_OMIT_VIRTUALTABLE
3706/*
3707** This function is called to process SQL if the previous shell command
3708** was ".expert". It passes the SQL in the second argument directly to
3709** the sqlite3expert object.
3710**
3711** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3712** code. In this case, (*pzErr) may be set to point to a buffer containing
3713** an English language error message. It is the responsibility of the
3714** caller to eventually free this buffer using sqlite3_free().
3715*/
3716static int expertHandleSQL(
3717  ShellState *pState,
3718  const char *zSql,
3719  char **pzErr
3720){
3721  assert( pState->expert.pExpert );
3722  assert( pzErr==0 || *pzErr==0 );
3723  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3724}
3725
3726/*
3727** This function is called either to silently clean up the object
3728** created by the ".expert" command (if bCancel==1), or to generate a
3729** report from it and then clean it up (if bCancel==0).
3730**
3731** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3732** code. In this case, (*pzErr) may be set to point to a buffer containing
3733** an English language error message. It is the responsibility of the
3734** caller to eventually free this buffer using sqlite3_free().
3735*/
3736static int expertFinish(
3737  ShellState *pState,
3738  int bCancel,
3739  char **pzErr
3740){
3741  int rc = SQLITE_OK;
3742  sqlite3expert *p = pState->expert.pExpert;
3743  assert( p );
3744  assert( bCancel || pzErr==0 || *pzErr==0 );
3745  if( bCancel==0 ){
3746    FILE *out = pState->out;
3747    int bVerbose = pState->expert.bVerbose;
3748
3749    rc = sqlite3_expert_analyze(p, pzErr);
3750    if( rc==SQLITE_OK ){
3751      int nQuery = sqlite3_expert_count(p);
3752      int i;
3753
3754      if( bVerbose ){
3755        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3756        raw_printf(out, "-- Candidates -----------------------------\n");
3757        raw_printf(out, "%s\n", zCand);
3758      }
3759      for(i=0; i<nQuery; i++){
3760        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3761        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3762        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3763        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3764        if( bVerbose ){
3765          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3766          raw_printf(out, "%s\n\n", zSql);
3767        }
3768        raw_printf(out, "%s\n", zIdx);
3769        raw_printf(out, "%s\n", zEQP);
3770      }
3771    }
3772  }
3773  sqlite3_expert_destroy(p);
3774  pState->expert.pExpert = 0;
3775  return rc;
3776}
3777
3778/*
3779** Implementation of ".expert" dot command.
3780*/
3781static int expertDotCommand(
3782  ShellState *pState,             /* Current shell tool state */
3783  char **azArg,                   /* Array of arguments passed to dot command */
3784  int nArg                        /* Number of entries in azArg[] */
3785){
3786  int rc = SQLITE_OK;
3787  char *zErr = 0;
3788  int i;
3789  int iSample = 0;
3790
3791  assert( pState->expert.pExpert==0 );
3792  memset(&pState->expert, 0, sizeof(ExpertInfo));
3793
3794  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3795    char *z = azArg[i];
3796    int n;
3797    if( z[0]=='-' && z[1]=='-' ) z++;
3798    n = strlen30(z);
3799    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3800      pState->expert.bVerbose = 1;
3801    }
3802    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3803      if( i==(nArg-1) ){
3804        raw_printf(stderr, "option requires an argument: %s\n", z);
3805        rc = SQLITE_ERROR;
3806      }else{
3807        iSample = (int)integerValue(azArg[++i]);
3808        if( iSample<0 || iSample>100 ){
3809          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3810          rc = SQLITE_ERROR;
3811        }
3812      }
3813    }
3814    else{
3815      raw_printf(stderr, "unknown option: %s\n", z);
3816      rc = SQLITE_ERROR;
3817    }
3818  }
3819
3820  if( rc==SQLITE_OK ){
3821    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3822    if( pState->expert.pExpert==0 ){
3823      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3824      rc = SQLITE_ERROR;
3825    }else{
3826      sqlite3_expert_config(
3827          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3828      );
3829    }
3830  }
3831  sqlite3_free(zErr);
3832
3833  return rc;
3834}
3835#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3836
3837/*
3838** Execute a statement or set of statements.  Print
3839** any result rows/columns depending on the current mode
3840** set via the supplied callback.
3841**
3842** This is very similar to SQLite's built-in sqlite3_exec()
3843** function except it takes a slightly different callback
3844** and callback data argument.
3845*/
3846static int shell_exec(
3847  ShellState *pArg,                         /* Pointer to ShellState */
3848  const char *zSql,                         /* SQL to be evaluated */
3849  char **pzErrMsg                           /* Error msg written here */
3850){
3851  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3852  int rc = SQLITE_OK;             /* Return Code */
3853  int rc2;
3854  const char *zLeftover;          /* Tail of unprocessed SQL */
3855  sqlite3 *db = pArg->db;
3856
3857  if( pzErrMsg ){
3858    *pzErrMsg = NULL;
3859  }
3860
3861#ifndef SQLITE_OMIT_VIRTUALTABLE
3862  if( pArg->expert.pExpert ){
3863    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3864    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3865  }
3866#endif
3867
3868  while( zSql[0] && (SQLITE_OK == rc) ){
3869    static const char *zStmtSql;
3870    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3871    if( SQLITE_OK != rc ){
3872      if( pzErrMsg ){
3873        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3874      }
3875    }else{
3876      if( !pStmt ){
3877        /* this happens for a comment or white-space */
3878        zSql = zLeftover;
3879        while( IsSpace(zSql[0]) ) zSql++;
3880        continue;
3881      }
3882      zStmtSql = sqlite3_sql(pStmt);
3883      if( zStmtSql==0 ) zStmtSql = "";
3884      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3885
3886      /* save off the prepared statment handle and reset row count */
3887      if( pArg ){
3888        pArg->pStmt = pStmt;
3889        pArg->cnt = 0;
3890      }
3891
3892      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3893      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3894        sqlite3_stmt *pExplain;
3895        char *zEQP;
3896        int triggerEQP = 0;
3897        disable_debug_trace_modes();
3898        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3899        if( pArg->autoEQP>=AUTOEQP_trigger ){
3900          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3901        }
3902        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3903        shell_check_oom(zEQP);
3904        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3905        if( rc==SQLITE_OK ){
3906          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3907            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3908            int iEqpId = sqlite3_column_int(pExplain, 0);
3909            int iParentId = sqlite3_column_int(pExplain, 1);
3910            if( zEQPLine==0 ) zEQPLine = "";
3911            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3912            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3913          }
3914          eqp_render(pArg);
3915        }
3916        sqlite3_finalize(pExplain);
3917        sqlite3_free(zEQP);
3918        if( pArg->autoEQP>=AUTOEQP_full ){
3919          /* Also do an EXPLAIN for ".eqp full" mode */
3920          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3921          shell_check_oom(zEQP);
3922          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3923          if( rc==SQLITE_OK ){
3924            pArg->cMode = MODE_Explain;
3925            explain_data_prepare(pArg, pExplain);
3926            exec_prepared_stmt(pArg, pExplain);
3927            explain_data_delete(pArg);
3928          }
3929          sqlite3_finalize(pExplain);
3930          sqlite3_free(zEQP);
3931        }
3932        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3933          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3934          /* Reprepare pStmt before reactiving trace modes */
3935          sqlite3_finalize(pStmt);
3936          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3937          if( pArg ) pArg->pStmt = pStmt;
3938        }
3939        restore_debug_trace_modes();
3940      }
3941
3942      if( pArg ){
3943        pArg->cMode = pArg->mode;
3944        if( pArg->autoExplain ){
3945          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3946            pArg->cMode = MODE_Explain;
3947          }
3948          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3949            pArg->cMode = MODE_EQP;
3950          }
3951        }
3952
3953        /* If the shell is currently in ".explain" mode, gather the extra
3954        ** data required to add indents to the output.*/
3955        if( pArg->cMode==MODE_Explain ){
3956          explain_data_prepare(pArg, pStmt);
3957        }
3958      }
3959
3960      bind_prepared_stmt(pArg, pStmt);
3961      exec_prepared_stmt(pArg, pStmt);
3962      explain_data_delete(pArg);
3963      eqp_render(pArg);
3964
3965      /* print usage stats if stats on */
3966      if( pArg && pArg->statsOn ){
3967        display_stats(db, pArg, 0);
3968      }
3969
3970      /* print loop-counters if required */
3971      if( pArg && pArg->scanstatsOn ){
3972        display_scanstats(db, pArg);
3973      }
3974
3975      /* Finalize the statement just executed. If this fails, save a
3976      ** copy of the error message. Otherwise, set zSql to point to the
3977      ** next statement to execute. */
3978      rc2 = sqlite3_finalize(pStmt);
3979      if( rc!=SQLITE_NOMEM ) rc = rc2;
3980      if( rc==SQLITE_OK ){
3981        zSql = zLeftover;
3982        while( IsSpace(zSql[0]) ) zSql++;
3983      }else if( pzErrMsg ){
3984        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3985      }
3986
3987      /* clear saved stmt handle */
3988      if( pArg ){
3989        pArg->pStmt = NULL;
3990      }
3991    }
3992  } /* end while */
3993
3994  return rc;
3995}
3996
3997/*
3998** Release memory previously allocated by tableColumnList().
3999*/
4000static void freeColumnList(char **azCol){
4001  int i;
4002  for(i=1; azCol[i]; i++){
4003    sqlite3_free(azCol[i]);
4004  }
4005  /* azCol[0] is a static string */
4006  sqlite3_free(azCol);
4007}
4008
4009/*
4010** Return a list of pointers to strings which are the names of all
4011** columns in table zTab.   The memory to hold the names is dynamically
4012** allocated and must be released by the caller using a subsequent call
4013** to freeColumnList().
4014**
4015** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
4016** value that needs to be preserved, then azCol[0] is filled in with the
4017** name of the rowid column.
4018**
4019** The first regular column in the table is azCol[1].  The list is terminated
4020** by an entry with azCol[i]==0.
4021*/
4022static char **tableColumnList(ShellState *p, const char *zTab){
4023  char **azCol = 0;
4024  sqlite3_stmt *pStmt;
4025  char *zSql;
4026  int nCol = 0;
4027  int nAlloc = 0;
4028  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
4029  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
4030  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4031  int rc;
4032
4033  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4034  shell_check_oom(zSql);
4035  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4036  sqlite3_free(zSql);
4037  if( rc ) return 0;
4038  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4039    if( nCol>=nAlloc-2 ){
4040      nAlloc = nAlloc*2 + nCol + 10;
4041      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4042      shell_check_oom(azCol);
4043    }
4044    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4045    shell_check_oom(azCol[nCol]);
4046    if( sqlite3_column_int(pStmt, 5) ){
4047      nPK++;
4048      if( nPK==1
4049       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4050                          "INTEGER")==0
4051      ){
4052        isIPK = 1;
4053      }else{
4054        isIPK = 0;
4055      }
4056    }
4057  }
4058  sqlite3_finalize(pStmt);
4059  if( azCol==0 ) return 0;
4060  azCol[0] = 0;
4061  azCol[nCol+1] = 0;
4062
4063  /* The decision of whether or not a rowid really needs to be preserved
4064  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4065  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4066  ** rowids on tables where the rowid is inaccessible because there are other
4067  ** columns in the table named "rowid", "_rowid_", and "oid".
4068  */
4069  if( preserveRowid && isIPK ){
4070    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4071    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4072    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4073    ** ROWID aliases.  To distinguish these cases, check to see if
4074    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4075    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4076    */
4077    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4078                           " WHERE origin='pk'", zTab);
4079    shell_check_oom(zSql);
4080    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4081    sqlite3_free(zSql);
4082    if( rc ){
4083      freeColumnList(azCol);
4084      return 0;
4085    }
4086    rc = sqlite3_step(pStmt);
4087    sqlite3_finalize(pStmt);
4088    preserveRowid = rc==SQLITE_ROW;
4089  }
4090  if( preserveRowid ){
4091    /* Only preserve the rowid if we can find a name to use for the
4092    ** rowid */
4093    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4094    int i, j;
4095    for(j=0; j<3; j++){
4096      for(i=1; i<=nCol; i++){
4097        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4098      }
4099      if( i>nCol ){
4100        /* At this point, we know that azRowid[j] is not the name of any
4101        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4102        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4103        ** tables will fail this last check */
4104        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4105        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4106        break;
4107      }
4108    }
4109  }
4110  return azCol;
4111}
4112
4113/*
4114** Toggle the reverse_unordered_selects setting.
4115*/
4116static void toggleSelectOrder(sqlite3 *db){
4117  sqlite3_stmt *pStmt = 0;
4118  int iSetting = 0;
4119  char zStmt[100];
4120  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4121  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4122    iSetting = sqlite3_column_int(pStmt, 0);
4123  }
4124  sqlite3_finalize(pStmt);
4125  sqlite3_snprintf(sizeof(zStmt), zStmt,
4126       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4127  sqlite3_exec(db, zStmt, 0, 0, 0);
4128}
4129
4130/*
4131** This is a different callback routine used for dumping the database.
4132** Each row received by this callback consists of a table name,
4133** the table type ("index" or "table") and SQL to create the table.
4134** This routine should print text sufficient to recreate the table.
4135*/
4136static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4137  int rc;
4138  const char *zTable;
4139  const char *zType;
4140  const char *zSql;
4141  ShellState *p = (ShellState *)pArg;
4142  int dataOnly;
4143  int noSys;
4144
4145  UNUSED_PARAMETER(azNotUsed);
4146  if( nArg!=3 || azArg==0 ) return 0;
4147  zTable = azArg[0];
4148  zType = azArg[1];
4149  zSql = azArg[2];
4150  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4151  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4152
4153  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4154    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4155  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4156    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4157  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4158    return 0;
4159  }else if( dataOnly ){
4160    /* no-op */
4161  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4162    char *zIns;
4163    if( !p->writableSchema ){
4164      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4165      p->writableSchema = 1;
4166    }
4167    zIns = sqlite3_mprintf(
4168       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4169       "VALUES('table','%q','%q',0,'%q');",
4170       zTable, zTable, zSql);
4171    shell_check_oom(zIns);
4172    utf8_printf(p->out, "%s\n", zIns);
4173    sqlite3_free(zIns);
4174    return 0;
4175  }else{
4176    printSchemaLine(p->out, zSql, ";\n");
4177  }
4178
4179  if( strcmp(zType, "table")==0 ){
4180    ShellText sSelect;
4181    ShellText sTable;
4182    char **azCol;
4183    int i;
4184    char *savedDestTable;
4185    int savedMode;
4186
4187    azCol = tableColumnList(p, zTable);
4188    if( azCol==0 ){
4189      p->nErr++;
4190      return 0;
4191    }
4192
4193    /* Always quote the table name, even if it appears to be pure ascii,
4194    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4195    initText(&sTable);
4196    appendText(&sTable, zTable, quoteChar(zTable));
4197    /* If preserving the rowid, add a column list after the table name.
4198    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4199    ** instead of the usual "INSERT INTO tab VALUES(...)".
4200    */
4201    if( azCol[0] ){
4202      appendText(&sTable, "(", 0);
4203      appendText(&sTable, azCol[0], 0);
4204      for(i=1; azCol[i]; i++){
4205        appendText(&sTable, ",", 0);
4206        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4207      }
4208      appendText(&sTable, ")", 0);
4209    }
4210
4211    /* Build an appropriate SELECT statement */
4212    initText(&sSelect);
4213    appendText(&sSelect, "SELECT ", 0);
4214    if( azCol[0] ){
4215      appendText(&sSelect, azCol[0], 0);
4216      appendText(&sSelect, ",", 0);
4217    }
4218    for(i=1; azCol[i]; i++){
4219      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4220      if( azCol[i+1] ){
4221        appendText(&sSelect, ",", 0);
4222      }
4223    }
4224    freeColumnList(azCol);
4225    appendText(&sSelect, " FROM ", 0);
4226    appendText(&sSelect, zTable, quoteChar(zTable));
4227
4228    savedDestTable = p->zDestTable;
4229    savedMode = p->mode;
4230    p->zDestTable = sTable.z;
4231    p->mode = p->cMode = MODE_Insert;
4232    rc = shell_exec(p, sSelect.z, 0);
4233    if( (rc&0xff)==SQLITE_CORRUPT ){
4234      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4235      toggleSelectOrder(p->db);
4236      shell_exec(p, sSelect.z, 0);
4237      toggleSelectOrder(p->db);
4238    }
4239    p->zDestTable = savedDestTable;
4240    p->mode = savedMode;
4241    freeText(&sTable);
4242    freeText(&sSelect);
4243    if( rc ) p->nErr++;
4244  }
4245  return 0;
4246}
4247
4248/*
4249** Run zQuery.  Use dump_callback() as the callback routine so that
4250** the contents of the query are output as SQL statements.
4251**
4252** If we get a SQLITE_CORRUPT error, rerun the query after appending
4253** "ORDER BY rowid DESC" to the end.
4254*/
4255static int run_schema_dump_query(
4256  ShellState *p,
4257  const char *zQuery
4258){
4259  int rc;
4260  char *zErr = 0;
4261  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4262  if( rc==SQLITE_CORRUPT ){
4263    char *zQ2;
4264    int len = strlen30(zQuery);
4265    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4266    if( zErr ){
4267      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4268      sqlite3_free(zErr);
4269      zErr = 0;
4270    }
4271    zQ2 = malloc( len+100 );
4272    if( zQ2==0 ) return rc;
4273    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4274    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4275    if( rc ){
4276      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4277    }else{
4278      rc = SQLITE_CORRUPT;
4279    }
4280    sqlite3_free(zErr);
4281    free(zQ2);
4282  }
4283  return rc;
4284}
4285
4286/*
4287** Text of help messages.
4288**
4289** The help text for each individual command begins with a line that starts
4290** with ".".  Subsequent lines are supplemental information.
4291**
4292** There must be two or more spaces between the end of the command and the
4293** start of the description of what that command does.
4294*/
4295static const char *(azHelp[]) = {
4296#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4297  && !defined(SQLITE_SHELL_FIDDLE)
4298  ".archive ...             Manage SQL archives",
4299  "   Each command must have exactly one of the following options:",
4300  "     -c, --create               Create a new archive",
4301  "     -u, --update               Add or update files with changed mtime",
4302  "     -i, --insert               Like -u but always add even if unchanged",
4303  "     -r, --remove               Remove files from archive",
4304  "     -t, --list                 List contents of archive",
4305  "     -x, --extract              Extract files from archive",
4306  "   Optional arguments:",
4307  "     -v, --verbose              Print each filename as it is processed",
4308  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4309  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4310  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4311  "     -g, --glob                 Use glob matching for names in archive",
4312  "     -n, --dryrun               Show the SQL that would have occurred",
4313  "   Examples:",
4314  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4315  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4316  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4317  "   See also:",
4318  "      http://sqlite.org/cli.html#sqlite_archive_support",
4319#endif
4320#ifndef SQLITE_OMIT_AUTHORIZATION
4321  ".auth ON|OFF             Show authorizer callbacks",
4322#endif
4323#ifndef SQLITE_SHELL_FIDDLE
4324  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4325  "   Options:",
4326  "       --append            Use the appendvfs",
4327  "       --async             Write to FILE without journal and fsync()",
4328#endif
4329  ".bail on|off             Stop after hitting an error.  Default OFF",
4330  ".binary on|off           Turn binary output on or off.  Default OFF",
4331#ifndef SQLITE_SHELL_FIDDLE
4332  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4333#endif
4334  ".changes on|off          Show number of rows changed by SQL",
4335#ifndef SQLITE_SHELL_FIDDLE
4336  ".check GLOB              Fail if output since .testcase does not match",
4337  ".clone NEWDB             Clone data into NEWDB from the existing database",
4338#endif
4339  ".connection [close] [#]  Open or close an auxiliary database connection",
4340  ".databases               List names and files of attached databases",
4341  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4342#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4343  ".dbinfo ?DB?             Show status information about the database",
4344#endif
4345  ".dump ?OBJECTS?          Render database content as SQL",
4346  "   Options:",
4347  "     --data-only            Output only INSERT statements",
4348  "     --newlines             Allow unescaped newline characters in output",
4349  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4350  "     --preserve-rowids      Include ROWID values in the output",
4351  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4352  "   Additional LIKE patterns can be given in subsequent arguments",
4353  ".echo on|off             Turn command echo on or off",
4354  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4355  "   Other Modes:",
4356#ifdef SQLITE_DEBUG
4357  "      test                  Show raw EXPLAIN QUERY PLAN output",
4358  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4359#endif
4360  "      trigger               Like \"full\" but also show trigger bytecode",
4361#ifndef SQLITE_SHELL_FIDDLE
4362  ".excel                   Display the output of next command in spreadsheet",
4363  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4364#endif
4365#ifndef SQLITE_SHELL_FIDDLE
4366  ".exit ?CODE?             Exit this program with return-code CODE",
4367#endif
4368  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4369  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4370  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4371  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4372  "   --help                  Show CMD details",
4373  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4374  ".headers on|off          Turn display of headers on or off",
4375  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4376#ifndef SQLITE_SHELL_FIDDLE
4377  ".import FILE TABLE       Import data from FILE into TABLE",
4378  "   Options:",
4379  "     --ascii               Use \\037 and \\036 as column and row separators",
4380  "     --csv                 Use , and \\n as column and row separators",
4381  "     --skip N              Skip the first N rows of input",
4382  "     --schema S            Target table to be S.TABLE",
4383  "     -v                    \"Verbose\" - increase auxiliary output",
4384  "   Notes:",
4385  "     *  If TABLE does not exist, it is created.  The first row of input",
4386  "        determines the column names.",
4387  "     *  If neither --csv or --ascii are used, the input mode is derived",
4388  "        from the \".mode\" output mode",
4389  "     *  If FILE begins with \"|\" then it is a command that generates the",
4390  "        input text.",
4391#endif
4392#ifndef SQLITE_OMIT_TEST_CONTROL
4393  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4394#endif
4395  ".indexes ?TABLE?         Show names of indexes",
4396  "                           If TABLE is specified, only show indexes for",
4397  "                           tables matching TABLE using the LIKE operator.",
4398#ifdef SQLITE_ENABLE_IOTRACE
4399  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4400#endif
4401  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4402  ".lint OPTIONS            Report potential schema issues.",
4403  "     Options:",
4404  "        fkey-indexes     Find missing foreign key indexes",
4405#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4406  ".load FILE ?ENTRY?       Load an extension library",
4407#endif
4408#ifndef SQLITE_SHELL_FIDDLE
4409  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4410#endif
4411  ".mode MODE ?OPTIONS?     Set output mode",
4412  "   MODE is one of:",
4413  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4414  "     box         Tables using unicode box-drawing characters",
4415  "     csv         Comma-separated values",
4416  "     column      Output in columns.  (See .width)",
4417  "     html        HTML <table> code",
4418  "     insert      SQL insert statements for TABLE",
4419  "     json        Results in a JSON array",
4420  "     line        One value per line",
4421  "     list        Values delimited by \"|\"",
4422  "     markdown    Markdown table format",
4423  "     qbox        Shorthand for \"box --width 60 --quote\"",
4424  "     quote       Escape answers as for SQL",
4425  "     table       ASCII-art table",
4426  "     tabs        Tab-separated values",
4427  "     tcl         TCL list elements",
4428  "   OPTIONS: (for columnar modes or insert mode):",
4429  "     --wrap N       Wrap output lines to no longer than N characters",
4430  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4431  "     --ww           Shorthand for \"--wordwrap 1\"",
4432  "     --quote        Quote output text as SQL literals",
4433  "     --noquote      Do not quote output text",
4434  "     TABLE          The name of SQL table used for \"insert\" mode",
4435#ifndef SQLITE_SHELL_FIDDLE
4436  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4437#endif
4438  ".nullvalue STRING        Use STRING in place of NULL values",
4439#ifndef SQLITE_SHELL_FIDDLE
4440  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4441  "     If FILE begins with '|' then open as a pipe",
4442  "       --bom  Put a UTF8 byte-order mark at the beginning",
4443  "       -e     Send output to the system text editor",
4444  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4445  /* Note that .open is (partially) available in WASM builds but is
4446  ** currently only intended to be used by the fiddle tool, not
4447  ** end users, so is "undocumented." */
4448  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4449  "     Options:",
4450  "        --append        Use appendvfs to append database to the end of FILE",
4451#endif
4452#ifndef SQLITE_OMIT_DESERIALIZE
4453  "        --deserialize   Load into memory using sqlite3_deserialize()",
4454  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4455  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4456#endif
4457  "        --new           Initialize FILE to an empty database",
4458  "        --nofollow      Do not follow symbolic links",
4459  "        --readonly      Open FILE readonly",
4460  "        --zip           FILE is a ZIP archive",
4461#ifndef SQLITE_SHELL_FIDDLE
4462  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4463  "   If FILE begins with '|' then open it as a pipe.",
4464  "   Options:",
4465  "     --bom                 Prefix output with a UTF8 byte-order mark",
4466  "     -e                    Send output to the system text editor",
4467  "     -x                    Send output as CSV to a spreadsheet",
4468#endif
4469  ".parameter CMD ...       Manage SQL parameter bindings",
4470  "   clear                   Erase all bindings",
4471  "   init                    Initialize the TEMP table that holds bindings",
4472  "   list                    List the current parameter bindings",
4473  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4474  "                           PARAMETER should start with one of: $ : @ ?",
4475  "   unset PARAMETER         Remove PARAMETER from the binding table",
4476  ".print STRING...         Print literal STRING",
4477#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4478  ".progress N              Invoke progress handler after every N opcodes",
4479  "   --limit N                 Interrupt after N progress callbacks",
4480  "   --once                    Do no more than one progress interrupt",
4481  "   --quiet|-q                No output except at interrupts",
4482  "   --reset                   Reset the count for each input and interrupt",
4483#endif
4484  ".prompt MAIN CONTINUE    Replace the standard prompts",
4485#ifndef SQLITE_SHELL_FIDDLE
4486  ".quit                    Exit this program",
4487  ".read FILE               Read input from FILE or command output",
4488  "    If FILE begins with \"|\", it is a command that generates the input.",
4489#endif
4490#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4491  ".recover                 Recover as much data as possible from corrupt db.",
4492  "   --freelist-corrupt       Assume the freelist is corrupt",
4493  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4494  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4495  "   --no-rowids              Do not attempt to recover rowid values",
4496  "                            that are not also INTEGER PRIMARY KEYs",
4497#endif
4498#ifndef SQLITE_SHELL_FIDDLE
4499  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4500  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4501#endif
4502  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4503  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4504  "   Options:",
4505  "      --indent             Try to pretty-print the schema",
4506  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4507  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4508  "    Options:",
4509  "       --init               Create a new SELFTEST table",
4510  "       -v                   Verbose output",
4511  ".separator COL ?ROW?     Change the column and row separators",
4512#if defined(SQLITE_ENABLE_SESSION)
4513  ".session ?NAME? CMD ...  Create or control sessions",
4514  "   Subcommands:",
4515  "     attach TABLE             Attach TABLE",
4516  "     changeset FILE           Write a changeset into FILE",
4517  "     close                    Close one session",
4518  "     enable ?BOOLEAN?         Set or query the enable bit",
4519  "     filter GLOB...           Reject tables matching GLOBs",
4520  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4521  "     isempty                  Query whether the session is empty",
4522  "     list                     List currently open session names",
4523  "     open DB NAME             Open a new session on DB",
4524  "     patchset FILE            Write a patchset into FILE",
4525  "   If ?NAME? is omitted, the first defined session is used.",
4526#endif
4527  ".sha3sum ...             Compute a SHA3 hash of database content",
4528  "    Options:",
4529  "      --schema              Also hash the sqlite_schema table",
4530  "      --sha3-224            Use the sha3-224 algorithm",
4531  "      --sha3-256            Use the sha3-256 algorithm (default)",
4532  "      --sha3-384            Use the sha3-384 algorithm",
4533  "      --sha3-512            Use the sha3-512 algorithm",
4534  "    Any other argument is a LIKE pattern for tables to hash",
4535#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4536  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4537#endif
4538  ".show                    Show the current values for various settings",
4539  ".stats ?ARG?             Show stats or turn stats on or off",
4540  "   off                      Turn off automatic stat display",
4541  "   on                       Turn on automatic stat display",
4542  "   stmt                     Show statement stats",
4543  "   vmstep                   Show the virtual machine step count only",
4544#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4545  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4546#endif
4547  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4548#ifndef SQLITE_SHELL_FIDDLE
4549  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4550#endif
4551  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4552  "                           Run \".testctrl\" with no arguments for details",
4553  ".timeout MS              Try opening locked tables for MS milliseconds",
4554  ".timer on|off            Turn SQL timer on or off",
4555#ifndef SQLITE_OMIT_TRACE
4556  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4557  "    FILE                    Send output to FILE",
4558  "    stdout                  Send output to stdout",
4559  "    stderr                  Send output to stderr",
4560  "    off                     Disable tracing",
4561  "    --expanded              Expand query parameters",
4562#ifdef SQLITE_ENABLE_NORMALIZE
4563  "    --normalized            Normal the SQL statements",
4564#endif
4565  "    --plain                 Show SQL as it is input",
4566  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4567  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4568  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4569  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4570#endif /* SQLITE_OMIT_TRACE */
4571#ifdef SQLITE_DEBUG
4572  ".unmodule NAME ...       Unregister virtual table modules",
4573  "    --allexcept             Unregister everything except those named",
4574#endif
4575  ".vfsinfo ?AUX?           Information about the top-level VFS",
4576  ".vfslist                 List all available VFSes",
4577  ".vfsname ?AUX?           Print the name of the VFS stack",
4578  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4579  "     Negative values right-justify",
4580};
4581
4582/*
4583** Output help text.
4584**
4585** zPattern describes the set of commands for which help text is provided.
4586** If zPattern is NULL, then show all commands, but only give a one-line
4587** description of each.
4588**
4589** Return the number of matches.
4590*/
4591static int showHelp(FILE *out, const char *zPattern){
4592  int i = 0;
4593  int j = 0;
4594  int n = 0;
4595  char *zPat;
4596  if( zPattern==0
4597   || zPattern[0]=='0'
4598   || strcmp(zPattern,"-a")==0
4599   || strcmp(zPattern,"-all")==0
4600   || strcmp(zPattern,"--all")==0
4601  ){
4602    /* Show all commands, but only one line per command */
4603    if( zPattern==0 ) zPattern = "";
4604    for(i=0; i<ArraySize(azHelp); i++){
4605      if( azHelp[i][0]=='.' || zPattern[0] ){
4606        utf8_printf(out, "%s\n", azHelp[i]);
4607        n++;
4608      }
4609    }
4610  }else{
4611    /* Look for commands that for which zPattern is an exact prefix */
4612    zPat = sqlite3_mprintf(".%s*", zPattern);
4613    shell_check_oom(zPat);
4614    for(i=0; i<ArraySize(azHelp); i++){
4615      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4616        utf8_printf(out, "%s\n", azHelp[i]);
4617        j = i+1;
4618        n++;
4619      }
4620    }
4621    sqlite3_free(zPat);
4622    if( n ){
4623      if( n==1 ){
4624        /* when zPattern is a prefix of exactly one command, then include the
4625        ** details of that command, which should begin at offset j */
4626        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4627          utf8_printf(out, "%s\n", azHelp[j]);
4628          j++;
4629        }
4630      }
4631      return n;
4632    }
4633    /* Look for commands that contain zPattern anywhere.  Show the complete
4634    ** text of all commands that match. */
4635    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4636    shell_check_oom(zPat);
4637    for(i=0; i<ArraySize(azHelp); i++){
4638      if( azHelp[i][0]=='.' ) j = i;
4639      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4640        utf8_printf(out, "%s\n", azHelp[j]);
4641        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4642          j++;
4643          utf8_printf(out, "%s\n", azHelp[j]);
4644        }
4645        i = j;
4646        n++;
4647      }
4648    }
4649    sqlite3_free(zPat);
4650  }
4651  return n;
4652}
4653
4654/* Forward reference */
4655static int process_input(ShellState *p);
4656
4657/*
4658** Read the content of file zName into memory obtained from sqlite3_malloc64()
4659** and return a pointer to the buffer. The caller is responsible for freeing
4660** the memory.
4661**
4662** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4663** read.
4664**
4665** For convenience, a nul-terminator byte is always appended to the data read
4666** from the file before the buffer is returned. This byte is not included in
4667** the final value of (*pnByte), if applicable.
4668**
4669** NULL is returned if any error is encountered. The final value of *pnByte
4670** is undefined in this case.
4671*/
4672static char *readFile(const char *zName, int *pnByte){
4673  FILE *in = fopen(zName, "rb");
4674  long nIn;
4675  size_t nRead;
4676  char *pBuf;
4677  if( in==0 ) return 0;
4678  fseek(in, 0, SEEK_END);
4679  nIn = ftell(in);
4680  rewind(in);
4681  pBuf = sqlite3_malloc64( nIn+1 );
4682  if( pBuf==0 ){ fclose(in); return 0; }
4683  nRead = fread(pBuf, nIn, 1, in);
4684  fclose(in);
4685  if( nRead!=1 ){
4686    sqlite3_free(pBuf);
4687    return 0;
4688  }
4689  pBuf[nIn] = 0;
4690  if( pnByte ) *pnByte = nIn;
4691  return pBuf;
4692}
4693
4694#if defined(SQLITE_ENABLE_SESSION)
4695/*
4696** Close a single OpenSession object and release all of its associated
4697** resources.
4698*/
4699static void session_close(OpenSession *pSession){
4700  int i;
4701  sqlite3session_delete(pSession->p);
4702  sqlite3_free(pSession->zName);
4703  for(i=0; i<pSession->nFilter; i++){
4704    sqlite3_free(pSession->azFilter[i]);
4705  }
4706  sqlite3_free(pSession->azFilter);
4707  memset(pSession, 0, sizeof(OpenSession));
4708}
4709#endif
4710
4711/*
4712** Close all OpenSession objects and release all associated resources.
4713*/
4714#if defined(SQLITE_ENABLE_SESSION)
4715static void session_close_all(ShellState *p, int i){
4716  int j;
4717  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4718  for(j=0; j<pAuxDb->nSession; j++){
4719    session_close(&pAuxDb->aSession[j]);
4720  }
4721  pAuxDb->nSession = 0;
4722}
4723#else
4724# define session_close_all(X,Y)
4725#endif
4726
4727/*
4728** Implementation of the xFilter function for an open session.  Omit
4729** any tables named by ".session filter" but let all other table through.
4730*/
4731#if defined(SQLITE_ENABLE_SESSION)
4732static int session_filter(void *pCtx, const char *zTab){
4733  OpenSession *pSession = (OpenSession*)pCtx;
4734  int i;
4735  for(i=0; i<pSession->nFilter; i++){
4736    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4737  }
4738  return 1;
4739}
4740#endif
4741
4742/*
4743** Try to deduce the type of file for zName based on its content.  Return
4744** one of the SHELL_OPEN_* constants.
4745**
4746** If the file does not exist or is empty but its name looks like a ZIP
4747** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4748** Otherwise, assume an ordinary database regardless of the filename if
4749** the type cannot be determined from content.
4750*/
4751int deduceDatabaseType(const char *zName, int dfltZip){
4752  FILE *f = fopen(zName, "rb");
4753  size_t n;
4754  int rc = SHELL_OPEN_UNSPEC;
4755  char zBuf[100];
4756  if( f==0 ){
4757    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4758       return SHELL_OPEN_ZIPFILE;
4759    }else{
4760       return SHELL_OPEN_NORMAL;
4761    }
4762  }
4763  n = fread(zBuf, 16, 1, f);
4764  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4765    fclose(f);
4766    return SHELL_OPEN_NORMAL;
4767  }
4768  fseek(f, -25, SEEK_END);
4769  n = fread(zBuf, 25, 1, f);
4770  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4771    rc = SHELL_OPEN_APPENDVFS;
4772  }else{
4773    fseek(f, -22, SEEK_END);
4774    n = fread(zBuf, 22, 1, f);
4775    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4776       && zBuf[3]==0x06 ){
4777      rc = SHELL_OPEN_ZIPFILE;
4778    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4779      rc = SHELL_OPEN_ZIPFILE;
4780    }
4781  }
4782  fclose(f);
4783  return rc;
4784}
4785
4786#ifndef SQLITE_OMIT_DESERIALIZE
4787/*
4788** Reconstruct an in-memory database using the output from the "dbtotxt"
4789** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4790** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4791*/
4792static unsigned char *readHexDb(ShellState *p, int *pnData){
4793  unsigned char *a = 0;
4794  int nLine;
4795  int n = 0;
4796  int pgsz = 0;
4797  int iOffset = 0;
4798  int j, k;
4799  int rc;
4800  FILE *in;
4801  const char *zDbFilename = p->pAuxDb->zDbFilename;
4802  unsigned int x[16];
4803  char zLine[1000];
4804  if( zDbFilename ){
4805    in = fopen(zDbFilename, "r");
4806    if( in==0 ){
4807      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4808      return 0;
4809    }
4810    nLine = 0;
4811  }else{
4812    in = p->in;
4813    nLine = p->lineno;
4814    if( in==0 ) in = stdin;
4815  }
4816  *pnData = 0;
4817  nLine++;
4818  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4819  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4820  if( rc!=2 ) goto readHexDb_error;
4821  if( n<0 ) goto readHexDb_error;
4822  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4823  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4824  a = sqlite3_malloc( n ? n : 1 );
4825  shell_check_oom(a);
4826  memset(a, 0, n);
4827  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4828    utf8_printf(stderr, "invalid pagesize\n");
4829    goto readHexDb_error;
4830  }
4831  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4832    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4833    if( rc==2 ){
4834      iOffset = k;
4835      continue;
4836    }
4837    if( strncmp(zLine, "| end ", 6)==0 ){
4838      break;
4839    }
4840    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4841                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4842                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4843    if( rc==17 ){
4844      k = iOffset+j;
4845      if( k+16<=n && k>=0 ){
4846        int ii;
4847        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4848      }
4849    }
4850  }
4851  *pnData = n;
4852  if( in!=p->in ){
4853    fclose(in);
4854  }else{
4855    p->lineno = nLine;
4856  }
4857  return a;
4858
4859readHexDb_error:
4860  if( in!=p->in ){
4861    fclose(in);
4862  }else{
4863    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4864      nLine++;
4865      if(strncmp(zLine, "| end ", 6)==0 ) break;
4866    }
4867    p->lineno = nLine;
4868  }
4869  sqlite3_free(a);
4870  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4871  return 0;
4872}
4873#endif /* SQLITE_OMIT_DESERIALIZE */
4874
4875/*
4876** Scalar function "shell_int32". The first argument to this function
4877** must be a blob. The second a non-negative integer. This function
4878** reads and returns a 32-bit big-endian integer from byte
4879** offset (4*<arg2>) of the blob.
4880*/
4881static void shellInt32(
4882  sqlite3_context *context,
4883  int argc,
4884  sqlite3_value **argv
4885){
4886  const unsigned char *pBlob;
4887  int nBlob;
4888  int iInt;
4889
4890  UNUSED_PARAMETER(argc);
4891  nBlob = sqlite3_value_bytes(argv[0]);
4892  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4893  iInt = sqlite3_value_int(argv[1]);
4894
4895  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4896    const unsigned char *a = &pBlob[iInt*4];
4897    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4898                       + ((sqlite3_int64)a[1]<<16)
4899                       + ((sqlite3_int64)a[2]<< 8)
4900                       + ((sqlite3_int64)a[3]<< 0);
4901    sqlite3_result_int64(context, iVal);
4902  }
4903}
4904
4905/*
4906** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4907** using "..." with internal double-quote characters doubled.
4908*/
4909static void shellIdQuote(
4910  sqlite3_context *context,
4911  int argc,
4912  sqlite3_value **argv
4913){
4914  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4915  UNUSED_PARAMETER(argc);
4916  if( zName ){
4917    char *z = sqlite3_mprintf("\"%w\"", zName);
4918    sqlite3_result_text(context, z, -1, sqlite3_free);
4919  }
4920}
4921
4922/*
4923** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4924*/
4925static void shellUSleepFunc(
4926  sqlite3_context *context,
4927  int argcUnused,
4928  sqlite3_value **argv
4929){
4930  int sleep = sqlite3_value_int(argv[0]);
4931  (void)argcUnused;
4932  sqlite3_sleep(sleep/1000);
4933  sqlite3_result_int(context, sleep);
4934}
4935
4936/*
4937** Scalar function "shell_escape_crnl" used by the .recover command.
4938** The argument passed to this function is the output of built-in
4939** function quote(). If the first character of the input is "'",
4940** indicating that the value passed to quote() was a text value,
4941** then this function searches the input for "\n" and "\r" characters
4942** and adds a wrapper similar to the following:
4943**
4944**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4945**
4946** Or, if the first character of the input is not "'", then a copy
4947** of the input is returned.
4948*/
4949static void shellEscapeCrnl(
4950  sqlite3_context *context,
4951  int argc,
4952  sqlite3_value **argv
4953){
4954  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4955  UNUSED_PARAMETER(argc);
4956  if( zText && zText[0]=='\'' ){
4957    i64 nText = sqlite3_value_bytes(argv[0]);
4958    i64 i;
4959    char zBuf1[20];
4960    char zBuf2[20];
4961    const char *zNL = 0;
4962    const char *zCR = 0;
4963    i64 nCR = 0;
4964    i64 nNL = 0;
4965
4966    for(i=0; zText[i]; i++){
4967      if( zNL==0 && zText[i]=='\n' ){
4968        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4969        nNL = strlen(zNL);
4970      }
4971      if( zCR==0 && zText[i]=='\r' ){
4972        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4973        nCR = strlen(zCR);
4974      }
4975    }
4976
4977    if( zNL || zCR ){
4978      i64 iOut = 0;
4979      i64 nMax = (nNL > nCR) ? nNL : nCR;
4980      i64 nAlloc = nMax * nText + (nMax+64)*2;
4981      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4982      if( zOut==0 ){
4983        sqlite3_result_error_nomem(context);
4984        return;
4985      }
4986
4987      if( zNL && zCR ){
4988        memcpy(&zOut[iOut], "replace(replace(", 16);
4989        iOut += 16;
4990      }else{
4991        memcpy(&zOut[iOut], "replace(", 8);
4992        iOut += 8;
4993      }
4994      for(i=0; zText[i]; i++){
4995        if( zText[i]=='\n' ){
4996          memcpy(&zOut[iOut], zNL, nNL);
4997          iOut += nNL;
4998        }else if( zText[i]=='\r' ){
4999          memcpy(&zOut[iOut], zCR, nCR);
5000          iOut += nCR;
5001        }else{
5002          zOut[iOut] = zText[i];
5003          iOut++;
5004        }
5005      }
5006
5007      if( zNL ){
5008        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5009        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
5010        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
5011      }
5012      if( zCR ){
5013        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5014        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
5015        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
5016      }
5017
5018      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
5019      sqlite3_free(zOut);
5020      return;
5021    }
5022  }
5023
5024  sqlite3_result_value(context, argv[0]);
5025}
5026
5027/* Flags for open_db().
5028**
5029** The default behavior of open_db() is to exit(1) if the database fails to
5030** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5031** but still returns without calling exit.
5032**
5033** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5034** ZIP archive if the file does not exist or is empty and its name matches
5035** the *.zip pattern.
5036*/
5037#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5038#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5039
5040/*
5041** Make sure the database is open.  If it is not, then open it.  If
5042** the database fails to open, print an error message and exit.
5043*/
5044static void open_db(ShellState *p, int openFlags){
5045  if( p->db==0 ){
5046    const char *zDbFilename = p->pAuxDb->zDbFilename;
5047    if( p->openMode==SHELL_OPEN_UNSPEC ){
5048      if( zDbFilename==0 || zDbFilename[0]==0 ){
5049        p->openMode = SHELL_OPEN_NORMAL;
5050      }else{
5051        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5052                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5053      }
5054    }
5055    switch( p->openMode ){
5056      case SHELL_OPEN_APPENDVFS: {
5057        sqlite3_open_v2(zDbFilename, &p->db,
5058           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5059        break;
5060      }
5061      case SHELL_OPEN_HEXDB:
5062      case SHELL_OPEN_DESERIALIZE: {
5063        sqlite3_open(0, &p->db);
5064        break;
5065      }
5066      case SHELL_OPEN_ZIPFILE: {
5067        sqlite3_open(":memory:", &p->db);
5068        break;
5069      }
5070      case SHELL_OPEN_READONLY: {
5071        sqlite3_open_v2(zDbFilename, &p->db,
5072            SQLITE_OPEN_READONLY|p->openFlags, 0);
5073        break;
5074      }
5075      case SHELL_OPEN_UNSPEC:
5076      case SHELL_OPEN_NORMAL: {
5077        sqlite3_open_v2(zDbFilename, &p->db,
5078           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5079        break;
5080      }
5081    }
5082    globalDb = p->db;
5083    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5084      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5085          zDbFilename, sqlite3_errmsg(p->db));
5086      if( openFlags & OPEN_DB_KEEPALIVE ){
5087        sqlite3_open(":memory:", &p->db);
5088        return;
5089      }
5090      exit(1);
5091    }
5092#ifndef SQLITE_OMIT_LOAD_EXTENSION
5093    sqlite3_enable_load_extension(p->db, 1);
5094#endif
5095    sqlite3_shathree_init(p->db, 0, 0);
5096    sqlite3_uint_init(p->db, 0, 0);
5097    sqlite3_decimal_init(p->db, 0, 0);
5098    sqlite3_regexp_init(p->db, 0, 0);
5099    sqlite3_ieee_init(p->db, 0, 0);
5100    sqlite3_series_init(p->db, 0, 0);
5101#ifndef SQLITE_SHELL_FIDDLE
5102    sqlite3_fileio_init(p->db, 0, 0);
5103    sqlite3_completion_init(p->db, 0, 0);
5104#endif
5105#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5106    sqlite3_dbdata_init(p->db, 0, 0);
5107#endif
5108#ifdef SQLITE_HAVE_ZLIB
5109    if( !p->bSafeModePersist ){
5110      sqlite3_zipfile_init(p->db, 0, 0);
5111      sqlite3_sqlar_init(p->db, 0, 0);
5112    }
5113#endif
5114    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5115                            shellAddSchemaName, 0, 0);
5116    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5117                            shellModuleSchema, 0, 0);
5118    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5119                            shellPutsFunc, 0, 0);
5120    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5121                            shellEscapeCrnl, 0, 0);
5122    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5123                            shellInt32, 0, 0);
5124    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5125                            shellIdQuote, 0, 0);
5126    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5127                            shellUSleepFunc, 0, 0);
5128#ifndef SQLITE_NOHAVE_SYSTEM
5129    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5130                            editFunc, 0, 0);
5131    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5132                            editFunc, 0, 0);
5133#endif
5134    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5135      char *zSql = sqlite3_mprintf(
5136         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5137      shell_check_oom(zSql);
5138      sqlite3_exec(p->db, zSql, 0, 0, 0);
5139      sqlite3_free(zSql);
5140    }
5141#ifndef SQLITE_OMIT_DESERIALIZE
5142    else
5143    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5144      int rc;
5145      int nData = 0;
5146      unsigned char *aData;
5147      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5148        aData = (unsigned char*)readFile(zDbFilename, &nData);
5149      }else{
5150        aData = readHexDb(p, &nData);
5151        if( aData==0 ){
5152          return;
5153        }
5154      }
5155      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5156                   SQLITE_DESERIALIZE_RESIZEABLE |
5157                   SQLITE_DESERIALIZE_FREEONCLOSE);
5158      if( rc ){
5159        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5160      }
5161      if( p->szMax>0 ){
5162        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5163      }
5164    }
5165#endif
5166  }
5167  if( p->bSafeModePersist && p->db!=0 ){
5168    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5169  }
5170}
5171
5172/*
5173** Attempt to close the databaes connection.  Report errors.
5174*/
5175void close_db(sqlite3 *db){
5176  int rc = sqlite3_close(db);
5177  if( rc ){
5178    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5179        rc, sqlite3_errmsg(db));
5180  }
5181}
5182
5183#if HAVE_READLINE || HAVE_EDITLINE
5184/*
5185** Readline completion callbacks
5186*/
5187static char *readline_completion_generator(const char *text, int state){
5188  static sqlite3_stmt *pStmt = 0;
5189  char *zRet;
5190  if( state==0 ){
5191    char *zSql;
5192    sqlite3_finalize(pStmt);
5193    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5194                           "  FROM completion(%Q) ORDER BY 1", text);
5195    shell_check_oom(zSql);
5196    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5197    sqlite3_free(zSql);
5198  }
5199  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5200    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5201    zRet = z ? strdup(z) : 0;
5202  }else{
5203    sqlite3_finalize(pStmt);
5204    pStmt = 0;
5205    zRet = 0;
5206  }
5207  return zRet;
5208}
5209static char **readline_completion(const char *zText, int iStart, int iEnd){
5210  rl_attempted_completion_over = 1;
5211  return rl_completion_matches(zText, readline_completion_generator);
5212}
5213
5214#elif HAVE_LINENOISE
5215/*
5216** Linenoise completion callback
5217*/
5218static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5219  i64 nLine = strlen(zLine);
5220  i64 i, iStart;
5221  sqlite3_stmt *pStmt = 0;
5222  char *zSql;
5223  char zBuf[1000];
5224
5225  if( nLine>sizeof(zBuf)-30 ) return;
5226  if( zLine[0]=='.' || zLine[0]=='#') return;
5227  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5228  if( i==nLine-1 ) return;
5229  iStart = i+1;
5230  memcpy(zBuf, zLine, iStart);
5231  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5232                         "  FROM completion(%Q,%Q) ORDER BY 1",
5233                         &zLine[iStart], zLine);
5234  shell_check_oom(zSql);
5235  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5236  sqlite3_free(zSql);
5237  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5238  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5239    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5240    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5241    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5242      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5243      linenoiseAddCompletion(lc, zBuf);
5244    }
5245  }
5246  sqlite3_finalize(pStmt);
5247}
5248#endif
5249
5250/*
5251** Do C-language style dequoting.
5252**
5253**    \a    -> alarm
5254**    \b    -> backspace
5255**    \t    -> tab
5256**    \n    -> newline
5257**    \v    -> vertical tab
5258**    \f    -> form feed
5259**    \r    -> carriage return
5260**    \s    -> space
5261**    \"    -> "
5262**    \'    -> '
5263**    \\    -> backslash
5264**    \NNN  -> ascii character NNN in octal
5265*/
5266static void resolve_backslashes(char *z){
5267  int i, j;
5268  char c;
5269  while( *z && *z!='\\' ) z++;
5270  for(i=j=0; (c = z[i])!=0; i++, j++){
5271    if( c=='\\' && z[i+1]!=0 ){
5272      c = z[++i];
5273      if( c=='a' ){
5274        c = '\a';
5275      }else if( c=='b' ){
5276        c = '\b';
5277      }else if( c=='t' ){
5278        c = '\t';
5279      }else if( c=='n' ){
5280        c = '\n';
5281      }else if( c=='v' ){
5282        c = '\v';
5283      }else if( c=='f' ){
5284        c = '\f';
5285      }else if( c=='r' ){
5286        c = '\r';
5287      }else if( c=='"' ){
5288        c = '"';
5289      }else if( c=='\'' ){
5290        c = '\'';
5291      }else if( c=='\\' ){
5292        c = '\\';
5293      }else if( c>='0' && c<='7' ){
5294        c -= '0';
5295        if( z[i+1]>='0' && z[i+1]<='7' ){
5296          i++;
5297          c = (c<<3) + z[i] - '0';
5298          if( z[i+1]>='0' && z[i+1]<='7' ){
5299            i++;
5300            c = (c<<3) + z[i] - '0';
5301          }
5302        }
5303      }
5304    }
5305    z[j] = c;
5306  }
5307  if( j<i ) z[j] = 0;
5308}
5309
5310/*
5311** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5312** for TRUE and FALSE.  Return the integer value if appropriate.
5313*/
5314static int booleanValue(const char *zArg){
5315  int i;
5316  if( zArg[0]=='0' && zArg[1]=='x' ){
5317    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5318  }else{
5319    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5320  }
5321  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5322  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5323    return 1;
5324  }
5325  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5326    return 0;
5327  }
5328  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5329          zArg);
5330  return 0;
5331}
5332
5333/*
5334** Set or clear a shell flag according to a boolean value.
5335*/
5336static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5337  if( booleanValue(zArg) ){
5338    ShellSetFlag(p, mFlag);
5339  }else{
5340    ShellClearFlag(p, mFlag);
5341  }
5342}
5343
5344/*
5345** Close an output file, assuming it is not stderr or stdout
5346*/
5347static void output_file_close(FILE *f){
5348  if( f && f!=stdout && f!=stderr ) fclose(f);
5349}
5350
5351/*
5352** Try to open an output file.   The names "stdout" and "stderr" are
5353** recognized and do the right thing.  NULL is returned if the output
5354** filename is "off".
5355*/
5356static FILE *output_file_open(const char *zFile, int bTextMode){
5357  FILE *f;
5358  if( strcmp(zFile,"stdout")==0 ){
5359    f = stdout;
5360  }else if( strcmp(zFile, "stderr")==0 ){
5361    f = stderr;
5362  }else if( strcmp(zFile, "off")==0 ){
5363    f = 0;
5364  }else{
5365    f = fopen(zFile, bTextMode ? "w" : "wb");
5366    if( f==0 ){
5367      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5368    }
5369  }
5370  return f;
5371}
5372
5373#ifndef SQLITE_OMIT_TRACE
5374/*
5375** A routine for handling output from sqlite3_trace().
5376*/
5377static int sql_trace_callback(
5378  unsigned mType,         /* The trace type */
5379  void *pArg,             /* The ShellState pointer */
5380  void *pP,               /* Usually a pointer to sqlite_stmt */
5381  void *pX                /* Auxiliary output */
5382){
5383  ShellState *p = (ShellState*)pArg;
5384  sqlite3_stmt *pStmt;
5385  const char *zSql;
5386  i64 nSql;
5387  if( p->traceOut==0 ) return 0;
5388  if( mType==SQLITE_TRACE_CLOSE ){
5389    utf8_printf(p->traceOut, "-- closing database connection\n");
5390    return 0;
5391  }
5392  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5393    zSql = (const char*)pX;
5394  }else{
5395    pStmt = (sqlite3_stmt*)pP;
5396    switch( p->eTraceType ){
5397      case SHELL_TRACE_EXPANDED: {
5398        zSql = sqlite3_expanded_sql(pStmt);
5399        break;
5400      }
5401#ifdef SQLITE_ENABLE_NORMALIZE
5402      case SHELL_TRACE_NORMALIZED: {
5403        zSql = sqlite3_normalized_sql(pStmt);
5404        break;
5405      }
5406#endif
5407      default: {
5408        zSql = sqlite3_sql(pStmt);
5409        break;
5410      }
5411    }
5412  }
5413  if( zSql==0 ) return 0;
5414  nSql = strlen(zSql);
5415  if( nSql>1000000000 ) nSql = 1000000000;
5416  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5417  switch( mType ){
5418    case SQLITE_TRACE_ROW:
5419    case SQLITE_TRACE_STMT: {
5420      utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5421      break;
5422    }
5423    case SQLITE_TRACE_PROFILE: {
5424      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5425      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5426      break;
5427    }
5428  }
5429  return 0;
5430}
5431#endif
5432
5433/*
5434** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5435** a useful spot to set a debugger breakpoint.
5436*/
5437static void test_breakpoint(void){
5438  static int nCall = 0;
5439  nCall++;
5440}
5441
5442/*
5443** An object used to read a CSV and other files for import.
5444*/
5445typedef struct ImportCtx ImportCtx;
5446struct ImportCtx {
5447  const char *zFile;  /* Name of the input file */
5448  FILE *in;           /* Read the CSV text from this input stream */
5449  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5450  char *z;            /* Accumulated text for a field */
5451  int n;              /* Number of bytes in z */
5452  int nAlloc;         /* Space allocated for z[] */
5453  int nLine;          /* Current line number */
5454  int nRow;           /* Number of rows imported */
5455  int nErr;           /* Number of errors encountered */
5456  int bNotFirst;      /* True if one or more bytes already read */
5457  int cTerm;          /* Character that terminated the most recent field */
5458  int cColSep;        /* The column separator character.  (Usually ",") */
5459  int cRowSep;        /* The row separator character.  (Usually "\n") */
5460};
5461
5462/* Clean up resourced used by an ImportCtx */
5463static void import_cleanup(ImportCtx *p){
5464  if( p->in!=0 && p->xCloser!=0 ){
5465    p->xCloser(p->in);
5466    p->in = 0;
5467  }
5468  sqlite3_free(p->z);
5469  p->z = 0;
5470}
5471
5472/* Append a single byte to z[] */
5473static void import_append_char(ImportCtx *p, int c){
5474  if( p->n+1>=p->nAlloc ){
5475    p->nAlloc += p->nAlloc + 100;
5476    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5477    shell_check_oom(p->z);
5478  }
5479  p->z[p->n++] = (char)c;
5480}
5481
5482/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5483** with the option of having a separator other than ",".
5484**
5485**   +  Input comes from p->in.
5486**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5487**      from sqlite3_malloc64().
5488**   +  Use p->cSep as the column separator.  The default is ",".
5489**   +  Use p->rSep as the row separator.  The default is "\n".
5490**   +  Keep track of the line number in p->nLine.
5491**   +  Store the character that terminates the field in p->cTerm.  Store
5492**      EOF on end-of-file.
5493**   +  Report syntax errors on stderr
5494*/
5495static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5496  int c;
5497  int cSep = p->cColSep;
5498  int rSep = p->cRowSep;
5499  p->n = 0;
5500  c = fgetc(p->in);
5501  if( c==EOF || seenInterrupt ){
5502    p->cTerm = EOF;
5503    return 0;
5504  }
5505  if( c=='"' ){
5506    int pc, ppc;
5507    int startLine = p->nLine;
5508    int cQuote = c;
5509    pc = ppc = 0;
5510    while( 1 ){
5511      c = fgetc(p->in);
5512      if( c==rSep ) p->nLine++;
5513      if( c==cQuote ){
5514        if( pc==cQuote ){
5515          pc = 0;
5516          continue;
5517        }
5518      }
5519      if( (c==cSep && pc==cQuote)
5520       || (c==rSep && pc==cQuote)
5521       || (c==rSep && pc=='\r' && ppc==cQuote)
5522       || (c==EOF && pc==cQuote)
5523      ){
5524        do{ p->n--; }while( p->z[p->n]!=cQuote );
5525        p->cTerm = c;
5526        break;
5527      }
5528      if( pc==cQuote && c!='\r' ){
5529        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5530                p->zFile, p->nLine, cQuote);
5531      }
5532      if( c==EOF ){
5533        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5534                p->zFile, startLine, cQuote);
5535        p->cTerm = c;
5536        break;
5537      }
5538      import_append_char(p, c);
5539      ppc = pc;
5540      pc = c;
5541    }
5542  }else{
5543    /* If this is the first field being parsed and it begins with the
5544    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5545    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5546      import_append_char(p, c);
5547      c = fgetc(p->in);
5548      if( (c&0xff)==0xbb ){
5549        import_append_char(p, c);
5550        c = fgetc(p->in);
5551        if( (c&0xff)==0xbf ){
5552          p->bNotFirst = 1;
5553          p->n = 0;
5554          return csv_read_one_field(p);
5555        }
5556      }
5557    }
5558    while( c!=EOF && c!=cSep && c!=rSep ){
5559      import_append_char(p, c);
5560      c = fgetc(p->in);
5561    }
5562    if( c==rSep ){
5563      p->nLine++;
5564      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5565    }
5566    p->cTerm = c;
5567  }
5568  if( p->z ) p->z[p->n] = 0;
5569  p->bNotFirst = 1;
5570  return p->z;
5571}
5572
5573/* Read a single field of ASCII delimited text.
5574**
5575**   +  Input comes from p->in.
5576**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5577**      from sqlite3_malloc64().
5578**   +  Use p->cSep as the column separator.  The default is "\x1F".
5579**   +  Use p->rSep as the row separator.  The default is "\x1E".
5580**   +  Keep track of the row number in p->nLine.
5581**   +  Store the character that terminates the field in p->cTerm.  Store
5582**      EOF on end-of-file.
5583**   +  Report syntax errors on stderr
5584*/
5585static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5586  int c;
5587  int cSep = p->cColSep;
5588  int rSep = p->cRowSep;
5589  p->n = 0;
5590  c = fgetc(p->in);
5591  if( c==EOF || seenInterrupt ){
5592    p->cTerm = EOF;
5593    return 0;
5594  }
5595  while( c!=EOF && c!=cSep && c!=rSep ){
5596    import_append_char(p, c);
5597    c = fgetc(p->in);
5598  }
5599  if( c==rSep ){
5600    p->nLine++;
5601  }
5602  p->cTerm = c;
5603  if( p->z ) p->z[p->n] = 0;
5604  return p->z;
5605}
5606
5607/*
5608** Try to transfer data for table zTable.  If an error is seen while
5609** moving forward, try to go backwards.  The backwards movement won't
5610** work for WITHOUT ROWID tables.
5611*/
5612static void tryToCloneData(
5613  ShellState *p,
5614  sqlite3 *newDb,
5615  const char *zTable
5616){
5617  sqlite3_stmt *pQuery = 0;
5618  sqlite3_stmt *pInsert = 0;
5619  char *zQuery = 0;
5620  char *zInsert = 0;
5621  int rc;
5622  int i, j, n;
5623  int nTable = strlen30(zTable);
5624  int k = 0;
5625  int cnt = 0;
5626  const int spinRate = 10000;
5627
5628  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5629  shell_check_oom(zQuery);
5630  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5631  if( rc ){
5632    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5633            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5634            zQuery);
5635    goto end_data_xfer;
5636  }
5637  n = sqlite3_column_count(pQuery);
5638  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5639  shell_check_oom(zInsert);
5640  sqlite3_snprintf(200+nTable,zInsert,
5641                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5642  i = strlen30(zInsert);
5643  for(j=1; j<n; j++){
5644    memcpy(zInsert+i, ",?", 2);
5645    i += 2;
5646  }
5647  memcpy(zInsert+i, ");", 3);
5648  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5649  if( rc ){
5650    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5651            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5652            zQuery);
5653    goto end_data_xfer;
5654  }
5655  for(k=0; k<2; k++){
5656    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5657      for(i=0; i<n; i++){
5658        switch( sqlite3_column_type(pQuery, i) ){
5659          case SQLITE_NULL: {
5660            sqlite3_bind_null(pInsert, i+1);
5661            break;
5662          }
5663          case SQLITE_INTEGER: {
5664            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5665            break;
5666          }
5667          case SQLITE_FLOAT: {
5668            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5669            break;
5670          }
5671          case SQLITE_TEXT: {
5672            sqlite3_bind_text(pInsert, i+1,
5673                             (const char*)sqlite3_column_text(pQuery,i),
5674                             -1, SQLITE_STATIC);
5675            break;
5676          }
5677          case SQLITE_BLOB: {
5678            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5679                                            sqlite3_column_bytes(pQuery,i),
5680                                            SQLITE_STATIC);
5681            break;
5682          }
5683        }
5684      } /* End for */
5685      rc = sqlite3_step(pInsert);
5686      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5687        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5688                        sqlite3_errmsg(newDb));
5689      }
5690      sqlite3_reset(pInsert);
5691      cnt++;
5692      if( (cnt%spinRate)==0 ){
5693        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5694        fflush(stdout);
5695      }
5696    } /* End while */
5697    if( rc==SQLITE_DONE ) break;
5698    sqlite3_finalize(pQuery);
5699    sqlite3_free(zQuery);
5700    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5701                             zTable);
5702    shell_check_oom(zQuery);
5703    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5704    if( rc ){
5705      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5706      break;
5707    }
5708  } /* End for(k=0...) */
5709
5710end_data_xfer:
5711  sqlite3_finalize(pQuery);
5712  sqlite3_finalize(pInsert);
5713  sqlite3_free(zQuery);
5714  sqlite3_free(zInsert);
5715}
5716
5717
5718/*
5719** Try to transfer all rows of the schema that match zWhere.  For
5720** each row, invoke xForEach() on the object defined by that row.
5721** If an error is encountered while moving forward through the
5722** sqlite_schema table, try again moving backwards.
5723*/
5724static void tryToCloneSchema(
5725  ShellState *p,
5726  sqlite3 *newDb,
5727  const char *zWhere,
5728  void (*xForEach)(ShellState*,sqlite3*,const char*)
5729){
5730  sqlite3_stmt *pQuery = 0;
5731  char *zQuery = 0;
5732  int rc;
5733  const unsigned char *zName;
5734  const unsigned char *zSql;
5735  char *zErrMsg = 0;
5736
5737  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5738                           " WHERE %s", zWhere);
5739  shell_check_oom(zQuery);
5740  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5741  if( rc ){
5742    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5743                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5744                    zQuery);
5745    goto end_schema_xfer;
5746  }
5747  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5748    zName = sqlite3_column_text(pQuery, 0);
5749    zSql = sqlite3_column_text(pQuery, 1);
5750    if( zName==0 || zSql==0 ) continue;
5751    printf("%s... ", zName); fflush(stdout);
5752    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5753    if( zErrMsg ){
5754      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5755      sqlite3_free(zErrMsg);
5756      zErrMsg = 0;
5757    }
5758    if( xForEach ){
5759      xForEach(p, newDb, (const char*)zName);
5760    }
5761    printf("done\n");
5762  }
5763  if( rc!=SQLITE_DONE ){
5764    sqlite3_finalize(pQuery);
5765    sqlite3_free(zQuery);
5766    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5767                             " WHERE %s ORDER BY rowid DESC", zWhere);
5768    shell_check_oom(zQuery);
5769    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5770    if( rc ){
5771      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5772                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5773                      zQuery);
5774      goto end_schema_xfer;
5775    }
5776    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5777      zName = sqlite3_column_text(pQuery, 0);
5778      zSql = sqlite3_column_text(pQuery, 1);
5779      if( zName==0 || zSql==0 ) continue;
5780      printf("%s... ", zName); fflush(stdout);
5781      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5782      if( zErrMsg ){
5783        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5784        sqlite3_free(zErrMsg);
5785        zErrMsg = 0;
5786      }
5787      if( xForEach ){
5788        xForEach(p, newDb, (const char*)zName);
5789      }
5790      printf("done\n");
5791    }
5792  }
5793end_schema_xfer:
5794  sqlite3_finalize(pQuery);
5795  sqlite3_free(zQuery);
5796}
5797
5798/*
5799** Open a new database file named "zNewDb".  Try to recover as much information
5800** as possible out of the main database (which might be corrupt) and write it
5801** into zNewDb.
5802*/
5803static void tryToClone(ShellState *p, const char *zNewDb){
5804  int rc;
5805  sqlite3 *newDb = 0;
5806  if( access(zNewDb,0)==0 ){
5807    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5808    return;
5809  }
5810  rc = sqlite3_open(zNewDb, &newDb);
5811  if( rc ){
5812    utf8_printf(stderr, "Cannot create output database: %s\n",
5813            sqlite3_errmsg(newDb));
5814  }else{
5815    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5816    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5817    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5818    tryToCloneSchema(p, newDb, "type!='table'", 0);
5819    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5820    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5821  }
5822  close_db(newDb);
5823}
5824
5825/*
5826** Change the output file back to stdout.
5827**
5828** If the p->doXdgOpen flag is set, that means the output was being
5829** redirected to a temporary file named by p->zTempFile.  In that case,
5830** launch start/open/xdg-open on that temporary file.
5831*/
5832static void output_reset(ShellState *p){
5833  if( p->outfile[0]=='|' ){
5834#ifndef SQLITE_OMIT_POPEN
5835    pclose(p->out);
5836#endif
5837  }else{
5838    output_file_close(p->out);
5839#ifndef SQLITE_NOHAVE_SYSTEM
5840    if( p->doXdgOpen ){
5841      const char *zXdgOpenCmd =
5842#if defined(_WIN32)
5843      "start";
5844#elif defined(__APPLE__)
5845      "open";
5846#else
5847      "xdg-open";
5848#endif
5849      char *zCmd;
5850      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5851      if( system(zCmd) ){
5852        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5853      }else{
5854        /* Give the start/open/xdg-open command some time to get
5855        ** going before we continue, and potential delete the
5856        ** p->zTempFile data file out from under it */
5857        sqlite3_sleep(2000);
5858      }
5859      sqlite3_free(zCmd);
5860      outputModePop(p);
5861      p->doXdgOpen = 0;
5862    }
5863#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5864  }
5865  p->outfile[0] = 0;
5866  p->out = stdout;
5867}
5868
5869/*
5870** Run an SQL command and return the single integer result.
5871*/
5872static int db_int(sqlite3 *db, const char *zSql){
5873  sqlite3_stmt *pStmt;
5874  int res = 0;
5875  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5876  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5877    res = sqlite3_column_int(pStmt,0);
5878  }
5879  sqlite3_finalize(pStmt);
5880  return res;
5881}
5882
5883#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5884/*
5885** Convert a 2-byte or 4-byte big-endian integer into a native integer
5886*/
5887static unsigned int get2byteInt(unsigned char *a){
5888  return (a[0]<<8) + a[1];
5889}
5890static unsigned int get4byteInt(unsigned char *a){
5891  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5892}
5893
5894/*
5895** Implementation of the ".dbinfo" command.
5896**
5897** Return 1 on error, 2 to exit, and 0 otherwise.
5898*/
5899static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5900  static const struct { const char *zName; int ofst; } aField[] = {
5901     { "file change counter:",  24  },
5902     { "database page count:",  28  },
5903     { "freelist page count:",  36  },
5904     { "schema cookie:",        40  },
5905     { "schema format:",        44  },
5906     { "default cache size:",   48  },
5907     { "autovacuum top root:",  52  },
5908     { "incremental vacuum:",   64  },
5909     { "text encoding:",        56  },
5910     { "user version:",         60  },
5911     { "application id:",       68  },
5912     { "software version:",     96  },
5913  };
5914  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5915     { "number of tables:",
5916       "SELECT count(*) FROM %s WHERE type='table'" },
5917     { "number of indexes:",
5918       "SELECT count(*) FROM %s WHERE type='index'" },
5919     { "number of triggers:",
5920       "SELECT count(*) FROM %s WHERE type='trigger'" },
5921     { "number of views:",
5922       "SELECT count(*) FROM %s WHERE type='view'" },
5923     { "schema size:",
5924       "SELECT total(length(sql)) FROM %s" },
5925  };
5926  int i, rc;
5927  unsigned iDataVersion;
5928  char *zSchemaTab;
5929  char *zDb = nArg>=2 ? azArg[1] : "main";
5930  sqlite3_stmt *pStmt = 0;
5931  unsigned char aHdr[100];
5932  open_db(p, 0);
5933  if( p->db==0 ) return 1;
5934  rc = sqlite3_prepare_v2(p->db,
5935             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5936             -1, &pStmt, 0);
5937  if( rc ){
5938    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5939    sqlite3_finalize(pStmt);
5940    return 1;
5941  }
5942  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5943  if( sqlite3_step(pStmt)==SQLITE_ROW
5944   && sqlite3_column_bytes(pStmt,0)>100
5945  ){
5946    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5947    sqlite3_finalize(pStmt);
5948  }else{
5949    raw_printf(stderr, "unable to read database header\n");
5950    sqlite3_finalize(pStmt);
5951    return 1;
5952  }
5953  i = get2byteInt(aHdr+16);
5954  if( i==1 ) i = 65536;
5955  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5956  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5957  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5958  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5959  for(i=0; i<ArraySize(aField); i++){
5960    int ofst = aField[i].ofst;
5961    unsigned int val = get4byteInt(aHdr + ofst);
5962    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5963    switch( ofst ){
5964      case 56: {
5965        if( val==1 ) raw_printf(p->out, " (utf8)");
5966        if( val==2 ) raw_printf(p->out, " (utf16le)");
5967        if( val==3 ) raw_printf(p->out, " (utf16be)");
5968      }
5969    }
5970    raw_printf(p->out, "\n");
5971  }
5972  if( zDb==0 ){
5973    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5974  }else if( strcmp(zDb,"temp")==0 ){
5975    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5976  }else{
5977    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5978  }
5979  for(i=0; i<ArraySize(aQuery); i++){
5980    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5981    int val = db_int(p->db, zSql);
5982    sqlite3_free(zSql);
5983    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5984  }
5985  sqlite3_free(zSchemaTab);
5986  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5987  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5988  return 0;
5989}
5990#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5991          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5992
5993/*
5994** Print the current sqlite3_errmsg() value to stderr and return 1.
5995*/
5996static int shellDatabaseError(sqlite3 *db){
5997  const char *zErr = sqlite3_errmsg(db);
5998  utf8_printf(stderr, "Error: %s\n", zErr);
5999  return 1;
6000}
6001
6002/*
6003** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
6004** if they match and FALSE (0) if they do not match.
6005**
6006** Globbing rules:
6007**
6008**      '*'       Matches any sequence of zero or more characters.
6009**
6010**      '?'       Matches exactly one character.
6011**
6012**     [...]      Matches one character from the enclosed list of
6013**                characters.
6014**
6015**     [^...]     Matches one character not in the enclosed list.
6016**
6017**      '#'       Matches any sequence of one or more digits with an
6018**                optional + or - sign in front
6019**
6020**      ' '       Any span of whitespace matches any other span of
6021**                whitespace.
6022**
6023** Extra whitespace at the end of z[] is ignored.
6024*/
6025static int testcase_glob(const char *zGlob, const char *z){
6026  int c, c2;
6027  int invert;
6028  int seen;
6029
6030  while( (c = (*(zGlob++)))!=0 ){
6031    if( IsSpace(c) ){
6032      if( !IsSpace(*z) ) return 0;
6033      while( IsSpace(*zGlob) ) zGlob++;
6034      while( IsSpace(*z) ) z++;
6035    }else if( c=='*' ){
6036      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6037        if( c=='?' && (*(z++))==0 ) return 0;
6038      }
6039      if( c==0 ){
6040        return 1;
6041      }else if( c=='[' ){
6042        while( *z && testcase_glob(zGlob-1,z)==0 ){
6043          z++;
6044        }
6045        return (*z)!=0;
6046      }
6047      while( (c2 = (*(z++)))!=0 ){
6048        while( c2!=c ){
6049          c2 = *(z++);
6050          if( c2==0 ) return 0;
6051        }
6052        if( testcase_glob(zGlob,z) ) return 1;
6053      }
6054      return 0;
6055    }else if( c=='?' ){
6056      if( (*(z++))==0 ) return 0;
6057    }else if( c=='[' ){
6058      int prior_c = 0;
6059      seen = 0;
6060      invert = 0;
6061      c = *(z++);
6062      if( c==0 ) return 0;
6063      c2 = *(zGlob++);
6064      if( c2=='^' ){
6065        invert = 1;
6066        c2 = *(zGlob++);
6067      }
6068      if( c2==']' ){
6069        if( c==']' ) seen = 1;
6070        c2 = *(zGlob++);
6071      }
6072      while( c2 && c2!=']' ){
6073        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6074          c2 = *(zGlob++);
6075          if( c>=prior_c && c<=c2 ) seen = 1;
6076          prior_c = 0;
6077        }else{
6078          if( c==c2 ){
6079            seen = 1;
6080          }
6081          prior_c = c2;
6082        }
6083        c2 = *(zGlob++);
6084      }
6085      if( c2==0 || (seen ^ invert)==0 ) return 0;
6086    }else if( c=='#' ){
6087      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6088      if( !IsDigit(z[0]) ) return 0;
6089      z++;
6090      while( IsDigit(z[0]) ){ z++; }
6091    }else{
6092      if( c!=(*(z++)) ) return 0;
6093    }
6094  }
6095  while( IsSpace(*z) ){ z++; }
6096  return *z==0;
6097}
6098
6099
6100/*
6101** Compare the string as a command-line option with either one or two
6102** initial "-" characters.
6103*/
6104static int optionMatch(const char *zStr, const char *zOpt){
6105  if( zStr[0]!='-' ) return 0;
6106  zStr++;
6107  if( zStr[0]=='-' ) zStr++;
6108  return strcmp(zStr, zOpt)==0;
6109}
6110
6111/*
6112** Delete a file.
6113*/
6114int shellDeleteFile(const char *zFilename){
6115  int rc;
6116#ifdef _WIN32
6117  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6118  rc = _wunlink(z);
6119  sqlite3_free(z);
6120#else
6121  rc = unlink(zFilename);
6122#endif
6123  return rc;
6124}
6125
6126/*
6127** Try to delete the temporary file (if there is one) and free the
6128** memory used to hold the name of the temp file.
6129*/
6130static void clearTempFile(ShellState *p){
6131  if( p->zTempFile==0 ) return;
6132  if( p->doXdgOpen ) return;
6133  if( shellDeleteFile(p->zTempFile) ) return;
6134  sqlite3_free(p->zTempFile);
6135  p->zTempFile = 0;
6136}
6137
6138/*
6139** Create a new temp file name with the given suffix.
6140*/
6141static void newTempFile(ShellState *p, const char *zSuffix){
6142  clearTempFile(p);
6143  sqlite3_free(p->zTempFile);
6144  p->zTempFile = 0;
6145  if( p->db ){
6146    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6147  }
6148  if( p->zTempFile==0 ){
6149    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6150    ** will not work and we will need to fallback to guessing */
6151    char *zTemp;
6152    sqlite3_uint64 r;
6153    sqlite3_randomness(sizeof(r), &r);
6154    zTemp = getenv("TEMP");
6155    if( zTemp==0 ) zTemp = getenv("TMP");
6156    if( zTemp==0 ){
6157#ifdef _WIN32
6158      zTemp = "\\tmp";
6159#else
6160      zTemp = "/tmp";
6161#endif
6162    }
6163    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6164  }else{
6165    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6166  }
6167  shell_check_oom(p->zTempFile);
6168}
6169
6170
6171/*
6172** The implementation of SQL scalar function fkey_collate_clause(), used
6173** by the ".lint fkey-indexes" command. This scalar function is always
6174** called with four arguments - the parent table name, the parent column name,
6175** the child table name and the child column name.
6176**
6177**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6178**
6179** If either of the named tables or columns do not exist, this function
6180** returns an empty string. An empty string is also returned if both tables
6181** and columns exist but have the same default collation sequence. Or,
6182** if both exist but the default collation sequences are different, this
6183** function returns the string " COLLATE <parent-collation>", where
6184** <parent-collation> is the default collation sequence of the parent column.
6185*/
6186static void shellFkeyCollateClause(
6187  sqlite3_context *pCtx,
6188  int nVal,
6189  sqlite3_value **apVal
6190){
6191  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6192  const char *zParent;
6193  const char *zParentCol;
6194  const char *zParentSeq;
6195  const char *zChild;
6196  const char *zChildCol;
6197  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6198  int rc;
6199
6200  assert( nVal==4 );
6201  zParent = (const char*)sqlite3_value_text(apVal[0]);
6202  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6203  zChild = (const char*)sqlite3_value_text(apVal[2]);
6204  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6205
6206  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6207  rc = sqlite3_table_column_metadata(
6208      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6209  );
6210  if( rc==SQLITE_OK ){
6211    rc = sqlite3_table_column_metadata(
6212        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6213    );
6214  }
6215
6216  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6217    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6218    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6219    sqlite3_free(z);
6220  }
6221}
6222
6223
6224/*
6225** The implementation of dot-command ".lint fkey-indexes".
6226*/
6227static int lintFkeyIndexes(
6228  ShellState *pState,             /* Current shell tool state */
6229  char **azArg,                   /* Array of arguments passed to dot command */
6230  int nArg                        /* Number of entries in azArg[] */
6231){
6232  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6233  FILE *out = pState->out;        /* Stream to write non-error output to */
6234  int bVerbose = 0;               /* If -verbose is present */
6235  int bGroupByParent = 0;         /* If -groupbyparent is present */
6236  int i;                          /* To iterate through azArg[] */
6237  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6238  int rc;                         /* Return code */
6239  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6240
6241  /*
6242  ** This SELECT statement returns one row for each foreign key constraint
6243  ** in the schema of the main database. The column values are:
6244  **
6245  ** 0. The text of an SQL statement similar to:
6246  **
6247  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6248  **
6249  **    This SELECT is similar to the one that the foreign keys implementation
6250  **    needs to run internally on child tables. If there is an index that can
6251  **    be used to optimize this query, then it can also be used by the FK
6252  **    implementation to optimize DELETE or UPDATE statements on the parent
6253  **    table.
6254  **
6255  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6256  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6257  **    contains an index that can be used to optimize the query.
6258  **
6259  ** 2. Human readable text that describes the child table and columns. e.g.
6260  **
6261  **       "child_table(child_key1, child_key2)"
6262  **
6263  ** 3. Human readable text that describes the parent table and columns. e.g.
6264  **
6265  **       "parent_table(parent_key1, parent_key2)"
6266  **
6267  ** 4. A full CREATE INDEX statement for an index that could be used to
6268  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6269  **
6270  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6271  **
6272  ** 5. The name of the parent table.
6273  **
6274  ** These six values are used by the C logic below to generate the report.
6275  */
6276  const char *zSql =
6277  "SELECT "
6278    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6279    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6280    "  || fkey_collate_clause("
6281    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6282    ", "
6283    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6284    "  || group_concat('*=?', ' AND ') || ')'"
6285    ", "
6286    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6287    ", "
6288    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6289    ", "
6290    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6291    "  || ' ON ' || quote(s.name) || '('"
6292    "  || group_concat(quote(f.[from]) ||"
6293    "        fkey_collate_clause("
6294    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6295    "  || ');'"
6296    ", "
6297    "     f.[table] "
6298    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6299    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6300    "GROUP BY s.name, f.id "
6301    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6302  ;
6303  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6304
6305  for(i=2; i<nArg; i++){
6306    int n = strlen30(azArg[i]);
6307    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6308      bVerbose = 1;
6309    }
6310    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6311      bGroupByParent = 1;
6312      zIndent = "    ";
6313    }
6314    else{
6315      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6316          azArg[0], azArg[1]
6317      );
6318      return SQLITE_ERROR;
6319    }
6320  }
6321
6322  /* Register the fkey_collate_clause() SQL function */
6323  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6324      0, shellFkeyCollateClause, 0, 0
6325  );
6326
6327
6328  if( rc==SQLITE_OK ){
6329    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6330  }
6331  if( rc==SQLITE_OK ){
6332    sqlite3_bind_int(pSql, 1, bGroupByParent);
6333  }
6334
6335  if( rc==SQLITE_OK ){
6336    int rc2;
6337    char *zPrev = 0;
6338    while( SQLITE_ROW==sqlite3_step(pSql) ){
6339      int res = -1;
6340      sqlite3_stmt *pExplain = 0;
6341      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6342      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6343      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6344      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6345      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6346      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6347
6348      if( zEQP==0 ) continue;
6349      if( zGlob==0 ) continue;
6350      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6351      if( rc!=SQLITE_OK ) break;
6352      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6353        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6354        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6355                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6356      }
6357      rc = sqlite3_finalize(pExplain);
6358      if( rc!=SQLITE_OK ) break;
6359
6360      if( res<0 ){
6361        raw_printf(stderr, "Error: internal error");
6362        break;
6363      }else{
6364        if( bGroupByParent
6365        && (bVerbose || res==0)
6366        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6367        ){
6368          raw_printf(out, "-- Parent table %s\n", zParent);
6369          sqlite3_free(zPrev);
6370          zPrev = sqlite3_mprintf("%s", zParent);
6371        }
6372
6373        if( res==0 ){
6374          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6375        }else if( bVerbose ){
6376          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6377              zIndent, zFrom, zTarget
6378          );
6379        }
6380      }
6381    }
6382    sqlite3_free(zPrev);
6383
6384    if( rc!=SQLITE_OK ){
6385      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6386    }
6387
6388    rc2 = sqlite3_finalize(pSql);
6389    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6390      rc = rc2;
6391      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6392    }
6393  }else{
6394    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6395  }
6396
6397  return rc;
6398}
6399
6400/*
6401** Implementation of ".lint" dot command.
6402*/
6403static int lintDotCommand(
6404  ShellState *pState,             /* Current shell tool state */
6405  char **azArg,                   /* Array of arguments passed to dot command */
6406  int nArg                        /* Number of entries in azArg[] */
6407){
6408  int n;
6409  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6410  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6411  return lintFkeyIndexes(pState, azArg, nArg);
6412
6413 usage:
6414  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6415  raw_printf(stderr, "Where sub-commands are:\n");
6416  raw_printf(stderr, "    fkey-indexes\n");
6417  return SQLITE_ERROR;
6418}
6419
6420#if !defined SQLITE_OMIT_VIRTUALTABLE
6421static void shellPrepare(
6422  sqlite3 *db,
6423  int *pRc,
6424  const char *zSql,
6425  sqlite3_stmt **ppStmt
6426){
6427  *ppStmt = 0;
6428  if( *pRc==SQLITE_OK ){
6429    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6430    if( rc!=SQLITE_OK ){
6431      raw_printf(stderr, "sql error: %s (%d)\n",
6432          sqlite3_errmsg(db), sqlite3_errcode(db)
6433      );
6434      *pRc = rc;
6435    }
6436  }
6437}
6438
6439/*
6440** Create a prepared statement using printf-style arguments for the SQL.
6441**
6442** This routine is could be marked "static".  But it is not always used,
6443** depending on compile-time options.  By omitting the "static", we avoid
6444** nuisance compiler warnings about "defined but not used".
6445*/
6446void shellPreparePrintf(
6447  sqlite3 *db,
6448  int *pRc,
6449  sqlite3_stmt **ppStmt,
6450  const char *zFmt,
6451  ...
6452){
6453  *ppStmt = 0;
6454  if( *pRc==SQLITE_OK ){
6455    va_list ap;
6456    char *z;
6457    va_start(ap, zFmt);
6458    z = sqlite3_vmprintf(zFmt, ap);
6459    va_end(ap);
6460    if( z==0 ){
6461      *pRc = SQLITE_NOMEM;
6462    }else{
6463      shellPrepare(db, pRc, z, ppStmt);
6464      sqlite3_free(z);
6465    }
6466  }
6467}
6468
6469/* Finalize the prepared statement created using shellPreparePrintf().
6470**
6471** This routine is could be marked "static".  But it is not always used,
6472** depending on compile-time options.  By omitting the "static", we avoid
6473** nuisance compiler warnings about "defined but not used".
6474*/
6475void shellFinalize(
6476  int *pRc,
6477  sqlite3_stmt *pStmt
6478){
6479  if( pStmt ){
6480    sqlite3 *db = sqlite3_db_handle(pStmt);
6481    int rc = sqlite3_finalize(pStmt);
6482    if( *pRc==SQLITE_OK ){
6483      if( rc!=SQLITE_OK ){
6484        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6485      }
6486      *pRc = rc;
6487    }
6488  }
6489}
6490
6491/* Reset the prepared statement created using shellPreparePrintf().
6492**
6493** This routine is could be marked "static".  But it is not always used,
6494** depending on compile-time options.  By omitting the "static", we avoid
6495** nuisance compiler warnings about "defined but not used".
6496*/
6497void shellReset(
6498  int *pRc,
6499  sqlite3_stmt *pStmt
6500){
6501  int rc = sqlite3_reset(pStmt);
6502  if( *pRc==SQLITE_OK ){
6503    if( rc!=SQLITE_OK ){
6504      sqlite3 *db = sqlite3_db_handle(pStmt);
6505      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6506    }
6507    *pRc = rc;
6508  }
6509}
6510#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6511
6512#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6513/******************************************************************************
6514** The ".archive" or ".ar" command.
6515*/
6516/*
6517** Structure representing a single ".ar" command.
6518*/
6519typedef struct ArCommand ArCommand;
6520struct ArCommand {
6521  u8 eCmd;                        /* An AR_CMD_* value */
6522  u8 bVerbose;                    /* True if --verbose */
6523  u8 bZip;                        /* True if the archive is a ZIP */
6524  u8 bDryRun;                     /* True if --dry-run */
6525  u8 bAppend;                     /* True if --append */
6526  u8 bGlob;                       /* True if --glob */
6527  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6528  int nArg;                       /* Number of command arguments */
6529  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6530  const char *zFile;              /* --file argument, or NULL */
6531  const char *zDir;               /* --directory argument, or NULL */
6532  char **azArg;                   /* Array of command arguments */
6533  ShellState *p;                  /* Shell state */
6534  sqlite3 *db;                    /* Database containing the archive */
6535};
6536
6537/*
6538** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6539*/
6540static int arUsage(FILE *f){
6541  showHelp(f,"archive");
6542  return SQLITE_ERROR;
6543}
6544
6545/*
6546** Print an error message for the .ar command to stderr and return
6547** SQLITE_ERROR.
6548*/
6549static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6550  va_list ap;
6551  char *z;
6552  va_start(ap, zFmt);
6553  z = sqlite3_vmprintf(zFmt, ap);
6554  va_end(ap);
6555  utf8_printf(stderr, "Error: %s\n", z);
6556  if( pAr->fromCmdLine ){
6557    utf8_printf(stderr, "Use \"-A\" for more help\n");
6558  }else{
6559    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6560  }
6561  sqlite3_free(z);
6562  return SQLITE_ERROR;
6563}
6564
6565/*
6566** Values for ArCommand.eCmd.
6567*/
6568#define AR_CMD_CREATE       1
6569#define AR_CMD_UPDATE       2
6570#define AR_CMD_INSERT       3
6571#define AR_CMD_EXTRACT      4
6572#define AR_CMD_LIST         5
6573#define AR_CMD_HELP         6
6574#define AR_CMD_REMOVE       7
6575
6576/*
6577** Other (non-command) switches.
6578*/
6579#define AR_SWITCH_VERBOSE     8
6580#define AR_SWITCH_FILE        9
6581#define AR_SWITCH_DIRECTORY  10
6582#define AR_SWITCH_APPEND     11
6583#define AR_SWITCH_DRYRUN     12
6584#define AR_SWITCH_GLOB       13
6585
6586static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6587  switch( eSwitch ){
6588    case AR_CMD_CREATE:
6589    case AR_CMD_EXTRACT:
6590    case AR_CMD_LIST:
6591    case AR_CMD_REMOVE:
6592    case AR_CMD_UPDATE:
6593    case AR_CMD_INSERT:
6594    case AR_CMD_HELP:
6595      if( pAr->eCmd ){
6596        return arErrorMsg(pAr, "multiple command options");
6597      }
6598      pAr->eCmd = eSwitch;
6599      break;
6600
6601    case AR_SWITCH_DRYRUN:
6602      pAr->bDryRun = 1;
6603      break;
6604    case AR_SWITCH_GLOB:
6605      pAr->bGlob = 1;
6606      break;
6607    case AR_SWITCH_VERBOSE:
6608      pAr->bVerbose = 1;
6609      break;
6610    case AR_SWITCH_APPEND:
6611      pAr->bAppend = 1;
6612      /* Fall thru into --file */
6613    case AR_SWITCH_FILE:
6614      pAr->zFile = zArg;
6615      break;
6616    case AR_SWITCH_DIRECTORY:
6617      pAr->zDir = zArg;
6618      break;
6619  }
6620
6621  return SQLITE_OK;
6622}
6623
6624/*
6625** Parse the command line for an ".ar" command. The results are written into
6626** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6627** successfully, otherwise an error message is written to stderr and
6628** SQLITE_ERROR returned.
6629*/
6630static int arParseCommand(
6631  char **azArg,                   /* Array of arguments passed to dot command */
6632  int nArg,                       /* Number of entries in azArg[] */
6633  ArCommand *pAr                  /* Populate this object */
6634){
6635  struct ArSwitch {
6636    const char *zLong;
6637    char cShort;
6638    u8 eSwitch;
6639    u8 bArg;
6640  } aSwitch[] = {
6641    { "create",    'c', AR_CMD_CREATE,       0 },
6642    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6643    { "insert",    'i', AR_CMD_INSERT,       0 },
6644    { "list",      't', AR_CMD_LIST,         0 },
6645    { "remove",    'r', AR_CMD_REMOVE,       0 },
6646    { "update",    'u', AR_CMD_UPDATE,       0 },
6647    { "help",      'h', AR_CMD_HELP,         0 },
6648    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6649    { "file",      'f', AR_SWITCH_FILE,      1 },
6650    { "append",    'a', AR_SWITCH_APPEND,    1 },
6651    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6652    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6653    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6654  };
6655  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6656  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6657
6658  if( nArg<=1 ){
6659    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6660    return arUsage(stderr);
6661  }else{
6662    char *z = azArg[1];
6663    if( z[0]!='-' ){
6664      /* Traditional style [tar] invocation */
6665      int i;
6666      int iArg = 2;
6667      for(i=0; z[i]; i++){
6668        const char *zArg = 0;
6669        struct ArSwitch *pOpt;
6670        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6671          if( z[i]==pOpt->cShort ) break;
6672        }
6673        if( pOpt==pEnd ){
6674          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6675        }
6676        if( pOpt->bArg ){
6677          if( iArg>=nArg ){
6678            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6679          }
6680          zArg = azArg[iArg++];
6681        }
6682        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6683      }
6684      pAr->nArg = nArg-iArg;
6685      if( pAr->nArg>0 ){
6686        pAr->azArg = &azArg[iArg];
6687      }
6688    }else{
6689      /* Non-traditional invocation */
6690      int iArg;
6691      for(iArg=1; iArg<nArg; iArg++){
6692        int n;
6693        z = azArg[iArg];
6694        if( z[0]!='-' ){
6695          /* All remaining command line words are command arguments. */
6696          pAr->azArg = &azArg[iArg];
6697          pAr->nArg = nArg-iArg;
6698          break;
6699        }
6700        n = strlen30(z);
6701
6702        if( z[1]!='-' ){
6703          int i;
6704          /* One or more short options */
6705          for(i=1; i<n; i++){
6706            const char *zArg = 0;
6707            struct ArSwitch *pOpt;
6708            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6709              if( z[i]==pOpt->cShort ) break;
6710            }
6711            if( pOpt==pEnd ){
6712              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6713            }
6714            if( pOpt->bArg ){
6715              if( i<(n-1) ){
6716                zArg = &z[i+1];
6717                i = n;
6718              }else{
6719                if( iArg>=(nArg-1) ){
6720                  return arErrorMsg(pAr, "option requires an argument: %c",
6721                                    z[i]);
6722                }
6723                zArg = azArg[++iArg];
6724              }
6725            }
6726            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6727          }
6728        }else if( z[2]=='\0' ){
6729          /* A -- option, indicating that all remaining command line words
6730          ** are command arguments.  */
6731          pAr->azArg = &azArg[iArg+1];
6732          pAr->nArg = nArg-iArg-1;
6733          break;
6734        }else{
6735          /* A long option */
6736          const char *zArg = 0;             /* Argument for option, if any */
6737          struct ArSwitch *pMatch = 0;      /* Matching option */
6738          struct ArSwitch *pOpt;            /* Iterator */
6739          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6740            const char *zLong = pOpt->zLong;
6741            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6742              if( pMatch ){
6743                return arErrorMsg(pAr, "ambiguous option: %s",z);
6744              }else{
6745                pMatch = pOpt;
6746              }
6747            }
6748          }
6749
6750          if( pMatch==0 ){
6751            return arErrorMsg(pAr, "unrecognized option: %s", z);
6752          }
6753          if( pMatch->bArg ){
6754            if( iArg>=(nArg-1) ){
6755              return arErrorMsg(pAr, "option requires an argument: %s", z);
6756            }
6757            zArg = azArg[++iArg];
6758          }
6759          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6760        }
6761      }
6762    }
6763  }
6764
6765  return SQLITE_OK;
6766}
6767
6768/*
6769** This function assumes that all arguments within the ArCommand.azArg[]
6770** array refer to archive members, as for the --extract, --list or --remove
6771** commands. It checks that each of them are "present". If any specified
6772** file is not present in the archive, an error is printed to stderr and an
6773** error code returned. Otherwise, if all specified arguments are present
6774** in the archive, SQLITE_OK is returned. Here, "present" means either an
6775** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6776** when pAr->bGlob is true.
6777**
6778** This function strips any trailing '/' characters from each argument.
6779** This is consistent with the way the [tar] command seems to work on
6780** Linux.
6781*/
6782static int arCheckEntries(ArCommand *pAr){
6783  int rc = SQLITE_OK;
6784  if( pAr->nArg ){
6785    int i, j;
6786    sqlite3_stmt *pTest = 0;
6787    const char *zSel = (pAr->bGlob)
6788      ? "SELECT name FROM %s WHERE glob($name,name)"
6789      : "SELECT name FROM %s WHERE name=$name";
6790
6791    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6792    j = sqlite3_bind_parameter_index(pTest, "$name");
6793    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6794      char *z = pAr->azArg[i];
6795      int n = strlen30(z);
6796      int bOk = 0;
6797      while( n>0 && z[n-1]=='/' ) n--;
6798      z[n] = '\0';
6799      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6800      if( SQLITE_ROW==sqlite3_step(pTest) ){
6801        bOk = 1;
6802      }
6803      shellReset(&rc, pTest);
6804      if( rc==SQLITE_OK && bOk==0 ){
6805        utf8_printf(stderr, "not found in archive: %s\n", z);
6806        rc = SQLITE_ERROR;
6807      }
6808    }
6809    shellFinalize(&rc, pTest);
6810  }
6811  return rc;
6812}
6813
6814/*
6815** Format a WHERE clause that can be used against the "sqlar" table to
6816** identify all archive members that match the command arguments held
6817** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6818** The caller is responsible for eventually calling sqlite3_free() on
6819** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6820** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6821*/
6822static void arWhereClause(
6823  int *pRc,
6824  ArCommand *pAr,
6825  char **pzWhere                  /* OUT: New WHERE clause */
6826){
6827  char *zWhere = 0;
6828  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6829  if( *pRc==SQLITE_OK ){
6830    if( pAr->nArg==0 ){
6831      zWhere = sqlite3_mprintf("1");
6832    }else{
6833      int i;
6834      const char *zSep = "";
6835      for(i=0; i<pAr->nArg; i++){
6836        const char *z = pAr->azArg[i];
6837        zWhere = sqlite3_mprintf(
6838          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6839          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6840        );
6841        if( zWhere==0 ){
6842          *pRc = SQLITE_NOMEM;
6843          break;
6844        }
6845        zSep = " OR ";
6846      }
6847    }
6848  }
6849  *pzWhere = zWhere;
6850}
6851
6852/*
6853** Implementation of .ar "lisT" command.
6854*/
6855static int arListCommand(ArCommand *pAr){
6856  const char *zSql = "SELECT %s FROM %s WHERE %s";
6857  const char *azCols[] = {
6858    "name",
6859    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6860  };
6861
6862  char *zWhere = 0;
6863  sqlite3_stmt *pSql = 0;
6864  int rc;
6865
6866  rc = arCheckEntries(pAr);
6867  arWhereClause(&rc, pAr, &zWhere);
6868
6869  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6870                     pAr->zSrcTable, zWhere);
6871  if( pAr->bDryRun ){
6872    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6873  }else{
6874    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6875      if( pAr->bVerbose ){
6876        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6877            sqlite3_column_text(pSql, 0),
6878            sqlite3_column_int(pSql, 1),
6879            sqlite3_column_text(pSql, 2),
6880            sqlite3_column_text(pSql, 3)
6881        );
6882      }else{
6883        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6884      }
6885    }
6886  }
6887  shellFinalize(&rc, pSql);
6888  sqlite3_free(zWhere);
6889  return rc;
6890}
6891
6892
6893/*
6894** Implementation of .ar "Remove" command.
6895*/
6896static int arRemoveCommand(ArCommand *pAr){
6897  int rc = 0;
6898  char *zSql = 0;
6899  char *zWhere = 0;
6900
6901  if( pAr->nArg ){
6902    /* Verify that args actually exist within the archive before proceeding.
6903    ** And formulate a WHERE clause to match them.  */
6904    rc = arCheckEntries(pAr);
6905    arWhereClause(&rc, pAr, &zWhere);
6906  }
6907  if( rc==SQLITE_OK ){
6908    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6909                           pAr->zSrcTable, zWhere);
6910    if( pAr->bDryRun ){
6911      utf8_printf(pAr->p->out, "%s\n", zSql);
6912    }else{
6913      char *zErr = 0;
6914      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6915      if( rc==SQLITE_OK ){
6916        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6917        if( rc!=SQLITE_OK ){
6918          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6919        }else{
6920          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6921        }
6922      }
6923      if( zErr ){
6924        utf8_printf(stdout, "ERROR: %s\n", zErr);
6925        sqlite3_free(zErr);
6926      }
6927    }
6928  }
6929  sqlite3_free(zWhere);
6930  sqlite3_free(zSql);
6931  return rc;
6932}
6933
6934/*
6935** Implementation of .ar "eXtract" command.
6936*/
6937static int arExtractCommand(ArCommand *pAr){
6938  const char *zSql1 =
6939    "SELECT "
6940    " ($dir || name),"
6941    " writefile(($dir || name), %s, mode, mtime) "
6942    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6943    " AND name NOT GLOB '*..[/\\]*'";
6944
6945  const char *azExtraArg[] = {
6946    "sqlar_uncompress(data, sz)",
6947    "data"
6948  };
6949
6950  sqlite3_stmt *pSql = 0;
6951  int rc = SQLITE_OK;
6952  char *zDir = 0;
6953  char *zWhere = 0;
6954  int i, j;
6955
6956  /* If arguments are specified, check that they actually exist within
6957  ** the archive before proceeding. And formulate a WHERE clause to
6958  ** match them.  */
6959  rc = arCheckEntries(pAr);
6960  arWhereClause(&rc, pAr, &zWhere);
6961
6962  if( rc==SQLITE_OK ){
6963    if( pAr->zDir ){
6964      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6965    }else{
6966      zDir = sqlite3_mprintf("");
6967    }
6968    if( zDir==0 ) rc = SQLITE_NOMEM;
6969  }
6970
6971  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6972      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6973  );
6974
6975  if( rc==SQLITE_OK ){
6976    j = sqlite3_bind_parameter_index(pSql, "$dir");
6977    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6978
6979    /* Run the SELECT statement twice. The first time, writefile() is called
6980    ** for all archive members that should be extracted. The second time,
6981    ** only for the directories. This is because the timestamps for
6982    ** extracted directories must be reset after they are populated (as
6983    ** populating them changes the timestamp).  */
6984    for(i=0; i<2; i++){
6985      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6986      sqlite3_bind_int(pSql, j, i);
6987      if( pAr->bDryRun ){
6988        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6989      }else{
6990        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6991          if( i==0 && pAr->bVerbose ){
6992            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6993          }
6994        }
6995      }
6996      shellReset(&rc, pSql);
6997    }
6998    shellFinalize(&rc, pSql);
6999  }
7000
7001  sqlite3_free(zDir);
7002  sqlite3_free(zWhere);
7003  return rc;
7004}
7005
7006/*
7007** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
7008*/
7009static int arExecSql(ArCommand *pAr, const char *zSql){
7010  int rc;
7011  if( pAr->bDryRun ){
7012    utf8_printf(pAr->p->out, "%s\n", zSql);
7013    rc = SQLITE_OK;
7014  }else{
7015    char *zErr = 0;
7016    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7017    if( zErr ){
7018      utf8_printf(stdout, "ERROR: %s\n", zErr);
7019      sqlite3_free(zErr);
7020    }
7021  }
7022  return rc;
7023}
7024
7025
7026/*
7027** Implementation of .ar "create", "insert", and "update" commands.
7028**
7029**     create    ->     Create a new SQL archive
7030**     insert    ->     Insert or reinsert all files listed
7031**     update    ->     Insert files that have changed or that were not
7032**                      previously in the archive
7033**
7034** Create the "sqlar" table in the database if it does not already exist.
7035** Then add each file in the azFile[] array to the archive. Directories
7036** are added recursively. If argument bVerbose is non-zero, a message is
7037** printed on stdout for each file archived.
7038**
7039** The create command is the same as update, except that it drops
7040** any existing "sqlar" table before beginning.  The "insert" command
7041** always overwrites every file named on the command-line, where as
7042** "update" only overwrites if the size or mtime or mode has changed.
7043*/
7044static int arCreateOrUpdateCommand(
7045  ArCommand *pAr,                 /* Command arguments and options */
7046  int bUpdate,                    /* true for a --create. */
7047  int bOnlyIfChanged              /* Only update if file has changed */
7048){
7049  const char *zCreate =
7050      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7051      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7052      "  mode INT,               -- access permissions\n"
7053      "  mtime INT,              -- last modification time\n"
7054      "  sz INT,                 -- original file size\n"
7055      "  data BLOB               -- compressed content\n"
7056      ")";
7057  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7058  const char *zInsertFmt[2] = {
7059     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7060     "  SELECT\n"
7061     "    %s,\n"
7062     "    mode,\n"
7063     "    mtime,\n"
7064     "    CASE substr(lsmode(mode),1,1)\n"
7065     "      WHEN '-' THEN length(data)\n"
7066     "      WHEN 'd' THEN 0\n"
7067     "      ELSE -1 END,\n"
7068     "    sqlar_compress(data)\n"
7069     "  FROM fsdir(%Q,%Q) AS disk\n"
7070     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7071     ,
7072     "REPLACE INTO %s(name,mode,mtime,data)\n"
7073     "  SELECT\n"
7074     "    %s,\n"
7075     "    mode,\n"
7076     "    mtime,\n"
7077     "    data\n"
7078     "  FROM fsdir(%Q,%Q) AS disk\n"
7079     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7080  };
7081  int i;                          /* For iterating through azFile[] */
7082  int rc;                         /* Return code */
7083  const char *zTab = 0;           /* SQL table into which to insert */
7084  char *zSql;
7085  char zTemp[50];
7086  char *zExists = 0;
7087
7088  arExecSql(pAr, "PRAGMA page_size=512");
7089  rc = arExecSql(pAr, "SAVEPOINT ar;");
7090  if( rc!=SQLITE_OK ) return rc;
7091  zTemp[0] = 0;
7092  if( pAr->bZip ){
7093    /* Initialize the zipfile virtual table, if necessary */
7094    if( pAr->zFile ){
7095      sqlite3_uint64 r;
7096      sqlite3_randomness(sizeof(r),&r);
7097      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7098      zTab = zTemp;
7099      zSql = sqlite3_mprintf(
7100         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7101         zTab, pAr->zFile
7102      );
7103      rc = arExecSql(pAr, zSql);
7104      sqlite3_free(zSql);
7105    }else{
7106      zTab = "zip";
7107    }
7108  }else{
7109    /* Initialize the table for an SQLAR */
7110    zTab = "sqlar";
7111    if( bUpdate==0 ){
7112      rc = arExecSql(pAr, zDrop);
7113      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7114    }
7115    rc = arExecSql(pAr, zCreate);
7116  }
7117  if( bOnlyIfChanged ){
7118    zExists = sqlite3_mprintf(
7119      " AND NOT EXISTS("
7120          "SELECT 1 FROM %s AS mem"
7121          " WHERE mem.name=disk.name"
7122          " AND mem.mtime=disk.mtime"
7123          " AND mem.mode=disk.mode)", zTab);
7124  }else{
7125    zExists = sqlite3_mprintf("");
7126  }
7127  if( zExists==0 ) rc = SQLITE_NOMEM;
7128  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7129    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7130        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7131        pAr->azArg[i], pAr->zDir, zExists);
7132    rc = arExecSql(pAr, zSql2);
7133    sqlite3_free(zSql2);
7134  }
7135end_ar_transaction:
7136  if( rc!=SQLITE_OK ){
7137    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7138  }else{
7139    rc = arExecSql(pAr, "RELEASE ar;");
7140    if( pAr->bZip && pAr->zFile ){
7141      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7142      arExecSql(pAr, zSql);
7143      sqlite3_free(zSql);
7144    }
7145  }
7146  sqlite3_free(zExists);
7147  return rc;
7148}
7149
7150/*
7151** Implementation of ".ar" dot command.
7152*/
7153static int arDotCommand(
7154  ShellState *pState,          /* Current shell tool state */
7155  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7156  char **azArg,                /* Array of arguments passed to dot command */
7157  int nArg                     /* Number of entries in azArg[] */
7158){
7159  ArCommand cmd;
7160  int rc;
7161  memset(&cmd, 0, sizeof(cmd));
7162  cmd.fromCmdLine = fromCmdLine;
7163  rc = arParseCommand(azArg, nArg, &cmd);
7164  if( rc==SQLITE_OK ){
7165    int eDbType = SHELL_OPEN_UNSPEC;
7166    cmd.p = pState;
7167    cmd.db = pState->db;
7168    if( cmd.zFile ){
7169      eDbType = deduceDatabaseType(cmd.zFile, 1);
7170    }else{
7171      eDbType = pState->openMode;
7172    }
7173    if( eDbType==SHELL_OPEN_ZIPFILE ){
7174      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7175        if( cmd.zFile==0 ){
7176          cmd.zSrcTable = sqlite3_mprintf("zip");
7177        }else{
7178          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7179        }
7180      }
7181      cmd.bZip = 1;
7182    }else if( cmd.zFile ){
7183      int flags;
7184      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7185      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7186           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7187        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7188      }else{
7189        flags = SQLITE_OPEN_READONLY;
7190      }
7191      cmd.db = 0;
7192      if( cmd.bDryRun ){
7193        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7194             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7195      }
7196      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7197             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7198      if( rc!=SQLITE_OK ){
7199        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7200            cmd.zFile, sqlite3_errmsg(cmd.db)
7201        );
7202        goto end_ar_command;
7203      }
7204      sqlite3_fileio_init(cmd.db, 0, 0);
7205      sqlite3_sqlar_init(cmd.db, 0, 0);
7206      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7207                              shellPutsFunc, 0, 0);
7208
7209    }
7210    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7211      if( cmd.eCmd!=AR_CMD_CREATE
7212       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7213      ){
7214        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7215        rc = SQLITE_ERROR;
7216        goto end_ar_command;
7217      }
7218      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7219    }
7220
7221    switch( cmd.eCmd ){
7222      case AR_CMD_CREATE:
7223        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7224        break;
7225
7226      case AR_CMD_EXTRACT:
7227        rc = arExtractCommand(&cmd);
7228        break;
7229
7230      case AR_CMD_LIST:
7231        rc = arListCommand(&cmd);
7232        break;
7233
7234      case AR_CMD_HELP:
7235        arUsage(pState->out);
7236        break;
7237
7238      case AR_CMD_INSERT:
7239        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7240        break;
7241
7242      case AR_CMD_REMOVE:
7243        rc = arRemoveCommand(&cmd);
7244        break;
7245
7246      default:
7247        assert( cmd.eCmd==AR_CMD_UPDATE );
7248        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7249        break;
7250    }
7251  }
7252end_ar_command:
7253  if( cmd.db!=pState->db ){
7254    close_db(cmd.db);
7255  }
7256  sqlite3_free(cmd.zSrcTable);
7257
7258  return rc;
7259}
7260/* End of the ".archive" or ".ar" command logic
7261*******************************************************************************/
7262#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7263
7264#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7265/*
7266** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7267** Otherwise, the SQL statement or statements in zSql are executed using
7268** database connection db and the error code written to *pRc before
7269** this function returns.
7270*/
7271static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7272  int rc = *pRc;
7273  if( rc==SQLITE_OK ){
7274    char *zErr = 0;
7275    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7276    if( rc!=SQLITE_OK ){
7277      raw_printf(stderr, "SQL error: %s\n", zErr);
7278    }
7279    sqlite3_free(zErr);
7280    *pRc = rc;
7281  }
7282}
7283
7284/*
7285** Like shellExec(), except that zFmt is a printf() style format string.
7286*/
7287static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7288  char *z = 0;
7289  if( *pRc==SQLITE_OK ){
7290    va_list ap;
7291    va_start(ap, zFmt);
7292    z = sqlite3_vmprintf(zFmt, ap);
7293    va_end(ap);
7294    if( z==0 ){
7295      *pRc = SQLITE_NOMEM;
7296    }else{
7297      shellExec(db, pRc, z);
7298    }
7299    sqlite3_free(z);
7300  }
7301}
7302
7303/*
7304** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7305** Otherwise, an attempt is made to allocate, zero and return a pointer
7306** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7307** to SQLITE_NOMEM and NULL returned.
7308*/
7309static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7310  void *pRet = 0;
7311  if( *pRc==SQLITE_OK ){
7312    pRet = sqlite3_malloc64(nByte);
7313    if( pRet==0 ){
7314      *pRc = SQLITE_NOMEM;
7315    }else{
7316      memset(pRet, 0, nByte);
7317    }
7318  }
7319  return pRet;
7320}
7321
7322/*
7323** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7324** Otherwise, zFmt is treated as a printf() style string. The result of
7325** formatting it along with any trailing arguments is written into a
7326** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7327** It is the responsibility of the caller to eventually free this buffer
7328** using a call to sqlite3_free().
7329**
7330** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7331** pointer returned.
7332*/
7333static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7334  char *z = 0;
7335  if( *pRc==SQLITE_OK ){
7336    va_list ap;
7337    va_start(ap, zFmt);
7338    z = sqlite3_vmprintf(zFmt, ap);
7339    va_end(ap);
7340    if( z==0 ){
7341      *pRc = SQLITE_NOMEM;
7342    }
7343  }
7344  return z;
7345}
7346
7347
7348/*
7349** When running the ".recover" command, each output table, and the special
7350** orphaned row table if it is required, is represented by an instance
7351** of the following struct.
7352*/
7353typedef struct RecoverTable RecoverTable;
7354struct RecoverTable {
7355  char *zQuoted;                  /* Quoted version of table name */
7356  int nCol;                       /* Number of columns in table */
7357  char **azlCol;                  /* Array of column lists */
7358  int iPk;                        /* Index of IPK column */
7359};
7360
7361/*
7362** Free a RecoverTable object allocated by recoverFindTable() or
7363** recoverOrphanTable().
7364*/
7365static void recoverFreeTable(RecoverTable *pTab){
7366  if( pTab ){
7367    sqlite3_free(pTab->zQuoted);
7368    if( pTab->azlCol ){
7369      int i;
7370      for(i=0; i<=pTab->nCol; i++){
7371        sqlite3_free(pTab->azlCol[i]);
7372      }
7373      sqlite3_free(pTab->azlCol);
7374    }
7375    sqlite3_free(pTab);
7376  }
7377}
7378
7379/*
7380** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7381** Otherwise, it allocates and returns a RecoverTable object based on the
7382** final four arguments passed to this function. It is the responsibility
7383** of the caller to eventually free the returned object using
7384** recoverFreeTable().
7385*/
7386static RecoverTable *recoverNewTable(
7387  int *pRc,                       /* IN/OUT: Error code */
7388  const char *zName,              /* Name of table */
7389  const char *zSql,               /* CREATE TABLE statement */
7390  int bIntkey,
7391  int nCol
7392){
7393  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7394  int rc = *pRc;
7395  RecoverTable *pTab = 0;
7396
7397  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7398  if( rc==SQLITE_OK ){
7399    int nSqlCol = 0;
7400    int bSqlIntkey = 0;
7401    sqlite3_stmt *pStmt = 0;
7402
7403    rc = sqlite3_open("", &dbtmp);
7404    if( rc==SQLITE_OK ){
7405      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7406                              shellIdQuote, 0, 0);
7407    }
7408    if( rc==SQLITE_OK ){
7409      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7410    }
7411    if( rc==SQLITE_OK ){
7412      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7413      if( rc==SQLITE_ERROR ){
7414        rc = SQLITE_OK;
7415        goto finished;
7416      }
7417    }
7418    shellPreparePrintf(dbtmp, &rc, &pStmt,
7419        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7420    );
7421    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7422      nSqlCol = sqlite3_column_int(pStmt, 0);
7423    }
7424    shellFinalize(&rc, pStmt);
7425
7426    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7427      goto finished;
7428    }
7429
7430    shellPreparePrintf(dbtmp, &rc, &pStmt,
7431      "SELECT ("
7432      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7433      ") FROM sqlite_schema WHERE name = %Q", zName
7434    );
7435    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7436      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7437    }
7438    shellFinalize(&rc, pStmt);
7439
7440    if( bIntkey==bSqlIntkey ){
7441      int i;
7442      const char *zPk = "_rowid_";
7443      sqlite3_stmt *pPkFinder = 0;
7444
7445      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7446      ** set zPk to the name of the PK column, and pTab->iPk to the index
7447      ** of the column, where columns are 0-numbered from left to right.
7448      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7449      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7450      pTab->iPk = -2;
7451      if( bIntkey ){
7452        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7453          "SELECT cid, name FROM pragma_table_info(%Q) "
7454          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7455          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7456          , zName, zName
7457        );
7458        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7459          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7460          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7461          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7462        }
7463      }
7464
7465      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7466      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7467      pTab->nCol = nSqlCol;
7468
7469      if( bIntkey ){
7470        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7471      }else{
7472        pTab->azlCol[0] = shellMPrintf(&rc, "");
7473      }
7474      i = 1;
7475      shellPreparePrintf(dbtmp, &rc, &pStmt,
7476          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7477          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7478          "FROM pragma_table_info(%Q)",
7479          bIntkey ? ", " : "", pTab->iPk,
7480          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7481          zName
7482      );
7483      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7484        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7485        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7486        i++;
7487      }
7488      shellFinalize(&rc, pStmt);
7489
7490      shellFinalize(&rc, pPkFinder);
7491    }
7492  }
7493
7494 finished:
7495  sqlite3_close(dbtmp);
7496  *pRc = rc;
7497  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7498    recoverFreeTable(pTab);
7499    pTab = 0;
7500  }
7501  return pTab;
7502}
7503
7504/*
7505** This function is called to search the schema recovered from the
7506** sqlite_schema table of the (possibly) corrupt database as part
7507** of a ".recover" command. Specifically, for a table with root page
7508** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7509** table must be a WITHOUT ROWID table, or if non-zero, not one of
7510** those.
7511**
7512** If a table is found, a (RecoverTable*) object is returned. Or, if
7513** no such table is found, but bIntkey is false and iRoot is the
7514** root page of an index in the recovered schema, then (*pbNoop) is
7515** set to true and NULL returned. Or, if there is no such table or
7516** index, NULL is returned and (*pbNoop) set to 0, indicating that
7517** the caller should write data to the orphans table.
7518*/
7519static RecoverTable *recoverFindTable(
7520  ShellState *pState,             /* Shell state object */
7521  int *pRc,                       /* IN/OUT: Error code */
7522  int iRoot,                      /* Root page of table */
7523  int bIntkey,                    /* True for an intkey table */
7524  int nCol,                       /* Number of columns in table */
7525  int *pbNoop                     /* OUT: True if iRoot is root of index */
7526){
7527  sqlite3_stmt *pStmt = 0;
7528  RecoverTable *pRet = 0;
7529  int bNoop = 0;
7530  const char *zSql = 0;
7531  const char *zName = 0;
7532
7533  /* Search the recovered schema for an object with root page iRoot. */
7534  shellPreparePrintf(pState->db, pRc, &pStmt,
7535      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7536  );
7537  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7538    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7539    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7540      bNoop = 1;
7541      break;
7542    }
7543    if( sqlite3_stricmp(zType, "table")==0 ){
7544      zName = (const char*)sqlite3_column_text(pStmt, 1);
7545      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7546      if( zName!=0 && zSql!=0 ){
7547        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7548        break;
7549      }
7550    }
7551  }
7552
7553  shellFinalize(pRc, pStmt);
7554  *pbNoop = bNoop;
7555  return pRet;
7556}
7557
7558/*
7559** Return a RecoverTable object representing the orphans table.
7560*/
7561static RecoverTable *recoverOrphanTable(
7562  ShellState *pState,             /* Shell state object */
7563  int *pRc,                       /* IN/OUT: Error code */
7564  const char *zLostAndFound,      /* Base name for orphans table */
7565  int nCol                        /* Number of user data columns */
7566){
7567  RecoverTable *pTab = 0;
7568  if( nCol>=0 && *pRc==SQLITE_OK ){
7569    int i;
7570
7571    /* This block determines the name of the orphan table. The prefered
7572    ** name is zLostAndFound. But if that clashes with another name
7573    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7574    ** and so on until a non-clashing name is found.  */
7575    int iTab = 0;
7576    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7577    sqlite3_stmt *pTest = 0;
7578    shellPrepare(pState->db, pRc,
7579        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7580    );
7581    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7582    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7583      shellReset(pRc, pTest);
7584      sqlite3_free(zTab);
7585      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7586      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7587    }
7588    shellFinalize(pRc, pTest);
7589
7590    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7591    if( pTab ){
7592      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7593      pTab->nCol = nCol;
7594      pTab->iPk = -2;
7595      if( nCol>0 ){
7596        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7597        if( pTab->azlCol ){
7598          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7599          for(i=nCol-1; i>=0; i--){
7600            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7601          }
7602        }
7603      }
7604
7605      if( *pRc!=SQLITE_OK ){
7606        recoverFreeTable(pTab);
7607        pTab = 0;
7608      }else{
7609        raw_printf(pState->out,
7610            "CREATE TABLE %s(rootpgno INTEGER, "
7611            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7612        );
7613        for(i=0; i<nCol; i++){
7614          raw_printf(pState->out, ", c%d", i);
7615        }
7616        raw_printf(pState->out, ");\n");
7617      }
7618    }
7619    sqlite3_free(zTab);
7620  }
7621  return pTab;
7622}
7623
7624/*
7625** This function is called to recover data from the database. A script
7626** to construct a new database containing all recovered data is output
7627** on stream pState->out.
7628*/
7629static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7630  int rc = SQLITE_OK;
7631  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7632  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7633  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7634  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7635  const char *zLostAndFound = "lost_and_found";
7636  int i;
7637  int nOrphan = -1;
7638  RecoverTable *pOrphan = 0;
7639
7640  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7641  int bRowids = 1;                /* 0 if --no-rowids */
7642  for(i=1; i<nArg; i++){
7643    char *z = azArg[i];
7644    int n;
7645    if( z[0]=='-' && z[1]=='-' ) z++;
7646    n = strlen30(z);
7647    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7648      bFreelist = 0;
7649    }else
7650    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7651      i++;
7652      zRecoveryDb = azArg[i];
7653    }else
7654    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7655      i++;
7656      zLostAndFound = azArg[i];
7657    }else
7658    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7659      bRowids = 0;
7660    }
7661    else{
7662      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7663      showHelp(pState->out, azArg[0]);
7664      return 1;
7665    }
7666  }
7667
7668  shellExecPrintf(pState->db, &rc,
7669    /* Attach an in-memory database named 'recovery'. Create an indexed
7670    ** cache of the sqlite_dbptr virtual table. */
7671    "PRAGMA writable_schema = on;"
7672    "ATTACH %Q AS recovery;"
7673    "DROP TABLE IF EXISTS recovery.dbptr;"
7674    "DROP TABLE IF EXISTS recovery.freelist;"
7675    "DROP TABLE IF EXISTS recovery.map;"
7676    "DROP TABLE IF EXISTS recovery.schema;"
7677    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7678  );
7679
7680  if( bFreelist ){
7681    shellExec(pState->db, &rc,
7682      "WITH trunk(pgno) AS ("
7683      "  SELECT shell_int32("
7684      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7685      "      WHERE x>0"
7686      "    UNION"
7687      "  SELECT shell_int32("
7688      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7689      "      FROM trunk WHERE x>0"
7690      "),"
7691      "freelist(data, n, freepgno) AS ("
7692      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7693      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7694      "    UNION ALL"
7695      "  SELECT data, n-1, shell_int32(data, 2+n) "
7696      "      FROM freelist WHERE n>=0"
7697      ")"
7698      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7699    );
7700  }
7701
7702  /* If this is an auto-vacuum database, add all pointer-map pages to
7703  ** the freelist table. Do this regardless of whether or not
7704  ** --freelist-corrupt was specified.  */
7705  shellExec(pState->db, &rc,
7706    "WITH ptrmap(pgno) AS ("
7707    "  SELECT 2 WHERE shell_int32("
7708    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7709    "  )"
7710    "    UNION ALL "
7711    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7712    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7713    ")"
7714    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7715  );
7716
7717  shellExec(pState->db, &rc,
7718    "CREATE TABLE recovery.dbptr("
7719    "      pgno, child, PRIMARY KEY(child, pgno)"
7720    ") WITHOUT ROWID;"
7721    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7722    "    SELECT * FROM sqlite_dbptr"
7723    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7724
7725    /* Delete any pointer to page 1. This ensures that page 1 is considered
7726    ** a root page, regardless of how corrupt the db is. */
7727    "DELETE FROM recovery.dbptr WHERE child = 1;"
7728
7729    /* Delete all pointers to any pages that have more than one pointer
7730    ** to them. Such pages will be treated as root pages when recovering
7731    ** data.  */
7732    "DELETE FROM recovery.dbptr WHERE child IN ("
7733    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7734    ");"
7735
7736    /* Create the "map" table that will (eventually) contain instructions
7737    ** for dealing with each page in the db that contains one or more
7738    ** records. */
7739    "CREATE TABLE recovery.map("
7740      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7741    ");"
7742
7743    /* Populate table [map]. If there are circular loops of pages in the
7744    ** database, the following adds all pages in such a loop to the map
7745    ** as individual root pages. This could be handled better.  */
7746    "WITH pages(i, maxlen) AS ("
7747    "  SELECT page_count, ("
7748    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7749    "  ) FROM pragma_page_count WHERE page_count>0"
7750    "    UNION ALL"
7751    "  SELECT i-1, ("
7752    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7753    "  ) FROM pages WHERE i>=2"
7754    ")"
7755    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7756    "  SELECT i, maxlen, NULL, ("
7757    "    WITH p(orig, pgno, parent) AS ("
7758    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7759    "        UNION "
7760    "      SELECT i, p.parent, "
7761    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7762    "    )"
7763    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7764    ") "
7765    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7766    "UPDATE recovery.map AS o SET intkey = ("
7767    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7768    ");"
7769
7770    /* Extract data from page 1 and any linked pages into table
7771    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7772    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7773    "INSERT INTO recovery.schema SELECT "
7774    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7775    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7776    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7777    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7778    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7779    "FROM sqlite_dbdata WHERE pgno IN ("
7780    "  SELECT pgno FROM recovery.map WHERE root=1"
7781    ")"
7782    "GROUP BY pgno, cell;"
7783    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7784  );
7785
7786  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7787  ** CREATE TABLE statements that extracted from the existing schema.  */
7788  if( rc==SQLITE_OK ){
7789    sqlite3_stmt *pStmt = 0;
7790    /* ".recover" might output content in an order which causes immediate
7791    ** foreign key constraints to be violated. So disable foreign-key
7792    ** constraint enforcement to prevent problems when running the output
7793    ** script. */
7794    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7795    raw_printf(pState->out, "BEGIN;\n");
7796    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7797    shellPrepare(pState->db, &rc,
7798        "SELECT sql FROM recovery.schema "
7799        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7800    );
7801    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7802      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7803      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7804          &zCreateTable[12]
7805      );
7806    }
7807    shellFinalize(&rc, pStmt);
7808  }
7809
7810  /* Figure out if an orphan table will be required. And if so, how many
7811  ** user columns it should contain */
7812  shellPrepare(pState->db, &rc,
7813      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7814      , &pLoop
7815  );
7816  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7817    nOrphan = sqlite3_column_int(pLoop, 0);
7818  }
7819  shellFinalize(&rc, pLoop);
7820  pLoop = 0;
7821
7822  shellPrepare(pState->db, &rc,
7823      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7824  );
7825
7826  shellPrepare(pState->db, &rc,
7827      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7828      "(case when (? AND field<0) then NULL else value end)"
7829      "), ', ')"
7830      ", min(field) "
7831      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7832      "GROUP BY cell", &pCells
7833  );
7834
7835  /* Loop through each root page. */
7836  shellPrepare(pState->db, &rc,
7837      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7838      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7839      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7840      ")", &pLoop
7841  );
7842  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7843    int iRoot = sqlite3_column_int(pLoop, 0);
7844    int bIntkey = sqlite3_column_int(pLoop, 1);
7845    int nCol = sqlite3_column_int(pLoop, 2);
7846    int bNoop = 0;
7847    RecoverTable *pTab;
7848
7849    assert( bIntkey==0 || bIntkey==1 );
7850    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7851    if( bNoop || rc ) continue;
7852    if( pTab==0 ){
7853      if( pOrphan==0 ){
7854        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7855      }
7856      pTab = pOrphan;
7857      if( pTab==0 ) break;
7858    }
7859
7860    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7861      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7862    }
7863    sqlite3_bind_int(pPages, 1, iRoot);
7864    if( bRowids==0 && pTab->iPk<0 ){
7865      sqlite3_bind_int(pCells, 1, 1);
7866    }else{
7867      sqlite3_bind_int(pCells, 1, 0);
7868    }
7869    sqlite3_bind_int(pCells, 3, pTab->iPk);
7870
7871    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7872      int iPgno = sqlite3_column_int(pPages, 0);
7873      sqlite3_bind_int(pCells, 2, iPgno);
7874      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7875        int nField = sqlite3_column_int(pCells, 0);
7876        int iMin = sqlite3_column_int(pCells, 2);
7877        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7878
7879        RecoverTable *pTab2 = pTab;
7880        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7881          if( pOrphan==0 ){
7882            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7883          }
7884          pTab2 = pOrphan;
7885          if( pTab2==0 ) break;
7886        }
7887
7888        nField = nField+1;
7889        if( pTab2==pOrphan ){
7890          raw_printf(pState->out,
7891              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7892              pTab2->zQuoted, iRoot, iPgno, nField,
7893              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7894          );
7895        }else{
7896          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7897              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7898          );
7899        }
7900      }
7901      shellReset(&rc, pCells);
7902    }
7903    shellReset(&rc, pPages);
7904    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7905  }
7906  shellFinalize(&rc, pLoop);
7907  shellFinalize(&rc, pPages);
7908  shellFinalize(&rc, pCells);
7909  recoverFreeTable(pOrphan);
7910
7911  /* The rest of the schema */
7912  if( rc==SQLITE_OK ){
7913    sqlite3_stmt *pStmt = 0;
7914    shellPrepare(pState->db, &rc,
7915        "SELECT sql, name FROM recovery.schema "
7916        "WHERE sql NOT LIKE 'create table%'", &pStmt
7917    );
7918    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7919      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7920      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7921        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7922        char *zPrint = shellMPrintf(&rc,
7923          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7924          zName, zName, zSql
7925        );
7926        raw_printf(pState->out, "%s;\n", zPrint);
7927        sqlite3_free(zPrint);
7928      }else{
7929        raw_printf(pState->out, "%s;\n", zSql);
7930      }
7931    }
7932    shellFinalize(&rc, pStmt);
7933  }
7934
7935  if( rc==SQLITE_OK ){
7936    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7937    raw_printf(pState->out, "COMMIT;\n");
7938  }
7939  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7940  return rc;
7941}
7942#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7943
7944
7945/*
7946 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7947 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7948 *   close db and set it to 0, and return the columns spec, to later
7949 *   be sqlite3_free()'ed by the caller.
7950 * The return is 0 when either:
7951 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7952 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7953 * The 3rd argument, pRenamed, references an out parameter. If the
7954 * pointer is non-zero, its referent will be set to a summary of renames
7955 * done if renaming was necessary, or set to 0 if none was done. The out
7956 * string (if any) must be sqlite3_free()'ed by the caller.
7957 */
7958#ifdef SHELL_DEBUG
7959#define rc_err_oom_die(rc) \
7960  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7961  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7962    fprintf(stderr,"E:%d\n",rc), assert(0)
7963#else
7964static void rc_err_oom_die(int rc){
7965  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7966  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7967}
7968#endif
7969
7970#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7971static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7972#else  /* Otherwise, memory is faster/better for the transient DB. */
7973static const char *zCOL_DB = ":memory:";
7974#endif
7975
7976/* Define character (as C string) to separate generated column ordinal
7977 * from protected part of incoming column names. This defaults to "_"
7978 * so that incoming column identifiers that did not need not be quoted
7979 * remain usable without being quoted. It must be one character.
7980 */
7981#ifndef SHELL_AUTOCOLUMN_SEP
7982# define AUTOCOLUMN_SEP "_"
7983#else
7984# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7985#endif
7986
7987static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7988  /* Queries and D{D,M}L used here */
7989  static const char * const zTabMake = "\
7990CREATE TABLE ColNames(\
7991 cpos INTEGER PRIMARY KEY,\
7992 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7993CREATE VIEW RepeatedNames AS \
7994SELECT DISTINCT t.name FROM ColNames t \
7995WHERE t.name COLLATE NOCASE IN (\
7996 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7997);\
7998";
7999  static const char * const zTabFill = "\
8000INSERT INTO ColNames(name,nlen,chop,reps,suff)\
8001 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
8002";
8003  static const char * const zHasDupes = "\
8004SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
8005 <count(name) FROM ColNames\
8006";
8007#ifdef SHELL_COLUMN_RENAME_CLEAN
8008  static const char * const zDedoctor = "\
8009UPDATE ColNames SET chop=iif(\
8010  (substring(name,nlen,1) BETWEEN '0' AND '9')\
8011  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
8012 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
8013 0\
8014)\
8015";
8016#endif
8017  static const char * const zSetReps = "\
8018UPDATE ColNames AS t SET reps=\
8019(SELECT count(*) FROM ColNames d \
8020 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
8021 COLLATE NOCASE\
8022)\
8023";
8024#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
8025  static const char * const zColDigits = "\
8026SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
8027";
8028#else
8029  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
8030  static const char * const zColDigits = "\
8031SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
8032 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
8033 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
8034";
8035#endif
8036  static const char * const zRenameRank =
8037#ifdef SHELL_COLUMN_RENAME_CLEAN
8038    "UPDATE ColNames AS t SET suff="
8039    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
8040#else /* ...RENAME_MINIMAL_ONE_PASS */
8041"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
8042"  SELECT 0 AS nlz"
8043"  UNION"
8044"  SELECT nlz+1 AS nlz FROM Lzn"
8045"  WHERE EXISTS("
8046"   SELECT 1"
8047"   FROM ColNames t, ColNames o"
8048"   WHERE"
8049"    iif(t.name IN (SELECT * FROM RepeatedNames),"
8050"     printf('%s"AUTOCOLUMN_SEP"%s',"
8051"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8052"     t.name"
8053"    )"
8054"    ="
8055"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8056"     printf('%s"AUTOCOLUMN_SEP"%s',"
8057"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8058"     o.name"
8059"    )"
8060"    COLLATE NOCASE"
8061"    AND o.cpos<>t.cpos"
8062"   GROUP BY t.cpos"
8063"  )"
8064") UPDATE Colnames AS t SET"
8065" chop = 0," /* No chopping, never touch incoming names. */
8066" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8067"  printf('"AUTOCOLUMN_SEP"%s', substring("
8068"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8069"  ''"
8070" )"
8071#endif
8072    ;
8073  static const char * const zCollectVar = "\
8074SELECT\
8075 '('||x'0a'\
8076 || group_concat(\
8077  cname||' TEXT',\
8078  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8079 ||')' AS ColsSpec \
8080FROM (\
8081 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8082 FROM ColNames ORDER BY cpos\
8083)";
8084  static const char * const zRenamesDone =
8085    "SELECT group_concat("
8086    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8087    " ','||x'0a')"
8088    "FROM ColNames WHERE suff<>'' OR chop!=0"
8089    ;
8090  int rc;
8091  sqlite3_stmt *pStmt = 0;
8092  assert(pDb!=0);
8093  if( zColNew ){
8094    /* Add initial or additional column. Init db if necessary. */
8095    if( *pDb==0 ){
8096      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8097#ifdef SHELL_COLFIX_DB
8098      if(*zCOL_DB!=':')
8099        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8100                     "drop view if exists RepeatedNames;",0,0,0);
8101#endif
8102      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8103      rc_err_oom_die(rc);
8104    }
8105    assert(*pDb!=0);
8106    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8107    rc_err_oom_die(rc);
8108    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8109    rc_err_oom_die(rc);
8110    rc = sqlite3_step(pStmt);
8111    rc_err_oom_die(rc);
8112    sqlite3_finalize(pStmt);
8113    return 0;
8114  }else if( *pDb==0 ){
8115    return 0;
8116  }else{
8117    /* Formulate the columns spec, close the DB, zero *pDb. */
8118    char *zColsSpec = 0;
8119    int hasDupes = db_int(*pDb, zHasDupes);
8120    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8121    if( hasDupes ){
8122#ifdef SHELL_COLUMN_RENAME_CLEAN
8123      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8124      rc_err_oom_die(rc);
8125#endif
8126      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8127      rc_err_oom_die(rc);
8128      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8129      rc_err_oom_die(rc);
8130      sqlite3_bind_int(pStmt, 1, nDigits);
8131      rc = sqlite3_step(pStmt);
8132      sqlite3_finalize(pStmt);
8133      assert(rc==SQLITE_DONE);
8134    }
8135    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8136    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8137    rc_err_oom_die(rc);
8138    rc = sqlite3_step(pStmt);
8139    if( rc==SQLITE_ROW ){
8140      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8141    }else{
8142      zColsSpec = 0;
8143    }
8144    if( pzRenamed!=0 ){
8145      if( !hasDupes ) *pzRenamed = 0;
8146      else{
8147        sqlite3_finalize(pStmt);
8148        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8149            && SQLITE_ROW==sqlite3_step(pStmt) ){
8150          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8151        }else
8152          *pzRenamed = 0;
8153      }
8154    }
8155    sqlite3_finalize(pStmt);
8156    sqlite3_close(*pDb);
8157    *pDb = 0;
8158    return zColsSpec;
8159  }
8160}
8161
8162/*
8163** If an input line begins with "." then invoke this routine to
8164** process that line.
8165**
8166** Return 1 on error, 2 to exit, and 0 otherwise.
8167*/
8168static int do_meta_command(char *zLine, ShellState *p){
8169  int h = 1;
8170  int nArg = 0;
8171  int n, c;
8172  int rc = 0;
8173  char *azArg[52];
8174
8175#ifndef SQLITE_OMIT_VIRTUALTABLE
8176  if( p->expert.pExpert ){
8177    expertFinish(p, 1, 0);
8178  }
8179#endif
8180
8181  /* Parse the input line into tokens.
8182  */
8183  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8184    while( IsSpace(zLine[h]) ){ h++; }
8185    if( zLine[h]==0 ) break;
8186    if( zLine[h]=='\'' || zLine[h]=='"' ){
8187      int delim = zLine[h++];
8188      azArg[nArg++] = &zLine[h];
8189      while( zLine[h] && zLine[h]!=delim ){
8190        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8191        h++;
8192      }
8193      if( zLine[h]==delim ){
8194        zLine[h++] = 0;
8195      }
8196      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8197    }else{
8198      azArg[nArg++] = &zLine[h];
8199      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8200      if( zLine[h] ) zLine[h++] = 0;
8201      resolve_backslashes(azArg[nArg-1]);
8202    }
8203  }
8204  azArg[nArg] = 0;
8205
8206  /* Process the input line.
8207  */
8208  if( nArg==0 ) return 0; /* no tokens, no error */
8209  n = strlen30(azArg[0]);
8210  c = azArg[0][0];
8211  clearTempFile(p);
8212
8213#ifndef SQLITE_OMIT_AUTHORIZATION
8214  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8215    if( nArg!=2 ){
8216      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8217      rc = 1;
8218      goto meta_command_exit;
8219    }
8220    open_db(p, 0);
8221    if( booleanValue(azArg[1]) ){
8222      sqlite3_set_authorizer(p->db, shellAuth, p);
8223    }else if( p->bSafeModePersist ){
8224      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8225    }else{
8226      sqlite3_set_authorizer(p->db, 0, 0);
8227    }
8228  }else
8229#endif
8230
8231#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8232  && !defined(SQLITE_SHELL_FIDDLE)
8233  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8234    open_db(p, 0);
8235    failIfSafeMode(p, "cannot run .archive in safe mode");
8236    rc = arDotCommand(p, 0, azArg, nArg);
8237  }else
8238#endif
8239
8240#ifndef SQLITE_SHELL_FIDDLE
8241  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8242   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8243  ){
8244    const char *zDestFile = 0;
8245    const char *zDb = 0;
8246    sqlite3 *pDest;
8247    sqlite3_backup *pBackup;
8248    int j;
8249    int bAsync = 0;
8250    const char *zVfs = 0;
8251    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8252    for(j=1; j<nArg; j++){
8253      const char *z = azArg[j];
8254      if( z[0]=='-' ){
8255        if( z[1]=='-' ) z++;
8256        if( strcmp(z, "-append")==0 ){
8257          zVfs = "apndvfs";
8258        }else
8259        if( strcmp(z, "-async")==0 ){
8260          bAsync = 1;
8261        }else
8262        {
8263          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8264          return 1;
8265        }
8266      }else if( zDestFile==0 ){
8267        zDestFile = azArg[j];
8268      }else if( zDb==0 ){
8269        zDb = zDestFile;
8270        zDestFile = azArg[j];
8271      }else{
8272        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8273        return 1;
8274      }
8275    }
8276    if( zDestFile==0 ){
8277      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8278      return 1;
8279    }
8280    if( zDb==0 ) zDb = "main";
8281    rc = sqlite3_open_v2(zDestFile, &pDest,
8282                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8283    if( rc!=SQLITE_OK ){
8284      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8285      close_db(pDest);
8286      return 1;
8287    }
8288    if( bAsync ){
8289      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8290                   0, 0, 0);
8291    }
8292    open_db(p, 0);
8293    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8294    if( pBackup==0 ){
8295      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8296      close_db(pDest);
8297      return 1;
8298    }
8299    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8300    sqlite3_backup_finish(pBackup);
8301    if( rc==SQLITE_DONE ){
8302      rc = 0;
8303    }else{
8304      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8305      rc = 1;
8306    }
8307    close_db(pDest);
8308  }else
8309#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8310
8311  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8312    if( nArg==2 ){
8313      bail_on_error = booleanValue(azArg[1]);
8314    }else{
8315      raw_printf(stderr, "Usage: .bail on|off\n");
8316      rc = 1;
8317    }
8318  }else
8319
8320  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8321    if( nArg==2 ){
8322      if( booleanValue(azArg[1]) ){
8323        setBinaryMode(p->out, 1);
8324      }else{
8325        setTextMode(p->out, 1);
8326      }
8327    }else{
8328      raw_printf(stderr, "Usage: .binary on|off\n");
8329      rc = 1;
8330    }
8331  }else
8332
8333  /* The undocumented ".breakpoint" command causes a call to the no-op
8334  ** routine named test_breakpoint().
8335  */
8336  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8337    test_breakpoint();
8338  }else
8339
8340#ifndef SQLITE_SHELL_FIDDLE
8341  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8342    failIfSafeMode(p, "cannot run .cd in safe mode");
8343    if( nArg==2 ){
8344#if defined(_WIN32) || defined(WIN32)
8345      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8346      rc = !SetCurrentDirectoryW(z);
8347      sqlite3_free(z);
8348#else
8349      rc = chdir(azArg[1]);
8350#endif
8351      if( rc ){
8352        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8353        rc = 1;
8354      }
8355    }else{
8356      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8357      rc = 1;
8358    }
8359  }else
8360#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8361
8362  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8363    if( nArg==2 ){
8364      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8365    }else{
8366      raw_printf(stderr, "Usage: .changes on|off\n");
8367      rc = 1;
8368    }
8369  }else
8370
8371#ifndef SQLITE_SHELL_FIDDLE
8372  /* Cancel output redirection, if it is currently set (by .testcase)
8373  ** Then read the content of the testcase-out.txt file and compare against
8374  ** azArg[1].  If there are differences, report an error and exit.
8375  */
8376  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8377    char *zRes = 0;
8378    output_reset(p);
8379    if( nArg!=2 ){
8380      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8381      rc = 2;
8382    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8383      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8384      rc = 2;
8385    }else if( testcase_glob(azArg[1],zRes)==0 ){
8386      utf8_printf(stderr,
8387                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8388                 p->zTestcase, azArg[1], zRes);
8389      rc = 1;
8390    }else{
8391      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8392      p->nCheck++;
8393    }
8394    sqlite3_free(zRes);
8395  }else
8396#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8397
8398#ifndef SQLITE_SHELL_FIDDLE
8399  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8400    failIfSafeMode(p, "cannot run .clone in safe mode");
8401    if( nArg==2 ){
8402      tryToClone(p, azArg[1]);
8403    }else{
8404      raw_printf(stderr, "Usage: .clone FILENAME\n");
8405      rc = 1;
8406    }
8407  }else
8408#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8409
8410  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8411    if( nArg==1 ){
8412      /* List available connections */
8413      int i;
8414      for(i=0; i<ArraySize(p->aAuxDb); i++){
8415        const char *zFile = p->aAuxDb[i].zDbFilename;
8416        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8417          zFile = "(not open)";
8418        }else if( zFile==0 ){
8419          zFile = "(memory)";
8420        }else if( zFile[0]==0 ){
8421          zFile = "(temporary-file)";
8422        }
8423        if( p->pAuxDb == &p->aAuxDb[i] ){
8424          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8425        }else if( p->aAuxDb[i].db!=0 ){
8426          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8427        }
8428      }
8429    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8430      int i = azArg[1][0] - '0';
8431      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8432        p->pAuxDb->db = p->db;
8433        p->pAuxDb = &p->aAuxDb[i];
8434        globalDb = p->db = p->pAuxDb->db;
8435        p->pAuxDb->db = 0;
8436      }
8437    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8438           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8439      int i = azArg[2][0] - '0';
8440      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8441        /* No-op */
8442      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8443        raw_printf(stderr, "cannot close the active database connection\n");
8444        rc = 1;
8445      }else if( p->aAuxDb[i].db ){
8446        session_close_all(p, i);
8447        close_db(p->aAuxDb[i].db);
8448        p->aAuxDb[i].db = 0;
8449      }
8450    }else{
8451      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8452      rc = 1;
8453    }
8454  }else
8455
8456  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8457    char **azName = 0;
8458    int nName = 0;
8459    sqlite3_stmt *pStmt;
8460    int i;
8461    open_db(p, 0);
8462    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8463    if( rc ){
8464      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8465      rc = 1;
8466    }else{
8467      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8468        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8469        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8470        if( zSchema==0 || zFile==0 ) continue;
8471        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8472        shell_check_oom(azName);
8473        azName[nName*2] = strdup(zSchema);
8474        azName[nName*2+1] = strdup(zFile);
8475        nName++;
8476      }
8477    }
8478    sqlite3_finalize(pStmt);
8479    for(i=0; i<nName; i++){
8480      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8481      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8482      const char *z = azName[i*2+1];
8483      utf8_printf(p->out, "%s: %s %s%s\n",
8484         azName[i*2],
8485         z && z[0] ? z : "\"\"",
8486         bRdonly ? "r/o" : "r/w",
8487         eTxn==SQLITE_TXN_NONE ? "" :
8488            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8489      free(azName[i*2]);
8490      free(azName[i*2+1]);
8491    }
8492    sqlite3_free(azName);
8493  }else
8494
8495  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8496    static const struct DbConfigChoices {
8497      const char *zName;
8498      int op;
8499    } aDbConfig[] = {
8500        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8501        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8502        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8503        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8504        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8505        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8506        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8507        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8508        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8509        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8510        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8511        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8512        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8513        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8514        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8515        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8516    };
8517    int ii, v;
8518    open_db(p, 0);
8519    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8520      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8521      if( nArg>=3 ){
8522        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8523      }
8524      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8525      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8526      if( nArg>1 ) break;
8527    }
8528    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8529      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8530      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8531    }
8532  }else
8533
8534#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8535  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8536    rc = shell_dbinfo_command(p, nArg, azArg);
8537  }else
8538
8539  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8540    open_db(p, 0);
8541    rc = recoverDatabaseCmd(p, nArg, azArg);
8542  }else
8543#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8544
8545  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8546    char *zLike = 0;
8547    char *zSql;
8548    int i;
8549    int savedShowHeader = p->showHeader;
8550    int savedShellFlags = p->shellFlgs;
8551    ShellClearFlag(p,
8552       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8553       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8554    for(i=1; i<nArg; i++){
8555      if( azArg[i][0]=='-' ){
8556        const char *z = azArg[i]+1;
8557        if( z[0]=='-' ) z++;
8558        if( strcmp(z,"preserve-rowids")==0 ){
8559#ifdef SQLITE_OMIT_VIRTUALTABLE
8560          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8561                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8562          rc = 1;
8563          sqlite3_free(zLike);
8564          goto meta_command_exit;
8565#else
8566          ShellSetFlag(p, SHFLG_PreserveRowid);
8567#endif
8568        }else
8569        if( strcmp(z,"newlines")==0 ){
8570          ShellSetFlag(p, SHFLG_Newlines);
8571        }else
8572        if( strcmp(z,"data-only")==0 ){
8573          ShellSetFlag(p, SHFLG_DumpDataOnly);
8574        }else
8575        if( strcmp(z,"nosys")==0 ){
8576          ShellSetFlag(p, SHFLG_DumpNoSys);
8577        }else
8578        {
8579          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8580          rc = 1;
8581          sqlite3_free(zLike);
8582          goto meta_command_exit;
8583        }
8584      }else{
8585        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8586        ** only dump data for tables for which either the table name matches
8587        ** the LIKE pattern, or the table appears to be a shadow table of
8588        ** a virtual table for which the name matches the LIKE pattern.
8589        */
8590        char *zExpr = sqlite3_mprintf(
8591            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8592            "  SELECT 1 FROM sqlite_schema WHERE "
8593            "    name LIKE %Q ESCAPE '\\' AND"
8594            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8595            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8596            ")", azArg[i], azArg[i]
8597        );
8598
8599        if( zLike ){
8600          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8601        }else{
8602          zLike = zExpr;
8603        }
8604      }
8605    }
8606
8607    open_db(p, 0);
8608
8609    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8610      /* When playing back a "dump", the content might appear in an order
8611      ** which causes immediate foreign key constraints to be violated.
8612      ** So disable foreign-key constraint enforcement to prevent problems. */
8613      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8614      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8615    }
8616    p->writableSchema = 0;
8617    p->showHeader = 0;
8618    /* Set writable_schema=ON since doing so forces SQLite to initialize
8619    ** as much of the schema as it can even if the sqlite_schema table is
8620    ** corrupt. */
8621    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8622    p->nErr = 0;
8623    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8624    zSql = sqlite3_mprintf(
8625      "SELECT name, type, sql FROM sqlite_schema AS o "
8626      "WHERE (%s) AND type=='table'"
8627      "  AND sql NOT NULL"
8628      " ORDER BY tbl_name='sqlite_sequence', rowid",
8629      zLike
8630    );
8631    run_schema_dump_query(p,zSql);
8632    sqlite3_free(zSql);
8633    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8634      zSql = sqlite3_mprintf(
8635        "SELECT sql FROM sqlite_schema AS o "
8636        "WHERE (%s) AND sql NOT NULL"
8637        "  AND type IN ('index','trigger','view')",
8638        zLike
8639      );
8640      run_table_dump_query(p, zSql);
8641      sqlite3_free(zSql);
8642    }
8643    sqlite3_free(zLike);
8644    if( p->writableSchema ){
8645      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8646      p->writableSchema = 0;
8647    }
8648    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8649    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8650    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8651      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8652    }
8653    p->showHeader = savedShowHeader;
8654    p->shellFlgs = savedShellFlags;
8655  }else
8656
8657  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8658    if( nArg==2 ){
8659      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8660    }else{
8661      raw_printf(stderr, "Usage: .echo on|off\n");
8662      rc = 1;
8663    }
8664  }else
8665
8666  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8667    if( nArg==2 ){
8668      p->autoEQPtest = 0;
8669      if( p->autoEQPtrace ){
8670        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8671        p->autoEQPtrace = 0;
8672      }
8673      if( strcmp(azArg[1],"full")==0 ){
8674        p->autoEQP = AUTOEQP_full;
8675      }else if( strcmp(azArg[1],"trigger")==0 ){
8676        p->autoEQP = AUTOEQP_trigger;
8677#ifdef SQLITE_DEBUG
8678      }else if( strcmp(azArg[1],"test")==0 ){
8679        p->autoEQP = AUTOEQP_on;
8680        p->autoEQPtest = 1;
8681      }else if( strcmp(azArg[1],"trace")==0 ){
8682        p->autoEQP = AUTOEQP_full;
8683        p->autoEQPtrace = 1;
8684        open_db(p, 0);
8685        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8686        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8687#endif
8688      }else{
8689        p->autoEQP = (u8)booleanValue(azArg[1]);
8690      }
8691    }else{
8692      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8693      rc = 1;
8694    }
8695  }else
8696
8697#ifndef SQLITE_SHELL_FIDDLE
8698  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8699    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8700    rc = 2;
8701  }else
8702#endif
8703
8704  /* The ".explain" command is automatic now.  It is largely pointless.  It
8705  ** retained purely for backwards compatibility */
8706  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8707    int val = 1;
8708    if( nArg>=2 ){
8709      if( strcmp(azArg[1],"auto")==0 ){
8710        val = 99;
8711      }else{
8712        val =  booleanValue(azArg[1]);
8713      }
8714    }
8715    if( val==1 && p->mode!=MODE_Explain ){
8716      p->normalMode = p->mode;
8717      p->mode = MODE_Explain;
8718      p->autoExplain = 0;
8719    }else if( val==0 ){
8720      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8721      p->autoExplain = 0;
8722    }else if( val==99 ){
8723      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8724      p->autoExplain = 1;
8725    }
8726  }else
8727
8728#ifndef SQLITE_OMIT_VIRTUALTABLE
8729  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8730    if( p->bSafeMode ){
8731      raw_printf(stderr,
8732        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8733        azArg[0]);
8734      rc = 1;
8735    }else{
8736      open_db(p, 0);
8737      expertDotCommand(p, azArg, nArg);
8738    }
8739  }else
8740#endif
8741
8742  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8743    static const struct {
8744       const char *zCtrlName;   /* Name of a test-control option */
8745       int ctrlCode;            /* Integer code for that option */
8746       const char *zUsage;      /* Usage notes */
8747    } aCtrl[] = {
8748      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8749      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8750      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8751      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8752      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8753   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8754      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8755      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8756      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8757      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8758   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8759    };
8760    int filectrl = -1;
8761    int iCtrl = -1;
8762    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8763    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8764    int n2, i;
8765    const char *zCmd = 0;
8766    const char *zSchema = 0;
8767
8768    open_db(p, 0);
8769    zCmd = nArg>=2 ? azArg[1] : "help";
8770
8771    if( zCmd[0]=='-'
8772     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8773     && nArg>=4
8774    ){
8775      zSchema = azArg[2];
8776      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8777      nArg -= 2;
8778      zCmd = azArg[1];
8779    }
8780
8781    /* The argument can optionally begin with "-" or "--" */
8782    if( zCmd[0]=='-' && zCmd[1] ){
8783      zCmd++;
8784      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8785    }
8786
8787    /* --help lists all file-controls */
8788    if( strcmp(zCmd,"help")==0 ){
8789      utf8_printf(p->out, "Available file-controls:\n");
8790      for(i=0; i<ArraySize(aCtrl); i++){
8791        utf8_printf(p->out, "  .filectrl %s %s\n",
8792                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8793      }
8794      rc = 1;
8795      goto meta_command_exit;
8796    }
8797
8798    /* convert filectrl text option to value. allow any unique prefix
8799    ** of the option name, or a numerical value. */
8800    n2 = strlen30(zCmd);
8801    for(i=0; i<ArraySize(aCtrl); i++){
8802      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8803        if( filectrl<0 ){
8804          filectrl = aCtrl[i].ctrlCode;
8805          iCtrl = i;
8806        }else{
8807          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8808                              "Use \".filectrl --help\" for help\n", zCmd);
8809          rc = 1;
8810          goto meta_command_exit;
8811        }
8812      }
8813    }
8814    if( filectrl<0 ){
8815      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8816                         "Use \".filectrl --help\" for help\n", zCmd);
8817    }else{
8818      switch(filectrl){
8819        case SQLITE_FCNTL_SIZE_LIMIT: {
8820          if( nArg!=2 && nArg!=3 ) break;
8821          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8822          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8823          isOk = 1;
8824          break;
8825        }
8826        case SQLITE_FCNTL_LOCK_TIMEOUT:
8827        case SQLITE_FCNTL_CHUNK_SIZE: {
8828          int x;
8829          if( nArg!=3 ) break;
8830          x = (int)integerValue(azArg[2]);
8831          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8832          isOk = 2;
8833          break;
8834        }
8835        case SQLITE_FCNTL_PERSIST_WAL:
8836        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8837          int x;
8838          if( nArg!=2 && nArg!=3 ) break;
8839          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8840          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8841          iRes = x;
8842          isOk = 1;
8843          break;
8844        }
8845        case SQLITE_FCNTL_DATA_VERSION:
8846        case SQLITE_FCNTL_HAS_MOVED: {
8847          int x;
8848          if( nArg!=2 ) break;
8849          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8850          iRes = x;
8851          isOk = 1;
8852          break;
8853        }
8854        case SQLITE_FCNTL_TEMPFILENAME: {
8855          char *z = 0;
8856          if( nArg!=2 ) break;
8857          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8858          if( z ){
8859            utf8_printf(p->out, "%s\n", z);
8860            sqlite3_free(z);
8861          }
8862          isOk = 2;
8863          break;
8864        }
8865        case SQLITE_FCNTL_RESERVE_BYTES: {
8866          int x;
8867          if( nArg>=3 ){
8868            x = atoi(azArg[2]);
8869            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8870          }
8871          x = -1;
8872          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8873          utf8_printf(p->out,"%d\n", x);
8874          isOk = 2;
8875          break;
8876        }
8877      }
8878    }
8879    if( isOk==0 && iCtrl>=0 ){
8880      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8881      rc = 1;
8882    }else if( isOk==1 ){
8883      char zBuf[100];
8884      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8885      raw_printf(p->out, "%s\n", zBuf);
8886    }
8887  }else
8888
8889  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8890    ShellState data;
8891    int doStats = 0;
8892    memcpy(&data, p, sizeof(data));
8893    data.showHeader = 0;
8894    data.cMode = data.mode = MODE_Semi;
8895    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8896      data.cMode = data.mode = MODE_Pretty;
8897      nArg = 1;
8898    }
8899    if( nArg!=1 ){
8900      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8901      rc = 1;
8902      goto meta_command_exit;
8903    }
8904    open_db(p, 0);
8905    rc = sqlite3_exec(p->db,
8906       "SELECT sql FROM"
8907       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8908       "     FROM sqlite_schema UNION ALL"
8909       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8910       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8911       "ORDER BY x",
8912       callback, &data, 0
8913    );
8914    if( rc==SQLITE_OK ){
8915      sqlite3_stmt *pStmt;
8916      rc = sqlite3_prepare_v2(p->db,
8917               "SELECT rowid FROM sqlite_schema"
8918               " WHERE name GLOB 'sqlite_stat[134]'",
8919               -1, &pStmt, 0);
8920      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8921      sqlite3_finalize(pStmt);
8922    }
8923    if( doStats==0 ){
8924      raw_printf(p->out, "/* No STAT tables available */\n");
8925    }else{
8926      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8927      data.cMode = data.mode = MODE_Insert;
8928      data.zDestTable = "sqlite_stat1";
8929      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8930      data.zDestTable = "sqlite_stat4";
8931      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8932      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8933    }
8934  }else
8935
8936  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8937    if( nArg==2 ){
8938      p->showHeader = booleanValue(azArg[1]);
8939      p->shellFlgs |= SHFLG_HeaderSet;
8940    }else{
8941      raw_printf(stderr, "Usage: .headers on|off\n");
8942      rc = 1;
8943    }
8944  }else
8945
8946  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8947    if( nArg>=2 ){
8948      n = showHelp(p->out, azArg[1]);
8949      if( n==0 ){
8950        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8951      }
8952    }else{
8953      showHelp(p->out, 0);
8954    }
8955  }else
8956
8957#ifndef SQLITE_SHELL_FIDDLE
8958  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8959    char *zTable = 0;           /* Insert data into this table */
8960    char *zSchema = 0;          /* within this schema (may default to "main") */
8961    char *zFile = 0;            /* Name of file to extra content from */
8962    sqlite3_stmt *pStmt = NULL; /* A statement */
8963    int nCol;                   /* Number of columns in the table */
8964    int nByte;                  /* Number of bytes in an SQL string */
8965    int i, j;                   /* Loop counters */
8966    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8967    int nSep;                   /* Number of bytes in p->colSeparator[] */
8968    char *zSql;                 /* An SQL statement */
8969    char *zFullTabName;         /* Table name with schema if applicable */
8970    ImportCtx sCtx;             /* Reader context */
8971    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8972    int eVerbose = 0;           /* Larger for more console output */
8973    int nSkip = 0;              /* Initial lines to skip */
8974    int useOutputMode = 1;      /* Use output mode to determine separators */
8975    char *zCreate = 0;          /* CREATE TABLE statement text */
8976
8977    failIfSafeMode(p, "cannot run .import in safe mode");
8978    memset(&sCtx, 0, sizeof(sCtx));
8979    if( p->mode==MODE_Ascii ){
8980      xRead = ascii_read_one_field;
8981    }else{
8982      xRead = csv_read_one_field;
8983    }
8984    rc = 1;
8985    for(i=1; i<nArg; i++){
8986      char *z = azArg[i];
8987      if( z[0]=='-' && z[1]=='-' ) z++;
8988      if( z[0]!='-' ){
8989        if( zFile==0 ){
8990          zFile = z;
8991        }else if( zTable==0 ){
8992          zTable = z;
8993        }else{
8994          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8995          showHelp(p->out, "import");
8996          goto meta_command_exit;
8997        }
8998      }else if( strcmp(z,"-v")==0 ){
8999        eVerbose++;
9000      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
9001        zSchema = azArg[++i];
9002      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
9003        nSkip = integerValue(azArg[++i]);
9004      }else if( strcmp(z,"-ascii")==0 ){
9005        sCtx.cColSep = SEP_Unit[0];
9006        sCtx.cRowSep = SEP_Record[0];
9007        xRead = ascii_read_one_field;
9008        useOutputMode = 0;
9009      }else if( strcmp(z,"-csv")==0 ){
9010        sCtx.cColSep = ',';
9011        sCtx.cRowSep = '\n';
9012        xRead = csv_read_one_field;
9013        useOutputMode = 0;
9014      }else{
9015        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
9016        showHelp(p->out, "import");
9017        goto meta_command_exit;
9018      }
9019    }
9020    if( zTable==0 ){
9021      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
9022                  zFile==0 ? "FILE" : "TABLE");
9023      showHelp(p->out, "import");
9024      goto meta_command_exit;
9025    }
9026    seenInterrupt = 0;
9027    open_db(p, 0);
9028    if( useOutputMode ){
9029      /* If neither the --csv or --ascii options are specified, then set
9030      ** the column and row separator characters from the output mode. */
9031      nSep = strlen30(p->colSeparator);
9032      if( nSep==0 ){
9033        raw_printf(stderr,
9034                   "Error: non-null column separator required for import\n");
9035        goto meta_command_exit;
9036      }
9037      if( nSep>1 ){
9038        raw_printf(stderr,
9039              "Error: multi-character column separators not allowed"
9040              " for import\n");
9041        goto meta_command_exit;
9042      }
9043      nSep = strlen30(p->rowSeparator);
9044      if( nSep==0 ){
9045        raw_printf(stderr,
9046            "Error: non-null row separator required for import\n");
9047        goto meta_command_exit;
9048      }
9049      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9050        /* When importing CSV (only), if the row separator is set to the
9051        ** default output row separator, change it to the default input
9052        ** row separator.  This avoids having to maintain different input
9053        ** and output row separators. */
9054        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9055        nSep = strlen30(p->rowSeparator);
9056      }
9057      if( nSep>1 ){
9058        raw_printf(stderr, "Error: multi-character row separators not allowed"
9059                           " for import\n");
9060        goto meta_command_exit;
9061      }
9062      sCtx.cColSep = p->colSeparator[0];
9063      sCtx.cRowSep = p->rowSeparator[0];
9064    }
9065    sCtx.zFile = zFile;
9066    sCtx.nLine = 1;
9067    if( sCtx.zFile[0]=='|' ){
9068#ifdef SQLITE_OMIT_POPEN
9069      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9070      goto meta_command_exit;
9071#else
9072      sCtx.in = popen(sCtx.zFile+1, "r");
9073      sCtx.zFile = "<pipe>";
9074      sCtx.xCloser = pclose;
9075#endif
9076    }else{
9077      sCtx.in = fopen(sCtx.zFile, "rb");
9078      sCtx.xCloser = fclose;
9079    }
9080    if( sCtx.in==0 ){
9081      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9082      goto meta_command_exit;
9083    }
9084    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9085      char zSep[2];
9086      zSep[1] = 0;
9087      zSep[0] = sCtx.cColSep;
9088      utf8_printf(p->out, "Column separator ");
9089      output_c_string(p->out, zSep);
9090      utf8_printf(p->out, ", row separator ");
9091      zSep[0] = sCtx.cRowSep;
9092      output_c_string(p->out, zSep);
9093      utf8_printf(p->out, "\n");
9094    }
9095    sCtx.z = sqlite3_malloc64(120);
9096    if( sCtx.z==0 ){
9097      import_cleanup(&sCtx);
9098      shell_out_of_memory();
9099    }
9100    /* Below, resources must be freed before exit. */
9101    while( (nSkip--)>0 ){
9102      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9103    }
9104    if( zSchema!=0 ){
9105      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9106    }else{
9107      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9108    }
9109    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9110    if( zSql==0 || zFullTabName==0 ){
9111      import_cleanup(&sCtx);
9112      shell_out_of_memory();
9113    }
9114    nByte = strlen30(zSql);
9115    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9116    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9117    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9118      sqlite3 *dbCols = 0;
9119      char *zRenames = 0;
9120      char *zColDefs;
9121      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9122      while( xRead(&sCtx) ){
9123        zAutoColumn(sCtx.z, &dbCols, 0);
9124        if( sCtx.cTerm!=sCtx.cColSep ) break;
9125      }
9126      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9127      if( zRenames!=0 ){
9128        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9129                    "Columns renamed during .import %s due to duplicates:\n"
9130                    "%s\n", sCtx.zFile, zRenames);
9131        sqlite3_free(zRenames);
9132      }
9133      assert(dbCols==0);
9134      if( zColDefs==0 ){
9135        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9136      import_fail:
9137        sqlite3_free(zCreate);
9138        sqlite3_free(zSql);
9139        sqlite3_free(zFullTabName);
9140        import_cleanup(&sCtx);
9141        rc = 1;
9142        goto meta_command_exit;
9143      }
9144      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9145      if( eVerbose>=1 ){
9146        utf8_printf(p->out, "%s\n", zCreate);
9147      }
9148      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9149      if( rc ){
9150        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9151        goto import_fail;
9152      }
9153      sqlite3_free(zCreate);
9154      zCreate = 0;
9155      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9156    }
9157    if( rc ){
9158      if (pStmt) sqlite3_finalize(pStmt);
9159      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9160      goto import_fail;
9161    }
9162    sqlite3_free(zSql);
9163    nCol = sqlite3_column_count(pStmt);
9164    sqlite3_finalize(pStmt);
9165    pStmt = 0;
9166    if( nCol==0 ) return 0; /* no columns, no error */
9167    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9168    if( zSql==0 ){
9169      import_cleanup(&sCtx);
9170      shell_out_of_memory();
9171    }
9172    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9173    j = strlen30(zSql);
9174    for(i=1; i<nCol; i++){
9175      zSql[j++] = ',';
9176      zSql[j++] = '?';
9177    }
9178    zSql[j++] = ')';
9179    zSql[j] = 0;
9180    if( eVerbose>=2 ){
9181      utf8_printf(p->out, "Insert using: %s\n", zSql);
9182    }
9183    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9184    if( rc ){
9185      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9186      if (pStmt) sqlite3_finalize(pStmt);
9187      goto import_fail;
9188    }
9189    sqlite3_free(zSql);
9190    sqlite3_free(zFullTabName);
9191    needCommit = sqlite3_get_autocommit(p->db);
9192    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9193    do{
9194      int startLine = sCtx.nLine;
9195      for(i=0; i<nCol; i++){
9196        char *z = xRead(&sCtx);
9197        /*
9198        ** Did we reach end-of-file before finding any columns?
9199        ** If so, stop instead of NULL filling the remaining columns.
9200        */
9201        if( z==0 && i==0 ) break;
9202        /*
9203        ** Did we reach end-of-file OR end-of-line before finding any
9204        ** columns in ASCII mode?  If so, stop instead of NULL filling
9205        ** the remaining columns.
9206        */
9207        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9208        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9209        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9210          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9211                          "filling the rest with NULL\n",
9212                          sCtx.zFile, startLine, nCol, i+1);
9213          i += 2;
9214          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9215        }
9216      }
9217      if( sCtx.cTerm==sCtx.cColSep ){
9218        do{
9219          xRead(&sCtx);
9220          i++;
9221        }while( sCtx.cTerm==sCtx.cColSep );
9222        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9223                        "extras ignored\n",
9224                        sCtx.zFile, startLine, nCol, i);
9225      }
9226      if( i>=nCol ){
9227        sqlite3_step(pStmt);
9228        rc = sqlite3_reset(pStmt);
9229        if( rc!=SQLITE_OK ){
9230          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9231                      startLine, sqlite3_errmsg(p->db));
9232          sCtx.nErr++;
9233        }else{
9234          sCtx.nRow++;
9235        }
9236      }
9237    }while( sCtx.cTerm!=EOF );
9238
9239    import_cleanup(&sCtx);
9240    sqlite3_finalize(pStmt);
9241    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9242    if( eVerbose>0 ){
9243      utf8_printf(p->out,
9244          "Added %d rows with %d errors using %d lines of input\n",
9245          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9246    }
9247  }else
9248#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9249
9250#ifndef SQLITE_UNTESTABLE
9251  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9252    char *zSql;
9253    char *zCollist = 0;
9254    sqlite3_stmt *pStmt;
9255    int tnum = 0;
9256    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9257    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9258    int i;
9259    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9260      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9261                          "       .imposter off\n");
9262      /* Also allowed, but not documented:
9263      **
9264      **    .imposter TABLE IMPOSTER
9265      **
9266      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9267      ** imposter is another WITHOUT ROWID table with the columns in
9268      ** storage order. */
9269      rc = 1;
9270      goto meta_command_exit;
9271    }
9272    open_db(p, 0);
9273    if( nArg==2 ){
9274      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9275      goto meta_command_exit;
9276    }
9277    zSql = sqlite3_mprintf(
9278      "SELECT rootpage, 0 FROM sqlite_schema"
9279      " WHERE name='%q' AND type='index'"
9280      "UNION ALL "
9281      "SELECT rootpage, 1 FROM sqlite_schema"
9282      " WHERE name='%q' AND type='table'"
9283      "   AND sql LIKE '%%without%%rowid%%'",
9284      azArg[1], azArg[1]
9285    );
9286    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9287    sqlite3_free(zSql);
9288    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9289      tnum = sqlite3_column_int(pStmt, 0);
9290      isWO = sqlite3_column_int(pStmt, 1);
9291    }
9292    sqlite3_finalize(pStmt);
9293    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9294    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9295    sqlite3_free(zSql);
9296    i = 0;
9297    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9298      char zLabel[20];
9299      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9300      i++;
9301      if( zCol==0 ){
9302        if( sqlite3_column_int(pStmt,1)==-1 ){
9303          zCol = "_ROWID_";
9304        }else{
9305          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9306          zCol = zLabel;
9307        }
9308      }
9309      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9310        lenPK = (int)strlen(zCollist);
9311      }
9312      if( zCollist==0 ){
9313        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9314      }else{
9315        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9316      }
9317    }
9318    sqlite3_finalize(pStmt);
9319    if( i==0 || tnum==0 ){
9320      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9321      rc = 1;
9322      sqlite3_free(zCollist);
9323      goto meta_command_exit;
9324    }
9325    if( lenPK==0 ) lenPK = 100000;
9326    zSql = sqlite3_mprintf(
9327          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9328          azArg[2], zCollist, lenPK, zCollist);
9329    sqlite3_free(zCollist);
9330    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9331    if( rc==SQLITE_OK ){
9332      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9333      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9334      if( rc ){
9335        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9336      }else{
9337        utf8_printf(stdout, "%s;\n", zSql);
9338        raw_printf(stdout,
9339          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9340          azArg[1], isWO ? "table" : "index"
9341        );
9342      }
9343    }else{
9344      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9345      rc = 1;
9346    }
9347    sqlite3_free(zSql);
9348  }else
9349#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9350
9351#ifdef SQLITE_ENABLE_IOTRACE
9352  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9353    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9354    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9355    iotrace = 0;
9356    if( nArg<2 ){
9357      sqlite3IoTrace = 0;
9358    }else if( strcmp(azArg[1], "-")==0 ){
9359      sqlite3IoTrace = iotracePrintf;
9360      iotrace = stdout;
9361    }else{
9362      iotrace = fopen(azArg[1], "w");
9363      if( iotrace==0 ){
9364        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9365        sqlite3IoTrace = 0;
9366        rc = 1;
9367      }else{
9368        sqlite3IoTrace = iotracePrintf;
9369      }
9370    }
9371  }else
9372#endif
9373
9374  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9375    static const struct {
9376       const char *zLimitName;   /* Name of a limit */
9377       int limitCode;            /* Integer code for that limit */
9378    } aLimit[] = {
9379      { "length",                SQLITE_LIMIT_LENGTH                    },
9380      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9381      { "column",                SQLITE_LIMIT_COLUMN                    },
9382      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9383      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9384      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9385      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9386      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9387      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9388      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9389      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9390      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9391    };
9392    int i, n2;
9393    open_db(p, 0);
9394    if( nArg==1 ){
9395      for(i=0; i<ArraySize(aLimit); i++){
9396        printf("%20s %d\n", aLimit[i].zLimitName,
9397               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9398      }
9399    }else if( nArg>3 ){
9400      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9401      rc = 1;
9402      goto meta_command_exit;
9403    }else{
9404      int iLimit = -1;
9405      n2 = strlen30(azArg[1]);
9406      for(i=0; i<ArraySize(aLimit); i++){
9407        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9408          if( iLimit<0 ){
9409            iLimit = i;
9410          }else{
9411            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9412            rc = 1;
9413            goto meta_command_exit;
9414          }
9415        }
9416      }
9417      if( iLimit<0 ){
9418        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9419                        "enter \".limits\" with no arguments for a list.\n",
9420                         azArg[1]);
9421        rc = 1;
9422        goto meta_command_exit;
9423      }
9424      if( nArg==3 ){
9425        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9426                      (int)integerValue(azArg[2]));
9427      }
9428      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9429             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9430    }
9431  }else
9432
9433  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9434    open_db(p, 0);
9435    lintDotCommand(p, azArg, nArg);
9436  }else
9437
9438#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9439  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9440    const char *zFile, *zProc;
9441    char *zErrMsg = 0;
9442    failIfSafeMode(p, "cannot run .load in safe mode");
9443    if( nArg<2 ){
9444      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9445      rc = 1;
9446      goto meta_command_exit;
9447    }
9448    zFile = azArg[1];
9449    zProc = nArg>=3 ? azArg[2] : 0;
9450    open_db(p, 0);
9451    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9452    if( rc!=SQLITE_OK ){
9453      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9454      sqlite3_free(zErrMsg);
9455      rc = 1;
9456    }
9457  }else
9458#endif
9459
9460#ifndef SQLITE_SHELL_FIDDLE
9461  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9462    failIfSafeMode(p, "cannot run .log in safe mode");
9463    if( nArg!=2 ){
9464      raw_printf(stderr, "Usage: .log FILENAME\n");
9465      rc = 1;
9466    }else{
9467      const char *zFile = azArg[1];
9468      output_file_close(p->pLog);
9469      p->pLog = output_file_open(zFile, 0);
9470    }
9471  }else
9472#endif
9473
9474  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9475    const char *zMode = 0;
9476    const char *zTabname = 0;
9477    int i, n2;
9478    ColModeOpts cmOpts = ColModeOpts_default;
9479    for(i=1; i<nArg; i++){
9480      const char *z = azArg[i];
9481      if( optionMatch(z,"wrap") && i+1<nArg ){
9482        cmOpts.iWrap = integerValue(azArg[++i]);
9483      }else if( optionMatch(z,"ww") ){
9484        cmOpts.bWordWrap = 1;
9485      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9486        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9487      }else if( optionMatch(z,"quote") ){
9488        cmOpts.bQuote = 1;
9489      }else if( optionMatch(z,"noquote") ){
9490        cmOpts.bQuote = 0;
9491      }else if( zMode==0 ){
9492        zMode = z;
9493        /* Apply defaults for qbox pseudo-mods. If that
9494         * overwrites already-set values, user was informed of this.
9495         */
9496        if( strcmp(z, "qbox")==0 ){
9497          ColModeOpts cmo = ColModeOpts_default_qbox;
9498          zMode = "box";
9499          cmOpts = cmo;
9500        }
9501      }else if( zTabname==0 ){
9502        zTabname = z;
9503      }else if( z[0]=='-' ){
9504        utf8_printf(stderr, "unknown option: %s\n", z);
9505        utf8_printf(stderr, "options:\n"
9506                            "  --noquote\n"
9507                            "  --quote\n"
9508                            "  --wordwrap on/off\n"
9509                            "  --wrap N\n"
9510                            "  --ww\n");
9511        rc = 1;
9512        goto meta_command_exit;
9513      }else{
9514        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9515        rc = 1;
9516        goto meta_command_exit;
9517      }
9518    }
9519    if( zMode==0 ){
9520      if( p->mode==MODE_Column
9521       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9522      ){
9523        raw_printf
9524          (p->out,
9525           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9526           modeDescr[p->mode], p->cmOpts.iWrap,
9527           p->cmOpts.bWordWrap ? "on" : "off",
9528           p->cmOpts.bQuote ? "" : "no");
9529      }else{
9530        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9531      }
9532      zMode = modeDescr[p->mode];
9533    }
9534    n2 = strlen30(zMode);
9535    if( strncmp(zMode,"lines",n2)==0 ){
9536      p->mode = MODE_Line;
9537      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9538    }else if( strncmp(zMode,"columns",n2)==0 ){
9539      p->mode = MODE_Column;
9540      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9541        p->showHeader = 1;
9542      }
9543      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9544      p->cmOpts = cmOpts;
9545    }else if( strncmp(zMode,"list",n2)==0 ){
9546      p->mode = MODE_List;
9547      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9548      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9549    }else if( strncmp(zMode,"html",n2)==0 ){
9550      p->mode = MODE_Html;
9551    }else if( strncmp(zMode,"tcl",n2)==0 ){
9552      p->mode = MODE_Tcl;
9553      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9554      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9555    }else if( strncmp(zMode,"csv",n2)==0 ){
9556      p->mode = MODE_Csv;
9557      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9558      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9559    }else if( strncmp(zMode,"tabs",n2)==0 ){
9560      p->mode = MODE_List;
9561      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9562    }else if( strncmp(zMode,"insert",n2)==0 ){
9563      p->mode = MODE_Insert;
9564      set_table_name(p, zTabname ? zTabname : "table");
9565    }else if( strncmp(zMode,"quote",n2)==0 ){
9566      p->mode = MODE_Quote;
9567      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9568      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9569    }else if( strncmp(zMode,"ascii",n2)==0 ){
9570      p->mode = MODE_Ascii;
9571      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9572      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9573    }else if( strncmp(zMode,"markdown",n2)==0 ){
9574      p->mode = MODE_Markdown;
9575      p->cmOpts = cmOpts;
9576    }else if( strncmp(zMode,"table",n2)==0 ){
9577      p->mode = MODE_Table;
9578      p->cmOpts = cmOpts;
9579    }else if( strncmp(zMode,"box",n2)==0 ){
9580      p->mode = MODE_Box;
9581      p->cmOpts = cmOpts;
9582    }else if( strncmp(zMode,"count",n2)==0 ){
9583      p->mode = MODE_Count;
9584    }else if( strncmp(zMode,"off",n2)==0 ){
9585      p->mode = MODE_Off;
9586    }else if( strncmp(zMode,"json",n2)==0 ){
9587      p->mode = MODE_Json;
9588    }else{
9589      raw_printf(stderr, "Error: mode should be one of: "
9590         "ascii box column csv html insert json line list markdown "
9591         "qbox quote table tabs tcl\n");
9592      rc = 1;
9593    }
9594    p->cMode = p->mode;
9595  }else
9596
9597#ifndef SQLITE_SHELL_FIDDLE
9598  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9599    if( nArg!=2 ){
9600      raw_printf(stderr, "Usage: .nonce NONCE\n");
9601      rc = 1;
9602    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9603      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9604                 p->lineno, azArg[1]);
9605      exit(1);
9606    }else{
9607      p->bSafeMode = 0;
9608      return 0;  /* Return immediately to bypass the safe mode reset
9609                 ** at the end of this procedure */
9610    }
9611  }else
9612#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9613
9614  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9615    if( nArg==2 ){
9616      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9617                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9618    }else{
9619      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9620      rc = 1;
9621    }
9622  }else
9623
9624  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9625    const char *zFN = 0;     /* Pointer to constant filename */
9626    char *zNewFilename = 0;  /* Name of the database file to open */
9627    int iName = 1;           /* Index in azArg[] of the filename */
9628    int newFlag = 0;         /* True to delete file before opening */
9629    int openMode = SHELL_OPEN_UNSPEC;
9630
9631    /* Check for command-line arguments */
9632    for(iName=1; iName<nArg; iName++){
9633      const char *z = azArg[iName];
9634#ifndef SQLITE_SHELL_FIDDLE
9635      if( optionMatch(z,"new") ){
9636        newFlag = 1;
9637#ifdef SQLITE_HAVE_ZLIB
9638      }else if( optionMatch(z, "zip") ){
9639        openMode = SHELL_OPEN_ZIPFILE;
9640#endif
9641      }else if( optionMatch(z, "append") ){
9642        openMode = SHELL_OPEN_APPENDVFS;
9643      }else if( optionMatch(z, "readonly") ){
9644        openMode = SHELL_OPEN_READONLY;
9645      }else if( optionMatch(z, "nofollow") ){
9646        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9647#ifndef SQLITE_OMIT_DESERIALIZE
9648      }else if( optionMatch(z, "deserialize") ){
9649        openMode = SHELL_OPEN_DESERIALIZE;
9650      }else if( optionMatch(z, "hexdb") ){
9651        openMode = SHELL_OPEN_HEXDB;
9652      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9653        p->szMax = integerValue(azArg[++iName]);
9654#endif /* SQLITE_OMIT_DESERIALIZE */
9655      }else
9656#endif /* !SQLITE_SHELL_FIDDLE */
9657      if( z[0]=='-' ){
9658        utf8_printf(stderr, "unknown option: %s\n", z);
9659        rc = 1;
9660        goto meta_command_exit;
9661      }else if( zFN ){
9662        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9663        rc = 1;
9664        goto meta_command_exit;
9665      }else{
9666        zFN = z;
9667      }
9668    }
9669
9670    /* Close the existing database */
9671    session_close_all(p, -1);
9672    close_db(p->db);
9673    p->db = 0;
9674    p->pAuxDb->zDbFilename = 0;
9675    sqlite3_free(p->pAuxDb->zFreeOnClose);
9676    p->pAuxDb->zFreeOnClose = 0;
9677    p->openMode = openMode;
9678    p->openFlags = 0;
9679    p->szMax = 0;
9680
9681    /* If a filename is specified, try to open it first */
9682    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9683      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9684#ifndef SQLITE_SHELL_FIDDLE
9685      if( p->bSafeMode
9686       && p->openMode!=SHELL_OPEN_HEXDB
9687       && zFN
9688       && strcmp(zFN,":memory:")!=0
9689      ){
9690        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9691      }
9692#else
9693      /* WASM mode has its own sandboxed pseudo-filesystem. */
9694#endif
9695      if( zFN ){
9696        zNewFilename = sqlite3_mprintf("%s", zFN);
9697        shell_check_oom(zNewFilename);
9698      }else{
9699        zNewFilename = 0;
9700      }
9701      p->pAuxDb->zDbFilename = zNewFilename;
9702      open_db(p, OPEN_DB_KEEPALIVE);
9703      if( p->db==0 ){
9704        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9705        sqlite3_free(zNewFilename);
9706      }else{
9707        p->pAuxDb->zFreeOnClose = zNewFilename;
9708      }
9709    }
9710    if( p->db==0 ){
9711      /* As a fall-back open a TEMP database */
9712      p->pAuxDb->zDbFilename = 0;
9713      open_db(p, 0);
9714    }
9715  }else
9716
9717#ifndef SQLITE_SHELL_FIDDLE
9718  if( (c=='o'
9719        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9720   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9721  ){
9722    char *zFile = 0;
9723    int bTxtMode = 0;
9724    int i;
9725    int eMode = 0;
9726    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9727    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9728
9729    zBOM[0] = 0;
9730    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9731    if( c=='e' ){
9732      eMode = 'x';
9733      bOnce = 2;
9734    }else if( strncmp(azArg[0],"once",n)==0 ){
9735      bOnce = 1;
9736    }
9737    for(i=1; i<nArg; i++){
9738      char *z = azArg[i];
9739      if( z[0]=='-' ){
9740        if( z[1]=='-' ) z++;
9741        if( strcmp(z,"-bom")==0 ){
9742          zBOM[0] = 0xef;
9743          zBOM[1] = 0xbb;
9744          zBOM[2] = 0xbf;
9745          zBOM[3] = 0;
9746        }else if( c!='e' && strcmp(z,"-x")==0 ){
9747          eMode = 'x';  /* spreadsheet */
9748        }else if( c!='e' && strcmp(z,"-e")==0 ){
9749          eMode = 'e';  /* text editor */
9750        }else{
9751          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9752                      azArg[i]);
9753          showHelp(p->out, azArg[0]);
9754          rc = 1;
9755          goto meta_command_exit;
9756        }
9757      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9758        zFile = sqlite3_mprintf("%s", z);
9759        if( zFile && zFile[0]=='|' ){
9760          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9761          break;
9762        }
9763      }else{
9764        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9765                    azArg[i]);
9766        showHelp(p->out, azArg[0]);
9767        rc = 1;
9768        sqlite3_free(zFile);
9769        goto meta_command_exit;
9770      }
9771    }
9772    if( zFile==0 ){
9773      zFile = sqlite3_mprintf("stdout");
9774    }
9775    if( bOnce ){
9776      p->outCount = 2;
9777    }else{
9778      p->outCount = 0;
9779    }
9780    output_reset(p);
9781#ifndef SQLITE_NOHAVE_SYSTEM
9782    if( eMode=='e' || eMode=='x' ){
9783      p->doXdgOpen = 1;
9784      outputModePush(p);
9785      if( eMode=='x' ){
9786        /* spreadsheet mode.  Output as CSV. */
9787        newTempFile(p, "csv");
9788        ShellClearFlag(p, SHFLG_Echo);
9789        p->mode = MODE_Csv;
9790        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9791        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9792      }else{
9793        /* text editor mode */
9794        newTempFile(p, "txt");
9795        bTxtMode = 1;
9796      }
9797      sqlite3_free(zFile);
9798      zFile = sqlite3_mprintf("%s", p->zTempFile);
9799    }
9800#endif /* SQLITE_NOHAVE_SYSTEM */
9801    shell_check_oom(zFile);
9802    if( zFile[0]=='|' ){
9803#ifdef SQLITE_OMIT_POPEN
9804      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9805      rc = 1;
9806      p->out = stdout;
9807#else
9808      p->out = popen(zFile + 1, "w");
9809      if( p->out==0 ){
9810        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9811        p->out = stdout;
9812        rc = 1;
9813      }else{
9814        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9815        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9816      }
9817#endif
9818    }else{
9819      p->out = output_file_open(zFile, bTxtMode);
9820      if( p->out==0 ){
9821        if( strcmp(zFile,"off")!=0 ){
9822          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9823        }
9824        p->out = stdout;
9825        rc = 1;
9826      } else {
9827        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9828        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9829      }
9830    }
9831    sqlite3_free(zFile);
9832  }else
9833#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9834
9835  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9836    open_db(p,0);
9837    if( nArg<=1 ) goto parameter_syntax_error;
9838
9839    /* .parameter clear
9840    ** Clear all bind parameters by dropping the TEMP table that holds them.
9841    */
9842    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9843      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9844                   0, 0, 0);
9845    }else
9846
9847    /* .parameter list
9848    ** List all bind parameters.
9849    */
9850    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9851      sqlite3_stmt *pStmt = 0;
9852      int rx;
9853      int len = 0;
9854      rx = sqlite3_prepare_v2(p->db,
9855             "SELECT max(length(key)) "
9856             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9857      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9858        len = sqlite3_column_int(pStmt, 0);
9859        if( len>40 ) len = 40;
9860      }
9861      sqlite3_finalize(pStmt);
9862      pStmt = 0;
9863      if( len ){
9864        rx = sqlite3_prepare_v2(p->db,
9865             "SELECT key, quote(value) "
9866             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9867        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9868          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9869                      sqlite3_column_text(pStmt,1));
9870        }
9871        sqlite3_finalize(pStmt);
9872      }
9873    }else
9874
9875    /* .parameter init
9876    ** Make sure the TEMP table used to hold bind parameters exists.
9877    ** Create it if necessary.
9878    */
9879    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9880      bind_table_init(p);
9881    }else
9882
9883    /* .parameter set NAME VALUE
9884    ** Set or reset a bind parameter.  NAME should be the full parameter
9885    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9886    ** VALUE can be in either SQL literal notation, or if not it will be
9887    ** understood to be a text string.
9888    */
9889    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9890      int rx;
9891      char *zSql;
9892      sqlite3_stmt *pStmt;
9893      const char *zKey = azArg[2];
9894      const char *zValue = azArg[3];
9895      bind_table_init(p);
9896      zSql = sqlite3_mprintf(
9897                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9898                  "VALUES(%Q,%s);", zKey, zValue);
9899      shell_check_oom(zSql);
9900      pStmt = 0;
9901      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9902      sqlite3_free(zSql);
9903      if( rx!=SQLITE_OK ){
9904        sqlite3_finalize(pStmt);
9905        pStmt = 0;
9906        zSql = sqlite3_mprintf(
9907                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9908                   "VALUES(%Q,%Q);", zKey, zValue);
9909        shell_check_oom(zSql);
9910        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9911        sqlite3_free(zSql);
9912        if( rx!=SQLITE_OK ){
9913          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9914          sqlite3_finalize(pStmt);
9915          pStmt = 0;
9916          rc = 1;
9917        }
9918      }
9919      sqlite3_step(pStmt);
9920      sqlite3_finalize(pStmt);
9921    }else
9922
9923    /* .parameter unset NAME
9924    ** Remove the NAME binding from the parameter binding table, if it
9925    ** exists.
9926    */
9927    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9928      char *zSql = sqlite3_mprintf(
9929          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9930      shell_check_oom(zSql);
9931      sqlite3_exec(p->db, zSql, 0, 0, 0);
9932      sqlite3_free(zSql);
9933    }else
9934    /* If no command name matches, show a syntax error */
9935    parameter_syntax_error:
9936    showHelp(p->out, "parameter");
9937  }else
9938
9939  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9940    int i;
9941    for(i=1; i<nArg; i++){
9942      if( i>1 ) raw_printf(p->out, " ");
9943      utf8_printf(p->out, "%s", azArg[i]);
9944    }
9945    raw_printf(p->out, "\n");
9946  }else
9947
9948#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9949  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9950    int i;
9951    int nn = 0;
9952    p->flgProgress = 0;
9953    p->mxProgress = 0;
9954    p->nProgress = 0;
9955    for(i=1; i<nArg; i++){
9956      const char *z = azArg[i];
9957      if( z[0]=='-' ){
9958        z++;
9959        if( z[0]=='-' ) z++;
9960        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9961          p->flgProgress |= SHELL_PROGRESS_QUIET;
9962          continue;
9963        }
9964        if( strcmp(z,"reset")==0 ){
9965          p->flgProgress |= SHELL_PROGRESS_RESET;
9966          continue;
9967        }
9968        if( strcmp(z,"once")==0 ){
9969          p->flgProgress |= SHELL_PROGRESS_ONCE;
9970          continue;
9971        }
9972        if( strcmp(z,"limit")==0 ){
9973          if( i+1>=nArg ){
9974            utf8_printf(stderr, "Error: missing argument on --limit\n");
9975            rc = 1;
9976            goto meta_command_exit;
9977          }else{
9978            p->mxProgress = (int)integerValue(azArg[++i]);
9979          }
9980          continue;
9981        }
9982        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9983        rc = 1;
9984        goto meta_command_exit;
9985      }else{
9986        nn = (int)integerValue(z);
9987      }
9988    }
9989    open_db(p, 0);
9990    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9991  }else
9992#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9993
9994  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9995    if( nArg >= 2) {
9996      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9997    }
9998    if( nArg >= 3) {
9999      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
10000    }
10001  }else
10002
10003#ifndef SQLITE_SHELL_FIDDLE
10004  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
10005    rc = 2;
10006  }else
10007#endif
10008
10009#ifndef SQLITE_SHELL_FIDDLE
10010  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
10011    FILE *inSaved = p->in;
10012    int savedLineno = p->lineno;
10013    failIfSafeMode(p, "cannot run .read in safe mode");
10014    if( nArg!=2 ){
10015      raw_printf(stderr, "Usage: .read FILE\n");
10016      rc = 1;
10017      goto meta_command_exit;
10018    }
10019    if( azArg[1][0]=='|' ){
10020#ifdef SQLITE_OMIT_POPEN
10021      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
10022      rc = 1;
10023      p->out = stdout;
10024#else
10025      p->in = popen(azArg[1]+1, "r");
10026      if( p->in==0 ){
10027        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
10028        rc = 1;
10029      }else{
10030        rc = process_input(p);
10031        pclose(p->in);
10032      }
10033#endif
10034    }else if( (p->in = openChrSource(azArg[1]))==0 ){
10035      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
10036      rc = 1;
10037    }else{
10038      rc = process_input(p);
10039      fclose(p->in);
10040    }
10041    p->in = inSaved;
10042    p->lineno = savedLineno;
10043  }else
10044#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10045
10046#ifndef SQLITE_SHELL_FIDDLE
10047  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10048    const char *zSrcFile;
10049    const char *zDb;
10050    sqlite3 *pSrc;
10051    sqlite3_backup *pBackup;
10052    int nTimeout = 0;
10053
10054    failIfSafeMode(p, "cannot run .restore in safe mode");
10055    if( nArg==2 ){
10056      zSrcFile = azArg[1];
10057      zDb = "main";
10058    }else if( nArg==3 ){
10059      zSrcFile = azArg[2];
10060      zDb = azArg[1];
10061    }else{
10062      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10063      rc = 1;
10064      goto meta_command_exit;
10065    }
10066    rc = sqlite3_open(zSrcFile, &pSrc);
10067    if( rc!=SQLITE_OK ){
10068      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10069      close_db(pSrc);
10070      return 1;
10071    }
10072    open_db(p, 0);
10073    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10074    if( pBackup==0 ){
10075      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10076      close_db(pSrc);
10077      return 1;
10078    }
10079    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10080          || rc==SQLITE_BUSY  ){
10081      if( rc==SQLITE_BUSY ){
10082        if( nTimeout++ >= 3 ) break;
10083        sqlite3_sleep(100);
10084      }
10085    }
10086    sqlite3_backup_finish(pBackup);
10087    if( rc==SQLITE_DONE ){
10088      rc = 0;
10089    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10090      raw_printf(stderr, "Error: source database is busy\n");
10091      rc = 1;
10092    }else{
10093      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10094      rc = 1;
10095    }
10096    close_db(pSrc);
10097  }else
10098#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10099
10100  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10101    if( nArg==2 ){
10102      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10103#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10104      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10105#endif
10106    }else{
10107      raw_printf(stderr, "Usage: .scanstats on|off\n");
10108      rc = 1;
10109    }
10110  }else
10111
10112  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10113    ShellText sSelect;
10114    ShellState data;
10115    char *zErrMsg = 0;
10116    const char *zDiv = "(";
10117    const char *zName = 0;
10118    int iSchema = 0;
10119    int bDebug = 0;
10120    int bNoSystemTabs = 0;
10121    int ii;
10122
10123    open_db(p, 0);
10124    memcpy(&data, p, sizeof(data));
10125    data.showHeader = 0;
10126    data.cMode = data.mode = MODE_Semi;
10127    initText(&sSelect);
10128    for(ii=1; ii<nArg; ii++){
10129      if( optionMatch(azArg[ii],"indent") ){
10130        data.cMode = data.mode = MODE_Pretty;
10131      }else if( optionMatch(azArg[ii],"debug") ){
10132        bDebug = 1;
10133      }else if( optionMatch(azArg[ii],"nosys") ){
10134        bNoSystemTabs = 1;
10135      }else if( azArg[ii][0]=='-' ){
10136        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10137        rc = 1;
10138        goto meta_command_exit;
10139      }else if( zName==0 ){
10140        zName = azArg[ii];
10141      }else{
10142        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10143        rc = 1;
10144        goto meta_command_exit;
10145      }
10146    }
10147    if( zName!=0 ){
10148      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10149                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10150                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10151                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10152      if( isSchema ){
10153        char *new_argv[2], *new_colv[2];
10154        new_argv[0] = sqlite3_mprintf(
10155                      "CREATE TABLE %s (\n"
10156                      "  type text,\n"
10157                      "  name text,\n"
10158                      "  tbl_name text,\n"
10159                      "  rootpage integer,\n"
10160                      "  sql text\n"
10161                      ")", zName);
10162        shell_check_oom(new_argv[0]);
10163        new_argv[1] = 0;
10164        new_colv[0] = "sql";
10165        new_colv[1] = 0;
10166        callback(&data, 1, new_argv, new_colv);
10167        sqlite3_free(new_argv[0]);
10168      }
10169    }
10170    if( zDiv ){
10171      sqlite3_stmt *pStmt = 0;
10172      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10173                              -1, &pStmt, 0);
10174      if( rc ){
10175        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10176        sqlite3_finalize(pStmt);
10177        rc = 1;
10178        goto meta_command_exit;
10179      }
10180      appendText(&sSelect, "SELECT sql FROM", 0);
10181      iSchema = 0;
10182      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10183        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10184        char zScNum[30];
10185        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10186        appendText(&sSelect, zDiv, 0);
10187        zDiv = " UNION ALL ";
10188        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10189        if( sqlite3_stricmp(zDb, "main")!=0 ){
10190          appendText(&sSelect, zDb, '\'');
10191        }else{
10192          appendText(&sSelect, "NULL", 0);
10193        }
10194        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10195        appendText(&sSelect, zScNum, 0);
10196        appendText(&sSelect, " AS snum, ", 0);
10197        appendText(&sSelect, zDb, '\'');
10198        appendText(&sSelect, " AS sname FROM ", 0);
10199        appendText(&sSelect, zDb, quoteChar(zDb));
10200        appendText(&sSelect, ".sqlite_schema", 0);
10201      }
10202      sqlite3_finalize(pStmt);
10203#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10204      if( zName ){
10205        appendText(&sSelect,
10206           " UNION ALL SELECT shell_module_schema(name),"
10207           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10208        0);
10209      }
10210#endif
10211      appendText(&sSelect, ") WHERE ", 0);
10212      if( zName ){
10213        char *zQarg = sqlite3_mprintf("%Q", zName);
10214        int bGlob;
10215        shell_check_oom(zQarg);
10216        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10217                strchr(zName, '[') != 0;
10218        if( strchr(zName, '.') ){
10219          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10220        }else{
10221          appendText(&sSelect, "lower(tbl_name)", 0);
10222        }
10223        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10224        appendText(&sSelect, zQarg, 0);
10225        if( !bGlob ){
10226          appendText(&sSelect, " ESCAPE '\\' ", 0);
10227        }
10228        appendText(&sSelect, " AND ", 0);
10229        sqlite3_free(zQarg);
10230      }
10231      if( bNoSystemTabs ){
10232        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10233      }
10234      appendText(&sSelect, "sql IS NOT NULL"
10235                           " ORDER BY snum, rowid", 0);
10236      if( bDebug ){
10237        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10238      }else{
10239        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10240      }
10241      freeText(&sSelect);
10242    }
10243    if( zErrMsg ){
10244      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10245      sqlite3_free(zErrMsg);
10246      rc = 1;
10247    }else if( rc != SQLITE_OK ){
10248      raw_printf(stderr,"Error: querying schema information\n");
10249      rc = 1;
10250    }else{
10251      rc = 0;
10252    }
10253  }else
10254
10255  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10256   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10257  ){
10258    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10259    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10260  }else
10261
10262#if defined(SQLITE_ENABLE_SESSION)
10263  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10264    struct AuxDb *pAuxDb = p->pAuxDb;
10265    OpenSession *pSession = &pAuxDb->aSession[0];
10266    char **azCmd = &azArg[1];
10267    int iSes = 0;
10268    int nCmd = nArg - 1;
10269    int i;
10270    if( nArg<=1 ) goto session_syntax_error;
10271    open_db(p, 0);
10272    if( nArg>=3 ){
10273      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10274        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10275      }
10276      if( iSes<pAuxDb->nSession ){
10277        pSession = &pAuxDb->aSession[iSes];
10278        azCmd++;
10279        nCmd--;
10280      }else{
10281        pSession = &pAuxDb->aSession[0];
10282        iSes = 0;
10283      }
10284    }
10285
10286    /* .session attach TABLE
10287    ** Invoke the sqlite3session_attach() interface to attach a particular
10288    ** table so that it is never filtered.
10289    */
10290    if( strcmp(azCmd[0],"attach")==0 ){
10291      if( nCmd!=2 ) goto session_syntax_error;
10292      if( pSession->p==0 ){
10293        session_not_open:
10294        raw_printf(stderr, "ERROR: No sessions are open\n");
10295      }else{
10296        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10297        if( rc ){
10298          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10299          rc = 0;
10300        }
10301      }
10302    }else
10303
10304    /* .session changeset FILE
10305    ** .session patchset FILE
10306    ** Write a changeset or patchset into a file.  The file is overwritten.
10307    */
10308    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10309      FILE *out = 0;
10310      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10311      if( nCmd!=2 ) goto session_syntax_error;
10312      if( pSession->p==0 ) goto session_not_open;
10313      out = fopen(azCmd[1], "wb");
10314      if( out==0 ){
10315        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10316                    azCmd[1]);
10317      }else{
10318        int szChng;
10319        void *pChng;
10320        if( azCmd[0][0]=='c' ){
10321          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10322        }else{
10323          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10324        }
10325        if( rc ){
10326          printf("Error: error code %d\n", rc);
10327          rc = 0;
10328        }
10329        if( pChng
10330          && fwrite(pChng, szChng, 1, out)!=1 ){
10331          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10332                  szChng);
10333        }
10334        sqlite3_free(pChng);
10335        fclose(out);
10336      }
10337    }else
10338
10339    /* .session close
10340    ** Close the identified session
10341    */
10342    if( strcmp(azCmd[0], "close")==0 ){
10343      if( nCmd!=1 ) goto session_syntax_error;
10344      if( pAuxDb->nSession ){
10345        session_close(pSession);
10346        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10347      }
10348    }else
10349
10350    /* .session enable ?BOOLEAN?
10351    ** Query or set the enable flag
10352    */
10353    if( strcmp(azCmd[0], "enable")==0 ){
10354      int ii;
10355      if( nCmd>2 ) goto session_syntax_error;
10356      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10357      if( pAuxDb->nSession ){
10358        ii = sqlite3session_enable(pSession->p, ii);
10359        utf8_printf(p->out, "session %s enable flag = %d\n",
10360                    pSession->zName, ii);
10361      }
10362    }else
10363
10364    /* .session filter GLOB ....
10365    ** Set a list of GLOB patterns of table names to be excluded.
10366    */
10367    if( strcmp(azCmd[0], "filter")==0 ){
10368      int ii, nByte;
10369      if( nCmd<2 ) goto session_syntax_error;
10370      if( pAuxDb->nSession ){
10371        for(ii=0; ii<pSession->nFilter; ii++){
10372          sqlite3_free(pSession->azFilter[ii]);
10373        }
10374        sqlite3_free(pSession->azFilter);
10375        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10376        pSession->azFilter = sqlite3_malloc( nByte );
10377        if( pSession->azFilter==0 ){
10378          raw_printf(stderr, "Error: out or memory\n");
10379          exit(1);
10380        }
10381        for(ii=1; ii<nCmd; ii++){
10382          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10383          shell_check_oom(x);
10384        }
10385        pSession->nFilter = ii-1;
10386      }
10387    }else
10388
10389    /* .session indirect ?BOOLEAN?
10390    ** Query or set the indirect flag
10391    */
10392    if( strcmp(azCmd[0], "indirect")==0 ){
10393      int ii;
10394      if( nCmd>2 ) goto session_syntax_error;
10395      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10396      if( pAuxDb->nSession ){
10397        ii = sqlite3session_indirect(pSession->p, ii);
10398        utf8_printf(p->out, "session %s indirect flag = %d\n",
10399                    pSession->zName, ii);
10400      }
10401    }else
10402
10403    /* .session isempty
10404    ** Determine if the session is empty
10405    */
10406    if( strcmp(azCmd[0], "isempty")==0 ){
10407      int ii;
10408      if( nCmd!=1 ) goto session_syntax_error;
10409      if( pAuxDb->nSession ){
10410        ii = sqlite3session_isempty(pSession->p);
10411        utf8_printf(p->out, "session %s isempty flag = %d\n",
10412                    pSession->zName, ii);
10413      }
10414    }else
10415
10416    /* .session list
10417    ** List all currently open sessions
10418    */
10419    if( strcmp(azCmd[0],"list")==0 ){
10420      for(i=0; i<pAuxDb->nSession; i++){
10421        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10422      }
10423    }else
10424
10425    /* .session open DB NAME
10426    ** Open a new session called NAME on the attached database DB.
10427    ** DB is normally "main".
10428    */
10429    if( strcmp(azCmd[0],"open")==0 ){
10430      char *zName;
10431      if( nCmd!=3 ) goto session_syntax_error;
10432      zName = azCmd[2];
10433      if( zName[0]==0 ) goto session_syntax_error;
10434      for(i=0; i<pAuxDb->nSession; i++){
10435        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10436          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10437          goto meta_command_exit;
10438        }
10439      }
10440      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10441        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10442        goto meta_command_exit;
10443      }
10444      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10445      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10446      if( rc ){
10447        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10448        rc = 0;
10449        goto meta_command_exit;
10450      }
10451      pSession->nFilter = 0;
10452      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10453      pAuxDb->nSession++;
10454      pSession->zName = sqlite3_mprintf("%s", zName);
10455      shell_check_oom(pSession->zName);
10456    }else
10457    /* If no command name matches, show a syntax error */
10458    session_syntax_error:
10459    showHelp(p->out, "session");
10460  }else
10461#endif
10462
10463#ifdef SQLITE_DEBUG
10464  /* Undocumented commands for internal testing.  Subject to change
10465  ** without notice. */
10466  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10467    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10468      int i, v;
10469      for(i=1; i<nArg; i++){
10470        v = booleanValue(azArg[i]);
10471        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10472      }
10473    }
10474    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10475      int i; sqlite3_int64 v;
10476      for(i=1; i<nArg; i++){
10477        char zBuf[200];
10478        v = integerValue(azArg[i]);
10479        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10480        utf8_printf(p->out, "%s", zBuf);
10481      }
10482    }
10483  }else
10484#endif
10485
10486  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10487    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10488    int bVerbose = 0;        /* Verbose output */
10489    int bSelftestExists;     /* True if SELFTEST already exists */
10490    int i, k;                /* Loop counters */
10491    int nTest = 0;           /* Number of tests runs */
10492    int nErr = 0;            /* Number of errors seen */
10493    ShellText str;           /* Answer for a query */
10494    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10495
10496    open_db(p,0);
10497    for(i=1; i<nArg; i++){
10498      const char *z = azArg[i];
10499      if( z[0]=='-' && z[1]=='-' ) z++;
10500      if( strcmp(z,"-init")==0 ){
10501        bIsInit = 1;
10502      }else
10503      if( strcmp(z,"-v")==0 ){
10504        bVerbose++;
10505      }else
10506      {
10507        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10508                    azArg[i], azArg[0]);
10509        raw_printf(stderr, "Should be one of: --init -v\n");
10510        rc = 1;
10511        goto meta_command_exit;
10512      }
10513    }
10514    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10515           != SQLITE_OK ){
10516      bSelftestExists = 0;
10517    }else{
10518      bSelftestExists = 1;
10519    }
10520    if( bIsInit ){
10521      createSelftestTable(p);
10522      bSelftestExists = 1;
10523    }
10524    initText(&str);
10525    appendText(&str, "x", 0);
10526    for(k=bSelftestExists; k>=0; k--){
10527      if( k==1 ){
10528        rc = sqlite3_prepare_v2(p->db,
10529            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10530            -1, &pStmt, 0);
10531      }else{
10532        rc = sqlite3_prepare_v2(p->db,
10533          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10534          "      (1,'run','PRAGMA integrity_check','ok')",
10535          -1, &pStmt, 0);
10536      }
10537      if( rc ){
10538        raw_printf(stderr, "Error querying the selftest table\n");
10539        rc = 1;
10540        sqlite3_finalize(pStmt);
10541        goto meta_command_exit;
10542      }
10543      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10544        int tno = sqlite3_column_int(pStmt, 0);
10545        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10546        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10547        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10548
10549        if( zOp==0 ) continue;
10550        if( zSql==0 ) continue;
10551        if( zAns==0 ) continue;
10552        k = 0;
10553        if( bVerbose>0 ){
10554          printf("%d: %s %s\n", tno, zOp, zSql);
10555        }
10556        if( strcmp(zOp,"memo")==0 ){
10557          utf8_printf(p->out, "%s\n", zSql);
10558        }else
10559        if( strcmp(zOp,"run")==0 ){
10560          char *zErrMsg = 0;
10561          str.n = 0;
10562          str.z[0] = 0;
10563          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10564          nTest++;
10565          if( bVerbose ){
10566            utf8_printf(p->out, "Result: %s\n", str.z);
10567          }
10568          if( rc || zErrMsg ){
10569            nErr++;
10570            rc = 1;
10571            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10572            sqlite3_free(zErrMsg);
10573          }else if( strcmp(zAns,str.z)!=0 ){
10574            nErr++;
10575            rc = 1;
10576            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10577            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10578          }
10579        }else
10580        {
10581          utf8_printf(stderr,
10582            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10583          rc = 1;
10584          break;
10585        }
10586      } /* End loop over rows of content from SELFTEST */
10587      sqlite3_finalize(pStmt);
10588    } /* End loop over k */
10589    freeText(&str);
10590    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10591  }else
10592
10593  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10594    if( nArg<2 || nArg>3 ){
10595      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10596      rc = 1;
10597    }
10598    if( nArg>=2 ){
10599      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10600                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10601    }
10602    if( nArg>=3 ){
10603      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10604                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10605    }
10606  }else
10607
10608  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10609    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10610    int i;                   /* Loop counter */
10611    int bSchema = 0;         /* Also hash the schema */
10612    int bSeparate = 0;       /* Hash each table separately */
10613    int iSize = 224;         /* Hash algorithm to use */
10614    int bDebug = 0;          /* Only show the query that would have run */
10615    sqlite3_stmt *pStmt;     /* For querying tables names */
10616    char *zSql;              /* SQL to be run */
10617    char *zSep;              /* Separator */
10618    ShellText sSql;          /* Complete SQL for the query to run the hash */
10619    ShellText sQuery;        /* Set of queries used to read all content */
10620    open_db(p, 0);
10621    for(i=1; i<nArg; i++){
10622      const char *z = azArg[i];
10623      if( z[0]=='-' ){
10624        z++;
10625        if( z[0]=='-' ) z++;
10626        if( strcmp(z,"schema")==0 ){
10627          bSchema = 1;
10628        }else
10629        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10630         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10631        ){
10632          iSize = atoi(&z[5]);
10633        }else
10634        if( strcmp(z,"debug")==0 ){
10635          bDebug = 1;
10636        }else
10637        {
10638          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10639                      azArg[i], azArg[0]);
10640          showHelp(p->out, azArg[0]);
10641          rc = 1;
10642          goto meta_command_exit;
10643        }
10644      }else if( zLike ){
10645        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10646        rc = 1;
10647        goto meta_command_exit;
10648      }else{
10649        zLike = z;
10650        bSeparate = 1;
10651        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10652      }
10653    }
10654    if( bSchema ){
10655      zSql = "SELECT lower(name) FROM sqlite_schema"
10656             " WHERE type='table' AND coalesce(rootpage,0)>1"
10657             " UNION ALL SELECT 'sqlite_schema'"
10658             " ORDER BY 1 collate nocase";
10659    }else{
10660      zSql = "SELECT lower(name) FROM sqlite_schema"
10661             " WHERE type='table' AND coalesce(rootpage,0)>1"
10662             " AND name NOT LIKE 'sqlite_%'"
10663             " ORDER BY 1 collate nocase";
10664    }
10665    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10666    initText(&sQuery);
10667    initText(&sSql);
10668    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10669    zSep = "VALUES(";
10670    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10671      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10672      if( zTab==0 ) continue;
10673      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10674      if( strncmp(zTab, "sqlite_",7)!=0 ){
10675        appendText(&sQuery,"SELECT * FROM ", 0);
10676        appendText(&sQuery,zTab,'"');
10677        appendText(&sQuery," NOT INDEXED;", 0);
10678      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10679        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10680                           " ORDER BY name;", 0);
10681      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10682        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10683                           " ORDER BY name;", 0);
10684      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10685        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10686                           " ORDER BY tbl,idx;", 0);
10687      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10688        appendText(&sQuery, "SELECT * FROM ", 0);
10689        appendText(&sQuery, zTab, 0);
10690        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10691      }
10692      appendText(&sSql, zSep, 0);
10693      appendText(&sSql, sQuery.z, '\'');
10694      sQuery.n = 0;
10695      appendText(&sSql, ",", 0);
10696      appendText(&sSql, zTab, '\'');
10697      zSep = "),(";
10698    }
10699    sqlite3_finalize(pStmt);
10700    if( bSeparate ){
10701      zSql = sqlite3_mprintf(
10702          "%s))"
10703          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10704          "   FROM [sha3sum$query]",
10705          sSql.z, iSize);
10706    }else{
10707      zSql = sqlite3_mprintf(
10708          "%s))"
10709          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10710          "   FROM [sha3sum$query]",
10711          sSql.z, iSize);
10712    }
10713    shell_check_oom(zSql);
10714    freeText(&sQuery);
10715    freeText(&sSql);
10716    if( bDebug ){
10717      utf8_printf(p->out, "%s\n", zSql);
10718    }else{
10719      shell_exec(p, zSql, 0);
10720    }
10721    sqlite3_free(zSql);
10722  }else
10723
10724#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10725  if( c=='s'
10726   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10727  ){
10728    char *zCmd;
10729    int i, x;
10730    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10731    if( nArg<2 ){
10732      raw_printf(stderr, "Usage: .system COMMAND\n");
10733      rc = 1;
10734      goto meta_command_exit;
10735    }
10736    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10737    for(i=2; i<nArg && zCmd!=0; i++){
10738      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10739                             zCmd, azArg[i]);
10740    }
10741    x = zCmd!=0 ? system(zCmd) : 1;
10742    sqlite3_free(zCmd);
10743    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10744  }else
10745#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10746
10747  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10748    static const char *azBool[] = { "off", "on", "trigger", "full"};
10749    const char *zOut;
10750    int i;
10751    if( nArg!=1 ){
10752      raw_printf(stderr, "Usage: .show\n");
10753      rc = 1;
10754      goto meta_command_exit;
10755    }
10756    utf8_printf(p->out, "%12.12s: %s\n","echo",
10757                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10758    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10759    utf8_printf(p->out, "%12.12s: %s\n","explain",
10760         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10761    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10762    if( p->mode==MODE_Column
10763     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10764    ){
10765      utf8_printf
10766        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10767         modeDescr[p->mode], p->cmOpts.iWrap,
10768         p->cmOpts.bWordWrap ? "on" : "off",
10769         p->cmOpts.bQuote ? "" : "no");
10770    }else{
10771      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10772    }
10773    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10774      output_c_string(p->out, p->nullValue);
10775      raw_printf(p->out, "\n");
10776    utf8_printf(p->out,"%12.12s: %s\n","output",
10777            strlen30(p->outfile) ? p->outfile : "stdout");
10778    utf8_printf(p->out,"%12.12s: ", "colseparator");
10779      output_c_string(p->out, p->colSeparator);
10780      raw_printf(p->out, "\n");
10781    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10782      output_c_string(p->out, p->rowSeparator);
10783      raw_printf(p->out, "\n");
10784    switch( p->statsOn ){
10785      case 0:  zOut = "off";     break;
10786      default: zOut = "on";      break;
10787      case 2:  zOut = "stmt";    break;
10788      case 3:  zOut = "vmstep";  break;
10789    }
10790    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10791    utf8_printf(p->out, "%12.12s: ", "width");
10792    for (i=0;i<p->nWidth;i++) {
10793      raw_printf(p->out, "%d ", p->colWidth[i]);
10794    }
10795    raw_printf(p->out, "\n");
10796    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10797                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10798  }else
10799
10800  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10801    if( nArg==2 ){
10802      if( strcmp(azArg[1],"stmt")==0 ){
10803        p->statsOn = 2;
10804      }else if( strcmp(azArg[1],"vmstep")==0 ){
10805        p->statsOn = 3;
10806      }else{
10807        p->statsOn = (u8)booleanValue(azArg[1]);
10808      }
10809    }else if( nArg==1 ){
10810      display_stats(p->db, p, 0);
10811    }else{
10812      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10813      rc = 1;
10814    }
10815  }else
10816
10817  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10818   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10819                 || strncmp(azArg[0], "indexes", n)==0) )
10820  ){
10821    sqlite3_stmt *pStmt;
10822    char **azResult;
10823    int nRow, nAlloc;
10824    int ii;
10825    ShellText s;
10826    initText(&s);
10827    open_db(p, 0);
10828    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10829    if( rc ){
10830      sqlite3_finalize(pStmt);
10831      return shellDatabaseError(p->db);
10832    }
10833
10834    if( nArg>2 && c=='i' ){
10835      /* It is an historical accident that the .indexes command shows an error
10836      ** when called with the wrong number of arguments whereas the .tables
10837      ** command does not. */
10838      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10839      rc = 1;
10840      sqlite3_finalize(pStmt);
10841      goto meta_command_exit;
10842    }
10843    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10844      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10845      if( zDbName==0 ) continue;
10846      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10847      if( sqlite3_stricmp(zDbName, "main")==0 ){
10848        appendText(&s, "SELECT name FROM ", 0);
10849      }else{
10850        appendText(&s, "SELECT ", 0);
10851        appendText(&s, zDbName, '\'');
10852        appendText(&s, "||'.'||name FROM ", 0);
10853      }
10854      appendText(&s, zDbName, '"');
10855      appendText(&s, ".sqlite_schema ", 0);
10856      if( c=='t' ){
10857        appendText(&s," WHERE type IN ('table','view')"
10858                      "   AND name NOT LIKE 'sqlite_%'"
10859                      "   AND name LIKE ?1", 0);
10860      }else{
10861        appendText(&s," WHERE type='index'"
10862                      "   AND tbl_name LIKE ?1", 0);
10863      }
10864    }
10865    rc = sqlite3_finalize(pStmt);
10866    if( rc==SQLITE_OK ){
10867      appendText(&s, " ORDER BY 1", 0);
10868      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10869    }
10870    freeText(&s);
10871    if( rc ) return shellDatabaseError(p->db);
10872
10873    /* Run the SQL statement prepared by the above block. Store the results
10874    ** as an array of nul-terminated strings in azResult[].  */
10875    nRow = nAlloc = 0;
10876    azResult = 0;
10877    if( nArg>1 ){
10878      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10879    }else{
10880      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10881    }
10882    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10883      if( nRow>=nAlloc ){
10884        char **azNew;
10885        int n2 = nAlloc*2 + 10;
10886        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10887        shell_check_oom(azNew);
10888        nAlloc = n2;
10889        azResult = azNew;
10890      }
10891      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10892      shell_check_oom(azResult[nRow]);
10893      nRow++;
10894    }
10895    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10896      rc = shellDatabaseError(p->db);
10897    }
10898
10899    /* Pretty-print the contents of array azResult[] to the output */
10900    if( rc==0 && nRow>0 ){
10901      int len, maxlen = 0;
10902      int i, j;
10903      int nPrintCol, nPrintRow;
10904      for(i=0; i<nRow; i++){
10905        len = strlen30(azResult[i]);
10906        if( len>maxlen ) maxlen = len;
10907      }
10908      nPrintCol = 80/(maxlen+2);
10909      if( nPrintCol<1 ) nPrintCol = 1;
10910      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10911      for(i=0; i<nPrintRow; i++){
10912        for(j=i; j<nRow; j+=nPrintRow){
10913          char *zSp = j<nPrintRow ? "" : "  ";
10914          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10915                      azResult[j] ? azResult[j]:"");
10916        }
10917        raw_printf(p->out, "\n");
10918      }
10919    }
10920
10921    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10922    sqlite3_free(azResult);
10923  }else
10924
10925#ifndef SQLITE_SHELL_FIDDLE
10926  /* Begin redirecting output to the file "testcase-out.txt" */
10927  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10928    output_reset(p);
10929    p->out = output_file_open("testcase-out.txt", 0);
10930    if( p->out==0 ){
10931      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10932    }
10933    if( nArg>=2 ){
10934      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10935    }else{
10936      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10937    }
10938  }else
10939#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10940
10941#ifndef SQLITE_UNTESTABLE
10942  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10943    static const struct {
10944       const char *zCtrlName;   /* Name of a test-control option */
10945       int ctrlCode;            /* Integer code for that option */
10946       int unSafe;              /* Not valid for --safe mode */
10947       const char *zUsage;      /* Usage notes */
10948    } aCtrl[] = {
10949      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10950      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10951    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10952    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10953      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10954      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10955    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10956      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10957      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10958      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10959      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10960      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10961#ifdef YYCOVERAGE
10962      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10963#endif
10964      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10965      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10966      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10967      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10968      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10969      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10970      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10971    };
10972    int testctrl = -1;
10973    int iCtrl = -1;
10974    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10975    int isOk = 0;
10976    int i, n2;
10977    const char *zCmd = 0;
10978
10979    open_db(p, 0);
10980    zCmd = nArg>=2 ? azArg[1] : "help";
10981
10982    /* The argument can optionally begin with "-" or "--" */
10983    if( zCmd[0]=='-' && zCmd[1] ){
10984      zCmd++;
10985      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10986    }
10987
10988    /* --help lists all test-controls */
10989    if( strcmp(zCmd,"help")==0 ){
10990      utf8_printf(p->out, "Available test-controls:\n");
10991      for(i=0; i<ArraySize(aCtrl); i++){
10992        utf8_printf(p->out, "  .testctrl %s %s\n",
10993                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10994      }
10995      rc = 1;
10996      goto meta_command_exit;
10997    }
10998
10999    /* convert testctrl text option to value. allow any unique prefix
11000    ** of the option name, or a numerical value. */
11001    n2 = strlen30(zCmd);
11002    for(i=0; i<ArraySize(aCtrl); i++){
11003      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
11004        if( testctrl<0 ){
11005          testctrl = aCtrl[i].ctrlCode;
11006          iCtrl = i;
11007        }else{
11008          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
11009                              "Use \".testctrl --help\" for help\n", zCmd);
11010          rc = 1;
11011          goto meta_command_exit;
11012        }
11013      }
11014    }
11015    if( testctrl<0 ){
11016      utf8_printf(stderr,"Error: unknown test-control: %s\n"
11017                         "Use \".testctrl --help\" for help\n", zCmd);
11018    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
11019      utf8_printf(stderr,
11020         "line %d: \".testctrl %s\" may not be used in safe mode\n",
11021         p->lineno, aCtrl[iCtrl].zCtrlName);
11022      exit(1);
11023    }else{
11024      switch(testctrl){
11025
11026        /* sqlite3_test_control(int, db, int) */
11027        case SQLITE_TESTCTRL_OPTIMIZATIONS:
11028          if( nArg==3 ){
11029            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
11030            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11031            isOk = 3;
11032          }
11033          break;
11034
11035        /* sqlite3_test_control(int) */
11036        case SQLITE_TESTCTRL_PRNG_SAVE:
11037        case SQLITE_TESTCTRL_PRNG_RESTORE:
11038        case SQLITE_TESTCTRL_BYTEORDER:
11039          if( nArg==2 ){
11040            rc2 = sqlite3_test_control(testctrl);
11041            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
11042          }
11043          break;
11044
11045        /* sqlite3_test_control(int, uint) */
11046        case SQLITE_TESTCTRL_PENDING_BYTE:
11047          if( nArg==3 ){
11048            unsigned int opt = (unsigned int)integerValue(azArg[2]);
11049            rc2 = sqlite3_test_control(testctrl, opt);
11050            isOk = 3;
11051          }
11052          break;
11053
11054        /* sqlite3_test_control(int, int, sqlite3*) */
11055        case SQLITE_TESTCTRL_PRNG_SEED:
11056          if( nArg==3 || nArg==4 ){
11057            int ii = (int)integerValue(azArg[2]);
11058            sqlite3 *db;
11059            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11060              sqlite3_randomness(sizeof(ii),&ii);
11061              printf("-- random seed: %d\n", ii);
11062            }
11063            if( nArg==3 ){
11064              db = 0;
11065            }else{
11066              db = p->db;
11067              /* Make sure the schema has been loaded */
11068              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11069            }
11070            rc2 = sqlite3_test_control(testctrl, ii, db);
11071            isOk = 3;
11072          }
11073          break;
11074
11075        /* sqlite3_test_control(int, int) */
11076        case SQLITE_TESTCTRL_ASSERT:
11077        case SQLITE_TESTCTRL_ALWAYS:
11078          if( nArg==3 ){
11079            int opt = booleanValue(azArg[2]);
11080            rc2 = sqlite3_test_control(testctrl, opt);
11081            isOk = 1;
11082          }
11083          break;
11084
11085        /* sqlite3_test_control(int, int) */
11086        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11087        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11088          if( nArg==3 ){
11089            int opt = booleanValue(azArg[2]);
11090            rc2 = sqlite3_test_control(testctrl, opt);
11091            isOk = 3;
11092          }
11093          break;
11094
11095        /* sqlite3_test_control(sqlite3*) */
11096        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11097          rc2 = sqlite3_test_control(testctrl, p->db);
11098          isOk = 3;
11099          break;
11100
11101        case SQLITE_TESTCTRL_IMPOSTER:
11102          if( nArg==5 ){
11103            rc2 = sqlite3_test_control(testctrl, p->db,
11104                          azArg[2],
11105                          integerValue(azArg[3]),
11106                          integerValue(azArg[4]));
11107            isOk = 3;
11108          }
11109          break;
11110
11111        case SQLITE_TESTCTRL_SEEK_COUNT: {
11112          u64 x = 0;
11113          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11114          utf8_printf(p->out, "%llu\n", x);
11115          isOk = 3;
11116          break;
11117        }
11118
11119#ifdef YYCOVERAGE
11120        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11121          if( nArg==2 ){
11122            sqlite3_test_control(testctrl, p->out);
11123            isOk = 3;
11124          }
11125          break;
11126        }
11127#endif
11128#ifdef SQLITE_DEBUG
11129        case SQLITE_TESTCTRL_TUNE: {
11130          if( nArg==4 ){
11131            int id = (int)integerValue(azArg[2]);
11132            int val = (int)integerValue(azArg[3]);
11133            sqlite3_test_control(testctrl, id, &val);
11134            isOk = 3;
11135          }else if( nArg==3 ){
11136            int id = (int)integerValue(azArg[2]);
11137            sqlite3_test_control(testctrl, -id, &rc2);
11138            isOk = 1;
11139          }else if( nArg==2 ){
11140            int id = 1;
11141            while(1){
11142              int val = 0;
11143              rc2 = sqlite3_test_control(testctrl, -id, &val);
11144              if( rc2!=SQLITE_OK ) break;
11145              if( id>1 ) utf8_printf(p->out, "  ");
11146              utf8_printf(p->out, "%d: %d", id, val);
11147              id++;
11148            }
11149            if( id>1 ) utf8_printf(p->out, "\n");
11150            isOk = 3;
11151          }
11152          break;
11153        }
11154#endif
11155        case SQLITE_TESTCTRL_SORTER_MMAP:
11156          if( nArg==3 ){
11157            int opt = (unsigned int)integerValue(azArg[2]);
11158            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11159            isOk = 3;
11160          }
11161          break;
11162      }
11163    }
11164    if( isOk==0 && iCtrl>=0 ){
11165      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11166      rc = 1;
11167    }else if( isOk==1 ){
11168      raw_printf(p->out, "%d\n", rc2);
11169    }else if( isOk==2 ){
11170      raw_printf(p->out, "0x%08x\n", rc2);
11171    }
11172  }else
11173#endif /* !defined(SQLITE_UNTESTABLE) */
11174
11175  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11176    open_db(p, 0);
11177    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11178  }else
11179
11180  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11181    if( nArg==2 ){
11182      enableTimer = booleanValue(azArg[1]);
11183      if( enableTimer && !HAS_TIMER ){
11184        raw_printf(stderr, "Error: timer not available on this system.\n");
11185        enableTimer = 0;
11186      }
11187    }else{
11188      raw_printf(stderr, "Usage: .timer on|off\n");
11189      rc = 1;
11190    }
11191  }else
11192
11193#ifndef SQLITE_OMIT_TRACE
11194  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11195    int mType = 0;
11196    int jj;
11197    open_db(p, 0);
11198    for(jj=1; jj<nArg; jj++){
11199      const char *z = azArg[jj];
11200      if( z[0]=='-' ){
11201        if( optionMatch(z, "expanded") ){
11202          p->eTraceType = SHELL_TRACE_EXPANDED;
11203        }
11204#ifdef SQLITE_ENABLE_NORMALIZE
11205        else if( optionMatch(z, "normalized") ){
11206          p->eTraceType = SHELL_TRACE_NORMALIZED;
11207        }
11208#endif
11209        else if( optionMatch(z, "plain") ){
11210          p->eTraceType = SHELL_TRACE_PLAIN;
11211        }
11212        else if( optionMatch(z, "profile") ){
11213          mType |= SQLITE_TRACE_PROFILE;
11214        }
11215        else if( optionMatch(z, "row") ){
11216          mType |= SQLITE_TRACE_ROW;
11217        }
11218        else if( optionMatch(z, "stmt") ){
11219          mType |= SQLITE_TRACE_STMT;
11220        }
11221        else if( optionMatch(z, "close") ){
11222          mType |= SQLITE_TRACE_CLOSE;
11223        }
11224        else {
11225          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11226          rc = 1;
11227          goto meta_command_exit;
11228        }
11229      }else{
11230        output_file_close(p->traceOut);
11231        p->traceOut = output_file_open(azArg[1], 0);
11232      }
11233    }
11234    if( p->traceOut==0 ){
11235      sqlite3_trace_v2(p->db, 0, 0, 0);
11236    }else{
11237      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11238      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11239    }
11240  }else
11241#endif /* !defined(SQLITE_OMIT_TRACE) */
11242
11243#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11244  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11245    int ii;
11246    int lenOpt;
11247    char *zOpt;
11248    if( nArg<2 ){
11249      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11250      rc = 1;
11251      goto meta_command_exit;
11252    }
11253    open_db(p, 0);
11254    zOpt = azArg[1];
11255    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11256    lenOpt = (int)strlen(zOpt);
11257    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11258      assert( azArg[nArg]==0 );
11259      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11260    }else{
11261      for(ii=1; ii<nArg; ii++){
11262        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11263      }
11264    }
11265  }else
11266#endif
11267
11268#if SQLITE_USER_AUTHENTICATION
11269  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11270    if( nArg<2 ){
11271      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11272      rc = 1;
11273      goto meta_command_exit;
11274    }
11275    open_db(p, 0);
11276    if( strcmp(azArg[1],"login")==0 ){
11277      if( nArg!=4 ){
11278        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11279        rc = 1;
11280        goto meta_command_exit;
11281      }
11282      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11283                                     strlen30(azArg[3]));
11284      if( rc ){
11285        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11286        rc = 1;
11287      }
11288    }else if( strcmp(azArg[1],"add")==0 ){
11289      if( nArg!=5 ){
11290        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11291        rc = 1;
11292        goto meta_command_exit;
11293      }
11294      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11295                            booleanValue(azArg[4]));
11296      if( rc ){
11297        raw_printf(stderr, "User-Add failed: %d\n", rc);
11298        rc = 1;
11299      }
11300    }else if( strcmp(azArg[1],"edit")==0 ){
11301      if( nArg!=5 ){
11302        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11303        rc = 1;
11304        goto meta_command_exit;
11305      }
11306      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11307                              booleanValue(azArg[4]));
11308      if( rc ){
11309        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11310        rc = 1;
11311      }
11312    }else if( strcmp(azArg[1],"delete")==0 ){
11313      if( nArg!=3 ){
11314        raw_printf(stderr, "Usage: .user delete USER\n");
11315        rc = 1;
11316        goto meta_command_exit;
11317      }
11318      rc = sqlite3_user_delete(p->db, azArg[2]);
11319      if( rc ){
11320        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11321        rc = 1;
11322      }
11323    }else{
11324      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11325      rc = 1;
11326      goto meta_command_exit;
11327    }
11328  }else
11329#endif /* SQLITE_USER_AUTHENTICATION */
11330
11331  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11332    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11333        sqlite3_libversion(), sqlite3_sourceid());
11334#if SQLITE_HAVE_ZLIB
11335    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11336#endif
11337#define CTIMEOPT_VAL_(opt) #opt
11338#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11339#if defined(__clang__) && defined(__clang_major__)
11340    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11341                    CTIMEOPT_VAL(__clang_minor__) "."
11342                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11343#elif defined(_MSC_VER)
11344    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11345#elif defined(__GNUC__) && defined(__VERSION__)
11346    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11347#endif
11348  }else
11349
11350  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11351    const char *zDbName = nArg==2 ? azArg[1] : "main";
11352    sqlite3_vfs *pVfs = 0;
11353    if( p->db ){
11354      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11355      if( pVfs ){
11356        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11357        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11358        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11359        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11360      }
11361    }
11362  }else
11363
11364  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11365    sqlite3_vfs *pVfs;
11366    sqlite3_vfs *pCurrent = 0;
11367    if( p->db ){
11368      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11369    }
11370    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11371      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11372           pVfs==pCurrent ? "  <--- CURRENT" : "");
11373      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11374      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11375      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11376      if( pVfs->pNext ){
11377        raw_printf(p->out, "-----------------------------------\n");
11378      }
11379    }
11380  }else
11381
11382  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11383    const char *zDbName = nArg==2 ? azArg[1] : "main";
11384    char *zVfsName = 0;
11385    if( p->db ){
11386      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11387      if( zVfsName ){
11388        utf8_printf(p->out, "%s\n", zVfsName);
11389        sqlite3_free(zVfsName);
11390      }
11391    }
11392  }else
11393
11394  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11395    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11396    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11397  }else
11398
11399  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11400    int j;
11401    assert( nArg<=ArraySize(azArg) );
11402    p->nWidth = nArg-1;
11403    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11404    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11405    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11406    for(j=1; j<nArg; j++){
11407      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11408    }
11409  }else
11410
11411  {
11412    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11413      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11414    rc = 1;
11415  }
11416
11417meta_command_exit:
11418  if( p->outCount ){
11419    p->outCount--;
11420    if( p->outCount==0 ) output_reset(p);
11421  }
11422  p->bSafeMode = p->bSafeModePersist;
11423  return rc;
11424}
11425
11426/* Line scan result and intermediate states (supporting scan resumption)
11427*/
11428#ifndef CHAR_BIT
11429# define CHAR_BIT 8
11430#endif
11431typedef enum {
11432  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11433  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11434  QSS_Start = 0
11435} QuickScanState;
11436#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11437#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11438#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11439#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11440#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11441
11442/*
11443** Scan line for classification to guide shell's handling.
11444** The scan is resumable for subsequent lines when prior
11445** return values are passed as the 2nd argument.
11446*/
11447static QuickScanState quickscan(char *zLine, QuickScanState qss){
11448  char cin;
11449  char cWait = (char)qss; /* intentional narrowing loss */
11450  if( cWait==0 ){
11451  PlainScan:
11452    assert( cWait==0 );
11453    while( (cin = *zLine++)!=0 ){
11454      if( IsSpace(cin) )
11455        continue;
11456      switch (cin){
11457      case '-':
11458        if( *zLine!='-' )
11459          break;
11460        while((cin = *++zLine)!=0 )
11461          if( cin=='\n')
11462            goto PlainScan;
11463        return qss;
11464      case ';':
11465        qss |= QSS_EndingSemi;
11466        continue;
11467      case '/':
11468        if( *zLine=='*' ){
11469          ++zLine;
11470          cWait = '*';
11471          qss = QSS_SETV(qss, cWait);
11472          goto TermScan;
11473        }
11474        break;
11475      case '[':
11476        cin = ']';
11477        /* fall thru */
11478      case '`': case '\'': case '"':
11479        cWait = cin;
11480        qss = QSS_HasDark | cWait;
11481        goto TermScan;
11482      default:
11483        break;
11484      }
11485      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11486    }
11487  }else{
11488  TermScan:
11489    while( (cin = *zLine++)!=0 ){
11490      if( cin==cWait ){
11491        switch( cWait ){
11492        case '*':
11493          if( *zLine != '/' )
11494            continue;
11495          ++zLine;
11496          cWait = 0;
11497          qss = QSS_SETV(qss, 0);
11498          goto PlainScan;
11499        case '`': case '\'': case '"':
11500          if(*zLine==cWait){
11501            ++zLine;
11502            continue;
11503          }
11504          /* fall thru */
11505        case ']':
11506          cWait = 0;
11507          qss = QSS_SETV(qss, 0);
11508          goto PlainScan;
11509        default: assert(0);
11510        }
11511      }
11512    }
11513  }
11514  return qss;
11515}
11516
11517/*
11518** Return TRUE if the line typed in is an SQL command terminator other
11519** than a semi-colon.  The SQL Server style "go" command is understood
11520** as is the Oracle "/".
11521*/
11522static int line_is_command_terminator(char *zLine){
11523  while( IsSpace(zLine[0]) ){ zLine++; };
11524  if( zLine[0]=='/' )
11525    zLine += 1; /* Oracle */
11526  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11527    zLine += 2; /* SQL Server */
11528  else
11529    return 0;
11530  return quickscan(zLine, QSS_Start)==QSS_Start;
11531}
11532
11533/*
11534** We need a default sqlite3_complete() implementation to use in case
11535** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11536** any arbitrary text is a complete SQL statement.  This is not very
11537** user-friendly, but it does seem to work.
11538*/
11539#ifdef SQLITE_OMIT_COMPLETE
11540#define sqlite3_complete(x) 1
11541#endif
11542
11543/*
11544** Return true if zSql is a complete SQL statement.  Return false if it
11545** ends in the middle of a string literal or C-style comment.
11546*/
11547static int line_is_complete(char *zSql, int nSql){
11548  int rc;
11549  if( zSql==0 ) return 1;
11550  zSql[nSql] = ';';
11551  zSql[nSql+1] = 0;
11552  rc = sqlite3_complete(zSql);
11553  zSql[nSql] = 0;
11554  return rc;
11555}
11556
11557/*
11558** Run a single line of SQL.  Return the number of errors.
11559*/
11560static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11561  int rc;
11562  char *zErrMsg = 0;
11563
11564  open_db(p, 0);
11565  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11566  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11567  BEGIN_TIMER;
11568  rc = shell_exec(p, zSql, &zErrMsg);
11569  END_TIMER;
11570  if( rc || zErrMsg ){
11571    char zPrefix[100];
11572    const char *zErrorTail;
11573    const char *zErrorType;
11574    if( zErrMsg==0 ){
11575      zErrorType = "Error";
11576      zErrorTail = sqlite3_errmsg(p->db);
11577    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11578      zErrorType = "Parse error";
11579      zErrorTail = &zErrMsg[12];
11580    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11581      zErrorType = "Runtime error";
11582      zErrorTail = &zErrMsg[10];
11583    }else{
11584      zErrorType = "Error";
11585      zErrorTail = zErrMsg;
11586    }
11587    if( in!=0 || !stdin_is_interactive ){
11588      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11589                       "%s near line %d:", zErrorType, startline);
11590    }else{
11591      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11592    }
11593    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11594    sqlite3_free(zErrMsg);
11595    zErrMsg = 0;
11596    return 1;
11597  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11598    char zLineBuf[2000];
11599    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11600            "changes: %lld   total_changes: %lld",
11601            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11602    raw_printf(p->out, "%s\n", zLineBuf);
11603  }
11604  return 0;
11605}
11606
11607static void echo_group_input(ShellState *p, const char *zDo){
11608  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11609}
11610
11611#ifdef SQLITE_SHELL_FIDDLE
11612/*
11613** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11614** because we need the global shellState and cannot access it from that function
11615** without moving lots of code around (creating a larger/messier diff).
11616*/
11617static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11618  /* Parse the next line from shellState.wasm.zInput. */
11619  const char *zBegin = shellState.wasm.zPos;
11620  const char *z = zBegin;
11621  char *zLine = 0;
11622  i64 nZ = 0;
11623
11624  UNUSED_PARAMETER(in);
11625  UNUSED_PARAMETER(isContinuation);
11626  if(!z || !*z){
11627    return 0;
11628  }
11629  while(*z && isspace(*z)) ++z;
11630  zBegin = z;
11631  for(; *z && '\n'!=*z; ++nZ, ++z){}
11632  if(nZ>0 && '\r'==zBegin[nZ-1]){
11633    --nZ;
11634  }
11635  shellState.wasm.zPos = z;
11636  zLine = realloc(zPrior, nZ+1);
11637  shell_check_oom(zLine);
11638  memcpy(zLine, zBegin, nZ);
11639  zLine[nZ] = 0;
11640  return zLine;
11641}
11642#endif /* SQLITE_SHELL_FIDDLE */
11643
11644/*
11645** Read input from *in and process it.  If *in==0 then input
11646** is interactive - the user is typing it it.  Otherwise, input
11647** is coming from a file or device.  A prompt is issued and history
11648** is saved only if input is interactive.  An interrupt signal will
11649** cause this routine to exit immediately, unless input is interactive.
11650**
11651** Return the number of errors.
11652*/
11653static int process_input(ShellState *p){
11654  char *zLine = 0;          /* A single input line */
11655  char *zSql = 0;           /* Accumulated SQL text */
11656  i64 nLine;                /* Length of current line */
11657  i64 nSql = 0;             /* Bytes of zSql[] used */
11658  i64 nAlloc = 0;           /* Allocated zSql[] space */
11659  int rc;                   /* Error code */
11660  int errCnt = 0;           /* Number of errors seen */
11661  i64 startline = 0;        /* Line number for start of current input */
11662  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11663
11664  if( p->inputNesting==MAX_INPUT_NESTING ){
11665    /* This will be more informative in a later version. */
11666    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11667                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11668    return 1;
11669  }
11670  ++p->inputNesting;
11671  p->lineno = 0;
11672  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11673    fflush(p->out);
11674    zLine = one_input_line(p->in, zLine, nSql>0);
11675    if( zLine==0 ){
11676      /* End of input */
11677      if( p->in==0 && stdin_is_interactive ) printf("\n");
11678      break;
11679    }
11680    if( seenInterrupt ){
11681      if( p->in!=0 ) break;
11682      seenInterrupt = 0;
11683    }
11684    p->lineno++;
11685    if( QSS_INPLAIN(qss)
11686        && line_is_command_terminator(zLine)
11687        && line_is_complete(zSql, nSql) ){
11688      memcpy(zLine,";",2);
11689    }
11690    qss = quickscan(zLine, qss);
11691    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11692      /* Just swallow single-line whitespace */
11693      echo_group_input(p, zLine);
11694      qss = QSS_Start;
11695      continue;
11696    }
11697    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11698      echo_group_input(p, zLine);
11699      if( zLine[0]=='.' ){
11700        rc = do_meta_command(zLine, p);
11701        if( rc==2 ){ /* exit requested */
11702          break;
11703        }else if( rc ){
11704          errCnt++;
11705        }
11706      }
11707      qss = QSS_Start;
11708      continue;
11709    }
11710    /* No single-line dispositions remain; accumulate line(s). */
11711    nLine = strlen(zLine);
11712    if( nSql+nLine+2>=nAlloc ){
11713      /* Grow buffer by half-again increments when big. */
11714      nAlloc = nSql+(nSql>>1)+nLine+100;
11715      zSql = realloc(zSql, nAlloc);
11716      shell_check_oom(zSql);
11717    }
11718    if( nSql==0 ){
11719      i64 i;
11720      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11721      assert( nAlloc>0 && zSql!=0 );
11722      memcpy(zSql, zLine+i, nLine+1-i);
11723      startline = p->lineno;
11724      nSql = nLine-i;
11725    }else{
11726      zSql[nSql++] = '\n';
11727      memcpy(zSql+nSql, zLine, nLine+1);
11728      nSql += nLine;
11729    }
11730    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11731      echo_group_input(p, zSql);
11732      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11733      nSql = 0;
11734      if( p->outCount ){
11735        output_reset(p);
11736        p->outCount = 0;
11737      }else{
11738        clearTempFile(p);
11739      }
11740      p->bSafeMode = p->bSafeModePersist;
11741      qss = QSS_Start;
11742    }else if( nSql && QSS_PLAINWHITE(qss) ){
11743      echo_group_input(p, zSql);
11744      nSql = 0;
11745      qss = QSS_Start;
11746    }
11747  }
11748  if( nSql ){
11749    /* This may be incomplete. Let the SQL parser deal with that. */
11750    echo_group_input(p, zSql);
11751    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11752  }
11753  free(zSql);
11754  free(zLine);
11755  --p->inputNesting;
11756  return errCnt>0;
11757}
11758
11759/*
11760** Return a pathname which is the user's home directory.  A
11761** 0 return indicates an error of some kind.
11762*/
11763static char *find_home_dir(int clearFlag){
11764  static char *home_dir = NULL;
11765  if( clearFlag ){
11766    free(home_dir);
11767    home_dir = 0;
11768    return 0;
11769  }
11770  if( home_dir ) return home_dir;
11771
11772#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11773     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11774  {
11775    struct passwd *pwent;
11776    uid_t uid = getuid();
11777    if( (pwent=getpwuid(uid)) != NULL) {
11778      home_dir = pwent->pw_dir;
11779    }
11780  }
11781#endif
11782
11783#if defined(_WIN32_WCE)
11784  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11785   */
11786  home_dir = "/";
11787#else
11788
11789#if defined(_WIN32) || defined(WIN32)
11790  if (!home_dir) {
11791    home_dir = getenv("USERPROFILE");
11792  }
11793#endif
11794
11795  if (!home_dir) {
11796    home_dir = getenv("HOME");
11797  }
11798
11799#if defined(_WIN32) || defined(WIN32)
11800  if (!home_dir) {
11801    char *zDrive, *zPath;
11802    int n;
11803    zDrive = getenv("HOMEDRIVE");
11804    zPath = getenv("HOMEPATH");
11805    if( zDrive && zPath ){
11806      n = strlen30(zDrive) + strlen30(zPath) + 1;
11807      home_dir = malloc( n );
11808      if( home_dir==0 ) return 0;
11809      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11810      return home_dir;
11811    }
11812    home_dir = "c:\\";
11813  }
11814#endif
11815
11816#endif /* !_WIN32_WCE */
11817
11818  if( home_dir ){
11819    i64 n = strlen(home_dir) + 1;
11820    char *z = malloc( n );
11821    if( z ) memcpy(z, home_dir, n);
11822    home_dir = z;
11823  }
11824
11825  return home_dir;
11826}
11827
11828/*
11829** Read input from the file given by sqliterc_override.  Or if that
11830** parameter is NULL, take input from ~/.sqliterc
11831**
11832** Returns the number of errors.
11833*/
11834static void process_sqliterc(
11835  ShellState *p,                  /* Configuration data */
11836  const char *sqliterc_override   /* Name of config file. NULL to use default */
11837){
11838  char *home_dir = NULL;
11839  const char *sqliterc = sqliterc_override;
11840  char *zBuf = 0;
11841  FILE *inSaved = p->in;
11842  int savedLineno = p->lineno;
11843
11844  if (sqliterc == NULL) {
11845    home_dir = find_home_dir(0);
11846    if( home_dir==0 ){
11847      raw_printf(stderr, "-- warning: cannot find home directory;"
11848                      " cannot read ~/.sqliterc\n");
11849      return;
11850    }
11851    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11852    shell_check_oom(zBuf);
11853    sqliterc = zBuf;
11854  }
11855  p->in = fopen(sqliterc,"rb");
11856  if( p->in ){
11857    if( stdin_is_interactive ){
11858      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11859    }
11860    if( process_input(p) && bail_on_error ) exit(1);
11861    fclose(p->in);
11862  }else if( sqliterc_override!=0 ){
11863    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11864    if( bail_on_error ) exit(1);
11865  }
11866  p->in = inSaved;
11867  p->lineno = savedLineno;
11868  sqlite3_free(zBuf);
11869}
11870
11871/*
11872** Show available command line options
11873*/
11874static const char zOptions[] =
11875#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11876  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11877#endif
11878  "   -append              append the database to the end of the file\n"
11879  "   -ascii               set output mode to 'ascii'\n"
11880  "   -bail                stop after hitting an error\n"
11881  "   -batch               force batch I/O\n"
11882  "   -box                 set output mode to 'box'\n"
11883  "   -column              set output mode to 'column'\n"
11884  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11885  "   -csv                 set output mode to 'csv'\n"
11886#if !defined(SQLITE_OMIT_DESERIALIZE)
11887  "   -deserialize         open the database using sqlite3_deserialize()\n"
11888#endif
11889  "   -echo                print inputs before execution\n"
11890  "   -init FILENAME       read/process named file\n"
11891  "   -[no]header          turn headers on or off\n"
11892#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11893  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11894#endif
11895  "   -help                show this message\n"
11896  "   -html                set output mode to HTML\n"
11897  "   -interactive         force interactive I/O\n"
11898  "   -json                set output mode to 'json'\n"
11899  "   -line                set output mode to 'line'\n"
11900  "   -list                set output mode to 'list'\n"
11901  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11902  "   -markdown            set output mode to 'markdown'\n"
11903#if !defined(SQLITE_OMIT_DESERIALIZE)
11904  "   -maxsize N           maximum size for a --deserialize database\n"
11905#endif
11906  "   -memtrace            trace all memory allocations and deallocations\n"
11907  "   -mmap N              default mmap size set to N\n"
11908#ifdef SQLITE_ENABLE_MULTIPLEX
11909  "   -multiplex           enable the multiplexor VFS\n"
11910#endif
11911  "   -newline SEP         set output row separator. Default: '\\n'\n"
11912  "   -nofollow            refuse to open symbolic links to database files\n"
11913  "   -nonce STRING        set the safe-mode escape nonce\n"
11914  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11915  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11916  "   -quote               set output mode to 'quote'\n"
11917  "   -readonly            open the database read-only\n"
11918  "   -safe                enable safe-mode\n"
11919  "   -separator SEP       set output column separator. Default: '|'\n"
11920#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11921  "   -sorterref SIZE      sorter references threshold size\n"
11922#endif
11923  "   -stats               print memory stats before each finalize\n"
11924  "   -table               set output mode to 'table'\n"
11925  "   -tabs                set output mode to 'tabs'\n"
11926  "   -version             show SQLite version\n"
11927  "   -vfs NAME            use NAME as the default VFS\n"
11928#ifdef SQLITE_ENABLE_VFSTRACE
11929  "   -vfstrace            enable tracing of all VFS calls\n"
11930#endif
11931#ifdef SQLITE_HAVE_ZLIB
11932  "   -zip                 open the file as a ZIP Archive\n"
11933#endif
11934;
11935static void usage(int showDetail){
11936  utf8_printf(stderr,
11937      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11938      "FILENAME is the name of an SQLite database. A new database is created\n"
11939      "if the file does not previously exist.\n", Argv0);
11940  if( showDetail ){
11941    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11942  }else{
11943    raw_printf(stderr, "Use the -help option for additional information\n");
11944  }
11945  exit(1);
11946}
11947
11948/*
11949** Internal check:  Verify that the SQLite is uninitialized.  Print a
11950** error message if it is initialized.
11951*/
11952static void verify_uninitialized(void){
11953  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11954    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11955                        " initialization.\n");
11956  }
11957}
11958
11959/*
11960** Initialize the state information in data
11961*/
11962static void main_init(ShellState *data) {
11963  memset(data, 0, sizeof(*data));
11964  data->normalMode = data->cMode = data->mode = MODE_List;
11965  data->autoExplain = 1;
11966  data->pAuxDb = &data->aAuxDb[0];
11967  memcpy(data->colSeparator,SEP_Column, 2);
11968  memcpy(data->rowSeparator,SEP_Row, 2);
11969  data->showHeader = 0;
11970  data->shellFlgs = SHFLG_Lookaside;
11971  verify_uninitialized();
11972  sqlite3_config(SQLITE_CONFIG_URI, 1);
11973  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11974  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11975  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11976  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11977}
11978
11979/*
11980** Output text to the console in a font that attracts extra attention.
11981*/
11982#ifdef _WIN32
11983static void printBold(const char *zText){
11984#if !SQLITE_OS_WINRT
11985  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11986  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11987  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11988  SetConsoleTextAttribute(out,
11989         FOREGROUND_RED|FOREGROUND_INTENSITY
11990  );
11991#endif
11992  printf("%s", zText);
11993#if !SQLITE_OS_WINRT
11994  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11995#endif
11996}
11997#else
11998static void printBold(const char *zText){
11999  printf("\033[1m%s\033[0m", zText);
12000}
12001#endif
12002
12003/*
12004** Get the argument to an --option.  Throw an error and die if no argument
12005** is available.
12006*/
12007static char *cmdline_option_value(int argc, char **argv, int i){
12008  if( i==argc ){
12009    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
12010            argv[0], argv[argc-1]);
12011    exit(1);
12012  }
12013  return argv[i];
12014}
12015
12016#ifndef SQLITE_SHELL_IS_UTF8
12017#  if (defined(_WIN32) || defined(WIN32)) \
12018   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12019#    define SQLITE_SHELL_IS_UTF8          (0)
12020#  else
12021#    define SQLITE_SHELL_IS_UTF8          (1)
12022#  endif
12023#endif
12024
12025#ifdef SQLITE_SHELL_FIDDLE
12026#  define main fiddle_main
12027#endif
12028
12029#if SQLITE_SHELL_IS_UTF8
12030int SQLITE_CDECL main(int argc, char **argv){
12031#else
12032int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12033  char **argv;
12034#endif
12035#ifdef SQLITE_DEBUG
12036  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
12037#endif
12038  char *zErrMsg = 0;
12039#ifdef SQLITE_SHELL_FIDDLE
12040#  define data shellState
12041#else
12042  ShellState data;
12043#endif
12044  const char *zInitFile = 0;
12045  int i;
12046  int rc = 0;
12047  int warnInmemoryDb = 0;
12048  int readStdin = 1;
12049  int nCmd = 0;
12050  char **azCmd = 0;
12051  const char *zVfs = 0;           /* Value of -vfs command-line option */
12052#if !SQLITE_SHELL_IS_UTF8
12053  char **argvToFree = 0;
12054  int argcToFree = 0;
12055#endif
12056
12057  setBinaryMode(stdin, 0);
12058  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12059#ifdef SQLITE_SHELL_FIDDLE
12060  stdin_is_interactive = 0;
12061  stdout_is_console = 1;
12062  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
12063#else
12064  stdin_is_interactive = isatty(0);
12065  stdout_is_console = isatty(1);
12066#endif
12067
12068#if !defined(_WIN32_WCE)
12069  if( getenv("SQLITE_DEBUG_BREAK") ){
12070    if( isatty(0) && isatty(2) ){
12071      fprintf(stderr,
12072          "attach debugger to process %d and press any key to continue.\n",
12073          GETPID());
12074      fgetc(stdin);
12075    }else{
12076#if defined(_WIN32) || defined(WIN32)
12077#if SQLITE_OS_WINRT
12078      __debugbreak();
12079#else
12080      DebugBreak();
12081#endif
12082#elif defined(SIGTRAP)
12083      raise(SIGTRAP);
12084#endif
12085    }
12086  }
12087#endif
12088
12089#if USE_SYSTEM_SQLITE+0!=1
12090  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12091    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12092            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12093    exit(1);
12094  }
12095#endif
12096  main_init(&data);
12097
12098  /* On Windows, we must translate command-line arguments into UTF-8.
12099  ** The SQLite memory allocator subsystem has to be enabled in order to
12100  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12101  ** subsequent sqlite3_config() calls will work.  So copy all results into
12102  ** memory that does not come from the SQLite memory allocator.
12103  */
12104#if !SQLITE_SHELL_IS_UTF8
12105  sqlite3_initialize();
12106  argvToFree = malloc(sizeof(argv[0])*argc*2);
12107  shell_check_oom(argvToFree);
12108  argcToFree = argc;
12109  argv = argvToFree + argc;
12110  for(i=0; i<argc; i++){
12111    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12112    i64 n;
12113    shell_check_oom(z);
12114    n = strlen(z);
12115    argv[i] = malloc( n+1 );
12116    shell_check_oom(argv[i]);
12117    memcpy(argv[i], z, n+1);
12118    argvToFree[i] = argv[i];
12119    sqlite3_free(z);
12120  }
12121  sqlite3_shutdown();
12122#endif
12123
12124  assert( argc>=1 && argv && argv[0] );
12125  Argv0 = argv[0];
12126
12127  /* Make sure we have a valid signal handler early, before anything
12128  ** else is done.
12129  */
12130#ifdef SIGINT
12131  signal(SIGINT, interrupt_handler);
12132#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12133  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12134#endif
12135
12136#ifdef SQLITE_SHELL_DBNAME_PROC
12137  {
12138    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12139    ** of a C-function that will provide the name of the database file.  Use
12140    ** this compile-time option to embed this shell program in larger
12141    ** applications. */
12142    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12143    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12144    warnInmemoryDb = 0;
12145  }
12146#endif
12147
12148  /* Do an initial pass through the command-line argument to locate
12149  ** the name of the database file, the name of the initialization file,
12150  ** the size of the alternative malloc heap,
12151  ** and the first command to execute.
12152  */
12153  verify_uninitialized();
12154  for(i=1; i<argc; i++){
12155    char *z;
12156    z = argv[i];
12157    if( z[0]!='-' ){
12158      if( data.aAuxDb->zDbFilename==0 ){
12159        data.aAuxDb->zDbFilename = z;
12160      }else{
12161        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12162        ** mean that nothing is read from stdin */
12163        readStdin = 0;
12164        nCmd++;
12165        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12166        shell_check_oom(azCmd);
12167        azCmd[nCmd-1] = z;
12168      }
12169    }
12170    if( z[1]=='-' ) z++;
12171    if( strcmp(z,"-separator")==0
12172     || strcmp(z,"-nullvalue")==0
12173     || strcmp(z,"-newline")==0
12174     || strcmp(z,"-cmd")==0
12175    ){
12176      (void)cmdline_option_value(argc, argv, ++i);
12177    }else if( strcmp(z,"-init")==0 ){
12178      zInitFile = cmdline_option_value(argc, argv, ++i);
12179    }else if( strcmp(z,"-batch")==0 ){
12180      /* Need to check for batch mode here to so we can avoid printing
12181      ** informational messages (like from process_sqliterc) before
12182      ** we do the actual processing of arguments later in a second pass.
12183      */
12184      stdin_is_interactive = 0;
12185    }else if( strcmp(z,"-heap")==0 ){
12186#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12187      const char *zSize;
12188      sqlite3_int64 szHeap;
12189
12190      zSize = cmdline_option_value(argc, argv, ++i);
12191      szHeap = integerValue(zSize);
12192      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12193      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12194#else
12195      (void)cmdline_option_value(argc, argv, ++i);
12196#endif
12197    }else if( strcmp(z,"-pagecache")==0 ){
12198      sqlite3_int64 n, sz;
12199      sz = integerValue(cmdline_option_value(argc,argv,++i));
12200      if( sz>70000 ) sz = 70000;
12201      if( sz<0 ) sz = 0;
12202      n = integerValue(cmdline_option_value(argc,argv,++i));
12203      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12204        n = 0xffffffffffffLL/sz;
12205      }
12206      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12207                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12208      data.shellFlgs |= SHFLG_Pagecache;
12209    }else if( strcmp(z,"-lookaside")==0 ){
12210      int n, sz;
12211      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12212      if( sz<0 ) sz = 0;
12213      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12214      if( n<0 ) n = 0;
12215      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12216      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12217    }else if( strcmp(z,"-threadsafe")==0 ){
12218      int n;
12219      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12220      switch( n ){
12221         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12222         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12223         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12224      }
12225#ifdef SQLITE_ENABLE_VFSTRACE
12226    }else if( strcmp(z,"-vfstrace")==0 ){
12227      extern int vfstrace_register(
12228         const char *zTraceName,
12229         const char *zOldVfsName,
12230         int (*xOut)(const char*,void*),
12231         void *pOutArg,
12232         int makeDefault
12233      );
12234      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12235#endif
12236#ifdef SQLITE_ENABLE_MULTIPLEX
12237    }else if( strcmp(z,"-multiplex")==0 ){
12238      extern int sqlite3_multiple_initialize(const char*,int);
12239      sqlite3_multiplex_initialize(0, 1);
12240#endif
12241    }else if( strcmp(z,"-mmap")==0 ){
12242      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12243      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12244#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12245    }else if( strcmp(z,"-sorterref")==0 ){
12246      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12247      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12248#endif
12249    }else if( strcmp(z,"-vfs")==0 ){
12250      zVfs = cmdline_option_value(argc, argv, ++i);
12251#ifdef SQLITE_HAVE_ZLIB
12252    }else if( strcmp(z,"-zip")==0 ){
12253      data.openMode = SHELL_OPEN_ZIPFILE;
12254#endif
12255    }else if( strcmp(z,"-append")==0 ){
12256      data.openMode = SHELL_OPEN_APPENDVFS;
12257#ifndef SQLITE_OMIT_DESERIALIZE
12258    }else if( strcmp(z,"-deserialize")==0 ){
12259      data.openMode = SHELL_OPEN_DESERIALIZE;
12260    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12261      data.szMax = integerValue(argv[++i]);
12262#endif
12263    }else if( strcmp(z,"-readonly")==0 ){
12264      data.openMode = SHELL_OPEN_READONLY;
12265    }else if( strcmp(z,"-nofollow")==0 ){
12266      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12267#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12268    }else if( strncmp(z, "-A",2)==0 ){
12269      /* All remaining command-line arguments are passed to the ".archive"
12270      ** command, so ignore them */
12271      break;
12272#endif
12273    }else if( strcmp(z, "-memtrace")==0 ){
12274      sqlite3MemTraceActivate(stderr);
12275    }else if( strcmp(z,"-bail")==0 ){
12276      bail_on_error = 1;
12277    }else if( strcmp(z,"-nonce")==0 ){
12278      free(data.zNonce);
12279      data.zNonce = strdup(argv[++i]);
12280    }else if( strcmp(z,"-safe")==0 ){
12281      /* no-op - catch this on the second pass */
12282    }
12283  }
12284  verify_uninitialized();
12285
12286
12287#ifdef SQLITE_SHELL_INIT_PROC
12288  {
12289    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12290    ** of a C-function that will perform initialization actions on SQLite that
12291    ** occur just before or after sqlite3_initialize(). Use this compile-time
12292    ** option to embed this shell program in larger applications. */
12293    extern void SQLITE_SHELL_INIT_PROC(void);
12294    SQLITE_SHELL_INIT_PROC();
12295  }
12296#else
12297  /* All the sqlite3_config() calls have now been made. So it is safe
12298  ** to call sqlite3_initialize() and process any command line -vfs option. */
12299  sqlite3_initialize();
12300#endif
12301
12302  if( zVfs ){
12303    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12304    if( pVfs ){
12305      sqlite3_vfs_register(pVfs, 1);
12306    }else{
12307      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12308      exit(1);
12309    }
12310  }
12311
12312  if( data.pAuxDb->zDbFilename==0 ){
12313#ifndef SQLITE_OMIT_MEMORYDB
12314    data.pAuxDb->zDbFilename = ":memory:";
12315    warnInmemoryDb = argc==1;
12316#else
12317    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12318    return 1;
12319#endif
12320  }
12321  data.out = stdout;
12322#ifndef SQLITE_SHELL_FIDDLE
12323  sqlite3_appendvfs_init(0,0,0);
12324#endif
12325
12326  /* Go ahead and open the database file if it already exists.  If the
12327  ** file does not exist, delay opening it.  This prevents empty database
12328  ** files from being created if a user mistypes the database name argument
12329  ** to the sqlite command-line tool.
12330  */
12331  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12332    open_db(&data, 0);
12333  }
12334
12335  /* Process the initialization file if there is one.  If no -init option
12336  ** is given on the command line, look for a file named ~/.sqliterc and
12337  ** try to process it.
12338  */
12339  process_sqliterc(&data,zInitFile);
12340
12341  /* Make a second pass through the command-line argument and set
12342  ** options.  This second pass is delayed until after the initialization
12343  ** file is processed so that the command-line arguments will override
12344  ** settings in the initialization file.
12345  */
12346  for(i=1; i<argc; i++){
12347    char *z = argv[i];
12348    if( z[0]!='-' ) continue;
12349    if( z[1]=='-' ){ z++; }
12350    if( strcmp(z,"-init")==0 ){
12351      i++;
12352    }else if( strcmp(z,"-html")==0 ){
12353      data.mode = MODE_Html;
12354    }else if( strcmp(z,"-list")==0 ){
12355      data.mode = MODE_List;
12356    }else if( strcmp(z,"-quote")==0 ){
12357      data.mode = MODE_Quote;
12358      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12359      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12360    }else if( strcmp(z,"-line")==0 ){
12361      data.mode = MODE_Line;
12362    }else if( strcmp(z,"-column")==0 ){
12363      data.mode = MODE_Column;
12364    }else if( strcmp(z,"-json")==0 ){
12365      data.mode = MODE_Json;
12366    }else if( strcmp(z,"-markdown")==0 ){
12367      data.mode = MODE_Markdown;
12368    }else if( strcmp(z,"-table")==0 ){
12369      data.mode = MODE_Table;
12370    }else if( strcmp(z,"-box")==0 ){
12371      data.mode = MODE_Box;
12372    }else if( strcmp(z,"-csv")==0 ){
12373      data.mode = MODE_Csv;
12374      memcpy(data.colSeparator,",",2);
12375#ifdef SQLITE_HAVE_ZLIB
12376    }else if( strcmp(z,"-zip")==0 ){
12377      data.openMode = SHELL_OPEN_ZIPFILE;
12378#endif
12379    }else if( strcmp(z,"-append")==0 ){
12380      data.openMode = SHELL_OPEN_APPENDVFS;
12381#ifndef SQLITE_OMIT_DESERIALIZE
12382    }else if( strcmp(z,"-deserialize")==0 ){
12383      data.openMode = SHELL_OPEN_DESERIALIZE;
12384    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12385      data.szMax = integerValue(argv[++i]);
12386#endif
12387    }else if( strcmp(z,"-readonly")==0 ){
12388      data.openMode = SHELL_OPEN_READONLY;
12389    }else if( strcmp(z,"-nofollow")==0 ){
12390      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12391    }else if( strcmp(z,"-ascii")==0 ){
12392      data.mode = MODE_Ascii;
12393      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12394      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12395    }else if( strcmp(z,"-tabs")==0 ){
12396      data.mode = MODE_List;
12397      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12398      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12399    }else if( strcmp(z,"-separator")==0 ){
12400      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12401                       "%s",cmdline_option_value(argc,argv,++i));
12402    }else if( strcmp(z,"-newline")==0 ){
12403      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12404                       "%s",cmdline_option_value(argc,argv,++i));
12405    }else if( strcmp(z,"-nullvalue")==0 ){
12406      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12407                       "%s",cmdline_option_value(argc,argv,++i));
12408    }else if( strcmp(z,"-header")==0 ){
12409      data.showHeader = 1;
12410      ShellSetFlag(&data, SHFLG_HeaderSet);
12411     }else if( strcmp(z,"-noheader")==0 ){
12412      data.showHeader = 0;
12413      ShellSetFlag(&data, SHFLG_HeaderSet);
12414    }else if( strcmp(z,"-echo")==0 ){
12415      ShellSetFlag(&data, SHFLG_Echo);
12416    }else if( strcmp(z,"-eqp")==0 ){
12417      data.autoEQP = AUTOEQP_on;
12418    }else if( strcmp(z,"-eqpfull")==0 ){
12419      data.autoEQP = AUTOEQP_full;
12420    }else if( strcmp(z,"-stats")==0 ){
12421      data.statsOn = 1;
12422    }else if( strcmp(z,"-scanstats")==0 ){
12423      data.scanstatsOn = 1;
12424    }else if( strcmp(z,"-backslash")==0 ){
12425      /* Undocumented command-line option: -backslash
12426      ** Causes C-style backslash escapes to be evaluated in SQL statements
12427      ** prior to sending the SQL into SQLite.  Useful for injecting
12428      ** crazy bytes in the middle of SQL statements for testing and debugging.
12429      */
12430      ShellSetFlag(&data, SHFLG_Backslash);
12431    }else if( strcmp(z,"-bail")==0 ){
12432      /* No-op.  The bail_on_error flag should already be set. */
12433    }else if( strcmp(z,"-version")==0 ){
12434      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12435      return 0;
12436    }else if( strcmp(z,"-interactive")==0 ){
12437      stdin_is_interactive = 1;
12438    }else if( strcmp(z,"-batch")==0 ){
12439      stdin_is_interactive = 0;
12440    }else if( strcmp(z,"-heap")==0 ){
12441      i++;
12442    }else if( strcmp(z,"-pagecache")==0 ){
12443      i+=2;
12444    }else if( strcmp(z,"-lookaside")==0 ){
12445      i+=2;
12446    }else if( strcmp(z,"-threadsafe")==0 ){
12447      i+=2;
12448    }else if( strcmp(z,"-nonce")==0 ){
12449      i += 2;
12450    }else if( strcmp(z,"-mmap")==0 ){
12451      i++;
12452    }else if( strcmp(z,"-memtrace")==0 ){
12453      i++;
12454#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12455    }else if( strcmp(z,"-sorterref")==0 ){
12456      i++;
12457#endif
12458    }else if( strcmp(z,"-vfs")==0 ){
12459      i++;
12460#ifdef SQLITE_ENABLE_VFSTRACE
12461    }else if( strcmp(z,"-vfstrace")==0 ){
12462      i++;
12463#endif
12464#ifdef SQLITE_ENABLE_MULTIPLEX
12465    }else if( strcmp(z,"-multiplex")==0 ){
12466      i++;
12467#endif
12468    }else if( strcmp(z,"-help")==0 ){
12469      usage(1);
12470    }else if( strcmp(z,"-cmd")==0 ){
12471      /* Run commands that follow -cmd first and separately from commands
12472      ** that simply appear on the command-line.  This seems goofy.  It would
12473      ** be better if all commands ran in the order that they appear.  But
12474      ** we retain the goofy behavior for historical compatibility. */
12475      if( i==argc-1 ) break;
12476      z = cmdline_option_value(argc,argv,++i);
12477      if( z[0]=='.' ){
12478        rc = do_meta_command(z, &data);
12479        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12480      }else{
12481        open_db(&data, 0);
12482        rc = shell_exec(&data, z, &zErrMsg);
12483        if( zErrMsg!=0 ){
12484          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12485          if( bail_on_error ) return rc!=0 ? rc : 1;
12486        }else if( rc!=0 ){
12487          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12488          if( bail_on_error ) return rc;
12489        }
12490      }
12491#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12492    }else if( strncmp(z, "-A", 2)==0 ){
12493      if( nCmd>0 ){
12494        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12495                            " with \"%s\"\n", z);
12496        return 1;
12497      }
12498      open_db(&data, OPEN_DB_ZIPFILE);
12499      if( z[2] ){
12500        argv[i] = &z[2];
12501        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12502      }else{
12503        arDotCommand(&data, 1, argv+i, argc-i);
12504      }
12505      readStdin = 0;
12506      break;
12507#endif
12508    }else if( strcmp(z,"-safe")==0 ){
12509      data.bSafeMode = data.bSafeModePersist = 1;
12510    }else{
12511      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12512      raw_printf(stderr,"Use -help for a list of options.\n");
12513      return 1;
12514    }
12515    data.cMode = data.mode;
12516  }
12517
12518  if( !readStdin ){
12519    /* Run all arguments that do not begin with '-' as if they were separate
12520    ** command-line inputs, except for the argToSkip argument which contains
12521    ** the database filename.
12522    */
12523    for(i=0; i<nCmd; i++){
12524      if( azCmd[i][0]=='.' ){
12525        rc = do_meta_command(azCmd[i], &data);
12526        if( rc ){
12527          free(azCmd);
12528          return rc==2 ? 0 : rc;
12529        }
12530      }else{
12531        open_db(&data, 0);
12532        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12533        if( zErrMsg || rc ){
12534          if( zErrMsg!=0 ){
12535            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12536          }else{
12537            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12538          }
12539          sqlite3_free(zErrMsg);
12540          free(azCmd);
12541          return rc!=0 ? rc : 1;
12542        }
12543      }
12544    }
12545  }else{
12546    /* Run commands received from standard input
12547    */
12548    if( stdin_is_interactive ){
12549      char *zHome;
12550      char *zHistory;
12551      int nHistory;
12552      printf(
12553        "SQLite version %s %.19s\n" /*extra-version-info*/
12554        "Enter \".help\" for usage hints.\n",
12555        sqlite3_libversion(), sqlite3_sourceid()
12556      );
12557      if( warnInmemoryDb ){
12558        printf("Connected to a ");
12559        printBold("transient in-memory database");
12560        printf(".\nUse \".open FILENAME\" to reopen on a "
12561               "persistent database.\n");
12562      }
12563      zHistory = getenv("SQLITE_HISTORY");
12564      if( zHistory ){
12565        zHistory = strdup(zHistory);
12566      }else if( (zHome = find_home_dir(0))!=0 ){
12567        nHistory = strlen30(zHome) + 20;
12568        if( (zHistory = malloc(nHistory))!=0 ){
12569          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12570        }
12571      }
12572      if( zHistory ){ shell_read_history(zHistory); }
12573#if HAVE_READLINE || HAVE_EDITLINE
12574      rl_attempted_completion_function = readline_completion;
12575#elif HAVE_LINENOISE
12576      linenoiseSetCompletionCallback(linenoise_completion);
12577#endif
12578      data.in = 0;
12579      rc = process_input(&data);
12580      if( zHistory ){
12581        shell_stifle_history(2000);
12582        shell_write_history(zHistory);
12583        free(zHistory);
12584      }
12585    }else{
12586      data.in = stdin;
12587      rc = process_input(&data);
12588    }
12589  }
12590#ifndef SQLITE_SHELL_FIDDLE
12591  /* In WASM mode we have to leave the db state in place so that
12592  ** client code can "push" SQL into it after this call returns. */
12593  free(azCmd);
12594  set_table_name(&data, 0);
12595  if( data.db ){
12596    session_close_all(&data, -1);
12597    close_db(data.db);
12598  }
12599  for(i=0; i<ArraySize(data.aAuxDb); i++){
12600    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12601    if( data.aAuxDb[i].db ){
12602      session_close_all(&data, i);
12603      close_db(data.aAuxDb[i].db);
12604    }
12605  }
12606  find_home_dir(1);
12607  output_reset(&data);
12608  data.doXdgOpen = 0;
12609  clearTempFile(&data);
12610#if !SQLITE_SHELL_IS_UTF8
12611  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12612  free(argvToFree);
12613#endif
12614  free(data.colWidth);
12615  free(data.zNonce);
12616  /* Clear the global data structure so that valgrind will detect memory
12617  ** leaks */
12618  memset(&data, 0, sizeof(data));
12619#ifdef SQLITE_DEBUG
12620  if( sqlite3_memory_used()>mem_main_enter ){
12621    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12622                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12623  }
12624#endif
12625#endif /* !SQLITE_SHELL_FIDDLE */
12626  return rc;
12627}
12628
12629
12630#ifdef SQLITE_SHELL_FIDDLE
12631/* Only for emcc experimentation purposes. */
12632int fiddle_experiment(int a,int b){
12633  return a + b;
12634}
12635
12636/*
12637** Returns a pointer to the current DB handle.
12638*/
12639sqlite3 * fiddle_db_handle(){
12640  return globalDb;
12641}
12642
12643/*
12644** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12645** "main" is assumed. Returns 0 if no db with the given name is
12646** open.
12647*/
12648sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12649  sqlite3_vfs * pVfs = 0;
12650  if(globalDb){
12651    sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12652                         SQLITE_FCNTL_VFS_POINTER, &pVfs);
12653  }
12654  return pVfs;
12655}
12656
12657/* Only for emcc experimentation purposes. */
12658sqlite3 * fiddle_db_arg(sqlite3 *arg){
12659    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12660    return arg;
12661}
12662
12663/*
12664** Intended to be called via a SharedWorker() while a separate
12665** SharedWorker() (which manages the wasm module) is performing work
12666** which should be interrupted. Unfortunately, SharedWorker is not
12667** portable enough to make real use of.
12668*/
12669void fiddle_interrupt(void){
12670  if( globalDb ) sqlite3_interrupt(globalDb);
12671}
12672
12673/*
12674** Returns the filename of the given db name, assuming "main" if
12675** zDbName is NULL. Returns NULL if globalDb is not opened.
12676*/
12677const char * fiddle_db_filename(const char * zDbName){
12678    return globalDb
12679      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12680      : NULL;
12681}
12682
12683/*
12684** Completely wipes out the contents of the currently-opened database
12685** but leaves its storage intact for reuse.
12686*/
12687void fiddle_reset_db(void){
12688  if( globalDb ){
12689    int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12690    if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12691    sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12692  }
12693}
12694
12695/*
12696** Uses the current database's VFS xRead to stream the db file's
12697** contents out to the given callback. The callback gets a single
12698** chunk of size n (its 2nd argument) on each call and must return 0
12699** on success, non-0 on error. This function returns 0 on success,
12700** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12701** code from the callback. Note that this is not thread-friendly: it
12702** expects that it will be the only thread reading the db file and
12703** takes no measures to ensure that is the case.
12704*/
12705int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12706  sqlite3_int64 nSize = 0;
12707  sqlite3_int64 nPos = 0;
12708  sqlite3_file * pFile = 0;
12709  unsigned char buf[1024 * 8];
12710  int nBuf = (int)sizeof(buf);
12711  int rc = shellState.db
12712    ? sqlite3_file_control(shellState.db, "main",
12713                           SQLITE_FCNTL_FILE_POINTER, &pFile)
12714    : SQLITE_NOTFOUND;
12715  if( rc ) return rc;
12716  rc = pFile->pMethods->xFileSize(pFile, &nSize);
12717  if( rc ) return rc;
12718  if(nSize % nBuf){
12719    /* DB size is not an even multiple of the buffer size. Reduce
12720    ** buffer size so that we do not unduly inflate the db size when
12721    ** exporting. */
12722    if(0 == nSize % 4096) nBuf = 4096;
12723    else if(0 == nSize % 2048) nBuf = 2048;
12724    else if(0 == nSize % 1024) nBuf = 1024;
12725    else nBuf = 512;
12726  }
12727  for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12728    rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12729    if(SQLITE_IOERR_SHORT_READ == rc){
12730      rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12731    }
12732    if( 0==rc ) rc = xCallback(buf, nBuf);
12733  }
12734  return rc;
12735}
12736
12737/*
12738** Trivial exportable function for emscripten. It processes zSql as if
12739** it were input to the sqlite3 shell and redirects all output to the
12740** wasm binding. If fiddle_main() has not been called by the time this
12741** is called, this function calls it with a conservative set of
12742** flags.
12743*/
12744void fiddle_exec(const char * zSql){
12745  if(zSql && *zSql){
12746    if('.'==*zSql) puts(zSql);
12747    shellState.wasm.zInput = zSql;
12748    shellState.wasm.zPos = zSql;
12749    process_input(&shellState);
12750    shellState.wasm.zInput = shellState.wasm.zPos = 0;
12751  }
12752}
12753#endif /* SQLITE_SHELL_FIDDLE */
12754