xref: /sqlite-3.40.0/src/shell.c.in (revision 46d43984)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26# define SHELL_STRINGIFY_(f) #f
27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28#ifdef SQLITE_CUSTOM_INCLUDE
29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
42** somewhat for use as a WASM module in a web browser. This flag
43** should only be used when building the "fiddle" web application, as
44** the browser-mode build has much different user input requirements
45** and this build mode rewires the user input subsystem to account for
46** that.
47*/
48
49/*
50** Warning pragmas copied from msvc.h in the core.
51*/
52#if defined(_MSC_VER)
53#pragma warning(disable : 4054)
54#pragma warning(disable : 4055)
55#pragma warning(disable : 4100)
56#pragma warning(disable : 4127)
57#pragma warning(disable : 4130)
58#pragma warning(disable : 4152)
59#pragma warning(disable : 4189)
60#pragma warning(disable : 4206)
61#pragma warning(disable : 4210)
62#pragma warning(disable : 4232)
63#pragma warning(disable : 4244)
64#pragma warning(disable : 4305)
65#pragma warning(disable : 4306)
66#pragma warning(disable : 4702)
67#pragma warning(disable : 4706)
68#endif /* defined(_MSC_VER) */
69
70/*
71** No support for loadable extensions in VxWorks.
72*/
73#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
74# define SQLITE_OMIT_LOAD_EXTENSION 1
75#endif
76
77/*
78** Enable large-file support for fopen() and friends on unix.
79*/
80#ifndef SQLITE_DISABLE_LFS
81# define _LARGE_FILE       1
82# ifndef _FILE_OFFSET_BITS
83#   define _FILE_OFFSET_BITS 64
84# endif
85# define _LARGEFILE_SOURCE 1
86#endif
87
88#include <stdlib.h>
89#include <string.h>
90#include <stdio.h>
91#include <assert.h>
92#include "sqlite3.h"
93typedef sqlite3_int64 i64;
94typedef sqlite3_uint64 u64;
95typedef unsigned char u8;
96#if SQLITE_USER_AUTHENTICATION
97# include "sqlite3userauth.h"
98#endif
99#include <ctype.h>
100#include <stdarg.h>
101
102#if !defined(_WIN32) && !defined(WIN32)
103# include <signal.h>
104# if !defined(__RTP__) && !defined(_WRS_KERNEL)
105#  include <pwd.h>
106# endif
107#endif
108#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
109# include <unistd.h>
110# include <dirent.h>
111# define GETPID getpid
112# if defined(__MINGW32__)
113#  define DIRENT dirent
114#  ifndef S_ISLNK
115#   define S_ISLNK(mode) (0)
116#  endif
117# endif
118#else
119# define GETPID (int)GetCurrentProcessId
120#endif
121#include <sys/types.h>
122#include <sys/stat.h>
123
124#if HAVE_READLINE
125# include <readline/readline.h>
126# include <readline/history.h>
127#endif
128
129#if HAVE_EDITLINE
130# include <editline/readline.h>
131#endif
132
133#if HAVE_EDITLINE || HAVE_READLINE
134
135# define shell_add_history(X) add_history(X)
136# define shell_read_history(X) read_history(X)
137# define shell_write_history(X) write_history(X)
138# define shell_stifle_history(X) stifle_history(X)
139# define shell_readline(X) readline(X)
140
141#elif HAVE_LINENOISE
142
143# include "linenoise.h"
144# define shell_add_history(X) linenoiseHistoryAdd(X)
145# define shell_read_history(X) linenoiseHistoryLoad(X)
146# define shell_write_history(X) linenoiseHistorySave(X)
147# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
148# define shell_readline(X) linenoise(X)
149
150#else
151
152# define shell_read_history(X)
153# define shell_write_history(X)
154# define shell_stifle_history(X)
155
156# define SHELL_USE_LOCAL_GETLINE 1
157#endif
158
159
160#if defined(_WIN32) || defined(WIN32)
161# if SQLITE_OS_WINRT
162#  define SQLITE_OMIT_POPEN 1
163# else
164#  include <io.h>
165#  include <fcntl.h>
166#  define isatty(h) _isatty(h)
167#  ifndef access
168#   define access(f,m) _access((f),(m))
169#  endif
170#  ifndef unlink
171#   define unlink _unlink
172#  endif
173#  ifndef strdup
174#   define strdup _strdup
175#  endif
176#  undef popen
177#  define popen _popen
178#  undef pclose
179#  define pclose _pclose
180# endif
181#else
182 /* Make sure isatty() has a prototype. */
183 extern int isatty(int);
184
185# if !defined(__RTP__) && !defined(_WRS_KERNEL)
186  /* popen and pclose are not C89 functions and so are
187  ** sometimes omitted from the <stdio.h> header */
188   extern FILE *popen(const char*,const char*);
189   extern int pclose(FILE*);
190# else
191#  define SQLITE_OMIT_POPEN 1
192# endif
193#endif
194
195#if defined(_WIN32_WCE)
196/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
197 * thus we always assume that we have a console. That can be
198 * overridden with the -batch command line option.
199 */
200#define isatty(x) 1
201#endif
202
203/* ctype macros that work with signed characters */
204#define IsSpace(X)  isspace((unsigned char)X)
205#define IsDigit(X)  isdigit((unsigned char)X)
206#define ToLower(X)  (char)tolower((unsigned char)X)
207
208#if defined(_WIN32) || defined(WIN32)
209#if SQLITE_OS_WINRT
210#include <intrin.h>
211#endif
212#include <windows.h>
213
214/* string conversion routines only needed on Win32 */
215extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
216extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
217extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
218extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
219#endif
220
221/* On Windows, we normally run with output mode of TEXT so that \n characters
222** are automatically translated into \r\n.  However, this behavior needs
223** to be disabled in some cases (ex: when generating CSV output and when
224** rendering quoted strings that contain \n characters).  The following
225** routines take care of that.
226*/
227#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
228static void setBinaryMode(FILE *file, int isOutput){
229  if( isOutput ) fflush(file);
230  _setmode(_fileno(file), _O_BINARY);
231}
232static void setTextMode(FILE *file, int isOutput){
233  if( isOutput ) fflush(file);
234  _setmode(_fileno(file), _O_TEXT);
235}
236#else
237# define setBinaryMode(X,Y)
238# define setTextMode(X,Y)
239#endif
240
241/* True if the timer is enabled */
242static int enableTimer = 0;
243
244/* Return the current wall-clock time */
245static sqlite3_int64 timeOfDay(void){
246  static sqlite3_vfs *clockVfs = 0;
247  sqlite3_int64 t;
248  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
249  if( clockVfs==0 ) return 0;  /* Never actually happens */
250  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
251    clockVfs->xCurrentTimeInt64(clockVfs, &t);
252  }else{
253    double r;
254    clockVfs->xCurrentTime(clockVfs, &r);
255    t = (sqlite3_int64)(r*86400000.0);
256  }
257  return t;
258}
259
260#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
261#include <sys/time.h>
262#include <sys/resource.h>
263
264/* VxWorks does not support getrusage() as far as we can determine */
265#if defined(_WRS_KERNEL) || defined(__RTP__)
266struct rusage {
267  struct timeval ru_utime; /* user CPU time used */
268  struct timeval ru_stime; /* system CPU time used */
269};
270#define getrusage(A,B) memset(B,0,sizeof(*B))
271#endif
272
273/* Saved resource information for the beginning of an operation */
274static struct rusage sBegin;  /* CPU time at start */
275static sqlite3_int64 iBegin;  /* Wall-clock time at start */
276
277/*
278** Begin timing an operation
279*/
280static void beginTimer(void){
281  if( enableTimer ){
282    getrusage(RUSAGE_SELF, &sBegin);
283    iBegin = timeOfDay();
284  }
285}
286
287/* Return the difference of two time_structs in seconds */
288static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
289  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
290         (double)(pEnd->tv_sec - pStart->tv_sec);
291}
292
293/*
294** Print the timing results.
295*/
296static void endTimer(void){
297  if( enableTimer ){
298    sqlite3_int64 iEnd = timeOfDay();
299    struct rusage sEnd;
300    getrusage(RUSAGE_SELF, &sEnd);
301    printf("Run Time: real %.3f user %f sys %f\n",
302       (iEnd - iBegin)*0.001,
303       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
304       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
305  }
306}
307
308#define BEGIN_TIMER beginTimer()
309#define END_TIMER endTimer()
310#define HAS_TIMER 1
311
312#elif (defined(_WIN32) || defined(WIN32))
313
314/* Saved resource information for the beginning of an operation */
315static HANDLE hProcess;
316static FILETIME ftKernelBegin;
317static FILETIME ftUserBegin;
318static sqlite3_int64 ftWallBegin;
319typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
320                                    LPFILETIME, LPFILETIME);
321static GETPROCTIMES getProcessTimesAddr = NULL;
322
323/*
324** Check to see if we have timer support.  Return 1 if necessary
325** support found (or found previously).
326*/
327static int hasTimer(void){
328  if( getProcessTimesAddr ){
329    return 1;
330  } else {
331#if !SQLITE_OS_WINRT
332    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
333    ** versions. See if the version we are running on has it, and if it
334    ** does, save off a pointer to it and the current process handle.
335    */
336    hProcess = GetCurrentProcess();
337    if( hProcess ){
338      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
339      if( NULL != hinstLib ){
340        getProcessTimesAddr =
341            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
342        if( NULL != getProcessTimesAddr ){
343          return 1;
344        }
345        FreeLibrary(hinstLib);
346      }
347    }
348#endif
349  }
350  return 0;
351}
352
353/*
354** Begin timing an operation
355*/
356static void beginTimer(void){
357  if( enableTimer && getProcessTimesAddr ){
358    FILETIME ftCreation, ftExit;
359    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
360                        &ftKernelBegin,&ftUserBegin);
361    ftWallBegin = timeOfDay();
362  }
363}
364
365/* Return the difference of two FILETIME structs in seconds */
366static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
367  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
368  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
369  return (double) ((i64End - i64Start) / 10000000.0);
370}
371
372/*
373** Print the timing results.
374*/
375static void endTimer(void){
376  if( enableTimer && getProcessTimesAddr){
377    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
378    sqlite3_int64 ftWallEnd = timeOfDay();
379    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
380    printf("Run Time: real %.3f user %f sys %f\n",
381       (ftWallEnd - ftWallBegin)*0.001,
382       timeDiff(&ftUserBegin, &ftUserEnd),
383       timeDiff(&ftKernelBegin, &ftKernelEnd));
384  }
385}
386
387#define BEGIN_TIMER beginTimer()
388#define END_TIMER endTimer()
389#define HAS_TIMER hasTimer()
390
391#else
392#define BEGIN_TIMER
393#define END_TIMER
394#define HAS_TIMER 0
395#endif
396
397/*
398** Used to prevent warnings about unused parameters
399*/
400#define UNUSED_PARAMETER(x) (void)(x)
401
402/*
403** Number of elements in an array
404*/
405#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
406
407/*
408** If the following flag is set, then command execution stops
409** at an error if we are not interactive.
410*/
411static int bail_on_error = 0;
412
413/*
414** Threat stdin as an interactive input if the following variable
415** is true.  Otherwise, assume stdin is connected to a file or pipe.
416*/
417static int stdin_is_interactive = 1;
418
419/*
420** On Windows systems we have to know if standard output is a console
421** in order to translate UTF-8 into MBCS.  The following variable is
422** true if translation is required.
423*/
424static int stdout_is_console = 1;
425
426/*
427** The following is the open SQLite database.  We make a pointer
428** to this database a static variable so that it can be accessed
429** by the SIGINT handler to interrupt database processing.
430*/
431static sqlite3 *globalDb = 0;
432
433/*
434** True if an interrupt (Control-C) has been received.
435*/
436static volatile int seenInterrupt = 0;
437
438/*
439** This is the name of our program. It is set in main(), used
440** in a number of other places, mostly for error messages.
441*/
442static char *Argv0;
443
444/*
445** Prompt strings. Initialized in main. Settable with
446**   .prompt main continue
447*/
448static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
449static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
450
451/*
452** Render output like fprintf().  Except, if the output is going to the
453** console and if this is running on a Windows machine, translate the
454** output from UTF-8 into MBCS.
455*/
456#if defined(_WIN32) || defined(WIN32)
457void utf8_printf(FILE *out, const char *zFormat, ...){
458  va_list ap;
459  va_start(ap, zFormat);
460  if( stdout_is_console && (out==stdout || out==stderr) ){
461    char *z1 = sqlite3_vmprintf(zFormat, ap);
462    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
463    sqlite3_free(z1);
464    fputs(z2, out);
465    sqlite3_free(z2);
466  }else{
467    vfprintf(out, zFormat, ap);
468  }
469  va_end(ap);
470}
471#elif !defined(utf8_printf)
472# define utf8_printf fprintf
473#endif
474
475/*
476** Render output like fprintf().  This should not be used on anything that
477** includes string formatting (e.g. "%s").
478*/
479#if !defined(raw_printf)
480# define raw_printf fprintf
481#endif
482
483/* Indicate out-of-memory and exit. */
484static void shell_out_of_memory(void){
485  raw_printf(stderr,"Error: out of memory\n");
486  exit(1);
487}
488
489/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
490** out-of-memory error.
491*/
492static void shell_check_oom(void *p){
493  if( p==0 ) shell_out_of_memory();
494}
495
496/*
497** Write I/O traces to the following stream.
498*/
499#ifdef SQLITE_ENABLE_IOTRACE
500static FILE *iotrace = 0;
501#endif
502
503/*
504** This routine works like printf in that its first argument is a
505** format string and subsequent arguments are values to be substituted
506** in place of % fields.  The result of formatting this string
507** is written to iotrace.
508*/
509#ifdef SQLITE_ENABLE_IOTRACE
510static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
511  va_list ap;
512  char *z;
513  if( iotrace==0 ) return;
514  va_start(ap, zFormat);
515  z = sqlite3_vmprintf(zFormat, ap);
516  va_end(ap);
517  utf8_printf(iotrace, "%s", z);
518  sqlite3_free(z);
519}
520#endif
521
522/*
523** Output string zUtf to stream pOut as w characters.  If w is negative,
524** then right-justify the text.  W is the width in UTF-8 characters, not
525** in bytes.  This is different from the %*.*s specification in printf
526** since with %*.*s the width is measured in bytes, not characters.
527*/
528static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
529  int i;
530  int n;
531  int aw = w<0 ? -w : w;
532  for(i=n=0; zUtf[i]; i++){
533    if( (zUtf[i]&0xc0)!=0x80 ){
534      n++;
535      if( n==aw ){
536        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
537        break;
538      }
539    }
540  }
541  if( n>=aw ){
542    utf8_printf(pOut, "%.*s", i, zUtf);
543  }else if( w<0 ){
544    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
545  }else{
546    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
547  }
548}
549
550
551/*
552** Determines if a string is a number of not.
553*/
554static int isNumber(const char *z, int *realnum){
555  if( *z=='-' || *z=='+' ) z++;
556  if( !IsDigit(*z) ){
557    return 0;
558  }
559  z++;
560  if( realnum ) *realnum = 0;
561  while( IsDigit(*z) ){ z++; }
562  if( *z=='.' ){
563    z++;
564    if( !IsDigit(*z) ) return 0;
565    while( IsDigit(*z) ){ z++; }
566    if( realnum ) *realnum = 1;
567  }
568  if( *z=='e' || *z=='E' ){
569    z++;
570    if( *z=='+' || *z=='-' ) z++;
571    if( !IsDigit(*z) ) return 0;
572    while( IsDigit(*z) ){ z++; }
573    if( realnum ) *realnum = 1;
574  }
575  return *z==0;
576}
577
578/*
579** Compute a string length that is limited to what can be stored in
580** lower 30 bits of a 32-bit signed integer.
581*/
582static int strlen30(const char *z){
583  const char *z2 = z;
584  while( *z2 ){ z2++; }
585  return 0x3fffffff & (int)(z2 - z);
586}
587
588/*
589** Return the length of a string in characters.  Multibyte UTF8 characters
590** count as a single character.
591*/
592static int strlenChar(const char *z){
593  int n = 0;
594  while( *z ){
595    if( (0xc0&*(z++))!=0x80 ) n++;
596  }
597  return n;
598}
599
600/*
601** Return open FILE * if zFile exists, can be opened for read
602** and is an ordinary file or a character stream source.
603** Otherwise return 0.
604*/
605static FILE * openChrSource(const char *zFile){
606#ifdef _WIN32
607  struct _stat x = {0};
608# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
609  /* On Windows, open first, then check the stream nature. This order
610  ** is necessary because _stat() and sibs, when checking a named pipe,
611  ** effectively break the pipe as its supplier sees it. */
612  FILE *rv = fopen(zFile, "rb");
613  if( rv==0 ) return 0;
614  if( _fstat(_fileno(rv), &x) != 0
615      || !STAT_CHR_SRC(x.st_mode)){
616    fclose(rv);
617    rv = 0;
618  }
619  return rv;
620#else
621  struct stat x = {0};
622  int rc = stat(zFile, &x);
623# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
624  if( rc!=0 ) return 0;
625  if( STAT_CHR_SRC(x.st_mode) ){
626    return fopen(zFile, "rb");
627  }else{
628    return 0;
629  }
630#endif
631#undef STAT_CHR_SRC
632}
633
634/*
635** This routine reads a line of text from FILE in, stores
636** the text in memory obtained from malloc() and returns a pointer
637** to the text.  NULL is returned at end of file, or if malloc()
638** fails.
639**
640** If zLine is not NULL then it is a malloced buffer returned from
641** a previous call to this routine that may be reused.
642*/
643static char *local_getline(char *zLine, FILE *in){
644  int nLine = zLine==0 ? 0 : 100;
645  int n = 0;
646
647  while( 1 ){
648    if( n+100>nLine ){
649      nLine = nLine*2 + 100;
650      zLine = realloc(zLine, nLine);
651      shell_check_oom(zLine);
652    }
653    if( fgets(&zLine[n], nLine - n, in)==0 ){
654      if( n==0 ){
655        free(zLine);
656        return 0;
657      }
658      zLine[n] = 0;
659      break;
660    }
661    while( zLine[n] ) n++;
662    if( n>0 && zLine[n-1]=='\n' ){
663      n--;
664      if( n>0 && zLine[n-1]=='\r' ) n--;
665      zLine[n] = 0;
666      break;
667    }
668  }
669#if defined(_WIN32) || defined(WIN32)
670  /* For interactive input on Windows systems, translate the
671  ** multi-byte characterset characters into UTF-8. */
672  if( stdin_is_interactive && in==stdin ){
673    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
674    if( zTrans ){
675      int nTrans = strlen30(zTrans)+1;
676      if( nTrans>nLine ){
677        zLine = realloc(zLine, nTrans);
678        shell_check_oom(zLine);
679      }
680      memcpy(zLine, zTrans, nTrans);
681      sqlite3_free(zTrans);
682    }
683  }
684#endif /* defined(_WIN32) || defined(WIN32) */
685  return zLine;
686}
687
688/*
689** Retrieve a single line of input text.
690**
691** If in==0 then read from standard input and prompt before each line.
692** If isContinuation is true, then a continuation prompt is appropriate.
693** If isContinuation is zero, then the main prompt should be used.
694**
695** If zPrior is not NULL then it is a buffer from a prior call to this
696** routine that can be reused.
697**
698** The result is stored in space obtained from malloc() and must either
699** be freed by the caller or else passed back into this routine via the
700** zPrior argument for reuse.
701*/
702#ifndef SQLITE_SHELL_FIDDLE
703static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
704  char *zPrompt;
705  char *zResult;
706  if( in!=0 ){
707    zResult = local_getline(zPrior, in);
708  }else{
709    zPrompt = isContinuation ? continuePrompt : mainPrompt;
710#if SHELL_USE_LOCAL_GETLINE
711    printf("%s", zPrompt);
712    fflush(stdout);
713    zResult = local_getline(zPrior, stdin);
714#else
715    free(zPrior);
716    zResult = shell_readline(zPrompt);
717    if( zResult && *zResult ) shell_add_history(zResult);
718#endif
719  }
720  return zResult;
721}
722#endif /* !SQLITE_SHELL_FIDDLE */
723
724/*
725** Return the value of a hexadecimal digit.  Return -1 if the input
726** is not a hex digit.
727*/
728static int hexDigitValue(char c){
729  if( c>='0' && c<='9' ) return c - '0';
730  if( c>='a' && c<='f' ) return c - 'a' + 10;
731  if( c>='A' && c<='F' ) return c - 'A' + 10;
732  return -1;
733}
734
735/*
736** Interpret zArg as an integer value, possibly with suffixes.
737*/
738static sqlite3_int64 integerValue(const char *zArg){
739  sqlite3_int64 v = 0;
740  static const struct { char *zSuffix; int iMult; } aMult[] = {
741    { "KiB", 1024 },
742    { "MiB", 1024*1024 },
743    { "GiB", 1024*1024*1024 },
744    { "KB",  1000 },
745    { "MB",  1000000 },
746    { "GB",  1000000000 },
747    { "K",   1000 },
748    { "M",   1000000 },
749    { "G",   1000000000 },
750  };
751  int i;
752  int isNeg = 0;
753  if( zArg[0]=='-' ){
754    isNeg = 1;
755    zArg++;
756  }else if( zArg[0]=='+' ){
757    zArg++;
758  }
759  if( zArg[0]=='0' && zArg[1]=='x' ){
760    int x;
761    zArg += 2;
762    while( (x = hexDigitValue(zArg[0]))>=0 ){
763      v = (v<<4) + x;
764      zArg++;
765    }
766  }else{
767    while( IsDigit(zArg[0]) ){
768      v = v*10 + zArg[0] - '0';
769      zArg++;
770    }
771  }
772  for(i=0; i<ArraySize(aMult); i++){
773    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
774      v *= aMult[i].iMult;
775      break;
776    }
777  }
778  return isNeg? -v : v;
779}
780
781/*
782** A variable length string to which one can append text.
783*/
784typedef struct ShellText ShellText;
785struct ShellText {
786  char *z;
787  int n;
788  int nAlloc;
789};
790
791/*
792** Initialize and destroy a ShellText object
793*/
794static void initText(ShellText *p){
795  memset(p, 0, sizeof(*p));
796}
797static void freeText(ShellText *p){
798  free(p->z);
799  initText(p);
800}
801
802/* zIn is either a pointer to a NULL-terminated string in memory obtained
803** from malloc(), or a NULL pointer. The string pointed to by zAppend is
804** added to zIn, and the result returned in memory obtained from malloc().
805** zIn, if it was not NULL, is freed.
806**
807** If the third argument, quote, is not '\0', then it is used as a
808** quote character for zAppend.
809*/
810static void appendText(ShellText *p, const char *zAppend, char quote){
811  int len;
812  int i;
813  int nAppend = strlen30(zAppend);
814
815  len = nAppend+p->n+1;
816  if( quote ){
817    len += 2;
818    for(i=0; i<nAppend; i++){
819      if( zAppend[i]==quote ) len++;
820    }
821  }
822
823  if( p->z==0 || p->n+len>=p->nAlloc ){
824    p->nAlloc = p->nAlloc*2 + len + 20;
825    p->z = realloc(p->z, p->nAlloc);
826    shell_check_oom(p->z);
827  }
828
829  if( quote ){
830    char *zCsr = p->z+p->n;
831    *zCsr++ = quote;
832    for(i=0; i<nAppend; i++){
833      *zCsr++ = zAppend[i];
834      if( zAppend[i]==quote ) *zCsr++ = quote;
835    }
836    *zCsr++ = quote;
837    p->n = (int)(zCsr - p->z);
838    *zCsr = '\0';
839  }else{
840    memcpy(p->z+p->n, zAppend, nAppend);
841    p->n += nAppend;
842    p->z[p->n] = '\0';
843  }
844}
845
846/*
847** Attempt to determine if identifier zName needs to be quoted, either
848** because it contains non-alphanumeric characters, or because it is an
849** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
850** that quoting is required.
851**
852** Return '"' if quoting is required.  Return 0 if no quoting is required.
853*/
854static char quoteChar(const char *zName){
855  int i;
856  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
857  for(i=0; zName[i]; i++){
858    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
859  }
860  return sqlite3_keyword_check(zName, i) ? '"' : 0;
861}
862
863/*
864** Construct a fake object name and column list to describe the structure
865** of the view, virtual table, or table valued function zSchema.zName.
866*/
867static char *shellFakeSchema(
868  sqlite3 *db,            /* The database connection containing the vtab */
869  const char *zSchema,    /* Schema of the database holding the vtab */
870  const char *zName       /* The name of the virtual table */
871){
872  sqlite3_stmt *pStmt = 0;
873  char *zSql;
874  ShellText s;
875  char cQuote;
876  char *zDiv = "(";
877  int nRow = 0;
878
879  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
880                         zSchema ? zSchema : "main", zName);
881  shell_check_oom(zSql);
882  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
883  sqlite3_free(zSql);
884  initText(&s);
885  if( zSchema ){
886    cQuote = quoteChar(zSchema);
887    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
888    appendText(&s, zSchema, cQuote);
889    appendText(&s, ".", 0);
890  }
891  cQuote = quoteChar(zName);
892  appendText(&s, zName, cQuote);
893  while( sqlite3_step(pStmt)==SQLITE_ROW ){
894    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
895    nRow++;
896    appendText(&s, zDiv, 0);
897    zDiv = ",";
898    if( zCol==0 ) zCol = "";
899    cQuote = quoteChar(zCol);
900    appendText(&s, zCol, cQuote);
901  }
902  appendText(&s, ")", 0);
903  sqlite3_finalize(pStmt);
904  if( nRow==0 ){
905    freeText(&s);
906    s.z = 0;
907  }
908  return s.z;
909}
910
911/*
912** SQL function:  shell_module_schema(X)
913**
914** Return a fake schema for the table-valued function or eponymous virtual
915** table X.
916*/
917static void shellModuleSchema(
918  sqlite3_context *pCtx,
919  int nVal,
920  sqlite3_value **apVal
921){
922  const char *zName;
923  char *zFake;
924  UNUSED_PARAMETER(nVal);
925  zName = (const char*)sqlite3_value_text(apVal[0]);
926  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
927  if( zFake ){
928    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
929                        -1, sqlite3_free);
930    free(zFake);
931  }
932}
933
934/*
935** SQL function:  shell_add_schema(S,X)
936**
937** Add the schema name X to the CREATE statement in S and return the result.
938** Examples:
939**
940**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
941**
942** Also works on
943**
944**    CREATE INDEX
945**    CREATE UNIQUE INDEX
946**    CREATE VIEW
947**    CREATE TRIGGER
948**    CREATE VIRTUAL TABLE
949**
950** This UDF is used by the .schema command to insert the schema name of
951** attached databases into the middle of the sqlite_schema.sql field.
952*/
953static void shellAddSchemaName(
954  sqlite3_context *pCtx,
955  int nVal,
956  sqlite3_value **apVal
957){
958  static const char *aPrefix[] = {
959     "TABLE",
960     "INDEX",
961     "UNIQUE INDEX",
962     "VIEW",
963     "TRIGGER",
964     "VIRTUAL TABLE"
965  };
966  int i = 0;
967  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
968  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
969  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
970  sqlite3 *db = sqlite3_context_db_handle(pCtx);
971  UNUSED_PARAMETER(nVal);
972  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
973    for(i=0; i<ArraySize(aPrefix); i++){
974      int n = strlen30(aPrefix[i]);
975      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
976        char *z = 0;
977        char *zFake = 0;
978        if( zSchema ){
979          char cQuote = quoteChar(zSchema);
980          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
981            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
982          }else{
983            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
984          }
985        }
986        if( zName
987         && aPrefix[i][0]=='V'
988         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
989        ){
990          if( z==0 ){
991            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
992          }else{
993            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
994          }
995          free(zFake);
996        }
997        if( z ){
998          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
999          return;
1000        }
1001      }
1002    }
1003  }
1004  sqlite3_result_value(pCtx, apVal[0]);
1005}
1006
1007/*
1008** The source code for several run-time loadable extensions is inserted
1009** below by the ../tool/mkshellc.tcl script.  Before processing that included
1010** code, we need to override some macros to make the included program code
1011** work here in the middle of this regular program.
1012*/
1013#define SQLITE_EXTENSION_INIT1
1014#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1015
1016#if defined(_WIN32) && defined(_MSC_VER)
1017INCLUDE test_windirent.h
1018INCLUDE test_windirent.c
1019#define dirent DIRENT
1020#endif
1021INCLUDE ../ext/misc/memtrace.c
1022INCLUDE ../ext/misc/shathree.c
1023INCLUDE ../ext/misc/uint.c
1024INCLUDE ../ext/misc/decimal.c
1025INCLUDE ../ext/misc/ieee754.c
1026INCLUDE ../ext/misc/series.c
1027INCLUDE ../ext/misc/regexp.c
1028#ifndef SQLITE_SHELL_FIDDLE
1029INCLUDE ../ext/misc/fileio.c
1030INCLUDE ../ext/misc/completion.c
1031INCLUDE ../ext/misc/appendvfs.c
1032#endif
1033#ifdef SQLITE_HAVE_ZLIB
1034INCLUDE ../ext/misc/zipfile.c
1035INCLUDE ../ext/misc/sqlar.c
1036#endif
1037INCLUDE ../ext/expert/sqlite3expert.h
1038INCLUDE ../ext/expert/sqlite3expert.c
1039
1040#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1041INCLUDE ../ext/misc/dbdata.c
1042INCLUDE ../ext/recover/sqlite3recover.h
1043INCLUDE ../ext/recover/sqlite3recover.c
1044#endif
1045
1046#if defined(SQLITE_ENABLE_SESSION)
1047/*
1048** State information for a single open session
1049*/
1050typedef struct OpenSession OpenSession;
1051struct OpenSession {
1052  char *zName;             /* Symbolic name for this session */
1053  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1054  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1055  sqlite3_session *p;      /* The open session */
1056};
1057#endif
1058
1059typedef struct ExpertInfo ExpertInfo;
1060struct ExpertInfo {
1061  sqlite3expert *pExpert;
1062  int bVerbose;
1063};
1064
1065/* A single line in the EQP output */
1066typedef struct EQPGraphRow EQPGraphRow;
1067struct EQPGraphRow {
1068  int iEqpId;           /* ID for this row */
1069  int iParentId;        /* ID of the parent row */
1070  EQPGraphRow *pNext;   /* Next row in sequence */
1071  char zText[1];        /* Text to display for this row */
1072};
1073
1074/* All EQP output is collected into an instance of the following */
1075typedef struct EQPGraph EQPGraph;
1076struct EQPGraph {
1077  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1078  EQPGraphRow *pLast;   /* Last element of the pRow list */
1079  char zPrefix[100];    /* Graph prefix */
1080};
1081
1082/* Parameters affecting columnar mode result display (defaulting together) */
1083typedef struct ColModeOpts {
1084  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1085  u8 bQuote;            /* Quote results for .mode box and table */
1086  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1087} ColModeOpts;
1088#define ColModeOpts_default { 60, 0, 0 }
1089#define ColModeOpts_default_qbox { 60, 1, 0 }
1090
1091/*
1092** State information about the database connection is contained in an
1093** instance of the following structure.
1094*/
1095typedef struct ShellState ShellState;
1096struct ShellState {
1097  sqlite3 *db;           /* The database */
1098  u8 autoExplain;        /* Automatically turn on .explain mode */
1099  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1100  u8 autoEQPtest;        /* autoEQP is in test mode */
1101  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1102  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1103  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1104  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1105  u8 nEqpLevel;          /* Depth of the EQP output graph */
1106  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1107  u8 bSafeMode;          /* True to prohibit unsafe operations */
1108  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1109  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1110  unsigned statsOn;      /* True to display memory stats before each finalize */
1111  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1112  int inputNesting;      /* Track nesting level of .read and other redirects */
1113  int outCount;          /* Revert to stdout when reaching zero */
1114  int cnt;               /* Number of records displayed so far */
1115  int lineno;            /* Line number of last line read from in */
1116  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1117  FILE *in;              /* Read commands from this stream */
1118  FILE *out;             /* Write results here */
1119  FILE *traceOut;        /* Output for sqlite3_trace() */
1120  int nErr;              /* Number of errors seen */
1121  int mode;              /* An output mode setting */
1122  int modePrior;         /* Saved mode */
1123  int cMode;             /* temporary output mode for the current query */
1124  int normalMode;        /* Output mode before ".explain on" */
1125  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1126  int showHeader;        /* True to show column names in List or Column mode */
1127  int nCheck;            /* Number of ".check" commands run */
1128  unsigned nProgress;    /* Number of progress callbacks encountered */
1129  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1130  unsigned flgProgress;  /* Flags for the progress callback */
1131  unsigned shellFlgs;    /* Various flags */
1132  unsigned priorShFlgs;  /* Saved copy of flags */
1133  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1134  char *zDestTable;      /* Name of destination table when MODE_Insert */
1135  char *zTempFile;       /* Temporary file that might need deleting */
1136  char zTestcase[30];    /* Name of current test case */
1137  char colSeparator[20]; /* Column separator character for several modes */
1138  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1139  char colSepPrior[20];  /* Saved column separator */
1140  char rowSepPrior[20];  /* Saved row separator */
1141  int *colWidth;         /* Requested width of each column in columnar modes */
1142  int *actualWidth;      /* Actual width of each column */
1143  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1144  char nullValue[20];    /* The text to print when a NULL comes back from
1145                         ** the database */
1146  char outfile[FILENAME_MAX]; /* Filename for *out */
1147  sqlite3_stmt *pStmt;   /* Current statement if any. */
1148  FILE *pLog;            /* Write log output here */
1149  struct AuxDb {         /* Storage space for auxiliary database connections */
1150    sqlite3 *db;               /* Connection pointer */
1151    const char *zDbFilename;   /* Filename used to open the connection */
1152    char *zFreeOnClose;        /* Free this memory allocation on close */
1153#if defined(SQLITE_ENABLE_SESSION)
1154    int nSession;              /* Number of active sessions */
1155    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1156#endif
1157  } aAuxDb[5],           /* Array of all database connections */
1158    *pAuxDb;             /* Currently active database connection */
1159  int *aiIndent;         /* Array of indents used in MODE_Explain */
1160  int nIndent;           /* Size of array aiIndent[] */
1161  int iIndent;           /* Index of current op in aiIndent[] */
1162  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1163  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1164  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1165#ifdef SQLITE_SHELL_FIDDLE
1166  struct {
1167    const char * zInput; /* Input string from wasm/JS proxy */
1168    const char * zPos;   /* Cursor pos into zInput */
1169  } wasm;
1170#endif
1171};
1172
1173#ifdef SQLITE_SHELL_FIDDLE
1174static ShellState shellState;
1175#endif
1176
1177
1178/* Allowed values for ShellState.autoEQP
1179*/
1180#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1181#define AUTOEQP_on       1           /* Automatic EQP is on */
1182#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1183#define AUTOEQP_full     3           /* Show full EXPLAIN */
1184
1185/* Allowed values for ShellState.openMode
1186*/
1187#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1188#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1189#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1190#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1191#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1192#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1193#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1194
1195/* Allowed values for ShellState.eTraceType
1196*/
1197#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1198#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1199#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1200
1201/* Bits in the ShellState.flgProgress variable */
1202#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1203#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1204                                   ** callback limit is reached, and for each
1205                                   ** top-level SQL statement */
1206#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1207
1208/*
1209** These are the allowed shellFlgs values
1210*/
1211#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1212#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1213#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1214#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1215#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1216#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1217#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1218#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1219#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1220#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1221
1222/*
1223** Macros for testing and setting shellFlgs
1224*/
1225#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1226#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1227#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1228
1229/*
1230** These are the allowed modes.
1231*/
1232#define MODE_Line     0  /* One column per line.  Blank line between records */
1233#define MODE_Column   1  /* One record per line in neat columns */
1234#define MODE_List     2  /* One record per line with a separator */
1235#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1236#define MODE_Html     4  /* Generate an XHTML table */
1237#define MODE_Insert   5  /* Generate SQL "insert" statements */
1238#define MODE_Quote    6  /* Quote values as for SQL */
1239#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1240#define MODE_Csv      8  /* Quote strings, numbers are plain */
1241#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1242#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1243#define MODE_Pretty  11  /* Pretty-print schemas */
1244#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1245#define MODE_Json    13  /* Output JSON */
1246#define MODE_Markdown 14 /* Markdown formatting */
1247#define MODE_Table   15  /* MySQL-style table formatting */
1248#define MODE_Box     16  /* Unicode box-drawing characters */
1249#define MODE_Count   17  /* Output only a count of the rows of output */
1250#define MODE_Off     18  /* No query output shown */
1251
1252static const char *modeDescr[] = {
1253  "line",
1254  "column",
1255  "list",
1256  "semi",
1257  "html",
1258  "insert",
1259  "quote",
1260  "tcl",
1261  "csv",
1262  "explain",
1263  "ascii",
1264  "prettyprint",
1265  "eqp",
1266  "json",
1267  "markdown",
1268  "table",
1269  "box",
1270  "count",
1271  "off"
1272};
1273
1274/*
1275** These are the column/row/line separators used by the various
1276** import/export modes.
1277*/
1278#define SEP_Column    "|"
1279#define SEP_Row       "\n"
1280#define SEP_Tab       "\t"
1281#define SEP_Space     " "
1282#define SEP_Comma     ","
1283#define SEP_CrLf      "\r\n"
1284#define SEP_Unit      "\x1F"
1285#define SEP_Record    "\x1E"
1286
1287/*
1288** Limit input nesting via .read or any other input redirect.
1289** It's not too expensive, so a generous allowance can be made.
1290*/
1291#define MAX_INPUT_NESTING 25
1292
1293/*
1294** A callback for the sqlite3_log() interface.
1295*/
1296static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1297  ShellState *p = (ShellState*)pArg;
1298  if( p->pLog==0 ) return;
1299  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1300  fflush(p->pLog);
1301}
1302
1303/*
1304** SQL function:  shell_putsnl(X)
1305**
1306** Write the text X to the screen (or whatever output is being directed)
1307** adding a newline at the end, and then return X.
1308*/
1309static void shellPutsFunc(
1310  sqlite3_context *pCtx,
1311  int nVal,
1312  sqlite3_value **apVal
1313){
1314  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1315  (void)nVal;
1316  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1317  sqlite3_result_value(pCtx, apVal[0]);
1318}
1319
1320/*
1321** If in safe mode, print an error message described by the arguments
1322** and exit immediately.
1323*/
1324static void failIfSafeMode(
1325  ShellState *p,
1326  const char *zErrMsg,
1327  ...
1328){
1329  if( p->bSafeMode ){
1330    va_list ap;
1331    char *zMsg;
1332    va_start(ap, zErrMsg);
1333    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1334    va_end(ap);
1335    raw_printf(stderr, "line %d: ", p->lineno);
1336    utf8_printf(stderr, "%s\n", zMsg);
1337    exit(1);
1338  }
1339}
1340
1341/*
1342** SQL function:   edit(VALUE)
1343**                 edit(VALUE,EDITOR)
1344**
1345** These steps:
1346**
1347**     (1) Write VALUE into a temporary file.
1348**     (2) Run program EDITOR on that temporary file.
1349**     (3) Read the temporary file back and return its content as the result.
1350**     (4) Delete the temporary file
1351**
1352** If the EDITOR argument is omitted, use the value in the VISUAL
1353** environment variable.  If still there is no EDITOR, through an error.
1354**
1355** Also throw an error if the EDITOR program returns a non-zero exit code.
1356*/
1357#ifndef SQLITE_NOHAVE_SYSTEM
1358static void editFunc(
1359  sqlite3_context *context,
1360  int argc,
1361  sqlite3_value **argv
1362){
1363  const char *zEditor;
1364  char *zTempFile = 0;
1365  sqlite3 *db;
1366  char *zCmd = 0;
1367  int bBin;
1368  int rc;
1369  int hasCRNL = 0;
1370  FILE *f = 0;
1371  sqlite3_int64 sz;
1372  sqlite3_int64 x;
1373  unsigned char *p = 0;
1374
1375  if( argc==2 ){
1376    zEditor = (const char*)sqlite3_value_text(argv[1]);
1377  }else{
1378    zEditor = getenv("VISUAL");
1379  }
1380  if( zEditor==0 ){
1381    sqlite3_result_error(context, "no editor for edit()", -1);
1382    return;
1383  }
1384  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1385    sqlite3_result_error(context, "NULL input to edit()", -1);
1386    return;
1387  }
1388  db = sqlite3_context_db_handle(context);
1389  zTempFile = 0;
1390  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1391  if( zTempFile==0 ){
1392    sqlite3_uint64 r = 0;
1393    sqlite3_randomness(sizeof(r), &r);
1394    zTempFile = sqlite3_mprintf("temp%llx", r);
1395    if( zTempFile==0 ){
1396      sqlite3_result_error_nomem(context);
1397      return;
1398    }
1399  }
1400  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1401  /* When writing the file to be edited, do \n to \r\n conversions on systems
1402  ** that want \r\n line endings */
1403  f = fopen(zTempFile, bBin ? "wb" : "w");
1404  if( f==0 ){
1405    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1406    goto edit_func_end;
1407  }
1408  sz = sqlite3_value_bytes(argv[0]);
1409  if( bBin ){
1410    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1411  }else{
1412    const char *z = (const char*)sqlite3_value_text(argv[0]);
1413    /* Remember whether or not the value originally contained \r\n */
1414    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1415    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1416  }
1417  fclose(f);
1418  f = 0;
1419  if( x!=sz ){
1420    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1421    goto edit_func_end;
1422  }
1423  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1424  if( zCmd==0 ){
1425    sqlite3_result_error_nomem(context);
1426    goto edit_func_end;
1427  }
1428  rc = system(zCmd);
1429  sqlite3_free(zCmd);
1430  if( rc ){
1431    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1432    goto edit_func_end;
1433  }
1434  f = fopen(zTempFile, "rb");
1435  if( f==0 ){
1436    sqlite3_result_error(context,
1437      "edit() cannot reopen temp file after edit", -1);
1438    goto edit_func_end;
1439  }
1440  fseek(f, 0, SEEK_END);
1441  sz = ftell(f);
1442  rewind(f);
1443  p = sqlite3_malloc64( sz+1 );
1444  if( p==0 ){
1445    sqlite3_result_error_nomem(context);
1446    goto edit_func_end;
1447  }
1448  x = fread(p, 1, (size_t)sz, f);
1449  fclose(f);
1450  f = 0;
1451  if( x!=sz ){
1452    sqlite3_result_error(context, "could not read back the whole file", -1);
1453    goto edit_func_end;
1454  }
1455  if( bBin ){
1456    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1457  }else{
1458    sqlite3_int64 i, j;
1459    if( hasCRNL ){
1460      /* If the original contains \r\n then do no conversions back to \n */
1461    }else{
1462      /* If the file did not originally contain \r\n then convert any new
1463      ** \r\n back into \n */
1464      for(i=j=0; i<sz; i++){
1465        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1466        p[j++] = p[i];
1467      }
1468      sz = j;
1469      p[sz] = 0;
1470    }
1471    sqlite3_result_text64(context, (const char*)p, sz,
1472                          sqlite3_free, SQLITE_UTF8);
1473  }
1474  p = 0;
1475
1476edit_func_end:
1477  if( f ) fclose(f);
1478  unlink(zTempFile);
1479  sqlite3_free(zTempFile);
1480  sqlite3_free(p);
1481}
1482#endif /* SQLITE_NOHAVE_SYSTEM */
1483
1484/*
1485** Save or restore the current output mode
1486*/
1487static void outputModePush(ShellState *p){
1488  p->modePrior = p->mode;
1489  p->priorShFlgs = p->shellFlgs;
1490  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1491  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1492}
1493static void outputModePop(ShellState *p){
1494  p->mode = p->modePrior;
1495  p->shellFlgs = p->priorShFlgs;
1496  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1497  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1498}
1499
1500/*
1501** Output the given string as a hex-encoded blob (eg. X'1234' )
1502*/
1503static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1504  int i;
1505  unsigned char *aBlob = (unsigned char*)pBlob;
1506
1507  char *zStr = sqlite3_malloc(nBlob*2 + 1);
1508  shell_check_oom(zStr);
1509
1510  for(i=0; i<nBlob; i++){
1511    static const char aHex[] = {
1512        '0', '1', '2', '3', '4', '5', '6', '7',
1513        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1514    };
1515    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1516    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1517  }
1518  zStr[i*2] = '\0';
1519
1520  raw_printf(out,"X'%s'", zStr);
1521  sqlite3_free(zStr);
1522}
1523
1524/*
1525** Find a string that is not found anywhere in z[].  Return a pointer
1526** to that string.
1527**
1528** Try to use zA and zB first.  If both of those are already found in z[]
1529** then make up some string and store it in the buffer zBuf.
1530*/
1531static const char *unused_string(
1532  const char *z,                    /* Result must not appear anywhere in z */
1533  const char *zA, const char *zB,   /* Try these first */
1534  char *zBuf                        /* Space to store a generated string */
1535){
1536  unsigned i = 0;
1537  if( strstr(z, zA)==0 ) return zA;
1538  if( strstr(z, zB)==0 ) return zB;
1539  do{
1540    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1541  }while( strstr(z,zBuf)!=0 );
1542  return zBuf;
1543}
1544
1545/*
1546** Output the given string as a quoted string using SQL quoting conventions.
1547**
1548** See also: output_quoted_escaped_string()
1549*/
1550static void output_quoted_string(FILE *out, const char *z){
1551  int i;
1552  char c;
1553  setBinaryMode(out, 1);
1554  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1555  if( c==0 ){
1556    utf8_printf(out,"'%s'",z);
1557  }else{
1558    raw_printf(out, "'");
1559    while( *z ){
1560      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1561      if( c=='\'' ) i++;
1562      if( i ){
1563        utf8_printf(out, "%.*s", i, z);
1564        z += i;
1565      }
1566      if( c=='\'' ){
1567        raw_printf(out, "'");
1568        continue;
1569      }
1570      if( c==0 ){
1571        break;
1572      }
1573      z++;
1574    }
1575    raw_printf(out, "'");
1576  }
1577  setTextMode(out, 1);
1578}
1579
1580/*
1581** Output the given string as a quoted string using SQL quoting conventions.
1582** Additionallly , escape the "\n" and "\r" characters so that they do not
1583** get corrupted by end-of-line translation facilities in some operating
1584** systems.
1585**
1586** This is like output_quoted_string() but with the addition of the \r\n
1587** escape mechanism.
1588*/
1589static void output_quoted_escaped_string(FILE *out, const char *z){
1590  int i;
1591  char c;
1592  setBinaryMode(out, 1);
1593  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1594  if( c==0 ){
1595    utf8_printf(out,"'%s'",z);
1596  }else{
1597    const char *zNL = 0;
1598    const char *zCR = 0;
1599    int nNL = 0;
1600    int nCR = 0;
1601    char zBuf1[20], zBuf2[20];
1602    for(i=0; z[i]; i++){
1603      if( z[i]=='\n' ) nNL++;
1604      if( z[i]=='\r' ) nCR++;
1605    }
1606    if( nNL ){
1607      raw_printf(out, "replace(");
1608      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1609    }
1610    if( nCR ){
1611      raw_printf(out, "replace(");
1612      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1613    }
1614    raw_printf(out, "'");
1615    while( *z ){
1616      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1617      if( c=='\'' ) i++;
1618      if( i ){
1619        utf8_printf(out, "%.*s", i, z);
1620        z += i;
1621      }
1622      if( c=='\'' ){
1623        raw_printf(out, "'");
1624        continue;
1625      }
1626      if( c==0 ){
1627        break;
1628      }
1629      z++;
1630      if( c=='\n' ){
1631        raw_printf(out, "%s", zNL);
1632        continue;
1633      }
1634      raw_printf(out, "%s", zCR);
1635    }
1636    raw_printf(out, "'");
1637    if( nCR ){
1638      raw_printf(out, ",'%s',char(13))", zCR);
1639    }
1640    if( nNL ){
1641      raw_printf(out, ",'%s',char(10))", zNL);
1642    }
1643  }
1644  setTextMode(out, 1);
1645}
1646
1647/*
1648** Output the given string as a quoted according to C or TCL quoting rules.
1649*/
1650static void output_c_string(FILE *out, const char *z){
1651  unsigned int c;
1652  fputc('"', out);
1653  while( (c = *(z++))!=0 ){
1654    if( c=='\\' ){
1655      fputc(c, out);
1656      fputc(c, out);
1657    }else if( c=='"' ){
1658      fputc('\\', out);
1659      fputc('"', out);
1660    }else if( c=='\t' ){
1661      fputc('\\', out);
1662      fputc('t', out);
1663    }else if( c=='\n' ){
1664      fputc('\\', out);
1665      fputc('n', out);
1666    }else if( c=='\r' ){
1667      fputc('\\', out);
1668      fputc('r', out);
1669    }else if( !isprint(c&0xff) ){
1670      raw_printf(out, "\\%03o", c&0xff);
1671    }else{
1672      fputc(c, out);
1673    }
1674  }
1675  fputc('"', out);
1676}
1677
1678/*
1679** Output the given string as a quoted according to JSON quoting rules.
1680*/
1681static void output_json_string(FILE *out, const char *z, int n){
1682  unsigned int c;
1683  if( n<0 ) n = (int)strlen(z);
1684  fputc('"', out);
1685  while( n-- ){
1686    c = *(z++);
1687    if( c=='\\' || c=='"' ){
1688      fputc('\\', out);
1689      fputc(c, out);
1690    }else if( c<=0x1f ){
1691      fputc('\\', out);
1692      if( c=='\b' ){
1693        fputc('b', out);
1694      }else if( c=='\f' ){
1695        fputc('f', out);
1696      }else if( c=='\n' ){
1697        fputc('n', out);
1698      }else if( c=='\r' ){
1699        fputc('r', out);
1700      }else if( c=='\t' ){
1701        fputc('t', out);
1702      }else{
1703         raw_printf(out, "u%04x",c);
1704      }
1705    }else{
1706      fputc(c, out);
1707    }
1708  }
1709  fputc('"', out);
1710}
1711
1712/*
1713** Output the given string with characters that are special to
1714** HTML escaped.
1715*/
1716static void output_html_string(FILE *out, const char *z){
1717  int i;
1718  if( z==0 ) z = "";
1719  while( *z ){
1720    for(i=0;   z[i]
1721            && z[i]!='<'
1722            && z[i]!='&'
1723            && z[i]!='>'
1724            && z[i]!='\"'
1725            && z[i]!='\'';
1726        i++){}
1727    if( i>0 ){
1728      utf8_printf(out,"%.*s",i,z);
1729    }
1730    if( z[i]=='<' ){
1731      raw_printf(out,"&lt;");
1732    }else if( z[i]=='&' ){
1733      raw_printf(out,"&amp;");
1734    }else if( z[i]=='>' ){
1735      raw_printf(out,"&gt;");
1736    }else if( z[i]=='\"' ){
1737      raw_printf(out,"&quot;");
1738    }else if( z[i]=='\'' ){
1739      raw_printf(out,"&#39;");
1740    }else{
1741      break;
1742    }
1743    z += i + 1;
1744  }
1745}
1746
1747/*
1748** If a field contains any character identified by a 1 in the following
1749** array, then the string must be quoted for CSV.
1750*/
1751static const char needCsvQuote[] = {
1752  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1753  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1754  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1755  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1756  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1757  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1758  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1759  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1760  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1761  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1762  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1763  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1764  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1765  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1766  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1767  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1768};
1769
1770/*
1771** Output a single term of CSV.  Actually, p->colSeparator is used for
1772** the separator, which may or may not be a comma.  p->nullValue is
1773** the null value.  Strings are quoted if necessary.  The separator
1774** is only issued if bSep is true.
1775*/
1776static void output_csv(ShellState *p, const char *z, int bSep){
1777  FILE *out = p->out;
1778  if( z==0 ){
1779    utf8_printf(out,"%s",p->nullValue);
1780  }else{
1781    unsigned i;
1782    for(i=0; z[i]; i++){
1783      if( needCsvQuote[((unsigned char*)z)[i]] ){
1784        i = 0;
1785        break;
1786      }
1787    }
1788    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1789      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1790      shell_check_oom(zQuoted);
1791      utf8_printf(out, "%s", zQuoted);
1792      sqlite3_free(zQuoted);
1793    }else{
1794      utf8_printf(out, "%s", z);
1795    }
1796  }
1797  if( bSep ){
1798    utf8_printf(p->out, "%s", p->colSeparator);
1799  }
1800}
1801
1802/*
1803** This routine runs when the user presses Ctrl-C
1804*/
1805static void interrupt_handler(int NotUsed){
1806  UNUSED_PARAMETER(NotUsed);
1807  seenInterrupt++;
1808  if( seenInterrupt>2 ) exit(1);
1809  if( globalDb ) sqlite3_interrupt(globalDb);
1810}
1811
1812#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1813/*
1814** This routine runs for console events (e.g. Ctrl-C) on Win32
1815*/
1816static BOOL WINAPI ConsoleCtrlHandler(
1817  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1818){
1819  if( dwCtrlType==CTRL_C_EVENT ){
1820    interrupt_handler(0);
1821    return TRUE;
1822  }
1823  return FALSE;
1824}
1825#endif
1826
1827#ifndef SQLITE_OMIT_AUTHORIZATION
1828/*
1829** This authorizer runs in safe mode.
1830*/
1831static int safeModeAuth(
1832  void *pClientData,
1833  int op,
1834  const char *zA1,
1835  const char *zA2,
1836  const char *zA3,
1837  const char *zA4
1838){
1839  ShellState *p = (ShellState*)pClientData;
1840  static const char *azProhibitedFunctions[] = {
1841    "edit",
1842    "fts3_tokenizer",
1843    "load_extension",
1844    "readfile",
1845    "writefile",
1846    "zipfile",
1847    "zipfile_cds",
1848  };
1849  UNUSED_PARAMETER(zA2);
1850  UNUSED_PARAMETER(zA3);
1851  UNUSED_PARAMETER(zA4);
1852  switch( op ){
1853    case SQLITE_ATTACH: {
1854#ifndef SQLITE_SHELL_FIDDLE
1855      /* In WASM builds the filesystem is a virtual sandbox, so
1856      ** there's no harm in using ATTACH. */
1857      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1858#endif
1859      break;
1860    }
1861    case SQLITE_FUNCTION: {
1862      int i;
1863      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1864        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1865          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1866                         azProhibitedFunctions[i]);
1867        }
1868      }
1869      break;
1870    }
1871  }
1872  return SQLITE_OK;
1873}
1874
1875/*
1876** When the ".auth ON" is set, the following authorizer callback is
1877** invoked.  It always returns SQLITE_OK.
1878*/
1879static int shellAuth(
1880  void *pClientData,
1881  int op,
1882  const char *zA1,
1883  const char *zA2,
1884  const char *zA3,
1885  const char *zA4
1886){
1887  ShellState *p = (ShellState*)pClientData;
1888  static const char *azAction[] = { 0,
1889     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1890     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1891     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1892     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1893     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1894     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1895     "PRAGMA",               "READ",                 "SELECT",
1896     "TRANSACTION",          "UPDATE",               "ATTACH",
1897     "DETACH",               "ALTER_TABLE",          "REINDEX",
1898     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1899     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1900  };
1901  int i;
1902  const char *az[4];
1903  az[0] = zA1;
1904  az[1] = zA2;
1905  az[2] = zA3;
1906  az[3] = zA4;
1907  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1908  for(i=0; i<4; i++){
1909    raw_printf(p->out, " ");
1910    if( az[i] ){
1911      output_c_string(p->out, az[i]);
1912    }else{
1913      raw_printf(p->out, "NULL");
1914    }
1915  }
1916  raw_printf(p->out, "\n");
1917  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1918  return SQLITE_OK;
1919}
1920#endif
1921
1922/*
1923** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1924**
1925** This routine converts some CREATE TABLE statements for shadow tables
1926** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1927**
1928** If the schema statement in z[] contains a start-of-comment and if
1929** sqlite3_complete() returns false, try to terminate the comment before
1930** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
1931*/
1932static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1933  char *zToFree = 0;
1934  if( z==0 ) return;
1935  if( zTail==0 ) return;
1936  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
1937    const char *zOrig = z;
1938    static const char *azTerm[] = { "", "*/", "\n" };
1939    int i;
1940    for(i=0; i<ArraySize(azTerm); i++){
1941      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
1942      if( sqlite3_complete(zNew) ){
1943        size_t n = strlen(zNew);
1944        zNew[n-1] = 0;
1945        zToFree = zNew;
1946        z = zNew;
1947        break;
1948      }
1949      sqlite3_free(zNew);
1950    }
1951  }
1952  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1953    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1954  }else{
1955    utf8_printf(out, "%s%s", z, zTail);
1956  }
1957  sqlite3_free(zToFree);
1958}
1959static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1960  char c = z[n];
1961  z[n] = 0;
1962  printSchemaLine(out, z, zTail);
1963  z[n] = c;
1964}
1965
1966/*
1967** Return true if string z[] has nothing but whitespace and comments to the
1968** end of the first line.
1969*/
1970static int wsToEol(const char *z){
1971  int i;
1972  for(i=0; z[i]; i++){
1973    if( z[i]=='\n' ) return 1;
1974    if( IsSpace(z[i]) ) continue;
1975    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1976    return 0;
1977  }
1978  return 1;
1979}
1980
1981/*
1982** Add a new entry to the EXPLAIN QUERY PLAN data
1983*/
1984static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1985  EQPGraphRow *pNew;
1986  int nText = strlen30(zText);
1987  if( p->autoEQPtest ){
1988    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1989  }
1990  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1991  shell_check_oom(pNew);
1992  pNew->iEqpId = iEqpId;
1993  pNew->iParentId = p2;
1994  memcpy(pNew->zText, zText, nText+1);
1995  pNew->pNext = 0;
1996  if( p->sGraph.pLast ){
1997    p->sGraph.pLast->pNext = pNew;
1998  }else{
1999    p->sGraph.pRow = pNew;
2000  }
2001  p->sGraph.pLast = pNew;
2002}
2003
2004/*
2005** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2006** in p->sGraph.
2007*/
2008static void eqp_reset(ShellState *p){
2009  EQPGraphRow *pRow, *pNext;
2010  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2011    pNext = pRow->pNext;
2012    sqlite3_free(pRow);
2013  }
2014  memset(&p->sGraph, 0, sizeof(p->sGraph));
2015}
2016
2017/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2018** pOld, or return the first such line if pOld is NULL
2019*/
2020static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2021  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2022  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2023  return pRow;
2024}
2025
2026/* Render a single level of the graph that has iEqpId as its parent.  Called
2027** recursively to render sublevels.
2028*/
2029static void eqp_render_level(ShellState *p, int iEqpId){
2030  EQPGraphRow *pRow, *pNext;
2031  int n = strlen30(p->sGraph.zPrefix);
2032  char *z;
2033  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2034    pNext = eqp_next_row(p, iEqpId, pRow);
2035    z = pRow->zText;
2036    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2037                pNext ? "|--" : "`--", z);
2038    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2039      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2040      eqp_render_level(p, pRow->iEqpId);
2041      p->sGraph.zPrefix[n] = 0;
2042    }
2043  }
2044}
2045
2046/*
2047** Display and reset the EXPLAIN QUERY PLAN data
2048*/
2049static void eqp_render(ShellState *p){
2050  EQPGraphRow *pRow = p->sGraph.pRow;
2051  if( pRow ){
2052    if( pRow->zText[0]=='-' ){
2053      if( pRow->pNext==0 ){
2054        eqp_reset(p);
2055        return;
2056      }
2057      utf8_printf(p->out, "%s\n", pRow->zText+3);
2058      p->sGraph.pRow = pRow->pNext;
2059      sqlite3_free(pRow);
2060    }else{
2061      utf8_printf(p->out, "QUERY PLAN\n");
2062    }
2063    p->sGraph.zPrefix[0] = 0;
2064    eqp_render_level(p, 0);
2065    eqp_reset(p);
2066  }
2067}
2068
2069#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2070/*
2071** Progress handler callback.
2072*/
2073static int progress_handler(void *pClientData) {
2074  ShellState *p = (ShellState*)pClientData;
2075  p->nProgress++;
2076  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2077    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2078    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2079    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2080    return 1;
2081  }
2082  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2083    raw_printf(p->out, "Progress %u\n", p->nProgress);
2084  }
2085  return 0;
2086}
2087#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2088
2089/*
2090** Print N dashes
2091*/
2092static void print_dashes(FILE *out, int N){
2093  const char zDash[] = "--------------------------------------------------";
2094  const int nDash = sizeof(zDash) - 1;
2095  while( N>nDash ){
2096    fputs(zDash, out);
2097    N -= nDash;
2098  }
2099  raw_printf(out, "%.*s", N, zDash);
2100}
2101
2102/*
2103** Print a markdown or table-style row separator using ascii-art
2104*/
2105static void print_row_separator(
2106  ShellState *p,
2107  int nArg,
2108  const char *zSep
2109){
2110  int i;
2111  if( nArg>0 ){
2112    fputs(zSep, p->out);
2113    print_dashes(p->out, p->actualWidth[0]+2);
2114    for(i=1; i<nArg; i++){
2115      fputs(zSep, p->out);
2116      print_dashes(p->out, p->actualWidth[i]+2);
2117    }
2118    fputs(zSep, p->out);
2119  }
2120  fputs("\n", p->out);
2121}
2122
2123/*
2124** This is the callback routine that the shell
2125** invokes for each row of a query result.
2126*/
2127static int shell_callback(
2128  void *pArg,
2129  int nArg,        /* Number of result columns */
2130  char **azArg,    /* Text of each result column */
2131  char **azCol,    /* Column names */
2132  int *aiType      /* Column types.  Might be NULL */
2133){
2134  int i;
2135  ShellState *p = (ShellState*)pArg;
2136
2137  if( azArg==0 ) return 0;
2138  switch( p->cMode ){
2139    case MODE_Count:
2140    case MODE_Off: {
2141      break;
2142    }
2143    case MODE_Line: {
2144      int w = 5;
2145      if( azArg==0 ) break;
2146      for(i=0; i<nArg; i++){
2147        int len = strlen30(azCol[i] ? azCol[i] : "");
2148        if( len>w ) w = len;
2149      }
2150      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2151      for(i=0; i<nArg; i++){
2152        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2153                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2154      }
2155      break;
2156    }
2157    case MODE_Explain: {
2158      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2159      if( nArg>ArraySize(aExplainWidth) ){
2160        nArg = ArraySize(aExplainWidth);
2161      }
2162      if( p->cnt++==0 ){
2163        for(i=0; i<nArg; i++){
2164          int w = aExplainWidth[i];
2165          utf8_width_print(p->out, w, azCol[i]);
2166          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2167        }
2168        for(i=0; i<nArg; i++){
2169          int w = aExplainWidth[i];
2170          print_dashes(p->out, w);
2171          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2172        }
2173      }
2174      if( azArg==0 ) break;
2175      for(i=0; i<nArg; i++){
2176        int w = aExplainWidth[i];
2177        if( i==nArg-1 ) w = 0;
2178        if( azArg[i] && strlenChar(azArg[i])>w ){
2179          w = strlenChar(azArg[i]);
2180        }
2181        if( i==1 && p->aiIndent && p->pStmt ){
2182          if( p->iIndent<p->nIndent ){
2183            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2184          }
2185          p->iIndent++;
2186        }
2187        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2188        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2189      }
2190      break;
2191    }
2192    case MODE_Semi: {   /* .schema and .fullschema output */
2193      printSchemaLine(p->out, azArg[0], ";\n");
2194      break;
2195    }
2196    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2197      char *z;
2198      int j;
2199      int nParen = 0;
2200      char cEnd = 0;
2201      char c;
2202      int nLine = 0;
2203      assert( nArg==1 );
2204      if( azArg[0]==0 ) break;
2205      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2206       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2207      ){
2208        utf8_printf(p->out, "%s;\n", azArg[0]);
2209        break;
2210      }
2211      z = sqlite3_mprintf("%s", azArg[0]);
2212      shell_check_oom(z);
2213      j = 0;
2214      for(i=0; IsSpace(z[i]); i++){}
2215      for(; (c = z[i])!=0; i++){
2216        if( IsSpace(c) ){
2217          if( z[j-1]=='\r' ) z[j-1] = '\n';
2218          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2219        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2220          j--;
2221        }
2222        z[j++] = c;
2223      }
2224      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2225      z[j] = 0;
2226      if( strlen30(z)>=79 ){
2227        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2228          if( c==cEnd ){
2229            cEnd = 0;
2230          }else if( c=='"' || c=='\'' || c=='`' ){
2231            cEnd = c;
2232          }else if( c=='[' ){
2233            cEnd = ']';
2234          }else if( c=='-' && z[i+1]=='-' ){
2235            cEnd = '\n';
2236          }else if( c=='(' ){
2237            nParen++;
2238          }else if( c==')' ){
2239            nParen--;
2240            if( nLine>0 && nParen==0 && j>0 ){
2241              printSchemaLineN(p->out, z, j, "\n");
2242              j = 0;
2243            }
2244          }
2245          z[j++] = c;
2246          if( nParen==1 && cEnd==0
2247           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2248          ){
2249            if( c=='\n' ) j--;
2250            printSchemaLineN(p->out, z, j, "\n  ");
2251            j = 0;
2252            nLine++;
2253            while( IsSpace(z[i+1]) ){ i++; }
2254          }
2255        }
2256        z[j] = 0;
2257      }
2258      printSchemaLine(p->out, z, ";\n");
2259      sqlite3_free(z);
2260      break;
2261    }
2262    case MODE_List: {
2263      if( p->cnt++==0 && p->showHeader ){
2264        for(i=0; i<nArg; i++){
2265          utf8_printf(p->out,"%s%s",azCol[i],
2266                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2267        }
2268      }
2269      if( azArg==0 ) break;
2270      for(i=0; i<nArg; i++){
2271        char *z = azArg[i];
2272        if( z==0 ) z = p->nullValue;
2273        utf8_printf(p->out, "%s", z);
2274        if( i<nArg-1 ){
2275          utf8_printf(p->out, "%s", p->colSeparator);
2276        }else{
2277          utf8_printf(p->out, "%s", p->rowSeparator);
2278        }
2279      }
2280      break;
2281    }
2282    case MODE_Html: {
2283      if( p->cnt++==0 && p->showHeader ){
2284        raw_printf(p->out,"<TR>");
2285        for(i=0; i<nArg; i++){
2286          raw_printf(p->out,"<TH>");
2287          output_html_string(p->out, azCol[i]);
2288          raw_printf(p->out,"</TH>\n");
2289        }
2290        raw_printf(p->out,"</TR>\n");
2291      }
2292      if( azArg==0 ) break;
2293      raw_printf(p->out,"<TR>");
2294      for(i=0; i<nArg; i++){
2295        raw_printf(p->out,"<TD>");
2296        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2297        raw_printf(p->out,"</TD>\n");
2298      }
2299      raw_printf(p->out,"</TR>\n");
2300      break;
2301    }
2302    case MODE_Tcl: {
2303      if( p->cnt++==0 && p->showHeader ){
2304        for(i=0; i<nArg; i++){
2305          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2306          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2307        }
2308        utf8_printf(p->out, "%s", p->rowSeparator);
2309      }
2310      if( azArg==0 ) break;
2311      for(i=0; i<nArg; i++){
2312        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2313        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2314      }
2315      utf8_printf(p->out, "%s", p->rowSeparator);
2316      break;
2317    }
2318    case MODE_Csv: {
2319      setBinaryMode(p->out, 1);
2320      if( p->cnt++==0 && p->showHeader ){
2321        for(i=0; i<nArg; i++){
2322          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2323        }
2324        utf8_printf(p->out, "%s", p->rowSeparator);
2325      }
2326      if( nArg>0 ){
2327        for(i=0; i<nArg; i++){
2328          output_csv(p, azArg[i], i<nArg-1);
2329        }
2330        utf8_printf(p->out, "%s", p->rowSeparator);
2331      }
2332      setTextMode(p->out, 1);
2333      break;
2334    }
2335    case MODE_Insert: {
2336      if( azArg==0 ) break;
2337      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2338      if( p->showHeader ){
2339        raw_printf(p->out,"(");
2340        for(i=0; i<nArg; i++){
2341          if( i>0 ) raw_printf(p->out, ",");
2342          if( quoteChar(azCol[i]) ){
2343            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2344            shell_check_oom(z);
2345            utf8_printf(p->out, "%s", z);
2346            sqlite3_free(z);
2347          }else{
2348            raw_printf(p->out, "%s", azCol[i]);
2349          }
2350        }
2351        raw_printf(p->out,")");
2352      }
2353      p->cnt++;
2354      for(i=0; i<nArg; i++){
2355        raw_printf(p->out, i>0 ? "," : " VALUES(");
2356        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2357          utf8_printf(p->out,"NULL");
2358        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2359          if( ShellHasFlag(p, SHFLG_Newlines) ){
2360            output_quoted_string(p->out, azArg[i]);
2361          }else{
2362            output_quoted_escaped_string(p->out, azArg[i]);
2363          }
2364        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2365          utf8_printf(p->out,"%s", azArg[i]);
2366        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2367          char z[50];
2368          double r = sqlite3_column_double(p->pStmt, i);
2369          sqlite3_uint64 ur;
2370          memcpy(&ur,&r,sizeof(r));
2371          if( ur==0x7ff0000000000000LL ){
2372            raw_printf(p->out, "1e999");
2373          }else if( ur==0xfff0000000000000LL ){
2374            raw_printf(p->out, "-1e999");
2375          }else{
2376            sqlite3_int64 ir = (sqlite3_int64)r;
2377            if( r==(double)ir ){
2378              sqlite3_snprintf(50,z,"%lld.0", ir);
2379            }else{
2380              sqlite3_snprintf(50,z,"%!.20g", r);
2381            }
2382            raw_printf(p->out, "%s", z);
2383          }
2384        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2385          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2386          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2387          output_hex_blob(p->out, pBlob, nBlob);
2388        }else if( isNumber(azArg[i], 0) ){
2389          utf8_printf(p->out,"%s", azArg[i]);
2390        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2391          output_quoted_string(p->out, azArg[i]);
2392        }else{
2393          output_quoted_escaped_string(p->out, azArg[i]);
2394        }
2395      }
2396      raw_printf(p->out,");\n");
2397      break;
2398    }
2399    case MODE_Json: {
2400      if( azArg==0 ) break;
2401      if( p->cnt==0 ){
2402        fputs("[{", p->out);
2403      }else{
2404        fputs(",\n{", p->out);
2405      }
2406      p->cnt++;
2407      for(i=0; i<nArg; i++){
2408        output_json_string(p->out, azCol[i], -1);
2409        putc(':', p->out);
2410        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2411          fputs("null",p->out);
2412        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2413          char z[50];
2414          double r = sqlite3_column_double(p->pStmt, i);
2415          sqlite3_uint64 ur;
2416          memcpy(&ur,&r,sizeof(r));
2417          if( ur==0x7ff0000000000000LL ){
2418            raw_printf(p->out, "1e999");
2419          }else if( ur==0xfff0000000000000LL ){
2420            raw_printf(p->out, "-1e999");
2421          }else{
2422            sqlite3_snprintf(50,z,"%!.20g", r);
2423            raw_printf(p->out, "%s", z);
2424          }
2425        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2426          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2427          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2428          output_json_string(p->out, pBlob, nBlob);
2429        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2430          output_json_string(p->out, azArg[i], -1);
2431        }else{
2432          utf8_printf(p->out,"%s", azArg[i]);
2433        }
2434        if( i<nArg-1 ){
2435          putc(',', p->out);
2436        }
2437      }
2438      putc('}', p->out);
2439      break;
2440    }
2441    case MODE_Quote: {
2442      if( azArg==0 ) break;
2443      if( p->cnt==0 && p->showHeader ){
2444        for(i=0; i<nArg; i++){
2445          if( i>0 ) fputs(p->colSeparator, p->out);
2446          output_quoted_string(p->out, azCol[i]);
2447        }
2448        fputs(p->rowSeparator, p->out);
2449      }
2450      p->cnt++;
2451      for(i=0; i<nArg; i++){
2452        if( i>0 ) fputs(p->colSeparator, p->out);
2453        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2454          utf8_printf(p->out,"NULL");
2455        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2456          output_quoted_string(p->out, azArg[i]);
2457        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2458          utf8_printf(p->out,"%s", azArg[i]);
2459        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2460          char z[50];
2461          double r = sqlite3_column_double(p->pStmt, i);
2462          sqlite3_snprintf(50,z,"%!.20g", r);
2463          raw_printf(p->out, "%s", z);
2464        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2465          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2466          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2467          output_hex_blob(p->out, pBlob, nBlob);
2468        }else if( isNumber(azArg[i], 0) ){
2469          utf8_printf(p->out,"%s", azArg[i]);
2470        }else{
2471          output_quoted_string(p->out, azArg[i]);
2472        }
2473      }
2474      fputs(p->rowSeparator, p->out);
2475      break;
2476    }
2477    case MODE_Ascii: {
2478      if( p->cnt++==0 && p->showHeader ){
2479        for(i=0; i<nArg; i++){
2480          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2481          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2482        }
2483        utf8_printf(p->out, "%s", p->rowSeparator);
2484      }
2485      if( azArg==0 ) break;
2486      for(i=0; i<nArg; i++){
2487        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2488        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2489      }
2490      utf8_printf(p->out, "%s", p->rowSeparator);
2491      break;
2492    }
2493    case MODE_EQP: {
2494      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2495      break;
2496    }
2497  }
2498  return 0;
2499}
2500
2501/*
2502** This is the callback routine that the SQLite library
2503** invokes for each row of a query result.
2504*/
2505static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2506  /* since we don't have type info, call the shell_callback with a NULL value */
2507  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2508}
2509
2510/*
2511** This is the callback routine from sqlite3_exec() that appends all
2512** output onto the end of a ShellText object.
2513*/
2514static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2515  ShellText *p = (ShellText*)pArg;
2516  int i;
2517  UNUSED_PARAMETER(az);
2518  if( azArg==0 ) return 0;
2519  if( p->n ) appendText(p, "|", 0);
2520  for(i=0; i<nArg; i++){
2521    if( i ) appendText(p, ",", 0);
2522    if( azArg[i] ) appendText(p, azArg[i], 0);
2523  }
2524  return 0;
2525}
2526
2527/*
2528** Generate an appropriate SELFTEST table in the main database.
2529*/
2530static void createSelftestTable(ShellState *p){
2531  char *zErrMsg = 0;
2532  sqlite3_exec(p->db,
2533    "SAVEPOINT selftest_init;\n"
2534    "CREATE TABLE IF NOT EXISTS selftest(\n"
2535    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2536    "  op TEXT,\n"                   /* Operator:  memo run */
2537    "  cmd TEXT,\n"                  /* Command text */
2538    "  ans TEXT\n"                   /* Desired answer */
2539    ");"
2540    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2541    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2542    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2543    "         'memo','Tests generated by --init');\n"
2544    "INSERT INTO [_shell$self]\n"
2545    "  SELECT 'run',\n"
2546    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2547                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2548    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2549                          "FROM sqlite_schema ORDER BY 2',224));\n"
2550    "INSERT INTO [_shell$self]\n"
2551    "  SELECT 'run',"
2552    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2553    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2554    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2555    "  FROM (\n"
2556    "    SELECT name FROM sqlite_schema\n"
2557    "     WHERE type='table'\n"
2558    "       AND name<>'selftest'\n"
2559    "       AND coalesce(rootpage,0)>0\n"
2560    "  )\n"
2561    " ORDER BY name;\n"
2562    "INSERT INTO [_shell$self]\n"
2563    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2564    "INSERT INTO selftest(tno,op,cmd,ans)"
2565    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2566    "DROP TABLE [_shell$self];"
2567    ,0,0,&zErrMsg);
2568  if( zErrMsg ){
2569    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2570    sqlite3_free(zErrMsg);
2571  }
2572  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2573}
2574
2575
2576/*
2577** Set the destination table field of the ShellState structure to
2578** the name of the table given.  Escape any quote characters in the
2579** table name.
2580*/
2581static void set_table_name(ShellState *p, const char *zName){
2582  int i, n;
2583  char cQuote;
2584  char *z;
2585
2586  if( p->zDestTable ){
2587    free(p->zDestTable);
2588    p->zDestTable = 0;
2589  }
2590  if( zName==0 ) return;
2591  cQuote = quoteChar(zName);
2592  n = strlen30(zName);
2593  if( cQuote ) n += n+2;
2594  z = p->zDestTable = malloc( n+1 );
2595  shell_check_oom(z);
2596  n = 0;
2597  if( cQuote ) z[n++] = cQuote;
2598  for(i=0; zName[i]; i++){
2599    z[n++] = zName[i];
2600    if( zName[i]==cQuote ) z[n++] = cQuote;
2601  }
2602  if( cQuote ) z[n++] = cQuote;
2603  z[n] = 0;
2604}
2605
2606/*
2607** Maybe construct two lines of text that point out the position of a
2608** syntax error.  Return a pointer to the text, in memory obtained from
2609** sqlite3_malloc().  Or, if the most recent error does not involve a
2610** specific token that we can point to, return an empty string.
2611**
2612** In all cases, the memory returned is obtained from sqlite3_malloc64()
2613** and should be released by the caller invoking sqlite3_free().
2614*/
2615static char *shell_error_context(const char *zSql, sqlite3 *db){
2616  int iOffset;
2617  size_t len;
2618  char *zCode;
2619  char *zMsg;
2620  int i;
2621  if( db==0
2622   || zSql==0
2623   || (iOffset = sqlite3_error_offset(db))<0
2624  ){
2625    return sqlite3_mprintf("");
2626  }
2627  while( iOffset>50 ){
2628    iOffset--;
2629    zSql++;
2630    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2631  }
2632  len = strlen(zSql);
2633  if( len>78 ){
2634    len = 78;
2635    while( (zSql[len]&0xc0)==0x80 ) len--;
2636  }
2637  zCode = sqlite3_mprintf("%.*s", len, zSql);
2638  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2639  if( iOffset<25 ){
2640    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2641  }else{
2642    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2643  }
2644  return zMsg;
2645}
2646
2647
2648/*
2649** Execute a query statement that will generate SQL output.  Print
2650** the result columns, comma-separated, on a line and then add a
2651** semicolon terminator to the end of that line.
2652**
2653** If the number of columns is 1 and that column contains text "--"
2654** then write the semicolon on a separate line.  That way, if a
2655** "--" comment occurs at the end of the statement, the comment
2656** won't consume the semicolon terminator.
2657*/
2658static int run_table_dump_query(
2659  ShellState *p,           /* Query context */
2660  const char *zSelect      /* SELECT statement to extract content */
2661){
2662  sqlite3_stmt *pSelect;
2663  int rc;
2664  int nResult;
2665  int i;
2666  const char *z;
2667  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2668  if( rc!=SQLITE_OK || !pSelect ){
2669    char *zContext = shell_error_context(zSelect, p->db);
2670    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2671                sqlite3_errmsg(p->db), zContext);
2672    sqlite3_free(zContext);
2673    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2674    return rc;
2675  }
2676  rc = sqlite3_step(pSelect);
2677  nResult = sqlite3_column_count(pSelect);
2678  while( rc==SQLITE_ROW ){
2679    z = (const char*)sqlite3_column_text(pSelect, 0);
2680    utf8_printf(p->out, "%s", z);
2681    for(i=1; i<nResult; i++){
2682      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2683    }
2684    if( z==0 ) z = "";
2685    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2686    if( z[0] ){
2687      raw_printf(p->out, "\n;\n");
2688    }else{
2689      raw_printf(p->out, ";\n");
2690    }
2691    rc = sqlite3_step(pSelect);
2692  }
2693  rc = sqlite3_finalize(pSelect);
2694  if( rc!=SQLITE_OK ){
2695    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2696                sqlite3_errmsg(p->db));
2697    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2698  }
2699  return rc;
2700}
2701
2702/*
2703** Allocate space and save off string indicating current error.
2704*/
2705static char *save_err_msg(
2706  sqlite3 *db,           /* Database to query */
2707  const char *zPhase,    /* When the error occcurs */
2708  int rc,                /* Error code returned from API */
2709  const char *zSql       /* SQL string, or NULL */
2710){
2711  char *zErr;
2712  char *zContext;
2713  sqlite3_str *pStr = sqlite3_str_new(0);
2714  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2715  if( rc>1 ){
2716    sqlite3_str_appendf(pStr, " (%d)", rc);
2717  }
2718  zContext = shell_error_context(zSql, db);
2719  if( zContext ){
2720    sqlite3_str_appendall(pStr, zContext);
2721    sqlite3_free(zContext);
2722  }
2723  zErr = sqlite3_str_finish(pStr);
2724  shell_check_oom(zErr);
2725  return zErr;
2726}
2727
2728#ifdef __linux__
2729/*
2730** Attempt to display I/O stats on Linux using /proc/PID/io
2731*/
2732static void displayLinuxIoStats(FILE *out){
2733  FILE *in;
2734  char z[200];
2735  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2736  in = fopen(z, "rb");
2737  if( in==0 ) return;
2738  while( fgets(z, sizeof(z), in)!=0 ){
2739    static const struct {
2740      const char *zPattern;
2741      const char *zDesc;
2742    } aTrans[] = {
2743      { "rchar: ",                  "Bytes received by read():" },
2744      { "wchar: ",                  "Bytes sent to write():"    },
2745      { "syscr: ",                  "Read() system calls:"      },
2746      { "syscw: ",                  "Write() system calls:"     },
2747      { "read_bytes: ",             "Bytes read from storage:"  },
2748      { "write_bytes: ",            "Bytes written to storage:" },
2749      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2750    };
2751    int i;
2752    for(i=0; i<ArraySize(aTrans); i++){
2753      int n = strlen30(aTrans[i].zPattern);
2754      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2755        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2756        break;
2757      }
2758    }
2759  }
2760  fclose(in);
2761}
2762#endif
2763
2764/*
2765** Display a single line of status using 64-bit values.
2766*/
2767static void displayStatLine(
2768  ShellState *p,            /* The shell context */
2769  char *zLabel,             /* Label for this one line */
2770  char *zFormat,            /* Format for the result */
2771  int iStatusCtrl,          /* Which status to display */
2772  int bReset                /* True to reset the stats */
2773){
2774  sqlite3_int64 iCur = -1;
2775  sqlite3_int64 iHiwtr = -1;
2776  int i, nPercent;
2777  char zLine[200];
2778  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2779  for(i=0, nPercent=0; zFormat[i]; i++){
2780    if( zFormat[i]=='%' ) nPercent++;
2781  }
2782  if( nPercent>1 ){
2783    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2784  }else{
2785    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2786  }
2787  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2788}
2789
2790/*
2791** Display memory stats.
2792*/
2793static int display_stats(
2794  sqlite3 *db,                /* Database to query */
2795  ShellState *pArg,           /* Pointer to ShellState */
2796  int bReset                  /* True to reset the stats */
2797){
2798  int iCur;
2799  int iHiwtr;
2800  FILE *out;
2801  if( pArg==0 || pArg->out==0 ) return 0;
2802  out = pArg->out;
2803
2804  if( pArg->pStmt && pArg->statsOn==2 ){
2805    int nCol, i, x;
2806    sqlite3_stmt *pStmt = pArg->pStmt;
2807    char z[100];
2808    nCol = sqlite3_column_count(pStmt);
2809    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2810    for(i=0; i<nCol; i++){
2811      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2812      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2813#ifndef SQLITE_OMIT_DECLTYPE
2814      sqlite3_snprintf(30, z+x, "declared type:");
2815      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2816#endif
2817#ifdef SQLITE_ENABLE_COLUMN_METADATA
2818      sqlite3_snprintf(30, z+x, "database name:");
2819      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2820      sqlite3_snprintf(30, z+x, "table name:");
2821      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2822      sqlite3_snprintf(30, z+x, "origin name:");
2823      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2824#endif
2825    }
2826  }
2827
2828  if( pArg->statsOn==3 ){
2829    if( pArg->pStmt ){
2830      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2831      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2832    }
2833    return 0;
2834  }
2835
2836  displayStatLine(pArg, "Memory Used:",
2837     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2838  displayStatLine(pArg, "Number of Outstanding Allocations:",
2839     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2840  if( pArg->shellFlgs & SHFLG_Pagecache ){
2841    displayStatLine(pArg, "Number of Pcache Pages Used:",
2842       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2843  }
2844  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2845     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2846  displayStatLine(pArg, "Largest Allocation:",
2847     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2848  displayStatLine(pArg, "Largest Pcache Allocation:",
2849     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2850#ifdef YYTRACKMAXSTACKDEPTH
2851  displayStatLine(pArg, "Deepest Parser Stack:",
2852     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2853#endif
2854
2855  if( db ){
2856    if( pArg->shellFlgs & SHFLG_Lookaside ){
2857      iHiwtr = iCur = -1;
2858      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2859                        &iCur, &iHiwtr, bReset);
2860      raw_printf(pArg->out,
2861              "Lookaside Slots Used:                %d (max %d)\n",
2862              iCur, iHiwtr);
2863      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2864                        &iCur, &iHiwtr, bReset);
2865      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2866              iHiwtr);
2867      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2868                        &iCur, &iHiwtr, bReset);
2869      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2870              iHiwtr);
2871      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2872                        &iCur, &iHiwtr, bReset);
2873      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2874              iHiwtr);
2875    }
2876    iHiwtr = iCur = -1;
2877    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2878    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2879            iCur);
2880    iHiwtr = iCur = -1;
2881    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2882    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2883    iHiwtr = iCur = -1;
2884    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2885    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2886    iHiwtr = iCur = -1;
2887    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2888    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2889    iHiwtr = iCur = -1;
2890    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2891    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2892    iHiwtr = iCur = -1;
2893    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2894    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2895            iCur);
2896    iHiwtr = iCur = -1;
2897    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2898    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2899            iCur);
2900  }
2901
2902  if( pArg->pStmt ){
2903    int iHit, iMiss;
2904    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2905                               bReset);
2906    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2907    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2908    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2909    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2910    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2911    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2912    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2913    if( iHit || iMiss ){
2914      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2915            iHit, iHit+iMiss);
2916    }
2917    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2918    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2919    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2920    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2921    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2922    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2923    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2924    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2925  }
2926
2927#ifdef __linux__
2928  displayLinuxIoStats(pArg->out);
2929#endif
2930
2931  /* Do not remove this machine readable comment: extra-stats-output-here */
2932
2933  return 0;
2934}
2935
2936/*
2937** Display scan stats.
2938*/
2939static void display_scanstats(
2940  sqlite3 *db,                    /* Database to query */
2941  ShellState *pArg                /* Pointer to ShellState */
2942){
2943#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2944  UNUSED_PARAMETER(db);
2945  UNUSED_PARAMETER(pArg);
2946#else
2947  int i, k, n, mx;
2948  raw_printf(pArg->out, "-------- scanstats --------\n");
2949  mx = 0;
2950  for(k=0; k<=mx; k++){
2951    double rEstLoop = 1.0;
2952    for(i=n=0; 1; i++){
2953      sqlite3_stmt *p = pArg->pStmt;
2954      sqlite3_int64 nLoop, nVisit;
2955      double rEst;
2956      int iSid;
2957      const char *zExplain;
2958      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2959        break;
2960      }
2961      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2962      if( iSid>mx ) mx = iSid;
2963      if( iSid!=k ) continue;
2964      if( n==0 ){
2965        rEstLoop = (double)nLoop;
2966        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2967      }
2968      n++;
2969      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2970      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2971      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2972      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2973      rEstLoop *= rEst;
2974      raw_printf(pArg->out,
2975          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2976          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2977      );
2978    }
2979  }
2980  raw_printf(pArg->out, "---------------------------\n");
2981#endif
2982}
2983
2984/*
2985** Parameter azArray points to a zero-terminated array of strings. zStr
2986** points to a single nul-terminated string. Return non-zero if zStr
2987** is equal, according to strcmp(), to any of the strings in the array.
2988** Otherwise, return zero.
2989*/
2990static int str_in_array(const char *zStr, const char **azArray){
2991  int i;
2992  for(i=0; azArray[i]; i++){
2993    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2994  }
2995  return 0;
2996}
2997
2998/*
2999** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3000** and populate the ShellState.aiIndent[] array with the number of
3001** spaces each opcode should be indented before it is output.
3002**
3003** The indenting rules are:
3004**
3005**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3006**       all opcodes that occur between the p2 jump destination and the opcode
3007**       itself by 2 spaces.
3008**
3009**     * Do the previous for "Return" instructions for when P2 is positive.
3010**       See tag-20220407a in wherecode.c and vdbe.c.
3011**
3012**     * For each "Goto", if the jump destination is earlier in the program
3013**       and ends on one of:
3014**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
3015**       or if the P1 parameter is one instead of zero,
3016**       then indent all opcodes between the earlier instruction
3017**       and "Goto" by 2 spaces.
3018*/
3019static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3020  const char *zSql;               /* The text of the SQL statement */
3021  const char *z;                  /* Used to check if this is an EXPLAIN */
3022  int *abYield = 0;               /* True if op is an OP_Yield */
3023  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
3024  int iOp;                        /* Index of operation in p->aiIndent[] */
3025
3026  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3027                           "Return", 0 };
3028  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3029                            "Rewind", 0 };
3030  const char *azGoto[] = { "Goto", 0 };
3031
3032  /* Try to figure out if this is really an EXPLAIN statement. If this
3033  ** cannot be verified, return early.  */
3034  if( sqlite3_column_count(pSql)!=8 ){
3035    p->cMode = p->mode;
3036    return;
3037  }
3038  zSql = sqlite3_sql(pSql);
3039  if( zSql==0 ) return;
3040  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3041  if( sqlite3_strnicmp(z, "explain", 7) ){
3042    p->cMode = p->mode;
3043    return;
3044  }
3045
3046  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3047    int i;
3048    int iAddr = sqlite3_column_int(pSql, 0);
3049    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3050
3051    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3052    ** p2 is an instruction address, set variable p2op to the index of that
3053    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3054    ** the current instruction is part of a sub-program generated by an
3055    ** SQL trigger or foreign key.  */
3056    int p2 = sqlite3_column_int(pSql, 3);
3057    int p2op = (p2 + (iOp-iAddr));
3058
3059    /* Grow the p->aiIndent array as required */
3060    if( iOp>=nAlloc ){
3061      if( iOp==0 ){
3062        /* Do further verfication that this is explain output.  Abort if
3063        ** it is not */
3064        static const char *explainCols[] = {
3065           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3066        int jj;
3067        for(jj=0; jj<ArraySize(explainCols); jj++){
3068          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3069            p->cMode = p->mode;
3070            sqlite3_reset(pSql);
3071            return;
3072          }
3073        }
3074      }
3075      nAlloc += 100;
3076      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3077      shell_check_oom(p->aiIndent);
3078      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3079      shell_check_oom(abYield);
3080    }
3081    abYield[iOp] = str_in_array(zOp, azYield);
3082    p->aiIndent[iOp] = 0;
3083    p->nIndent = iOp+1;
3084
3085    if( str_in_array(zOp, azNext) && p2op>0 ){
3086      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3087    }
3088    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3089     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3090    ){
3091      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3092    }
3093  }
3094
3095  p->iIndent = 0;
3096  sqlite3_free(abYield);
3097  sqlite3_reset(pSql);
3098}
3099
3100/*
3101** Free the array allocated by explain_data_prepare().
3102*/
3103static void explain_data_delete(ShellState *p){
3104  sqlite3_free(p->aiIndent);
3105  p->aiIndent = 0;
3106  p->nIndent = 0;
3107  p->iIndent = 0;
3108}
3109
3110/*
3111** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3112*/
3113static unsigned int savedSelectTrace;
3114static unsigned int savedWhereTrace;
3115static void disable_debug_trace_modes(void){
3116  unsigned int zero = 0;
3117  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3118  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3119  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3120  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3121}
3122static void restore_debug_trace_modes(void){
3123  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3124  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3125}
3126
3127/* Create the TEMP table used to store parameter bindings */
3128static void bind_table_init(ShellState *p){
3129  int wrSchema = 0;
3130  int defensiveMode = 0;
3131  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3132  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3133  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3134  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3135  sqlite3_exec(p->db,
3136    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3137    "  key TEXT PRIMARY KEY,\n"
3138    "  value\n"
3139    ") WITHOUT ROWID;",
3140    0, 0, 0);
3141  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3142  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3143}
3144
3145/*
3146** Bind parameters on a prepared statement.
3147**
3148** Parameter bindings are taken from a TEMP table of the form:
3149**
3150**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3151**    WITHOUT ROWID;
3152**
3153** No bindings occur if this table does not exist.  The name of the table
3154** begins with "sqlite_" so that it will not collide with ordinary application
3155** tables.  The table must be in the TEMP schema.
3156*/
3157static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3158  int nVar;
3159  int i;
3160  int rc;
3161  sqlite3_stmt *pQ = 0;
3162
3163  nVar = sqlite3_bind_parameter_count(pStmt);
3164  if( nVar==0 ) return;  /* Nothing to do */
3165  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3166                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3167    return; /* Parameter table does not exist */
3168  }
3169  rc = sqlite3_prepare_v2(pArg->db,
3170          "SELECT value FROM temp.sqlite_parameters"
3171          " WHERE key=?1", -1, &pQ, 0);
3172  if( rc || pQ==0 ) return;
3173  for(i=1; i<=nVar; i++){
3174    char zNum[30];
3175    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3176    if( zVar==0 ){
3177      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3178      zVar = zNum;
3179    }
3180    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3181    if( sqlite3_step(pQ)==SQLITE_ROW ){
3182      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3183    }else{
3184      sqlite3_bind_null(pStmt, i);
3185    }
3186    sqlite3_reset(pQ);
3187  }
3188  sqlite3_finalize(pQ);
3189}
3190
3191/*
3192** UTF8 box-drawing characters.  Imagine box lines like this:
3193**
3194**           1
3195**           |
3196**       4 --+-- 2
3197**           |
3198**           3
3199**
3200** Each box characters has between 2 and 4 of the lines leading from
3201** the center.  The characters are here identified by the numbers of
3202** their corresponding lines.
3203*/
3204#define BOX_24   "\342\224\200"  /* U+2500 --- */
3205#define BOX_13   "\342\224\202"  /* U+2502  |  */
3206#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3207#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3208#define BOX_12   "\342\224\224"  /* U+2514  '- */
3209#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3210#define BOX_123  "\342\224\234"  /* U+251c  |- */
3211#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3212#define BOX_234  "\342\224\254"  /* U+252c -,- */
3213#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3214#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3215
3216/* Draw horizontal line N characters long using unicode box
3217** characters
3218*/
3219static void print_box_line(FILE *out, int N){
3220  const char zDash[] =
3221      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3222      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3223  const int nDash = sizeof(zDash) - 1;
3224  N *= 3;
3225  while( N>nDash ){
3226    utf8_printf(out, zDash);
3227    N -= nDash;
3228  }
3229  utf8_printf(out, "%.*s", N, zDash);
3230}
3231
3232/*
3233** Draw a horizontal separator for a MODE_Box table.
3234*/
3235static void print_box_row_separator(
3236  ShellState *p,
3237  int nArg,
3238  const char *zSep1,
3239  const char *zSep2,
3240  const char *zSep3
3241){
3242  int i;
3243  if( nArg>0 ){
3244    utf8_printf(p->out, "%s", zSep1);
3245    print_box_line(p->out, p->actualWidth[0]+2);
3246    for(i=1; i<nArg; i++){
3247      utf8_printf(p->out, "%s", zSep2);
3248      print_box_line(p->out, p->actualWidth[i]+2);
3249    }
3250    utf8_printf(p->out, "%s", zSep3);
3251  }
3252  fputs("\n", p->out);
3253}
3254
3255/*
3256** z[] is a line of text that is to be displayed the .mode box or table or
3257** similar tabular formats.  z[] might contain control characters such
3258** as \n, \t, \f, or \r.
3259**
3260** Compute characters to display on the first line of z[].  Stop at the
3261** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3262** from malloc()) of that first line, which caller should free sometime.
3263** Write anything to display on the next line into *pzTail.  If this is
3264** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3265*/
3266static char *translateForDisplayAndDup(
3267  const unsigned char *z,            /* Input text to be transformed */
3268  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3269  int mxWidth,                       /* Max width.  0 means no limit */
3270  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3271){
3272  int i;                 /* Input bytes consumed */
3273  int j;                 /* Output bytes generated */
3274  int k;                 /* Input bytes to be displayed */
3275  int n;                 /* Output column number */
3276  unsigned char *zOut;   /* Output text */
3277
3278  if( z==0 ){
3279    *pzTail = 0;
3280    return 0;
3281  }
3282  if( mxWidth<0 ) mxWidth = -mxWidth;
3283  if( mxWidth==0 ) mxWidth = 1000000;
3284  i = j = n = 0;
3285  while( n<mxWidth ){
3286    if( z[i]>=' ' ){
3287      n++;
3288      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3289      continue;
3290    }
3291    if( z[i]=='\t' ){
3292      do{
3293        n++;
3294        j++;
3295      }while( (n&7)!=0 && n<mxWidth );
3296      i++;
3297      continue;
3298    }
3299    break;
3300  }
3301  if( n>=mxWidth && bWordWrap  ){
3302    /* Perhaps try to back up to a better place to break the line */
3303    for(k=i; k>i/2; k--){
3304      if( isspace(z[k-1]) ) break;
3305    }
3306    if( k<=i/2 ){
3307      for(k=i; k>i/2; k--){
3308        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3309      }
3310    }
3311    if( k<=i/2 ){
3312      k = i;
3313    }else{
3314      i = k;
3315      while( z[i]==' ' ) i++;
3316    }
3317  }else{
3318    k = i;
3319  }
3320  if( n>=mxWidth && z[i]>=' ' ){
3321   *pzTail = &z[i];
3322  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3323    *pzTail = z[i+2] ? &z[i+2] : 0;
3324  }else if( z[i]==0 || z[i+1]==0 ){
3325    *pzTail = 0;
3326  }else{
3327    *pzTail = &z[i+1];
3328  }
3329  zOut = malloc( j+1 );
3330  shell_check_oom(zOut);
3331  i = j = n = 0;
3332  while( i<k ){
3333    if( z[i]>=' ' ){
3334      n++;
3335      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3336      continue;
3337    }
3338    if( z[i]=='\t' ){
3339      do{
3340        n++;
3341        zOut[j++] = ' ';
3342      }while( (n&7)!=0 && n<mxWidth );
3343      i++;
3344      continue;
3345    }
3346    break;
3347  }
3348  zOut[j] = 0;
3349  return (char*)zOut;
3350}
3351
3352/* Extract the value of the i-th current column for pStmt as an SQL literal
3353** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3354** the caller.
3355*/
3356static char *quoted_column(sqlite3_stmt *pStmt, int i){
3357  switch( sqlite3_column_type(pStmt, i) ){
3358    case SQLITE_NULL: {
3359      return sqlite3_mprintf("NULL");
3360    }
3361    case SQLITE_INTEGER:
3362    case SQLITE_FLOAT: {
3363      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3364    }
3365    case SQLITE_TEXT: {
3366      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3367    }
3368    case SQLITE_BLOB: {
3369      int j;
3370      sqlite3_str *pStr = sqlite3_str_new(0);
3371      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3372      int n = sqlite3_column_bytes(pStmt,i);
3373      sqlite3_str_append(pStr, "x'", 2);
3374      for(j=0; j<n; j++){
3375        sqlite3_str_appendf(pStr, "%02x", a[j]);
3376      }
3377      sqlite3_str_append(pStr, "'", 1);
3378      return sqlite3_str_finish(pStr);
3379    }
3380  }
3381  return 0; /* Not reached */
3382}
3383
3384/*
3385** Run a prepared statement and output the result in one of the
3386** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3387** or MODE_Box.
3388**
3389** This is different from ordinary exec_prepared_stmt() in that
3390** it has to run the entire query and gather the results into memory
3391** first, in order to determine column widths, before providing
3392** any output.
3393*/
3394static void exec_prepared_stmt_columnar(
3395  ShellState *p,                        /* Pointer to ShellState */
3396  sqlite3_stmt *pStmt                   /* Statment to run */
3397){
3398  sqlite3_int64 nRow = 0;
3399  int nColumn = 0;
3400  char **azData = 0;
3401  sqlite3_int64 nAlloc = 0;
3402  char *abRowDiv = 0;
3403  const unsigned char *uz;
3404  const char *z;
3405  char **azQuoted = 0;
3406  int rc;
3407  sqlite3_int64 i, nData;
3408  int j, nTotal, w, n;
3409  const char *colSep = 0;
3410  const char *rowSep = 0;
3411  const unsigned char **azNextLine = 0;
3412  int bNextLine = 0;
3413  int bMultiLineRowExists = 0;
3414  int bw = p->cmOpts.bWordWrap;
3415  const char *zEmpty = "";
3416  const char *zShowNull = p->nullValue;
3417
3418  rc = sqlite3_step(pStmt);
3419  if( rc!=SQLITE_ROW ) return;
3420  nColumn = sqlite3_column_count(pStmt);
3421  nAlloc = nColumn*4;
3422  if( nAlloc<=0 ) nAlloc = 1;
3423  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3424  shell_check_oom(azData);
3425  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3426  shell_check_oom((void*)azNextLine);
3427  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3428  if( p->cmOpts.bQuote ){
3429    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3430    shell_check_oom(azQuoted);
3431    memset(azQuoted, 0, nColumn*sizeof(char*) );
3432  }
3433  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3434  shell_check_oom(abRowDiv);
3435  if( nColumn>p->nWidth ){
3436    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3437    shell_check_oom(p->colWidth);
3438    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3439    p->nWidth = nColumn;
3440    p->actualWidth = &p->colWidth[nColumn];
3441  }
3442  memset(p->actualWidth, 0, nColumn*sizeof(int));
3443  for(i=0; i<nColumn; i++){
3444    w = p->colWidth[i];
3445    if( w<0 ) w = -w;
3446    p->actualWidth[i] = w;
3447  }
3448  for(i=0; i<nColumn; i++){
3449    const unsigned char *zNotUsed;
3450    int wx = p->colWidth[i];
3451    if( wx==0 ){
3452      wx = p->cmOpts.iWrap;
3453    }
3454    if( wx<0 ) wx = -wx;
3455    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3456    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3457  }
3458  do{
3459    int useNextLine = bNextLine;
3460    bNextLine = 0;
3461    if( (nRow+2)*nColumn >= nAlloc ){
3462      nAlloc *= 2;
3463      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3464      shell_check_oom(azData);
3465      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3466      shell_check_oom(abRowDiv);
3467    }
3468    abRowDiv[nRow] = 1;
3469    nRow++;
3470    for(i=0; i<nColumn; i++){
3471      int wx = p->colWidth[i];
3472      if( wx==0 ){
3473        wx = p->cmOpts.iWrap;
3474      }
3475      if( wx<0 ) wx = -wx;
3476      if( useNextLine ){
3477        uz = azNextLine[i];
3478        if( uz==0 ) uz = (u8*)zEmpty;
3479      }else if( p->cmOpts.bQuote ){
3480        sqlite3_free(azQuoted[i]);
3481        azQuoted[i] = quoted_column(pStmt,i);
3482        uz = (const unsigned char*)azQuoted[i];
3483      }else{
3484        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3485        if( uz==0 ) uz = (u8*)zShowNull;
3486      }
3487      azData[nRow*nColumn + i]
3488        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3489      if( azNextLine[i] ){
3490        bNextLine = 1;
3491        abRowDiv[nRow-1] = 0;
3492        bMultiLineRowExists = 1;
3493      }
3494    }
3495  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3496  nTotal = nColumn*(nRow+1);
3497  for(i=0; i<nTotal; i++){
3498    z = azData[i];
3499    if( z==0 ) z = (char*)zEmpty;
3500    n = strlenChar(z);
3501    j = i%nColumn;
3502    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3503  }
3504  if( seenInterrupt ) goto columnar_end;
3505  if( nColumn==0 ) goto columnar_end;
3506  switch( p->cMode ){
3507    case MODE_Column: {
3508      colSep = "  ";
3509      rowSep = "\n";
3510      if( p->showHeader ){
3511        for(i=0; i<nColumn; i++){
3512          w = p->actualWidth[i];
3513          if( p->colWidth[i]<0 ) w = -w;
3514          utf8_width_print(p->out, w, azData[i]);
3515          fputs(i==nColumn-1?"\n":"  ", p->out);
3516        }
3517        for(i=0; i<nColumn; i++){
3518          print_dashes(p->out, p->actualWidth[i]);
3519          fputs(i==nColumn-1?"\n":"  ", p->out);
3520        }
3521      }
3522      break;
3523    }
3524    case MODE_Table: {
3525      colSep = " | ";
3526      rowSep = " |\n";
3527      print_row_separator(p, nColumn, "+");
3528      fputs("| ", p->out);
3529      for(i=0; i<nColumn; i++){
3530        w = p->actualWidth[i];
3531        n = strlenChar(azData[i]);
3532        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3533        fputs(i==nColumn-1?" |\n":" | ", p->out);
3534      }
3535      print_row_separator(p, nColumn, "+");
3536      break;
3537    }
3538    case MODE_Markdown: {
3539      colSep = " | ";
3540      rowSep = " |\n";
3541      fputs("| ", p->out);
3542      for(i=0; i<nColumn; i++){
3543        w = p->actualWidth[i];
3544        n = strlenChar(azData[i]);
3545        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3546        fputs(i==nColumn-1?" |\n":" | ", p->out);
3547      }
3548      print_row_separator(p, nColumn, "|");
3549      break;
3550    }
3551    case MODE_Box: {
3552      colSep = " " BOX_13 " ";
3553      rowSep = " " BOX_13 "\n";
3554      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3555      utf8_printf(p->out, BOX_13 " ");
3556      for(i=0; i<nColumn; i++){
3557        w = p->actualWidth[i];
3558        n = strlenChar(azData[i]);
3559        utf8_printf(p->out, "%*s%s%*s%s",
3560            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3561            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3562      }
3563      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3564      break;
3565    }
3566  }
3567  for(i=nColumn, j=0; i<nTotal; i++, j++){
3568    if( j==0 && p->cMode!=MODE_Column ){
3569      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3570    }
3571    z = azData[i];
3572    if( z==0 ) z = p->nullValue;
3573    w = p->actualWidth[j];
3574    if( p->colWidth[j]<0 ) w = -w;
3575    utf8_width_print(p->out, w, z);
3576    if( j==nColumn-1 ){
3577      utf8_printf(p->out, "%s", rowSep);
3578      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3579        if( p->cMode==MODE_Table ){
3580          print_row_separator(p, nColumn, "+");
3581        }else if( p->cMode==MODE_Box ){
3582          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3583        }else if( p->cMode==MODE_Column ){
3584          raw_printf(p->out, "\n");
3585        }
3586      }
3587      j = -1;
3588      if( seenInterrupt ) goto columnar_end;
3589    }else{
3590      utf8_printf(p->out, "%s", colSep);
3591    }
3592  }
3593  if( p->cMode==MODE_Table ){
3594    print_row_separator(p, nColumn, "+");
3595  }else if( p->cMode==MODE_Box ){
3596    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3597  }
3598columnar_end:
3599  if( seenInterrupt ){
3600    utf8_printf(p->out, "Interrupt\n");
3601  }
3602  nData = (nRow+1)*nColumn;
3603  for(i=0; i<nData; i++){
3604    z = azData[i];
3605    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3606  }
3607  sqlite3_free(azData);
3608  sqlite3_free((void*)azNextLine);
3609  sqlite3_free(abRowDiv);
3610  if( azQuoted ){
3611    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3612    sqlite3_free(azQuoted);
3613  }
3614}
3615
3616/*
3617** Run a prepared statement
3618*/
3619static void exec_prepared_stmt(
3620  ShellState *pArg,                                /* Pointer to ShellState */
3621  sqlite3_stmt *pStmt                              /* Statment to run */
3622){
3623  int rc;
3624  sqlite3_uint64 nRow = 0;
3625
3626  if( pArg->cMode==MODE_Column
3627   || pArg->cMode==MODE_Table
3628   || pArg->cMode==MODE_Box
3629   || pArg->cMode==MODE_Markdown
3630  ){
3631    exec_prepared_stmt_columnar(pArg, pStmt);
3632    return;
3633  }
3634
3635  /* perform the first step.  this will tell us if we
3636  ** have a result set or not and how wide it is.
3637  */
3638  rc = sqlite3_step(pStmt);
3639  /* if we have a result set... */
3640  if( SQLITE_ROW == rc ){
3641    /* allocate space for col name ptr, value ptr, and type */
3642    int nCol = sqlite3_column_count(pStmt);
3643    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3644    if( !pData ){
3645      shell_out_of_memory();
3646    }else{
3647      char **azCols = (char **)pData;      /* Names of result columns */
3648      char **azVals = &azCols[nCol];       /* Results */
3649      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3650      int i, x;
3651      assert(sizeof(int) <= sizeof(char *));
3652      /* save off ptrs to column names */
3653      for(i=0; i<nCol; i++){
3654        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3655      }
3656      do{
3657        nRow++;
3658        /* extract the data and data types */
3659        for(i=0; i<nCol; i++){
3660          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3661          if( x==SQLITE_BLOB
3662           && pArg
3663           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3664          ){
3665            azVals[i] = "";
3666          }else{
3667            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3668          }
3669          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3670            rc = SQLITE_NOMEM;
3671            break; /* from for */
3672          }
3673        } /* end for */
3674
3675        /* if data and types extracted successfully... */
3676        if( SQLITE_ROW == rc ){
3677          /* call the supplied callback with the result row data */
3678          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3679            rc = SQLITE_ABORT;
3680          }else{
3681            rc = sqlite3_step(pStmt);
3682          }
3683        }
3684      } while( SQLITE_ROW == rc );
3685      sqlite3_free(pData);
3686      if( pArg->cMode==MODE_Json ){
3687        fputs("]\n", pArg->out);
3688      }else if( pArg->cMode==MODE_Count ){
3689        char zBuf[200];
3690        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3691                         nRow, nRow!=1 ? "s" : "");
3692        printf("%s", zBuf);
3693      }
3694    }
3695  }
3696}
3697
3698#ifndef SQLITE_OMIT_VIRTUALTABLE
3699/*
3700** This function is called to process SQL if the previous shell command
3701** was ".expert". It passes the SQL in the second argument directly to
3702** the sqlite3expert object.
3703**
3704** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3705** code. In this case, (*pzErr) may be set to point to a buffer containing
3706** an English language error message. It is the responsibility of the
3707** caller to eventually free this buffer using sqlite3_free().
3708*/
3709static int expertHandleSQL(
3710  ShellState *pState,
3711  const char *zSql,
3712  char **pzErr
3713){
3714  assert( pState->expert.pExpert );
3715  assert( pzErr==0 || *pzErr==0 );
3716  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3717}
3718
3719/*
3720** This function is called either to silently clean up the object
3721** created by the ".expert" command (if bCancel==1), or to generate a
3722** report from it and then clean it up (if bCancel==0).
3723**
3724** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3725** code. In this case, (*pzErr) may be set to point to a buffer containing
3726** an English language error message. It is the responsibility of the
3727** caller to eventually free this buffer using sqlite3_free().
3728*/
3729static int expertFinish(
3730  ShellState *pState,
3731  int bCancel,
3732  char **pzErr
3733){
3734  int rc = SQLITE_OK;
3735  sqlite3expert *p = pState->expert.pExpert;
3736  assert( p );
3737  assert( bCancel || pzErr==0 || *pzErr==0 );
3738  if( bCancel==0 ){
3739    FILE *out = pState->out;
3740    int bVerbose = pState->expert.bVerbose;
3741
3742    rc = sqlite3_expert_analyze(p, pzErr);
3743    if( rc==SQLITE_OK ){
3744      int nQuery = sqlite3_expert_count(p);
3745      int i;
3746
3747      if( bVerbose ){
3748        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3749        raw_printf(out, "-- Candidates -----------------------------\n");
3750        raw_printf(out, "%s\n", zCand);
3751      }
3752      for(i=0; i<nQuery; i++){
3753        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3754        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3755        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3756        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3757        if( bVerbose ){
3758          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3759          raw_printf(out, "%s\n\n", zSql);
3760        }
3761        raw_printf(out, "%s\n", zIdx);
3762        raw_printf(out, "%s\n", zEQP);
3763      }
3764    }
3765  }
3766  sqlite3_expert_destroy(p);
3767  pState->expert.pExpert = 0;
3768  return rc;
3769}
3770
3771/*
3772** Implementation of ".expert" dot command.
3773*/
3774static int expertDotCommand(
3775  ShellState *pState,             /* Current shell tool state */
3776  char **azArg,                   /* Array of arguments passed to dot command */
3777  int nArg                        /* Number of entries in azArg[] */
3778){
3779  int rc = SQLITE_OK;
3780  char *zErr = 0;
3781  int i;
3782  int iSample = 0;
3783
3784  assert( pState->expert.pExpert==0 );
3785  memset(&pState->expert, 0, sizeof(ExpertInfo));
3786
3787  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3788    char *z = azArg[i];
3789    int n;
3790    if( z[0]=='-' && z[1]=='-' ) z++;
3791    n = strlen30(z);
3792    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3793      pState->expert.bVerbose = 1;
3794    }
3795    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3796      if( i==(nArg-1) ){
3797        raw_printf(stderr, "option requires an argument: %s\n", z);
3798        rc = SQLITE_ERROR;
3799      }else{
3800        iSample = (int)integerValue(azArg[++i]);
3801        if( iSample<0 || iSample>100 ){
3802          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3803          rc = SQLITE_ERROR;
3804        }
3805      }
3806    }
3807    else{
3808      raw_printf(stderr, "unknown option: %s\n", z);
3809      rc = SQLITE_ERROR;
3810    }
3811  }
3812
3813  if( rc==SQLITE_OK ){
3814    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3815    if( pState->expert.pExpert==0 ){
3816      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3817      rc = SQLITE_ERROR;
3818    }else{
3819      sqlite3_expert_config(
3820          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3821      );
3822    }
3823  }
3824  sqlite3_free(zErr);
3825
3826  return rc;
3827}
3828#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3829
3830/*
3831** Execute a statement or set of statements.  Print
3832** any result rows/columns depending on the current mode
3833** set via the supplied callback.
3834**
3835** This is very similar to SQLite's built-in sqlite3_exec()
3836** function except it takes a slightly different callback
3837** and callback data argument.
3838*/
3839static int shell_exec(
3840  ShellState *pArg,                         /* Pointer to ShellState */
3841  const char *zSql,                         /* SQL to be evaluated */
3842  char **pzErrMsg                           /* Error msg written here */
3843){
3844  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3845  int rc = SQLITE_OK;             /* Return Code */
3846  int rc2;
3847  const char *zLeftover;          /* Tail of unprocessed SQL */
3848  sqlite3 *db = pArg->db;
3849
3850  if( pzErrMsg ){
3851    *pzErrMsg = NULL;
3852  }
3853
3854#ifndef SQLITE_OMIT_VIRTUALTABLE
3855  if( pArg->expert.pExpert ){
3856    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3857    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3858  }
3859#endif
3860
3861  while( zSql[0] && (SQLITE_OK == rc) ){
3862    static const char *zStmtSql;
3863    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3864    if( SQLITE_OK != rc ){
3865      if( pzErrMsg ){
3866        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3867      }
3868    }else{
3869      if( !pStmt ){
3870        /* this happens for a comment or white-space */
3871        zSql = zLeftover;
3872        while( IsSpace(zSql[0]) ) zSql++;
3873        continue;
3874      }
3875      zStmtSql = sqlite3_sql(pStmt);
3876      if( zStmtSql==0 ) zStmtSql = "";
3877      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3878
3879      /* save off the prepared statment handle and reset row count */
3880      if( pArg ){
3881        pArg->pStmt = pStmt;
3882        pArg->cnt = 0;
3883      }
3884
3885      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3886      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3887        sqlite3_stmt *pExplain;
3888        char *zEQP;
3889        int triggerEQP = 0;
3890        disable_debug_trace_modes();
3891        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3892        if( pArg->autoEQP>=AUTOEQP_trigger ){
3893          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3894        }
3895        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3896        shell_check_oom(zEQP);
3897        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3898        if( rc==SQLITE_OK ){
3899          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3900            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3901            int iEqpId = sqlite3_column_int(pExplain, 0);
3902            int iParentId = sqlite3_column_int(pExplain, 1);
3903            if( zEQPLine==0 ) zEQPLine = "";
3904            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3905            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3906          }
3907          eqp_render(pArg);
3908        }
3909        sqlite3_finalize(pExplain);
3910        sqlite3_free(zEQP);
3911        if( pArg->autoEQP>=AUTOEQP_full ){
3912          /* Also do an EXPLAIN for ".eqp full" mode */
3913          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3914          shell_check_oom(zEQP);
3915          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3916          if( rc==SQLITE_OK ){
3917            pArg->cMode = MODE_Explain;
3918            explain_data_prepare(pArg, pExplain);
3919            exec_prepared_stmt(pArg, pExplain);
3920            explain_data_delete(pArg);
3921          }
3922          sqlite3_finalize(pExplain);
3923          sqlite3_free(zEQP);
3924        }
3925        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3926          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3927          /* Reprepare pStmt before reactiving trace modes */
3928          sqlite3_finalize(pStmt);
3929          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3930          if( pArg ) pArg->pStmt = pStmt;
3931        }
3932        restore_debug_trace_modes();
3933      }
3934
3935      if( pArg ){
3936        pArg->cMode = pArg->mode;
3937        if( pArg->autoExplain ){
3938          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3939            pArg->cMode = MODE_Explain;
3940          }
3941          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3942            pArg->cMode = MODE_EQP;
3943          }
3944        }
3945
3946        /* If the shell is currently in ".explain" mode, gather the extra
3947        ** data required to add indents to the output.*/
3948        if( pArg->cMode==MODE_Explain ){
3949          explain_data_prepare(pArg, pStmt);
3950        }
3951      }
3952
3953      bind_prepared_stmt(pArg, pStmt);
3954      exec_prepared_stmt(pArg, pStmt);
3955      explain_data_delete(pArg);
3956      eqp_render(pArg);
3957
3958      /* print usage stats if stats on */
3959      if( pArg && pArg->statsOn ){
3960        display_stats(db, pArg, 0);
3961      }
3962
3963      /* print loop-counters if required */
3964      if( pArg && pArg->scanstatsOn ){
3965        display_scanstats(db, pArg);
3966      }
3967
3968      /* Finalize the statement just executed. If this fails, save a
3969      ** copy of the error message. Otherwise, set zSql to point to the
3970      ** next statement to execute. */
3971      rc2 = sqlite3_finalize(pStmt);
3972      if( rc!=SQLITE_NOMEM ) rc = rc2;
3973      if( rc==SQLITE_OK ){
3974        zSql = zLeftover;
3975        while( IsSpace(zSql[0]) ) zSql++;
3976      }else if( pzErrMsg ){
3977        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3978      }
3979
3980      /* clear saved stmt handle */
3981      if( pArg ){
3982        pArg->pStmt = NULL;
3983      }
3984    }
3985  } /* end while */
3986
3987  return rc;
3988}
3989
3990/*
3991** Release memory previously allocated by tableColumnList().
3992*/
3993static void freeColumnList(char **azCol){
3994  int i;
3995  for(i=1; azCol[i]; i++){
3996    sqlite3_free(azCol[i]);
3997  }
3998  /* azCol[0] is a static string */
3999  sqlite3_free(azCol);
4000}
4001
4002/*
4003** Return a list of pointers to strings which are the names of all
4004** columns in table zTab.   The memory to hold the names is dynamically
4005** allocated and must be released by the caller using a subsequent call
4006** to freeColumnList().
4007**
4008** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
4009** value that needs to be preserved, then azCol[0] is filled in with the
4010** name of the rowid column.
4011**
4012** The first regular column in the table is azCol[1].  The list is terminated
4013** by an entry with azCol[i]==0.
4014*/
4015static char **tableColumnList(ShellState *p, const char *zTab){
4016  char **azCol = 0;
4017  sqlite3_stmt *pStmt;
4018  char *zSql;
4019  int nCol = 0;
4020  int nAlloc = 0;
4021  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
4022  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
4023  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4024  int rc;
4025
4026  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4027  shell_check_oom(zSql);
4028  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4029  sqlite3_free(zSql);
4030  if( rc ) return 0;
4031  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4032    if( nCol>=nAlloc-2 ){
4033      nAlloc = nAlloc*2 + nCol + 10;
4034      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4035      shell_check_oom(azCol);
4036    }
4037    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4038    shell_check_oom(azCol[nCol]);
4039    if( sqlite3_column_int(pStmt, 5) ){
4040      nPK++;
4041      if( nPK==1
4042       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4043                          "INTEGER")==0
4044      ){
4045        isIPK = 1;
4046      }else{
4047        isIPK = 0;
4048      }
4049    }
4050  }
4051  sqlite3_finalize(pStmt);
4052  if( azCol==0 ) return 0;
4053  azCol[0] = 0;
4054  azCol[nCol+1] = 0;
4055
4056  /* The decision of whether or not a rowid really needs to be preserved
4057  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4058  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4059  ** rowids on tables where the rowid is inaccessible because there are other
4060  ** columns in the table named "rowid", "_rowid_", and "oid".
4061  */
4062  if( preserveRowid && isIPK ){
4063    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4064    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4065    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4066    ** ROWID aliases.  To distinguish these cases, check to see if
4067    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4068    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4069    */
4070    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4071                           " WHERE origin='pk'", zTab);
4072    shell_check_oom(zSql);
4073    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4074    sqlite3_free(zSql);
4075    if( rc ){
4076      freeColumnList(azCol);
4077      return 0;
4078    }
4079    rc = sqlite3_step(pStmt);
4080    sqlite3_finalize(pStmt);
4081    preserveRowid = rc==SQLITE_ROW;
4082  }
4083  if( preserveRowid ){
4084    /* Only preserve the rowid if we can find a name to use for the
4085    ** rowid */
4086    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4087    int i, j;
4088    for(j=0; j<3; j++){
4089      for(i=1; i<=nCol; i++){
4090        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4091      }
4092      if( i>nCol ){
4093        /* At this point, we know that azRowid[j] is not the name of any
4094        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4095        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4096        ** tables will fail this last check */
4097        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4098        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4099        break;
4100      }
4101    }
4102  }
4103  return azCol;
4104}
4105
4106/*
4107** Toggle the reverse_unordered_selects setting.
4108*/
4109static void toggleSelectOrder(sqlite3 *db){
4110  sqlite3_stmt *pStmt = 0;
4111  int iSetting = 0;
4112  char zStmt[100];
4113  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4114  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4115    iSetting = sqlite3_column_int(pStmt, 0);
4116  }
4117  sqlite3_finalize(pStmt);
4118  sqlite3_snprintf(sizeof(zStmt), zStmt,
4119       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4120  sqlite3_exec(db, zStmt, 0, 0, 0);
4121}
4122
4123/*
4124** This is a different callback routine used for dumping the database.
4125** Each row received by this callback consists of a table name,
4126** the table type ("index" or "table") and SQL to create the table.
4127** This routine should print text sufficient to recreate the table.
4128*/
4129static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4130  int rc;
4131  const char *zTable;
4132  const char *zType;
4133  const char *zSql;
4134  ShellState *p = (ShellState *)pArg;
4135  int dataOnly;
4136  int noSys;
4137
4138  UNUSED_PARAMETER(azNotUsed);
4139  if( nArg!=3 || azArg==0 ) return 0;
4140  zTable = azArg[0];
4141  zType = azArg[1];
4142  zSql = azArg[2];
4143  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4144  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4145
4146  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4147    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4148  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4149    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4150  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4151    return 0;
4152  }else if( dataOnly ){
4153    /* no-op */
4154  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4155    char *zIns;
4156    if( !p->writableSchema ){
4157      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4158      p->writableSchema = 1;
4159    }
4160    zIns = sqlite3_mprintf(
4161       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4162       "VALUES('table','%q','%q',0,'%q');",
4163       zTable, zTable, zSql);
4164    shell_check_oom(zIns);
4165    utf8_printf(p->out, "%s\n", zIns);
4166    sqlite3_free(zIns);
4167    return 0;
4168  }else{
4169    printSchemaLine(p->out, zSql, ";\n");
4170  }
4171
4172  if( strcmp(zType, "table")==0 ){
4173    ShellText sSelect;
4174    ShellText sTable;
4175    char **azCol;
4176    int i;
4177    char *savedDestTable;
4178    int savedMode;
4179
4180    azCol = tableColumnList(p, zTable);
4181    if( azCol==0 ){
4182      p->nErr++;
4183      return 0;
4184    }
4185
4186    /* Always quote the table name, even if it appears to be pure ascii,
4187    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4188    initText(&sTable);
4189    appendText(&sTable, zTable, quoteChar(zTable));
4190    /* If preserving the rowid, add a column list after the table name.
4191    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4192    ** instead of the usual "INSERT INTO tab VALUES(...)".
4193    */
4194    if( azCol[0] ){
4195      appendText(&sTable, "(", 0);
4196      appendText(&sTable, azCol[0], 0);
4197      for(i=1; azCol[i]; i++){
4198        appendText(&sTable, ",", 0);
4199        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4200      }
4201      appendText(&sTable, ")", 0);
4202    }
4203
4204    /* Build an appropriate SELECT statement */
4205    initText(&sSelect);
4206    appendText(&sSelect, "SELECT ", 0);
4207    if( azCol[0] ){
4208      appendText(&sSelect, azCol[0], 0);
4209      appendText(&sSelect, ",", 0);
4210    }
4211    for(i=1; azCol[i]; i++){
4212      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4213      if( azCol[i+1] ){
4214        appendText(&sSelect, ",", 0);
4215      }
4216    }
4217    freeColumnList(azCol);
4218    appendText(&sSelect, " FROM ", 0);
4219    appendText(&sSelect, zTable, quoteChar(zTable));
4220
4221    savedDestTable = p->zDestTable;
4222    savedMode = p->mode;
4223    p->zDestTable = sTable.z;
4224    p->mode = p->cMode = MODE_Insert;
4225    rc = shell_exec(p, sSelect.z, 0);
4226    if( (rc&0xff)==SQLITE_CORRUPT ){
4227      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4228      toggleSelectOrder(p->db);
4229      shell_exec(p, sSelect.z, 0);
4230      toggleSelectOrder(p->db);
4231    }
4232    p->zDestTable = savedDestTable;
4233    p->mode = savedMode;
4234    freeText(&sTable);
4235    freeText(&sSelect);
4236    if( rc ) p->nErr++;
4237  }
4238  return 0;
4239}
4240
4241/*
4242** Run zQuery.  Use dump_callback() as the callback routine so that
4243** the contents of the query are output as SQL statements.
4244**
4245** If we get a SQLITE_CORRUPT error, rerun the query after appending
4246** "ORDER BY rowid DESC" to the end.
4247*/
4248static int run_schema_dump_query(
4249  ShellState *p,
4250  const char *zQuery
4251){
4252  int rc;
4253  char *zErr = 0;
4254  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4255  if( rc==SQLITE_CORRUPT ){
4256    char *zQ2;
4257    int len = strlen30(zQuery);
4258    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4259    if( zErr ){
4260      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4261      sqlite3_free(zErr);
4262      zErr = 0;
4263    }
4264    zQ2 = malloc( len+100 );
4265    if( zQ2==0 ) return rc;
4266    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4267    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4268    if( rc ){
4269      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4270    }else{
4271      rc = SQLITE_CORRUPT;
4272    }
4273    sqlite3_free(zErr);
4274    free(zQ2);
4275  }
4276  return rc;
4277}
4278
4279/*
4280** Text of help messages.
4281**
4282** The help text for each individual command begins with a line that starts
4283** with ".".  Subsequent lines are supplemental information.
4284**
4285** There must be two or more spaces between the end of the command and the
4286** start of the description of what that command does.
4287*/
4288static const char *(azHelp[]) = {
4289#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4290  && !defined(SQLITE_SHELL_FIDDLE)
4291  ".archive ...             Manage SQL archives",
4292  "   Each command must have exactly one of the following options:",
4293  "     -c, --create               Create a new archive",
4294  "     -u, --update               Add or update files with changed mtime",
4295  "     -i, --insert               Like -u but always add even if unchanged",
4296  "     -r, --remove               Remove files from archive",
4297  "     -t, --list                 List contents of archive",
4298  "     -x, --extract              Extract files from archive",
4299  "   Optional arguments:",
4300  "     -v, --verbose              Print each filename as it is processed",
4301  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4302  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4303  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4304  "     -g, --glob                 Use glob matching for names in archive",
4305  "     -n, --dryrun               Show the SQL that would have occurred",
4306  "   Examples:",
4307  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4308  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4309  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4310  "   See also:",
4311  "      http://sqlite.org/cli.html#sqlite_archive_support",
4312#endif
4313#ifndef SQLITE_OMIT_AUTHORIZATION
4314  ".auth ON|OFF             Show authorizer callbacks",
4315#endif
4316#ifndef SQLITE_SHELL_FIDDLE
4317  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4318  "   Options:",
4319  "       --append            Use the appendvfs",
4320  "       --async             Write to FILE without journal and fsync()",
4321#endif
4322  ".bail on|off             Stop after hitting an error.  Default OFF",
4323  ".binary on|off           Turn binary output on or off.  Default OFF",
4324#ifndef SQLITE_SHELL_FIDDLE
4325  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4326#endif
4327  ".changes on|off          Show number of rows changed by SQL",
4328#ifndef SQLITE_SHELL_FIDDLE
4329  ".check GLOB              Fail if output since .testcase does not match",
4330  ".clone NEWDB             Clone data into NEWDB from the existing database",
4331#endif
4332  ".connection [close] [#]  Open or close an auxiliary database connection",
4333  ".databases               List names and files of attached databases",
4334  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4335#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4336  ".dbinfo ?DB?             Show status information about the database",
4337#endif
4338  ".dump ?OBJECTS?          Render database content as SQL",
4339  "   Options:",
4340  "     --data-only            Output only INSERT statements",
4341  "     --newlines             Allow unescaped newline characters in output",
4342  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4343  "     --preserve-rowids      Include ROWID values in the output",
4344  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4345  "   Additional LIKE patterns can be given in subsequent arguments",
4346  ".echo on|off             Turn command echo on or off",
4347  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4348  "   Other Modes:",
4349#ifdef SQLITE_DEBUG
4350  "      test                  Show raw EXPLAIN QUERY PLAN output",
4351  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4352#endif
4353  "      trigger               Like \"full\" but also show trigger bytecode",
4354#ifndef SQLITE_SHELL_FIDDLE
4355  ".excel                   Display the output of next command in spreadsheet",
4356  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4357#endif
4358#ifndef SQLITE_SHELL_FIDDLE
4359  ".exit ?CODE?             Exit this program with return-code CODE",
4360#endif
4361  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4362  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4363  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4364  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4365  "   --help                  Show CMD details",
4366  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4367  ".headers on|off          Turn display of headers on or off",
4368  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4369#ifndef SQLITE_SHELL_FIDDLE
4370  ".import FILE TABLE       Import data from FILE into TABLE",
4371  "   Options:",
4372  "     --ascii               Use \\037 and \\036 as column and row separators",
4373  "     --csv                 Use , and \\n as column and row separators",
4374  "     --skip N              Skip the first N rows of input",
4375  "     --schema S            Target table to be S.TABLE",
4376  "     -v                    \"Verbose\" - increase auxiliary output",
4377  "   Notes:",
4378  "     *  If TABLE does not exist, it is created.  The first row of input",
4379  "        determines the column names.",
4380  "     *  If neither --csv or --ascii are used, the input mode is derived",
4381  "        from the \".mode\" output mode",
4382  "     *  If FILE begins with \"|\" then it is a command that generates the",
4383  "        input text.",
4384#endif
4385#ifndef SQLITE_OMIT_TEST_CONTROL
4386  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4387#endif
4388  ".indexes ?TABLE?         Show names of indexes",
4389  "                           If TABLE is specified, only show indexes for",
4390  "                           tables matching TABLE using the LIKE operator.",
4391#ifdef SQLITE_ENABLE_IOTRACE
4392  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4393#endif
4394  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4395  ".lint OPTIONS            Report potential schema issues.",
4396  "     Options:",
4397  "        fkey-indexes     Find missing foreign key indexes",
4398#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4399  ".load FILE ?ENTRY?       Load an extension library",
4400#endif
4401#ifndef SQLITE_SHELL_FIDDLE
4402  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4403#endif
4404  ".mode MODE ?OPTIONS?     Set output mode",
4405  "   MODE is one of:",
4406  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4407  "     box         Tables using unicode box-drawing characters",
4408  "     csv         Comma-separated values",
4409  "     column      Output in columns.  (See .width)",
4410  "     html        HTML <table> code",
4411  "     insert      SQL insert statements for TABLE",
4412  "     json        Results in a JSON array",
4413  "     line        One value per line",
4414  "     list        Values delimited by \"|\"",
4415  "     markdown    Markdown table format",
4416  "     qbox        Shorthand for \"box --width 60 --quote\"",
4417  "     quote       Escape answers as for SQL",
4418  "     table       ASCII-art table",
4419  "     tabs        Tab-separated values",
4420  "     tcl         TCL list elements",
4421  "   OPTIONS: (for columnar modes or insert mode):",
4422  "     --wrap N       Wrap output lines to no longer than N characters",
4423  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4424  "     --ww           Shorthand for \"--wordwrap 1\"",
4425  "     --quote        Quote output text as SQL literals",
4426  "     --noquote      Do not quote output text",
4427  "     TABLE          The name of SQL table used for \"insert\" mode",
4428#ifndef SQLITE_SHELL_FIDDLE
4429  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4430#endif
4431  ".nullvalue STRING        Use STRING in place of NULL values",
4432#ifndef SQLITE_SHELL_FIDDLE
4433  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4434  "     If FILE begins with '|' then open as a pipe",
4435  "       --bom  Put a UTF8 byte-order mark at the beginning",
4436  "       -e     Send output to the system text editor",
4437  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4438  /* Note that .open is (partially) available in WASM builds but is
4439  ** currently only intended to be used by the fiddle tool, not
4440  ** end users, so is "undocumented." */
4441  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4442  "     Options:",
4443  "        --append        Use appendvfs to append database to the end of FILE",
4444#endif
4445#ifndef SQLITE_OMIT_DESERIALIZE
4446  "        --deserialize   Load into memory using sqlite3_deserialize()",
4447  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4448  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4449#endif
4450  "        --new           Initialize FILE to an empty database",
4451  "        --nofollow      Do not follow symbolic links",
4452  "        --readonly      Open FILE readonly",
4453  "        --zip           FILE is a ZIP archive",
4454#ifndef SQLITE_SHELL_FIDDLE
4455  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4456  "   If FILE begins with '|' then open it as a pipe.",
4457  "   Options:",
4458  "     --bom                 Prefix output with a UTF8 byte-order mark",
4459  "     -e                    Send output to the system text editor",
4460  "     -x                    Send output as CSV to a spreadsheet",
4461#endif
4462  ".parameter CMD ...       Manage SQL parameter bindings",
4463  "   clear                   Erase all bindings",
4464  "   init                    Initialize the TEMP table that holds bindings",
4465  "   list                    List the current parameter bindings",
4466  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4467  "                           PARAMETER should start with one of: $ : @ ?",
4468  "   unset PARAMETER         Remove PARAMETER from the binding table",
4469  ".print STRING...         Print literal STRING",
4470#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4471  ".progress N              Invoke progress handler after every N opcodes",
4472  "   --limit N                 Interrupt after N progress callbacks",
4473  "   --once                    Do no more than one progress interrupt",
4474  "   --quiet|-q                No output except at interrupts",
4475  "   --reset                   Reset the count for each input and interrupt",
4476#endif
4477  ".prompt MAIN CONTINUE    Replace the standard prompts",
4478#ifndef SQLITE_SHELL_FIDDLE
4479  ".quit                    Exit this program",
4480  ".read FILE               Read input from FILE or command output",
4481  "    If FILE begins with \"|\", it is a command that generates the input.",
4482#endif
4483#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4484  ".recover                 Recover as much data as possible from corrupt db.",
4485  "   --freelist-corrupt       Assume the freelist is corrupt",
4486  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4487  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4488  "   --no-rowids              Do not attempt to recover rowid values",
4489  "                            that are not also INTEGER PRIMARY KEYs",
4490#endif
4491#ifndef SQLITE_SHELL_FIDDLE
4492  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4493  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4494#endif
4495  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4496  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4497  "   Options:",
4498  "      --indent             Try to pretty-print the schema",
4499  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4500  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4501  "    Options:",
4502  "       --init               Create a new SELFTEST table",
4503  "       -v                   Verbose output",
4504  ".separator COL ?ROW?     Change the column and row separators",
4505#if defined(SQLITE_ENABLE_SESSION)
4506  ".session ?NAME? CMD ...  Create or control sessions",
4507  "   Subcommands:",
4508  "     attach TABLE             Attach TABLE",
4509  "     changeset FILE           Write a changeset into FILE",
4510  "     close                    Close one session",
4511  "     enable ?BOOLEAN?         Set or query the enable bit",
4512  "     filter GLOB...           Reject tables matching GLOBs",
4513  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4514  "     isempty                  Query whether the session is empty",
4515  "     list                     List currently open session names",
4516  "     open DB NAME             Open a new session on DB",
4517  "     patchset FILE            Write a patchset into FILE",
4518  "   If ?NAME? is omitted, the first defined session is used.",
4519#endif
4520  ".sha3sum ...             Compute a SHA3 hash of database content",
4521  "    Options:",
4522  "      --schema              Also hash the sqlite_schema table",
4523  "      --sha3-224            Use the sha3-224 algorithm",
4524  "      --sha3-256            Use the sha3-256 algorithm (default)",
4525  "      --sha3-384            Use the sha3-384 algorithm",
4526  "      --sha3-512            Use the sha3-512 algorithm",
4527  "    Any other argument is a LIKE pattern for tables to hash",
4528#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4529  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4530#endif
4531  ".show                    Show the current values for various settings",
4532  ".stats ?ARG?             Show stats or turn stats on or off",
4533  "   off                      Turn off automatic stat display",
4534  "   on                       Turn on automatic stat display",
4535  "   stmt                     Show statement stats",
4536  "   vmstep                   Show the virtual machine step count only",
4537#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4538  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4539#endif
4540  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4541#ifndef SQLITE_SHELL_FIDDLE
4542  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4543#endif
4544  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4545  "                           Run \".testctrl\" with no arguments for details",
4546  ".timeout MS              Try opening locked tables for MS milliseconds",
4547  ".timer on|off            Turn SQL timer on or off",
4548#ifndef SQLITE_OMIT_TRACE
4549  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4550  "    FILE                    Send output to FILE",
4551  "    stdout                  Send output to stdout",
4552  "    stderr                  Send output to stderr",
4553  "    off                     Disable tracing",
4554  "    --expanded              Expand query parameters",
4555#ifdef SQLITE_ENABLE_NORMALIZE
4556  "    --normalized            Normal the SQL statements",
4557#endif
4558  "    --plain                 Show SQL as it is input",
4559  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4560  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4561  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4562  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4563#endif /* SQLITE_OMIT_TRACE */
4564#ifdef SQLITE_DEBUG
4565  ".unmodule NAME ...       Unregister virtual table modules",
4566  "    --allexcept             Unregister everything except those named",
4567#endif
4568  ".vfsinfo ?AUX?           Information about the top-level VFS",
4569  ".vfslist                 List all available VFSes",
4570  ".vfsname ?AUX?           Print the name of the VFS stack",
4571  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4572  "     Negative values right-justify",
4573};
4574
4575/*
4576** Output help text.
4577**
4578** zPattern describes the set of commands for which help text is provided.
4579** If zPattern is NULL, then show all commands, but only give a one-line
4580** description of each.
4581**
4582** Return the number of matches.
4583*/
4584static int showHelp(FILE *out, const char *zPattern){
4585  int i = 0;
4586  int j = 0;
4587  int n = 0;
4588  char *zPat;
4589  if( zPattern==0
4590   || zPattern[0]=='0'
4591   || strcmp(zPattern,"-a")==0
4592   || strcmp(zPattern,"-all")==0
4593   || strcmp(zPattern,"--all")==0
4594  ){
4595    /* Show all commands, but only one line per command */
4596    if( zPattern==0 ) zPattern = "";
4597    for(i=0; i<ArraySize(azHelp); i++){
4598      if( azHelp[i][0]=='.' || zPattern[0] ){
4599        utf8_printf(out, "%s\n", azHelp[i]);
4600        n++;
4601      }
4602    }
4603  }else{
4604    /* Look for commands that for which zPattern is an exact prefix */
4605    zPat = sqlite3_mprintf(".%s*", zPattern);
4606    shell_check_oom(zPat);
4607    for(i=0; i<ArraySize(azHelp); i++){
4608      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4609        utf8_printf(out, "%s\n", azHelp[i]);
4610        j = i+1;
4611        n++;
4612      }
4613    }
4614    sqlite3_free(zPat);
4615    if( n ){
4616      if( n==1 ){
4617        /* when zPattern is a prefix of exactly one command, then include the
4618        ** details of that command, which should begin at offset j */
4619        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4620          utf8_printf(out, "%s\n", azHelp[j]);
4621          j++;
4622        }
4623      }
4624      return n;
4625    }
4626    /* Look for commands that contain zPattern anywhere.  Show the complete
4627    ** text of all commands that match. */
4628    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4629    shell_check_oom(zPat);
4630    for(i=0; i<ArraySize(azHelp); i++){
4631      if( azHelp[i][0]=='.' ) j = i;
4632      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4633        utf8_printf(out, "%s\n", azHelp[j]);
4634        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4635          j++;
4636          utf8_printf(out, "%s\n", azHelp[j]);
4637        }
4638        i = j;
4639        n++;
4640      }
4641    }
4642    sqlite3_free(zPat);
4643  }
4644  return n;
4645}
4646
4647/* Forward reference */
4648static int process_input(ShellState *p);
4649
4650/*
4651** Read the content of file zName into memory obtained from sqlite3_malloc64()
4652** and return a pointer to the buffer. The caller is responsible for freeing
4653** the memory.
4654**
4655** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4656** read.
4657**
4658** For convenience, a nul-terminator byte is always appended to the data read
4659** from the file before the buffer is returned. This byte is not included in
4660** the final value of (*pnByte), if applicable.
4661**
4662** NULL is returned if any error is encountered. The final value of *pnByte
4663** is undefined in this case.
4664*/
4665static char *readFile(const char *zName, int *pnByte){
4666  FILE *in = fopen(zName, "rb");
4667  long nIn;
4668  size_t nRead;
4669  char *pBuf;
4670  if( in==0 ) return 0;
4671  fseek(in, 0, SEEK_END);
4672  nIn = ftell(in);
4673  rewind(in);
4674  pBuf = sqlite3_malloc64( nIn+1 );
4675  if( pBuf==0 ){ fclose(in); return 0; }
4676  nRead = fread(pBuf, nIn, 1, in);
4677  fclose(in);
4678  if( nRead!=1 ){
4679    sqlite3_free(pBuf);
4680    return 0;
4681  }
4682  pBuf[nIn] = 0;
4683  if( pnByte ) *pnByte = nIn;
4684  return pBuf;
4685}
4686
4687#if defined(SQLITE_ENABLE_SESSION)
4688/*
4689** Close a single OpenSession object and release all of its associated
4690** resources.
4691*/
4692static void session_close(OpenSession *pSession){
4693  int i;
4694  sqlite3session_delete(pSession->p);
4695  sqlite3_free(pSession->zName);
4696  for(i=0; i<pSession->nFilter; i++){
4697    sqlite3_free(pSession->azFilter[i]);
4698  }
4699  sqlite3_free(pSession->azFilter);
4700  memset(pSession, 0, sizeof(OpenSession));
4701}
4702#endif
4703
4704/*
4705** Close all OpenSession objects and release all associated resources.
4706*/
4707#if defined(SQLITE_ENABLE_SESSION)
4708static void session_close_all(ShellState *p, int i){
4709  int j;
4710  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4711  for(j=0; j<pAuxDb->nSession; j++){
4712    session_close(&pAuxDb->aSession[j]);
4713  }
4714  pAuxDb->nSession = 0;
4715}
4716#else
4717# define session_close_all(X,Y)
4718#endif
4719
4720/*
4721** Implementation of the xFilter function for an open session.  Omit
4722** any tables named by ".session filter" but let all other table through.
4723*/
4724#if defined(SQLITE_ENABLE_SESSION)
4725static int session_filter(void *pCtx, const char *zTab){
4726  OpenSession *pSession = (OpenSession*)pCtx;
4727  int i;
4728  for(i=0; i<pSession->nFilter; i++){
4729    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4730  }
4731  return 1;
4732}
4733#endif
4734
4735/*
4736** Try to deduce the type of file for zName based on its content.  Return
4737** one of the SHELL_OPEN_* constants.
4738**
4739** If the file does not exist or is empty but its name looks like a ZIP
4740** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4741** Otherwise, assume an ordinary database regardless of the filename if
4742** the type cannot be determined from content.
4743*/
4744int deduceDatabaseType(const char *zName, int dfltZip){
4745  FILE *f = fopen(zName, "rb");
4746  size_t n;
4747  int rc = SHELL_OPEN_UNSPEC;
4748  char zBuf[100];
4749  if( f==0 ){
4750    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4751       return SHELL_OPEN_ZIPFILE;
4752    }else{
4753       return SHELL_OPEN_NORMAL;
4754    }
4755  }
4756  n = fread(zBuf, 16, 1, f);
4757  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4758    fclose(f);
4759    return SHELL_OPEN_NORMAL;
4760  }
4761  fseek(f, -25, SEEK_END);
4762  n = fread(zBuf, 25, 1, f);
4763  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4764    rc = SHELL_OPEN_APPENDVFS;
4765  }else{
4766    fseek(f, -22, SEEK_END);
4767    n = fread(zBuf, 22, 1, f);
4768    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4769       && zBuf[3]==0x06 ){
4770      rc = SHELL_OPEN_ZIPFILE;
4771    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4772      rc = SHELL_OPEN_ZIPFILE;
4773    }
4774  }
4775  fclose(f);
4776  return rc;
4777}
4778
4779#ifndef SQLITE_OMIT_DESERIALIZE
4780/*
4781** Reconstruct an in-memory database using the output from the "dbtotxt"
4782** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4783** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4784*/
4785static unsigned char *readHexDb(ShellState *p, int *pnData){
4786  unsigned char *a = 0;
4787  int nLine;
4788  int n = 0;
4789  int pgsz = 0;
4790  int iOffset = 0;
4791  int j, k;
4792  int rc;
4793  FILE *in;
4794  const char *zDbFilename = p->pAuxDb->zDbFilename;
4795  unsigned int x[16];
4796  char zLine[1000];
4797  if( zDbFilename ){
4798    in = fopen(zDbFilename, "r");
4799    if( in==0 ){
4800      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4801      return 0;
4802    }
4803    nLine = 0;
4804  }else{
4805    in = p->in;
4806    nLine = p->lineno;
4807    if( in==0 ) in = stdin;
4808  }
4809  *pnData = 0;
4810  nLine++;
4811  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4812  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4813  if( rc!=2 ) goto readHexDb_error;
4814  if( n<0 ) goto readHexDb_error;
4815  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4816  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4817  a = sqlite3_malloc( n ? n : 1 );
4818  shell_check_oom(a);
4819  memset(a, 0, n);
4820  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4821    utf8_printf(stderr, "invalid pagesize\n");
4822    goto readHexDb_error;
4823  }
4824  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4825    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4826    if( rc==2 ){
4827      iOffset = k;
4828      continue;
4829    }
4830    if( strncmp(zLine, "| end ", 6)==0 ){
4831      break;
4832    }
4833    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4834                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4835                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4836    if( rc==17 ){
4837      k = iOffset+j;
4838      if( k+16<=n && k>=0 ){
4839        int ii;
4840        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4841      }
4842    }
4843  }
4844  *pnData = n;
4845  if( in!=p->in ){
4846    fclose(in);
4847  }else{
4848    p->lineno = nLine;
4849  }
4850  return a;
4851
4852readHexDb_error:
4853  if( in!=p->in ){
4854    fclose(in);
4855  }else{
4856    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4857      nLine++;
4858      if(strncmp(zLine, "| end ", 6)==0 ) break;
4859    }
4860    p->lineno = nLine;
4861  }
4862  sqlite3_free(a);
4863  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4864  return 0;
4865}
4866#endif /* SQLITE_OMIT_DESERIALIZE */
4867
4868/*
4869** Scalar function "shell_int32". The first argument to this function
4870** must be a blob. The second a non-negative integer. This function
4871** reads and returns a 32-bit big-endian integer from byte
4872** offset (4*<arg2>) of the blob.
4873*/
4874static void shellInt32(
4875  sqlite3_context *context,
4876  int argc,
4877  sqlite3_value **argv
4878){
4879  const unsigned char *pBlob;
4880  int nBlob;
4881  int iInt;
4882
4883  UNUSED_PARAMETER(argc);
4884  nBlob = sqlite3_value_bytes(argv[0]);
4885  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4886  iInt = sqlite3_value_int(argv[1]);
4887
4888  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4889    const unsigned char *a = &pBlob[iInt*4];
4890    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4891                       + ((sqlite3_int64)a[1]<<16)
4892                       + ((sqlite3_int64)a[2]<< 8)
4893                       + ((sqlite3_int64)a[3]<< 0);
4894    sqlite3_result_int64(context, iVal);
4895  }
4896}
4897
4898/*
4899** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4900** using "..." with internal double-quote characters doubled.
4901*/
4902static void shellIdQuote(
4903  sqlite3_context *context,
4904  int argc,
4905  sqlite3_value **argv
4906){
4907  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4908  UNUSED_PARAMETER(argc);
4909  if( zName ){
4910    char *z = sqlite3_mprintf("\"%w\"", zName);
4911    sqlite3_result_text(context, z, -1, sqlite3_free);
4912  }
4913}
4914
4915/*
4916** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4917*/
4918static void shellUSleepFunc(
4919  sqlite3_context *context,
4920  int argcUnused,
4921  sqlite3_value **argv
4922){
4923  int sleep = sqlite3_value_int(argv[0]);
4924  (void)argcUnused;
4925  sqlite3_sleep(sleep/1000);
4926  sqlite3_result_int(context, sleep);
4927}
4928
4929/*
4930** Scalar function "shell_escape_crnl" used by the .recover command.
4931** The argument passed to this function is the output of built-in
4932** function quote(). If the first character of the input is "'",
4933** indicating that the value passed to quote() was a text value,
4934** then this function searches the input for "\n" and "\r" characters
4935** and adds a wrapper similar to the following:
4936**
4937**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4938**
4939** Or, if the first character of the input is not "'", then a copy
4940** of the input is returned.
4941*/
4942static void shellEscapeCrnl(
4943  sqlite3_context *context,
4944  int argc,
4945  sqlite3_value **argv
4946){
4947  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4948  UNUSED_PARAMETER(argc);
4949  if( zText && zText[0]=='\'' ){
4950    int nText = sqlite3_value_bytes(argv[0]);
4951    int i;
4952    char zBuf1[20];
4953    char zBuf2[20];
4954    const char *zNL = 0;
4955    const char *zCR = 0;
4956    int nCR = 0;
4957    int nNL = 0;
4958
4959    for(i=0; zText[i]; i++){
4960      if( zNL==0 && zText[i]=='\n' ){
4961        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4962        nNL = (int)strlen(zNL);
4963      }
4964      if( zCR==0 && zText[i]=='\r' ){
4965        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4966        nCR = (int)strlen(zCR);
4967      }
4968    }
4969
4970    if( zNL || zCR ){
4971      int iOut = 0;
4972      i64 nMax = (nNL > nCR) ? nNL : nCR;
4973      i64 nAlloc = nMax * nText + (nMax+64)*2;
4974      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4975      if( zOut==0 ){
4976        sqlite3_result_error_nomem(context);
4977        return;
4978      }
4979
4980      if( zNL && zCR ){
4981        memcpy(&zOut[iOut], "replace(replace(", 16);
4982        iOut += 16;
4983      }else{
4984        memcpy(&zOut[iOut], "replace(", 8);
4985        iOut += 8;
4986      }
4987      for(i=0; zText[i]; i++){
4988        if( zText[i]=='\n' ){
4989          memcpy(&zOut[iOut], zNL, nNL);
4990          iOut += nNL;
4991        }else if( zText[i]=='\r' ){
4992          memcpy(&zOut[iOut], zCR, nCR);
4993          iOut += nCR;
4994        }else{
4995          zOut[iOut] = zText[i];
4996          iOut++;
4997        }
4998      }
4999
5000      if( zNL ){
5001        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5002        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
5003        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
5004      }
5005      if( zCR ){
5006        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5007        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
5008        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
5009      }
5010
5011      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
5012      sqlite3_free(zOut);
5013      return;
5014    }
5015  }
5016
5017  sqlite3_result_value(context, argv[0]);
5018}
5019
5020/* Flags for open_db().
5021**
5022** The default behavior of open_db() is to exit(1) if the database fails to
5023** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5024** but still returns without calling exit.
5025**
5026** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5027** ZIP archive if the file does not exist or is empty and its name matches
5028** the *.zip pattern.
5029*/
5030#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5031#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5032
5033/*
5034** Make sure the database is open.  If it is not, then open it.  If
5035** the database fails to open, print an error message and exit.
5036*/
5037static void open_db(ShellState *p, int openFlags){
5038  if( p->db==0 ){
5039    const char *zDbFilename = p->pAuxDb->zDbFilename;
5040    if( p->openMode==SHELL_OPEN_UNSPEC ){
5041      if( zDbFilename==0 || zDbFilename[0]==0 ){
5042        p->openMode = SHELL_OPEN_NORMAL;
5043      }else{
5044        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5045                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5046      }
5047    }
5048    switch( p->openMode ){
5049      case SHELL_OPEN_APPENDVFS: {
5050        sqlite3_open_v2(zDbFilename, &p->db,
5051           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5052        break;
5053      }
5054      case SHELL_OPEN_HEXDB:
5055      case SHELL_OPEN_DESERIALIZE: {
5056        sqlite3_open(0, &p->db);
5057        break;
5058      }
5059      case SHELL_OPEN_ZIPFILE: {
5060        sqlite3_open(":memory:", &p->db);
5061        break;
5062      }
5063      case SHELL_OPEN_READONLY: {
5064        sqlite3_open_v2(zDbFilename, &p->db,
5065            SQLITE_OPEN_READONLY|p->openFlags, 0);
5066        break;
5067      }
5068      case SHELL_OPEN_UNSPEC:
5069      case SHELL_OPEN_NORMAL: {
5070        sqlite3_open_v2(zDbFilename, &p->db,
5071           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5072        break;
5073      }
5074    }
5075    globalDb = p->db;
5076    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5077      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5078          zDbFilename, sqlite3_errmsg(p->db));
5079      if( openFlags & OPEN_DB_KEEPALIVE ){
5080        sqlite3_open(":memory:", &p->db);
5081        return;
5082      }
5083      exit(1);
5084    }
5085#ifndef SQLITE_OMIT_LOAD_EXTENSION
5086    sqlite3_enable_load_extension(p->db, 1);
5087#endif
5088    sqlite3_shathree_init(p->db, 0, 0);
5089    sqlite3_uint_init(p->db, 0, 0);
5090    sqlite3_decimal_init(p->db, 0, 0);
5091    sqlite3_regexp_init(p->db, 0, 0);
5092    sqlite3_ieee_init(p->db, 0, 0);
5093    sqlite3_series_init(p->db, 0, 0);
5094#ifndef SQLITE_SHELL_FIDDLE
5095    sqlite3_fileio_init(p->db, 0, 0);
5096    sqlite3_completion_init(p->db, 0, 0);
5097#endif
5098#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5099    sqlite3_dbdata_init(p->db, 0, 0);
5100#endif
5101#ifdef SQLITE_HAVE_ZLIB
5102    if( !p->bSafeModePersist ){
5103      sqlite3_zipfile_init(p->db, 0, 0);
5104      sqlite3_sqlar_init(p->db, 0, 0);
5105    }
5106#endif
5107    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5108                            shellAddSchemaName, 0, 0);
5109    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5110                            shellModuleSchema, 0, 0);
5111    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5112                            shellPutsFunc, 0, 0);
5113    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5114                            shellEscapeCrnl, 0, 0);
5115    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5116                            shellInt32, 0, 0);
5117    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5118                            shellIdQuote, 0, 0);
5119    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5120                            shellUSleepFunc, 0, 0);
5121#ifndef SQLITE_NOHAVE_SYSTEM
5122    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5123                            editFunc, 0, 0);
5124    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5125                            editFunc, 0, 0);
5126#endif
5127    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5128      char *zSql = sqlite3_mprintf(
5129         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5130      shell_check_oom(zSql);
5131      sqlite3_exec(p->db, zSql, 0, 0, 0);
5132      sqlite3_free(zSql);
5133    }
5134#ifndef SQLITE_OMIT_DESERIALIZE
5135    else
5136    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5137      int rc;
5138      int nData = 0;
5139      unsigned char *aData;
5140      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5141        aData = (unsigned char*)readFile(zDbFilename, &nData);
5142      }else{
5143        aData = readHexDb(p, &nData);
5144        if( aData==0 ){
5145          return;
5146        }
5147      }
5148      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5149                   SQLITE_DESERIALIZE_RESIZEABLE |
5150                   SQLITE_DESERIALIZE_FREEONCLOSE);
5151      if( rc ){
5152        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5153      }
5154      if( p->szMax>0 ){
5155        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5156      }
5157    }
5158#endif
5159  }
5160  if( p->bSafeModePersist && p->db!=0 ){
5161    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5162  }
5163}
5164
5165/*
5166** Attempt to close the databaes connection.  Report errors.
5167*/
5168void close_db(sqlite3 *db){
5169  int rc = sqlite3_close(db);
5170  if( rc ){
5171    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5172        rc, sqlite3_errmsg(db));
5173  }
5174}
5175
5176#if HAVE_READLINE || HAVE_EDITLINE
5177/*
5178** Readline completion callbacks
5179*/
5180static char *readline_completion_generator(const char *text, int state){
5181  static sqlite3_stmt *pStmt = 0;
5182  char *zRet;
5183  if( state==0 ){
5184    char *zSql;
5185    sqlite3_finalize(pStmt);
5186    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5187                           "  FROM completion(%Q) ORDER BY 1", text);
5188    shell_check_oom(zSql);
5189    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5190    sqlite3_free(zSql);
5191  }
5192  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5193    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5194    zRet = z ? strdup(z) : 0;
5195  }else{
5196    sqlite3_finalize(pStmt);
5197    pStmt = 0;
5198    zRet = 0;
5199  }
5200  return zRet;
5201}
5202static char **readline_completion(const char *zText, int iStart, int iEnd){
5203  rl_attempted_completion_over = 1;
5204  return rl_completion_matches(zText, readline_completion_generator);
5205}
5206
5207#elif HAVE_LINENOISE
5208/*
5209** Linenoise completion callback
5210*/
5211static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5212  int nLine = strlen30(zLine);
5213  int i, iStart;
5214  sqlite3_stmt *pStmt = 0;
5215  char *zSql;
5216  char zBuf[1000];
5217
5218  if( nLine>sizeof(zBuf)-30 ) return;
5219  if( zLine[0]=='.' || zLine[0]=='#') return;
5220  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5221  if( i==nLine-1 ) return;
5222  iStart = i+1;
5223  memcpy(zBuf, zLine, iStart);
5224  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5225                         "  FROM completion(%Q,%Q) ORDER BY 1",
5226                         &zLine[iStart], zLine);
5227  shell_check_oom(zSql);
5228  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5229  sqlite3_free(zSql);
5230  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5231  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5232    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5233    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5234    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5235      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5236      linenoiseAddCompletion(lc, zBuf);
5237    }
5238  }
5239  sqlite3_finalize(pStmt);
5240}
5241#endif
5242
5243/*
5244** Do C-language style dequoting.
5245**
5246**    \a    -> alarm
5247**    \b    -> backspace
5248**    \t    -> tab
5249**    \n    -> newline
5250**    \v    -> vertical tab
5251**    \f    -> form feed
5252**    \r    -> carriage return
5253**    \s    -> space
5254**    \"    -> "
5255**    \'    -> '
5256**    \\    -> backslash
5257**    \NNN  -> ascii character NNN in octal
5258*/
5259static void resolve_backslashes(char *z){
5260  int i, j;
5261  char c;
5262  while( *z && *z!='\\' ) z++;
5263  for(i=j=0; (c = z[i])!=0; i++, j++){
5264    if( c=='\\' && z[i+1]!=0 ){
5265      c = z[++i];
5266      if( c=='a' ){
5267        c = '\a';
5268      }else if( c=='b' ){
5269        c = '\b';
5270      }else if( c=='t' ){
5271        c = '\t';
5272      }else if( c=='n' ){
5273        c = '\n';
5274      }else if( c=='v' ){
5275        c = '\v';
5276      }else if( c=='f' ){
5277        c = '\f';
5278      }else if( c=='r' ){
5279        c = '\r';
5280      }else if( c=='"' ){
5281        c = '"';
5282      }else if( c=='\'' ){
5283        c = '\'';
5284      }else if( c=='\\' ){
5285        c = '\\';
5286      }else if( c>='0' && c<='7' ){
5287        c -= '0';
5288        if( z[i+1]>='0' && z[i+1]<='7' ){
5289          i++;
5290          c = (c<<3) + z[i] - '0';
5291          if( z[i+1]>='0' && z[i+1]<='7' ){
5292            i++;
5293            c = (c<<3) + z[i] - '0';
5294          }
5295        }
5296      }
5297    }
5298    z[j] = c;
5299  }
5300  if( j<i ) z[j] = 0;
5301}
5302
5303/*
5304** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5305** for TRUE and FALSE.  Return the integer value if appropriate.
5306*/
5307static int booleanValue(const char *zArg){
5308  int i;
5309  if( zArg[0]=='0' && zArg[1]=='x' ){
5310    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5311  }else{
5312    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5313  }
5314  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5315  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5316    return 1;
5317  }
5318  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5319    return 0;
5320  }
5321  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5322          zArg);
5323  return 0;
5324}
5325
5326/*
5327** Set or clear a shell flag according to a boolean value.
5328*/
5329static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5330  if( booleanValue(zArg) ){
5331    ShellSetFlag(p, mFlag);
5332  }else{
5333    ShellClearFlag(p, mFlag);
5334  }
5335}
5336
5337/*
5338** Close an output file, assuming it is not stderr or stdout
5339*/
5340static void output_file_close(FILE *f){
5341  if( f && f!=stdout && f!=stderr ) fclose(f);
5342}
5343
5344/*
5345** Try to open an output file.   The names "stdout" and "stderr" are
5346** recognized and do the right thing.  NULL is returned if the output
5347** filename is "off".
5348*/
5349static FILE *output_file_open(const char *zFile, int bTextMode){
5350  FILE *f;
5351  if( strcmp(zFile,"stdout")==0 ){
5352    f = stdout;
5353  }else if( strcmp(zFile, "stderr")==0 ){
5354    f = stderr;
5355  }else if( strcmp(zFile, "off")==0 ){
5356    f = 0;
5357  }else{
5358    f = fopen(zFile, bTextMode ? "w" : "wb");
5359    if( f==0 ){
5360      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5361    }
5362  }
5363  return f;
5364}
5365
5366#ifndef SQLITE_OMIT_TRACE
5367/*
5368** A routine for handling output from sqlite3_trace().
5369*/
5370static int sql_trace_callback(
5371  unsigned mType,         /* The trace type */
5372  void *pArg,             /* The ShellState pointer */
5373  void *pP,               /* Usually a pointer to sqlite_stmt */
5374  void *pX                /* Auxiliary output */
5375){
5376  ShellState *p = (ShellState*)pArg;
5377  sqlite3_stmt *pStmt;
5378  const char *zSql;
5379  int nSql;
5380  if( p->traceOut==0 ) return 0;
5381  if( mType==SQLITE_TRACE_CLOSE ){
5382    utf8_printf(p->traceOut, "-- closing database connection\n");
5383    return 0;
5384  }
5385  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5386    zSql = (const char*)pX;
5387  }else{
5388    pStmt = (sqlite3_stmt*)pP;
5389    switch( p->eTraceType ){
5390      case SHELL_TRACE_EXPANDED: {
5391        zSql = sqlite3_expanded_sql(pStmt);
5392        break;
5393      }
5394#ifdef SQLITE_ENABLE_NORMALIZE
5395      case SHELL_TRACE_NORMALIZED: {
5396        zSql = sqlite3_normalized_sql(pStmt);
5397        break;
5398      }
5399#endif
5400      default: {
5401        zSql = sqlite3_sql(pStmt);
5402        break;
5403      }
5404    }
5405  }
5406  if( zSql==0 ) return 0;
5407  nSql = strlen30(zSql);
5408  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5409  switch( mType ){
5410    case SQLITE_TRACE_ROW:
5411    case SQLITE_TRACE_STMT: {
5412      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5413      break;
5414    }
5415    case SQLITE_TRACE_PROFILE: {
5416      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5417      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5418      break;
5419    }
5420  }
5421  return 0;
5422}
5423#endif
5424
5425/*
5426** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5427** a useful spot to set a debugger breakpoint.
5428*/
5429static void test_breakpoint(void){
5430  static int nCall = 0;
5431  nCall++;
5432}
5433
5434/*
5435** An object used to read a CSV and other files for import.
5436*/
5437typedef struct ImportCtx ImportCtx;
5438struct ImportCtx {
5439  const char *zFile;  /* Name of the input file */
5440  FILE *in;           /* Read the CSV text from this input stream */
5441  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5442  char *z;            /* Accumulated text for a field */
5443  int n;              /* Number of bytes in z */
5444  int nAlloc;         /* Space allocated for z[] */
5445  int nLine;          /* Current line number */
5446  int nRow;           /* Number of rows imported */
5447  int nErr;           /* Number of errors encountered */
5448  int bNotFirst;      /* True if one or more bytes already read */
5449  int cTerm;          /* Character that terminated the most recent field */
5450  int cColSep;        /* The column separator character.  (Usually ",") */
5451  int cRowSep;        /* The row separator character.  (Usually "\n") */
5452};
5453
5454/* Clean up resourced used by an ImportCtx */
5455static void import_cleanup(ImportCtx *p){
5456  if( p->in!=0 && p->xCloser!=0 ){
5457    p->xCloser(p->in);
5458    p->in = 0;
5459  }
5460  sqlite3_free(p->z);
5461  p->z = 0;
5462}
5463
5464/* Append a single byte to z[] */
5465static void import_append_char(ImportCtx *p, int c){
5466  if( p->n+1>=p->nAlloc ){
5467    p->nAlloc += p->nAlloc + 100;
5468    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5469    shell_check_oom(p->z);
5470  }
5471  p->z[p->n++] = (char)c;
5472}
5473
5474/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5475** with the option of having a separator other than ",".
5476**
5477**   +  Input comes from p->in.
5478**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5479**      from sqlite3_malloc64().
5480**   +  Use p->cSep as the column separator.  The default is ",".
5481**   +  Use p->rSep as the row separator.  The default is "\n".
5482**   +  Keep track of the line number in p->nLine.
5483**   +  Store the character that terminates the field in p->cTerm.  Store
5484**      EOF on end-of-file.
5485**   +  Report syntax errors on stderr
5486*/
5487static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5488  int c;
5489  int cSep = p->cColSep;
5490  int rSep = p->cRowSep;
5491  p->n = 0;
5492  c = fgetc(p->in);
5493  if( c==EOF || seenInterrupt ){
5494    p->cTerm = EOF;
5495    return 0;
5496  }
5497  if( c=='"' ){
5498    int pc, ppc;
5499    int startLine = p->nLine;
5500    int cQuote = c;
5501    pc = ppc = 0;
5502    while( 1 ){
5503      c = fgetc(p->in);
5504      if( c==rSep ) p->nLine++;
5505      if( c==cQuote ){
5506        if( pc==cQuote ){
5507          pc = 0;
5508          continue;
5509        }
5510      }
5511      if( (c==cSep && pc==cQuote)
5512       || (c==rSep && pc==cQuote)
5513       || (c==rSep && pc=='\r' && ppc==cQuote)
5514       || (c==EOF && pc==cQuote)
5515      ){
5516        do{ p->n--; }while( p->z[p->n]!=cQuote );
5517        p->cTerm = c;
5518        break;
5519      }
5520      if( pc==cQuote && c!='\r' ){
5521        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5522                p->zFile, p->nLine, cQuote);
5523      }
5524      if( c==EOF ){
5525        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5526                p->zFile, startLine, cQuote);
5527        p->cTerm = c;
5528        break;
5529      }
5530      import_append_char(p, c);
5531      ppc = pc;
5532      pc = c;
5533    }
5534  }else{
5535    /* If this is the first field being parsed and it begins with the
5536    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5537    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5538      import_append_char(p, c);
5539      c = fgetc(p->in);
5540      if( (c&0xff)==0xbb ){
5541        import_append_char(p, c);
5542        c = fgetc(p->in);
5543        if( (c&0xff)==0xbf ){
5544          p->bNotFirst = 1;
5545          p->n = 0;
5546          return csv_read_one_field(p);
5547        }
5548      }
5549    }
5550    while( c!=EOF && c!=cSep && c!=rSep ){
5551      import_append_char(p, c);
5552      c = fgetc(p->in);
5553    }
5554    if( c==rSep ){
5555      p->nLine++;
5556      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5557    }
5558    p->cTerm = c;
5559  }
5560  if( p->z ) p->z[p->n] = 0;
5561  p->bNotFirst = 1;
5562  return p->z;
5563}
5564
5565/* Read a single field of ASCII delimited text.
5566**
5567**   +  Input comes from p->in.
5568**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5569**      from sqlite3_malloc64().
5570**   +  Use p->cSep as the column separator.  The default is "\x1F".
5571**   +  Use p->rSep as the row separator.  The default is "\x1E".
5572**   +  Keep track of the row number in p->nLine.
5573**   +  Store the character that terminates the field in p->cTerm.  Store
5574**      EOF on end-of-file.
5575**   +  Report syntax errors on stderr
5576*/
5577static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5578  int c;
5579  int cSep = p->cColSep;
5580  int rSep = p->cRowSep;
5581  p->n = 0;
5582  c = fgetc(p->in);
5583  if( c==EOF || seenInterrupt ){
5584    p->cTerm = EOF;
5585    return 0;
5586  }
5587  while( c!=EOF && c!=cSep && c!=rSep ){
5588    import_append_char(p, c);
5589    c = fgetc(p->in);
5590  }
5591  if( c==rSep ){
5592    p->nLine++;
5593  }
5594  p->cTerm = c;
5595  if( p->z ) p->z[p->n] = 0;
5596  return p->z;
5597}
5598
5599/*
5600** Try to transfer data for table zTable.  If an error is seen while
5601** moving forward, try to go backwards.  The backwards movement won't
5602** work for WITHOUT ROWID tables.
5603*/
5604static void tryToCloneData(
5605  ShellState *p,
5606  sqlite3 *newDb,
5607  const char *zTable
5608){
5609  sqlite3_stmt *pQuery = 0;
5610  sqlite3_stmt *pInsert = 0;
5611  char *zQuery = 0;
5612  char *zInsert = 0;
5613  int rc;
5614  int i, j, n;
5615  int nTable = strlen30(zTable);
5616  int k = 0;
5617  int cnt = 0;
5618  const int spinRate = 10000;
5619
5620  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5621  shell_check_oom(zQuery);
5622  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5623  if( rc ){
5624    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5625            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5626            zQuery);
5627    goto end_data_xfer;
5628  }
5629  n = sqlite3_column_count(pQuery);
5630  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5631  shell_check_oom(zInsert);
5632  sqlite3_snprintf(200+nTable,zInsert,
5633                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5634  i = strlen30(zInsert);
5635  for(j=1; j<n; j++){
5636    memcpy(zInsert+i, ",?", 2);
5637    i += 2;
5638  }
5639  memcpy(zInsert+i, ");", 3);
5640  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5641  if( rc ){
5642    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5643            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5644            zQuery);
5645    goto end_data_xfer;
5646  }
5647  for(k=0; k<2; k++){
5648    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5649      for(i=0; i<n; i++){
5650        switch( sqlite3_column_type(pQuery, i) ){
5651          case SQLITE_NULL: {
5652            sqlite3_bind_null(pInsert, i+1);
5653            break;
5654          }
5655          case SQLITE_INTEGER: {
5656            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5657            break;
5658          }
5659          case SQLITE_FLOAT: {
5660            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5661            break;
5662          }
5663          case SQLITE_TEXT: {
5664            sqlite3_bind_text(pInsert, i+1,
5665                             (const char*)sqlite3_column_text(pQuery,i),
5666                             -1, SQLITE_STATIC);
5667            break;
5668          }
5669          case SQLITE_BLOB: {
5670            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5671                                            sqlite3_column_bytes(pQuery,i),
5672                                            SQLITE_STATIC);
5673            break;
5674          }
5675        }
5676      } /* End for */
5677      rc = sqlite3_step(pInsert);
5678      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5679        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5680                        sqlite3_errmsg(newDb));
5681      }
5682      sqlite3_reset(pInsert);
5683      cnt++;
5684      if( (cnt%spinRate)==0 ){
5685        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5686        fflush(stdout);
5687      }
5688    } /* End while */
5689    if( rc==SQLITE_DONE ) break;
5690    sqlite3_finalize(pQuery);
5691    sqlite3_free(zQuery);
5692    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5693                             zTable);
5694    shell_check_oom(zQuery);
5695    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5696    if( rc ){
5697      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5698      break;
5699    }
5700  } /* End for(k=0...) */
5701
5702end_data_xfer:
5703  sqlite3_finalize(pQuery);
5704  sqlite3_finalize(pInsert);
5705  sqlite3_free(zQuery);
5706  sqlite3_free(zInsert);
5707}
5708
5709
5710/*
5711** Try to transfer all rows of the schema that match zWhere.  For
5712** each row, invoke xForEach() on the object defined by that row.
5713** If an error is encountered while moving forward through the
5714** sqlite_schema table, try again moving backwards.
5715*/
5716static void tryToCloneSchema(
5717  ShellState *p,
5718  sqlite3 *newDb,
5719  const char *zWhere,
5720  void (*xForEach)(ShellState*,sqlite3*,const char*)
5721){
5722  sqlite3_stmt *pQuery = 0;
5723  char *zQuery = 0;
5724  int rc;
5725  const unsigned char *zName;
5726  const unsigned char *zSql;
5727  char *zErrMsg = 0;
5728
5729  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5730                           " WHERE %s", zWhere);
5731  shell_check_oom(zQuery);
5732  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5733  if( rc ){
5734    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5735                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5736                    zQuery);
5737    goto end_schema_xfer;
5738  }
5739  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5740    zName = sqlite3_column_text(pQuery, 0);
5741    zSql = sqlite3_column_text(pQuery, 1);
5742    if( zName==0 || zSql==0 ) continue;
5743    printf("%s... ", zName); fflush(stdout);
5744    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5745    if( zErrMsg ){
5746      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5747      sqlite3_free(zErrMsg);
5748      zErrMsg = 0;
5749    }
5750    if( xForEach ){
5751      xForEach(p, newDb, (const char*)zName);
5752    }
5753    printf("done\n");
5754  }
5755  if( rc!=SQLITE_DONE ){
5756    sqlite3_finalize(pQuery);
5757    sqlite3_free(zQuery);
5758    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5759                             " WHERE %s ORDER BY rowid DESC", zWhere);
5760    shell_check_oom(zQuery);
5761    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5762    if( rc ){
5763      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5764                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5765                      zQuery);
5766      goto end_schema_xfer;
5767    }
5768    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5769      zName = sqlite3_column_text(pQuery, 0);
5770      zSql = sqlite3_column_text(pQuery, 1);
5771      if( zName==0 || zSql==0 ) continue;
5772      printf("%s... ", zName); fflush(stdout);
5773      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5774      if( zErrMsg ){
5775        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5776        sqlite3_free(zErrMsg);
5777        zErrMsg = 0;
5778      }
5779      if( xForEach ){
5780        xForEach(p, newDb, (const char*)zName);
5781      }
5782      printf("done\n");
5783    }
5784  }
5785end_schema_xfer:
5786  sqlite3_finalize(pQuery);
5787  sqlite3_free(zQuery);
5788}
5789
5790/*
5791** Open a new database file named "zNewDb".  Try to recover as much information
5792** as possible out of the main database (which might be corrupt) and write it
5793** into zNewDb.
5794*/
5795static void tryToClone(ShellState *p, const char *zNewDb){
5796  int rc;
5797  sqlite3 *newDb = 0;
5798  if( access(zNewDb,0)==0 ){
5799    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5800    return;
5801  }
5802  rc = sqlite3_open(zNewDb, &newDb);
5803  if( rc ){
5804    utf8_printf(stderr, "Cannot create output database: %s\n",
5805            sqlite3_errmsg(newDb));
5806  }else{
5807    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5808    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5809    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5810    tryToCloneSchema(p, newDb, "type!='table'", 0);
5811    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5812    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5813  }
5814  close_db(newDb);
5815}
5816
5817/*
5818** Change the output file back to stdout.
5819**
5820** If the p->doXdgOpen flag is set, that means the output was being
5821** redirected to a temporary file named by p->zTempFile.  In that case,
5822** launch start/open/xdg-open on that temporary file.
5823*/
5824static void output_reset(ShellState *p){
5825  if( p->outfile[0]=='|' ){
5826#ifndef SQLITE_OMIT_POPEN
5827    pclose(p->out);
5828#endif
5829  }else{
5830    output_file_close(p->out);
5831#ifndef SQLITE_NOHAVE_SYSTEM
5832    if( p->doXdgOpen ){
5833      const char *zXdgOpenCmd =
5834#if defined(_WIN32)
5835      "start";
5836#elif defined(__APPLE__)
5837      "open";
5838#else
5839      "xdg-open";
5840#endif
5841      char *zCmd;
5842      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5843      if( system(zCmd) ){
5844        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5845      }else{
5846        /* Give the start/open/xdg-open command some time to get
5847        ** going before we continue, and potential delete the
5848        ** p->zTempFile data file out from under it */
5849        sqlite3_sleep(2000);
5850      }
5851      sqlite3_free(zCmd);
5852      outputModePop(p);
5853      p->doXdgOpen = 0;
5854    }
5855#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5856  }
5857  p->outfile[0] = 0;
5858  p->out = stdout;
5859}
5860
5861/*
5862** Run an SQL command and return the single integer result.
5863*/
5864static int db_int(sqlite3 *db, const char *zSql){
5865  sqlite3_stmt *pStmt;
5866  int res = 0;
5867  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5868  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5869    res = sqlite3_column_int(pStmt,0);
5870  }
5871  sqlite3_finalize(pStmt);
5872  return res;
5873}
5874
5875#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5876/*
5877** Convert a 2-byte or 4-byte big-endian integer into a native integer
5878*/
5879static unsigned int get2byteInt(unsigned char *a){
5880  return (a[0]<<8) + a[1];
5881}
5882static unsigned int get4byteInt(unsigned char *a){
5883  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5884}
5885
5886/*
5887** Implementation of the ".dbinfo" command.
5888**
5889** Return 1 on error, 2 to exit, and 0 otherwise.
5890*/
5891static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5892  static const struct { const char *zName; int ofst; } aField[] = {
5893     { "file change counter:",  24  },
5894     { "database page count:",  28  },
5895     { "freelist page count:",  36  },
5896     { "schema cookie:",        40  },
5897     { "schema format:",        44  },
5898     { "default cache size:",   48  },
5899     { "autovacuum top root:",  52  },
5900     { "incremental vacuum:",   64  },
5901     { "text encoding:",        56  },
5902     { "user version:",         60  },
5903     { "application id:",       68  },
5904     { "software version:",     96  },
5905  };
5906  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5907     { "number of tables:",
5908       "SELECT count(*) FROM %s WHERE type='table'" },
5909     { "number of indexes:",
5910       "SELECT count(*) FROM %s WHERE type='index'" },
5911     { "number of triggers:",
5912       "SELECT count(*) FROM %s WHERE type='trigger'" },
5913     { "number of views:",
5914       "SELECT count(*) FROM %s WHERE type='view'" },
5915     { "schema size:",
5916       "SELECT total(length(sql)) FROM %s" },
5917  };
5918  int i, rc;
5919  unsigned iDataVersion;
5920  char *zSchemaTab;
5921  char *zDb = nArg>=2 ? azArg[1] : "main";
5922  sqlite3_stmt *pStmt = 0;
5923  unsigned char aHdr[100];
5924  open_db(p, 0);
5925  if( p->db==0 ) return 1;
5926  rc = sqlite3_prepare_v2(p->db,
5927             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5928             -1, &pStmt, 0);
5929  if( rc ){
5930    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5931    sqlite3_finalize(pStmt);
5932    return 1;
5933  }
5934  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5935  if( sqlite3_step(pStmt)==SQLITE_ROW
5936   && sqlite3_column_bytes(pStmt,0)>100
5937  ){
5938    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5939    sqlite3_finalize(pStmt);
5940  }else{
5941    raw_printf(stderr, "unable to read database header\n");
5942    sqlite3_finalize(pStmt);
5943    return 1;
5944  }
5945  i = get2byteInt(aHdr+16);
5946  if( i==1 ) i = 65536;
5947  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5948  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5949  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5950  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5951  for(i=0; i<ArraySize(aField); i++){
5952    int ofst = aField[i].ofst;
5953    unsigned int val = get4byteInt(aHdr + ofst);
5954    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5955    switch( ofst ){
5956      case 56: {
5957        if( val==1 ) raw_printf(p->out, " (utf8)");
5958        if( val==2 ) raw_printf(p->out, " (utf16le)");
5959        if( val==3 ) raw_printf(p->out, " (utf16be)");
5960      }
5961    }
5962    raw_printf(p->out, "\n");
5963  }
5964  if( zDb==0 ){
5965    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5966  }else if( strcmp(zDb,"temp")==0 ){
5967    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5968  }else{
5969    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5970  }
5971  for(i=0; i<ArraySize(aQuery); i++){
5972    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5973    int val = db_int(p->db, zSql);
5974    sqlite3_free(zSql);
5975    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5976  }
5977  sqlite3_free(zSchemaTab);
5978  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5979  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5980  return 0;
5981}
5982#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5983          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5984
5985/*
5986** Print the current sqlite3_errmsg() value to stderr and return 1.
5987*/
5988static int shellDatabaseError(sqlite3 *db){
5989  const char *zErr = sqlite3_errmsg(db);
5990  utf8_printf(stderr, "Error: %s\n", zErr);
5991  return 1;
5992}
5993
5994/*
5995** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5996** if they match and FALSE (0) if they do not match.
5997**
5998** Globbing rules:
5999**
6000**      '*'       Matches any sequence of zero or more characters.
6001**
6002**      '?'       Matches exactly one character.
6003**
6004**     [...]      Matches one character from the enclosed list of
6005**                characters.
6006**
6007**     [^...]     Matches one character not in the enclosed list.
6008**
6009**      '#'       Matches any sequence of one or more digits with an
6010**                optional + or - sign in front
6011**
6012**      ' '       Any span of whitespace matches any other span of
6013**                whitespace.
6014**
6015** Extra whitespace at the end of z[] is ignored.
6016*/
6017static int testcase_glob(const char *zGlob, const char *z){
6018  int c, c2;
6019  int invert;
6020  int seen;
6021
6022  while( (c = (*(zGlob++)))!=0 ){
6023    if( IsSpace(c) ){
6024      if( !IsSpace(*z) ) return 0;
6025      while( IsSpace(*zGlob) ) zGlob++;
6026      while( IsSpace(*z) ) z++;
6027    }else if( c=='*' ){
6028      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6029        if( c=='?' && (*(z++))==0 ) return 0;
6030      }
6031      if( c==0 ){
6032        return 1;
6033      }else if( c=='[' ){
6034        while( *z && testcase_glob(zGlob-1,z)==0 ){
6035          z++;
6036        }
6037        return (*z)!=0;
6038      }
6039      while( (c2 = (*(z++)))!=0 ){
6040        while( c2!=c ){
6041          c2 = *(z++);
6042          if( c2==0 ) return 0;
6043        }
6044        if( testcase_glob(zGlob,z) ) return 1;
6045      }
6046      return 0;
6047    }else if( c=='?' ){
6048      if( (*(z++))==0 ) return 0;
6049    }else if( c=='[' ){
6050      int prior_c = 0;
6051      seen = 0;
6052      invert = 0;
6053      c = *(z++);
6054      if( c==0 ) return 0;
6055      c2 = *(zGlob++);
6056      if( c2=='^' ){
6057        invert = 1;
6058        c2 = *(zGlob++);
6059      }
6060      if( c2==']' ){
6061        if( c==']' ) seen = 1;
6062        c2 = *(zGlob++);
6063      }
6064      while( c2 && c2!=']' ){
6065        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6066          c2 = *(zGlob++);
6067          if( c>=prior_c && c<=c2 ) seen = 1;
6068          prior_c = 0;
6069        }else{
6070          if( c==c2 ){
6071            seen = 1;
6072          }
6073          prior_c = c2;
6074        }
6075        c2 = *(zGlob++);
6076      }
6077      if( c2==0 || (seen ^ invert)==0 ) return 0;
6078    }else if( c=='#' ){
6079      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6080      if( !IsDigit(z[0]) ) return 0;
6081      z++;
6082      while( IsDigit(z[0]) ){ z++; }
6083    }else{
6084      if( c!=(*(z++)) ) return 0;
6085    }
6086  }
6087  while( IsSpace(*z) ){ z++; }
6088  return *z==0;
6089}
6090
6091
6092/*
6093** Compare the string as a command-line option with either one or two
6094** initial "-" characters.
6095*/
6096static int optionMatch(const char *zStr, const char *zOpt){
6097  if( zStr[0]!='-' ) return 0;
6098  zStr++;
6099  if( zStr[0]=='-' ) zStr++;
6100  return strcmp(zStr, zOpt)==0;
6101}
6102
6103/*
6104** Delete a file.
6105*/
6106int shellDeleteFile(const char *zFilename){
6107  int rc;
6108#ifdef _WIN32
6109  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6110  rc = _wunlink(z);
6111  sqlite3_free(z);
6112#else
6113  rc = unlink(zFilename);
6114#endif
6115  return rc;
6116}
6117
6118/*
6119** Try to delete the temporary file (if there is one) and free the
6120** memory used to hold the name of the temp file.
6121*/
6122static void clearTempFile(ShellState *p){
6123  if( p->zTempFile==0 ) return;
6124  if( p->doXdgOpen ) return;
6125  if( shellDeleteFile(p->zTempFile) ) return;
6126  sqlite3_free(p->zTempFile);
6127  p->zTempFile = 0;
6128}
6129
6130/*
6131** Create a new temp file name with the given suffix.
6132*/
6133static void newTempFile(ShellState *p, const char *zSuffix){
6134  clearTempFile(p);
6135  sqlite3_free(p->zTempFile);
6136  p->zTempFile = 0;
6137  if( p->db ){
6138    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6139  }
6140  if( p->zTempFile==0 ){
6141    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6142    ** will not work and we will need to fallback to guessing */
6143    char *zTemp;
6144    sqlite3_uint64 r;
6145    sqlite3_randomness(sizeof(r), &r);
6146    zTemp = getenv("TEMP");
6147    if( zTemp==0 ) zTemp = getenv("TMP");
6148    if( zTemp==0 ){
6149#ifdef _WIN32
6150      zTemp = "\\tmp";
6151#else
6152      zTemp = "/tmp";
6153#endif
6154    }
6155    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6156  }else{
6157    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6158  }
6159  shell_check_oom(p->zTempFile);
6160}
6161
6162
6163/*
6164** The implementation of SQL scalar function fkey_collate_clause(), used
6165** by the ".lint fkey-indexes" command. This scalar function is always
6166** called with four arguments - the parent table name, the parent column name,
6167** the child table name and the child column name.
6168**
6169**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6170**
6171** If either of the named tables or columns do not exist, this function
6172** returns an empty string. An empty string is also returned if both tables
6173** and columns exist but have the same default collation sequence. Or,
6174** if both exist but the default collation sequences are different, this
6175** function returns the string " COLLATE <parent-collation>", where
6176** <parent-collation> is the default collation sequence of the parent column.
6177*/
6178static void shellFkeyCollateClause(
6179  sqlite3_context *pCtx,
6180  int nVal,
6181  sqlite3_value **apVal
6182){
6183  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6184  const char *zParent;
6185  const char *zParentCol;
6186  const char *zParentSeq;
6187  const char *zChild;
6188  const char *zChildCol;
6189  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6190  int rc;
6191
6192  assert( nVal==4 );
6193  zParent = (const char*)sqlite3_value_text(apVal[0]);
6194  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6195  zChild = (const char*)sqlite3_value_text(apVal[2]);
6196  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6197
6198  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6199  rc = sqlite3_table_column_metadata(
6200      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6201  );
6202  if( rc==SQLITE_OK ){
6203    rc = sqlite3_table_column_metadata(
6204        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6205    );
6206  }
6207
6208  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6209    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6210    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6211    sqlite3_free(z);
6212  }
6213}
6214
6215
6216/*
6217** The implementation of dot-command ".lint fkey-indexes".
6218*/
6219static int lintFkeyIndexes(
6220  ShellState *pState,             /* Current shell tool state */
6221  char **azArg,                   /* Array of arguments passed to dot command */
6222  int nArg                        /* Number of entries in azArg[] */
6223){
6224  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6225  FILE *out = pState->out;        /* Stream to write non-error output to */
6226  int bVerbose = 0;               /* If -verbose is present */
6227  int bGroupByParent = 0;         /* If -groupbyparent is present */
6228  int i;                          /* To iterate through azArg[] */
6229  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6230  int rc;                         /* Return code */
6231  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6232
6233  /*
6234  ** This SELECT statement returns one row for each foreign key constraint
6235  ** in the schema of the main database. The column values are:
6236  **
6237  ** 0. The text of an SQL statement similar to:
6238  **
6239  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6240  **
6241  **    This SELECT is similar to the one that the foreign keys implementation
6242  **    needs to run internally on child tables. If there is an index that can
6243  **    be used to optimize this query, then it can also be used by the FK
6244  **    implementation to optimize DELETE or UPDATE statements on the parent
6245  **    table.
6246  **
6247  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6248  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6249  **    contains an index that can be used to optimize the query.
6250  **
6251  ** 2. Human readable text that describes the child table and columns. e.g.
6252  **
6253  **       "child_table(child_key1, child_key2)"
6254  **
6255  ** 3. Human readable text that describes the parent table and columns. e.g.
6256  **
6257  **       "parent_table(parent_key1, parent_key2)"
6258  **
6259  ** 4. A full CREATE INDEX statement for an index that could be used to
6260  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6261  **
6262  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6263  **
6264  ** 5. The name of the parent table.
6265  **
6266  ** These six values are used by the C logic below to generate the report.
6267  */
6268  const char *zSql =
6269  "SELECT "
6270    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6271    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6272    "  || fkey_collate_clause("
6273    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6274    ", "
6275    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6276    "  || group_concat('*=?', ' AND ') || ')'"
6277    ", "
6278    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6279    ", "
6280    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6281    ", "
6282    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6283    "  || ' ON ' || quote(s.name) || '('"
6284    "  || group_concat(quote(f.[from]) ||"
6285    "        fkey_collate_clause("
6286    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6287    "  || ');'"
6288    ", "
6289    "     f.[table] "
6290    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6291    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6292    "GROUP BY s.name, f.id "
6293    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6294  ;
6295  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6296
6297  for(i=2; i<nArg; i++){
6298    int n = strlen30(azArg[i]);
6299    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6300      bVerbose = 1;
6301    }
6302    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6303      bGroupByParent = 1;
6304      zIndent = "    ";
6305    }
6306    else{
6307      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6308          azArg[0], azArg[1]
6309      );
6310      return SQLITE_ERROR;
6311    }
6312  }
6313
6314  /* Register the fkey_collate_clause() SQL function */
6315  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6316      0, shellFkeyCollateClause, 0, 0
6317  );
6318
6319
6320  if( rc==SQLITE_OK ){
6321    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6322  }
6323  if( rc==SQLITE_OK ){
6324    sqlite3_bind_int(pSql, 1, bGroupByParent);
6325  }
6326
6327  if( rc==SQLITE_OK ){
6328    int rc2;
6329    char *zPrev = 0;
6330    while( SQLITE_ROW==sqlite3_step(pSql) ){
6331      int res = -1;
6332      sqlite3_stmt *pExplain = 0;
6333      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6334      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6335      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6336      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6337      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6338      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6339
6340      if( zEQP==0 ) continue;
6341      if( zGlob==0 ) continue;
6342      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6343      if( rc!=SQLITE_OK ) break;
6344      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6345        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6346        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6347                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6348      }
6349      rc = sqlite3_finalize(pExplain);
6350      if( rc!=SQLITE_OK ) break;
6351
6352      if( res<0 ){
6353        raw_printf(stderr, "Error: internal error");
6354        break;
6355      }else{
6356        if( bGroupByParent
6357        && (bVerbose || res==0)
6358        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6359        ){
6360          raw_printf(out, "-- Parent table %s\n", zParent);
6361          sqlite3_free(zPrev);
6362          zPrev = sqlite3_mprintf("%s", zParent);
6363        }
6364
6365        if( res==0 ){
6366          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6367        }else if( bVerbose ){
6368          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6369              zIndent, zFrom, zTarget
6370          );
6371        }
6372      }
6373    }
6374    sqlite3_free(zPrev);
6375
6376    if( rc!=SQLITE_OK ){
6377      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6378    }
6379
6380    rc2 = sqlite3_finalize(pSql);
6381    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6382      rc = rc2;
6383      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6384    }
6385  }else{
6386    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6387  }
6388
6389  return rc;
6390}
6391
6392/*
6393** Implementation of ".lint" dot command.
6394*/
6395static int lintDotCommand(
6396  ShellState *pState,             /* Current shell tool state */
6397  char **azArg,                   /* Array of arguments passed to dot command */
6398  int nArg                        /* Number of entries in azArg[] */
6399){
6400  int n;
6401  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6402  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6403  return lintFkeyIndexes(pState, azArg, nArg);
6404
6405 usage:
6406  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6407  raw_printf(stderr, "Where sub-commands are:\n");
6408  raw_printf(stderr, "    fkey-indexes\n");
6409  return SQLITE_ERROR;
6410}
6411
6412#if !defined SQLITE_OMIT_VIRTUALTABLE
6413static void shellPrepare(
6414  sqlite3 *db,
6415  int *pRc,
6416  const char *zSql,
6417  sqlite3_stmt **ppStmt
6418){
6419  *ppStmt = 0;
6420  if( *pRc==SQLITE_OK ){
6421    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6422    if( rc!=SQLITE_OK ){
6423      raw_printf(stderr, "sql error: %s (%d)\n",
6424          sqlite3_errmsg(db), sqlite3_errcode(db)
6425      );
6426      *pRc = rc;
6427    }
6428  }
6429}
6430
6431/*
6432** Create a prepared statement using printf-style arguments for the SQL.
6433**
6434** This routine is could be marked "static".  But it is not always used,
6435** depending on compile-time options.  By omitting the "static", we avoid
6436** nuisance compiler warnings about "defined but not used".
6437*/
6438void shellPreparePrintf(
6439  sqlite3 *db,
6440  int *pRc,
6441  sqlite3_stmt **ppStmt,
6442  const char *zFmt,
6443  ...
6444){
6445  *ppStmt = 0;
6446  if( *pRc==SQLITE_OK ){
6447    va_list ap;
6448    char *z;
6449    va_start(ap, zFmt);
6450    z = sqlite3_vmprintf(zFmt, ap);
6451    va_end(ap);
6452    if( z==0 ){
6453      *pRc = SQLITE_NOMEM;
6454    }else{
6455      shellPrepare(db, pRc, z, ppStmt);
6456      sqlite3_free(z);
6457    }
6458  }
6459}
6460
6461/* Finalize the prepared statement created using shellPreparePrintf().
6462**
6463** This routine is could be marked "static".  But it is not always used,
6464** depending on compile-time options.  By omitting the "static", we avoid
6465** nuisance compiler warnings about "defined but not used".
6466*/
6467void shellFinalize(
6468  int *pRc,
6469  sqlite3_stmt *pStmt
6470){
6471  if( pStmt ){
6472    sqlite3 *db = sqlite3_db_handle(pStmt);
6473    int rc = sqlite3_finalize(pStmt);
6474    if( *pRc==SQLITE_OK ){
6475      if( rc!=SQLITE_OK ){
6476        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6477      }
6478      *pRc = rc;
6479    }
6480  }
6481}
6482
6483/* Reset the prepared statement created using shellPreparePrintf().
6484**
6485** This routine is could be marked "static".  But it is not always used,
6486** depending on compile-time options.  By omitting the "static", we avoid
6487** nuisance compiler warnings about "defined but not used".
6488*/
6489void shellReset(
6490  int *pRc,
6491  sqlite3_stmt *pStmt
6492){
6493  int rc = sqlite3_reset(pStmt);
6494  if( *pRc==SQLITE_OK ){
6495    if( rc!=SQLITE_OK ){
6496      sqlite3 *db = sqlite3_db_handle(pStmt);
6497      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6498    }
6499    *pRc = rc;
6500  }
6501}
6502#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6503
6504#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6505/******************************************************************************
6506** The ".archive" or ".ar" command.
6507*/
6508/*
6509** Structure representing a single ".ar" command.
6510*/
6511typedef struct ArCommand ArCommand;
6512struct ArCommand {
6513  u8 eCmd;                        /* An AR_CMD_* value */
6514  u8 bVerbose;                    /* True if --verbose */
6515  u8 bZip;                        /* True if the archive is a ZIP */
6516  u8 bDryRun;                     /* True if --dry-run */
6517  u8 bAppend;                     /* True if --append */
6518  u8 bGlob;                       /* True if --glob */
6519  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6520  int nArg;                       /* Number of command arguments */
6521  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6522  const char *zFile;              /* --file argument, or NULL */
6523  const char *zDir;               /* --directory argument, or NULL */
6524  char **azArg;                   /* Array of command arguments */
6525  ShellState *p;                  /* Shell state */
6526  sqlite3 *db;                    /* Database containing the archive */
6527};
6528
6529/*
6530** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6531*/
6532static int arUsage(FILE *f){
6533  showHelp(f,"archive");
6534  return SQLITE_ERROR;
6535}
6536
6537/*
6538** Print an error message for the .ar command to stderr and return
6539** SQLITE_ERROR.
6540*/
6541static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6542  va_list ap;
6543  char *z;
6544  va_start(ap, zFmt);
6545  z = sqlite3_vmprintf(zFmt, ap);
6546  va_end(ap);
6547  utf8_printf(stderr, "Error: %s\n", z);
6548  if( pAr->fromCmdLine ){
6549    utf8_printf(stderr, "Use \"-A\" for more help\n");
6550  }else{
6551    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6552  }
6553  sqlite3_free(z);
6554  return SQLITE_ERROR;
6555}
6556
6557/*
6558** Values for ArCommand.eCmd.
6559*/
6560#define AR_CMD_CREATE       1
6561#define AR_CMD_UPDATE       2
6562#define AR_CMD_INSERT       3
6563#define AR_CMD_EXTRACT      4
6564#define AR_CMD_LIST         5
6565#define AR_CMD_HELP         6
6566#define AR_CMD_REMOVE       7
6567
6568/*
6569** Other (non-command) switches.
6570*/
6571#define AR_SWITCH_VERBOSE     8
6572#define AR_SWITCH_FILE        9
6573#define AR_SWITCH_DIRECTORY  10
6574#define AR_SWITCH_APPEND     11
6575#define AR_SWITCH_DRYRUN     12
6576#define AR_SWITCH_GLOB       13
6577
6578static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6579  switch( eSwitch ){
6580    case AR_CMD_CREATE:
6581    case AR_CMD_EXTRACT:
6582    case AR_CMD_LIST:
6583    case AR_CMD_REMOVE:
6584    case AR_CMD_UPDATE:
6585    case AR_CMD_INSERT:
6586    case AR_CMD_HELP:
6587      if( pAr->eCmd ){
6588        return arErrorMsg(pAr, "multiple command options");
6589      }
6590      pAr->eCmd = eSwitch;
6591      break;
6592
6593    case AR_SWITCH_DRYRUN:
6594      pAr->bDryRun = 1;
6595      break;
6596    case AR_SWITCH_GLOB:
6597      pAr->bGlob = 1;
6598      break;
6599    case AR_SWITCH_VERBOSE:
6600      pAr->bVerbose = 1;
6601      break;
6602    case AR_SWITCH_APPEND:
6603      pAr->bAppend = 1;
6604      /* Fall thru into --file */
6605    case AR_SWITCH_FILE:
6606      pAr->zFile = zArg;
6607      break;
6608    case AR_SWITCH_DIRECTORY:
6609      pAr->zDir = zArg;
6610      break;
6611  }
6612
6613  return SQLITE_OK;
6614}
6615
6616/*
6617** Parse the command line for an ".ar" command. The results are written into
6618** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6619** successfully, otherwise an error message is written to stderr and
6620** SQLITE_ERROR returned.
6621*/
6622static int arParseCommand(
6623  char **azArg,                   /* Array of arguments passed to dot command */
6624  int nArg,                       /* Number of entries in azArg[] */
6625  ArCommand *pAr                  /* Populate this object */
6626){
6627  struct ArSwitch {
6628    const char *zLong;
6629    char cShort;
6630    u8 eSwitch;
6631    u8 bArg;
6632  } aSwitch[] = {
6633    { "create",    'c', AR_CMD_CREATE,       0 },
6634    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6635    { "insert",    'i', AR_CMD_INSERT,       0 },
6636    { "list",      't', AR_CMD_LIST,         0 },
6637    { "remove",    'r', AR_CMD_REMOVE,       0 },
6638    { "update",    'u', AR_CMD_UPDATE,       0 },
6639    { "help",      'h', AR_CMD_HELP,         0 },
6640    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6641    { "file",      'f', AR_SWITCH_FILE,      1 },
6642    { "append",    'a', AR_SWITCH_APPEND,    1 },
6643    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6644    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6645    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6646  };
6647  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6648  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6649
6650  if( nArg<=1 ){
6651    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6652    return arUsage(stderr);
6653  }else{
6654    char *z = azArg[1];
6655    if( z[0]!='-' ){
6656      /* Traditional style [tar] invocation */
6657      int i;
6658      int iArg = 2;
6659      for(i=0; z[i]; i++){
6660        const char *zArg = 0;
6661        struct ArSwitch *pOpt;
6662        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6663          if( z[i]==pOpt->cShort ) break;
6664        }
6665        if( pOpt==pEnd ){
6666          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6667        }
6668        if( pOpt->bArg ){
6669          if( iArg>=nArg ){
6670            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6671          }
6672          zArg = azArg[iArg++];
6673        }
6674        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6675      }
6676      pAr->nArg = nArg-iArg;
6677      if( pAr->nArg>0 ){
6678        pAr->azArg = &azArg[iArg];
6679      }
6680    }else{
6681      /* Non-traditional invocation */
6682      int iArg;
6683      for(iArg=1; iArg<nArg; iArg++){
6684        int n;
6685        z = azArg[iArg];
6686        if( z[0]!='-' ){
6687          /* All remaining command line words are command arguments. */
6688          pAr->azArg = &azArg[iArg];
6689          pAr->nArg = nArg-iArg;
6690          break;
6691        }
6692        n = strlen30(z);
6693
6694        if( z[1]!='-' ){
6695          int i;
6696          /* One or more short options */
6697          for(i=1; i<n; i++){
6698            const char *zArg = 0;
6699            struct ArSwitch *pOpt;
6700            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6701              if( z[i]==pOpt->cShort ) break;
6702            }
6703            if( pOpt==pEnd ){
6704              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6705            }
6706            if( pOpt->bArg ){
6707              if( i<(n-1) ){
6708                zArg = &z[i+1];
6709                i = n;
6710              }else{
6711                if( iArg>=(nArg-1) ){
6712                  return arErrorMsg(pAr, "option requires an argument: %c",
6713                                    z[i]);
6714                }
6715                zArg = azArg[++iArg];
6716              }
6717            }
6718            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6719          }
6720        }else if( z[2]=='\0' ){
6721          /* A -- option, indicating that all remaining command line words
6722          ** are command arguments.  */
6723          pAr->azArg = &azArg[iArg+1];
6724          pAr->nArg = nArg-iArg-1;
6725          break;
6726        }else{
6727          /* A long option */
6728          const char *zArg = 0;             /* Argument for option, if any */
6729          struct ArSwitch *pMatch = 0;      /* Matching option */
6730          struct ArSwitch *pOpt;            /* Iterator */
6731          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6732            const char *zLong = pOpt->zLong;
6733            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6734              if( pMatch ){
6735                return arErrorMsg(pAr, "ambiguous option: %s",z);
6736              }else{
6737                pMatch = pOpt;
6738              }
6739            }
6740          }
6741
6742          if( pMatch==0 ){
6743            return arErrorMsg(pAr, "unrecognized option: %s", z);
6744          }
6745          if( pMatch->bArg ){
6746            if( iArg>=(nArg-1) ){
6747              return arErrorMsg(pAr, "option requires an argument: %s", z);
6748            }
6749            zArg = azArg[++iArg];
6750          }
6751          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6752        }
6753      }
6754    }
6755  }
6756
6757  return SQLITE_OK;
6758}
6759
6760/*
6761** This function assumes that all arguments within the ArCommand.azArg[]
6762** array refer to archive members, as for the --extract, --list or --remove
6763** commands. It checks that each of them are "present". If any specified
6764** file is not present in the archive, an error is printed to stderr and an
6765** error code returned. Otherwise, if all specified arguments are present
6766** in the archive, SQLITE_OK is returned. Here, "present" means either an
6767** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6768** when pAr->bGlob is true.
6769**
6770** This function strips any trailing '/' characters from each argument.
6771** This is consistent with the way the [tar] command seems to work on
6772** Linux.
6773*/
6774static int arCheckEntries(ArCommand *pAr){
6775  int rc = SQLITE_OK;
6776  if( pAr->nArg ){
6777    int i, j;
6778    sqlite3_stmt *pTest = 0;
6779    const char *zSel = (pAr->bGlob)
6780      ? "SELECT name FROM %s WHERE glob($name,name)"
6781      : "SELECT name FROM %s WHERE name=$name";
6782
6783    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6784    j = sqlite3_bind_parameter_index(pTest, "$name");
6785    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6786      char *z = pAr->azArg[i];
6787      int n = strlen30(z);
6788      int bOk = 0;
6789      while( n>0 && z[n-1]=='/' ) n--;
6790      z[n] = '\0';
6791      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6792      if( SQLITE_ROW==sqlite3_step(pTest) ){
6793        bOk = 1;
6794      }
6795      shellReset(&rc, pTest);
6796      if( rc==SQLITE_OK && bOk==0 ){
6797        utf8_printf(stderr, "not found in archive: %s\n", z);
6798        rc = SQLITE_ERROR;
6799      }
6800    }
6801    shellFinalize(&rc, pTest);
6802  }
6803  return rc;
6804}
6805
6806/*
6807** Format a WHERE clause that can be used against the "sqlar" table to
6808** identify all archive members that match the command arguments held
6809** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6810** The caller is responsible for eventually calling sqlite3_free() on
6811** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6812** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6813*/
6814static void arWhereClause(
6815  int *pRc,
6816  ArCommand *pAr,
6817  char **pzWhere                  /* OUT: New WHERE clause */
6818){
6819  char *zWhere = 0;
6820  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6821  if( *pRc==SQLITE_OK ){
6822    if( pAr->nArg==0 ){
6823      zWhere = sqlite3_mprintf("1");
6824    }else{
6825      int i;
6826      const char *zSep = "";
6827      for(i=0; i<pAr->nArg; i++){
6828        const char *z = pAr->azArg[i];
6829        zWhere = sqlite3_mprintf(
6830          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6831          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6832        );
6833        if( zWhere==0 ){
6834          *pRc = SQLITE_NOMEM;
6835          break;
6836        }
6837        zSep = " OR ";
6838      }
6839    }
6840  }
6841  *pzWhere = zWhere;
6842}
6843
6844/*
6845** Implementation of .ar "lisT" command.
6846*/
6847static int arListCommand(ArCommand *pAr){
6848  const char *zSql = "SELECT %s FROM %s WHERE %s";
6849  const char *azCols[] = {
6850    "name",
6851    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6852  };
6853
6854  char *zWhere = 0;
6855  sqlite3_stmt *pSql = 0;
6856  int rc;
6857
6858  rc = arCheckEntries(pAr);
6859  arWhereClause(&rc, pAr, &zWhere);
6860
6861  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6862                     pAr->zSrcTable, zWhere);
6863  if( pAr->bDryRun ){
6864    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6865  }else{
6866    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6867      if( pAr->bVerbose ){
6868        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6869            sqlite3_column_text(pSql, 0),
6870            sqlite3_column_int(pSql, 1),
6871            sqlite3_column_text(pSql, 2),
6872            sqlite3_column_text(pSql, 3)
6873        );
6874      }else{
6875        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6876      }
6877    }
6878  }
6879  shellFinalize(&rc, pSql);
6880  sqlite3_free(zWhere);
6881  return rc;
6882}
6883
6884
6885/*
6886** Implementation of .ar "Remove" command.
6887*/
6888static int arRemoveCommand(ArCommand *pAr){
6889  int rc = 0;
6890  char *zSql = 0;
6891  char *zWhere = 0;
6892
6893  if( pAr->nArg ){
6894    /* Verify that args actually exist within the archive before proceeding.
6895    ** And formulate a WHERE clause to match them.  */
6896    rc = arCheckEntries(pAr);
6897    arWhereClause(&rc, pAr, &zWhere);
6898  }
6899  if( rc==SQLITE_OK ){
6900    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6901                           pAr->zSrcTable, zWhere);
6902    if( pAr->bDryRun ){
6903      utf8_printf(pAr->p->out, "%s\n", zSql);
6904    }else{
6905      char *zErr = 0;
6906      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6907      if( rc==SQLITE_OK ){
6908        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6909        if( rc!=SQLITE_OK ){
6910          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6911        }else{
6912          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6913        }
6914      }
6915      if( zErr ){
6916        utf8_printf(stdout, "ERROR: %s\n", zErr);
6917        sqlite3_free(zErr);
6918      }
6919    }
6920  }
6921  sqlite3_free(zWhere);
6922  sqlite3_free(zSql);
6923  return rc;
6924}
6925
6926/*
6927** Implementation of .ar "eXtract" command.
6928*/
6929static int arExtractCommand(ArCommand *pAr){
6930  const char *zSql1 =
6931    "SELECT "
6932    " ($dir || name),"
6933    " writefile(($dir || name), %s, mode, mtime) "
6934    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6935    " AND name NOT GLOB '*..[/\\]*'";
6936
6937  const char *azExtraArg[] = {
6938    "sqlar_uncompress(data, sz)",
6939    "data"
6940  };
6941
6942  sqlite3_stmt *pSql = 0;
6943  int rc = SQLITE_OK;
6944  char *zDir = 0;
6945  char *zWhere = 0;
6946  int i, j;
6947
6948  /* If arguments are specified, check that they actually exist within
6949  ** the archive before proceeding. And formulate a WHERE clause to
6950  ** match them.  */
6951  rc = arCheckEntries(pAr);
6952  arWhereClause(&rc, pAr, &zWhere);
6953
6954  if( rc==SQLITE_OK ){
6955    if( pAr->zDir ){
6956      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6957    }else{
6958      zDir = sqlite3_mprintf("");
6959    }
6960    if( zDir==0 ) rc = SQLITE_NOMEM;
6961  }
6962
6963  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6964      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6965  );
6966
6967  if( rc==SQLITE_OK ){
6968    j = sqlite3_bind_parameter_index(pSql, "$dir");
6969    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6970
6971    /* Run the SELECT statement twice. The first time, writefile() is called
6972    ** for all archive members that should be extracted. The second time,
6973    ** only for the directories. This is because the timestamps for
6974    ** extracted directories must be reset after they are populated (as
6975    ** populating them changes the timestamp).  */
6976    for(i=0; i<2; i++){
6977      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6978      sqlite3_bind_int(pSql, j, i);
6979      if( pAr->bDryRun ){
6980        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6981      }else{
6982        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6983          if( i==0 && pAr->bVerbose ){
6984            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6985          }
6986        }
6987      }
6988      shellReset(&rc, pSql);
6989    }
6990    shellFinalize(&rc, pSql);
6991  }
6992
6993  sqlite3_free(zDir);
6994  sqlite3_free(zWhere);
6995  return rc;
6996}
6997
6998/*
6999** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
7000*/
7001static int arExecSql(ArCommand *pAr, const char *zSql){
7002  int rc;
7003  if( pAr->bDryRun ){
7004    utf8_printf(pAr->p->out, "%s\n", zSql);
7005    rc = SQLITE_OK;
7006  }else{
7007    char *zErr = 0;
7008    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7009    if( zErr ){
7010      utf8_printf(stdout, "ERROR: %s\n", zErr);
7011      sqlite3_free(zErr);
7012    }
7013  }
7014  return rc;
7015}
7016
7017
7018/*
7019** Implementation of .ar "create", "insert", and "update" commands.
7020**
7021**     create    ->     Create a new SQL archive
7022**     insert    ->     Insert or reinsert all files listed
7023**     update    ->     Insert files that have changed or that were not
7024**                      previously in the archive
7025**
7026** Create the "sqlar" table in the database if it does not already exist.
7027** Then add each file in the azFile[] array to the archive. Directories
7028** are added recursively. If argument bVerbose is non-zero, a message is
7029** printed on stdout for each file archived.
7030**
7031** The create command is the same as update, except that it drops
7032** any existing "sqlar" table before beginning.  The "insert" command
7033** always overwrites every file named on the command-line, where as
7034** "update" only overwrites if the size or mtime or mode has changed.
7035*/
7036static int arCreateOrUpdateCommand(
7037  ArCommand *pAr,                 /* Command arguments and options */
7038  int bUpdate,                    /* true for a --create. */
7039  int bOnlyIfChanged              /* Only update if file has changed */
7040){
7041  const char *zCreate =
7042      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7043      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7044      "  mode INT,               -- access permissions\n"
7045      "  mtime INT,              -- last modification time\n"
7046      "  sz INT,                 -- original file size\n"
7047      "  data BLOB               -- compressed content\n"
7048      ")";
7049  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7050  const char *zInsertFmt[2] = {
7051     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7052     "  SELECT\n"
7053     "    %s,\n"
7054     "    mode,\n"
7055     "    mtime,\n"
7056     "    CASE substr(lsmode(mode),1,1)\n"
7057     "      WHEN '-' THEN length(data)\n"
7058     "      WHEN 'd' THEN 0\n"
7059     "      ELSE -1 END,\n"
7060     "    sqlar_compress(data)\n"
7061     "  FROM fsdir(%Q,%Q) AS disk\n"
7062     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7063     ,
7064     "REPLACE INTO %s(name,mode,mtime,data)\n"
7065     "  SELECT\n"
7066     "    %s,\n"
7067     "    mode,\n"
7068     "    mtime,\n"
7069     "    data\n"
7070     "  FROM fsdir(%Q,%Q) AS disk\n"
7071     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7072  };
7073  int i;                          /* For iterating through azFile[] */
7074  int rc;                         /* Return code */
7075  const char *zTab = 0;           /* SQL table into which to insert */
7076  char *zSql;
7077  char zTemp[50];
7078  char *zExists = 0;
7079
7080  arExecSql(pAr, "PRAGMA page_size=512");
7081  rc = arExecSql(pAr, "SAVEPOINT ar;");
7082  if( rc!=SQLITE_OK ) return rc;
7083  zTemp[0] = 0;
7084  if( pAr->bZip ){
7085    /* Initialize the zipfile virtual table, if necessary */
7086    if( pAr->zFile ){
7087      sqlite3_uint64 r;
7088      sqlite3_randomness(sizeof(r),&r);
7089      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7090      zTab = zTemp;
7091      zSql = sqlite3_mprintf(
7092         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7093         zTab, pAr->zFile
7094      );
7095      rc = arExecSql(pAr, zSql);
7096      sqlite3_free(zSql);
7097    }else{
7098      zTab = "zip";
7099    }
7100  }else{
7101    /* Initialize the table for an SQLAR */
7102    zTab = "sqlar";
7103    if( bUpdate==0 ){
7104      rc = arExecSql(pAr, zDrop);
7105      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7106    }
7107    rc = arExecSql(pAr, zCreate);
7108  }
7109  if( bOnlyIfChanged ){
7110    zExists = sqlite3_mprintf(
7111      " AND NOT EXISTS("
7112          "SELECT 1 FROM %s AS mem"
7113          " WHERE mem.name=disk.name"
7114          " AND mem.mtime=disk.mtime"
7115          " AND mem.mode=disk.mode)", zTab);
7116  }else{
7117    zExists = sqlite3_mprintf("");
7118  }
7119  if( zExists==0 ) rc = SQLITE_NOMEM;
7120  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7121    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7122        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7123        pAr->azArg[i], pAr->zDir, zExists);
7124    rc = arExecSql(pAr, zSql2);
7125    sqlite3_free(zSql2);
7126  }
7127end_ar_transaction:
7128  if( rc!=SQLITE_OK ){
7129    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7130  }else{
7131    rc = arExecSql(pAr, "RELEASE ar;");
7132    if( pAr->bZip && pAr->zFile ){
7133      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7134      arExecSql(pAr, zSql);
7135      sqlite3_free(zSql);
7136    }
7137  }
7138  sqlite3_free(zExists);
7139  return rc;
7140}
7141
7142/*
7143** Implementation of ".ar" dot command.
7144*/
7145static int arDotCommand(
7146  ShellState *pState,          /* Current shell tool state */
7147  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7148  char **azArg,                /* Array of arguments passed to dot command */
7149  int nArg                     /* Number of entries in azArg[] */
7150){
7151  ArCommand cmd;
7152  int rc;
7153  memset(&cmd, 0, sizeof(cmd));
7154  cmd.fromCmdLine = fromCmdLine;
7155  rc = arParseCommand(azArg, nArg, &cmd);
7156  if( rc==SQLITE_OK ){
7157    int eDbType = SHELL_OPEN_UNSPEC;
7158    cmd.p = pState;
7159    cmd.db = pState->db;
7160    if( cmd.zFile ){
7161      eDbType = deduceDatabaseType(cmd.zFile, 1);
7162    }else{
7163      eDbType = pState->openMode;
7164    }
7165    if( eDbType==SHELL_OPEN_ZIPFILE ){
7166      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7167        if( cmd.zFile==0 ){
7168          cmd.zSrcTable = sqlite3_mprintf("zip");
7169        }else{
7170          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7171        }
7172      }
7173      cmd.bZip = 1;
7174    }else if( cmd.zFile ){
7175      int flags;
7176      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7177      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7178           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7179        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7180      }else{
7181        flags = SQLITE_OPEN_READONLY;
7182      }
7183      cmd.db = 0;
7184      if( cmd.bDryRun ){
7185        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7186             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7187      }
7188      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7189             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7190      if( rc!=SQLITE_OK ){
7191        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7192            cmd.zFile, sqlite3_errmsg(cmd.db)
7193        );
7194        goto end_ar_command;
7195      }
7196      sqlite3_fileio_init(cmd.db, 0, 0);
7197      sqlite3_sqlar_init(cmd.db, 0, 0);
7198      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7199                              shellPutsFunc, 0, 0);
7200
7201    }
7202    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7203      if( cmd.eCmd!=AR_CMD_CREATE
7204       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7205      ){
7206        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7207        rc = SQLITE_ERROR;
7208        goto end_ar_command;
7209      }
7210      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7211    }
7212
7213    switch( cmd.eCmd ){
7214      case AR_CMD_CREATE:
7215        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7216        break;
7217
7218      case AR_CMD_EXTRACT:
7219        rc = arExtractCommand(&cmd);
7220        break;
7221
7222      case AR_CMD_LIST:
7223        rc = arListCommand(&cmd);
7224        break;
7225
7226      case AR_CMD_HELP:
7227        arUsage(pState->out);
7228        break;
7229
7230      case AR_CMD_INSERT:
7231        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7232        break;
7233
7234      case AR_CMD_REMOVE:
7235        rc = arRemoveCommand(&cmd);
7236        break;
7237
7238      default:
7239        assert( cmd.eCmd==AR_CMD_UPDATE );
7240        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7241        break;
7242    }
7243  }
7244end_ar_command:
7245  if( cmd.db!=pState->db ){
7246    close_db(cmd.db);
7247  }
7248  sqlite3_free(cmd.zSrcTable);
7249
7250  return rc;
7251}
7252/* End of the ".archive" or ".ar" command logic
7253*******************************************************************************/
7254#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7255
7256#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7257
7258/*
7259** This function is used as a callback by the recover extension. Simply
7260** print the supplied SQL statement to stdout.
7261*/
7262static int recoverSqlCb(void *pCtx, const char *zSql){
7263  ShellState *pState = (ShellState*)pCtx;
7264  raw_printf(stdout, "%s;\n", zSql);
7265  return SQLITE_OK;
7266}
7267
7268/*
7269** This function is called to recover data from the database. A script
7270** to construct a new database containing all recovered data is output
7271** on stream pState->out.
7272*/
7273static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7274  int rc = SQLITE_OK;
7275  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7276  const char *zLAF = "lost_and_found";
7277  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7278  int bRowids = 1;                /* 0 if --no-rowids */
7279  sqlite3_recover *p = 0;
7280  int i = 0;
7281
7282  for(i=1; i<nArg; i++){
7283    char *z = azArg[i];
7284    int n;
7285    if( z[0]=='-' && z[1]=='-' ) z++;
7286    n = strlen30(z);
7287    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7288      bFreelist = 0;
7289    }else
7290    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7291      i++;
7292      zRecoveryDb = azArg[i];
7293    }else
7294    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7295      i++;
7296      zLAF = azArg[i];
7297    }else
7298    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7299      bRowids = 0;
7300    }
7301    else{
7302      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7303      showHelp(pState->out, azArg[0]);
7304      return 1;
7305    }
7306  }
7307
7308  p = sqlite3_recover_init_sql(
7309      pState->db, "main", recoverSqlCb, (void*)pState
7310  );
7311
7312  sqlite3_recover_config(p, SQLITE_RECOVER_TESTDB, (void*)zRecoveryDb);
7313  sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7314  sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7315  sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7316
7317  sqlite3_recover_run(p);
7318  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7319    const char *zErr = sqlite3_recover_errmsg(p);
7320    int errCode = sqlite3_recover_errcode(p);
7321    raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
7322  }
7323  rc = sqlite3_recover_finish(p);
7324  return rc;
7325}
7326#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7327
7328
7329/*
7330 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7331 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7332 *   close db and set it to 0, and return the columns spec, to later
7333 *   be sqlite3_free()'ed by the caller.
7334 * The return is 0 when either:
7335 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7336 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7337 * The 3rd argument, pRenamed, references an out parameter. If the
7338 * pointer is non-zero, its referent will be set to a summary of renames
7339 * done if renaming was necessary, or set to 0 if none was done. The out
7340 * string (if any) must be sqlite3_free()'ed by the caller.
7341 */
7342#ifdef SHELL_DEBUG
7343#define rc_err_oom_die(rc) \
7344  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7345  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7346    fprintf(stderr,"E:%d\n",rc), assert(0)
7347#else
7348static void rc_err_oom_die(int rc){
7349  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7350  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7351}
7352#endif
7353
7354#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7355static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7356#else  /* Otherwise, memory is faster/better for the transient DB. */
7357static const char *zCOL_DB = ":memory:";
7358#endif
7359
7360/* Define character (as C string) to separate generated column ordinal
7361 * from protected part of incoming column names. This defaults to "_"
7362 * so that incoming column identifiers that did not need not be quoted
7363 * remain usable without being quoted. It must be one character.
7364 */
7365#ifndef SHELL_AUTOCOLUMN_SEP
7366# define AUTOCOLUMN_SEP "_"
7367#else
7368# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7369#endif
7370
7371static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7372  /* Queries and D{D,M}L used here */
7373  static const char * const zTabMake = "\
7374CREATE TABLE ColNames(\
7375 cpos INTEGER PRIMARY KEY,\
7376 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7377CREATE VIEW RepeatedNames AS \
7378SELECT DISTINCT t.name FROM ColNames t \
7379WHERE t.name COLLATE NOCASE IN (\
7380 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7381);\
7382";
7383  static const char * const zTabFill = "\
7384INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7385 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7386";
7387  static const char * const zHasDupes = "\
7388SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7389 <count(name) FROM ColNames\
7390";
7391#ifdef SHELL_COLUMN_RENAME_CLEAN
7392  static const char * const zDedoctor = "\
7393UPDATE ColNames SET chop=iif(\
7394  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7395  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7396 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7397 0\
7398)\
7399";
7400#endif
7401  static const char * const zSetReps = "\
7402UPDATE ColNames AS t SET reps=\
7403(SELECT count(*) FROM ColNames d \
7404 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7405 COLLATE NOCASE\
7406)\
7407";
7408#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7409  static const char * const zColDigits = "\
7410SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7411";
7412#else
7413  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7414  static const char * const zColDigits = "\
7415SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7416 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7417 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7418";
7419#endif
7420  static const char * const zRenameRank =
7421#ifdef SHELL_COLUMN_RENAME_CLEAN
7422    "UPDATE ColNames AS t SET suff="
7423    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7424#else /* ...RENAME_MINIMAL_ONE_PASS */
7425"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7426"  SELECT 0 AS nlz"
7427"  UNION"
7428"  SELECT nlz+1 AS nlz FROM Lzn"
7429"  WHERE EXISTS("
7430"   SELECT 1"
7431"   FROM ColNames t, ColNames o"
7432"   WHERE"
7433"    iif(t.name IN (SELECT * FROM RepeatedNames),"
7434"     printf('%s"AUTOCOLUMN_SEP"%s',"
7435"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7436"     t.name"
7437"    )"
7438"    ="
7439"    iif(o.name IN (SELECT * FROM RepeatedNames),"
7440"     printf('%s"AUTOCOLUMN_SEP"%s',"
7441"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7442"     o.name"
7443"    )"
7444"    COLLATE NOCASE"
7445"    AND o.cpos<>t.cpos"
7446"   GROUP BY t.cpos"
7447"  )"
7448") UPDATE Colnames AS t SET"
7449" chop = 0," /* No chopping, never touch incoming names. */
7450" suff = iif(name IN (SELECT * FROM RepeatedNames),"
7451"  printf('"AUTOCOLUMN_SEP"%s', substring("
7452"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7453"  ''"
7454" )"
7455#endif
7456    ;
7457  static const char * const zCollectVar = "\
7458SELECT\
7459 '('||x'0a'\
7460 || group_concat(\
7461  cname||' TEXT',\
7462  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7463 ||')' AS ColsSpec \
7464FROM (\
7465 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7466 FROM ColNames ORDER BY cpos\
7467)";
7468  static const char * const zRenamesDone =
7469    "SELECT group_concat("
7470    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7471    " ','||x'0a')"
7472    "FROM ColNames WHERE suff<>'' OR chop!=0"
7473    ;
7474  int rc;
7475  sqlite3_stmt *pStmt = 0;
7476  assert(pDb!=0);
7477  if( zColNew ){
7478    /* Add initial or additional column. Init db if necessary. */
7479    if( *pDb==0 ){
7480      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7481#ifdef SHELL_COLFIX_DB
7482      if(*zCOL_DB!=':')
7483        sqlite3_exec(*pDb,"drop table if exists ColNames;"
7484                     "drop view if exists RepeatedNames;",0,0,0);
7485#endif
7486      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7487      rc_err_oom_die(rc);
7488    }
7489    assert(*pDb!=0);
7490    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7491    rc_err_oom_die(rc);
7492    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7493    rc_err_oom_die(rc);
7494    rc = sqlite3_step(pStmt);
7495    rc_err_oom_die(rc);
7496    sqlite3_finalize(pStmt);
7497    return 0;
7498  }else if( *pDb==0 ){
7499    return 0;
7500  }else{
7501    /* Formulate the columns spec, close the DB, zero *pDb. */
7502    char *zColsSpec = 0;
7503    int hasDupes = db_int(*pDb, zHasDupes);
7504    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7505    if( hasDupes ){
7506#ifdef SHELL_COLUMN_RENAME_CLEAN
7507      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7508      rc_err_oom_die(rc);
7509#endif
7510      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7511      rc_err_oom_die(rc);
7512      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7513      rc_err_oom_die(rc);
7514      sqlite3_bind_int(pStmt, 1, nDigits);
7515      rc = sqlite3_step(pStmt);
7516      sqlite3_finalize(pStmt);
7517      assert(rc==SQLITE_DONE);
7518    }
7519    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7520    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7521    rc_err_oom_die(rc);
7522    rc = sqlite3_step(pStmt);
7523    if( rc==SQLITE_ROW ){
7524      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7525    }else{
7526      zColsSpec = 0;
7527    }
7528    if( pzRenamed!=0 ){
7529      if( !hasDupes ) *pzRenamed = 0;
7530      else{
7531        sqlite3_finalize(pStmt);
7532        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7533            && SQLITE_ROW==sqlite3_step(pStmt) ){
7534          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7535        }else
7536          *pzRenamed = 0;
7537      }
7538    }
7539    sqlite3_finalize(pStmt);
7540    sqlite3_close(*pDb);
7541    *pDb = 0;
7542    return zColsSpec;
7543  }
7544}
7545
7546/*
7547** If an input line begins with "." then invoke this routine to
7548** process that line.
7549**
7550** Return 1 on error, 2 to exit, and 0 otherwise.
7551*/
7552static int do_meta_command(char *zLine, ShellState *p){
7553  int h = 1;
7554  int nArg = 0;
7555  int n, c;
7556  int rc = 0;
7557  char *azArg[52];
7558
7559#ifndef SQLITE_OMIT_VIRTUALTABLE
7560  if( p->expert.pExpert ){
7561    expertFinish(p, 1, 0);
7562  }
7563#endif
7564
7565  /* Parse the input line into tokens.
7566  */
7567  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7568    while( IsSpace(zLine[h]) ){ h++; }
7569    if( zLine[h]==0 ) break;
7570    if( zLine[h]=='\'' || zLine[h]=='"' ){
7571      int delim = zLine[h++];
7572      azArg[nArg++] = &zLine[h];
7573      while( zLine[h] && zLine[h]!=delim ){
7574        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7575        h++;
7576      }
7577      if( zLine[h]==delim ){
7578        zLine[h++] = 0;
7579      }
7580      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7581    }else{
7582      azArg[nArg++] = &zLine[h];
7583      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7584      if( zLine[h] ) zLine[h++] = 0;
7585      resolve_backslashes(azArg[nArg-1]);
7586    }
7587  }
7588  azArg[nArg] = 0;
7589
7590  /* Process the input line.
7591  */
7592  if( nArg==0 ) return 0; /* no tokens, no error */
7593  n = strlen30(azArg[0]);
7594  c = azArg[0][0];
7595  clearTempFile(p);
7596
7597#ifndef SQLITE_OMIT_AUTHORIZATION
7598  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7599    if( nArg!=2 ){
7600      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7601      rc = 1;
7602      goto meta_command_exit;
7603    }
7604    open_db(p, 0);
7605    if( booleanValue(azArg[1]) ){
7606      sqlite3_set_authorizer(p->db, shellAuth, p);
7607    }else if( p->bSafeModePersist ){
7608      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7609    }else{
7610      sqlite3_set_authorizer(p->db, 0, 0);
7611    }
7612  }else
7613#endif
7614
7615#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7616  && !defined(SQLITE_SHELL_FIDDLE)
7617  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7618    open_db(p, 0);
7619    failIfSafeMode(p, "cannot run .archive in safe mode");
7620    rc = arDotCommand(p, 0, azArg, nArg);
7621  }else
7622#endif
7623
7624#ifndef SQLITE_SHELL_FIDDLE
7625  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7626   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7627  ){
7628    const char *zDestFile = 0;
7629    const char *zDb = 0;
7630    sqlite3 *pDest;
7631    sqlite3_backup *pBackup;
7632    int j;
7633    int bAsync = 0;
7634    const char *zVfs = 0;
7635    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7636    for(j=1; j<nArg; j++){
7637      const char *z = azArg[j];
7638      if( z[0]=='-' ){
7639        if( z[1]=='-' ) z++;
7640        if( strcmp(z, "-append")==0 ){
7641          zVfs = "apndvfs";
7642        }else
7643        if( strcmp(z, "-async")==0 ){
7644          bAsync = 1;
7645        }else
7646        {
7647          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7648          return 1;
7649        }
7650      }else if( zDestFile==0 ){
7651        zDestFile = azArg[j];
7652      }else if( zDb==0 ){
7653        zDb = zDestFile;
7654        zDestFile = azArg[j];
7655      }else{
7656        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7657        return 1;
7658      }
7659    }
7660    if( zDestFile==0 ){
7661      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7662      return 1;
7663    }
7664    if( zDb==0 ) zDb = "main";
7665    rc = sqlite3_open_v2(zDestFile, &pDest,
7666                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7667    if( rc!=SQLITE_OK ){
7668      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7669      close_db(pDest);
7670      return 1;
7671    }
7672    if( bAsync ){
7673      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7674                   0, 0, 0);
7675    }
7676    open_db(p, 0);
7677    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7678    if( pBackup==0 ){
7679      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7680      close_db(pDest);
7681      return 1;
7682    }
7683    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7684    sqlite3_backup_finish(pBackup);
7685    if( rc==SQLITE_DONE ){
7686      rc = 0;
7687    }else{
7688      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7689      rc = 1;
7690    }
7691    close_db(pDest);
7692  }else
7693#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7694
7695  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7696    if( nArg==2 ){
7697      bail_on_error = booleanValue(azArg[1]);
7698    }else{
7699      raw_printf(stderr, "Usage: .bail on|off\n");
7700      rc = 1;
7701    }
7702  }else
7703
7704  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7705    if( nArg==2 ){
7706      if( booleanValue(azArg[1]) ){
7707        setBinaryMode(p->out, 1);
7708      }else{
7709        setTextMode(p->out, 1);
7710      }
7711    }else{
7712      raw_printf(stderr, "Usage: .binary on|off\n");
7713      rc = 1;
7714    }
7715  }else
7716
7717  /* The undocumented ".breakpoint" command causes a call to the no-op
7718  ** routine named test_breakpoint().
7719  */
7720  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7721    test_breakpoint();
7722  }else
7723
7724#ifndef SQLITE_SHELL_FIDDLE
7725  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7726    failIfSafeMode(p, "cannot run .cd in safe mode");
7727    if( nArg==2 ){
7728#if defined(_WIN32) || defined(WIN32)
7729      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7730      rc = !SetCurrentDirectoryW(z);
7731      sqlite3_free(z);
7732#else
7733      rc = chdir(azArg[1]);
7734#endif
7735      if( rc ){
7736        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7737        rc = 1;
7738      }
7739    }else{
7740      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7741      rc = 1;
7742    }
7743  }else
7744#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7745
7746  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7747    if( nArg==2 ){
7748      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7749    }else{
7750      raw_printf(stderr, "Usage: .changes on|off\n");
7751      rc = 1;
7752    }
7753  }else
7754
7755#ifndef SQLITE_SHELL_FIDDLE
7756  /* Cancel output redirection, if it is currently set (by .testcase)
7757  ** Then read the content of the testcase-out.txt file and compare against
7758  ** azArg[1].  If there are differences, report an error and exit.
7759  */
7760  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7761    char *zRes = 0;
7762    output_reset(p);
7763    if( nArg!=2 ){
7764      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7765      rc = 2;
7766    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7767      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7768      rc = 2;
7769    }else if( testcase_glob(azArg[1],zRes)==0 ){
7770      utf8_printf(stderr,
7771                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7772                 p->zTestcase, azArg[1], zRes);
7773      rc = 1;
7774    }else{
7775      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7776      p->nCheck++;
7777    }
7778    sqlite3_free(zRes);
7779  }else
7780#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7781
7782#ifndef SQLITE_SHELL_FIDDLE
7783  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7784    failIfSafeMode(p, "cannot run .clone in safe mode");
7785    if( nArg==2 ){
7786      tryToClone(p, azArg[1]);
7787    }else{
7788      raw_printf(stderr, "Usage: .clone FILENAME\n");
7789      rc = 1;
7790    }
7791  }else
7792#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7793
7794  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
7795    if( nArg==1 ){
7796      /* List available connections */
7797      int i;
7798      for(i=0; i<ArraySize(p->aAuxDb); i++){
7799        const char *zFile = p->aAuxDb[i].zDbFilename;
7800        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7801          zFile = "(not open)";
7802        }else if( zFile==0 ){
7803          zFile = "(memory)";
7804        }else if( zFile[0]==0 ){
7805          zFile = "(temporary-file)";
7806        }
7807        if( p->pAuxDb == &p->aAuxDb[i] ){
7808          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7809        }else if( p->aAuxDb[i].db!=0 ){
7810          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7811        }
7812      }
7813    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7814      int i = azArg[1][0] - '0';
7815      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7816        p->pAuxDb->db = p->db;
7817        p->pAuxDb = &p->aAuxDb[i];
7818        globalDb = p->db = p->pAuxDb->db;
7819        p->pAuxDb->db = 0;
7820      }
7821    }else if( nArg==3 && strcmp(azArg[1], "close")==0
7822           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7823      int i = azArg[2][0] - '0';
7824      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7825        /* No-op */
7826      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7827        raw_printf(stderr, "cannot close the active database connection\n");
7828        rc = 1;
7829      }else if( p->aAuxDb[i].db ){
7830        session_close_all(p, i);
7831        close_db(p->aAuxDb[i].db);
7832        p->aAuxDb[i].db = 0;
7833      }
7834    }else{
7835      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7836      rc = 1;
7837    }
7838  }else
7839
7840  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7841    char **azName = 0;
7842    int nName = 0;
7843    sqlite3_stmt *pStmt;
7844    int i;
7845    open_db(p, 0);
7846    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7847    if( rc ){
7848      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7849      rc = 1;
7850    }else{
7851      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7852        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7853        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7854        if( zSchema==0 || zFile==0 ) continue;
7855        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7856        shell_check_oom(azName);
7857        azName[nName*2] = strdup(zSchema);
7858        azName[nName*2+1] = strdup(zFile);
7859        nName++;
7860      }
7861    }
7862    sqlite3_finalize(pStmt);
7863    for(i=0; i<nName; i++){
7864      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7865      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7866      const char *z = azName[i*2+1];
7867      utf8_printf(p->out, "%s: %s %s%s\n",
7868         azName[i*2],
7869         z && z[0] ? z : "\"\"",
7870         bRdonly ? "r/o" : "r/w",
7871         eTxn==SQLITE_TXN_NONE ? "" :
7872            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7873      free(azName[i*2]);
7874      free(azName[i*2+1]);
7875    }
7876    sqlite3_free(azName);
7877  }else
7878
7879  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7880    static const struct DbConfigChoices {
7881      const char *zName;
7882      int op;
7883    } aDbConfig[] = {
7884        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7885        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7886        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7887        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7888        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7889        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7890        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7891        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7892        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7893        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7894        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7895        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7896        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7897        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7898        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7899        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7900    };
7901    int ii, v;
7902    open_db(p, 0);
7903    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7904      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7905      if( nArg>=3 ){
7906        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7907      }
7908      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7909      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7910      if( nArg>1 ) break;
7911    }
7912    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7913      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7914      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7915    }
7916  }else
7917
7918#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7919  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7920    rc = shell_dbinfo_command(p, nArg, azArg);
7921  }else
7922
7923  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7924    open_db(p, 0);
7925    rc = recoverDatabaseCmd(p, nArg, azArg);
7926  }else
7927#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7928
7929  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7930    char *zLike = 0;
7931    char *zSql;
7932    int i;
7933    int savedShowHeader = p->showHeader;
7934    int savedShellFlags = p->shellFlgs;
7935    ShellClearFlag(p,
7936       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7937       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7938    for(i=1; i<nArg; i++){
7939      if( azArg[i][0]=='-' ){
7940        const char *z = azArg[i]+1;
7941        if( z[0]=='-' ) z++;
7942        if( strcmp(z,"preserve-rowids")==0 ){
7943#ifdef SQLITE_OMIT_VIRTUALTABLE
7944          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7945                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7946          rc = 1;
7947          sqlite3_free(zLike);
7948          goto meta_command_exit;
7949#else
7950          ShellSetFlag(p, SHFLG_PreserveRowid);
7951#endif
7952        }else
7953        if( strcmp(z,"newlines")==0 ){
7954          ShellSetFlag(p, SHFLG_Newlines);
7955        }else
7956        if( strcmp(z,"data-only")==0 ){
7957          ShellSetFlag(p, SHFLG_DumpDataOnly);
7958        }else
7959        if( strcmp(z,"nosys")==0 ){
7960          ShellSetFlag(p, SHFLG_DumpNoSys);
7961        }else
7962        {
7963          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7964          rc = 1;
7965          sqlite3_free(zLike);
7966          goto meta_command_exit;
7967        }
7968      }else{
7969        /* azArg[i] contains a LIKE pattern. This ".dump" request should
7970        ** only dump data for tables for which either the table name matches
7971        ** the LIKE pattern, or the table appears to be a shadow table of
7972        ** a virtual table for which the name matches the LIKE pattern.
7973        */
7974        char *zExpr = sqlite3_mprintf(
7975            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
7976            "  SELECT 1 FROM sqlite_schema WHERE "
7977            "    name LIKE %Q ESCAPE '\\' AND"
7978            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
7979            "    substr(o.name, 1, length(name)+1) == (name||'_')"
7980            ")", azArg[i], azArg[i]
7981        );
7982
7983        if( zLike ){
7984          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
7985        }else{
7986          zLike = zExpr;
7987        }
7988      }
7989    }
7990
7991    open_db(p, 0);
7992
7993    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7994      /* When playing back a "dump", the content might appear in an order
7995      ** which causes immediate foreign key constraints to be violated.
7996      ** So disable foreign-key constraint enforcement to prevent problems. */
7997      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7998      raw_printf(p->out, "BEGIN TRANSACTION;\n");
7999    }
8000    p->writableSchema = 0;
8001    p->showHeader = 0;
8002    /* Set writable_schema=ON since doing so forces SQLite to initialize
8003    ** as much of the schema as it can even if the sqlite_schema table is
8004    ** corrupt. */
8005    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8006    p->nErr = 0;
8007    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8008    zSql = sqlite3_mprintf(
8009      "SELECT name, type, sql FROM sqlite_schema AS o "
8010      "WHERE (%s) AND type=='table'"
8011      "  AND sql NOT NULL"
8012      " ORDER BY tbl_name='sqlite_sequence', rowid",
8013      zLike
8014    );
8015    run_schema_dump_query(p,zSql);
8016    sqlite3_free(zSql);
8017    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8018      zSql = sqlite3_mprintf(
8019        "SELECT sql FROM sqlite_schema AS o "
8020        "WHERE (%s) AND sql NOT NULL"
8021        "  AND type IN ('index','trigger','view')",
8022        zLike
8023      );
8024      run_table_dump_query(p, zSql);
8025      sqlite3_free(zSql);
8026    }
8027    sqlite3_free(zLike);
8028    if( p->writableSchema ){
8029      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8030      p->writableSchema = 0;
8031    }
8032    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8033    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8034    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8035      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8036    }
8037    p->showHeader = savedShowHeader;
8038    p->shellFlgs = savedShellFlags;
8039  }else
8040
8041  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8042    if( nArg==2 ){
8043      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8044    }else{
8045      raw_printf(stderr, "Usage: .echo on|off\n");
8046      rc = 1;
8047    }
8048  }else
8049
8050  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8051    if( nArg==2 ){
8052      p->autoEQPtest = 0;
8053      if( p->autoEQPtrace ){
8054        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8055        p->autoEQPtrace = 0;
8056      }
8057      if( strcmp(azArg[1],"full")==0 ){
8058        p->autoEQP = AUTOEQP_full;
8059      }else if( strcmp(azArg[1],"trigger")==0 ){
8060        p->autoEQP = AUTOEQP_trigger;
8061#ifdef SQLITE_DEBUG
8062      }else if( strcmp(azArg[1],"test")==0 ){
8063        p->autoEQP = AUTOEQP_on;
8064        p->autoEQPtest = 1;
8065      }else if( strcmp(azArg[1],"trace")==0 ){
8066        p->autoEQP = AUTOEQP_full;
8067        p->autoEQPtrace = 1;
8068        open_db(p, 0);
8069        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8070        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8071#endif
8072      }else{
8073        p->autoEQP = (u8)booleanValue(azArg[1]);
8074      }
8075    }else{
8076      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8077      rc = 1;
8078    }
8079  }else
8080
8081#ifndef SQLITE_SHELL_FIDDLE
8082  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8083    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8084    rc = 2;
8085  }else
8086#endif
8087
8088  /* The ".explain" command is automatic now.  It is largely pointless.  It
8089  ** retained purely for backwards compatibility */
8090  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8091    int val = 1;
8092    if( nArg>=2 ){
8093      if( strcmp(azArg[1],"auto")==0 ){
8094        val = 99;
8095      }else{
8096        val =  booleanValue(azArg[1]);
8097      }
8098    }
8099    if( val==1 && p->mode!=MODE_Explain ){
8100      p->normalMode = p->mode;
8101      p->mode = MODE_Explain;
8102      p->autoExplain = 0;
8103    }else if( val==0 ){
8104      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8105      p->autoExplain = 0;
8106    }else if( val==99 ){
8107      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8108      p->autoExplain = 1;
8109    }
8110  }else
8111
8112#ifndef SQLITE_OMIT_VIRTUALTABLE
8113  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8114    if( p->bSafeMode ){
8115      raw_printf(stderr,
8116        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8117        azArg[0]);
8118      rc = 1;
8119    }else{
8120      open_db(p, 0);
8121      expertDotCommand(p, azArg, nArg);
8122    }
8123  }else
8124#endif
8125
8126  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8127    static const struct {
8128       const char *zCtrlName;   /* Name of a test-control option */
8129       int ctrlCode;            /* Integer code for that option */
8130       const char *zUsage;      /* Usage notes */
8131    } aCtrl[] = {
8132      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8133      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8134      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8135      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8136      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8137   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8138      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8139      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8140      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8141      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8142   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8143    };
8144    int filectrl = -1;
8145    int iCtrl = -1;
8146    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8147    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8148    int n2, i;
8149    const char *zCmd = 0;
8150    const char *zSchema = 0;
8151
8152    open_db(p, 0);
8153    zCmd = nArg>=2 ? azArg[1] : "help";
8154
8155    if( zCmd[0]=='-'
8156     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8157     && nArg>=4
8158    ){
8159      zSchema = azArg[2];
8160      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8161      nArg -= 2;
8162      zCmd = azArg[1];
8163    }
8164
8165    /* The argument can optionally begin with "-" or "--" */
8166    if( zCmd[0]=='-' && zCmd[1] ){
8167      zCmd++;
8168      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8169    }
8170
8171    /* --help lists all file-controls */
8172    if( strcmp(zCmd,"help")==0 ){
8173      utf8_printf(p->out, "Available file-controls:\n");
8174      for(i=0; i<ArraySize(aCtrl); i++){
8175        utf8_printf(p->out, "  .filectrl %s %s\n",
8176                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8177      }
8178      rc = 1;
8179      goto meta_command_exit;
8180    }
8181
8182    /* convert filectrl text option to value. allow any unique prefix
8183    ** of the option name, or a numerical value. */
8184    n2 = strlen30(zCmd);
8185    for(i=0; i<ArraySize(aCtrl); i++){
8186      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8187        if( filectrl<0 ){
8188          filectrl = aCtrl[i].ctrlCode;
8189          iCtrl = i;
8190        }else{
8191          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8192                              "Use \".filectrl --help\" for help\n", zCmd);
8193          rc = 1;
8194          goto meta_command_exit;
8195        }
8196      }
8197    }
8198    if( filectrl<0 ){
8199      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8200                         "Use \".filectrl --help\" for help\n", zCmd);
8201    }else{
8202      switch(filectrl){
8203        case SQLITE_FCNTL_SIZE_LIMIT: {
8204          if( nArg!=2 && nArg!=3 ) break;
8205          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8206          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8207          isOk = 1;
8208          break;
8209        }
8210        case SQLITE_FCNTL_LOCK_TIMEOUT:
8211        case SQLITE_FCNTL_CHUNK_SIZE: {
8212          int x;
8213          if( nArg!=3 ) break;
8214          x = (int)integerValue(azArg[2]);
8215          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8216          isOk = 2;
8217          break;
8218        }
8219        case SQLITE_FCNTL_PERSIST_WAL:
8220        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8221          int x;
8222          if( nArg!=2 && nArg!=3 ) break;
8223          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8224          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8225          iRes = x;
8226          isOk = 1;
8227          break;
8228        }
8229        case SQLITE_FCNTL_DATA_VERSION:
8230        case SQLITE_FCNTL_HAS_MOVED: {
8231          int x;
8232          if( nArg!=2 ) break;
8233          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8234          iRes = x;
8235          isOk = 1;
8236          break;
8237        }
8238        case SQLITE_FCNTL_TEMPFILENAME: {
8239          char *z = 0;
8240          if( nArg!=2 ) break;
8241          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8242          if( z ){
8243            utf8_printf(p->out, "%s\n", z);
8244            sqlite3_free(z);
8245          }
8246          isOk = 2;
8247          break;
8248        }
8249        case SQLITE_FCNTL_RESERVE_BYTES: {
8250          int x;
8251          if( nArg>=3 ){
8252            x = atoi(azArg[2]);
8253            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8254          }
8255          x = -1;
8256          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8257          utf8_printf(p->out,"%d\n", x);
8258          isOk = 2;
8259          break;
8260        }
8261      }
8262    }
8263    if( isOk==0 && iCtrl>=0 ){
8264      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8265      rc = 1;
8266    }else if( isOk==1 ){
8267      char zBuf[100];
8268      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8269      raw_printf(p->out, "%s\n", zBuf);
8270    }
8271  }else
8272
8273  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8274    ShellState data;
8275    int doStats = 0;
8276    memcpy(&data, p, sizeof(data));
8277    data.showHeader = 0;
8278    data.cMode = data.mode = MODE_Semi;
8279    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8280      data.cMode = data.mode = MODE_Pretty;
8281      nArg = 1;
8282    }
8283    if( nArg!=1 ){
8284      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8285      rc = 1;
8286      goto meta_command_exit;
8287    }
8288    open_db(p, 0);
8289    rc = sqlite3_exec(p->db,
8290       "SELECT sql FROM"
8291       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8292       "     FROM sqlite_schema UNION ALL"
8293       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8294       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8295       "ORDER BY x",
8296       callback, &data, 0
8297    );
8298    if( rc==SQLITE_OK ){
8299      sqlite3_stmt *pStmt;
8300      rc = sqlite3_prepare_v2(p->db,
8301               "SELECT rowid FROM sqlite_schema"
8302               " WHERE name GLOB 'sqlite_stat[134]'",
8303               -1, &pStmt, 0);
8304      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8305      sqlite3_finalize(pStmt);
8306    }
8307    if( doStats==0 ){
8308      raw_printf(p->out, "/* No STAT tables available */\n");
8309    }else{
8310      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8311      data.cMode = data.mode = MODE_Insert;
8312      data.zDestTable = "sqlite_stat1";
8313      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8314      data.zDestTable = "sqlite_stat4";
8315      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8316      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8317    }
8318  }else
8319
8320  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8321    if( nArg==2 ){
8322      p->showHeader = booleanValue(azArg[1]);
8323      p->shellFlgs |= SHFLG_HeaderSet;
8324    }else{
8325      raw_printf(stderr, "Usage: .headers on|off\n");
8326      rc = 1;
8327    }
8328  }else
8329
8330  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8331    if( nArg>=2 ){
8332      n = showHelp(p->out, azArg[1]);
8333      if( n==0 ){
8334        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8335      }
8336    }else{
8337      showHelp(p->out, 0);
8338    }
8339  }else
8340
8341#ifndef SQLITE_SHELL_FIDDLE
8342  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8343    char *zTable = 0;           /* Insert data into this table */
8344    char *zSchema = 0;          /* within this schema (may default to "main") */
8345    char *zFile = 0;            /* Name of file to extra content from */
8346    sqlite3_stmt *pStmt = NULL; /* A statement */
8347    int nCol;                   /* Number of columns in the table */
8348    int nByte;                  /* Number of bytes in an SQL string */
8349    int i, j;                   /* Loop counters */
8350    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8351    int nSep;                   /* Number of bytes in p->colSeparator[] */
8352    char *zSql;                 /* An SQL statement */
8353    char *zFullTabName;         /* Table name with schema if applicable */
8354    ImportCtx sCtx;             /* Reader context */
8355    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8356    int eVerbose = 0;           /* Larger for more console output */
8357    int nSkip = 0;              /* Initial lines to skip */
8358    int useOutputMode = 1;      /* Use output mode to determine separators */
8359    char *zCreate = 0;          /* CREATE TABLE statement text */
8360
8361    failIfSafeMode(p, "cannot run .import in safe mode");
8362    memset(&sCtx, 0, sizeof(sCtx));
8363    if( p->mode==MODE_Ascii ){
8364      xRead = ascii_read_one_field;
8365    }else{
8366      xRead = csv_read_one_field;
8367    }
8368    rc = 1;
8369    for(i=1; i<nArg; i++){
8370      char *z = azArg[i];
8371      if( z[0]=='-' && z[1]=='-' ) z++;
8372      if( z[0]!='-' ){
8373        if( zFile==0 ){
8374          zFile = z;
8375        }else if( zTable==0 ){
8376          zTable = z;
8377        }else{
8378          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8379          showHelp(p->out, "import");
8380          goto meta_command_exit;
8381        }
8382      }else if( strcmp(z,"-v")==0 ){
8383        eVerbose++;
8384      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8385        zSchema = azArg[++i];
8386      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8387        nSkip = integerValue(azArg[++i]);
8388      }else if( strcmp(z,"-ascii")==0 ){
8389        sCtx.cColSep = SEP_Unit[0];
8390        sCtx.cRowSep = SEP_Record[0];
8391        xRead = ascii_read_one_field;
8392        useOutputMode = 0;
8393      }else if( strcmp(z,"-csv")==0 ){
8394        sCtx.cColSep = ',';
8395        sCtx.cRowSep = '\n';
8396        xRead = csv_read_one_field;
8397        useOutputMode = 0;
8398      }else{
8399        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8400        showHelp(p->out, "import");
8401        goto meta_command_exit;
8402      }
8403    }
8404    if( zTable==0 ){
8405      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8406                  zFile==0 ? "FILE" : "TABLE");
8407      showHelp(p->out, "import");
8408      goto meta_command_exit;
8409    }
8410    seenInterrupt = 0;
8411    open_db(p, 0);
8412    if( useOutputMode ){
8413      /* If neither the --csv or --ascii options are specified, then set
8414      ** the column and row separator characters from the output mode. */
8415      nSep = strlen30(p->colSeparator);
8416      if( nSep==0 ){
8417        raw_printf(stderr,
8418                   "Error: non-null column separator required for import\n");
8419        goto meta_command_exit;
8420      }
8421      if( nSep>1 ){
8422        raw_printf(stderr,
8423              "Error: multi-character column separators not allowed"
8424              " for import\n");
8425        goto meta_command_exit;
8426      }
8427      nSep = strlen30(p->rowSeparator);
8428      if( nSep==0 ){
8429        raw_printf(stderr,
8430            "Error: non-null row separator required for import\n");
8431        goto meta_command_exit;
8432      }
8433      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8434        /* When importing CSV (only), if the row separator is set to the
8435        ** default output row separator, change it to the default input
8436        ** row separator.  This avoids having to maintain different input
8437        ** and output row separators. */
8438        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8439        nSep = strlen30(p->rowSeparator);
8440      }
8441      if( nSep>1 ){
8442        raw_printf(stderr, "Error: multi-character row separators not allowed"
8443                           " for import\n");
8444        goto meta_command_exit;
8445      }
8446      sCtx.cColSep = p->colSeparator[0];
8447      sCtx.cRowSep = p->rowSeparator[0];
8448    }
8449    sCtx.zFile = zFile;
8450    sCtx.nLine = 1;
8451    if( sCtx.zFile[0]=='|' ){
8452#ifdef SQLITE_OMIT_POPEN
8453      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8454      goto meta_command_exit;
8455#else
8456      sCtx.in = popen(sCtx.zFile+1, "r");
8457      sCtx.zFile = "<pipe>";
8458      sCtx.xCloser = pclose;
8459#endif
8460    }else{
8461      sCtx.in = fopen(sCtx.zFile, "rb");
8462      sCtx.xCloser = fclose;
8463    }
8464    if( sCtx.in==0 ){
8465      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8466      goto meta_command_exit;
8467    }
8468    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8469      char zSep[2];
8470      zSep[1] = 0;
8471      zSep[0] = sCtx.cColSep;
8472      utf8_printf(p->out, "Column separator ");
8473      output_c_string(p->out, zSep);
8474      utf8_printf(p->out, ", row separator ");
8475      zSep[0] = sCtx.cRowSep;
8476      output_c_string(p->out, zSep);
8477      utf8_printf(p->out, "\n");
8478    }
8479    sCtx.z = sqlite3_malloc64(120);
8480    if( sCtx.z==0 ){
8481      import_cleanup(&sCtx);
8482      shell_out_of_memory();
8483    }
8484    /* Below, resources must be freed before exit. */
8485    while( (nSkip--)>0 ){
8486      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8487    }
8488    if( zSchema!=0 ){
8489      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8490    }else{
8491      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8492    }
8493    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8494    if( zSql==0 || zFullTabName==0 ){
8495      import_cleanup(&sCtx);
8496      shell_out_of_memory();
8497    }
8498    nByte = strlen30(zSql);
8499    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8500    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8501    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8502      sqlite3 *dbCols = 0;
8503      char *zRenames = 0;
8504      char *zColDefs;
8505      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
8506      while( xRead(&sCtx) ){
8507        zAutoColumn(sCtx.z, &dbCols, 0);
8508        if( sCtx.cTerm!=sCtx.cColSep ) break;
8509      }
8510      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8511      if( zRenames!=0 ){
8512        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8513                    "Columns renamed during .import %s due to duplicates:\n"
8514                    "%s\n", sCtx.zFile, zRenames);
8515        sqlite3_free(zRenames);
8516      }
8517      assert(dbCols==0);
8518      if( zColDefs==0 ){
8519        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8520      import_fail:
8521        sqlite3_free(zCreate);
8522        sqlite3_free(zSql);
8523        sqlite3_free(zFullTabName);
8524        import_cleanup(&sCtx);
8525        rc = 1;
8526        goto meta_command_exit;
8527      }
8528      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8529      if( eVerbose>=1 ){
8530        utf8_printf(p->out, "%s\n", zCreate);
8531      }
8532      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8533      if( rc ){
8534        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8535        goto import_fail;
8536      }
8537      sqlite3_free(zCreate);
8538      zCreate = 0;
8539      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8540    }
8541    if( rc ){
8542      if (pStmt) sqlite3_finalize(pStmt);
8543      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8544      goto import_fail;
8545    }
8546    sqlite3_free(zSql);
8547    nCol = sqlite3_column_count(pStmt);
8548    sqlite3_finalize(pStmt);
8549    pStmt = 0;
8550    if( nCol==0 ) return 0; /* no columns, no error */
8551    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8552    if( zSql==0 ){
8553      import_cleanup(&sCtx);
8554      shell_out_of_memory();
8555    }
8556    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
8557    j = strlen30(zSql);
8558    for(i=1; i<nCol; i++){
8559      zSql[j++] = ',';
8560      zSql[j++] = '?';
8561    }
8562    zSql[j++] = ')';
8563    zSql[j] = 0;
8564    if( eVerbose>=2 ){
8565      utf8_printf(p->out, "Insert using: %s\n", zSql);
8566    }
8567    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8568    if( rc ){
8569      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8570      if (pStmt) sqlite3_finalize(pStmt);
8571      goto import_fail;
8572    }
8573    sqlite3_free(zSql);
8574    sqlite3_free(zFullTabName);
8575    needCommit = sqlite3_get_autocommit(p->db);
8576    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8577    do{
8578      int startLine = sCtx.nLine;
8579      for(i=0; i<nCol; i++){
8580        char *z = xRead(&sCtx);
8581        /*
8582        ** Did we reach end-of-file before finding any columns?
8583        ** If so, stop instead of NULL filling the remaining columns.
8584        */
8585        if( z==0 && i==0 ) break;
8586        /*
8587        ** Did we reach end-of-file OR end-of-line before finding any
8588        ** columns in ASCII mode?  If so, stop instead of NULL filling
8589        ** the remaining columns.
8590        */
8591        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8592        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8593        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8594          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8595                          "filling the rest with NULL\n",
8596                          sCtx.zFile, startLine, nCol, i+1);
8597          i += 2;
8598          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8599        }
8600      }
8601      if( sCtx.cTerm==sCtx.cColSep ){
8602        do{
8603          xRead(&sCtx);
8604          i++;
8605        }while( sCtx.cTerm==sCtx.cColSep );
8606        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8607                        "extras ignored\n",
8608                        sCtx.zFile, startLine, nCol, i);
8609      }
8610      if( i>=nCol ){
8611        sqlite3_step(pStmt);
8612        rc = sqlite3_reset(pStmt);
8613        if( rc!=SQLITE_OK ){
8614          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8615                      startLine, sqlite3_errmsg(p->db));
8616          sCtx.nErr++;
8617        }else{
8618          sCtx.nRow++;
8619        }
8620      }
8621    }while( sCtx.cTerm!=EOF );
8622
8623    import_cleanup(&sCtx);
8624    sqlite3_finalize(pStmt);
8625    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8626    if( eVerbose>0 ){
8627      utf8_printf(p->out,
8628          "Added %d rows with %d errors using %d lines of input\n",
8629          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8630    }
8631  }else
8632#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8633
8634#ifndef SQLITE_UNTESTABLE
8635  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8636    char *zSql;
8637    char *zCollist = 0;
8638    sqlite3_stmt *pStmt;
8639    int tnum = 0;
8640    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8641    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8642    int i;
8643    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8644      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8645                          "       .imposter off\n");
8646      /* Also allowed, but not documented:
8647      **
8648      **    .imposter TABLE IMPOSTER
8649      **
8650      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8651      ** imposter is another WITHOUT ROWID table with the columns in
8652      ** storage order. */
8653      rc = 1;
8654      goto meta_command_exit;
8655    }
8656    open_db(p, 0);
8657    if( nArg==2 ){
8658      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8659      goto meta_command_exit;
8660    }
8661    zSql = sqlite3_mprintf(
8662      "SELECT rootpage, 0 FROM sqlite_schema"
8663      " WHERE name='%q' AND type='index'"
8664      "UNION ALL "
8665      "SELECT rootpage, 1 FROM sqlite_schema"
8666      " WHERE name='%q' AND type='table'"
8667      "   AND sql LIKE '%%without%%rowid%%'",
8668      azArg[1], azArg[1]
8669    );
8670    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8671    sqlite3_free(zSql);
8672    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8673      tnum = sqlite3_column_int(pStmt, 0);
8674      isWO = sqlite3_column_int(pStmt, 1);
8675    }
8676    sqlite3_finalize(pStmt);
8677    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8678    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8679    sqlite3_free(zSql);
8680    i = 0;
8681    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8682      char zLabel[20];
8683      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8684      i++;
8685      if( zCol==0 ){
8686        if( sqlite3_column_int(pStmt,1)==-1 ){
8687          zCol = "_ROWID_";
8688        }else{
8689          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8690          zCol = zLabel;
8691        }
8692      }
8693      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8694        lenPK = (int)strlen(zCollist);
8695      }
8696      if( zCollist==0 ){
8697        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8698      }else{
8699        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8700      }
8701    }
8702    sqlite3_finalize(pStmt);
8703    if( i==0 || tnum==0 ){
8704      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8705      rc = 1;
8706      sqlite3_free(zCollist);
8707      goto meta_command_exit;
8708    }
8709    if( lenPK==0 ) lenPK = 100000;
8710    zSql = sqlite3_mprintf(
8711          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8712          azArg[2], zCollist, lenPK, zCollist);
8713    sqlite3_free(zCollist);
8714    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8715    if( rc==SQLITE_OK ){
8716      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8717      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8718      if( rc ){
8719        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8720      }else{
8721        utf8_printf(stdout, "%s;\n", zSql);
8722        raw_printf(stdout,
8723          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8724          azArg[1], isWO ? "table" : "index"
8725        );
8726      }
8727    }else{
8728      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8729      rc = 1;
8730    }
8731    sqlite3_free(zSql);
8732  }else
8733#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8734
8735#ifdef SQLITE_ENABLE_IOTRACE
8736  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8737    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8738    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8739    iotrace = 0;
8740    if( nArg<2 ){
8741      sqlite3IoTrace = 0;
8742    }else if( strcmp(azArg[1], "-")==0 ){
8743      sqlite3IoTrace = iotracePrintf;
8744      iotrace = stdout;
8745    }else{
8746      iotrace = fopen(azArg[1], "w");
8747      if( iotrace==0 ){
8748        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8749        sqlite3IoTrace = 0;
8750        rc = 1;
8751      }else{
8752        sqlite3IoTrace = iotracePrintf;
8753      }
8754    }
8755  }else
8756#endif
8757
8758  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8759    static const struct {
8760       const char *zLimitName;   /* Name of a limit */
8761       int limitCode;            /* Integer code for that limit */
8762    } aLimit[] = {
8763      { "length",                SQLITE_LIMIT_LENGTH                    },
8764      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8765      { "column",                SQLITE_LIMIT_COLUMN                    },
8766      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8767      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8768      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8769      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8770      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8771      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8772      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8773      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8774      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8775    };
8776    int i, n2;
8777    open_db(p, 0);
8778    if( nArg==1 ){
8779      for(i=0; i<ArraySize(aLimit); i++){
8780        printf("%20s %d\n", aLimit[i].zLimitName,
8781               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8782      }
8783    }else if( nArg>3 ){
8784      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8785      rc = 1;
8786      goto meta_command_exit;
8787    }else{
8788      int iLimit = -1;
8789      n2 = strlen30(azArg[1]);
8790      for(i=0; i<ArraySize(aLimit); i++){
8791        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8792          if( iLimit<0 ){
8793            iLimit = i;
8794          }else{
8795            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8796            rc = 1;
8797            goto meta_command_exit;
8798          }
8799        }
8800      }
8801      if( iLimit<0 ){
8802        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8803                        "enter \".limits\" with no arguments for a list.\n",
8804                         azArg[1]);
8805        rc = 1;
8806        goto meta_command_exit;
8807      }
8808      if( nArg==3 ){
8809        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8810                      (int)integerValue(azArg[2]));
8811      }
8812      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8813             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8814    }
8815  }else
8816
8817  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8818    open_db(p, 0);
8819    lintDotCommand(p, azArg, nArg);
8820  }else
8821
8822#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
8823  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8824    const char *zFile, *zProc;
8825    char *zErrMsg = 0;
8826    failIfSafeMode(p, "cannot run .load in safe mode");
8827    if( nArg<2 ){
8828      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8829      rc = 1;
8830      goto meta_command_exit;
8831    }
8832    zFile = azArg[1];
8833    zProc = nArg>=3 ? azArg[2] : 0;
8834    open_db(p, 0);
8835    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8836    if( rc!=SQLITE_OK ){
8837      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8838      sqlite3_free(zErrMsg);
8839      rc = 1;
8840    }
8841  }else
8842#endif
8843
8844#ifndef SQLITE_SHELL_FIDDLE
8845  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8846    failIfSafeMode(p, "cannot run .log in safe mode");
8847    if( nArg!=2 ){
8848      raw_printf(stderr, "Usage: .log FILENAME\n");
8849      rc = 1;
8850    }else{
8851      const char *zFile = azArg[1];
8852      output_file_close(p->pLog);
8853      p->pLog = output_file_open(zFile, 0);
8854    }
8855  }else
8856#endif
8857
8858  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8859    const char *zMode = 0;
8860    const char *zTabname = 0;
8861    int i, n2;
8862    ColModeOpts cmOpts = ColModeOpts_default;
8863    for(i=1; i<nArg; i++){
8864      const char *z = azArg[i];
8865      if( optionMatch(z,"wrap") && i+1<nArg ){
8866        cmOpts.iWrap = integerValue(azArg[++i]);
8867      }else if( optionMatch(z,"ww") ){
8868        cmOpts.bWordWrap = 1;
8869      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
8870        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
8871      }else if( optionMatch(z,"quote") ){
8872        cmOpts.bQuote = 1;
8873      }else if( optionMatch(z,"noquote") ){
8874        cmOpts.bQuote = 0;
8875      }else if( zMode==0 ){
8876        zMode = z;
8877        /* Apply defaults for qbox pseudo-mods. If that
8878         * overwrites already-set values, user was informed of this.
8879         */
8880        if( strcmp(z, "qbox")==0 ){
8881          ColModeOpts cmo = ColModeOpts_default_qbox;
8882          zMode = "box";
8883          cmOpts = cmo;
8884        }
8885      }else if( zTabname==0 ){
8886        zTabname = z;
8887      }else if( z[0]=='-' ){
8888        utf8_printf(stderr, "unknown option: %s\n", z);
8889        utf8_printf(stderr, "options:\n"
8890                            "  --noquote\n"
8891                            "  --quote\n"
8892                            "  --wordwrap on/off\n"
8893                            "  --wrap N\n"
8894                            "  --ww\n");
8895        rc = 1;
8896        goto meta_command_exit;
8897      }else{
8898        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
8899        rc = 1;
8900        goto meta_command_exit;
8901      }
8902    }
8903    if( zMode==0 ){
8904      if( p->mode==MODE_Column
8905       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
8906      ){
8907        raw_printf
8908          (p->out,
8909           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
8910           modeDescr[p->mode], p->cmOpts.iWrap,
8911           p->cmOpts.bWordWrap ? "on" : "off",
8912           p->cmOpts.bQuote ? "" : "no");
8913      }else{
8914        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8915      }
8916      zMode = modeDescr[p->mode];
8917    }
8918    n2 = strlen30(zMode);
8919    if( strncmp(zMode,"lines",n2)==0 ){
8920      p->mode = MODE_Line;
8921      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8922    }else if( strncmp(zMode,"columns",n2)==0 ){
8923      p->mode = MODE_Column;
8924      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8925        p->showHeader = 1;
8926      }
8927      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8928      p->cmOpts = cmOpts;
8929    }else if( strncmp(zMode,"list",n2)==0 ){
8930      p->mode = MODE_List;
8931      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8932      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8933    }else if( strncmp(zMode,"html",n2)==0 ){
8934      p->mode = MODE_Html;
8935    }else if( strncmp(zMode,"tcl",n2)==0 ){
8936      p->mode = MODE_Tcl;
8937      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8938      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8939    }else if( strncmp(zMode,"csv",n2)==0 ){
8940      p->mode = MODE_Csv;
8941      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8942      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8943    }else if( strncmp(zMode,"tabs",n2)==0 ){
8944      p->mode = MODE_List;
8945      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8946    }else if( strncmp(zMode,"insert",n2)==0 ){
8947      p->mode = MODE_Insert;
8948      set_table_name(p, zTabname ? zTabname : "table");
8949    }else if( strncmp(zMode,"quote",n2)==0 ){
8950      p->mode = MODE_Quote;
8951      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8952      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8953    }else if( strncmp(zMode,"ascii",n2)==0 ){
8954      p->mode = MODE_Ascii;
8955      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8956      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8957    }else if( strncmp(zMode,"markdown",n2)==0 ){
8958      p->mode = MODE_Markdown;
8959      p->cmOpts = cmOpts;
8960    }else if( strncmp(zMode,"table",n2)==0 ){
8961      p->mode = MODE_Table;
8962      p->cmOpts = cmOpts;
8963    }else if( strncmp(zMode,"box",n2)==0 ){
8964      p->mode = MODE_Box;
8965      p->cmOpts = cmOpts;
8966    }else if( strncmp(zMode,"count",n2)==0 ){
8967      p->mode = MODE_Count;
8968    }else if( strncmp(zMode,"off",n2)==0 ){
8969      p->mode = MODE_Off;
8970    }else if( strncmp(zMode,"json",n2)==0 ){
8971      p->mode = MODE_Json;
8972    }else{
8973      raw_printf(stderr, "Error: mode should be one of: "
8974         "ascii box column csv html insert json line list markdown "
8975         "qbox quote table tabs tcl\n");
8976      rc = 1;
8977    }
8978    p->cMode = p->mode;
8979  }else
8980
8981#ifndef SQLITE_SHELL_FIDDLE
8982  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
8983    if( nArg!=2 ){
8984      raw_printf(stderr, "Usage: .nonce NONCE\n");
8985      rc = 1;
8986    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
8987      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
8988                 p->lineno, azArg[1]);
8989      exit(1);
8990    }else{
8991      p->bSafeMode = 0;
8992      return 0;  /* Return immediately to bypass the safe mode reset
8993                 ** at the end of this procedure */
8994    }
8995  }else
8996#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8997
8998  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8999    if( nArg==2 ){
9000      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9001                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9002    }else{
9003      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9004      rc = 1;
9005    }
9006  }else
9007
9008  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9009    const char *zFN = 0;     /* Pointer to constant filename */
9010    char *zNewFilename = 0;  /* Name of the database file to open */
9011    int iName = 1;           /* Index in azArg[] of the filename */
9012    int newFlag = 0;         /* True to delete file before opening */
9013    int openMode = SHELL_OPEN_UNSPEC;
9014
9015    /* Check for command-line arguments */
9016    for(iName=1; iName<nArg; iName++){
9017      const char *z = azArg[iName];
9018#ifndef SQLITE_SHELL_FIDDLE
9019      if( optionMatch(z,"new") ){
9020        newFlag = 1;
9021#ifdef SQLITE_HAVE_ZLIB
9022      }else if( optionMatch(z, "zip") ){
9023        openMode = SHELL_OPEN_ZIPFILE;
9024#endif
9025      }else if( optionMatch(z, "append") ){
9026        openMode = SHELL_OPEN_APPENDVFS;
9027      }else if( optionMatch(z, "readonly") ){
9028        openMode = SHELL_OPEN_READONLY;
9029      }else if( optionMatch(z, "nofollow") ){
9030        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9031#ifndef SQLITE_OMIT_DESERIALIZE
9032      }else if( optionMatch(z, "deserialize") ){
9033        openMode = SHELL_OPEN_DESERIALIZE;
9034      }else if( optionMatch(z, "hexdb") ){
9035        openMode = SHELL_OPEN_HEXDB;
9036      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9037        p->szMax = integerValue(azArg[++iName]);
9038#endif /* SQLITE_OMIT_DESERIALIZE */
9039      }else
9040#endif /* !SQLITE_SHELL_FIDDLE */
9041      if( z[0]=='-' ){
9042        utf8_printf(stderr, "unknown option: %s\n", z);
9043        rc = 1;
9044        goto meta_command_exit;
9045      }else if( zFN ){
9046        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9047        rc = 1;
9048        goto meta_command_exit;
9049      }else{
9050        zFN = z;
9051      }
9052    }
9053
9054    /* Close the existing database */
9055    session_close_all(p, -1);
9056    close_db(p->db);
9057    p->db = 0;
9058    p->pAuxDb->zDbFilename = 0;
9059    sqlite3_free(p->pAuxDb->zFreeOnClose);
9060    p->pAuxDb->zFreeOnClose = 0;
9061    p->openMode = openMode;
9062    p->openFlags = 0;
9063    p->szMax = 0;
9064
9065    /* If a filename is specified, try to open it first */
9066    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9067      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9068#ifndef SQLITE_SHELL_FIDDLE
9069      if( p->bSafeMode
9070       && p->openMode!=SHELL_OPEN_HEXDB
9071       && zFN
9072       && strcmp(zFN,":memory:")!=0
9073      ){
9074        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9075      }
9076#else
9077      /* WASM mode has its own sandboxed pseudo-filesystem. */
9078#endif
9079      if( zFN ){
9080        zNewFilename = sqlite3_mprintf("%s", zFN);
9081        shell_check_oom(zNewFilename);
9082      }else{
9083        zNewFilename = 0;
9084      }
9085      p->pAuxDb->zDbFilename = zNewFilename;
9086      open_db(p, OPEN_DB_KEEPALIVE);
9087      if( p->db==0 ){
9088        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9089        sqlite3_free(zNewFilename);
9090      }else{
9091        p->pAuxDb->zFreeOnClose = zNewFilename;
9092      }
9093    }
9094    if( p->db==0 ){
9095      /* As a fall-back open a TEMP database */
9096      p->pAuxDb->zDbFilename = 0;
9097      open_db(p, 0);
9098    }
9099  }else
9100
9101#ifndef SQLITE_SHELL_FIDDLE
9102  if( (c=='o'
9103        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9104   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9105  ){
9106    char *zFile = 0;
9107    int bTxtMode = 0;
9108    int i;
9109    int eMode = 0;
9110    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9111    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9112
9113    zBOM[0] = 0;
9114    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9115    if( c=='e' ){
9116      eMode = 'x';
9117      bOnce = 2;
9118    }else if( strncmp(azArg[0],"once",n)==0 ){
9119      bOnce = 1;
9120    }
9121    for(i=1; i<nArg; i++){
9122      char *z = azArg[i];
9123      if( z[0]=='-' ){
9124        if( z[1]=='-' ) z++;
9125        if( strcmp(z,"-bom")==0 ){
9126          zBOM[0] = 0xef;
9127          zBOM[1] = 0xbb;
9128          zBOM[2] = 0xbf;
9129          zBOM[3] = 0;
9130        }else if( c!='e' && strcmp(z,"-x")==0 ){
9131          eMode = 'x';  /* spreadsheet */
9132        }else if( c!='e' && strcmp(z,"-e")==0 ){
9133          eMode = 'e';  /* text editor */
9134        }else{
9135          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9136                      azArg[i]);
9137          showHelp(p->out, azArg[0]);
9138          rc = 1;
9139          goto meta_command_exit;
9140        }
9141      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9142        zFile = sqlite3_mprintf("%s", z);
9143        if( zFile && zFile[0]=='|' ){
9144          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9145          break;
9146        }
9147      }else{
9148        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9149                    azArg[i]);
9150        showHelp(p->out, azArg[0]);
9151        rc = 1;
9152        sqlite3_free(zFile);
9153        goto meta_command_exit;
9154      }
9155    }
9156    if( zFile==0 ){
9157      zFile = sqlite3_mprintf("stdout");
9158    }
9159    if( bOnce ){
9160      p->outCount = 2;
9161    }else{
9162      p->outCount = 0;
9163    }
9164    output_reset(p);
9165#ifndef SQLITE_NOHAVE_SYSTEM
9166    if( eMode=='e' || eMode=='x' ){
9167      p->doXdgOpen = 1;
9168      outputModePush(p);
9169      if( eMode=='x' ){
9170        /* spreadsheet mode.  Output as CSV. */
9171        newTempFile(p, "csv");
9172        ShellClearFlag(p, SHFLG_Echo);
9173        p->mode = MODE_Csv;
9174        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9175        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9176      }else{
9177        /* text editor mode */
9178        newTempFile(p, "txt");
9179        bTxtMode = 1;
9180      }
9181      sqlite3_free(zFile);
9182      zFile = sqlite3_mprintf("%s", p->zTempFile);
9183    }
9184#endif /* SQLITE_NOHAVE_SYSTEM */
9185    shell_check_oom(zFile);
9186    if( zFile[0]=='|' ){
9187#ifdef SQLITE_OMIT_POPEN
9188      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9189      rc = 1;
9190      p->out = stdout;
9191#else
9192      p->out = popen(zFile + 1, "w");
9193      if( p->out==0 ){
9194        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9195        p->out = stdout;
9196        rc = 1;
9197      }else{
9198        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9199        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9200      }
9201#endif
9202    }else{
9203      p->out = output_file_open(zFile, bTxtMode);
9204      if( p->out==0 ){
9205        if( strcmp(zFile,"off")!=0 ){
9206          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9207        }
9208        p->out = stdout;
9209        rc = 1;
9210      } else {
9211        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9212        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9213      }
9214    }
9215    sqlite3_free(zFile);
9216  }else
9217#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9218
9219  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9220    open_db(p,0);
9221    if( nArg<=1 ) goto parameter_syntax_error;
9222
9223    /* .parameter clear
9224    ** Clear all bind parameters by dropping the TEMP table that holds them.
9225    */
9226    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9227      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9228                   0, 0, 0);
9229    }else
9230
9231    /* .parameter list
9232    ** List all bind parameters.
9233    */
9234    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9235      sqlite3_stmt *pStmt = 0;
9236      int rx;
9237      int len = 0;
9238      rx = sqlite3_prepare_v2(p->db,
9239             "SELECT max(length(key)) "
9240             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9241      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9242        len = sqlite3_column_int(pStmt, 0);
9243        if( len>40 ) len = 40;
9244      }
9245      sqlite3_finalize(pStmt);
9246      pStmt = 0;
9247      if( len ){
9248        rx = sqlite3_prepare_v2(p->db,
9249             "SELECT key, quote(value) "
9250             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9251        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9252          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9253                      sqlite3_column_text(pStmt,1));
9254        }
9255        sqlite3_finalize(pStmt);
9256      }
9257    }else
9258
9259    /* .parameter init
9260    ** Make sure the TEMP table used to hold bind parameters exists.
9261    ** Create it if necessary.
9262    */
9263    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9264      bind_table_init(p);
9265    }else
9266
9267    /* .parameter set NAME VALUE
9268    ** Set or reset a bind parameter.  NAME should be the full parameter
9269    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9270    ** VALUE can be in either SQL literal notation, or if not it will be
9271    ** understood to be a text string.
9272    */
9273    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9274      int rx;
9275      char *zSql;
9276      sqlite3_stmt *pStmt;
9277      const char *zKey = azArg[2];
9278      const char *zValue = azArg[3];
9279      bind_table_init(p);
9280      zSql = sqlite3_mprintf(
9281                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9282                  "VALUES(%Q,%s);", zKey, zValue);
9283      shell_check_oom(zSql);
9284      pStmt = 0;
9285      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9286      sqlite3_free(zSql);
9287      if( rx!=SQLITE_OK ){
9288        sqlite3_finalize(pStmt);
9289        pStmt = 0;
9290        zSql = sqlite3_mprintf(
9291                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9292                   "VALUES(%Q,%Q);", zKey, zValue);
9293        shell_check_oom(zSql);
9294        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9295        sqlite3_free(zSql);
9296        if( rx!=SQLITE_OK ){
9297          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9298          sqlite3_finalize(pStmt);
9299          pStmt = 0;
9300          rc = 1;
9301        }
9302      }
9303      sqlite3_step(pStmt);
9304      sqlite3_finalize(pStmt);
9305    }else
9306
9307    /* .parameter unset NAME
9308    ** Remove the NAME binding from the parameter binding table, if it
9309    ** exists.
9310    */
9311    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9312      char *zSql = sqlite3_mprintf(
9313          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9314      shell_check_oom(zSql);
9315      sqlite3_exec(p->db, zSql, 0, 0, 0);
9316      sqlite3_free(zSql);
9317    }else
9318    /* If no command name matches, show a syntax error */
9319    parameter_syntax_error:
9320    showHelp(p->out, "parameter");
9321  }else
9322
9323  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9324    int i;
9325    for(i=1; i<nArg; i++){
9326      if( i>1 ) raw_printf(p->out, " ");
9327      utf8_printf(p->out, "%s", azArg[i]);
9328    }
9329    raw_printf(p->out, "\n");
9330  }else
9331
9332#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9333  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9334    int i;
9335    int nn = 0;
9336    p->flgProgress = 0;
9337    p->mxProgress = 0;
9338    p->nProgress = 0;
9339    for(i=1; i<nArg; i++){
9340      const char *z = azArg[i];
9341      if( z[0]=='-' ){
9342        z++;
9343        if( z[0]=='-' ) z++;
9344        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9345          p->flgProgress |= SHELL_PROGRESS_QUIET;
9346          continue;
9347        }
9348        if( strcmp(z,"reset")==0 ){
9349          p->flgProgress |= SHELL_PROGRESS_RESET;
9350          continue;
9351        }
9352        if( strcmp(z,"once")==0 ){
9353          p->flgProgress |= SHELL_PROGRESS_ONCE;
9354          continue;
9355        }
9356        if( strcmp(z,"limit")==0 ){
9357          if( i+1>=nArg ){
9358            utf8_printf(stderr, "Error: missing argument on --limit\n");
9359            rc = 1;
9360            goto meta_command_exit;
9361          }else{
9362            p->mxProgress = (int)integerValue(azArg[++i]);
9363          }
9364          continue;
9365        }
9366        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9367        rc = 1;
9368        goto meta_command_exit;
9369      }else{
9370        nn = (int)integerValue(z);
9371      }
9372    }
9373    open_db(p, 0);
9374    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9375  }else
9376#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9377
9378  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9379    if( nArg >= 2) {
9380      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9381    }
9382    if( nArg >= 3) {
9383      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9384    }
9385  }else
9386
9387#ifndef SQLITE_SHELL_FIDDLE
9388  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9389    rc = 2;
9390  }else
9391#endif
9392
9393#ifndef SQLITE_SHELL_FIDDLE
9394  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9395    FILE *inSaved = p->in;
9396    int savedLineno = p->lineno;
9397    failIfSafeMode(p, "cannot run .read in safe mode");
9398    if( nArg!=2 ){
9399      raw_printf(stderr, "Usage: .read FILE\n");
9400      rc = 1;
9401      goto meta_command_exit;
9402    }
9403    if( azArg[1][0]=='|' ){
9404#ifdef SQLITE_OMIT_POPEN
9405      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9406      rc = 1;
9407      p->out = stdout;
9408#else
9409      p->in = popen(azArg[1]+1, "r");
9410      if( p->in==0 ){
9411        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9412        rc = 1;
9413      }else{
9414        rc = process_input(p);
9415        pclose(p->in);
9416      }
9417#endif
9418    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9419      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9420      rc = 1;
9421    }else{
9422      rc = process_input(p);
9423      fclose(p->in);
9424    }
9425    p->in = inSaved;
9426    p->lineno = savedLineno;
9427  }else
9428#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9429
9430#ifndef SQLITE_SHELL_FIDDLE
9431  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9432    const char *zSrcFile;
9433    const char *zDb;
9434    sqlite3 *pSrc;
9435    sqlite3_backup *pBackup;
9436    int nTimeout = 0;
9437
9438    failIfSafeMode(p, "cannot run .restore in safe mode");
9439    if( nArg==2 ){
9440      zSrcFile = azArg[1];
9441      zDb = "main";
9442    }else if( nArg==3 ){
9443      zSrcFile = azArg[2];
9444      zDb = azArg[1];
9445    }else{
9446      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9447      rc = 1;
9448      goto meta_command_exit;
9449    }
9450    rc = sqlite3_open(zSrcFile, &pSrc);
9451    if( rc!=SQLITE_OK ){
9452      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9453      close_db(pSrc);
9454      return 1;
9455    }
9456    open_db(p, 0);
9457    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9458    if( pBackup==0 ){
9459      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9460      close_db(pSrc);
9461      return 1;
9462    }
9463    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9464          || rc==SQLITE_BUSY  ){
9465      if( rc==SQLITE_BUSY ){
9466        if( nTimeout++ >= 3 ) break;
9467        sqlite3_sleep(100);
9468      }
9469    }
9470    sqlite3_backup_finish(pBackup);
9471    if( rc==SQLITE_DONE ){
9472      rc = 0;
9473    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9474      raw_printf(stderr, "Error: source database is busy\n");
9475      rc = 1;
9476    }else{
9477      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9478      rc = 1;
9479    }
9480    close_db(pSrc);
9481  }else
9482#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9483
9484  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9485    if( nArg==2 ){
9486      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9487#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9488      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9489#endif
9490    }else{
9491      raw_printf(stderr, "Usage: .scanstats on|off\n");
9492      rc = 1;
9493    }
9494  }else
9495
9496  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9497    ShellText sSelect;
9498    ShellState data;
9499    char *zErrMsg = 0;
9500    const char *zDiv = "(";
9501    const char *zName = 0;
9502    int iSchema = 0;
9503    int bDebug = 0;
9504    int bNoSystemTabs = 0;
9505    int ii;
9506
9507    open_db(p, 0);
9508    memcpy(&data, p, sizeof(data));
9509    data.showHeader = 0;
9510    data.cMode = data.mode = MODE_Semi;
9511    initText(&sSelect);
9512    for(ii=1; ii<nArg; ii++){
9513      if( optionMatch(azArg[ii],"indent") ){
9514        data.cMode = data.mode = MODE_Pretty;
9515      }else if( optionMatch(azArg[ii],"debug") ){
9516        bDebug = 1;
9517      }else if( optionMatch(azArg[ii],"nosys") ){
9518        bNoSystemTabs = 1;
9519      }else if( azArg[ii][0]=='-' ){
9520        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9521        rc = 1;
9522        goto meta_command_exit;
9523      }else if( zName==0 ){
9524        zName = azArg[ii];
9525      }else{
9526        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9527        rc = 1;
9528        goto meta_command_exit;
9529      }
9530    }
9531    if( zName!=0 ){
9532      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9533                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9534                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9535                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9536      if( isSchema ){
9537        char *new_argv[2], *new_colv[2];
9538        new_argv[0] = sqlite3_mprintf(
9539                      "CREATE TABLE %s (\n"
9540                      "  type text,\n"
9541                      "  name text,\n"
9542                      "  tbl_name text,\n"
9543                      "  rootpage integer,\n"
9544                      "  sql text\n"
9545                      ")", zName);
9546        shell_check_oom(new_argv[0]);
9547        new_argv[1] = 0;
9548        new_colv[0] = "sql";
9549        new_colv[1] = 0;
9550        callback(&data, 1, new_argv, new_colv);
9551        sqlite3_free(new_argv[0]);
9552      }
9553    }
9554    if( zDiv ){
9555      sqlite3_stmt *pStmt = 0;
9556      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9557                              -1, &pStmt, 0);
9558      if( rc ){
9559        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9560        sqlite3_finalize(pStmt);
9561        rc = 1;
9562        goto meta_command_exit;
9563      }
9564      appendText(&sSelect, "SELECT sql FROM", 0);
9565      iSchema = 0;
9566      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9567        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9568        char zScNum[30];
9569        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9570        appendText(&sSelect, zDiv, 0);
9571        zDiv = " UNION ALL ";
9572        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9573        if( sqlite3_stricmp(zDb, "main")!=0 ){
9574          appendText(&sSelect, zDb, '\'');
9575        }else{
9576          appendText(&sSelect, "NULL", 0);
9577        }
9578        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9579        appendText(&sSelect, zScNum, 0);
9580        appendText(&sSelect, " AS snum, ", 0);
9581        appendText(&sSelect, zDb, '\'');
9582        appendText(&sSelect, " AS sname FROM ", 0);
9583        appendText(&sSelect, zDb, quoteChar(zDb));
9584        appendText(&sSelect, ".sqlite_schema", 0);
9585      }
9586      sqlite3_finalize(pStmt);
9587#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9588      if( zName ){
9589        appendText(&sSelect,
9590           " UNION ALL SELECT shell_module_schema(name),"
9591           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9592        0);
9593      }
9594#endif
9595      appendText(&sSelect, ") WHERE ", 0);
9596      if( zName ){
9597        char *zQarg = sqlite3_mprintf("%Q", zName);
9598        int bGlob;
9599        shell_check_oom(zQarg);
9600        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9601                strchr(zName, '[') != 0;
9602        if( strchr(zName, '.') ){
9603          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9604        }else{
9605          appendText(&sSelect, "lower(tbl_name)", 0);
9606        }
9607        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9608        appendText(&sSelect, zQarg, 0);
9609        if( !bGlob ){
9610          appendText(&sSelect, " ESCAPE '\\' ", 0);
9611        }
9612        appendText(&sSelect, " AND ", 0);
9613        sqlite3_free(zQarg);
9614      }
9615      if( bNoSystemTabs ){
9616        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9617      }
9618      appendText(&sSelect, "sql IS NOT NULL"
9619                           " ORDER BY snum, rowid", 0);
9620      if( bDebug ){
9621        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9622      }else{
9623        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9624      }
9625      freeText(&sSelect);
9626    }
9627    if( zErrMsg ){
9628      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9629      sqlite3_free(zErrMsg);
9630      rc = 1;
9631    }else if( rc != SQLITE_OK ){
9632      raw_printf(stderr,"Error: querying schema information\n");
9633      rc = 1;
9634    }else{
9635      rc = 0;
9636    }
9637  }else
9638
9639  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
9640   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
9641  ){
9642    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9643    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9644  }else
9645
9646#if defined(SQLITE_ENABLE_SESSION)
9647  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9648    struct AuxDb *pAuxDb = p->pAuxDb;
9649    OpenSession *pSession = &pAuxDb->aSession[0];
9650    char **azCmd = &azArg[1];
9651    int iSes = 0;
9652    int nCmd = nArg - 1;
9653    int i;
9654    if( nArg<=1 ) goto session_syntax_error;
9655    open_db(p, 0);
9656    if( nArg>=3 ){
9657      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9658        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9659      }
9660      if( iSes<pAuxDb->nSession ){
9661        pSession = &pAuxDb->aSession[iSes];
9662        azCmd++;
9663        nCmd--;
9664      }else{
9665        pSession = &pAuxDb->aSession[0];
9666        iSes = 0;
9667      }
9668    }
9669
9670    /* .session attach TABLE
9671    ** Invoke the sqlite3session_attach() interface to attach a particular
9672    ** table so that it is never filtered.
9673    */
9674    if( strcmp(azCmd[0],"attach")==0 ){
9675      if( nCmd!=2 ) goto session_syntax_error;
9676      if( pSession->p==0 ){
9677        session_not_open:
9678        raw_printf(stderr, "ERROR: No sessions are open\n");
9679      }else{
9680        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9681        if( rc ){
9682          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9683          rc = 0;
9684        }
9685      }
9686    }else
9687
9688    /* .session changeset FILE
9689    ** .session patchset FILE
9690    ** Write a changeset or patchset into a file.  The file is overwritten.
9691    */
9692    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9693      FILE *out = 0;
9694      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9695      if( nCmd!=2 ) goto session_syntax_error;
9696      if( pSession->p==0 ) goto session_not_open;
9697      out = fopen(azCmd[1], "wb");
9698      if( out==0 ){
9699        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9700                    azCmd[1]);
9701      }else{
9702        int szChng;
9703        void *pChng;
9704        if( azCmd[0][0]=='c' ){
9705          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9706        }else{
9707          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9708        }
9709        if( rc ){
9710          printf("Error: error code %d\n", rc);
9711          rc = 0;
9712        }
9713        if( pChng
9714          && fwrite(pChng, szChng, 1, out)!=1 ){
9715          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9716                  szChng);
9717        }
9718        sqlite3_free(pChng);
9719        fclose(out);
9720      }
9721    }else
9722
9723    /* .session close
9724    ** Close the identified session
9725    */
9726    if( strcmp(azCmd[0], "close")==0 ){
9727      if( nCmd!=1 ) goto session_syntax_error;
9728      if( pAuxDb->nSession ){
9729        session_close(pSession);
9730        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9731      }
9732    }else
9733
9734    /* .session enable ?BOOLEAN?
9735    ** Query or set the enable flag
9736    */
9737    if( strcmp(azCmd[0], "enable")==0 ){
9738      int ii;
9739      if( nCmd>2 ) goto session_syntax_error;
9740      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9741      if( pAuxDb->nSession ){
9742        ii = sqlite3session_enable(pSession->p, ii);
9743        utf8_printf(p->out, "session %s enable flag = %d\n",
9744                    pSession->zName, ii);
9745      }
9746    }else
9747
9748    /* .session filter GLOB ....
9749    ** Set a list of GLOB patterns of table names to be excluded.
9750    */
9751    if( strcmp(azCmd[0], "filter")==0 ){
9752      int ii, nByte;
9753      if( nCmd<2 ) goto session_syntax_error;
9754      if( pAuxDb->nSession ){
9755        for(ii=0; ii<pSession->nFilter; ii++){
9756          sqlite3_free(pSession->azFilter[ii]);
9757        }
9758        sqlite3_free(pSession->azFilter);
9759        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9760        pSession->azFilter = sqlite3_malloc( nByte );
9761        if( pSession->azFilter==0 ){
9762          raw_printf(stderr, "Error: out or memory\n");
9763          exit(1);
9764        }
9765        for(ii=1; ii<nCmd; ii++){
9766          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9767          shell_check_oom(x);
9768        }
9769        pSession->nFilter = ii-1;
9770      }
9771    }else
9772
9773    /* .session indirect ?BOOLEAN?
9774    ** Query or set the indirect flag
9775    */
9776    if( strcmp(azCmd[0], "indirect")==0 ){
9777      int ii;
9778      if( nCmd>2 ) goto session_syntax_error;
9779      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9780      if( pAuxDb->nSession ){
9781        ii = sqlite3session_indirect(pSession->p, ii);
9782        utf8_printf(p->out, "session %s indirect flag = %d\n",
9783                    pSession->zName, ii);
9784      }
9785    }else
9786
9787    /* .session isempty
9788    ** Determine if the session is empty
9789    */
9790    if( strcmp(azCmd[0], "isempty")==0 ){
9791      int ii;
9792      if( nCmd!=1 ) goto session_syntax_error;
9793      if( pAuxDb->nSession ){
9794        ii = sqlite3session_isempty(pSession->p);
9795        utf8_printf(p->out, "session %s isempty flag = %d\n",
9796                    pSession->zName, ii);
9797      }
9798    }else
9799
9800    /* .session list
9801    ** List all currently open sessions
9802    */
9803    if( strcmp(azCmd[0],"list")==0 ){
9804      for(i=0; i<pAuxDb->nSession; i++){
9805        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9806      }
9807    }else
9808
9809    /* .session open DB NAME
9810    ** Open a new session called NAME on the attached database DB.
9811    ** DB is normally "main".
9812    */
9813    if( strcmp(azCmd[0],"open")==0 ){
9814      char *zName;
9815      if( nCmd!=3 ) goto session_syntax_error;
9816      zName = azCmd[2];
9817      if( zName[0]==0 ) goto session_syntax_error;
9818      for(i=0; i<pAuxDb->nSession; i++){
9819        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9820          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9821          goto meta_command_exit;
9822        }
9823      }
9824      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9825        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9826        goto meta_command_exit;
9827      }
9828      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9829      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9830      if( rc ){
9831        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9832        rc = 0;
9833        goto meta_command_exit;
9834      }
9835      pSession->nFilter = 0;
9836      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9837      pAuxDb->nSession++;
9838      pSession->zName = sqlite3_mprintf("%s", zName);
9839      shell_check_oom(pSession->zName);
9840    }else
9841    /* If no command name matches, show a syntax error */
9842    session_syntax_error:
9843    showHelp(p->out, "session");
9844  }else
9845#endif
9846
9847#ifdef SQLITE_DEBUG
9848  /* Undocumented commands for internal testing.  Subject to change
9849  ** without notice. */
9850  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9851    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9852      int i, v;
9853      for(i=1; i<nArg; i++){
9854        v = booleanValue(azArg[i]);
9855        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9856      }
9857    }
9858    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9859      int i; sqlite3_int64 v;
9860      for(i=1; i<nArg; i++){
9861        char zBuf[200];
9862        v = integerValue(azArg[i]);
9863        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9864        utf8_printf(p->out, "%s", zBuf);
9865      }
9866    }
9867  }else
9868#endif
9869
9870  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9871    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9872    int bVerbose = 0;        /* Verbose output */
9873    int bSelftestExists;     /* True if SELFTEST already exists */
9874    int i, k;                /* Loop counters */
9875    int nTest = 0;           /* Number of tests runs */
9876    int nErr = 0;            /* Number of errors seen */
9877    ShellText str;           /* Answer for a query */
9878    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9879
9880    open_db(p,0);
9881    for(i=1; i<nArg; i++){
9882      const char *z = azArg[i];
9883      if( z[0]=='-' && z[1]=='-' ) z++;
9884      if( strcmp(z,"-init")==0 ){
9885        bIsInit = 1;
9886      }else
9887      if( strcmp(z,"-v")==0 ){
9888        bVerbose++;
9889      }else
9890      {
9891        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9892                    azArg[i], azArg[0]);
9893        raw_printf(stderr, "Should be one of: --init -v\n");
9894        rc = 1;
9895        goto meta_command_exit;
9896      }
9897    }
9898    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9899           != SQLITE_OK ){
9900      bSelftestExists = 0;
9901    }else{
9902      bSelftestExists = 1;
9903    }
9904    if( bIsInit ){
9905      createSelftestTable(p);
9906      bSelftestExists = 1;
9907    }
9908    initText(&str);
9909    appendText(&str, "x", 0);
9910    for(k=bSelftestExists; k>=0; k--){
9911      if( k==1 ){
9912        rc = sqlite3_prepare_v2(p->db,
9913            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9914            -1, &pStmt, 0);
9915      }else{
9916        rc = sqlite3_prepare_v2(p->db,
9917          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9918          "      (1,'run','PRAGMA integrity_check','ok')",
9919          -1, &pStmt, 0);
9920      }
9921      if( rc ){
9922        raw_printf(stderr, "Error querying the selftest table\n");
9923        rc = 1;
9924        sqlite3_finalize(pStmt);
9925        goto meta_command_exit;
9926      }
9927      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9928        int tno = sqlite3_column_int(pStmt, 0);
9929        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9930        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9931        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9932
9933        if( zOp==0 ) continue;
9934        if( zSql==0 ) continue;
9935        if( zAns==0 ) continue;
9936        k = 0;
9937        if( bVerbose>0 ){
9938          printf("%d: %s %s\n", tno, zOp, zSql);
9939        }
9940        if( strcmp(zOp,"memo")==0 ){
9941          utf8_printf(p->out, "%s\n", zSql);
9942        }else
9943        if( strcmp(zOp,"run")==0 ){
9944          char *zErrMsg = 0;
9945          str.n = 0;
9946          str.z[0] = 0;
9947          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9948          nTest++;
9949          if( bVerbose ){
9950            utf8_printf(p->out, "Result: %s\n", str.z);
9951          }
9952          if( rc || zErrMsg ){
9953            nErr++;
9954            rc = 1;
9955            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9956            sqlite3_free(zErrMsg);
9957          }else if( strcmp(zAns,str.z)!=0 ){
9958            nErr++;
9959            rc = 1;
9960            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9961            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
9962          }
9963        }else
9964        {
9965          utf8_printf(stderr,
9966            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9967          rc = 1;
9968          break;
9969        }
9970      } /* End loop over rows of content from SELFTEST */
9971      sqlite3_finalize(pStmt);
9972    } /* End loop over k */
9973    freeText(&str);
9974    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9975  }else
9976
9977  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9978    if( nArg<2 || nArg>3 ){
9979      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9980      rc = 1;
9981    }
9982    if( nArg>=2 ){
9983      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9984                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9985    }
9986    if( nArg>=3 ){
9987      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9988                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9989    }
9990  }else
9991
9992  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9993    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
9994    int i;                   /* Loop counter */
9995    int bSchema = 0;         /* Also hash the schema */
9996    int bSeparate = 0;       /* Hash each table separately */
9997    int iSize = 224;         /* Hash algorithm to use */
9998    int bDebug = 0;          /* Only show the query that would have run */
9999    sqlite3_stmt *pStmt;     /* For querying tables names */
10000    char *zSql;              /* SQL to be run */
10001    char *zSep;              /* Separator */
10002    ShellText sSql;          /* Complete SQL for the query to run the hash */
10003    ShellText sQuery;        /* Set of queries used to read all content */
10004    open_db(p, 0);
10005    for(i=1; i<nArg; i++){
10006      const char *z = azArg[i];
10007      if( z[0]=='-' ){
10008        z++;
10009        if( z[0]=='-' ) z++;
10010        if( strcmp(z,"schema")==0 ){
10011          bSchema = 1;
10012        }else
10013        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10014         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10015        ){
10016          iSize = atoi(&z[5]);
10017        }else
10018        if( strcmp(z,"debug")==0 ){
10019          bDebug = 1;
10020        }else
10021        {
10022          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10023                      azArg[i], azArg[0]);
10024          showHelp(p->out, azArg[0]);
10025          rc = 1;
10026          goto meta_command_exit;
10027        }
10028      }else if( zLike ){
10029        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10030        rc = 1;
10031        goto meta_command_exit;
10032      }else{
10033        zLike = z;
10034        bSeparate = 1;
10035        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10036      }
10037    }
10038    if( bSchema ){
10039      zSql = "SELECT lower(name) FROM sqlite_schema"
10040             " WHERE type='table' AND coalesce(rootpage,0)>1"
10041             " UNION ALL SELECT 'sqlite_schema'"
10042             " ORDER BY 1 collate nocase";
10043    }else{
10044      zSql = "SELECT lower(name) FROM sqlite_schema"
10045             " WHERE type='table' AND coalesce(rootpage,0)>1"
10046             " AND name NOT LIKE 'sqlite_%'"
10047             " ORDER BY 1 collate nocase";
10048    }
10049    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10050    initText(&sQuery);
10051    initText(&sSql);
10052    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10053    zSep = "VALUES(";
10054    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10055      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10056      if( zTab==0 ) continue;
10057      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10058      if( strncmp(zTab, "sqlite_",7)!=0 ){
10059        appendText(&sQuery,"SELECT * FROM ", 0);
10060        appendText(&sQuery,zTab,'"');
10061        appendText(&sQuery," NOT INDEXED;", 0);
10062      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10063        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10064                           " ORDER BY name;", 0);
10065      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10066        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10067                           " ORDER BY name;", 0);
10068      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10069        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10070                           " ORDER BY tbl,idx;", 0);
10071      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10072        appendText(&sQuery, "SELECT * FROM ", 0);
10073        appendText(&sQuery, zTab, 0);
10074        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10075      }
10076      appendText(&sSql, zSep, 0);
10077      appendText(&sSql, sQuery.z, '\'');
10078      sQuery.n = 0;
10079      appendText(&sSql, ",", 0);
10080      appendText(&sSql, zTab, '\'');
10081      zSep = "),(";
10082    }
10083    sqlite3_finalize(pStmt);
10084    if( bSeparate ){
10085      zSql = sqlite3_mprintf(
10086          "%s))"
10087          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10088          "   FROM [sha3sum$query]",
10089          sSql.z, iSize);
10090    }else{
10091      zSql = sqlite3_mprintf(
10092          "%s))"
10093          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10094          "   FROM [sha3sum$query]",
10095          sSql.z, iSize);
10096    }
10097    shell_check_oom(zSql);
10098    freeText(&sQuery);
10099    freeText(&sSql);
10100    if( bDebug ){
10101      utf8_printf(p->out, "%s\n", zSql);
10102    }else{
10103      shell_exec(p, zSql, 0);
10104    }
10105    sqlite3_free(zSql);
10106  }else
10107
10108#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10109  if( c=='s'
10110   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10111  ){
10112    char *zCmd;
10113    int i, x;
10114    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10115    if( nArg<2 ){
10116      raw_printf(stderr, "Usage: .system COMMAND\n");
10117      rc = 1;
10118      goto meta_command_exit;
10119    }
10120    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10121    for(i=2; i<nArg && zCmd!=0; i++){
10122      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10123                             zCmd, azArg[i]);
10124    }
10125    x = zCmd!=0 ? system(zCmd) : 1;
10126    sqlite3_free(zCmd);
10127    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10128  }else
10129#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10130
10131  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10132    static const char *azBool[] = { "off", "on", "trigger", "full"};
10133    const char *zOut;
10134    int i;
10135    if( nArg!=1 ){
10136      raw_printf(stderr, "Usage: .show\n");
10137      rc = 1;
10138      goto meta_command_exit;
10139    }
10140    utf8_printf(p->out, "%12.12s: %s\n","echo",
10141                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10142    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10143    utf8_printf(p->out, "%12.12s: %s\n","explain",
10144         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10145    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10146    if( p->mode==MODE_Column
10147     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10148    ){
10149      utf8_printf
10150        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10151         modeDescr[p->mode], p->cmOpts.iWrap,
10152         p->cmOpts.bWordWrap ? "on" : "off",
10153         p->cmOpts.bQuote ? "" : "no");
10154    }else{
10155      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10156    }
10157    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10158      output_c_string(p->out, p->nullValue);
10159      raw_printf(p->out, "\n");
10160    utf8_printf(p->out,"%12.12s: %s\n","output",
10161            strlen30(p->outfile) ? p->outfile : "stdout");
10162    utf8_printf(p->out,"%12.12s: ", "colseparator");
10163      output_c_string(p->out, p->colSeparator);
10164      raw_printf(p->out, "\n");
10165    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10166      output_c_string(p->out, p->rowSeparator);
10167      raw_printf(p->out, "\n");
10168    switch( p->statsOn ){
10169      case 0:  zOut = "off";     break;
10170      default: zOut = "on";      break;
10171      case 2:  zOut = "stmt";    break;
10172      case 3:  zOut = "vmstep";  break;
10173    }
10174    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10175    utf8_printf(p->out, "%12.12s: ", "width");
10176    for (i=0;i<p->nWidth;i++) {
10177      raw_printf(p->out, "%d ", p->colWidth[i]);
10178    }
10179    raw_printf(p->out, "\n");
10180    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10181                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10182  }else
10183
10184  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10185    if( nArg==2 ){
10186      if( strcmp(azArg[1],"stmt")==0 ){
10187        p->statsOn = 2;
10188      }else if( strcmp(azArg[1],"vmstep")==0 ){
10189        p->statsOn = 3;
10190      }else{
10191        p->statsOn = (u8)booleanValue(azArg[1]);
10192      }
10193    }else if( nArg==1 ){
10194      display_stats(p->db, p, 0);
10195    }else{
10196      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10197      rc = 1;
10198    }
10199  }else
10200
10201  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10202   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10203                 || strncmp(azArg[0], "indexes", n)==0) )
10204  ){
10205    sqlite3_stmt *pStmt;
10206    char **azResult;
10207    int nRow, nAlloc;
10208    int ii;
10209    ShellText s;
10210    initText(&s);
10211    open_db(p, 0);
10212    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10213    if( rc ){
10214      sqlite3_finalize(pStmt);
10215      return shellDatabaseError(p->db);
10216    }
10217
10218    if( nArg>2 && c=='i' ){
10219      /* It is an historical accident that the .indexes command shows an error
10220      ** when called with the wrong number of arguments whereas the .tables
10221      ** command does not. */
10222      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10223      rc = 1;
10224      sqlite3_finalize(pStmt);
10225      goto meta_command_exit;
10226    }
10227    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10228      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10229      if( zDbName==0 ) continue;
10230      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10231      if( sqlite3_stricmp(zDbName, "main")==0 ){
10232        appendText(&s, "SELECT name FROM ", 0);
10233      }else{
10234        appendText(&s, "SELECT ", 0);
10235        appendText(&s, zDbName, '\'');
10236        appendText(&s, "||'.'||name FROM ", 0);
10237      }
10238      appendText(&s, zDbName, '"');
10239      appendText(&s, ".sqlite_schema ", 0);
10240      if( c=='t' ){
10241        appendText(&s," WHERE type IN ('table','view')"
10242                      "   AND name NOT LIKE 'sqlite_%'"
10243                      "   AND name LIKE ?1", 0);
10244      }else{
10245        appendText(&s," WHERE type='index'"
10246                      "   AND tbl_name LIKE ?1", 0);
10247      }
10248    }
10249    rc = sqlite3_finalize(pStmt);
10250    if( rc==SQLITE_OK ){
10251      appendText(&s, " ORDER BY 1", 0);
10252      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10253    }
10254    freeText(&s);
10255    if( rc ) return shellDatabaseError(p->db);
10256
10257    /* Run the SQL statement prepared by the above block. Store the results
10258    ** as an array of nul-terminated strings in azResult[].  */
10259    nRow = nAlloc = 0;
10260    azResult = 0;
10261    if( nArg>1 ){
10262      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10263    }else{
10264      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10265    }
10266    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10267      if( nRow>=nAlloc ){
10268        char **azNew;
10269        int n2 = nAlloc*2 + 10;
10270        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10271        shell_check_oom(azNew);
10272        nAlloc = n2;
10273        azResult = azNew;
10274      }
10275      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10276      shell_check_oom(azResult[nRow]);
10277      nRow++;
10278    }
10279    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10280      rc = shellDatabaseError(p->db);
10281    }
10282
10283    /* Pretty-print the contents of array azResult[] to the output */
10284    if( rc==0 && nRow>0 ){
10285      int len, maxlen = 0;
10286      int i, j;
10287      int nPrintCol, nPrintRow;
10288      for(i=0; i<nRow; i++){
10289        len = strlen30(azResult[i]);
10290        if( len>maxlen ) maxlen = len;
10291      }
10292      nPrintCol = 80/(maxlen+2);
10293      if( nPrintCol<1 ) nPrintCol = 1;
10294      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10295      for(i=0; i<nPrintRow; i++){
10296        for(j=i; j<nRow; j+=nPrintRow){
10297          char *zSp = j<nPrintRow ? "" : "  ";
10298          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10299                      azResult[j] ? azResult[j]:"");
10300        }
10301        raw_printf(p->out, "\n");
10302      }
10303    }
10304
10305    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10306    sqlite3_free(azResult);
10307  }else
10308
10309#ifndef SQLITE_SHELL_FIDDLE
10310  /* Begin redirecting output to the file "testcase-out.txt" */
10311  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10312    output_reset(p);
10313    p->out = output_file_open("testcase-out.txt", 0);
10314    if( p->out==0 ){
10315      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10316    }
10317    if( nArg>=2 ){
10318      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10319    }else{
10320      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10321    }
10322  }else
10323#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10324
10325#ifndef SQLITE_UNTESTABLE
10326  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10327    static const struct {
10328       const char *zCtrlName;   /* Name of a test-control option */
10329       int ctrlCode;            /* Integer code for that option */
10330       int unSafe;              /* Not valid for --safe mode */
10331       const char *zUsage;      /* Usage notes */
10332    } aCtrl[] = {
10333      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10334      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10335    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10336    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10337      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10338      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10339    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10340      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10341      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10342      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10343      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10344      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10345#ifdef YYCOVERAGE
10346      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10347#endif
10348      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10349      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10350      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10351      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10352      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10353      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10354      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10355    };
10356    int testctrl = -1;
10357    int iCtrl = -1;
10358    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10359    int isOk = 0;
10360    int i, n2;
10361    const char *zCmd = 0;
10362
10363    open_db(p, 0);
10364    zCmd = nArg>=2 ? azArg[1] : "help";
10365
10366    /* The argument can optionally begin with "-" or "--" */
10367    if( zCmd[0]=='-' && zCmd[1] ){
10368      zCmd++;
10369      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10370    }
10371
10372    /* --help lists all test-controls */
10373    if( strcmp(zCmd,"help")==0 ){
10374      utf8_printf(p->out, "Available test-controls:\n");
10375      for(i=0; i<ArraySize(aCtrl); i++){
10376        utf8_printf(p->out, "  .testctrl %s %s\n",
10377                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10378      }
10379      rc = 1;
10380      goto meta_command_exit;
10381    }
10382
10383    /* convert testctrl text option to value. allow any unique prefix
10384    ** of the option name, or a numerical value. */
10385    n2 = strlen30(zCmd);
10386    for(i=0; i<ArraySize(aCtrl); i++){
10387      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10388        if( testctrl<0 ){
10389          testctrl = aCtrl[i].ctrlCode;
10390          iCtrl = i;
10391        }else{
10392          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10393                              "Use \".testctrl --help\" for help\n", zCmd);
10394          rc = 1;
10395          goto meta_command_exit;
10396        }
10397      }
10398    }
10399    if( testctrl<0 ){
10400      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10401                         "Use \".testctrl --help\" for help\n", zCmd);
10402    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10403      utf8_printf(stderr,
10404         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10405         p->lineno, aCtrl[iCtrl].zCtrlName);
10406      exit(1);
10407    }else{
10408      switch(testctrl){
10409
10410        /* sqlite3_test_control(int, db, int) */
10411        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10412          if( nArg==3 ){
10413            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10414            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10415            isOk = 3;
10416          }
10417          break;
10418
10419        /* sqlite3_test_control(int) */
10420        case SQLITE_TESTCTRL_PRNG_SAVE:
10421        case SQLITE_TESTCTRL_PRNG_RESTORE:
10422        case SQLITE_TESTCTRL_BYTEORDER:
10423          if( nArg==2 ){
10424            rc2 = sqlite3_test_control(testctrl);
10425            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10426          }
10427          break;
10428
10429        /* sqlite3_test_control(int, uint) */
10430        case SQLITE_TESTCTRL_PENDING_BYTE:
10431          if( nArg==3 ){
10432            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10433            rc2 = sqlite3_test_control(testctrl, opt);
10434            isOk = 3;
10435          }
10436          break;
10437
10438        /* sqlite3_test_control(int, int, sqlite3*) */
10439        case SQLITE_TESTCTRL_PRNG_SEED:
10440          if( nArg==3 || nArg==4 ){
10441            int ii = (int)integerValue(azArg[2]);
10442            sqlite3 *db;
10443            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10444              sqlite3_randomness(sizeof(ii),&ii);
10445              printf("-- random seed: %d\n", ii);
10446            }
10447            if( nArg==3 ){
10448              db = 0;
10449            }else{
10450              db = p->db;
10451              /* Make sure the schema has been loaded */
10452              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10453            }
10454            rc2 = sqlite3_test_control(testctrl, ii, db);
10455            isOk = 3;
10456          }
10457          break;
10458
10459        /* sqlite3_test_control(int, int) */
10460        case SQLITE_TESTCTRL_ASSERT:
10461        case SQLITE_TESTCTRL_ALWAYS:
10462          if( nArg==3 ){
10463            int opt = booleanValue(azArg[2]);
10464            rc2 = sqlite3_test_control(testctrl, opt);
10465            isOk = 1;
10466          }
10467          break;
10468
10469        /* sqlite3_test_control(int, int) */
10470        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10471        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10472          if( nArg==3 ){
10473            int opt = booleanValue(azArg[2]);
10474            rc2 = sqlite3_test_control(testctrl, opt);
10475            isOk = 3;
10476          }
10477          break;
10478
10479        /* sqlite3_test_control(sqlite3*) */
10480        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10481          rc2 = sqlite3_test_control(testctrl, p->db);
10482          isOk = 3;
10483          break;
10484
10485        case SQLITE_TESTCTRL_IMPOSTER:
10486          if( nArg==5 ){
10487            rc2 = sqlite3_test_control(testctrl, p->db,
10488                          azArg[2],
10489                          integerValue(azArg[3]),
10490                          integerValue(azArg[4]));
10491            isOk = 3;
10492          }
10493          break;
10494
10495        case SQLITE_TESTCTRL_SEEK_COUNT: {
10496          u64 x = 0;
10497          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10498          utf8_printf(p->out, "%llu\n", x);
10499          isOk = 3;
10500          break;
10501        }
10502
10503#ifdef YYCOVERAGE
10504        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10505          if( nArg==2 ){
10506            sqlite3_test_control(testctrl, p->out);
10507            isOk = 3;
10508          }
10509          break;
10510        }
10511#endif
10512#ifdef SQLITE_DEBUG
10513        case SQLITE_TESTCTRL_TUNE: {
10514          if( nArg==4 ){
10515            int id = (int)integerValue(azArg[2]);
10516            int val = (int)integerValue(azArg[3]);
10517            sqlite3_test_control(testctrl, id, &val);
10518            isOk = 3;
10519          }else if( nArg==3 ){
10520            int id = (int)integerValue(azArg[2]);
10521            sqlite3_test_control(testctrl, -id, &rc2);
10522            isOk = 1;
10523          }else if( nArg==2 ){
10524            int id = 1;
10525            while(1){
10526              int val = 0;
10527              rc2 = sqlite3_test_control(testctrl, -id, &val);
10528              if( rc2!=SQLITE_OK ) break;
10529              if( id>1 ) utf8_printf(p->out, "  ");
10530              utf8_printf(p->out, "%d: %d", id, val);
10531              id++;
10532            }
10533            if( id>1 ) utf8_printf(p->out, "\n");
10534            isOk = 3;
10535          }
10536          break;
10537        }
10538#endif
10539        case SQLITE_TESTCTRL_SORTER_MMAP:
10540          if( nArg==3 ){
10541            int opt = (unsigned int)integerValue(azArg[2]);
10542            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10543            isOk = 3;
10544          }
10545          break;
10546      }
10547    }
10548    if( isOk==0 && iCtrl>=0 ){
10549      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10550      rc = 1;
10551    }else if( isOk==1 ){
10552      raw_printf(p->out, "%d\n", rc2);
10553    }else if( isOk==2 ){
10554      raw_printf(p->out, "0x%08x\n", rc2);
10555    }
10556  }else
10557#endif /* !defined(SQLITE_UNTESTABLE) */
10558
10559  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10560    open_db(p, 0);
10561    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10562  }else
10563
10564  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10565    if( nArg==2 ){
10566      enableTimer = booleanValue(azArg[1]);
10567      if( enableTimer && !HAS_TIMER ){
10568        raw_printf(stderr, "Error: timer not available on this system.\n");
10569        enableTimer = 0;
10570      }
10571    }else{
10572      raw_printf(stderr, "Usage: .timer on|off\n");
10573      rc = 1;
10574    }
10575  }else
10576
10577#ifndef SQLITE_OMIT_TRACE
10578  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10579    int mType = 0;
10580    int jj;
10581    open_db(p, 0);
10582    for(jj=1; jj<nArg; jj++){
10583      const char *z = azArg[jj];
10584      if( z[0]=='-' ){
10585        if( optionMatch(z, "expanded") ){
10586          p->eTraceType = SHELL_TRACE_EXPANDED;
10587        }
10588#ifdef SQLITE_ENABLE_NORMALIZE
10589        else if( optionMatch(z, "normalized") ){
10590          p->eTraceType = SHELL_TRACE_NORMALIZED;
10591        }
10592#endif
10593        else if( optionMatch(z, "plain") ){
10594          p->eTraceType = SHELL_TRACE_PLAIN;
10595        }
10596        else if( optionMatch(z, "profile") ){
10597          mType |= SQLITE_TRACE_PROFILE;
10598        }
10599        else if( optionMatch(z, "row") ){
10600          mType |= SQLITE_TRACE_ROW;
10601        }
10602        else if( optionMatch(z, "stmt") ){
10603          mType |= SQLITE_TRACE_STMT;
10604        }
10605        else if( optionMatch(z, "close") ){
10606          mType |= SQLITE_TRACE_CLOSE;
10607        }
10608        else {
10609          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10610          rc = 1;
10611          goto meta_command_exit;
10612        }
10613      }else{
10614        output_file_close(p->traceOut);
10615        p->traceOut = output_file_open(azArg[1], 0);
10616      }
10617    }
10618    if( p->traceOut==0 ){
10619      sqlite3_trace_v2(p->db, 0, 0, 0);
10620    }else{
10621      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10622      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10623    }
10624  }else
10625#endif /* !defined(SQLITE_OMIT_TRACE) */
10626
10627#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10628  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10629    int ii;
10630    int lenOpt;
10631    char *zOpt;
10632    if( nArg<2 ){
10633      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10634      rc = 1;
10635      goto meta_command_exit;
10636    }
10637    open_db(p, 0);
10638    zOpt = azArg[1];
10639    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10640    lenOpt = (int)strlen(zOpt);
10641    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10642      assert( azArg[nArg]==0 );
10643      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10644    }else{
10645      for(ii=1; ii<nArg; ii++){
10646        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10647      }
10648    }
10649  }else
10650#endif
10651
10652#if SQLITE_USER_AUTHENTICATION
10653  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10654    if( nArg<2 ){
10655      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10656      rc = 1;
10657      goto meta_command_exit;
10658    }
10659    open_db(p, 0);
10660    if( strcmp(azArg[1],"login")==0 ){
10661      if( nArg!=4 ){
10662        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10663        rc = 1;
10664        goto meta_command_exit;
10665      }
10666      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10667                                     strlen30(azArg[3]));
10668      if( rc ){
10669        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10670        rc = 1;
10671      }
10672    }else if( strcmp(azArg[1],"add")==0 ){
10673      if( nArg!=5 ){
10674        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10675        rc = 1;
10676        goto meta_command_exit;
10677      }
10678      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10679                            booleanValue(azArg[4]));
10680      if( rc ){
10681        raw_printf(stderr, "User-Add failed: %d\n", rc);
10682        rc = 1;
10683      }
10684    }else if( strcmp(azArg[1],"edit")==0 ){
10685      if( nArg!=5 ){
10686        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10687        rc = 1;
10688        goto meta_command_exit;
10689      }
10690      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10691                              booleanValue(azArg[4]));
10692      if( rc ){
10693        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10694        rc = 1;
10695      }
10696    }else if( strcmp(azArg[1],"delete")==0 ){
10697      if( nArg!=3 ){
10698        raw_printf(stderr, "Usage: .user delete USER\n");
10699        rc = 1;
10700        goto meta_command_exit;
10701      }
10702      rc = sqlite3_user_delete(p->db, azArg[2]);
10703      if( rc ){
10704        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10705        rc = 1;
10706      }
10707    }else{
10708      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10709      rc = 1;
10710      goto meta_command_exit;
10711    }
10712  }else
10713#endif /* SQLITE_USER_AUTHENTICATION */
10714
10715  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10716    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10717        sqlite3_libversion(), sqlite3_sourceid());
10718#if SQLITE_HAVE_ZLIB
10719    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10720#endif
10721#define CTIMEOPT_VAL_(opt) #opt
10722#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10723#if defined(__clang__) && defined(__clang_major__)
10724    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10725                    CTIMEOPT_VAL(__clang_minor__) "."
10726                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10727#elif defined(_MSC_VER)
10728    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10729#elif defined(__GNUC__) && defined(__VERSION__)
10730    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10731#endif
10732  }else
10733
10734  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10735    const char *zDbName = nArg==2 ? azArg[1] : "main";
10736    sqlite3_vfs *pVfs = 0;
10737    if( p->db ){
10738      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10739      if( pVfs ){
10740        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10741        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10742        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10743        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10744      }
10745    }
10746  }else
10747
10748  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10749    sqlite3_vfs *pVfs;
10750    sqlite3_vfs *pCurrent = 0;
10751    if( p->db ){
10752      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10753    }
10754    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10755      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10756           pVfs==pCurrent ? "  <--- CURRENT" : "");
10757      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10758      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10759      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10760      if( pVfs->pNext ){
10761        raw_printf(p->out, "-----------------------------------\n");
10762      }
10763    }
10764  }else
10765
10766  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10767    const char *zDbName = nArg==2 ? azArg[1] : "main";
10768    char *zVfsName = 0;
10769    if( p->db ){
10770      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10771      if( zVfsName ){
10772        utf8_printf(p->out, "%s\n", zVfsName);
10773        sqlite3_free(zVfsName);
10774      }
10775    }
10776  }else
10777
10778  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10779    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10780    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10781  }else
10782
10783  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10784    int j;
10785    assert( nArg<=ArraySize(azArg) );
10786    p->nWidth = nArg-1;
10787    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
10788    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10789    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10790    for(j=1; j<nArg; j++){
10791      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10792    }
10793  }else
10794
10795  {
10796    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10797      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10798    rc = 1;
10799  }
10800
10801meta_command_exit:
10802  if( p->outCount ){
10803    p->outCount--;
10804    if( p->outCount==0 ) output_reset(p);
10805  }
10806  p->bSafeMode = p->bSafeModePersist;
10807  return rc;
10808}
10809
10810/* Line scan result and intermediate states (supporting scan resumption)
10811*/
10812#ifndef CHAR_BIT
10813# define CHAR_BIT 8
10814#endif
10815typedef enum {
10816  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
10817  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
10818  QSS_Start = 0
10819} QuickScanState;
10820#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10821#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10822#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10823#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10824#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10825
10826/*
10827** Scan line for classification to guide shell's handling.
10828** The scan is resumable for subsequent lines when prior
10829** return values are passed as the 2nd argument.
10830*/
10831static QuickScanState quickscan(char *zLine, QuickScanState qss){
10832  char cin;
10833  char cWait = (char)qss; /* intentional narrowing loss */
10834  if( cWait==0 ){
10835  PlainScan:
10836    assert( cWait==0 );
10837    while( (cin = *zLine++)!=0 ){
10838      if( IsSpace(cin) )
10839        continue;
10840      switch (cin){
10841      case '-':
10842        if( *zLine!='-' )
10843          break;
10844        while((cin = *++zLine)!=0 )
10845          if( cin=='\n')
10846            goto PlainScan;
10847        return qss;
10848      case ';':
10849        qss |= QSS_EndingSemi;
10850        continue;
10851      case '/':
10852        if( *zLine=='*' ){
10853          ++zLine;
10854          cWait = '*';
10855          qss = QSS_SETV(qss, cWait);
10856          goto TermScan;
10857        }
10858        break;
10859      case '[':
10860        cin = ']';
10861        /* fall thru */
10862      case '`': case '\'': case '"':
10863        cWait = cin;
10864        qss = QSS_HasDark | cWait;
10865        goto TermScan;
10866      default:
10867        break;
10868      }
10869      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
10870    }
10871  }else{
10872  TermScan:
10873    while( (cin = *zLine++)!=0 ){
10874      if( cin==cWait ){
10875        switch( cWait ){
10876        case '*':
10877          if( *zLine != '/' )
10878            continue;
10879          ++zLine;
10880          cWait = 0;
10881          qss = QSS_SETV(qss, 0);
10882          goto PlainScan;
10883        case '`': case '\'': case '"':
10884          if(*zLine==cWait){
10885            ++zLine;
10886            continue;
10887          }
10888          /* fall thru */
10889        case ']':
10890          cWait = 0;
10891          qss = QSS_SETV(qss, 0);
10892          goto PlainScan;
10893        default: assert(0);
10894        }
10895      }
10896    }
10897  }
10898  return qss;
10899}
10900
10901/*
10902** Return TRUE if the line typed in is an SQL command terminator other
10903** than a semi-colon.  The SQL Server style "go" command is understood
10904** as is the Oracle "/".
10905*/
10906static int line_is_command_terminator(char *zLine){
10907  while( IsSpace(zLine[0]) ){ zLine++; };
10908  if( zLine[0]=='/' )
10909    zLine += 1; /* Oracle */
10910  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
10911    zLine += 2; /* SQL Server */
10912  else
10913    return 0;
10914  return quickscan(zLine, QSS_Start)==QSS_Start;
10915}
10916
10917/*
10918** We need a default sqlite3_complete() implementation to use in case
10919** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10920** any arbitrary text is a complete SQL statement.  This is not very
10921** user-friendly, but it does seem to work.
10922*/
10923#ifdef SQLITE_OMIT_COMPLETE
10924#define sqlite3_complete(x) 1
10925#endif
10926
10927/*
10928** Return true if zSql is a complete SQL statement.  Return false if it
10929** ends in the middle of a string literal or C-style comment.
10930*/
10931static int line_is_complete(char *zSql, int nSql){
10932  int rc;
10933  if( zSql==0 ) return 1;
10934  zSql[nSql] = ';';
10935  zSql[nSql+1] = 0;
10936  rc = sqlite3_complete(zSql);
10937  zSql[nSql] = 0;
10938  return rc;
10939}
10940
10941/*
10942** Run a single line of SQL.  Return the number of errors.
10943*/
10944static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10945  int rc;
10946  char *zErrMsg = 0;
10947
10948  open_db(p, 0);
10949  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10950  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10951  BEGIN_TIMER;
10952  rc = shell_exec(p, zSql, &zErrMsg);
10953  END_TIMER;
10954  if( rc || zErrMsg ){
10955    char zPrefix[100];
10956    const char *zErrorTail;
10957    const char *zErrorType;
10958    if( zErrMsg==0 ){
10959      zErrorType = "Error";
10960      zErrorTail = sqlite3_errmsg(p->db);
10961    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
10962      zErrorType = "Parse error";
10963      zErrorTail = &zErrMsg[12];
10964    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
10965      zErrorType = "Runtime error";
10966      zErrorTail = &zErrMsg[10];
10967    }else{
10968      zErrorType = "Error";
10969      zErrorTail = zErrMsg;
10970    }
10971    if( in!=0 || !stdin_is_interactive ){
10972      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10973                       "%s near line %d:", zErrorType, startline);
10974    }else{
10975      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
10976    }
10977    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
10978    sqlite3_free(zErrMsg);
10979    zErrMsg = 0;
10980    return 1;
10981  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10982    char zLineBuf[2000];
10983    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
10984            "changes: %lld   total_changes: %lld",
10985            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
10986    raw_printf(p->out, "%s\n", zLineBuf);
10987  }
10988  return 0;
10989}
10990
10991static void echo_group_input(ShellState *p, const char *zDo){
10992  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
10993}
10994
10995#ifdef SQLITE_SHELL_FIDDLE
10996/*
10997** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
10998** because we need the global shellState and cannot access it from that function
10999** without moving lots of code around (creating a larger/messier diff).
11000*/
11001static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11002  /* Parse the next line from shellState.wasm.zInput. */
11003  const char *zBegin = shellState.wasm.zPos;
11004  const char *z = zBegin;
11005  char *zLine = 0;
11006  int nZ = 0;
11007
11008  UNUSED_PARAMETER(in);
11009  UNUSED_PARAMETER(isContinuation);
11010  if(!z || !*z){
11011    return 0;
11012  }
11013  while(*z && isspace(*z)) ++z;
11014  zBegin = z;
11015  for(; *z && '\n'!=*z; ++nZ, ++z){}
11016  if(nZ>0 && '\r'==zBegin[nZ-1]){
11017    --nZ;
11018  }
11019  shellState.wasm.zPos = z;
11020  zLine = realloc(zPrior, nZ+1);
11021  shell_check_oom(zLine);
11022  memcpy(zLine, zBegin, (size_t)nZ);
11023  zLine[nZ] = 0;
11024  return zLine;
11025}
11026#endif /* SQLITE_SHELL_FIDDLE */
11027
11028/*
11029** Read input from *in and process it.  If *in==0 then input
11030** is interactive - the user is typing it it.  Otherwise, input
11031** is coming from a file or device.  A prompt is issued and history
11032** is saved only if input is interactive.  An interrupt signal will
11033** cause this routine to exit immediately, unless input is interactive.
11034**
11035** Return the number of errors.
11036*/
11037static int process_input(ShellState *p){
11038  char *zLine = 0;          /* A single input line */
11039  char *zSql = 0;           /* Accumulated SQL text */
11040  int nLine;                /* Length of current line */
11041  int nSql = 0;             /* Bytes of zSql[] used */
11042  int nAlloc = 0;           /* Allocated zSql[] space */
11043  int rc;                   /* Error code */
11044  int errCnt = 0;           /* Number of errors seen */
11045  int startline = 0;        /* Line number for start of current input */
11046  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11047
11048  if( p->inputNesting==MAX_INPUT_NESTING ){
11049    /* This will be more informative in a later version. */
11050    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11051                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11052    return 1;
11053  }
11054  ++p->inputNesting;
11055  p->lineno = 0;
11056  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11057    fflush(p->out);
11058    zLine = one_input_line(p->in, zLine, nSql>0);
11059    if( zLine==0 ){
11060      /* End of input */
11061      if( p->in==0 && stdin_is_interactive ) printf("\n");
11062      break;
11063    }
11064    if( seenInterrupt ){
11065      if( p->in!=0 ) break;
11066      seenInterrupt = 0;
11067    }
11068    p->lineno++;
11069    if( QSS_INPLAIN(qss)
11070        && line_is_command_terminator(zLine)
11071        && line_is_complete(zSql, nSql) ){
11072      memcpy(zLine,";",2);
11073    }
11074    qss = quickscan(zLine, qss);
11075    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11076      /* Just swallow single-line whitespace */
11077      echo_group_input(p, zLine);
11078      qss = QSS_Start;
11079      continue;
11080    }
11081    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11082      echo_group_input(p, zLine);
11083      if( zLine[0]=='.' ){
11084        rc = do_meta_command(zLine, p);
11085        if( rc==2 ){ /* exit requested */
11086          break;
11087        }else if( rc ){
11088          errCnt++;
11089        }
11090      }
11091      qss = QSS_Start;
11092      continue;
11093    }
11094    /* No single-line dispositions remain; accumulate line(s). */
11095    nLine = strlen30(zLine);
11096    if( nSql+nLine+2>=nAlloc ){
11097      /* Grow buffer by half-again increments when big. */
11098      nAlloc = nSql+(nSql>>1)+nLine+100;
11099      zSql = realloc(zSql, nAlloc);
11100      shell_check_oom(zSql);
11101    }
11102    if( nSql==0 ){
11103      int i;
11104      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11105      assert( nAlloc>0 && zSql!=0 );
11106      memcpy(zSql, zLine+i, nLine+1-i);
11107      startline = p->lineno;
11108      nSql = nLine-i;
11109    }else{
11110      zSql[nSql++] = '\n';
11111      memcpy(zSql+nSql, zLine, nLine+1);
11112      nSql += nLine;
11113    }
11114    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11115      echo_group_input(p, zSql);
11116      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11117      nSql = 0;
11118      if( p->outCount ){
11119        output_reset(p);
11120        p->outCount = 0;
11121      }else{
11122        clearTempFile(p);
11123      }
11124      p->bSafeMode = p->bSafeModePersist;
11125      qss = QSS_Start;
11126    }else if( nSql && QSS_PLAINWHITE(qss) ){
11127      echo_group_input(p, zSql);
11128      nSql = 0;
11129      qss = QSS_Start;
11130    }
11131  }
11132  if( nSql ){
11133    /* This may be incomplete. Let the SQL parser deal with that. */
11134    echo_group_input(p, zSql);
11135    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11136  }
11137  free(zSql);
11138  free(zLine);
11139  --p->inputNesting;
11140  return errCnt>0;
11141}
11142
11143/*
11144** Return a pathname which is the user's home directory.  A
11145** 0 return indicates an error of some kind.
11146*/
11147static char *find_home_dir(int clearFlag){
11148  static char *home_dir = NULL;
11149  if( clearFlag ){
11150    free(home_dir);
11151    home_dir = 0;
11152    return 0;
11153  }
11154  if( home_dir ) return home_dir;
11155
11156#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11157     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11158  {
11159    struct passwd *pwent;
11160    uid_t uid = getuid();
11161    if( (pwent=getpwuid(uid)) != NULL) {
11162      home_dir = pwent->pw_dir;
11163    }
11164  }
11165#endif
11166
11167#if defined(_WIN32_WCE)
11168  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11169   */
11170  home_dir = "/";
11171#else
11172
11173#if defined(_WIN32) || defined(WIN32)
11174  if (!home_dir) {
11175    home_dir = getenv("USERPROFILE");
11176  }
11177#endif
11178
11179  if (!home_dir) {
11180    home_dir = getenv("HOME");
11181  }
11182
11183#if defined(_WIN32) || defined(WIN32)
11184  if (!home_dir) {
11185    char *zDrive, *zPath;
11186    int n;
11187    zDrive = getenv("HOMEDRIVE");
11188    zPath = getenv("HOMEPATH");
11189    if( zDrive && zPath ){
11190      n = strlen30(zDrive) + strlen30(zPath) + 1;
11191      home_dir = malloc( n );
11192      if( home_dir==0 ) return 0;
11193      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11194      return home_dir;
11195    }
11196    home_dir = "c:\\";
11197  }
11198#endif
11199
11200#endif /* !_WIN32_WCE */
11201
11202  if( home_dir ){
11203    int n = strlen30(home_dir) + 1;
11204    char *z = malloc( n );
11205    if( z ) memcpy(z, home_dir, n);
11206    home_dir = z;
11207  }
11208
11209  return home_dir;
11210}
11211
11212/*
11213** Read input from the file given by sqliterc_override.  Or if that
11214** parameter is NULL, take input from ~/.sqliterc
11215**
11216** Returns the number of errors.
11217*/
11218static void process_sqliterc(
11219  ShellState *p,                  /* Configuration data */
11220  const char *sqliterc_override   /* Name of config file. NULL to use default */
11221){
11222  char *home_dir = NULL;
11223  const char *sqliterc = sqliterc_override;
11224  char *zBuf = 0;
11225  FILE *inSaved = p->in;
11226  int savedLineno = p->lineno;
11227
11228  if (sqliterc == NULL) {
11229    home_dir = find_home_dir(0);
11230    if( home_dir==0 ){
11231      raw_printf(stderr, "-- warning: cannot find home directory;"
11232                      " cannot read ~/.sqliterc\n");
11233      return;
11234    }
11235    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11236    shell_check_oom(zBuf);
11237    sqliterc = zBuf;
11238  }
11239  p->in = fopen(sqliterc,"rb");
11240  if( p->in ){
11241    if( stdin_is_interactive ){
11242      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11243    }
11244    if( process_input(p) && bail_on_error ) exit(1);
11245    fclose(p->in);
11246  }else if( sqliterc_override!=0 ){
11247    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11248    if( bail_on_error ) exit(1);
11249  }
11250  p->in = inSaved;
11251  p->lineno = savedLineno;
11252  sqlite3_free(zBuf);
11253}
11254
11255/*
11256** Show available command line options
11257*/
11258static const char zOptions[] =
11259#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11260  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11261#endif
11262  "   -append              append the database to the end of the file\n"
11263  "   -ascii               set output mode to 'ascii'\n"
11264  "   -bail                stop after hitting an error\n"
11265  "   -batch               force batch I/O\n"
11266  "   -box                 set output mode to 'box'\n"
11267  "   -column              set output mode to 'column'\n"
11268  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11269  "   -csv                 set output mode to 'csv'\n"
11270#if !defined(SQLITE_OMIT_DESERIALIZE)
11271  "   -deserialize         open the database using sqlite3_deserialize()\n"
11272#endif
11273  "   -echo                print inputs before execution\n"
11274  "   -init FILENAME       read/process named file\n"
11275  "   -[no]header          turn headers on or off\n"
11276#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11277  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11278#endif
11279  "   -help                show this message\n"
11280  "   -html                set output mode to HTML\n"
11281  "   -interactive         force interactive I/O\n"
11282  "   -json                set output mode to 'json'\n"
11283  "   -line                set output mode to 'line'\n"
11284  "   -list                set output mode to 'list'\n"
11285  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11286  "   -markdown            set output mode to 'markdown'\n"
11287#if !defined(SQLITE_OMIT_DESERIALIZE)
11288  "   -maxsize N           maximum size for a --deserialize database\n"
11289#endif
11290  "   -memtrace            trace all memory allocations and deallocations\n"
11291  "   -mmap N              default mmap size set to N\n"
11292#ifdef SQLITE_ENABLE_MULTIPLEX
11293  "   -multiplex           enable the multiplexor VFS\n"
11294#endif
11295  "   -newline SEP         set output row separator. Default: '\\n'\n"
11296  "   -nofollow            refuse to open symbolic links to database files\n"
11297  "   -nonce STRING        set the safe-mode escape nonce\n"
11298  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11299  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11300  "   -quote               set output mode to 'quote'\n"
11301  "   -readonly            open the database read-only\n"
11302  "   -safe                enable safe-mode\n"
11303  "   -separator SEP       set output column separator. Default: '|'\n"
11304#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11305  "   -sorterref SIZE      sorter references threshold size\n"
11306#endif
11307  "   -stats               print memory stats before each finalize\n"
11308  "   -table               set output mode to 'table'\n"
11309  "   -tabs                set output mode to 'tabs'\n"
11310  "   -version             show SQLite version\n"
11311  "   -vfs NAME            use NAME as the default VFS\n"
11312#ifdef SQLITE_ENABLE_VFSTRACE
11313  "   -vfstrace            enable tracing of all VFS calls\n"
11314#endif
11315#ifdef SQLITE_HAVE_ZLIB
11316  "   -zip                 open the file as a ZIP Archive\n"
11317#endif
11318;
11319static void usage(int showDetail){
11320  utf8_printf(stderr,
11321      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11322      "FILENAME is the name of an SQLite database. A new database is created\n"
11323      "if the file does not previously exist.\n", Argv0);
11324  if( showDetail ){
11325    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11326  }else{
11327    raw_printf(stderr, "Use the -help option for additional information\n");
11328  }
11329  exit(1);
11330}
11331
11332/*
11333** Internal check:  Verify that the SQLite is uninitialized.  Print a
11334** error message if it is initialized.
11335*/
11336static void verify_uninitialized(void){
11337  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11338    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11339                        " initialization.\n");
11340  }
11341}
11342
11343/*
11344** Initialize the state information in data
11345*/
11346static void main_init(ShellState *data) {
11347  memset(data, 0, sizeof(*data));
11348  data->normalMode = data->cMode = data->mode = MODE_List;
11349  data->autoExplain = 1;
11350  data->pAuxDb = &data->aAuxDb[0];
11351  memcpy(data->colSeparator,SEP_Column, 2);
11352  memcpy(data->rowSeparator,SEP_Row, 2);
11353  data->showHeader = 0;
11354  data->shellFlgs = SHFLG_Lookaside;
11355  verify_uninitialized();
11356  sqlite3_config(SQLITE_CONFIG_URI, 1);
11357  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11358  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11359  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11360  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11361}
11362
11363/*
11364** Output text to the console in a font that attracts extra attention.
11365*/
11366#ifdef _WIN32
11367static void printBold(const char *zText){
11368#if !SQLITE_OS_WINRT
11369  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11370  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11371  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11372  SetConsoleTextAttribute(out,
11373         FOREGROUND_RED|FOREGROUND_INTENSITY
11374  );
11375#endif
11376  printf("%s", zText);
11377#if !SQLITE_OS_WINRT
11378  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11379#endif
11380}
11381#else
11382static void printBold(const char *zText){
11383  printf("\033[1m%s\033[0m", zText);
11384}
11385#endif
11386
11387/*
11388** Get the argument to an --option.  Throw an error and die if no argument
11389** is available.
11390*/
11391static char *cmdline_option_value(int argc, char **argv, int i){
11392  if( i==argc ){
11393    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11394            argv[0], argv[argc-1]);
11395    exit(1);
11396  }
11397  return argv[i];
11398}
11399
11400#ifndef SQLITE_SHELL_IS_UTF8
11401#  if (defined(_WIN32) || defined(WIN32)) \
11402   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11403#    define SQLITE_SHELL_IS_UTF8          (0)
11404#  else
11405#    define SQLITE_SHELL_IS_UTF8          (1)
11406#  endif
11407#endif
11408
11409#ifdef SQLITE_SHELL_FIDDLE
11410#  define main fiddle_main
11411#endif
11412
11413#if SQLITE_SHELL_IS_UTF8
11414int SQLITE_CDECL main(int argc, char **argv){
11415#else
11416int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11417  char **argv;
11418#endif
11419#ifdef SQLITE_DEBUG
11420  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
11421#endif
11422  char *zErrMsg = 0;
11423#ifdef SQLITE_SHELL_FIDDLE
11424#  define data shellState
11425#else
11426  ShellState data;
11427#endif
11428  const char *zInitFile = 0;
11429  int i;
11430  int rc = 0;
11431  int warnInmemoryDb = 0;
11432  int readStdin = 1;
11433  int nCmd = 0;
11434  char **azCmd = 0;
11435  const char *zVfs = 0;           /* Value of -vfs command-line option */
11436#if !SQLITE_SHELL_IS_UTF8
11437  char **argvToFree = 0;
11438  int argcToFree = 0;
11439#endif
11440
11441  setBinaryMode(stdin, 0);
11442  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11443#ifdef SQLITE_SHELL_FIDDLE
11444  stdin_is_interactive = 0;
11445  stdout_is_console = 1;
11446#else
11447  stdin_is_interactive = isatty(0);
11448  stdout_is_console = isatty(1);
11449#endif
11450
11451#if !defined(_WIN32_WCE)
11452  if( getenv("SQLITE_DEBUG_BREAK") ){
11453    if( isatty(0) && isatty(2) ){
11454      fprintf(stderr,
11455          "attach debugger to process %d and press any key to continue.\n",
11456          GETPID());
11457      fgetc(stdin);
11458    }else{
11459#if defined(_WIN32) || defined(WIN32)
11460#if SQLITE_OS_WINRT
11461      __debugbreak();
11462#else
11463      DebugBreak();
11464#endif
11465#elif defined(SIGTRAP)
11466      raise(SIGTRAP);
11467#endif
11468    }
11469  }
11470#endif
11471
11472#if USE_SYSTEM_SQLITE+0!=1
11473  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11474    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11475            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11476    exit(1);
11477  }
11478#endif
11479  main_init(&data);
11480
11481  /* On Windows, we must translate command-line arguments into UTF-8.
11482  ** The SQLite memory allocator subsystem has to be enabled in order to
11483  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11484  ** subsequent sqlite3_config() calls will work.  So copy all results into
11485  ** memory that does not come from the SQLite memory allocator.
11486  */
11487#if !SQLITE_SHELL_IS_UTF8
11488  sqlite3_initialize();
11489  argvToFree = malloc(sizeof(argv[0])*argc*2);
11490  shell_check_oom(argvToFree);
11491  argcToFree = argc;
11492  argv = argvToFree + argc;
11493  for(i=0; i<argc; i++){
11494    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11495    int n;
11496    shell_check_oom(z);
11497    n = (int)strlen(z);
11498    argv[i] = malloc( n+1 );
11499    shell_check_oom(argv[i]);
11500    memcpy(argv[i], z, n+1);
11501    argvToFree[i] = argv[i];
11502    sqlite3_free(z);
11503  }
11504  sqlite3_shutdown();
11505#endif
11506
11507  assert( argc>=1 && argv && argv[0] );
11508  Argv0 = argv[0];
11509
11510  /* Make sure we have a valid signal handler early, before anything
11511  ** else is done.
11512  */
11513#ifdef SIGINT
11514  signal(SIGINT, interrupt_handler);
11515#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11516  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11517#endif
11518
11519#ifdef SQLITE_SHELL_DBNAME_PROC
11520  {
11521    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11522    ** of a C-function that will provide the name of the database file.  Use
11523    ** this compile-time option to embed this shell program in larger
11524    ** applications. */
11525    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11526    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11527    warnInmemoryDb = 0;
11528  }
11529#endif
11530
11531  /* Do an initial pass through the command-line argument to locate
11532  ** the name of the database file, the name of the initialization file,
11533  ** the size of the alternative malloc heap,
11534  ** and the first command to execute.
11535  */
11536  verify_uninitialized();
11537  for(i=1; i<argc; i++){
11538    char *z;
11539    z = argv[i];
11540    if( z[0]!='-' ){
11541      if( data.aAuxDb->zDbFilename==0 ){
11542        data.aAuxDb->zDbFilename = z;
11543      }else{
11544        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11545        ** mean that nothing is read from stdin */
11546        readStdin = 0;
11547        nCmd++;
11548        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11549        shell_check_oom(azCmd);
11550        azCmd[nCmd-1] = z;
11551      }
11552    }
11553    if( z[1]=='-' ) z++;
11554    if( strcmp(z,"-separator")==0
11555     || strcmp(z,"-nullvalue")==0
11556     || strcmp(z,"-newline")==0
11557     || strcmp(z,"-cmd")==0
11558    ){
11559      (void)cmdline_option_value(argc, argv, ++i);
11560    }else if( strcmp(z,"-init")==0 ){
11561      zInitFile = cmdline_option_value(argc, argv, ++i);
11562    }else if( strcmp(z,"-batch")==0 ){
11563      /* Need to check for batch mode here to so we can avoid printing
11564      ** informational messages (like from process_sqliterc) before
11565      ** we do the actual processing of arguments later in a second pass.
11566      */
11567      stdin_is_interactive = 0;
11568    }else if( strcmp(z,"-heap")==0 ){
11569#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11570      const char *zSize;
11571      sqlite3_int64 szHeap;
11572
11573      zSize = cmdline_option_value(argc, argv, ++i);
11574      szHeap = integerValue(zSize);
11575      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11576      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11577#else
11578      (void)cmdline_option_value(argc, argv, ++i);
11579#endif
11580    }else if( strcmp(z,"-pagecache")==0 ){
11581      sqlite3_int64 n, sz;
11582      sz = integerValue(cmdline_option_value(argc,argv,++i));
11583      if( sz>70000 ) sz = 70000;
11584      if( sz<0 ) sz = 0;
11585      n = integerValue(cmdline_option_value(argc,argv,++i));
11586      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11587        n = 0xffffffffffffLL/sz;
11588      }
11589      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11590                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11591      data.shellFlgs |= SHFLG_Pagecache;
11592    }else if( strcmp(z,"-lookaside")==0 ){
11593      int n, sz;
11594      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11595      if( sz<0 ) sz = 0;
11596      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11597      if( n<0 ) n = 0;
11598      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11599      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11600    }else if( strcmp(z,"-threadsafe")==0 ){
11601      int n;
11602      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11603      switch( n ){
11604         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11605         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11606         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11607      }
11608#ifdef SQLITE_ENABLE_VFSTRACE
11609    }else if( strcmp(z,"-vfstrace")==0 ){
11610      extern int vfstrace_register(
11611         const char *zTraceName,
11612         const char *zOldVfsName,
11613         int (*xOut)(const char*,void*),
11614         void *pOutArg,
11615         int makeDefault
11616      );
11617      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11618#endif
11619#ifdef SQLITE_ENABLE_MULTIPLEX
11620    }else if( strcmp(z,"-multiplex")==0 ){
11621      extern int sqlite3_multiple_initialize(const char*,int);
11622      sqlite3_multiplex_initialize(0, 1);
11623#endif
11624    }else if( strcmp(z,"-mmap")==0 ){
11625      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11626      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11627#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11628    }else if( strcmp(z,"-sorterref")==0 ){
11629      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11630      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11631#endif
11632    }else if( strcmp(z,"-vfs")==0 ){
11633      zVfs = cmdline_option_value(argc, argv, ++i);
11634#ifdef SQLITE_HAVE_ZLIB
11635    }else if( strcmp(z,"-zip")==0 ){
11636      data.openMode = SHELL_OPEN_ZIPFILE;
11637#endif
11638    }else if( strcmp(z,"-append")==0 ){
11639      data.openMode = SHELL_OPEN_APPENDVFS;
11640#ifndef SQLITE_OMIT_DESERIALIZE
11641    }else if( strcmp(z,"-deserialize")==0 ){
11642      data.openMode = SHELL_OPEN_DESERIALIZE;
11643    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11644      data.szMax = integerValue(argv[++i]);
11645#endif
11646    }else if( strcmp(z,"-readonly")==0 ){
11647      data.openMode = SHELL_OPEN_READONLY;
11648    }else if( strcmp(z,"-nofollow")==0 ){
11649      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11650#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11651    }else if( strncmp(z, "-A",2)==0 ){
11652      /* All remaining command-line arguments are passed to the ".archive"
11653      ** command, so ignore them */
11654      break;
11655#endif
11656    }else if( strcmp(z, "-memtrace")==0 ){
11657      sqlite3MemTraceActivate(stderr);
11658    }else if( strcmp(z,"-bail")==0 ){
11659      bail_on_error = 1;
11660    }else if( strcmp(z,"-nonce")==0 ){
11661      free(data.zNonce);
11662      data.zNonce = strdup(argv[++i]);
11663    }else if( strcmp(z,"-safe")==0 ){
11664      /* no-op - catch this on the second pass */
11665    }
11666  }
11667  verify_uninitialized();
11668
11669
11670#ifdef SQLITE_SHELL_INIT_PROC
11671  {
11672    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11673    ** of a C-function that will perform initialization actions on SQLite that
11674    ** occur just before or after sqlite3_initialize(). Use this compile-time
11675    ** option to embed this shell program in larger applications. */
11676    extern void SQLITE_SHELL_INIT_PROC(void);
11677    SQLITE_SHELL_INIT_PROC();
11678  }
11679#else
11680  /* All the sqlite3_config() calls have now been made. So it is safe
11681  ** to call sqlite3_initialize() and process any command line -vfs option. */
11682  sqlite3_initialize();
11683#endif
11684
11685  if( zVfs ){
11686    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11687    if( pVfs ){
11688      sqlite3_vfs_register(pVfs, 1);
11689    }else{
11690      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11691      exit(1);
11692    }
11693  }
11694
11695  if( data.pAuxDb->zDbFilename==0 ){
11696#ifndef SQLITE_OMIT_MEMORYDB
11697    data.pAuxDb->zDbFilename = ":memory:";
11698    warnInmemoryDb = argc==1;
11699#else
11700    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11701    return 1;
11702#endif
11703  }
11704  data.out = stdout;
11705#ifndef SQLITE_SHELL_FIDDLE
11706  sqlite3_appendvfs_init(0,0,0);
11707#endif
11708
11709  /* Go ahead and open the database file if it already exists.  If the
11710  ** file does not exist, delay opening it.  This prevents empty database
11711  ** files from being created if a user mistypes the database name argument
11712  ** to the sqlite command-line tool.
11713  */
11714  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11715    open_db(&data, 0);
11716  }
11717
11718  /* Process the initialization file if there is one.  If no -init option
11719  ** is given on the command line, look for a file named ~/.sqliterc and
11720  ** try to process it.
11721  */
11722  process_sqliterc(&data,zInitFile);
11723
11724  /* Make a second pass through the command-line argument and set
11725  ** options.  This second pass is delayed until after the initialization
11726  ** file is processed so that the command-line arguments will override
11727  ** settings in the initialization file.
11728  */
11729  for(i=1; i<argc; i++){
11730    char *z = argv[i];
11731    if( z[0]!='-' ) continue;
11732    if( z[1]=='-' ){ z++; }
11733    if( strcmp(z,"-init")==0 ){
11734      i++;
11735    }else if( strcmp(z,"-html")==0 ){
11736      data.mode = MODE_Html;
11737    }else if( strcmp(z,"-list")==0 ){
11738      data.mode = MODE_List;
11739    }else if( strcmp(z,"-quote")==0 ){
11740      data.mode = MODE_Quote;
11741      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11742      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11743    }else if( strcmp(z,"-line")==0 ){
11744      data.mode = MODE_Line;
11745    }else if( strcmp(z,"-column")==0 ){
11746      data.mode = MODE_Column;
11747    }else if( strcmp(z,"-json")==0 ){
11748      data.mode = MODE_Json;
11749    }else if( strcmp(z,"-markdown")==0 ){
11750      data.mode = MODE_Markdown;
11751    }else if( strcmp(z,"-table")==0 ){
11752      data.mode = MODE_Table;
11753    }else if( strcmp(z,"-box")==0 ){
11754      data.mode = MODE_Box;
11755    }else if( strcmp(z,"-csv")==0 ){
11756      data.mode = MODE_Csv;
11757      memcpy(data.colSeparator,",",2);
11758#ifdef SQLITE_HAVE_ZLIB
11759    }else if( strcmp(z,"-zip")==0 ){
11760      data.openMode = SHELL_OPEN_ZIPFILE;
11761#endif
11762    }else if( strcmp(z,"-append")==0 ){
11763      data.openMode = SHELL_OPEN_APPENDVFS;
11764#ifndef SQLITE_OMIT_DESERIALIZE
11765    }else if( strcmp(z,"-deserialize")==0 ){
11766      data.openMode = SHELL_OPEN_DESERIALIZE;
11767    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11768      data.szMax = integerValue(argv[++i]);
11769#endif
11770    }else if( strcmp(z,"-readonly")==0 ){
11771      data.openMode = SHELL_OPEN_READONLY;
11772    }else if( strcmp(z,"-nofollow")==0 ){
11773      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11774    }else if( strcmp(z,"-ascii")==0 ){
11775      data.mode = MODE_Ascii;
11776      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11777      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11778    }else if( strcmp(z,"-tabs")==0 ){
11779      data.mode = MODE_List;
11780      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11781      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11782    }else if( strcmp(z,"-separator")==0 ){
11783      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11784                       "%s",cmdline_option_value(argc,argv,++i));
11785    }else if( strcmp(z,"-newline")==0 ){
11786      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11787                       "%s",cmdline_option_value(argc,argv,++i));
11788    }else if( strcmp(z,"-nullvalue")==0 ){
11789      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11790                       "%s",cmdline_option_value(argc,argv,++i));
11791    }else if( strcmp(z,"-header")==0 ){
11792      data.showHeader = 1;
11793      ShellSetFlag(&data, SHFLG_HeaderSet);
11794     }else if( strcmp(z,"-noheader")==0 ){
11795      data.showHeader = 0;
11796      ShellSetFlag(&data, SHFLG_HeaderSet);
11797    }else if( strcmp(z,"-echo")==0 ){
11798      ShellSetFlag(&data, SHFLG_Echo);
11799    }else if( strcmp(z,"-eqp")==0 ){
11800      data.autoEQP = AUTOEQP_on;
11801    }else if( strcmp(z,"-eqpfull")==0 ){
11802      data.autoEQP = AUTOEQP_full;
11803    }else if( strcmp(z,"-stats")==0 ){
11804      data.statsOn = 1;
11805    }else if( strcmp(z,"-scanstats")==0 ){
11806      data.scanstatsOn = 1;
11807    }else if( strcmp(z,"-backslash")==0 ){
11808      /* Undocumented command-line option: -backslash
11809      ** Causes C-style backslash escapes to be evaluated in SQL statements
11810      ** prior to sending the SQL into SQLite.  Useful for injecting
11811      ** crazy bytes in the middle of SQL statements for testing and debugging.
11812      */
11813      ShellSetFlag(&data, SHFLG_Backslash);
11814    }else if( strcmp(z,"-bail")==0 ){
11815      /* No-op.  The bail_on_error flag should already be set. */
11816    }else if( strcmp(z,"-version")==0 ){
11817      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11818      return 0;
11819    }else if( strcmp(z,"-interactive")==0 ){
11820      stdin_is_interactive = 1;
11821    }else if( strcmp(z,"-batch")==0 ){
11822      stdin_is_interactive = 0;
11823    }else if( strcmp(z,"-heap")==0 ){
11824      i++;
11825    }else if( strcmp(z,"-pagecache")==0 ){
11826      i+=2;
11827    }else if( strcmp(z,"-lookaside")==0 ){
11828      i+=2;
11829    }else if( strcmp(z,"-threadsafe")==0 ){
11830      i+=2;
11831    }else if( strcmp(z,"-nonce")==0 ){
11832      i += 2;
11833    }else if( strcmp(z,"-mmap")==0 ){
11834      i++;
11835    }else if( strcmp(z,"-memtrace")==0 ){
11836      i++;
11837#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11838    }else if( strcmp(z,"-sorterref")==0 ){
11839      i++;
11840#endif
11841    }else if( strcmp(z,"-vfs")==0 ){
11842      i++;
11843#ifdef SQLITE_ENABLE_VFSTRACE
11844    }else if( strcmp(z,"-vfstrace")==0 ){
11845      i++;
11846#endif
11847#ifdef SQLITE_ENABLE_MULTIPLEX
11848    }else if( strcmp(z,"-multiplex")==0 ){
11849      i++;
11850#endif
11851    }else if( strcmp(z,"-help")==0 ){
11852      usage(1);
11853    }else if( strcmp(z,"-cmd")==0 ){
11854      /* Run commands that follow -cmd first and separately from commands
11855      ** that simply appear on the command-line.  This seems goofy.  It would
11856      ** be better if all commands ran in the order that they appear.  But
11857      ** we retain the goofy behavior for historical compatibility. */
11858      if( i==argc-1 ) break;
11859      z = cmdline_option_value(argc,argv,++i);
11860      if( z[0]=='.' ){
11861        rc = do_meta_command(z, &data);
11862        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11863      }else{
11864        open_db(&data, 0);
11865        rc = shell_exec(&data, z, &zErrMsg);
11866        if( zErrMsg!=0 ){
11867          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11868          if( bail_on_error ) return rc!=0 ? rc : 1;
11869        }else if( rc!=0 ){
11870          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11871          if( bail_on_error ) return rc;
11872        }
11873      }
11874#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11875    }else if( strncmp(z, "-A", 2)==0 ){
11876      if( nCmd>0 ){
11877        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11878                            " with \"%s\"\n", z);
11879        return 1;
11880      }
11881      open_db(&data, OPEN_DB_ZIPFILE);
11882      if( z[2] ){
11883        argv[i] = &z[2];
11884        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11885      }else{
11886        arDotCommand(&data, 1, argv+i, argc-i);
11887      }
11888      readStdin = 0;
11889      break;
11890#endif
11891    }else if( strcmp(z,"-safe")==0 ){
11892      data.bSafeMode = data.bSafeModePersist = 1;
11893    }else{
11894      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11895      raw_printf(stderr,"Use -help for a list of options.\n");
11896      return 1;
11897    }
11898    data.cMode = data.mode;
11899  }
11900
11901  if( !readStdin ){
11902    /* Run all arguments that do not begin with '-' as if they were separate
11903    ** command-line inputs, except for the argToSkip argument which contains
11904    ** the database filename.
11905    */
11906    for(i=0; i<nCmd; i++){
11907      if( azCmd[i][0]=='.' ){
11908        rc = do_meta_command(azCmd[i], &data);
11909        if( rc ){
11910          free(azCmd);
11911          return rc==2 ? 0 : rc;
11912        }
11913      }else{
11914        open_db(&data, 0);
11915        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11916        if( zErrMsg || rc ){
11917          if( zErrMsg!=0 ){
11918            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11919          }else{
11920            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11921          }
11922          sqlite3_free(zErrMsg);
11923          free(azCmd);
11924          return rc!=0 ? rc : 1;
11925        }
11926      }
11927    }
11928  }else{
11929    /* Run commands received from standard input
11930    */
11931    if( stdin_is_interactive ){
11932      char *zHome;
11933      char *zHistory;
11934      int nHistory;
11935      printf(
11936        "SQLite version %s %.19s\n" /*extra-version-info*/
11937        "Enter \".help\" for usage hints.\n",
11938        sqlite3_libversion(), sqlite3_sourceid()
11939      );
11940      if( warnInmemoryDb ){
11941        printf("Connected to a ");
11942        printBold("transient in-memory database");
11943        printf(".\nUse \".open FILENAME\" to reopen on a "
11944               "persistent database.\n");
11945      }
11946      zHistory = getenv("SQLITE_HISTORY");
11947      if( zHistory ){
11948        zHistory = strdup(zHistory);
11949      }else if( (zHome = find_home_dir(0))!=0 ){
11950        nHistory = strlen30(zHome) + 20;
11951        if( (zHistory = malloc(nHistory))!=0 ){
11952          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11953        }
11954      }
11955      if( zHistory ){ shell_read_history(zHistory); }
11956#if HAVE_READLINE || HAVE_EDITLINE
11957      rl_attempted_completion_function = readline_completion;
11958#elif HAVE_LINENOISE
11959      linenoiseSetCompletionCallback(linenoise_completion);
11960#endif
11961      data.in = 0;
11962      rc = process_input(&data);
11963      if( zHistory ){
11964        shell_stifle_history(2000);
11965        shell_write_history(zHistory);
11966        free(zHistory);
11967      }
11968    }else{
11969      data.in = stdin;
11970      rc = process_input(&data);
11971    }
11972  }
11973#ifndef SQLITE_SHELL_FIDDLE
11974  /* In WASM mode we have to leave the db state in place so that
11975  ** client code can "push" SQL into it after this call returns. */
11976  free(azCmd);
11977  set_table_name(&data, 0);
11978  if( data.db ){
11979    session_close_all(&data, -1);
11980    close_db(data.db);
11981  }
11982  for(i=0; i<ArraySize(data.aAuxDb); i++){
11983    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
11984    if( data.aAuxDb[i].db ){
11985      session_close_all(&data, i);
11986      close_db(data.aAuxDb[i].db);
11987    }
11988  }
11989  find_home_dir(1);
11990  output_reset(&data);
11991  data.doXdgOpen = 0;
11992  clearTempFile(&data);
11993#if !SQLITE_SHELL_IS_UTF8
11994  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11995  free(argvToFree);
11996#endif
11997  free(data.colWidth);
11998  free(data.zNonce);
11999  /* Clear the global data structure so that valgrind will detect memory
12000  ** leaks */
12001  memset(&data, 0, sizeof(data));
12002#ifdef SQLITE_DEBUG
12003  if( sqlite3_memory_used()>mem_main_enter ){
12004    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12005                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12006  }
12007#endif
12008#endif /* !SQLITE_SHELL_FIDDLE */
12009  return rc;
12010}
12011
12012
12013#ifdef SQLITE_SHELL_FIDDLE
12014/* Only for emcc experimentation purposes. */
12015int fiddle_experiment(int a,int b){
12016   return a + b;
12017}
12018
12019/* Only for emcc experimentation purposes.
12020
12021  Define this function in JS using:
12022
12023  emcc ... --js-library somefile.js
12024
12025  containing:
12026
12027mergeInto(LibraryManager.library, {
12028    my_foo: function(){
12029        console.debug("my_foo()",arguments);
12030    }
12031});
12032*/
12033/*extern void my_foo(sqlite3 *);*/
12034/* Only for emcc experimentation purposes. */
12035sqlite3 * fiddle_the_db(){
12036    printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12037    /*my_foo(globalDb);*/
12038    return globalDb;
12039}
12040/* Only for emcc experimentation purposes. */
12041sqlite3 * fiddle_db_arg(sqlite3 *arg){
12042    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12043    return arg;
12044}
12045
12046/*
12047** Intended to be called via a SharedWorker() while a separate
12048** SharedWorker() (which manages the wasm module) is performing work
12049** which should be interrupted. Unfortunately, SharedWorker is not
12050** portable enough to make real use of.
12051*/
12052void fiddle_interrupt(void){
12053  if(globalDb) sqlite3_interrupt(globalDb);
12054}
12055
12056/*
12057** Returns the filename of the given db name, assuming "main" if
12058** zDbName is NULL. Returns NULL if globalDb is not opened.
12059*/
12060const char * fiddle_db_filename(const char * zDbName){
12061    return globalDb
12062      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12063      : NULL;
12064}
12065
12066/*
12067** Closes, unlinks, and reopens the db using its current filename (or
12068** the default if the db is currently closed). It is assumed, for
12069** purposes of the fiddle build, that the file is in a transient
12070** virtual filesystem within the browser.
12071*/
12072void fiddle_reset_db(void){
12073  char *zFilename = 0;
12074  if(0==globalDb){
12075    shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12076  }else{
12077    zFilename =
12078      sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12079    shell_check_oom(zFilename);
12080    close_db(globalDb);
12081    shellDeleteFile(zFilename);
12082    shellState.db = 0;
12083    shellState.pAuxDb->zDbFilename = zFilename;
12084  }
12085  open_db(&shellState, 0);
12086  sqlite3_free(zFilename);
12087}
12088
12089/*
12090** Trivial exportable function for emscripten. Needs to be exported using:
12091**
12092** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12093**
12094** (Note the underscore before the function name.) It processes zSql
12095** as if it were input to the sqlite3 shell and redirects all output
12096** to the wasm binding.
12097*/
12098void fiddle_exec(const char * zSql){
12099  static int once = 0;
12100  int rc = 0;
12101  if(!once){
12102    /* Simulate an argv array for main() */
12103    static char * argv[] = {"fiddle",
12104                            "-bail",
12105                            "-safe"};
12106    rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12107    once = rc ? -1 : 1;
12108    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12109    printf(
12110        "SQLite version %s %.19s\n" /*extra-version-info*/,
12111        sqlite3_libversion(), sqlite3_sourceid()
12112    );
12113    puts("WASM shell");
12114    puts("Enter \".help\" for usage hints.");
12115    if(once>0){
12116      fiddle_reset_db();
12117    }
12118    if(shellState.db){
12119      printf("Connected to %s.\n", fiddle_db_filename(NULL));
12120    }else{
12121      fprintf(stderr,"ERROR initializing db!\n");
12122      return;
12123    }
12124  }
12125  if(once<0){
12126    puts("DB init failed. Not executing SQL.");
12127  }else if(zSql && *zSql){
12128    shellState.wasm.zInput = zSql;
12129    shellState.wasm.zPos = zSql;
12130    process_input(&shellState);
12131    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12132  }
12133}
12134#endif /* SQLITE_SHELL_FIDDLE */
12135