Imported Upstream version 3.18.0
[platform/upstream/sqlite.git] / shell.c
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 ** If requested, include the SQLite compiler options file for MSVC.
22 */
23 #if defined(INCLUDE_MSVC_H)
24 #include "msvc.h"
25 #endif
26
27 /*
28 ** No support for loadable extensions in VxWorks.
29 */
30 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
31 # define SQLITE_OMIT_LOAD_EXTENSION 1
32 #endif
33
34 /*
35 ** Enable large-file support for fopen() and friends on unix.
36 */
37 #ifndef SQLITE_DISABLE_LFS
38 # define _LARGE_FILE       1
39 # ifndef _FILE_OFFSET_BITS
40 #   define _FILE_OFFSET_BITS 64
41 # endif
42 # define _LARGEFILE_SOURCE 1
43 #endif
44
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdio.h>
48 #include <assert.h>
49 #include "sqlite3.h"
50 #if SQLITE_USER_AUTHENTICATION
51 # include "sqlite3userauth.h"
52 #endif
53 #include <ctype.h>
54 #include <stdarg.h>
55
56 #if !defined(_WIN32) && !defined(WIN32)
57 # include <signal.h>
58 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
59 #  include <pwd.h>
60 # endif
61 # include <unistd.h>
62 # include <sys/types.h>
63 #endif
64
65 #if HAVE_READLINE
66 # include <readline/readline.h>
67 # include <readline/history.h>
68 #endif
69
70 #if HAVE_EDITLINE
71 # include <editline/readline.h>
72 #endif
73
74 #if HAVE_EDITLINE || HAVE_READLINE
75
76 # define shell_add_history(X) add_history(X)
77 # define shell_read_history(X) read_history(X)
78 # define shell_write_history(X) write_history(X)
79 # define shell_stifle_history(X) stifle_history(X)
80 # define shell_readline(X) readline(X)
81
82 #elif HAVE_LINENOISE
83
84 # include "linenoise.h"
85 # define shell_add_history(X) linenoiseHistoryAdd(X)
86 # define shell_read_history(X) linenoiseHistoryLoad(X)
87 # define shell_write_history(X) linenoiseHistorySave(X)
88 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89 # define shell_readline(X) linenoise(X)
90
91 #else
92
93 # define shell_read_history(X)
94 # define shell_write_history(X)
95 # define shell_stifle_history(X)
96
97 # define SHELL_USE_LOCAL_GETLINE 1
98 #endif
99
100
101 #if defined(_WIN32) || defined(WIN32)
102 # include <io.h>
103 # include <fcntl.h>
104 # define isatty(h) _isatty(h)
105 # ifndef access
106 #  define access(f,m) _access((f),(m))
107 # endif
108 # undef popen
109 # define popen _popen
110 # undef pclose
111 # define pclose _pclose
112 #else
113  /* Make sure isatty() has a prototype. */
114  extern int isatty(int);
115
116 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
117   /* popen and pclose are not C89 functions and so are
118   ** sometimes omitted from the <stdio.h> header */
119    extern FILE *popen(const char*,const char*);
120    extern int pclose(FILE*);
121 # else
122 #  define SQLITE_OMIT_POPEN 1
123 # endif
124 #endif
125
126 #if defined(_WIN32_WCE)
127 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128  * thus we always assume that we have a console. That can be
129  * overridden with the -batch command line option.
130  */
131 #define isatty(x) 1
132 #endif
133
134 /* ctype macros that work with signed characters */
135 #define IsSpace(X)  isspace((unsigned char)X)
136 #define IsDigit(X)  isdigit((unsigned char)X)
137 #define ToLower(X)  (char)tolower((unsigned char)X)
138
139 #if defined(_WIN32) || defined(WIN32)
140 #include <windows.h>
141
142 /* string conversion routines only needed on Win32 */
143 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
144 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
146 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
147 #endif
148
149 /* On Windows, we normally run with output mode of TEXT so that \n characters
150 ** are automatically translated into \r\n.  However, this behavior needs
151 ** to be disabled in some cases (ex: when generating CSV output and when
152 ** rendering quoted strings that contain \n characters).  The following
153 ** routines take care of that.
154 */
155 #if defined(_WIN32) || defined(WIN32)
156 static void setBinaryMode(FILE *file, int isOutput){
157   if( isOutput ) fflush(file);
158   _setmode(_fileno(file), _O_BINARY);
159 }
160 static void setTextMode(FILE *file, int isOutput){
161   if( isOutput ) fflush(file);
162   _setmode(_fileno(file), _O_TEXT);
163 }
164 #else
165 # define setBinaryMode(X,Y)
166 # define setTextMode(X,Y)
167 #endif
168
169
170 /* True if the timer is enabled */
171 static int enableTimer = 0;
172
173 /* Return the current wall-clock time */
174 static sqlite3_int64 timeOfDay(void){
175   static sqlite3_vfs *clockVfs = 0;
176   sqlite3_int64 t;
177   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
178   if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
179     clockVfs->xCurrentTimeInt64(clockVfs, &t);
180   }else{
181     double r;
182     clockVfs->xCurrentTime(clockVfs, &r);
183     t = (sqlite3_int64)(r*86400000.0);
184   }
185   return t;
186 }
187
188 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
189 #include <sys/time.h>
190 #include <sys/resource.h>
191
192 /* VxWorks does not support getrusage() as far as we can determine */
193 #if defined(_WRS_KERNEL) || defined(__RTP__)
194 struct rusage {
195   struct timeval ru_utime; /* user CPU time used */
196   struct timeval ru_stime; /* system CPU time used */
197 };
198 #define getrusage(A,B) memset(B,0,sizeof(*B))
199 #endif
200
201 /* Saved resource information for the beginning of an operation */
202 static struct rusage sBegin;  /* CPU time at start */
203 static sqlite3_int64 iBegin;  /* Wall-clock time at start */
204
205 /*
206 ** Begin timing an operation
207 */
208 static void beginTimer(void){
209   if( enableTimer ){
210     getrusage(RUSAGE_SELF, &sBegin);
211     iBegin = timeOfDay();
212   }
213 }
214
215 /* Return the difference of two time_structs in seconds */
216 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
217   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
218          (double)(pEnd->tv_sec - pStart->tv_sec);
219 }
220
221 /*
222 ** Print the timing results.
223 */
224 static void endTimer(void){
225   if( enableTimer ){
226     sqlite3_int64 iEnd = timeOfDay();
227     struct rusage sEnd;
228     getrusage(RUSAGE_SELF, &sEnd);
229     printf("Run Time: real %.3f user %f sys %f\n",
230        (iEnd - iBegin)*0.001,
231        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
232        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
233   }
234 }
235
236 #define BEGIN_TIMER beginTimer()
237 #define END_TIMER endTimer()
238 #define HAS_TIMER 1
239
240 #elif (defined(_WIN32) || defined(WIN32))
241
242 /* Saved resource information for the beginning of an operation */
243 static HANDLE hProcess;
244 static FILETIME ftKernelBegin;
245 static FILETIME ftUserBegin;
246 static sqlite3_int64 ftWallBegin;
247 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
248                                     LPFILETIME, LPFILETIME);
249 static GETPROCTIMES getProcessTimesAddr = NULL;
250
251 /*
252 ** Check to see if we have timer support.  Return 1 if necessary
253 ** support found (or found previously).
254 */
255 static int hasTimer(void){
256   if( getProcessTimesAddr ){
257     return 1;
258   } else {
259     /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260     ** versions. See if the version we are running on has it, and if it
261     ** does, save off a pointer to it and the current process handle.
262     */
263     hProcess = GetCurrentProcess();
264     if( hProcess ){
265       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
266       if( NULL != hinstLib ){
267         getProcessTimesAddr =
268             (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
269         if( NULL != getProcessTimesAddr ){
270           return 1;
271         }
272         FreeLibrary(hinstLib);
273       }
274     }
275   }
276   return 0;
277 }
278
279 /*
280 ** Begin timing an operation
281 */
282 static void beginTimer(void){
283   if( enableTimer && getProcessTimesAddr ){
284     FILETIME ftCreation, ftExit;
285     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
286                         &ftKernelBegin,&ftUserBegin);
287     ftWallBegin = timeOfDay();
288   }
289 }
290
291 /* Return the difference of two FILETIME structs in seconds */
292 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
293   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
294   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
295   return (double) ((i64End - i64Start) / 10000000.0);
296 }
297
298 /*
299 ** Print the timing results.
300 */
301 static void endTimer(void){
302   if( enableTimer && getProcessTimesAddr){
303     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
304     sqlite3_int64 ftWallEnd = timeOfDay();
305     getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
306     printf("Run Time: real %.3f user %f sys %f\n",
307        (ftWallEnd - ftWallBegin)*0.001,
308        timeDiff(&ftUserBegin, &ftUserEnd),
309        timeDiff(&ftKernelBegin, &ftKernelEnd));
310   }
311 }
312
313 #define BEGIN_TIMER beginTimer()
314 #define END_TIMER endTimer()
315 #define HAS_TIMER hasTimer()
316
317 #else
318 #define BEGIN_TIMER
319 #define END_TIMER
320 #define HAS_TIMER 0
321 #endif
322
323 /*
324 ** Used to prevent warnings about unused parameters
325 */
326 #define UNUSED_PARAMETER(x) (void)(x)
327
328 /*
329 ** If the following flag is set, then command execution stops
330 ** at an error if we are not interactive.
331 */
332 static int bail_on_error = 0;
333
334 /*
335 ** Threat stdin as an interactive input if the following variable
336 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
337 */
338 static int stdin_is_interactive = 1;
339
340 /*
341 ** On Windows systems we have to know if standard output is a console
342 ** in order to translate UTF-8 into MBCS.  The following variable is
343 ** true if translation is required.
344 */
345 static int stdout_is_console = 1;
346
347 /*
348 ** The following is the open SQLite database.  We make a pointer
349 ** to this database a static variable so that it can be accessed
350 ** by the SIGINT handler to interrupt database processing.
351 */
352 static sqlite3 *globalDb = 0;
353
354 /*
355 ** True if an interrupt (Control-C) has been received.
356 */
357 static volatile int seenInterrupt = 0;
358
359 /*
360 ** This is the name of our program. It is set in main(), used
361 ** in a number of other places, mostly for error messages.
362 */
363 static char *Argv0;
364
365 /*
366 ** Prompt strings. Initialized in main. Settable with
367 **   .prompt main continue
368 */
369 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
370 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
371
372 /*
373 ** Render output like fprintf().  Except, if the output is going to the
374 ** console and if this is running on a Windows machine, translate the
375 ** output from UTF-8 into MBCS.
376 */
377 #if defined(_WIN32) || defined(WIN32)
378 void utf8_printf(FILE *out, const char *zFormat, ...){
379   va_list ap;
380   va_start(ap, zFormat);
381   if( stdout_is_console && (out==stdout || out==stderr) ){
382     char *z1 = sqlite3_vmprintf(zFormat, ap);
383     char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
384     sqlite3_free(z1);
385     fputs(z2, out);
386     sqlite3_free(z2);
387   }else{
388     vfprintf(out, zFormat, ap);
389   }
390   va_end(ap);
391 }
392 #elif !defined(utf8_printf)
393 # define utf8_printf fprintf
394 #endif
395
396 /*
397 ** Render output like fprintf().  This should not be used on anything that
398 ** includes string formatting (e.g. "%s").
399 */
400 #if !defined(raw_printf)
401 # define raw_printf fprintf
402 #endif
403
404 /*
405 ** Write I/O traces to the following stream.
406 */
407 #ifdef SQLITE_ENABLE_IOTRACE
408 static FILE *iotrace = 0;
409 #endif
410
411 /*
412 ** This routine works like printf in that its first argument is a
413 ** format string and subsequent arguments are values to be substituted
414 ** in place of % fields.  The result of formatting this string
415 ** is written to iotrace.
416 */
417 #ifdef SQLITE_ENABLE_IOTRACE
418 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
419   va_list ap;
420   char *z;
421   if( iotrace==0 ) return;
422   va_start(ap, zFormat);
423   z = sqlite3_vmprintf(zFormat, ap);
424   va_end(ap);
425   utf8_printf(iotrace, "%s", z);
426   sqlite3_free(z);
427 }
428 #endif
429
430
431 /*
432 ** Determines if a string is a number of not.
433 */
434 static int isNumber(const char *z, int *realnum){
435   if( *z=='-' || *z=='+' ) z++;
436   if( !IsDigit(*z) ){
437     return 0;
438   }
439   z++;
440   if( realnum ) *realnum = 0;
441   while( IsDigit(*z) ){ z++; }
442   if( *z=='.' ){
443     z++;
444     if( !IsDigit(*z) ) return 0;
445     while( IsDigit(*z) ){ z++; }
446     if( realnum ) *realnum = 1;
447   }
448   if( *z=='e' || *z=='E' ){
449     z++;
450     if( *z=='+' || *z=='-' ) z++;
451     if( !IsDigit(*z) ) return 0;
452     while( IsDigit(*z) ){ z++; }
453     if( realnum ) *realnum = 1;
454   }
455   return *z==0;
456 }
457
458 /*
459 ** Compute a string length that is limited to what can be stored in
460 ** lower 30 bits of a 32-bit signed integer.
461 */
462 static int strlen30(const char *z){
463   const char *z2 = z;
464   while( *z2 ){ z2++; }
465   return 0x3fffffff & (int)(z2 - z);
466 }
467
468 /*
469 ** This routine reads a line of text from FILE in, stores
470 ** the text in memory obtained from malloc() and returns a pointer
471 ** to the text.  NULL is returned at end of file, or if malloc()
472 ** fails.
473 **
474 ** If zLine is not NULL then it is a malloced buffer returned from
475 ** a previous call to this routine that may be reused.
476 */
477 static char *local_getline(char *zLine, FILE *in){
478   int nLine = zLine==0 ? 0 : 100;
479   int n = 0;
480
481   while( 1 ){
482     if( n+100>nLine ){
483       nLine = nLine*2 + 100;
484       zLine = realloc(zLine, nLine);
485       if( zLine==0 ) return 0;
486     }
487     if( fgets(&zLine[n], nLine - n, in)==0 ){
488       if( n==0 ){
489         free(zLine);
490         return 0;
491       }
492       zLine[n] = 0;
493       break;
494     }
495     while( zLine[n] ) n++;
496     if( n>0 && zLine[n-1]=='\n' ){
497       n--;
498       if( n>0 && zLine[n-1]=='\r' ) n--;
499       zLine[n] = 0;
500       break;
501     }
502   }
503 #if defined(_WIN32) || defined(WIN32)
504   /* For interactive input on Windows systems, translate the
505   ** multi-byte characterset characters into UTF-8. */
506   if( stdin_is_interactive && in==stdin ){
507     char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
508     if( zTrans ){
509       int nTrans = strlen30(zTrans)+1;
510       if( nTrans>nLine ){
511         zLine = realloc(zLine, nTrans);
512         if( zLine==0 ){
513           sqlite3_free(zTrans);
514           return 0;
515         }
516       }
517       memcpy(zLine, zTrans, nTrans);
518       sqlite3_free(zTrans);
519     }
520   }
521 #endif /* defined(_WIN32) || defined(WIN32) */
522   return zLine;
523 }
524
525 /*
526 ** Retrieve a single line of input text.
527 **
528 ** If in==0 then read from standard input and prompt before each line.
529 ** If isContinuation is true, then a continuation prompt is appropriate.
530 ** If isContinuation is zero, then the main prompt should be used.
531 **
532 ** If zPrior is not NULL then it is a buffer from a prior call to this
533 ** routine that can be reused.
534 **
535 ** The result is stored in space obtained from malloc() and must either
536 ** be freed by the caller or else passed back into this routine via the
537 ** zPrior argument for reuse.
538 */
539 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
540   char *zPrompt;
541   char *zResult;
542   if( in!=0 ){
543     zResult = local_getline(zPrior, in);
544   }else{
545     zPrompt = isContinuation ? continuePrompt : mainPrompt;
546 #if SHELL_USE_LOCAL_GETLINE
547     printf("%s", zPrompt);
548     fflush(stdout);
549     zResult = local_getline(zPrior, stdin);
550 #else
551     free(zPrior);
552     zResult = shell_readline(zPrompt);
553     if( zResult && *zResult ) shell_add_history(zResult);
554 #endif
555   }
556   return zResult;
557 }
558 /*
559 ** A variable length string to which one can append text.
560 */
561 typedef struct ShellText ShellText;
562 struct ShellText {
563   char *z;
564   int n;
565   int nAlloc;
566 };
567
568 /*
569 ** Initialize and destroy a ShellText object
570 */
571 static void initText(ShellText *p){
572   memset(p, 0, sizeof(*p));
573 }
574 static void freeText(ShellText *p){
575   free(p->z);
576   initText(p);
577 }
578
579 /* zIn is either a pointer to a NULL-terminated string in memory obtained
580 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
581 ** added to zIn, and the result returned in memory obtained from malloc().
582 ** zIn, if it was not NULL, is freed.
583 **
584 ** If the third argument, quote, is not '\0', then it is used as a
585 ** quote character for zAppend.
586 */
587 static void appendText(ShellText *p, char const *zAppend, char quote){
588   int len;
589   int i;
590   int nAppend = strlen30(zAppend);
591
592   len = nAppend+p->n+1;
593   if( quote ){
594     len += 2;
595     for(i=0; i<nAppend; i++){
596       if( zAppend[i]==quote ) len++;
597     }
598   }
599
600   if( p->n+len>=p->nAlloc ){
601     p->nAlloc = p->nAlloc*2 + len + 20;
602     p->z = realloc(p->z, p->nAlloc);
603     if( p->z==0 ){
604       memset(p, 0, sizeof(*p));
605       return;
606     }
607   }
608
609   if( quote ){
610     char *zCsr = p->z+p->n;
611     *zCsr++ = quote;
612     for(i=0; i<nAppend; i++){
613       *zCsr++ = zAppend[i];
614       if( zAppend[i]==quote ) *zCsr++ = quote;
615     }
616     *zCsr++ = quote;
617     p->n = (int)(zCsr - p->z);
618     *zCsr = '\0';
619   }else{
620     memcpy(p->z+p->n, zAppend, nAppend);
621     p->n += nAppend;
622     p->z[p->n] = '\0';
623   }
624 }
625
626 /*
627 ** Attempt to determine if identifier zName needs to be quoted, either
628 ** because it contains non-alphanumeric characters, or because it is an
629 ** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
630 ** that quoting is required.
631 **
632 ** Return '"' if quoting is required.  Return 0 if no quoting is required.
633 */
634 static char quoteChar(const char *zName){
635   /* All SQLite keywords, in alphabetical order */
636   static const char *azKeywords[] = {
637     "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
638     "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
639     "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
640     "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
641     "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
642     "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
643     "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
644     "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
645     "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
646     "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
647     "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
648     "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
649     "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
650     "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
651     "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
652     "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
653     "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
654     "WITH", "WITHOUT",
655   };
656   int i, lwr, upr, mid, c;
657   if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
658   for(i=0; zName[i]; i++){
659     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
660   }
661   lwr = 0;
662   upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
663   while( lwr<=upr ){
664     mid = (lwr+upr)/2;
665     c = sqlite3_stricmp(azKeywords[mid], zName);
666     if( c==0 ) return '"';
667     if( c<0 ){
668       lwr = mid+1;
669     }else{
670       upr = mid-1;
671     }
672   }
673   return 0;
674 }
675
676 /******************************************************************************
677 ** SHA3 hash implementation copied from ../ext/misc/shathree.c
678 */
679 typedef sqlite3_uint64 u64;
680 /*
681 ** Macros to determine whether the machine is big or little endian,
682 ** and whether or not that determination is run-time or compile-time.
683 **
684 ** For best performance, an attempt is made to guess at the byte-order
685 ** using C-preprocessor macros.  If that is unsuccessful, or if
686 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
687 ** at run-time.
688 */
689 #ifndef SHA3_BYTEORDER
690 # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
691      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
692      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
693      defined(__arm__)
694 #   define SHA3_BYTEORDER    1234
695 # elif defined(sparc)    || defined(__ppc__)
696 #   define SHA3_BYTEORDER    4321
697 # else
698 #   define SHA3_BYTEORDER 0
699 # endif
700 #endif
701
702
703 /*
704 ** State structure for a SHA3 hash in progress
705 */
706 typedef struct SHA3Context SHA3Context;
707 struct SHA3Context {
708   union {
709     u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
710     unsigned char x[1600];    /* ... or 1600 bytes */
711   } u;
712   unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
713   unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
714   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
715 };
716
717 /*
718 ** A single step of the Keccak mixing function for a 1600-bit state
719 */
720 static void KeccakF1600Step(SHA3Context *p){
721   int i;
722   u64 B0, B1, B2, B3, B4;
723   u64 C0, C1, C2, C3, C4;
724   u64 D0, D1, D2, D3, D4;
725   static const u64 RC[] = {
726     0x0000000000000001ULL,  0x0000000000008082ULL,
727     0x800000000000808aULL,  0x8000000080008000ULL,
728     0x000000000000808bULL,  0x0000000080000001ULL,
729     0x8000000080008081ULL,  0x8000000000008009ULL,
730     0x000000000000008aULL,  0x0000000000000088ULL,
731     0x0000000080008009ULL,  0x000000008000000aULL,
732     0x000000008000808bULL,  0x800000000000008bULL,
733     0x8000000000008089ULL,  0x8000000000008003ULL,
734     0x8000000000008002ULL,  0x8000000000000080ULL,
735     0x000000000000800aULL,  0x800000008000000aULL,
736     0x8000000080008081ULL,  0x8000000000008080ULL,
737     0x0000000080000001ULL,  0x8000000080008008ULL
738   };
739 # define A00 (p->u.s[0])
740 # define A01 (p->u.s[1])
741 # define A02 (p->u.s[2])
742 # define A03 (p->u.s[3])
743 # define A04 (p->u.s[4])
744 # define A10 (p->u.s[5])
745 # define A11 (p->u.s[6])
746 # define A12 (p->u.s[7])
747 # define A13 (p->u.s[8])
748 # define A14 (p->u.s[9])
749 # define A20 (p->u.s[10])
750 # define A21 (p->u.s[11])
751 # define A22 (p->u.s[12])
752 # define A23 (p->u.s[13])
753 # define A24 (p->u.s[14])
754 # define A30 (p->u.s[15])
755 # define A31 (p->u.s[16])
756 # define A32 (p->u.s[17])
757 # define A33 (p->u.s[18])
758 # define A34 (p->u.s[19])
759 # define A40 (p->u.s[20])
760 # define A41 (p->u.s[21])
761 # define A42 (p->u.s[22])
762 # define A43 (p->u.s[23])
763 # define A44 (p->u.s[24])
764 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
765
766   for(i=0; i<24; i+=4){
767     C0 = A00^A10^A20^A30^A40;
768     C1 = A01^A11^A21^A31^A41;
769     C2 = A02^A12^A22^A32^A42;
770     C3 = A03^A13^A23^A33^A43;
771     C4 = A04^A14^A24^A34^A44;
772     D0 = C4^ROL64(C1, 1);
773     D1 = C0^ROL64(C2, 1);
774     D2 = C1^ROL64(C3, 1);
775     D3 = C2^ROL64(C4, 1);
776     D4 = C3^ROL64(C0, 1);
777
778     B0 = (A00^D0);
779     B1 = ROL64((A11^D1), 44);
780     B2 = ROL64((A22^D2), 43);
781     B3 = ROL64((A33^D3), 21);
782     B4 = ROL64((A44^D4), 14);
783     A00 =   B0 ^((~B1)&  B2 );
784     A00 ^= RC[i];
785     A11 =   B1 ^((~B2)&  B3 );
786     A22 =   B2 ^((~B3)&  B4 );
787     A33 =   B3 ^((~B4)&  B0 );
788     A44 =   B4 ^((~B0)&  B1 );
789
790     B2 = ROL64((A20^D0), 3);
791     B3 = ROL64((A31^D1), 45);
792     B4 = ROL64((A42^D2), 61);
793     B0 = ROL64((A03^D3), 28);
794     B1 = ROL64((A14^D4), 20);
795     A20 =   B0 ^((~B1)&  B2 );
796     A31 =   B1 ^((~B2)&  B3 );
797     A42 =   B2 ^((~B3)&  B4 );
798     A03 =   B3 ^((~B4)&  B0 );
799     A14 =   B4 ^((~B0)&  B1 );
800
801     B4 = ROL64((A40^D0), 18);
802     B0 = ROL64((A01^D1), 1);
803     B1 = ROL64((A12^D2), 6);
804     B2 = ROL64((A23^D3), 25);
805     B3 = ROL64((A34^D4), 8);
806     A40 =   B0 ^((~B1)&  B2 );
807     A01 =   B1 ^((~B2)&  B3 );
808     A12 =   B2 ^((~B3)&  B4 );
809     A23 =   B3 ^((~B4)&  B0 );
810     A34 =   B4 ^((~B0)&  B1 );
811
812     B1 = ROL64((A10^D0), 36);
813     B2 = ROL64((A21^D1), 10);
814     B3 = ROL64((A32^D2), 15);
815     B4 = ROL64((A43^D3), 56);
816     B0 = ROL64((A04^D4), 27);
817     A10 =   B0 ^((~B1)&  B2 );
818     A21 =   B1 ^((~B2)&  B3 );
819     A32 =   B2 ^((~B3)&  B4 );
820     A43 =   B3 ^((~B4)&  B0 );
821     A04 =   B4 ^((~B0)&  B1 );
822
823     B3 = ROL64((A30^D0), 41);
824     B4 = ROL64((A41^D1), 2);
825     B0 = ROL64((A02^D2), 62);
826     B1 = ROL64((A13^D3), 55);
827     B2 = ROL64((A24^D4), 39);
828     A30 =   B0 ^((~B1)&  B2 );
829     A41 =   B1 ^((~B2)&  B3 );
830     A02 =   B2 ^((~B3)&  B4 );
831     A13 =   B3 ^((~B4)&  B0 );
832     A24 =   B4 ^((~B0)&  B1 );
833
834     C0 = A00^A20^A40^A10^A30;
835     C1 = A11^A31^A01^A21^A41;
836     C2 = A22^A42^A12^A32^A02;
837     C3 = A33^A03^A23^A43^A13;
838     C4 = A44^A14^A34^A04^A24;
839     D0 = C4^ROL64(C1, 1);
840     D1 = C0^ROL64(C2, 1);
841     D2 = C1^ROL64(C3, 1);
842     D3 = C2^ROL64(C4, 1);
843     D4 = C3^ROL64(C0, 1);
844
845     B0 = (A00^D0);
846     B1 = ROL64((A31^D1), 44);
847     B2 = ROL64((A12^D2), 43);
848     B3 = ROL64((A43^D3), 21);
849     B4 = ROL64((A24^D4), 14);
850     A00 =   B0 ^((~B1)&  B2 );
851     A00 ^= RC[i+1];
852     A31 =   B1 ^((~B2)&  B3 );
853     A12 =   B2 ^((~B3)&  B4 );
854     A43 =   B3 ^((~B4)&  B0 );
855     A24 =   B4 ^((~B0)&  B1 );
856
857     B2 = ROL64((A40^D0), 3);
858     B3 = ROL64((A21^D1), 45);
859     B4 = ROL64((A02^D2), 61);
860     B0 = ROL64((A33^D3), 28);
861     B1 = ROL64((A14^D4), 20);
862     A40 =   B0 ^((~B1)&  B2 );
863     A21 =   B1 ^((~B2)&  B3 );
864     A02 =   B2 ^((~B3)&  B4 );
865     A33 =   B3 ^((~B4)&  B0 );
866     A14 =   B4 ^((~B0)&  B1 );
867
868     B4 = ROL64((A30^D0), 18);
869     B0 = ROL64((A11^D1), 1);
870     B1 = ROL64((A42^D2), 6);
871     B2 = ROL64((A23^D3), 25);
872     B3 = ROL64((A04^D4), 8);
873     A30 =   B0 ^((~B1)&  B2 );
874     A11 =   B1 ^((~B2)&  B3 );
875     A42 =   B2 ^((~B3)&  B4 );
876     A23 =   B3 ^((~B4)&  B0 );
877     A04 =   B4 ^((~B0)&  B1 );
878
879     B1 = ROL64((A20^D0), 36);
880     B2 = ROL64((A01^D1), 10);
881     B3 = ROL64((A32^D2), 15);
882     B4 = ROL64((A13^D3), 56);
883     B0 = ROL64((A44^D4), 27);
884     A20 =   B0 ^((~B1)&  B2 );
885     A01 =   B1 ^((~B2)&  B3 );
886     A32 =   B2 ^((~B3)&  B4 );
887     A13 =   B3 ^((~B4)&  B0 );
888     A44 =   B4 ^((~B0)&  B1 );
889
890     B3 = ROL64((A10^D0), 41);
891     B4 = ROL64((A41^D1), 2);
892     B0 = ROL64((A22^D2), 62);
893     B1 = ROL64((A03^D3), 55);
894     B2 = ROL64((A34^D4), 39);
895     A10 =   B0 ^((~B1)&  B2 );
896     A41 =   B1 ^((~B2)&  B3 );
897     A22 =   B2 ^((~B3)&  B4 );
898     A03 =   B3 ^((~B4)&  B0 );
899     A34 =   B4 ^((~B0)&  B1 );
900
901     C0 = A00^A40^A30^A20^A10;
902     C1 = A31^A21^A11^A01^A41;
903     C2 = A12^A02^A42^A32^A22;
904     C3 = A43^A33^A23^A13^A03;
905     C4 = A24^A14^A04^A44^A34;
906     D0 = C4^ROL64(C1, 1);
907     D1 = C0^ROL64(C2, 1);
908     D2 = C1^ROL64(C3, 1);
909     D3 = C2^ROL64(C4, 1);
910     D4 = C3^ROL64(C0, 1);
911
912     B0 = (A00^D0);
913     B1 = ROL64((A21^D1), 44);
914     B2 = ROL64((A42^D2), 43);
915     B3 = ROL64((A13^D3), 21);
916     B4 = ROL64((A34^D4), 14);
917     A00 =   B0 ^((~B1)&  B2 );
918     A00 ^= RC[i+2];
919     A21 =   B1 ^((~B2)&  B3 );
920     A42 =   B2 ^((~B3)&  B4 );
921     A13 =   B3 ^((~B4)&  B0 );
922     A34 =   B4 ^((~B0)&  B1 );
923
924     B2 = ROL64((A30^D0), 3);
925     B3 = ROL64((A01^D1), 45);
926     B4 = ROL64((A22^D2), 61);
927     B0 = ROL64((A43^D3), 28);
928     B1 = ROL64((A14^D4), 20);
929     A30 =   B0 ^((~B1)&  B2 );
930     A01 =   B1 ^((~B2)&  B3 );
931     A22 =   B2 ^((~B3)&  B4 );
932     A43 =   B3 ^((~B4)&  B0 );
933     A14 =   B4 ^((~B0)&  B1 );
934
935     B4 = ROL64((A10^D0), 18);
936     B0 = ROL64((A31^D1), 1);
937     B1 = ROL64((A02^D2), 6);
938     B2 = ROL64((A23^D3), 25);
939     B3 = ROL64((A44^D4), 8);
940     A10 =   B0 ^((~B1)&  B2 );
941     A31 =   B1 ^((~B2)&  B3 );
942     A02 =   B2 ^((~B3)&  B4 );
943     A23 =   B3 ^((~B4)&  B0 );
944     A44 =   B4 ^((~B0)&  B1 );
945
946     B1 = ROL64((A40^D0), 36);
947     B2 = ROL64((A11^D1), 10);
948     B3 = ROL64((A32^D2), 15);
949     B4 = ROL64((A03^D3), 56);
950     B0 = ROL64((A24^D4), 27);
951     A40 =   B0 ^((~B1)&  B2 );
952     A11 =   B1 ^((~B2)&  B3 );
953     A32 =   B2 ^((~B3)&  B4 );
954     A03 =   B3 ^((~B4)&  B0 );
955     A24 =   B4 ^((~B0)&  B1 );
956
957     B3 = ROL64((A20^D0), 41);
958     B4 = ROL64((A41^D1), 2);
959     B0 = ROL64((A12^D2), 62);
960     B1 = ROL64((A33^D3), 55);
961     B2 = ROL64((A04^D4), 39);
962     A20 =   B0 ^((~B1)&  B2 );
963     A41 =   B1 ^((~B2)&  B3 );
964     A12 =   B2 ^((~B3)&  B4 );
965     A33 =   B3 ^((~B4)&  B0 );
966     A04 =   B4 ^((~B0)&  B1 );
967
968     C0 = A00^A30^A10^A40^A20;
969     C1 = A21^A01^A31^A11^A41;
970     C2 = A42^A22^A02^A32^A12;
971     C3 = A13^A43^A23^A03^A33;
972     C4 = A34^A14^A44^A24^A04;
973     D0 = C4^ROL64(C1, 1);
974     D1 = C0^ROL64(C2, 1);
975     D2 = C1^ROL64(C3, 1);
976     D3 = C2^ROL64(C4, 1);
977     D4 = C3^ROL64(C0, 1);
978
979     B0 = (A00^D0);
980     B1 = ROL64((A01^D1), 44);
981     B2 = ROL64((A02^D2), 43);
982     B3 = ROL64((A03^D3), 21);
983     B4 = ROL64((A04^D4), 14);
984     A00 =   B0 ^((~B1)&  B2 );
985     A00 ^= RC[i+3];
986     A01 =   B1 ^((~B2)&  B3 );
987     A02 =   B2 ^((~B3)&  B4 );
988     A03 =   B3 ^((~B4)&  B0 );
989     A04 =   B4 ^((~B0)&  B1 );
990
991     B2 = ROL64((A10^D0), 3);
992     B3 = ROL64((A11^D1), 45);
993     B4 = ROL64((A12^D2), 61);
994     B0 = ROL64((A13^D3), 28);
995     B1 = ROL64((A14^D4), 20);
996     A10 =   B0 ^((~B1)&  B2 );
997     A11 =   B1 ^((~B2)&  B3 );
998     A12 =   B2 ^((~B3)&  B4 );
999     A13 =   B3 ^((~B4)&  B0 );
1000     A14 =   B4 ^((~B0)&  B1 );
1001
1002     B4 = ROL64((A20^D0), 18);
1003     B0 = ROL64((A21^D1), 1);
1004     B1 = ROL64((A22^D2), 6);
1005     B2 = ROL64((A23^D3), 25);
1006     B3 = ROL64((A24^D4), 8);
1007     A20 =   B0 ^((~B1)&  B2 );
1008     A21 =   B1 ^((~B2)&  B3 );
1009     A22 =   B2 ^((~B3)&  B4 );
1010     A23 =   B3 ^((~B4)&  B0 );
1011     A24 =   B4 ^((~B0)&  B1 );
1012
1013     B1 = ROL64((A30^D0), 36);
1014     B2 = ROL64((A31^D1), 10);
1015     B3 = ROL64((A32^D2), 15);
1016     B4 = ROL64((A33^D3), 56);
1017     B0 = ROL64((A34^D4), 27);
1018     A30 =   B0 ^((~B1)&  B2 );
1019     A31 =   B1 ^((~B2)&  B3 );
1020     A32 =   B2 ^((~B3)&  B4 );
1021     A33 =   B3 ^((~B4)&  B0 );
1022     A34 =   B4 ^((~B0)&  B1 );
1023
1024     B3 = ROL64((A40^D0), 41);
1025     B4 = ROL64((A41^D1), 2);
1026     B0 = ROL64((A42^D2), 62);
1027     B1 = ROL64((A43^D3), 55);
1028     B2 = ROL64((A44^D4), 39);
1029     A40 =   B0 ^((~B1)&  B2 );
1030     A41 =   B1 ^((~B2)&  B3 );
1031     A42 =   B2 ^((~B3)&  B4 );
1032     A43 =   B3 ^((~B4)&  B0 );
1033     A44 =   B4 ^((~B0)&  B1 );
1034   }
1035 }
1036
1037 /*
1038 ** Initialize a new hash.  iSize determines the size of the hash
1039 ** in bits and should be one of 224, 256, 384, or 512.  Or iSize
1040 ** can be zero to use the default hash size of 256 bits.
1041 */
1042 static void SHA3Init(SHA3Context *p, int iSize){
1043   memset(p, 0, sizeof(*p));
1044   if( iSize>=128 && iSize<=512 ){
1045     p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1046   }else{
1047     p->nRate = (1600 - 2*256)/8;
1048   }
1049 #if SHA3_BYTEORDER==1234
1050   /* Known to be little-endian at compile-time. No-op */
1051 #elif SHA3_BYTEORDER==4321
1052   p->ixMask = 7;  /* Big-endian */
1053 #else
1054   {
1055     static unsigned int one = 1;
1056     if( 1==*(unsigned char*)&one ){
1057       /* Little endian.  No byte swapping. */
1058       p->ixMask = 0;
1059     }else{
1060       /* Big endian.  Byte swap. */
1061       p->ixMask = 7;
1062     }
1063   }
1064 #endif
1065 }
1066
1067 /*
1068 ** Make consecutive calls to the SHA3Update function to add new content
1069 ** to the hash
1070 */
1071 static void SHA3Update(
1072   SHA3Context *p,
1073   const unsigned char *aData,
1074   unsigned int nData
1075 ){
1076   unsigned int i = 0;
1077 #if SHA3_BYTEORDER==1234
1078   if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1079     for(; i+7<nData; i+=8){
1080       p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1081       p->nLoaded += 8;
1082       if( p->nLoaded>=p->nRate ){
1083         KeccakF1600Step(p);
1084         p->nLoaded = 0;
1085       }
1086     }
1087   }
1088 #endif
1089   for(; i<nData; i++){
1090 #if SHA3_BYTEORDER==1234
1091     p->u.x[p->nLoaded] ^= aData[i];
1092 #elif SHA3_BYTEORDER==4321
1093     p->u.x[p->nLoaded^0x07] ^= aData[i];
1094 #else
1095     p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1096 #endif
1097     p->nLoaded++;
1098     if( p->nLoaded==p->nRate ){
1099       KeccakF1600Step(p);
1100       p->nLoaded = 0;
1101     }
1102   }
1103 }
1104
1105 /*
1106 ** After all content has been added, invoke SHA3Final() to compute
1107 ** the final hash.  The function returns a pointer to the binary
1108 ** hash value.
1109 */
1110 static unsigned char *SHA3Final(SHA3Context *p){
1111   unsigned int i;
1112   if( p->nLoaded==p->nRate-1 ){
1113     const unsigned char c1 = 0x86;
1114     SHA3Update(p, &c1, 1);
1115   }else{
1116     const unsigned char c2 = 0x06;
1117     const unsigned char c3 = 0x80;
1118     SHA3Update(p, &c2, 1);
1119     p->nLoaded = p->nRate - 1;
1120     SHA3Update(p, &c3, 1);
1121   }
1122   for(i=0; i<p->nRate; i++){
1123     p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1124   }
1125   return &p->u.x[p->nRate];
1126 }
1127
1128 /*
1129 ** Implementation of the sha3(X,SIZE) function.
1130 **
1131 ** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
1132 ** size is 256.  If X is a BLOB, it is hashed as is.  
1133 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1134 ** and the string is hashed without the trailing 0x00 terminator.  The hash
1135 ** of a NULL value is NULL.
1136 */
1137 static void sha3Func(
1138   sqlite3_context *context,
1139   int argc,
1140   sqlite3_value **argv
1141 ){
1142   SHA3Context cx;
1143   int eType = sqlite3_value_type(argv[0]);
1144   int nByte = sqlite3_value_bytes(argv[0]);
1145   int iSize;
1146   if( argc==1 ){
1147     iSize = 256;
1148   }else{
1149     iSize = sqlite3_value_int(argv[1]);
1150     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1151       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1152                                     "384 512", -1);
1153       return;
1154     }
1155   }
1156   if( eType==SQLITE_NULL ) return;
1157   SHA3Init(&cx, iSize);
1158   if( eType==SQLITE_BLOB ){
1159     SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1160   }else{
1161     SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1162   }
1163   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1164 }
1165
1166 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1167 ** of 50 bytes and add it to the hash.
1168 */
1169 static void hash_step_vformat(
1170   SHA3Context *p,                 /* Add content to this context */
1171   const char *zFormat,
1172   ...
1173 ){
1174   va_list ap;
1175   int n;
1176   char zBuf[50];
1177   va_start(ap, zFormat);
1178   sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1179   va_end(ap);
1180   n = (int)strlen(zBuf);
1181   SHA3Update(p, (unsigned char*)zBuf, n);
1182 }
1183
1184 /*
1185 ** Implementation of the sha3_query(SQL,SIZE) function.
1186 **
1187 ** This function compiles and runs the SQL statement(s) given in the
1188 ** argument. The results are hashed using a SIZE-bit SHA3.  The default
1189 ** size is 256.
1190 **
1191 ** The format of the byte stream that is hashed is summarized as follows:
1192 **
1193 **       S<n>:<sql>
1194 **       R
1195 **       N
1196 **       I<int>
1197 **       F<ieee-float>
1198 **       B<size>:<bytes>
1199 **       T<size>:<text>
1200 **
1201 ** <sql> is the original SQL text for each statement run and <n> is
1202 ** the size of that text.  The SQL text is UTF-8.  A single R character
1203 ** occurs before the start of each row.  N means a NULL value.
1204 ** I mean an 8-byte little-endian integer <int>.  F is a floating point
1205 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1206 ** B means blobs of <size> bytes.  T means text rendered as <size>
1207 ** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
1208 ** text integers.
1209 **
1210 ** For each SQL statement in the X input, there is one S segment.  Each
1211 ** S segment is followed by zero or more R segments, one for each row in the
1212 ** result set.  After each R, there are one or more N, I, F, B, or T segments,
1213 ** one for each column in the result set.  Segments are concatentated directly
1214 ** with no delimiters of any kind.
1215 */
1216 static void sha3QueryFunc(
1217   sqlite3_context *context,
1218   int argc,
1219   sqlite3_value **argv
1220 ){
1221   sqlite3 *db = sqlite3_context_db_handle(context);
1222   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1223   sqlite3_stmt *pStmt = 0;
1224   int nCol;                   /* Number of columns in the result set */
1225   int i;                      /* Loop counter */
1226   int rc;
1227   int n;
1228   const char *z;
1229   SHA3Context cx;
1230   int iSize;
1231
1232   if( argc==1 ){
1233     iSize = 256;
1234   }else{
1235     iSize = sqlite3_value_int(argv[1]);
1236     if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1237       sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1238                                     "384 512", -1);
1239       return;
1240     }
1241   }
1242   if( zSql==0 ) return;
1243   SHA3Init(&cx, iSize);
1244   while( zSql[0] ){
1245     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1246     if( rc ){
1247       char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1248                                    zSql, sqlite3_errmsg(db));
1249       sqlite3_finalize(pStmt);
1250       sqlite3_result_error(context, zMsg, -1);
1251       sqlite3_free(zMsg);
1252       return;
1253     }
1254     if( !sqlite3_stmt_readonly(pStmt) ){
1255       char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1256       sqlite3_finalize(pStmt);
1257       sqlite3_result_error(context, zMsg, -1);
1258       sqlite3_free(zMsg);
1259       return;
1260     }
1261     nCol = sqlite3_column_count(pStmt);
1262     z = sqlite3_sql(pStmt);
1263     if( z==0 ){
1264       sqlite3_finalize(pStmt);
1265       continue;
1266     }
1267     n = (int)strlen(z);
1268     hash_step_vformat(&cx,"S%d:",n);
1269     SHA3Update(&cx,(unsigned char*)z,n);
1270
1271     /* Compute a hash over the result of the query */
1272     while( SQLITE_ROW==sqlite3_step(pStmt) ){
1273       SHA3Update(&cx,(const unsigned char*)"R",1);
1274       for(i=0; i<nCol; i++){
1275         switch( sqlite3_column_type(pStmt,i) ){
1276           case SQLITE_NULL: {
1277             SHA3Update(&cx, (const unsigned char*)"N",1);
1278             break;
1279           }
1280           case SQLITE_INTEGER: {
1281             sqlite3_uint64 u;
1282             int j;
1283             unsigned char x[9];
1284             sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1285             memcpy(&u, &v, 8);
1286             for(j=8; j>=1; j--){
1287               x[j] = u & 0xff;
1288               u >>= 8;
1289             }
1290             x[0] = 'I';
1291             SHA3Update(&cx, x, 9);
1292             break;
1293           }
1294           case SQLITE_FLOAT: {
1295             sqlite3_uint64 u;
1296             int j;
1297             unsigned char x[9];
1298             double r = sqlite3_column_double(pStmt,i);
1299             memcpy(&u, &r, 8);
1300             for(j=8; j>=1; j--){
1301               x[j] = u & 0xff;
1302               u >>= 8;
1303             }
1304             x[0] = 'F';
1305             SHA3Update(&cx,x,9);
1306             break;
1307           }
1308           case SQLITE_TEXT: {
1309             int n2 = sqlite3_column_bytes(pStmt, i);
1310             const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1311             hash_step_vformat(&cx,"T%d:",n2);
1312             SHA3Update(&cx, z2, n2);
1313             break;
1314           }
1315           case SQLITE_BLOB: {
1316             int n2 = sqlite3_column_bytes(pStmt, i);
1317             const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1318             hash_step_vformat(&cx,"B%d:",n2);
1319             SHA3Update(&cx, z2, n2);
1320             break;
1321           }
1322         }
1323       }
1324     }
1325     sqlite3_finalize(pStmt);
1326   }
1327   sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1328 }
1329 /* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1330 ********************************************************************************/
1331
1332 #if defined(SQLITE_ENABLE_SESSION)
1333 /*
1334 ** State information for a single open session
1335 */
1336 typedef struct OpenSession OpenSession;
1337 struct OpenSession {
1338   char *zName;             /* Symbolic name for this session */
1339   int nFilter;             /* Number of xFilter rejection GLOB patterns */
1340   char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1341   sqlite3_session *p;      /* The open session */
1342 };
1343 #endif
1344
1345 /*
1346 ** Shell output mode information from before ".explain on",
1347 ** saved so that it can be restored by ".explain off"
1348 */
1349 typedef struct SavedModeInfo SavedModeInfo;
1350 struct SavedModeInfo {
1351   int valid;          /* Is there legit data in here? */
1352   int mode;           /* Mode prior to ".explain on" */
1353   int showHeader;     /* The ".header" setting prior to ".explain on" */
1354   int colWidth[100];  /* Column widths prior to ".explain on" */
1355 };
1356
1357 /*
1358 ** State information about the database connection is contained in an
1359 ** instance of the following structure.
1360 */
1361 typedef struct ShellState ShellState;
1362 struct ShellState {
1363   sqlite3 *db;           /* The database */
1364   int autoExplain;       /* Automatically turn on .explain mode */
1365   int autoEQP;           /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1366   int statsOn;           /* True to display memory stats before each finalize */
1367   int scanstatsOn;       /* True to display scan stats before each finalize */
1368   int outCount;          /* Revert to stdout when reaching zero */
1369   int cnt;               /* Number of records displayed so far */
1370   FILE *out;             /* Write results here */
1371   FILE *traceOut;        /* Output for sqlite3_trace() */
1372   int nErr;              /* Number of errors seen */
1373   int mode;              /* An output mode setting */
1374   int cMode;             /* temporary output mode for the current query */
1375   int normalMode;        /* Output mode before ".explain on" */
1376   int writableSchema;    /* True if PRAGMA writable_schema=ON */
1377   int showHeader;        /* True to show column names in List or Column mode */
1378   int nCheck;            /* Number of ".check" commands run */
1379   unsigned shellFlgs;    /* Various flags */
1380   char *zDestTable;      /* Name of destination table when MODE_Insert */
1381   char zTestcase[30];    /* Name of current test case */
1382   char colSeparator[20]; /* Column separator character for several modes */
1383   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1384   int colWidth[100];     /* Requested width of each column when in column mode*/
1385   int actualWidth[100];  /* Actual width of each column */
1386   char nullValue[20];    /* The text to print when a NULL comes back from
1387                          ** the database */
1388   char outfile[FILENAME_MAX]; /* Filename for *out */
1389   const char *zDbFilename;    /* name of the database file */
1390   char *zFreeOnClose;         /* Filename to free when closing */
1391   const char *zVfs;           /* Name of VFS to use */
1392   sqlite3_stmt *pStmt;   /* Current statement if any. */
1393   FILE *pLog;            /* Write log output here */
1394   int *aiIndent;         /* Array of indents used in MODE_Explain */
1395   int nIndent;           /* Size of array aiIndent[] */
1396   int iIndent;           /* Index of current op in aiIndent[] */
1397 #if defined(SQLITE_ENABLE_SESSION)
1398   int nSession;             /* Number of active sessions */
1399   OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
1400 #endif
1401 };
1402
1403 /*
1404 ** These are the allowed shellFlgs values
1405 */
1406 #define SHFLG_Scratch        0x00000001 /* The --scratch option is used */
1407 #define SHFLG_Pagecache      0x00000002 /* The --pagecache option is used */
1408 #define SHFLG_Lookaside      0x00000004 /* Lookaside memory is used */
1409 #define SHFLG_Backslash      0x00000008 /* The --backslash option is used */
1410 #define SHFLG_PreserveRowid  0x00000010 /* .dump preserves rowid values */
1411 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
1412 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1413
1414 /*
1415 ** Macros for testing and setting shellFlgs
1416 */
1417 #define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1418 #define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1419 #define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1420
1421 /*
1422 ** These are the allowed modes.
1423 */
1424 #define MODE_Line     0  /* One column per line.  Blank line between records */
1425 #define MODE_Column   1  /* One record per line in neat columns */
1426 #define MODE_List     2  /* One record per line with a separator */
1427 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1428 #define MODE_Html     4  /* Generate an XHTML table */
1429 #define MODE_Insert   5  /* Generate SQL "insert" statements */
1430 #define MODE_Quote    6  /* Quote values as for SQL */
1431 #define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1432 #define MODE_Csv      8  /* Quote strings, numbers are plain */
1433 #define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1434 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1435 #define MODE_Pretty  11  /* Pretty-print schemas */
1436
1437 static const char *modeDescr[] = {
1438   "line",
1439   "column",
1440   "list",
1441   "semi",
1442   "html",
1443   "insert",
1444   "quote",
1445   "tcl",
1446   "csv",
1447   "explain",
1448   "ascii",
1449   "prettyprint",
1450 };
1451
1452 /*
1453 ** These are the column/row/line separators used by the various
1454 ** import/export modes.
1455 */
1456 #define SEP_Column    "|"
1457 #define SEP_Row       "\n"
1458 #define SEP_Tab       "\t"
1459 #define SEP_Space     " "
1460 #define SEP_Comma     ","
1461 #define SEP_CrLf      "\r\n"
1462 #define SEP_Unit      "\x1F"
1463 #define SEP_Record    "\x1E"
1464
1465 /*
1466 ** Number of elements in an array
1467 */
1468 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
1469
1470 /*
1471 ** A callback for the sqlite3_log() interface.
1472 */
1473 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1474   ShellState *p = (ShellState*)pArg;
1475   if( p->pLog==0 ) return;
1476   utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1477   fflush(p->pLog);
1478 }
1479
1480 /*
1481 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1482 */
1483 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1484   int i;
1485   char *zBlob = (char *)pBlob;
1486   raw_printf(out,"X'");
1487   for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1488   raw_printf(out,"'");
1489 }
1490
1491 /*
1492 ** Output the given string as a quoted string using SQL quoting conventions.
1493 **
1494 ** The "\n" and "\r" characters are converted to char(10) and char(13)
1495 ** to prevent them from being transformed by end-of-line translators.
1496 */
1497 static void output_quoted_string(FILE *out, const char *z){
1498   int i;
1499   char c;
1500   setBinaryMode(out, 1);
1501   for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1502   if( c==0 ){
1503     utf8_printf(out,"'%s'",z);
1504   }else{
1505     int inQuote = 0;
1506     int bStarted = 0;
1507     while( *z ){
1508       for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1509       if( c=='\'' ) i++;
1510       if( i ){
1511         if( !inQuote ){
1512           if( bStarted ) raw_printf(out, "||");
1513           raw_printf(out, "'");
1514           inQuote = 1;
1515         }
1516         utf8_printf(out, "%.*s", i, z);
1517         z += i;
1518         bStarted = 1;
1519       }
1520       if( c=='\'' ){
1521         raw_printf(out, "'");
1522         continue;
1523       }
1524       if( inQuote ){
1525         raw_printf(out, "'");
1526         inQuote = 0;
1527       }
1528       if( c==0 ){
1529         break;
1530       }
1531       for(i=0; (c = z[i])=='\r' || c=='\n'; i++){
1532         if( bStarted ) raw_printf(out, "||");
1533         raw_printf(out, "char(%d)", c);
1534         bStarted = 1;
1535       }
1536       z += i;
1537     }
1538     if( inQuote ) raw_printf(out, "'");
1539   }
1540   setTextMode(out, 1);
1541 }
1542
1543 /*
1544 ** Output the given string as a quoted according to C or TCL quoting rules.
1545 */
1546 static void output_c_string(FILE *out, const char *z){
1547   unsigned int c;
1548   fputc('"', out);
1549   while( (c = *(z++))!=0 ){
1550     if( c=='\\' ){
1551       fputc(c, out);
1552       fputc(c, out);
1553     }else if( c=='"' ){
1554       fputc('\\', out);
1555       fputc('"', out);
1556     }else if( c=='\t' ){
1557       fputc('\\', out);
1558       fputc('t', out);
1559     }else if( c=='\n' ){
1560       fputc('\\', out);
1561       fputc('n', out);
1562     }else if( c=='\r' ){
1563       fputc('\\', out);
1564       fputc('r', out);
1565     }else if( !isprint(c&0xff) ){
1566       raw_printf(out, "\\%03o", c&0xff);
1567     }else{
1568       fputc(c, out);
1569     }
1570   }
1571   fputc('"', out);
1572 }
1573
1574 /*
1575 ** Output the given string with characters that are special to
1576 ** HTML escaped.
1577 */
1578 static void output_html_string(FILE *out, const char *z){
1579   int i;
1580   if( z==0 ) z = "";
1581   while( *z ){
1582     for(i=0;   z[i]
1583             && z[i]!='<'
1584             && z[i]!='&'
1585             && z[i]!='>'
1586             && z[i]!='\"'
1587             && z[i]!='\'';
1588         i++){}
1589     if( i>0 ){
1590       utf8_printf(out,"%.*s",i,z);
1591     }
1592     if( z[i]=='<' ){
1593       raw_printf(out,"&lt;");
1594     }else if( z[i]=='&' ){
1595       raw_printf(out,"&amp;");
1596     }else if( z[i]=='>' ){
1597       raw_printf(out,"&gt;");
1598     }else if( z[i]=='\"' ){
1599       raw_printf(out,"&quot;");
1600     }else if( z[i]=='\'' ){
1601       raw_printf(out,"&#39;");
1602     }else{
1603       break;
1604     }
1605     z += i + 1;
1606   }
1607 }
1608
1609 /*
1610 ** If a field contains any character identified by a 1 in the following
1611 ** array, then the string must be quoted for CSV.
1612 */
1613 static const char needCsvQuote[] = {
1614   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1615   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1616   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1617   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1618   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1619   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1620   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1621   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1622   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1623   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1624   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1625   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1626   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1627   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1628   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1629   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1630 };
1631
1632 /*
1633 ** Output a single term of CSV.  Actually, p->colSeparator is used for
1634 ** the separator, which may or may not be a comma.  p->nullValue is
1635 ** the null value.  Strings are quoted if necessary.  The separator
1636 ** is only issued if bSep is true.
1637 */
1638 static void output_csv(ShellState *p, const char *z, int bSep){
1639   FILE *out = p->out;
1640   if( z==0 ){
1641     utf8_printf(out,"%s",p->nullValue);
1642   }else{
1643     int i;
1644     int nSep = strlen30(p->colSeparator);
1645     for(i=0; z[i]; i++){
1646       if( needCsvQuote[((unsigned char*)z)[i]]
1647          || (z[i]==p->colSeparator[0] &&
1648              (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1649         i = 0;
1650         break;
1651       }
1652     }
1653     if( i==0 ){
1654       putc('"', out);
1655       for(i=0; z[i]; i++){
1656         if( z[i]=='"' ) putc('"', out);
1657         putc(z[i], out);
1658       }
1659       putc('"', out);
1660     }else{
1661       utf8_printf(out, "%s", z);
1662     }
1663   }
1664   if( bSep ){
1665     utf8_printf(p->out, "%s", p->colSeparator);
1666   }
1667 }
1668
1669 #ifdef SIGINT
1670 /*
1671 ** This routine runs when the user presses Ctrl-C
1672 */
1673 static void interrupt_handler(int NotUsed){
1674   UNUSED_PARAMETER(NotUsed);
1675   seenInterrupt++;
1676   if( seenInterrupt>2 ) exit(1);
1677   if( globalDb ) sqlite3_interrupt(globalDb);
1678 }
1679 #endif
1680
1681 #ifndef SQLITE_OMIT_AUTHORIZATION
1682 /*
1683 ** When the ".auth ON" is set, the following authorizer callback is
1684 ** invoked.  It always returns SQLITE_OK.
1685 */
1686 static int shellAuth(
1687   void *pClientData,
1688   int op,
1689   const char *zA1,
1690   const char *zA2,
1691   const char *zA3,
1692   const char *zA4
1693 ){
1694   ShellState *p = (ShellState*)pClientData;
1695   static const char *azAction[] = { 0,
1696      "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1697      "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1698      "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1699      "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1700      "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1701      "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1702      "PRAGMA",               "READ",                 "SELECT",
1703      "TRANSACTION",          "UPDATE",               "ATTACH",
1704      "DETACH",               "ALTER_TABLE",          "REINDEX",
1705      "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1706      "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1707   };
1708   int i;
1709   const char *az[4];
1710   az[0] = zA1;
1711   az[1] = zA2;
1712   az[2] = zA3;
1713   az[3] = zA4;
1714   utf8_printf(p->out, "authorizer: %s", azAction[op]);
1715   for(i=0; i<4; i++){
1716     raw_printf(p->out, " ");
1717     if( az[i] ){
1718       output_c_string(p->out, az[i]);
1719     }else{
1720       raw_printf(p->out, "NULL");
1721     }
1722   }
1723   raw_printf(p->out, "\n");
1724   return SQLITE_OK;
1725 }
1726 #endif
1727
1728 /*
1729 ** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1730 **
1731 ** This routine converts some CREATE TABLE statements for shadow tables
1732 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1733 */
1734 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1735   if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1736     utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1737   }else{
1738     utf8_printf(out, "%s%s", z, zTail);
1739   }
1740 }
1741 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1742   char c = z[n];
1743   z[n] = 0;
1744   printSchemaLine(out, z, zTail);
1745   z[n] = c;
1746 }
1747
1748 /*
1749 ** This is the callback routine that the shell
1750 ** invokes for each row of a query result.
1751 */
1752 static int shell_callback(
1753   void *pArg,
1754   int nArg,        /* Number of result columns */
1755   char **azArg,    /* Text of each result column */
1756   char **azCol,    /* Column names */
1757   int *aiType      /* Column types */
1758 ){
1759   int i;
1760   ShellState *p = (ShellState*)pArg;
1761
1762   switch( p->cMode ){
1763     case MODE_Line: {
1764       int w = 5;
1765       if( azArg==0 ) break;
1766       for(i=0; i<nArg; i++){
1767         int len = strlen30(azCol[i] ? azCol[i] : "");
1768         if( len>w ) w = len;
1769       }
1770       if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1771       for(i=0; i<nArg; i++){
1772         utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1773                 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1774       }
1775       break;
1776     }
1777     case MODE_Explain:
1778     case MODE_Column: {
1779       static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1780       const int *colWidth;
1781       int showHdr;
1782       char *rowSep;
1783       if( p->cMode==MODE_Column ){
1784         colWidth = p->colWidth;
1785         showHdr = p->showHeader;
1786         rowSep = p->rowSeparator;
1787       }else{
1788         colWidth = aExplainWidths;
1789         showHdr = 1;
1790         rowSep = SEP_Row;
1791       }
1792       if( p->cnt++==0 ){
1793         for(i=0; i<nArg; i++){
1794           int w, n;
1795           if( i<ArraySize(p->colWidth) ){
1796             w = colWidth[i];
1797           }else{
1798             w = 0;
1799           }
1800           if( w==0 ){
1801             w = strlen30(azCol[i] ? azCol[i] : "");
1802             if( w<10 ) w = 10;
1803             n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
1804             if( w<n ) w = n;
1805           }
1806           if( i<ArraySize(p->actualWidth) ){
1807             p->actualWidth[i] = w;
1808           }
1809           if( showHdr ){
1810             if( w<0 ){
1811               utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
1812                       i==nArg-1 ? rowSep : "  ");
1813             }else{
1814               utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
1815                       i==nArg-1 ? rowSep : "  ");
1816             }
1817           }
1818         }
1819         if( showHdr ){
1820           for(i=0; i<nArg; i++){
1821             int w;
1822             if( i<ArraySize(p->actualWidth) ){
1823                w = p->actualWidth[i];
1824                if( w<0 ) w = -w;
1825             }else{
1826                w = 10;
1827             }
1828             utf8_printf(p->out,"%-*.*s%s",w,w,
1829                    "----------------------------------------------------------"
1830                    "----------------------------------------------------------",
1831                     i==nArg-1 ? rowSep : "  ");
1832           }
1833         }
1834       }
1835       if( azArg==0 ) break;
1836       for(i=0; i<nArg; i++){
1837         int w;
1838         if( i<ArraySize(p->actualWidth) ){
1839            w = p->actualWidth[i];
1840         }else{
1841            w = 10;
1842         }
1843         if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
1844           w = strlen30(azArg[i]);
1845         }
1846         if( i==1 && p->aiIndent && p->pStmt ){
1847           if( p->iIndent<p->nIndent ){
1848             utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1849           }
1850           p->iIndent++;
1851         }
1852         if( w<0 ){
1853           utf8_printf(p->out,"%*.*s%s",-w,-w,
1854               azArg[i] ? azArg[i] : p->nullValue,
1855               i==nArg-1 ? rowSep : "  ");
1856         }else{
1857           utf8_printf(p->out,"%-*.*s%s",w,w,
1858               azArg[i] ? azArg[i] : p->nullValue,
1859               i==nArg-1 ? rowSep : "  ");
1860         }
1861       }
1862       break;
1863     }
1864     case MODE_Semi: {   /* .schema and .fullschema output */
1865       printSchemaLine(p->out, azArg[0], ";\n");
1866       break;
1867     }
1868     case MODE_Pretty: {  /* .schema and .fullschema with --indent */
1869       char *z;
1870       int j;
1871       int nParen = 0;
1872       char cEnd = 0;
1873       char c;
1874       int nLine = 0;
1875       assert( nArg==1 );
1876       if( azArg[0]==0 ) break;
1877       if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1878        || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1879       ){
1880         utf8_printf(p->out, "%s;\n", azArg[0]);
1881         break;
1882       }
1883       z = sqlite3_mprintf("%s", azArg[0]);
1884       j = 0;
1885       for(i=0; IsSpace(z[i]); i++){}
1886       for(; (c = z[i])!=0; i++){
1887         if( IsSpace(c) ){
1888           if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1889         }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1890           j--;
1891         }
1892         z[j++] = c;
1893       }
1894       while( j>0 && IsSpace(z[j-1]) ){ j--; }
1895       z[j] = 0;
1896       if( strlen30(z)>=79 ){
1897         for(i=j=0; (c = z[i])!=0; i++){
1898           if( c==cEnd ){
1899             cEnd = 0;
1900           }else if( c=='"' || c=='\'' || c=='`' ){
1901             cEnd = c;
1902           }else if( c=='[' ){
1903             cEnd = ']';
1904           }else if( c=='(' ){
1905             nParen++;
1906           }else if( c==')' ){
1907             nParen--;
1908             if( nLine>0 && nParen==0 && j>0 ){
1909               printSchemaLineN(p->out, z, j, "\n");
1910               j = 0;
1911             }
1912           }
1913           z[j++] = c;
1914           if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1915             if( c=='\n' ) j--;
1916             printSchemaLineN(p->out, z, j, "\n  ");
1917             j = 0;
1918             nLine++;
1919             while( IsSpace(z[i+1]) ){ i++; }
1920           }
1921         }
1922         z[j] = 0;
1923       }
1924       printSchemaLine(p->out, z, ";\n");
1925       sqlite3_free(z);
1926       break;
1927     }
1928     case MODE_List: {
1929       if( p->cnt++==0 && p->showHeader ){
1930         for(i=0; i<nArg; i++){
1931           utf8_printf(p->out,"%s%s",azCol[i],
1932                   i==nArg-1 ? p->rowSeparator : p->colSeparator);
1933         }
1934       }
1935       if( azArg==0 ) break;
1936       for(i=0; i<nArg; i++){
1937         char *z = azArg[i];
1938         if( z==0 ) z = p->nullValue;
1939         utf8_printf(p->out, "%s", z);
1940         if( i<nArg-1 ){
1941           utf8_printf(p->out, "%s", p->colSeparator);
1942         }else{
1943           utf8_printf(p->out, "%s", p->rowSeparator);
1944         }
1945       }
1946       break;
1947     }
1948     case MODE_Html: {
1949       if( p->cnt++==0 && p->showHeader ){
1950         raw_printf(p->out,"<TR>");
1951         for(i=0; i<nArg; i++){
1952           raw_printf(p->out,"<TH>");
1953           output_html_string(p->out, azCol[i]);
1954           raw_printf(p->out,"</TH>\n");
1955         }
1956         raw_printf(p->out,"</TR>\n");
1957       }
1958       if( azArg==0 ) break;
1959       raw_printf(p->out,"<TR>");
1960       for(i=0; i<nArg; i++){
1961         raw_printf(p->out,"<TD>");
1962         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1963         raw_printf(p->out,"</TD>\n");
1964       }
1965       raw_printf(p->out,"</TR>\n");
1966       break;
1967     }
1968     case MODE_Tcl: {
1969       if( p->cnt++==0 && p->showHeader ){
1970         for(i=0; i<nArg; i++){
1971           output_c_string(p->out,azCol[i] ? azCol[i] : "");
1972           if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1973         }
1974         utf8_printf(p->out, "%s", p->rowSeparator);
1975       }
1976       if( azArg==0 ) break;
1977       for(i=0; i<nArg; i++){
1978         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1979         if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1980       }
1981       utf8_printf(p->out, "%s", p->rowSeparator);
1982       break;
1983     }
1984     case MODE_Csv: {
1985       setBinaryMode(p->out, 1);
1986       if( p->cnt++==0 && p->showHeader ){
1987         for(i=0; i<nArg; i++){
1988           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1989         }
1990         utf8_printf(p->out, "%s", p->rowSeparator);
1991       }
1992       if( nArg>0 ){
1993         for(i=0; i<nArg; i++){
1994           output_csv(p, azArg[i], i<nArg-1);
1995         }
1996         utf8_printf(p->out, "%s", p->rowSeparator);
1997       }
1998       setTextMode(p->out, 1);
1999       break;
2000     }
2001     case MODE_Quote:
2002     case MODE_Insert: {
2003       if( azArg==0 ) break;
2004       if( p->cMode==MODE_Insert ){
2005         utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2006         if( p->showHeader ){
2007           raw_printf(p->out,"(");
2008           for(i=0; i<nArg; i++){
2009             char *zSep = i>0 ? ",": "";
2010             utf8_printf(p->out, "%s%s", zSep, azCol[i]);
2011           }
2012           raw_printf(p->out,")");
2013         }
2014         raw_printf(p->out," VALUES(");
2015       }else if( p->cnt==0 && p->showHeader ){
2016         for(i=0; i<nArg; i++){
2017           if( i>0 ) raw_printf(p->out, ",");
2018           output_quoted_string(p->out, azCol[i]);
2019         }
2020         raw_printf(p->out,"\n");
2021       }
2022       p->cnt++;
2023       for(i=0; i<nArg; i++){
2024         char *zSep = i>0 ? ",": "";
2025         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2026           utf8_printf(p->out,"%sNULL",zSep);
2027         }else if( aiType && aiType[i]==SQLITE_TEXT ){
2028           if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2029           output_quoted_string(p->out, azArg[i]);
2030         }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2031           utf8_printf(p->out,"%s%s",zSep, azArg[i]);
2032         }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2033           char z[50];
2034           double r = sqlite3_column_double(p->pStmt, i);
2035           sqlite3_snprintf(50,z,"%!.20g", r);
2036           raw_printf(p->out, "%s%s", zSep, z);
2037         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2038           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2039           int nBlob = sqlite3_column_bytes(p->pStmt, i);
2040           if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2041           output_hex_blob(p->out, pBlob, nBlob);
2042         }else if( isNumber(azArg[i], 0) ){
2043           utf8_printf(p->out,"%s%s",zSep, azArg[i]);
2044         }else{
2045           if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2046           output_quoted_string(p->out, azArg[i]);
2047         }
2048       }
2049       raw_printf(p->out,p->cMode==MODE_Quote?"\n":");\n");
2050       break;
2051     }
2052     case MODE_Ascii: {
2053       if( p->cnt++==0 && p->showHeader ){
2054         for(i=0; i<nArg; i++){
2055           if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2056           utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2057         }
2058         utf8_printf(p->out, "%s", p->rowSeparator);
2059       }
2060       if( azArg==0 ) break;
2061       for(i=0; i<nArg; i++){
2062         if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2063         utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2064       }
2065       utf8_printf(p->out, "%s", p->rowSeparator);
2066       break;
2067     }
2068   }
2069   return 0;
2070 }
2071
2072 /*
2073 ** This is the callback routine that the SQLite library
2074 ** invokes for each row of a query result.
2075 */
2076 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2077   /* since we don't have type info, call the shell_callback with a NULL value */
2078   return shell_callback(pArg, nArg, azArg, azCol, NULL);
2079 }
2080
2081 /*
2082 ** This is the callback routine from sqlite3_exec() that appends all
2083 ** output onto the end of a ShellText object.
2084 */
2085 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2086   ShellText *p = (ShellText*)pArg;
2087   int i;
2088   UNUSED_PARAMETER(az);
2089   if( p->n ) appendText(p, "|", 0);
2090   for(i=0; i<nArg; i++){
2091     if( i ) appendText(p, ",", 0);
2092     if( azArg[i] ) appendText(p, azArg[i], 0);
2093   }
2094   return 0;
2095 }
2096
2097 /*
2098 ** Generate an appropriate SELFTEST table in the main database.
2099 */
2100 static void createSelftestTable(ShellState *p){
2101   char *zErrMsg = 0;
2102   sqlite3_exec(p->db,
2103     "SAVEPOINT selftest_init;\n"
2104     "CREATE TABLE IF NOT EXISTS selftest(\n"
2105     "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2106     "  op TEXT,\n"                   /* Operator:  memo run */
2107     "  cmd TEXT,\n"                  /* Command text */
2108     "  ans TEXT\n"                   /* Desired answer */
2109     ");"
2110     "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2111     "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2112     "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2113     "         'memo','Tests generated by --init');\n"
2114     "INSERT INTO [_shell$self]\n"
2115     "  SELECT 'run',\n"
2116     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2117                                  "FROM sqlite_master ORDER BY 2'',224))',\n"
2118     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2119                           "FROM sqlite_master ORDER BY 2',224));\n"
2120     "INSERT INTO [_shell$self]\n"
2121     "  SELECT 'run',"
2122     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2123     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2124     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2125     "  FROM (\n"
2126     "    SELECT name FROM sqlite_master\n"
2127     "     WHERE type='table'\n"
2128     "       AND name<>'selftest'\n"
2129     "       AND coalesce(rootpage,0)>0\n"
2130     "  )\n"
2131     " ORDER BY name;\n"
2132     "INSERT INTO [_shell$self]\n"
2133     "  VALUES('run','PRAGMA integrity_check','ok');\n"
2134     "INSERT INTO selftest(tno,op,cmd,ans)"
2135     "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2136     "DROP TABLE [_shell$self];"
2137     ,0,0,&zErrMsg);
2138   if( zErrMsg ){
2139     utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2140     sqlite3_free(zErrMsg);
2141   }
2142   sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2143 }
2144
2145
2146 /*
2147 ** Set the destination table field of the ShellState structure to
2148 ** the name of the table given.  Escape any quote characters in the
2149 ** table name.
2150 */
2151 static void set_table_name(ShellState *p, const char *zName){
2152   int i, n;
2153   int cQuote;
2154   char *z;
2155
2156   if( p->zDestTable ){
2157     free(p->zDestTable);
2158     p->zDestTable = 0;
2159   }
2160   if( zName==0 ) return;
2161   cQuote = quoteChar(zName);
2162   n = strlen30(zName);
2163   if( cQuote ) n += 2;
2164   z = p->zDestTable = malloc( n+1 );
2165   if( z==0 ){
2166     raw_printf(stderr,"Error: out of memory\n");
2167     exit(1);
2168   }
2169   n = 0;
2170   if( cQuote ) z[n++] = cQuote;
2171   for(i=0; zName[i]; i++){
2172     z[n++] = zName[i];
2173     if( zName[i]==cQuote ) z[n++] = cQuote;
2174   }
2175   if( cQuote ) z[n++] = cQuote;
2176   z[n] = 0;
2177 }
2178
2179
2180 /*
2181 ** Execute a query statement that will generate SQL output.  Print
2182 ** the result columns, comma-separated, on a line and then add a
2183 ** semicolon terminator to the end of that line.
2184 **
2185 ** If the number of columns is 1 and that column contains text "--"
2186 ** then write the semicolon on a separate line.  That way, if a
2187 ** "--" comment occurs at the end of the statement, the comment
2188 ** won't consume the semicolon terminator.
2189 */
2190 static int run_table_dump_query(
2191   ShellState *p,           /* Query context */
2192   const char *zSelect,     /* SELECT statement to extract content */
2193   const char *zFirstRow    /* Print before first row, if not NULL */
2194 ){
2195   sqlite3_stmt *pSelect;
2196   int rc;
2197   int nResult;
2198   int i;
2199   const char *z;
2200   rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2201   if( rc!=SQLITE_OK || !pSelect ){
2202     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2203                 sqlite3_errmsg(p->db));
2204     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2205     return rc;
2206   }
2207   rc = sqlite3_step(pSelect);
2208   nResult = sqlite3_column_count(pSelect);
2209   while( rc==SQLITE_ROW ){
2210     if( zFirstRow ){
2211       utf8_printf(p->out, "%s", zFirstRow);
2212       zFirstRow = 0;
2213     }
2214     z = (const char*)sqlite3_column_text(pSelect, 0);
2215     utf8_printf(p->out, "%s", z);
2216     for(i=1; i<nResult; i++){
2217       utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2218     }
2219     if( z==0 ) z = "";
2220     while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2221     if( z[0] ){
2222       raw_printf(p->out, "\n;\n");
2223     }else{
2224       raw_printf(p->out, ";\n");
2225     }
2226     rc = sqlite3_step(pSelect);
2227   }
2228   rc = sqlite3_finalize(pSelect);
2229   if( rc!=SQLITE_OK ){
2230     utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2231                 sqlite3_errmsg(p->db));
2232     if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2233   }
2234   return rc;
2235 }
2236
2237 /*
2238 ** Allocate space and save off current error string.
2239 */
2240 static char *save_err_msg(
2241   sqlite3 *db            /* Database to query */
2242 ){
2243   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2244   char *zErrMsg = sqlite3_malloc64(nErrMsg);
2245   if( zErrMsg ){
2246     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2247   }
2248   return zErrMsg;
2249 }
2250
2251 #ifdef __linux__
2252 /*
2253 ** Attempt to display I/O stats on Linux using /proc/PID/io
2254 */
2255 static void displayLinuxIoStats(FILE *out){
2256   FILE *in;
2257   char z[200];
2258   sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2259   in = fopen(z, "rb");
2260   if( in==0 ) return;
2261   while( fgets(z, sizeof(z), in)!=0 ){
2262     static const struct {
2263       const char *zPattern;
2264       const char *zDesc;
2265     } aTrans[] = {
2266       { "rchar: ",                  "Bytes received by read():" },
2267       { "wchar: ",                  "Bytes sent to write():"    },
2268       { "syscr: ",                  "Read() system calls:"      },
2269       { "syscw: ",                  "Write() system calls:"     },
2270       { "read_bytes: ",             "Bytes read from storage:"  },
2271       { "write_bytes: ",            "Bytes written to storage:" },
2272       { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2273     };
2274     int i;
2275     for(i=0; i<ArraySize(aTrans); i++){
2276       int n = (int)strlen(aTrans[i].zPattern);
2277       if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2278         utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2279         break;
2280       }
2281     }
2282   }
2283   fclose(in);
2284 }
2285 #endif
2286
2287 /*
2288 ** Display a single line of status using 64-bit values.
2289 */
2290 static void displayStatLine(
2291   ShellState *p,            /* The shell context */
2292   char *zLabel,             /* Label for this one line */
2293   char *zFormat,            /* Format for the result */
2294   int iStatusCtrl,          /* Which status to display */
2295   int bReset                /* True to reset the stats */
2296 ){
2297   sqlite3_int64 iCur = -1;
2298   sqlite3_int64 iHiwtr = -1;
2299   int i, nPercent;
2300   char zLine[200];
2301   sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2302   for(i=0, nPercent=0; zFormat[i]; i++){
2303     if( zFormat[i]=='%' ) nPercent++;
2304   }
2305   if( nPercent>1 ){
2306     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2307   }else{
2308     sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2309   }
2310   raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2311 }
2312
2313 /*
2314 ** Display memory stats.
2315 */
2316 static int display_stats(
2317   sqlite3 *db,                /* Database to query */
2318   ShellState *pArg,           /* Pointer to ShellState */
2319   int bReset                  /* True to reset the stats */
2320 ){
2321   int iCur;
2322   int iHiwtr;
2323
2324   if( pArg && pArg->out ){
2325     displayStatLine(pArg, "Memory Used:",
2326        "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2327     displayStatLine(pArg, "Number of Outstanding Allocations:",
2328        "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2329     if( pArg->shellFlgs & SHFLG_Pagecache ){
2330       displayStatLine(pArg, "Number of Pcache Pages Used:",
2331          "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2332     }
2333     displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2334        "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2335     if( pArg->shellFlgs & SHFLG_Scratch ){
2336       displayStatLine(pArg, "Number of Scratch Allocations Used:",
2337          "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
2338     }
2339     displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2340        "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2341     displayStatLine(pArg, "Largest Allocation:",
2342        "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2343     displayStatLine(pArg, "Largest Pcache Allocation:",
2344        "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2345     displayStatLine(pArg, "Largest Scratch Allocation:",
2346        "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
2347 #ifdef YYTRACKMAXSTACKDEPTH
2348     displayStatLine(pArg, "Deepest Parser Stack:",
2349        "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2350 #endif
2351   }
2352
2353   if( pArg && pArg->out && db ){
2354     if( pArg->shellFlgs & SHFLG_Lookaside ){
2355       iHiwtr = iCur = -1;
2356       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2357                         &iCur, &iHiwtr, bReset);
2358       raw_printf(pArg->out,
2359               "Lookaside Slots Used:                %d (max %d)\n",
2360               iCur, iHiwtr);
2361       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2362                         &iCur, &iHiwtr, bReset);
2363       raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2364               iHiwtr);
2365       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2366                         &iCur, &iHiwtr, bReset);
2367       raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2368               iHiwtr);
2369       sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2370                         &iCur, &iHiwtr, bReset);
2371       raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2372               iHiwtr);
2373     }
2374     iHiwtr = iCur = -1;
2375     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2376     raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2377             iCur);
2378     iHiwtr = iCur = -1;
2379     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2380     raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2381     iHiwtr = iCur = -1;
2382     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2383     raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2384     iHiwtr = iCur = -1;
2385     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2386     raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2387     iHiwtr = iCur = -1;
2388     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2389     raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2390             iCur);
2391     iHiwtr = iCur = -1;
2392     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2393     raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2394             iCur);
2395   }
2396
2397   if( pArg && pArg->out && db && pArg->pStmt ){
2398     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2399                                bReset);
2400     raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2401     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2402     raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2403     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2404     raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2405     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2406     raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2407   }
2408
2409 #ifdef __linux__
2410   displayLinuxIoStats(pArg->out);
2411 #endif
2412
2413   /* Do not remove this machine readable comment: extra-stats-output-here */
2414
2415   return 0;
2416 }
2417
2418 /*
2419 ** Display scan stats.
2420 */
2421 static void display_scanstats(
2422   sqlite3 *db,                    /* Database to query */
2423   ShellState *pArg                /* Pointer to ShellState */
2424 ){
2425 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2426   UNUSED_PARAMETER(db);
2427   UNUSED_PARAMETER(pArg);
2428 #else
2429   int i, k, n, mx;
2430   raw_printf(pArg->out, "-------- scanstats --------\n");
2431   mx = 0;
2432   for(k=0; k<=mx; k++){
2433     double rEstLoop = 1.0;
2434     for(i=n=0; 1; i++){
2435       sqlite3_stmt *p = pArg->pStmt;
2436       sqlite3_int64 nLoop, nVisit;
2437       double rEst;
2438       int iSid;
2439       const char *zExplain;
2440       if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2441         break;
2442       }
2443       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2444       if( iSid>mx ) mx = iSid;
2445       if( iSid!=k ) continue;
2446       if( n==0 ){
2447         rEstLoop = (double)nLoop;
2448         if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2449       }
2450       n++;
2451       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2452       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2453       sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2454       utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2455       rEstLoop *= rEst;
2456       raw_printf(pArg->out,
2457           "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2458           nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2459       );
2460     }
2461   }
2462   raw_printf(pArg->out, "---------------------------\n");
2463 #endif
2464 }
2465
2466 /*
2467 ** Parameter azArray points to a zero-terminated array of strings. zStr
2468 ** points to a single nul-terminated string. Return non-zero if zStr
2469 ** is equal, according to strcmp(), to any of the strings in the array.
2470 ** Otherwise, return zero.
2471 */
2472 static int str_in_array(const char *zStr, const char **azArray){
2473   int i;
2474   for(i=0; azArray[i]; i++){
2475     if( 0==strcmp(zStr, azArray[i]) ) return 1;
2476   }
2477   return 0;
2478 }
2479
2480 /*
2481 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2482 ** and populate the ShellState.aiIndent[] array with the number of
2483 ** spaces each opcode should be indented before it is output.
2484 **
2485 ** The indenting rules are:
2486 **
2487 **     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2488 **       all opcodes that occur between the p2 jump destination and the opcode
2489 **       itself by 2 spaces.
2490 **
2491 **     * For each "Goto", if the jump destination is earlier in the program
2492 **       and ends on one of:
2493 **          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2494 **       or if the P1 parameter is one instead of zero,
2495 **       then indent all opcodes between the earlier instruction
2496 **       and "Goto" by 2 spaces.
2497 */
2498 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2499   const char *zSql;               /* The text of the SQL statement */
2500   const char *z;                  /* Used to check if this is an EXPLAIN */
2501   int *abYield = 0;               /* True if op is an OP_Yield */
2502   int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2503   int iOp;                        /* Index of operation in p->aiIndent[] */
2504
2505   const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2506                            "NextIfOpen", "PrevIfOpen", 0 };
2507   const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2508                             "Rewind", 0 };
2509   const char *azGoto[] = { "Goto", 0 };
2510
2511   /* Try to figure out if this is really an EXPLAIN statement. If this
2512   ** cannot be verified, return early.  */
2513   if( sqlite3_column_count(pSql)!=8 ){
2514     p->cMode = p->mode;
2515     return;
2516   }
2517   zSql = sqlite3_sql(pSql);
2518   if( zSql==0 ) return;
2519   for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2520   if( sqlite3_strnicmp(z, "explain", 7) ){
2521     p->cMode = p->mode;
2522     return;
2523   }
2524
2525   for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2526     int i;
2527     int iAddr = sqlite3_column_int(pSql, 0);
2528     const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2529
2530     /* Set p2 to the P2 field of the current opcode. Then, assuming that
2531     ** p2 is an instruction address, set variable p2op to the index of that
2532     ** instruction in the aiIndent[] array. p2 and p2op may be different if
2533     ** the current instruction is part of a sub-program generated by an
2534     ** SQL trigger or foreign key.  */
2535     int p2 = sqlite3_column_int(pSql, 3);
2536     int p2op = (p2 + (iOp-iAddr));
2537
2538     /* Grow the p->aiIndent array as required */
2539     if( iOp>=nAlloc ){
2540       if( iOp==0 ){
2541         /* Do further verfication that this is explain output.  Abort if
2542         ** it is not */
2543         static const char *explainCols[] = {
2544            "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2545         int jj;
2546         for(jj=0; jj<ArraySize(explainCols); jj++){
2547           if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2548             p->cMode = p->mode;
2549             sqlite3_reset(pSql);
2550             return;
2551           }
2552         }
2553       }
2554       nAlloc += 100;
2555       p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2556       abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2557     }
2558     abYield[iOp] = str_in_array(zOp, azYield);
2559     p->aiIndent[iOp] = 0;
2560     p->nIndent = iOp+1;
2561
2562     if( str_in_array(zOp, azNext) ){
2563       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2564     }
2565     if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2566      && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2567     ){
2568       for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2569     }
2570   }
2571
2572   p->iIndent = 0;
2573   sqlite3_free(abYield);
2574   sqlite3_reset(pSql);
2575 }
2576
2577 /*
2578 ** Free the array allocated by explain_data_prepare().
2579 */
2580 static void explain_data_delete(ShellState *p){
2581   sqlite3_free(p->aiIndent);
2582   p->aiIndent = 0;
2583   p->nIndent = 0;
2584   p->iIndent = 0;
2585 }
2586
2587 /*
2588 ** Disable and restore .wheretrace and .selecttrace settings.
2589 */
2590 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2591 extern int sqlite3SelectTrace;
2592 static int savedSelectTrace;
2593 #endif
2594 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2595 extern int sqlite3WhereTrace;
2596 static int savedWhereTrace;
2597 #endif
2598 static void disable_debug_trace_modes(void){
2599 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2600   savedSelectTrace = sqlite3SelectTrace;
2601   sqlite3SelectTrace = 0;
2602 #endif
2603 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2604   savedWhereTrace = sqlite3WhereTrace;
2605   sqlite3WhereTrace = 0;
2606 #endif
2607 }
2608 static void restore_debug_trace_modes(void){
2609 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2610   sqlite3SelectTrace = savedSelectTrace;
2611 #endif
2612 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2613   sqlite3WhereTrace = savedWhereTrace;
2614 #endif
2615 }
2616
2617 /*
2618 ** Run a prepared statement
2619 */
2620 static void exec_prepared_stmt(
2621   ShellState *pArg,                                /* Pointer to ShellState */
2622   sqlite3_stmt *pStmt,                             /* Statment to run */
2623   int (*xCallback)(void*,int,char**,char**,int*)   /* Callback function */
2624 ){
2625   int rc;
2626
2627   /* perform the first step.  this will tell us if we
2628   ** have a result set or not and how wide it is.
2629   */
2630   rc = sqlite3_step(pStmt);
2631   /* if we have a result set... */
2632   if( SQLITE_ROW == rc ){
2633     /* if we have a callback... */
2634     if( xCallback ){
2635       /* allocate space for col name ptr, value ptr, and type */
2636       int nCol = sqlite3_column_count(pStmt);
2637       void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2638       if( !pData ){
2639         rc = SQLITE_NOMEM;
2640       }else{
2641         char **azCols = (char **)pData;      /* Names of result columns */
2642         char **azVals = &azCols[nCol];       /* Results */
2643         int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2644         int i, x;
2645         assert(sizeof(int) <= sizeof(char *));
2646         /* save off ptrs to column names */
2647         for(i=0; i<nCol; i++){
2648           azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2649         }
2650         do{
2651           /* extract the data and data types */
2652           for(i=0; i<nCol; i++){
2653             aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2654             if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2655               azVals[i] = "";
2656             }else{
2657               azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2658             }
2659             if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2660               rc = SQLITE_NOMEM;
2661               break; /* from for */
2662             }
2663           } /* end for */
2664
2665           /* if data and types extracted successfully... */
2666           if( SQLITE_ROW == rc ){
2667             /* call the supplied callback with the result row data */
2668             if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2669               rc = SQLITE_ABORT;
2670             }else{
2671               rc = sqlite3_step(pStmt);
2672             }
2673           }
2674         } while( SQLITE_ROW == rc );
2675         sqlite3_free(pData);
2676       }
2677     }else{
2678       do{
2679         rc = sqlite3_step(pStmt);
2680       } while( rc == SQLITE_ROW );
2681     }
2682   }
2683 }
2684
2685 /*
2686 ** Execute a statement or set of statements.  Print
2687 ** any result rows/columns depending on the current mode
2688 ** set via the supplied callback.
2689 **
2690 ** This is very similar to SQLite's built-in sqlite3_exec()
2691 ** function except it takes a slightly different callback
2692 ** and callback data argument.
2693 */
2694 static int shell_exec(
2695   sqlite3 *db,                              /* An open database */
2696   const char *zSql,                         /* SQL to be evaluated */
2697   int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
2698                                             /* (not the same as sqlite3_exec) */
2699   ShellState *pArg,                         /* Pointer to ShellState */
2700   char **pzErrMsg                           /* Error msg written here */
2701 ){
2702   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
2703   int rc = SQLITE_OK;             /* Return Code */
2704   int rc2;
2705   const char *zLeftover;          /* Tail of unprocessed SQL */
2706
2707   if( pzErrMsg ){
2708     *pzErrMsg = NULL;
2709   }
2710
2711   while( zSql[0] && (SQLITE_OK == rc) ){
2712     static const char *zStmtSql;
2713     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2714     if( SQLITE_OK != rc ){
2715       if( pzErrMsg ){
2716         *pzErrMsg = save_err_msg(db);
2717       }
2718     }else{
2719       if( !pStmt ){
2720         /* this happens for a comment or white-space */
2721         zSql = zLeftover;
2722         while( IsSpace(zSql[0]) ) zSql++;
2723         continue;
2724       }
2725       zStmtSql = sqlite3_sql(pStmt);
2726       if( zStmtSql==0 ) zStmtSql = "";
2727       while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2728
2729       /* save off the prepared statment handle and reset row count */
2730       if( pArg ){
2731         pArg->pStmt = pStmt;
2732         pArg->cnt = 0;
2733       }
2734
2735       /* echo the sql statement if echo on */
2736       if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2737         utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2738       }
2739
2740       /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2741       if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2742         sqlite3_stmt *pExplain;
2743         char *zEQP;
2744         disable_debug_trace_modes();
2745         zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2746         rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2747         if( rc==SQLITE_OK ){
2748           while( sqlite3_step(pExplain)==SQLITE_ROW ){
2749             raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2750             raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2751             raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2752             utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2753           }
2754         }
2755         sqlite3_finalize(pExplain);
2756         sqlite3_free(zEQP);
2757         if( pArg->autoEQP>=2 ){
2758           /* Also do an EXPLAIN for ".eqp full" mode */
2759           zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2760           rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2761           if( rc==SQLITE_OK ){
2762             pArg->cMode = MODE_Explain;
2763             explain_data_prepare(pArg, pExplain);
2764             exec_prepared_stmt(pArg, pExplain, xCallback);
2765             explain_data_delete(pArg);
2766           }
2767           sqlite3_finalize(pExplain);
2768           sqlite3_free(zEQP);
2769         }
2770         restore_debug_trace_modes();
2771       }
2772
2773       if( pArg ){
2774         pArg->cMode = pArg->mode;
2775         if( pArg->autoExplain
2776          && sqlite3_column_count(pStmt)==8
2777          && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2778         ){
2779           pArg->cMode = MODE_Explain;
2780         }
2781
2782         /* If the shell is currently in ".explain" mode, gather the extra
2783         ** data required to add indents to the output.*/
2784         if( pArg->cMode==MODE_Explain ){
2785           explain_data_prepare(pArg, pStmt);
2786         }
2787       }
2788
2789       exec_prepared_stmt(pArg, pStmt, xCallback);
2790       explain_data_delete(pArg);
2791
2792       /* print usage stats if stats on */
2793       if( pArg && pArg->statsOn ){
2794         display_stats(db, pArg, 0);
2795       }
2796
2797       /* print loop-counters if required */
2798       if( pArg && pArg->scanstatsOn ){
2799         display_scanstats(db, pArg);
2800       }
2801
2802       /* Finalize the statement just executed. If this fails, save a
2803       ** copy of the error message. Otherwise, set zSql to point to the
2804       ** next statement to execute. */
2805       rc2 = sqlite3_finalize(pStmt);
2806       if( rc!=SQLITE_NOMEM ) rc = rc2;
2807       if( rc==SQLITE_OK ){
2808         zSql = zLeftover;
2809         while( IsSpace(zSql[0]) ) zSql++;
2810       }else if( pzErrMsg ){
2811         *pzErrMsg = save_err_msg(db);
2812       }
2813
2814       /* clear saved stmt handle */
2815       if( pArg ){
2816         pArg->pStmt = NULL;
2817       }
2818     }
2819   } /* end while */
2820
2821   return rc;
2822 }
2823
2824 /*
2825 ** Release memory previously allocated by tableColumnList().
2826 */
2827 static void freeColumnList(char **azCol){
2828   int i;
2829   for(i=1; azCol[i]; i++){
2830     sqlite3_free(azCol[i]);
2831   }
2832   /* azCol[0] is a static string */
2833   sqlite3_free(azCol);
2834 }
2835
2836 /*
2837 ** Return a list of pointers to strings which are the names of all
2838 ** columns in table zTab.   The memory to hold the names is dynamically
2839 ** allocated and must be released by the caller using a subsequent call
2840 ** to freeColumnList().
2841 **
2842 ** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
2843 ** value that needs to be preserved, then azCol[0] is filled in with the
2844 ** name of the rowid column.
2845 **
2846 ** The first regular column in the table is azCol[1].  The list is terminated
2847 ** by an entry with azCol[i]==0.
2848 */
2849 static char **tableColumnList(ShellState *p, const char *zTab){
2850   char **azCol = 0;
2851   sqlite3_stmt *pStmt;
2852   char *zSql;
2853   int nCol = 0;
2854   int nAlloc = 0;
2855   int nPK = 0;       /* Number of PRIMARY KEY columns seen */
2856   int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
2857   int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2858   int rc;
2859
2860   zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2861   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2862   sqlite3_free(zSql);
2863   if( rc ) return 0;
2864   while( sqlite3_step(pStmt)==SQLITE_ROW ){
2865     if( nCol>=nAlloc-2 ){
2866       nAlloc = nAlloc*2 + nCol + 10;
2867       azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2868       if( azCol==0 ){
2869         raw_printf(stderr, "Error: out of memory\n");
2870         exit(1);
2871       }
2872     }
2873     azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2874     if( sqlite3_column_int(pStmt, 5) ){
2875       nPK++;
2876       if( nPK==1
2877        && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2878                           "INTEGER")==0 
2879       ){
2880         isIPK = 1;
2881       }else{
2882         isIPK = 0;
2883       }
2884     }
2885   }
2886   sqlite3_finalize(pStmt);
2887   azCol[0] = 0;
2888   azCol[nCol+1] = 0;
2889
2890   /* The decision of whether or not a rowid really needs to be preserved
2891   ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
2892   ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
2893   ** rowids on tables where the rowid is inaccessible because there are other
2894   ** columns in the table named "rowid", "_rowid_", and "oid".
2895   */
2896   if( preserveRowid && isIPK ){
2897     /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2898     ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
2899     ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2900     ** ROWID aliases.  To distinguish these cases, check to see if
2901     ** there is a "pk" entry in "PRAGMA index_list".  There will be
2902     ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2903     */
2904     zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2905                            " WHERE origin='pk'", zTab);
2906     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2907     sqlite3_free(zSql);
2908     if( rc ){
2909       freeColumnList(azCol);
2910       return 0;
2911     }
2912     rc = sqlite3_step(pStmt);
2913     sqlite3_finalize(pStmt);
2914     preserveRowid = rc==SQLITE_ROW;
2915   }
2916   if( preserveRowid ){
2917     /* Only preserve the rowid if we can find a name to use for the
2918     ** rowid */
2919     static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2920     int i, j;
2921     for(j=0; j<3; j++){
2922       for(i=1; i<=nCol; i++){
2923         if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2924       }
2925       if( i>nCol ){
2926         /* At this point, we know that azRowid[j] is not the name of any
2927         ** ordinary column in the table.  Verify that azRowid[j] is a valid
2928         ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
2929         ** tables will fail this last check */
2930         rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2931         if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2932         break;
2933       }
2934     }
2935   }
2936   return azCol;
2937 }
2938
2939 /*
2940 ** Toggle the reverse_unordered_selects setting.
2941 */
2942 static void toggleSelectOrder(sqlite3 *db){
2943   sqlite3_stmt *pStmt = 0;
2944   int iSetting = 0;
2945   char zStmt[100];
2946   sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2947   if( sqlite3_step(pStmt)==SQLITE_ROW ){
2948     iSetting = sqlite3_column_int(pStmt, 0);
2949   }
2950   sqlite3_finalize(pStmt);
2951   sqlite3_snprintf(sizeof(zStmt), zStmt,
2952        "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2953   sqlite3_exec(db, zStmt, 0, 0, 0);
2954 }
2955
2956 /*
2957 ** This is a different callback routine used for dumping the database.
2958 ** Each row received by this callback consists of a table name,
2959 ** the table type ("index" or "table") and SQL to create the table.
2960 ** This routine should print text sufficient to recreate the table.
2961 */
2962 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2963   int rc;
2964   const char *zTable;
2965   const char *zType;
2966   const char *zSql;
2967   ShellState *p = (ShellState *)pArg;
2968
2969   UNUSED_PARAMETER(azNotUsed);
2970   if( nArg!=3 ) return 1;
2971   zTable = azArg[0];
2972   zType = azArg[1];
2973   zSql = azArg[2];
2974
2975   if( strcmp(zTable, "sqlite_sequence")==0 ){
2976     raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2977   }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2978     raw_printf(p->out, "ANALYZE sqlite_master;\n");
2979   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2980     return 0;
2981   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2982     char *zIns;
2983     if( !p->writableSchema ){
2984       raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2985       p->writableSchema = 1;
2986     }
2987     zIns = sqlite3_mprintf(
2988        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2989        "VALUES('table','%q','%q',0,'%q');",
2990        zTable, zTable, zSql);
2991     utf8_printf(p->out, "%s\n", zIns);
2992     sqlite3_free(zIns);
2993     return 0;
2994   }else{
2995     printSchemaLine(p->out, zSql, ";\n");
2996   }
2997
2998   if( strcmp(zType, "table")==0 ){
2999     ShellText sSelect;
3000     ShellText sTable;
3001     char **azCol;
3002     int i;
3003     char *savedDestTable;
3004     int savedMode;
3005
3006     azCol = tableColumnList(p, zTable);
3007     if( azCol==0 ){
3008       p->nErr++;
3009       return 0;
3010     }
3011
3012     /* Always quote the table name, even if it appears to be pure ascii,
3013     ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3014     initText(&sTable);
3015     appendText(&sTable, zTable, quoteChar(zTable));
3016     /* If preserving the rowid, add a column list after the table name.
3017     ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3018     ** instead of the usual "INSERT INTO tab VALUES(...)".
3019     */
3020     if( azCol[0] ){
3021       appendText(&sTable, "(", 0);
3022       appendText(&sTable, azCol[0], 0);
3023       for(i=1; azCol[i]; i++){
3024         appendText(&sTable, ",", 0);
3025         appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3026       }
3027       appendText(&sTable, ")", 0);
3028     }
3029
3030     /* Build an appropriate SELECT statement */
3031     initText(&sSelect);
3032     appendText(&sSelect, "SELECT ", 0);
3033     if( azCol[0] ){
3034       appendText(&sSelect, azCol[0], 0);
3035       appendText(&sSelect, ",", 0);
3036     }
3037     for(i=1; azCol[i]; i++){
3038       appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3039       if( azCol[i+1] ){
3040         appendText(&sSelect, ",", 0);
3041       }
3042     }
3043     freeColumnList(azCol);
3044     appendText(&sSelect, " FROM ", 0);
3045     appendText(&sSelect, zTable, quoteChar(zTable));
3046
3047     savedDestTable = p->zDestTable;
3048     savedMode = p->mode;
3049     p->zDestTable = sTable.z;
3050     p->mode = p->cMode = MODE_Insert;
3051     rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3052     if( (rc&0xff)==SQLITE_CORRUPT ){
3053       raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3054       toggleSelectOrder(p->db);
3055       shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3056       toggleSelectOrder(p->db);
3057     }
3058     p->zDestTable = savedDestTable;
3059     p->mode = savedMode;
3060     freeText(&sTable);
3061     freeText(&sSelect);
3062     if( rc ) p->nErr++;
3063   }
3064   return 0;
3065 }
3066
3067 /*
3068 ** Run zQuery.  Use dump_callback() as the callback routine so that
3069 ** the contents of the query are output as SQL statements.
3070 **
3071 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3072 ** "ORDER BY rowid DESC" to the end.
3073 */
3074 static int run_schema_dump_query(
3075   ShellState *p,
3076   const char *zQuery
3077 ){
3078   int rc;
3079   char *zErr = 0;
3080   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3081   if( rc==SQLITE_CORRUPT ){
3082     char *zQ2;
3083     int len = strlen30(zQuery);
3084     raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3085     if( zErr ){
3086       utf8_printf(p->out, "/****** %s ******/\n", zErr);
3087       sqlite3_free(zErr);
3088       zErr = 0;
3089     }
3090     zQ2 = malloc( len+100 );
3091     if( zQ2==0 ) return rc;
3092     sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3093     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3094     if( rc ){
3095       utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3096     }else{
3097       rc = SQLITE_CORRUPT;
3098     }
3099     sqlite3_free(zErr);
3100     free(zQ2);
3101   }
3102   return rc;
3103 }
3104
3105 /*
3106 ** Text of a help message
3107 */
3108 static char zHelp[] =
3109 #ifndef SQLITE_OMIT_AUTHORIZATION
3110   ".auth ON|OFF           Show authorizer callbacks\n"
3111 #endif
3112   ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
3113   ".bail on|off           Stop after hitting an error.  Default OFF\n"
3114   ".binary on|off         Turn binary output on or off.  Default OFF\n"
3115   ".changes on|off        Show number of rows changed by SQL\n"
3116   ".check GLOB            Fail if output since .testcase does not match\n"
3117   ".clone NEWDB           Clone data into NEWDB from the existing database\n"
3118   ".databases             List names and files of attached databases\n"
3119   ".dbinfo ?DB?           Show status information about the database\n"
3120   ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
3121   "                         If TABLE specified, only dump tables matching\n"
3122   "                         LIKE pattern TABLE.\n"
3123   ".echo on|off           Turn command echo on or off\n"
3124   ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
3125   ".exit                  Exit this program\n"
3126   ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
3127   ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3128   ".headers on|off        Turn display of headers on or off\n"
3129   ".help                  Show this message\n"
3130   ".import FILE TABLE     Import data from FILE into TABLE\n"
3131 #ifndef SQLITE_OMIT_TEST_CONTROL
3132   ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
3133 #endif
3134   ".indexes ?TABLE?       Show names of all indexes\n"
3135   "                         If TABLE specified, only show indexes for tables\n"
3136   "                         matching LIKE pattern TABLE.\n"
3137 #ifdef SQLITE_ENABLE_IOTRACE
3138   ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
3139 #endif
3140   ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
3141   ".lint OPTIONS          Report potential schema issues. Options:\n"
3142   "                         fkey-indexes     Find missing foreign key indexes\n"
3143 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3144   ".load FILE ?ENTRY?     Load an extension library\n"
3145 #endif
3146   ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
3147   ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
3148   "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
3149   "                         csv      Comma-separated values\n"
3150   "                         column   Left-aligned columns.  (See .width)\n"
3151   "                         html     HTML <table> code\n"
3152   "                         insert   SQL insert statements for TABLE\n"
3153   "                         line     One value per line\n"
3154   "                         list     Values delimited by \"|\"\n"
3155   "                         quote    Escape answers as for SQL\n"
3156   "                         tabs     Tab-separated values\n"
3157   "                         tcl      TCL list elements\n"
3158   ".nullvalue STRING      Use STRING in place of NULL values\n"
3159   ".once FILENAME         Output for the next SQL command only to FILENAME\n"
3160   ".open ?--new? ?FILE?   Close existing database and reopen FILE\n"
3161   "                         The --new starts with an empty file\n"
3162   ".output ?FILENAME?     Send output to FILENAME or stdout\n"
3163   ".print STRING...       Print literal STRING\n"
3164   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
3165   ".quit                  Exit this program\n"
3166   ".read FILENAME         Execute SQL in FILENAME\n"
3167   ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
3168   ".save FILE             Write in-memory database into FILE\n"
3169   ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3170   ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
3171   "                          Add --indent for pretty-printing\n"
3172   ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
3173   ".separator COL ?ROW?   Change the column separator and optionally the row\n"
3174   "                         separator for both the output mode and .import\n"
3175 #if defined(SQLITE_ENABLE_SESSION)
3176   ".session CMD ...       Create or control sessions\n"
3177 #endif
3178   ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
3179   ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
3180   ".show                  Show the current values for various settings\n"
3181   ".stats ?on|off?        Show stats or turn stats on or off\n"
3182   ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
3183   ".tables ?TABLE?        List names of tables\n"
3184   "                         If TABLE specified, only list tables matching\n"
3185   "                         LIKE pattern TABLE.\n"
3186   ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
3187   ".timeout MS            Try opening locked tables for MS milliseconds\n"
3188   ".timer on|off          Turn SQL timer on or off\n"
3189   ".trace FILE|off        Output each SQL statement as it is run\n"
3190   ".vfsinfo ?AUX?         Information about the top-level VFS\n"
3191   ".vfslist               List all available VFSes\n"
3192   ".vfsname ?AUX?         Print the name of the VFS stack\n"
3193   ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
3194   "                         Negative values right-justify\n"
3195 ;
3196
3197 #if defined(SQLITE_ENABLE_SESSION)
3198 /*
3199 ** Print help information for the ".sessions" command
3200 */
3201 void session_help(ShellState *p){
3202   raw_printf(p->out,
3203     ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3204     "If ?NAME? is omitted, the first defined session is used.\n"
3205     "Subcommands:\n"
3206     "   attach TABLE             Attach TABLE\n"
3207     "   changeset FILE           Write a changeset into FILE\n"
3208     "   close                    Close one session\n"
3209     "   enable ?BOOLEAN?         Set or query the enable bit\n"
3210     "   filter GLOB...           Reject tables matching GLOBs\n"
3211     "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
3212     "   isempty                  Query whether the session is empty\n"
3213     "   list                     List currently open session names\n"
3214     "   open DB NAME             Open a new session on DB\n"
3215     "   patchset FILE            Write a patchset into FILE\n"
3216   );
3217 }
3218 #endif
3219
3220
3221 /* Forward reference */
3222 static int process_input(ShellState *p, FILE *in);
3223
3224 /*
3225 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3226 ** and return a pointer to the buffer. The caller is responsible for freeing 
3227 ** the memory. 
3228 **
3229 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3230 ** read.
3231 **
3232 ** For convenience, a nul-terminator byte is always appended to the data read
3233 ** from the file before the buffer is returned. This byte is not included in
3234 ** the final value of (*pnByte), if applicable.
3235 **
3236 ** NULL is returned if any error is encountered. The final value of *pnByte
3237 ** is undefined in this case.
3238 */
3239 static char *readFile(const char *zName, int *pnByte){
3240   FILE *in = fopen(zName, "rb");
3241   long nIn;
3242   size_t nRead;
3243   char *pBuf;
3244   if( in==0 ) return 0;
3245   fseek(in, 0, SEEK_END);
3246   nIn = ftell(in);
3247   rewind(in);
3248   pBuf = sqlite3_malloc64( nIn+1 );
3249   if( pBuf==0 ) return 0;
3250   nRead = fread(pBuf, nIn, 1, in);
3251   fclose(in);
3252   if( nRead!=1 ){
3253     sqlite3_free(pBuf);
3254     return 0;
3255   }
3256   pBuf[nIn] = 0;
3257   if( pnByte ) *pnByte = nIn;
3258   return pBuf;
3259 }
3260
3261 /*
3262 ** Implementation of the "readfile(X)" SQL function.  The entire content
3263 ** of the file named X is read and returned as a BLOB.  NULL is returned
3264 ** if the file does not exist or is unreadable.
3265 */
3266 static void readfileFunc(
3267   sqlite3_context *context,
3268   int argc,
3269   sqlite3_value **argv
3270 ){
3271   const char *zName;
3272   void *pBuf;
3273   int nBuf;
3274
3275   UNUSED_PARAMETER(argc);
3276   zName = (const char*)sqlite3_value_text(argv[0]);
3277   if( zName==0 ) return;
3278   pBuf = readFile(zName, &nBuf);
3279   if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
3280 }
3281
3282 /*
3283 ** Implementation of the "writefile(X,Y)" SQL function.  The argument Y
3284 ** is written into file X.  The number of bytes written is returned.  Or
3285 ** NULL is returned if something goes wrong, such as being unable to open
3286 ** file X for writing.
3287 */
3288 static void writefileFunc(
3289   sqlite3_context *context,
3290   int argc,
3291   sqlite3_value **argv
3292 ){
3293   FILE *out;
3294   const char *z;
3295   sqlite3_int64 rc;
3296   const char *zFile;
3297
3298   UNUSED_PARAMETER(argc);
3299   zFile = (const char*)sqlite3_value_text(argv[0]);
3300   if( zFile==0 ) return;
3301   out = fopen(zFile, "wb");
3302   if( out==0 ) return;
3303   z = (const char*)sqlite3_value_blob(argv[1]);
3304   if( z==0 ){
3305     rc = 0;
3306   }else{
3307     rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
3308   }
3309   fclose(out);
3310   sqlite3_result_int64(context, rc);
3311 }
3312
3313 #if defined(SQLITE_ENABLE_SESSION)
3314 /*
3315 ** Close a single OpenSession object and release all of its associated
3316 ** resources.
3317 */
3318 static void session_close(OpenSession *pSession){
3319   int i;
3320   sqlite3session_delete(pSession->p);
3321   sqlite3_free(pSession->zName);
3322   for(i=0; i<pSession->nFilter; i++){
3323     sqlite3_free(pSession->azFilter[i]);
3324   }
3325   sqlite3_free(pSession->azFilter);
3326   memset(pSession, 0, sizeof(OpenSession));
3327 }
3328 #endif
3329
3330 /*
3331 ** Close all OpenSession objects and release all associated resources.
3332 */
3333 #if defined(SQLITE_ENABLE_SESSION)
3334 static void session_close_all(ShellState *p){
3335   int i;
3336   for(i=0; i<p->nSession; i++){
3337     session_close(&p->aSession[i]);
3338   }
3339   p->nSession = 0;
3340 }
3341 #else
3342 # define session_close_all(X)
3343 #endif
3344
3345 /*
3346 ** Implementation of the xFilter function for an open session.  Omit
3347 ** any tables named by ".session filter" but let all other table through.
3348 */
3349 #if defined(SQLITE_ENABLE_SESSION)
3350 static int session_filter(void *pCtx, const char *zTab){
3351   OpenSession *pSession = (OpenSession*)pCtx;
3352   int i;
3353   for(i=0; i<pSession->nFilter; i++){
3354     if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3355   }
3356   return 1;
3357 }
3358 #endif
3359
3360 /*
3361 ** Make sure the database is open.  If it is not, then open it.  If
3362 ** the database fails to open, print an error message and exit.
3363 */
3364 static void open_db(ShellState *p, int keepAlive){
3365   if( p->db==0 ){
3366     sqlite3_initialize();
3367     sqlite3_open(p->zDbFilename, &p->db);
3368     globalDb = p->db;
3369     if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3370       utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3371           p->zDbFilename, sqlite3_errmsg(p->db));
3372       if( keepAlive ) return;
3373       exit(1);
3374     }
3375 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3376     sqlite3_enable_load_extension(p->db, 1);
3377 #endif
3378     sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
3379                             readfileFunc, 0, 0);
3380     sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
3381                             writefileFunc, 0, 0);
3382     sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3383                             sha3Func, 0, 0);
3384     sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3385                             sha3Func, 0, 0);
3386     sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3387                             sha3QueryFunc, 0, 0);
3388     sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3389                             sha3QueryFunc, 0, 0);
3390   }
3391 }
3392
3393 /*
3394 ** Do C-language style dequoting.
3395 **
3396 **    \a    -> alarm
3397 **    \b    -> backspace
3398 **    \t    -> tab
3399 **    \n    -> newline
3400 **    \v    -> vertical tab
3401 **    \f    -> form feed
3402 **    \r    -> carriage return
3403 **    \s    -> space
3404 **    \"    -> "
3405 **    \'    -> '
3406 **    \\    -> backslash
3407 **    \NNN  -> ascii character NNN in octal
3408 */
3409 static void resolve_backslashes(char *z){
3410   int i, j;
3411   char c;
3412   while( *z && *z!='\\' ) z++;
3413   for(i=j=0; (c = z[i])!=0; i++, j++){
3414     if( c=='\\' && z[i+1]!=0 ){
3415       c = z[++i];
3416       if( c=='a' ){
3417         c = '\a';
3418       }else if( c=='b' ){
3419         c = '\b';
3420       }else if( c=='t' ){
3421         c = '\t';
3422       }else if( c=='n' ){
3423         c = '\n';
3424       }else if( c=='v' ){
3425         c = '\v';
3426       }else if( c=='f' ){
3427         c = '\f';
3428       }else if( c=='r' ){
3429         c = '\r';
3430       }else if( c=='"' ){
3431         c = '"';
3432       }else if( c=='\'' ){
3433         c = '\'';
3434       }else if( c=='\\' ){
3435         c = '\\';
3436       }else if( c>='0' && c<='7' ){
3437         c -= '0';
3438         if( z[i+1]>='0' && z[i+1]<='7' ){
3439           i++;
3440           c = (c<<3) + z[i] - '0';
3441           if( z[i+1]>='0' && z[i+1]<='7' ){
3442             i++;
3443             c = (c<<3) + z[i] - '0';
3444           }
3445         }
3446       }
3447     }
3448     z[j] = c;
3449   }
3450   if( j<i ) z[j] = 0;
3451 }
3452
3453 /*
3454 ** Return the value of a hexadecimal digit.  Return -1 if the input
3455 ** is not a hex digit.
3456 */
3457 static int hexDigitValue(char c){
3458   if( c>='0' && c<='9' ) return c - '0';
3459   if( c>='a' && c<='f' ) return c - 'a' + 10;
3460   if( c>='A' && c<='F' ) return c - 'A' + 10;
3461   return -1;
3462 }
3463
3464 /*
3465 ** Interpret zArg as an integer value, possibly with suffixes.
3466 */
3467 static sqlite3_int64 integerValue(const char *zArg){
3468   sqlite3_int64 v = 0;
3469   static const struct { char *zSuffix; int iMult; } aMult[] = {
3470     { "KiB", 1024 },
3471     { "MiB", 1024*1024 },
3472     { "GiB", 1024*1024*1024 },
3473     { "KB",  1000 },
3474     { "MB",  1000000 },
3475     { "GB",  1000000000 },
3476     { "K",   1000 },
3477     { "M",   1000000 },
3478     { "G",   1000000000 },
3479   };
3480   int i;
3481   int isNeg = 0;
3482   if( zArg[0]=='-' ){
3483     isNeg = 1;
3484     zArg++;
3485   }else if( zArg[0]=='+' ){
3486     zArg++;
3487   }
3488   if( zArg[0]=='0' && zArg[1]=='x' ){
3489     int x;
3490     zArg += 2;
3491     while( (x = hexDigitValue(zArg[0]))>=0 ){
3492       v = (v<<4) + x;
3493       zArg++;
3494     }
3495   }else{
3496     while( IsDigit(zArg[0]) ){
3497       v = v*10 + zArg[0] - '0';
3498       zArg++;
3499     }
3500   }
3501   for(i=0; i<ArraySize(aMult); i++){
3502     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3503       v *= aMult[i].iMult;
3504       break;
3505     }
3506   }
3507   return isNeg? -v : v;
3508 }
3509
3510 /*
3511 ** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
3512 ** for TRUE and FALSE.  Return the integer value if appropriate.
3513 */
3514 static int booleanValue(const char *zArg){
3515   int i;
3516   if( zArg[0]=='0' && zArg[1]=='x' ){
3517     for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3518   }else{
3519     for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3520   }
3521   if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3522   if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3523     return 1;
3524   }
3525   if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3526     return 0;
3527   }
3528   utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3529           zArg);
3530   return 0;
3531 }
3532
3533 /*
3534 ** Set or clear a shell flag according to a boolean value.
3535 */
3536 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3537   if( booleanValue(zArg) ){
3538     ShellSetFlag(p, mFlag);
3539   }else{
3540     ShellClearFlag(p, mFlag);
3541   }
3542 }
3543
3544 /*
3545 ** Close an output file, assuming it is not stderr or stdout
3546 */
3547 static void output_file_close(FILE *f){
3548   if( f && f!=stdout && f!=stderr ) fclose(f);
3549 }
3550
3551 /*
3552 ** Try to open an output file.   The names "stdout" and "stderr" are
3553 ** recognized and do the right thing.  NULL is returned if the output
3554 ** filename is "off".
3555 */
3556 static FILE *output_file_open(const char *zFile){
3557   FILE *f;
3558   if( strcmp(zFile,"stdout")==0 ){
3559     f = stdout;
3560   }else if( strcmp(zFile, "stderr")==0 ){
3561     f = stderr;
3562   }else if( strcmp(zFile, "off")==0 ){
3563     f = 0;
3564   }else{
3565     f = fopen(zFile, "wb");
3566     if( f==0 ){
3567       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3568     }
3569   }
3570   return f;
3571 }
3572
3573 #if !defined(SQLITE_UNTESTABLE)
3574 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3575 /*
3576 ** A routine for handling output from sqlite3_trace().
3577 */
3578 static int sql_trace_callback(
3579   unsigned mType,
3580   void *pArg,
3581   void *pP,
3582   void *pX
3583 ){
3584   FILE *f = (FILE*)pArg;
3585   UNUSED_PARAMETER(mType);
3586   UNUSED_PARAMETER(pP);
3587   if( f ){
3588     const char *z = (const char*)pX;
3589     int i = (int)strlen(z);
3590     while( i>0 && z[i-1]==';' ){ i--; }
3591     utf8_printf(f, "%.*s;\n", i, z);
3592   }
3593   return 0;
3594 }
3595 #endif
3596 #endif
3597
3598 /*
3599 ** A no-op routine that runs with the ".breakpoint" doc-command.  This is
3600 ** a useful spot to set a debugger breakpoint.
3601 */
3602 static void test_breakpoint(void){
3603   static int nCall = 0;
3604   nCall++;
3605 }
3606
3607 /*
3608 ** An object used to read a CSV and other files for import.
3609 */
3610 typedef struct ImportCtx ImportCtx;
3611 struct ImportCtx {
3612   const char *zFile;  /* Name of the input file */
3613   FILE *in;           /* Read the CSV text from this input stream */
3614   char *z;            /* Accumulated text for a field */
3615   int n;              /* Number of bytes in z */
3616   int nAlloc;         /* Space allocated for z[] */
3617   int nLine;          /* Current line number */
3618   int cTerm;          /* Character that terminated the most recent field */
3619   int cColSep;        /* The column separator character.  (Usually ",") */
3620   int cRowSep;        /* The row separator character.  (Usually "\n") */
3621 };
3622
3623 /* Append a single byte to z[] */
3624 static void import_append_char(ImportCtx *p, int c){
3625   if( p->n+1>=p->nAlloc ){
3626     p->nAlloc += p->nAlloc + 100;
3627     p->z = sqlite3_realloc64(p->z, p->nAlloc);
3628     if( p->z==0 ){
3629       raw_printf(stderr, "out of memory\n");
3630       exit(1);
3631     }
3632   }
3633   p->z[p->n++] = (char)c;
3634 }
3635
3636 /* Read a single field of CSV text.  Compatible with rfc4180 and extended
3637 ** with the option of having a separator other than ",".
3638 **
3639 **   +  Input comes from p->in.
3640 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
3641 **      from sqlite3_malloc64().
3642 **   +  Use p->cSep as the column separator.  The default is ",".
3643 **   +  Use p->rSep as the row separator.  The default is "\n".
3644 **   +  Keep track of the line number in p->nLine.
3645 **   +  Store the character that terminates the field in p->cTerm.  Store
3646 **      EOF on end-of-file.
3647 **   +  Report syntax errors on stderr
3648 */
3649 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3650   int c;
3651   int cSep = p->cColSep;
3652   int rSep = p->cRowSep;
3653   p->n = 0;
3654   c = fgetc(p->in);
3655   if( c==EOF || seenInterrupt ){
3656     p->cTerm = EOF;
3657     return 0;
3658   }
3659   if( c=='"' ){
3660     int pc, ppc;
3661     int startLine = p->nLine;
3662     int cQuote = c;
3663     pc = ppc = 0;
3664     while( 1 ){
3665       c = fgetc(p->in);
3666       if( c==rSep ) p->nLine++;
3667       if( c==cQuote ){
3668         if( pc==cQuote ){
3669           pc = 0;
3670           continue;
3671         }
3672       }
3673       if( (c==cSep && pc==cQuote)
3674        || (c==rSep && pc==cQuote)
3675        || (c==rSep && pc=='\r' && ppc==cQuote)
3676        || (c==EOF && pc==cQuote)
3677       ){
3678         do{ p->n--; }while( p->z[p->n]!=cQuote );
3679         p->cTerm = c;
3680         break;
3681       }
3682       if( pc==cQuote && c!='\r' ){
3683         utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3684                 p->zFile, p->nLine, cQuote);
3685       }
3686       if( c==EOF ){
3687         utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3688                 p->zFile, startLine, cQuote);
3689         p->cTerm = c;
3690         break;
3691       }
3692       import_append_char(p, c);
3693       ppc = pc;
3694       pc = c;
3695     }
3696   }else{
3697     while( c!=EOF && c!=cSep && c!=rSep ){
3698       import_append_char(p, c);
3699       c = fgetc(p->in);
3700     }
3701     if( c==rSep ){
3702       p->nLine++;
3703       if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3704     }
3705     p->cTerm = c;
3706   }
3707   if( p->z ) p->z[p->n] = 0;
3708   return p->z;
3709 }
3710
3711 /* Read a single field of ASCII delimited text.
3712 **
3713 **   +  Input comes from p->in.
3714 **   +  Store results in p->z of length p->n.  Space to hold p->z comes
3715 **      from sqlite3_malloc64().
3716 **   +  Use p->cSep as the column separator.  The default is "\x1F".
3717 **   +  Use p->rSep as the row separator.  The default is "\x1E".
3718 **   +  Keep track of the row number in p->nLine.
3719 **   +  Store the character that terminates the field in p->cTerm.  Store
3720 **      EOF on end-of-file.
3721 **   +  Report syntax errors on stderr
3722 */
3723 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3724   int c;
3725   int cSep = p->cColSep;
3726   int rSep = p->cRowSep;
3727   p->n = 0;
3728   c = fgetc(p->in);
3729   if( c==EOF || seenInterrupt ){
3730     p->cTerm = EOF;
3731     return 0;
3732   }
3733   while( c!=EOF && c!=cSep && c!=rSep ){
3734     import_append_char(p, c);
3735     c = fgetc(p->in);
3736   }
3737   if( c==rSep ){
3738     p->nLine++;
3739   }
3740   p->cTerm = c;
3741   if( p->z ) p->z[p->n] = 0;
3742   return p->z;
3743 }
3744
3745 /*
3746 ** Try to transfer data for table zTable.  If an error is seen while
3747 ** moving forward, try to go backwards.  The backwards movement won't
3748 ** work for WITHOUT ROWID tables.
3749 */
3750 static void tryToCloneData(
3751   ShellState *p,
3752   sqlite3 *newDb,
3753   const char *zTable
3754 ){
3755   sqlite3_stmt *pQuery = 0;
3756   sqlite3_stmt *pInsert = 0;
3757   char *zQuery = 0;
3758   char *zInsert = 0;
3759   int rc;
3760   int i, j, n;
3761   int nTable = (int)strlen(zTable);
3762   int k = 0;
3763   int cnt = 0;
3764   const int spinRate = 10000;
3765
3766   zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3767   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3768   if( rc ){
3769     utf8_printf(stderr, "Error %d: %s on [%s]\n",
3770             sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3771             zQuery);
3772     goto end_data_xfer;
3773   }
3774   n = sqlite3_column_count(pQuery);
3775   zInsert = sqlite3_malloc64(200 + nTable + n*3);
3776   if( zInsert==0 ){
3777     raw_printf(stderr, "out of memory\n");
3778     goto end_data_xfer;
3779   }
3780   sqlite3_snprintf(200+nTable,zInsert,
3781                    "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3782   i = (int)strlen(zInsert);
3783   for(j=1; j<n; j++){
3784     memcpy(zInsert+i, ",?", 2);
3785     i += 2;
3786   }
3787   memcpy(zInsert+i, ");", 3);
3788   rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3789   if( rc ){
3790     utf8_printf(stderr, "Error %d: %s on [%s]\n",
3791             sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3792             zQuery);
3793     goto end_data_xfer;
3794   }
3795   for(k=0; k<2; k++){
3796     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3797       for(i=0; i<n; i++){
3798         switch( sqlite3_column_type(pQuery, i) ){
3799           case SQLITE_NULL: {
3800             sqlite3_bind_null(pInsert, i+1);
3801             break;
3802           }
3803           case SQLITE_INTEGER: {
3804             sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3805             break;
3806           }
3807           case SQLITE_FLOAT: {
3808             sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3809             break;
3810           }
3811           case SQLITE_TEXT: {
3812             sqlite3_bind_text(pInsert, i+1,
3813                              (const char*)sqlite3_column_text(pQuery,i),
3814                              -1, SQLITE_STATIC);
3815             break;
3816           }
3817           case SQLITE_BLOB: {
3818             sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3819                                             sqlite3_column_bytes(pQuery,i),
3820                                             SQLITE_STATIC);
3821             break;
3822           }
3823         }
3824       } /* End for */
3825       rc = sqlite3_step(pInsert);
3826       if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3827         utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3828                         sqlite3_errmsg(newDb));
3829       }
3830       sqlite3_reset(pInsert);
3831       cnt++;
3832       if( (cnt%spinRate)==0 ){
3833         printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3834         fflush(stdout);
3835       }
3836     } /* End while */
3837     if( rc==SQLITE_DONE ) break;
3838     sqlite3_finalize(pQuery);
3839     sqlite3_free(zQuery);
3840     zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3841                              zTable);
3842     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3843     if( rc ){
3844       utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3845       break;
3846     }
3847   } /* End for(k=0...) */
3848
3849 end_data_xfer:
3850   sqlite3_finalize(pQuery);
3851   sqlite3_finalize(pInsert);
3852   sqlite3_free(zQuery);
3853   sqlite3_free(zInsert);
3854 }
3855
3856
3857 /*
3858 ** Try to transfer all rows of the schema that match zWhere.  For
3859 ** each row, invoke xForEach() on the object defined by that row.
3860 ** If an error is encountered while moving forward through the
3861 ** sqlite_master table, try again moving backwards.
3862 */
3863 static void tryToCloneSchema(
3864   ShellState *p,
3865   sqlite3 *newDb,
3866   const char *zWhere,
3867   void (*xForEach)(ShellState*,sqlite3*,const char*)
3868 ){
3869   sqlite3_stmt *pQuery = 0;
3870   char *zQuery = 0;
3871   int rc;
3872   const unsigned char *zName;
3873   const unsigned char *zSql;
3874   char *zErrMsg = 0;
3875
3876   zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3877                            " WHERE %s", zWhere);
3878   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3879   if( rc ){
3880     utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3881                     sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3882                     zQuery);
3883     goto end_schema_xfer;
3884   }
3885   while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3886     zName = sqlite3_column_text(pQuery, 0);
3887     zSql = sqlite3_column_text(pQuery, 1);
3888     printf("%s... ", zName); fflush(stdout);
3889     sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3890     if( zErrMsg ){
3891       utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3892       sqlite3_free(zErrMsg);
3893       zErrMsg = 0;
3894     }
3895     if( xForEach ){
3896       xForEach(p, newDb, (const char*)zName);
3897     }
3898     printf("done\n");
3899   }
3900   if( rc!=SQLITE_DONE ){
3901     sqlite3_finalize(pQuery);
3902     sqlite3_free(zQuery);
3903     zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3904                              " WHERE %s ORDER BY rowid DESC", zWhere);
3905     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3906     if( rc ){
3907       utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3908                       sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3909                       zQuery);
3910       goto end_schema_xfer;
3911     }
3912     while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3913       zName = sqlite3_column_text(pQuery, 0);
3914       zSql = sqlite3_column_text(pQuery, 1);
3915       printf("%s... ", zName); fflush(stdout);
3916       sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3917       if( zErrMsg ){
3918         utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3919         sqlite3_free(zErrMsg);
3920         zErrMsg = 0;
3921       }
3922       if( xForEach ){
3923         xForEach(p, newDb, (const char*)zName);
3924       }
3925       printf("done\n");
3926     }
3927   }
3928 end_schema_xfer:
3929   sqlite3_finalize(pQuery);
3930   sqlite3_free(zQuery);
3931 }
3932
3933 /*
3934 ** Open a new database file named "zNewDb".  Try to recover as much information
3935 ** as possible out of the main database (which might be corrupt) and write it
3936 ** into zNewDb.
3937 */
3938 static void tryToClone(ShellState *p, const char *zNewDb){
3939   int rc;
3940   sqlite3 *newDb = 0;
3941   if( access(zNewDb,0)==0 ){
3942     utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3943     return;
3944   }
3945   rc = sqlite3_open(zNewDb, &newDb);
3946   if( rc ){
3947     utf8_printf(stderr, "Cannot create output database: %s\n",
3948             sqlite3_errmsg(newDb));
3949   }else{
3950     sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3951     sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3952     tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3953     tryToCloneSchema(p, newDb, "type!='table'", 0);
3954     sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3955     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3956   }
3957   sqlite3_close(newDb);
3958 }
3959
3960 /*
3961 ** Change the output file back to stdout
3962 */
3963 static void output_reset(ShellState *p){
3964   if( p->outfile[0]=='|' ){
3965 #ifndef SQLITE_OMIT_POPEN
3966     pclose(p->out);
3967 #endif
3968   }else{
3969     output_file_close(p->out);
3970   }
3971   p->outfile[0] = 0;
3972   p->out = stdout;
3973 }
3974
3975 /*
3976 ** Run an SQL command and return the single integer result.
3977 */
3978 static int db_int(ShellState *p, const char *zSql){
3979   sqlite3_stmt *pStmt;
3980   int res = 0;
3981   sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3982   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3983     res = sqlite3_column_int(pStmt,0);
3984   }
3985   sqlite3_finalize(pStmt);
3986   return res;
3987 }
3988
3989 /*
3990 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3991 */
3992 static unsigned int get2byteInt(unsigned char *a){
3993   return (a[0]<<8) + a[1];
3994 }
3995 static unsigned int get4byteInt(unsigned char *a){
3996   return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3997 }
3998
3999 /*
4000 ** Implementation of the ".info" command.
4001 **
4002 ** Return 1 on error, 2 to exit, and 0 otherwise.
4003 */
4004 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4005   static const struct { const char *zName; int ofst; } aField[] = {
4006      { "file change counter:",  24  },
4007      { "database page count:",  28  },
4008      { "freelist page count:",  36  },
4009      { "schema cookie:",        40  },
4010      { "schema format:",        44  },
4011      { "default cache size:",   48  },
4012      { "autovacuum top root:",  52  },
4013      { "incremental vacuum:",   64  },
4014      { "text encoding:",        56  },
4015      { "user version:",         60  },
4016      { "application id:",       68  },
4017      { "software version:",     96  },
4018   };
4019   static const struct { const char *zName; const char *zSql; } aQuery[] = {
4020      { "number of tables:",
4021        "SELECT count(*) FROM %s WHERE type='table'" },
4022      { "number of indexes:",
4023        "SELECT count(*) FROM %s WHERE type='index'" },
4024      { "number of triggers:",
4025        "SELECT count(*) FROM %s WHERE type='trigger'" },
4026      { "number of views:",
4027        "SELECT count(*) FROM %s WHERE type='view'" },
4028      { "schema size:",
4029        "SELECT total(length(sql)) FROM %s" },
4030   };
4031   sqlite3_file *pFile = 0;
4032   int i;
4033   char *zSchemaTab;
4034   char *zDb = nArg>=2 ? azArg[1] : "main";
4035   unsigned char aHdr[100];
4036   open_db(p, 0);
4037   if( p->db==0 ) return 1;
4038   sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
4039   if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4040     return 1;
4041   }
4042   i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4043   if( i!=SQLITE_OK ){
4044     raw_printf(stderr, "unable to read database header\n");
4045     return 1;
4046   }
4047   i = get2byteInt(aHdr+16);
4048   if( i==1 ) i = 65536;
4049   utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4050   utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4051   utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4052   utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4053   for(i=0; i<ArraySize(aField); i++){
4054     int ofst = aField[i].ofst;
4055     unsigned int val = get4byteInt(aHdr + ofst);
4056     utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4057     switch( ofst ){
4058       case 56: {
4059         if( val==1 ) raw_printf(p->out, " (utf8)");
4060         if( val==2 ) raw_printf(p->out, " (utf16le)");
4061         if( val==3 ) raw_printf(p->out, " (utf16be)");
4062       }
4063     }
4064     raw_printf(p->out, "\n");
4065   }
4066   if( zDb==0 ){
4067     zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4068   }else if( strcmp(zDb,"temp")==0 ){
4069     zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4070   }else{
4071     zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4072   }
4073   for(i=0; i<ArraySize(aQuery); i++){
4074     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4075     int val = db_int(p, zSql);
4076     sqlite3_free(zSql);
4077     utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4078   }
4079   sqlite3_free(zSchemaTab);
4080   return 0;
4081 }
4082
4083 /*
4084 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4085 */
4086 static int shellDatabaseError(sqlite3 *db){
4087   const char *zErr = sqlite3_errmsg(db);
4088   utf8_printf(stderr, "Error: %s\n", zErr);
4089   return 1;
4090 }
4091
4092 /*
4093 ** Print an out-of-memory message to stderr and return 1.
4094 */
4095 static int shellNomemError(void){
4096   raw_printf(stderr, "Error: out of memory\n");
4097   return 1;
4098 }
4099
4100 /*
4101 ** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
4102 ** if they match and FALSE (0) if they do not match.
4103 **
4104 ** Globbing rules:
4105 **
4106 **      '*'       Matches any sequence of zero or more characters.
4107 **
4108 **      '?'       Matches exactly one character.
4109 **
4110 **     [...]      Matches one character from the enclosed list of
4111 **                characters.
4112 **
4113 **     [^...]     Matches one character not in the enclosed list.
4114 **
4115 **      '#'       Matches any sequence of one or more digits with an
4116 **                optional + or - sign in front
4117 **
4118 **      ' '       Any span of whitespace matches any other span of
4119 **                whitespace.
4120 **
4121 ** Extra whitespace at the end of z[] is ignored.
4122 */
4123 static int testcase_glob(const char *zGlob, const char *z){
4124   int c, c2;
4125   int invert;
4126   int seen;
4127
4128   while( (c = (*(zGlob++)))!=0 ){
4129     if( IsSpace(c) ){
4130       if( !IsSpace(*z) ) return 0;
4131       while( IsSpace(*zGlob) ) zGlob++;
4132       while( IsSpace(*z) ) z++;
4133     }else if( c=='*' ){
4134       while( (c=(*(zGlob++))) == '*' || c=='?' ){
4135         if( c=='?' && (*(z++))==0 ) return 0;
4136       }
4137       if( c==0 ){
4138         return 1;
4139       }else if( c=='[' ){
4140         while( *z && testcase_glob(zGlob-1,z)==0 ){
4141           z++;
4142         }
4143         return (*z)!=0;
4144       }
4145       while( (c2 = (*(z++)))!=0 ){
4146         while( c2!=c ){
4147           c2 = *(z++);
4148           if( c2==0 ) return 0;
4149         }
4150         if( testcase_glob(zGlob,z) ) return 1;
4151       }
4152       return 0;
4153     }else if( c=='?' ){
4154       if( (*(z++))==0 ) return 0;
4155     }else if( c=='[' ){
4156       int prior_c = 0;
4157       seen = 0;
4158       invert = 0;
4159       c = *(z++);
4160       if( c==0 ) return 0;
4161       c2 = *(zGlob++);
4162       if( c2=='^' ){
4163         invert = 1;
4164         c2 = *(zGlob++);
4165       }
4166       if( c2==']' ){
4167         if( c==']' ) seen = 1;
4168         c2 = *(zGlob++);
4169       }
4170       while( c2 && c2!=']' ){
4171         if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4172           c2 = *(zGlob++);
4173           if( c>=prior_c && c<=c2 ) seen = 1;
4174           prior_c = 0;
4175         }else{
4176           if( c==c2 ){
4177             seen = 1;
4178           }
4179           prior_c = c2;
4180         }
4181         c2 = *(zGlob++);
4182       }
4183       if( c2==0 || (seen ^ invert)==0 ) return 0;
4184     }else if( c=='#' ){
4185       if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4186       if( !IsDigit(z[0]) ) return 0;
4187       z++;
4188       while( IsDigit(z[0]) ){ z++; }
4189     }else{
4190       if( c!=(*(z++)) ) return 0;
4191     }
4192   }
4193   while( IsSpace(*z) ){ z++; }
4194   return *z==0;
4195 }
4196
4197
4198 /*
4199 ** Compare the string as a command-line option with either one or two
4200 ** initial "-" characters.
4201 */
4202 static int optionMatch(const char *zStr, const char *zOpt){
4203   if( zStr[0]!='-' ) return 0;
4204   zStr++;
4205   if( zStr[0]=='-' ) zStr++;
4206   return strcmp(zStr, zOpt)==0;
4207 }
4208
4209 /*
4210 ** Delete a file.
4211 */
4212 int shellDeleteFile(const char *zFilename){
4213   int rc;
4214 #ifdef _WIN32
4215   wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4216   rc = _wunlink(z);
4217   sqlite3_free(z);
4218 #else
4219   rc = unlink(zFilename);
4220 #endif
4221   return rc;
4222 }
4223
4224
4225 /*
4226 ** The implementation of SQL scalar function fkey_collate_clause(), used
4227 ** by the ".lint fkey-indexes" command. This scalar function is always
4228 ** called with four arguments - the parent table name, the parent column name,
4229 ** the child table name and the child column name.
4230 **
4231 **   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4232 **
4233 ** If either of the named tables or columns do not exist, this function
4234 ** returns an empty string. An empty string is also returned if both tables 
4235 ** and columns exist but have the same default collation sequence. Or,
4236 ** if both exist but the default collation sequences are different, this
4237 ** function returns the string " COLLATE <parent-collation>", where
4238 ** <parent-collation> is the default collation sequence of the parent column.
4239 */
4240 static void shellFkeyCollateClause(
4241   sqlite3_context *pCtx, 
4242   int nVal, 
4243   sqlite3_value **apVal
4244 ){
4245   sqlite3 *db = sqlite3_context_db_handle(pCtx);
4246   const char *zParent;
4247   const char *zParentCol;
4248   const char *zParentSeq;
4249   const char *zChild;
4250   const char *zChildCol;
4251   const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
4252   int rc;
4253   
4254   assert( nVal==4 );
4255   zParent = (const char*)sqlite3_value_text(apVal[0]);
4256   zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4257   zChild = (const char*)sqlite3_value_text(apVal[2]);
4258   zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4259
4260   sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4261   rc = sqlite3_table_column_metadata(
4262       db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4263   );
4264   if( rc==SQLITE_OK ){
4265     rc = sqlite3_table_column_metadata(
4266         db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4267     );
4268   }
4269
4270   if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4271     char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4272     sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4273     sqlite3_free(z);
4274   }
4275 }
4276
4277
4278 /*
4279 ** The implementation of dot-command ".lint fkey-indexes".
4280 */
4281 static int lintFkeyIndexes(
4282   ShellState *pState,             /* Current shell tool state */
4283   char **azArg,                   /* Array of arguments passed to dot command */
4284   int nArg                        /* Number of entries in azArg[] */
4285 ){
4286   sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
4287   FILE *out = pState->out;        /* Stream to write non-error output to */
4288   int bVerbose = 0;               /* If -verbose is present */
4289   int bGroupByParent = 0;         /* If -groupbyparent is present */
4290   int i;                          /* To iterate through azArg[] */
4291   const char *zIndent = "";       /* How much to indent CREATE INDEX by */
4292   int rc;                         /* Return code */
4293   sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
4294
4295   /*
4296   ** This SELECT statement returns one row for each foreign key constraint
4297   ** in the schema of the main database. The column values are:
4298   **
4299   ** 0. The text of an SQL statement similar to:
4300   **
4301   **      "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4302   **
4303   **    This is the same SELECT that the foreign keys implementation needs
4304   **    to run internally on child tables. If there is an index that can
4305   **    be used to optimize this query, then it can also be used by the FK
4306   **    implementation to optimize DELETE or UPDATE statements on the parent
4307   **    table.
4308   **
4309   ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4310   **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4311   **    contains an index that can be used to optimize the query.
4312   **
4313   ** 2. Human readable text that describes the child table and columns. e.g.
4314   **
4315   **       "child_table(child_key1, child_key2)"
4316   **
4317   ** 3. Human readable text that describes the parent table and columns. e.g.
4318   **
4319   **       "parent_table(parent_key1, parent_key2)"
4320   **
4321   ** 4. A full CREATE INDEX statement for an index that could be used to
4322   **    optimize DELETE or UPDATE statements on the parent table. e.g.
4323   **
4324   **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
4325   **
4326   ** 5. The name of the parent table.
4327   **
4328   ** These six values are used by the C logic below to generate the report.
4329   */
4330   const char *zSql =
4331   "SELECT "
4332     "     'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4333     "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4334     "  || fkey_collate_clause(f.[table], f.[to], s.name, f.[from]),' AND ')"
4335     ", "
4336     "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4337     "  || group_concat('*=?', ' AND ') || ')'"
4338     ", "
4339     "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
4340     ", "
4341     "     f.[table] || '(' || group_concat(COALESCE(f.[to], "
4342     "       (SELECT name FROM pragma_table_info(f.[table]) WHERE pk=seq+1)"
4343     "     )) || ')'"
4344     ", "
4345     "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4346     "  || ' ON ' || quote(s.name) || '('"
4347     "  || group_concat(quote(f.[from]) ||"
4348     "        fkey_collate_clause(f.[table], f.[to], s.name, f.[from]), ', ')"
4349     "  || ');'"
4350     ", "
4351     "     f.[table] "
4352
4353     "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4354     "GROUP BY s.name, f.id "
4355     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4356   ;
4357
4358   for(i=2; i<nArg; i++){
4359     int n = (int)strlen(azArg[i]);
4360     if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4361       bVerbose = 1;
4362     }
4363     else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4364       bGroupByParent = 1;
4365       zIndent = "    ";
4366     }
4367     else{
4368       raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4369           azArg[0], azArg[1]
4370       );
4371       return SQLITE_ERROR;
4372     }
4373   }
4374   
4375   /* Register the fkey_collate_clause() SQL function */
4376   rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4377       0, shellFkeyCollateClause, 0, 0
4378   );
4379
4380
4381   if( rc==SQLITE_OK ){
4382     rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4383   }
4384   if( rc==SQLITE_OK ){
4385     sqlite3_bind_int(pSql, 1, bGroupByParent);
4386   }
4387
4388   if( rc==SQLITE_OK ){
4389     int rc2;
4390     char *zPrev = 0;
4391     while( SQLITE_ROW==sqlite3_step(pSql) ){
4392       int res = -1;
4393       sqlite3_stmt *pExplain = 0;
4394       const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4395       const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4396       const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4397       const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4398       const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4399       const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4400
4401       rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4402       if( rc!=SQLITE_OK ) break;
4403       if( SQLITE_ROW==sqlite3_step(pExplain) ){
4404         const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4405         res = (0==sqlite3_strglob(zGlob, zPlan));
4406       }
4407       rc = sqlite3_finalize(pExplain);
4408       if( rc!=SQLITE_OK ) break;
4409
4410       if( res<0 ){
4411         raw_printf(stderr, "Error: internal error");
4412         break;
4413       }else{
4414         if( bGroupByParent 
4415         && (bVerbose || res==0)
4416         && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 
4417         ){
4418           raw_printf(out, "-- Parent table %s\n", zParent);
4419           sqlite3_free(zPrev);
4420           zPrev = sqlite3_mprintf("%s", zParent);
4421         }
4422
4423         if( res==0 ){
4424           raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4425         }else if( bVerbose ){
4426           raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 
4427               zIndent, zFrom, zTarget
4428           );
4429         }
4430       }
4431     }
4432     sqlite3_free(zPrev);
4433
4434     if( rc!=SQLITE_OK ){
4435       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4436     }
4437
4438     rc2 = sqlite3_finalize(pSql);
4439     if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4440       rc = rc2;
4441       raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4442     }
4443   }else{
4444     raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4445   }
4446
4447   return rc;
4448 }
4449
4450 /*
4451 ** Implementation of ".lint" dot command.
4452 */
4453 static int lintDotCommand(
4454   ShellState *pState,             /* Current shell tool state */
4455   char **azArg,                   /* Array of arguments passed to dot command */
4456   int nArg                        /* Number of entries in azArg[] */
4457 ){
4458   int n;
4459   n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
4460   if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4461   return lintFkeyIndexes(pState, azArg, nArg);
4462
4463  usage:
4464   raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4465   raw_printf(stderr, "Where sub-commands are:\n");
4466   raw_printf(stderr, "    fkey-indexes\n");
4467   return SQLITE_ERROR;
4468 }
4469
4470
4471 /*
4472 ** If an input line begins with "." then invoke this routine to
4473 ** process that line.
4474 **
4475 ** Return 1 on error, 2 to exit, and 0 otherwise.
4476 */
4477 static int do_meta_command(char *zLine, ShellState *p){
4478   int h = 1;
4479   int nArg = 0;
4480   int n, c;
4481   int rc = 0;
4482   char *azArg[50];
4483
4484   /* Parse the input line into tokens.
4485   */
4486   while( zLine[h] && nArg<ArraySize(azArg) ){
4487     while( IsSpace(zLine[h]) ){ h++; }
4488     if( zLine[h]==0 ) break;
4489     if( zLine[h]=='\'' || zLine[h]=='"' ){
4490       int delim = zLine[h++];
4491       azArg[nArg++] = &zLine[h];
4492       while( zLine[h] && zLine[h]!=delim ){
4493         if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
4494         h++;
4495       }
4496       if( zLine[h]==delim ){
4497         zLine[h++] = 0;
4498       }
4499       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
4500     }else{
4501       azArg[nArg++] = &zLine[h];
4502       while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4503       if( zLine[h] ) zLine[h++] = 0;
4504       resolve_backslashes(azArg[nArg-1]);
4505     }
4506   }
4507
4508   /* Process the input line.
4509   */
4510   if( nArg==0 ) return 0; /* no tokens, no error */
4511   n = strlen30(azArg[0]);
4512   c = azArg[0][0];
4513
4514 #ifndef SQLITE_OMIT_AUTHORIZATION
4515   if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4516     if( nArg!=2 ){
4517       raw_printf(stderr, "Usage: .auth ON|OFF\n");
4518       rc = 1;
4519       goto meta_command_exit;
4520     }
4521     open_db(p, 0);
4522     if( booleanValue(azArg[1]) ){
4523       sqlite3_set_authorizer(p->db, shellAuth, p);
4524     }else{
4525       sqlite3_set_authorizer(p->db, 0, 0);
4526     }
4527   }else
4528 #endif
4529
4530   if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4531    || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4532   ){
4533     const char *zDestFile = 0;
4534     const char *zDb = 0;
4535     sqlite3 *pDest;
4536     sqlite3_backup *pBackup;
4537     int j;
4538     for(j=1; j<nArg; j++){
4539       const char *z = azArg[j];
4540       if( z[0]=='-' ){
4541         while( z[0]=='-' ) z++;
4542         /* No options to process at this time */
4543         {
4544           utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
4545           return 1;
4546         }
4547       }else if( zDestFile==0 ){
4548         zDestFile = azArg[j];
4549       }else if( zDb==0 ){
4550         zDb = zDestFile;
4551         zDestFile = azArg[j];
4552       }else{
4553         raw_printf(stderr, "too many arguments to .backup\n");
4554         return 1;
4555       }
4556     }
4557     if( zDestFile==0 ){
4558       raw_printf(stderr, "missing FILENAME argument on .backup\n");
4559       return 1;
4560     }
4561     if( zDb==0 ) zDb = "main";
4562     rc = sqlite3_open(zDestFile, &pDest);
4563     if( rc!=SQLITE_OK ){
4564       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
4565       sqlite3_close(pDest);
4566       return 1;
4567     }
4568     open_db(p, 0);
4569     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4570     if( pBackup==0 ){
4571       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4572       sqlite3_close(pDest);
4573       return 1;
4574     }
4575     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4576     sqlite3_backup_finish(pBackup);
4577     if( rc==SQLITE_DONE ){
4578       rc = 0;
4579     }else{
4580       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4581       rc = 1;
4582     }
4583     sqlite3_close(pDest);
4584   }else
4585
4586   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4587     if( nArg==2 ){
4588       bail_on_error = booleanValue(azArg[1]);
4589     }else{
4590       raw_printf(stderr, "Usage: .bail on|off\n");
4591       rc = 1;
4592     }
4593   }else
4594
4595   if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4596     if( nArg==2 ){
4597       if( booleanValue(azArg[1]) ){
4598         setBinaryMode(p->out, 1);
4599       }else{
4600         setTextMode(p->out, 1);
4601       }
4602     }else{
4603       raw_printf(stderr, "Usage: .binary on|off\n");
4604       rc = 1;
4605     }
4606   }else
4607
4608   /* The undocumented ".breakpoint" command causes a call to the no-op
4609   ** routine named test_breakpoint().
4610   */
4611   if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4612     test_breakpoint();
4613   }else
4614
4615   if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4616     if( nArg==2 ){
4617       setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
4618     }else{
4619       raw_printf(stderr, "Usage: .changes on|off\n");
4620       rc = 1;
4621     }
4622   }else
4623
4624   /* Cancel output redirection, if it is currently set (by .testcase)
4625   ** Then read the content of the testcase-out.txt file and compare against
4626   ** azArg[1].  If there are differences, report an error and exit.
4627   */
4628   if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4629     char *zRes = 0;
4630     output_reset(p);
4631     if( nArg!=2 ){
4632       raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
4633       rc = 2;
4634     }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
4635       raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4636       rc = 2;
4637     }else if( testcase_glob(azArg[1],zRes)==0 ){
4638       utf8_printf(stderr,
4639                  "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
4640                  p->zTestcase, azArg[1], zRes);
4641       rc = 2;
4642     }else{
4643       utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
4644       p->nCheck++;
4645     }
4646     sqlite3_free(zRes);
4647   }else
4648
4649   if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4650     if( nArg==2 ){
4651       tryToClone(p, azArg[1]);
4652     }else{
4653       raw_printf(stderr, "Usage: .clone FILENAME\n");
4654       rc = 1;
4655     }
4656   }else
4657
4658   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
4659     ShellState data;
4660     char *zErrMsg = 0;
4661     open_db(p, 0);
4662     memcpy(&data, p, sizeof(data));
4663     data.showHeader = 0;
4664     data.cMode = data.mode = MODE_List;
4665     sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
4666     data.cnt = 0;
4667     sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4668                  callback, &data, &zErrMsg);
4669     if( zErrMsg ){
4670       utf8_printf(stderr,"Error: %s\n", zErrMsg);
4671       sqlite3_free(zErrMsg);
4672       rc = 1;
4673     }
4674   }else
4675
4676   if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4677     rc = shell_dbinfo_command(p, nArg, azArg);
4678   }else
4679
4680   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
4681     const char *zLike = 0;
4682     int i;
4683     ShellClearFlag(p, SHFLG_PreserveRowid);
4684     for(i=1; i<nArg; i++){
4685       if( azArg[i][0]=='-' ){
4686         const char *z = azArg[i]+1;
4687         if( z[0]=='-' ) z++;
4688         if( strcmp(z,"preserve-rowids")==0 ){
4689 #ifdef SQLITE_OMIT_VIRTUALTABLE
4690           raw_printf(stderr, "The --preserve-rowids option is not compatible"
4691                              " with SQLITE_OMIT_VIRTUALTABLE\n");
4692           rc = 1;
4693           goto meta_command_exit;
4694 #else
4695           ShellSetFlag(p, SHFLG_PreserveRowid);
4696 #endif
4697         }else
4698         {
4699           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4700           rc = 1;
4701           goto meta_command_exit;
4702         }
4703       }else if( zLike ){
4704         raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4705         rc = 1;
4706         goto meta_command_exit;
4707       }else{
4708         zLike = azArg[i];
4709       }
4710     }
4711     open_db(p, 0);
4712     /* When playing back a "dump", the content might appear in an order
4713     ** which causes immediate foreign key constraints to be violated.
4714     ** So disable foreign-key constraint enforcement to prevent problems. */
4715     raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4716     raw_printf(p->out, "BEGIN TRANSACTION;\n");
4717     p->writableSchema = 0;
4718     /* Set writable_schema=ON since doing so forces SQLite to initialize
4719     ** as much of the schema as it can even if the sqlite_master table is
4720     ** corrupt. */
4721     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4722     p->nErr = 0;
4723     if( zLike==0 ){
4724       run_schema_dump_query(p,
4725         "SELECT name, type, sql FROM sqlite_master "
4726         "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4727       );
4728       run_schema_dump_query(p,
4729         "SELECT name, type, sql FROM sqlite_master "
4730         "WHERE name=='sqlite_sequence'"
4731       );
4732       run_table_dump_query(p,
4733         "SELECT sql FROM sqlite_master "
4734         "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4735       );
4736     }else{
4737       char *zSql;
4738       zSql = sqlite3_mprintf(
4739         "SELECT name, type, sql FROM sqlite_master "
4740         "WHERE tbl_name LIKE %Q AND type=='table'"
4741         "  AND sql NOT NULL", zLike);
4742       run_schema_dump_query(p,zSql);
4743       sqlite3_free(zSql);
4744       zSql = sqlite3_mprintf(
4745         "SELECT sql FROM sqlite_master "
4746         "WHERE sql NOT NULL"
4747         "  AND type IN ('index','trigger','view')"
4748         "  AND tbl_name LIKE %Q", zLike);
4749       run_table_dump_query(p, zSql, 0);
4750       sqlite3_free(zSql);
4751     }
4752     if( p->writableSchema ){
4753       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
4754       p->writableSchema = 0;
4755     }
4756     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4757     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
4758     raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4759   }else
4760
4761   if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4762     if( nArg==2 ){
4763       setOrClearFlag(p, SHFLG_Echo, azArg[1]);
4764     }else{
4765       raw_printf(stderr, "Usage: .echo on|off\n");
4766       rc = 1;
4767     }
4768   }else
4769
4770   if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4771     if( nArg==2 ){
4772       if( strcmp(azArg[1],"full")==0 ){
4773         p->autoEQP = 2;
4774       }else{
4775         p->autoEQP = booleanValue(azArg[1]);
4776       }
4777     }else{
4778       raw_printf(stderr, "Usage: .eqp on|off|full\n");
4779       rc = 1;
4780     }
4781   }else
4782
4783   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
4784     if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
4785     rc = 2;
4786   }else
4787
4788   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
4789     int val = 1;
4790     if( nArg>=2 ){
4791       if( strcmp(azArg[1],"auto")==0 ){
4792         val = 99;
4793       }else{
4794         val =  booleanValue(azArg[1]);
4795       }
4796     }
4797     if( val==1 && p->mode!=MODE_Explain ){
4798       p->normalMode = p->mode;
4799       p->mode = MODE_Explain;
4800       p->autoExplain = 0;
4801     }else if( val==0 ){
4802       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4803       p->autoExplain = 0;
4804     }else if( val==99 ){
4805       if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4806       p->autoExplain = 1;
4807     }
4808   }else
4809
4810   if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
4811     ShellState data;
4812     char *zErrMsg = 0;
4813     int doStats = 0;
4814     memcpy(&data, p, sizeof(data));
4815     data.showHeader = 0;
4816     data.cMode = data.mode = MODE_Semi;
4817     if( nArg==2 && optionMatch(azArg[1], "indent") ){
4818       data.cMode = data.mode = MODE_Pretty;
4819       nArg = 1;
4820     }
4821     if( nArg!=1 ){
4822       raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
4823       rc = 1;
4824       goto meta_command_exit;
4825     }
4826     open_db(p, 0);
4827     rc = sqlite3_exec(p->db,
4828        "SELECT sql FROM"
4829        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4830        "     FROM sqlite_master UNION ALL"
4831        "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4832        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4833        "ORDER BY rowid",
4834        callback, &data, &zErrMsg
4835     );
4836     if( rc==SQLITE_OK ){
4837       sqlite3_stmt *pStmt;
4838       rc = sqlite3_prepare_v2(p->db,
4839                "SELECT rowid FROM sqlite_master"
4840                " WHERE name GLOB 'sqlite_stat[134]'",
4841                -1, &pStmt, 0);
4842       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4843       sqlite3_finalize(pStmt);
4844     }
4845     if( doStats==0 ){
4846       raw_printf(p->out, "/* No STAT tables available */\n");
4847     }else{
4848       raw_printf(p->out, "ANALYZE sqlite_master;\n");
4849       sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4850                    callback, &data, &zErrMsg);
4851       data.cMode = data.mode = MODE_Insert;
4852       data.zDestTable = "sqlite_stat1";
4853       shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4854                  shell_callback, &data,&zErrMsg);
4855       data.zDestTable = "sqlite_stat3";
4856       shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4857                  shell_callback, &data,&zErrMsg);
4858       data.zDestTable = "sqlite_stat4";
4859       shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4860                  shell_callback, &data, &zErrMsg);
4861       raw_printf(p->out, "ANALYZE sqlite_master;\n");
4862     }
4863   }else
4864
4865   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4866     if( nArg==2 ){
4867       p->showHeader = booleanValue(azArg[1]);
4868     }else{
4869       raw_printf(stderr, "Usage: .headers on|off\n");
4870       rc = 1;
4871     }
4872   }else
4873
4874   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
4875     utf8_printf(p->out, "%s", zHelp);
4876   }else
4877
4878   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
4879     char *zTable;               /* Insert data into this table */
4880     char *zFile;                /* Name of file to extra content from */
4881     sqlite3_stmt *pStmt = NULL; /* A statement */
4882     int nCol;                   /* Number of columns in the table */
4883     int nByte;                  /* Number of bytes in an SQL string */
4884     int i, j;                   /* Loop counters */
4885     int needCommit;             /* True to COMMIT or ROLLBACK at end */
4886     int nSep;                   /* Number of bytes in p->colSeparator[] */
4887     char *zSql;                 /* An SQL statement */
4888     ImportCtx sCtx;             /* Reader context */
4889     char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4890     int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
4891
4892     if( nArg!=3 ){
4893       raw_printf(stderr, "Usage: .import FILE TABLE\n");
4894       goto meta_command_exit;
4895     }
4896     zFile = azArg[1];
4897     zTable = azArg[2];
4898     seenInterrupt = 0;
4899     memset(&sCtx, 0, sizeof(sCtx));
4900     open_db(p, 0);
4901     nSep = strlen30(p->colSeparator);
4902     if( nSep==0 ){
4903       raw_printf(stderr,
4904                  "Error: non-null column separator required for import\n");
4905       return 1;
4906     }
4907     if( nSep>1 ){
4908       raw_printf(stderr, "Error: multi-character column separators not allowed"
4909                       " for import\n");
4910       return 1;
4911     }
4912     nSep = strlen30(p->rowSeparator);
4913     if( nSep==0 ){
4914       raw_printf(stderr, "Error: non-null row separator required for import\n");
4915       return 1;
4916     }
4917     if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4918       /* When importing CSV (only), if the row separator is set to the
4919       ** default output row separator, change it to the default input
4920       ** row separator.  This avoids having to maintain different input
4921       ** and output row separators. */
4922       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4923       nSep = strlen30(p->rowSeparator);
4924     }
4925     if( nSep>1 ){
4926       raw_printf(stderr, "Error: multi-character row separators not allowed"
4927                       " for import\n");
4928       return 1;
4929     }
4930     sCtx.zFile = zFile;
4931     sCtx.nLine = 1;
4932     if( sCtx.zFile[0]=='|' ){
4933 #ifdef SQLITE_OMIT_POPEN
4934       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4935       return 1;
4936 #else
4937       sCtx.in = popen(sCtx.zFile+1, "r");
4938       sCtx.zFile = "<pipe>";
4939       xCloser = pclose;
4940 #endif
4941     }else{
4942       sCtx.in = fopen(sCtx.zFile, "rb");
4943       xCloser = fclose;
4944     }
4945     if( p->mode==MODE_Ascii ){
4946       xRead = ascii_read_one_field;
4947     }else{
4948       xRead = csv_read_one_field;
4949     }
4950     if( sCtx.in==0 ){
4951       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4952       return 1;
4953     }
4954     sCtx.cColSep = p->colSeparator[0];
4955     sCtx.cRowSep = p->rowSeparator[0];
4956     zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
4957     if( zSql==0 ){
4958       raw_printf(stderr, "Error: out of memory\n");
4959       xCloser(sCtx.in);
4960       return 1;
4961     }
4962     nByte = strlen30(zSql);
4963     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4964     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
4965     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
4966       char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
4967       char cSep = '(';
4968       while( xRead(&sCtx) ){
4969         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
4970         cSep = ',';
4971         if( sCtx.cTerm!=sCtx.cColSep ) break;
4972       }
4973       if( cSep=='(' ){
4974         sqlite3_free(zCreate);
4975         sqlite3_free(sCtx.z);
4976         xCloser(sCtx.in);
4977         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
4978         return 1;
4979       }
4980       zCreate = sqlite3_mprintf("%z\n)", zCreate);
4981       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
4982       sqlite3_free(zCreate);
4983       if( rc ){
4984         utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
4985                 sqlite3_errmsg(p->db));
4986         sqlite3_free(sCtx.z);
4987         xCloser(sCtx.in);
4988         return 1;
4989       }
4990       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4991     }
4992     sqlite3_free(zSql);
4993     if( rc ){
4994       if (pStmt) sqlite3_finalize(pStmt);
4995       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
4996       xCloser(sCtx.in);
4997       return 1;
4998     }
4999     nCol = sqlite3_column_count(pStmt);
5000     sqlite3_finalize(pStmt);
5001     pStmt = 0;
5002     if( nCol==0 ) return 0; /* no columns, no error */
5003     zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5004     if( zSql==0 ){
5005       raw_printf(stderr, "Error: out of memory\n");
5006       xCloser(sCtx.in);
5007       return 1;
5008     }
5009     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5010     j = strlen30(zSql);
5011     for(i=1; i<nCol; i++){
5012       zSql[j++] = ',';
5013       zSql[j++] = '?';
5014     }
5015     zSql[j++] = ')';
5016     zSql[j] = 0;
5017     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5018     sqlite3_free(zSql);
5019     if( rc ){
5020       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5021       if (pStmt) sqlite3_finalize(pStmt);
5022       xCloser(sCtx.in);
5023       return 1;
5024     }
5025     needCommit = sqlite3_get_autocommit(p->db);
5026     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5027     do{
5028       int startLine = sCtx.nLine;
5029       for(i=0; i<nCol; i++){
5030         char *z = xRead(&sCtx);
5031         /*
5032         ** Did we reach end-of-file before finding any columns?
5033         ** If so, stop instead of NULL filling the remaining columns.
5034         */
5035         if( z==0 && i==0 ) break;
5036         /*
5037         ** Did we reach end-of-file OR end-of-line before finding any
5038         ** columns in ASCII mode?  If so, stop instead of NULL filling
5039         ** the remaining columns.
5040         */
5041         if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5042         sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5043         if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5044           utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5045                           "filling the rest with NULL\n",
5046                           sCtx.zFile, startLine, nCol, i+1);
5047           i += 2;
5048           while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5049         }
5050       }
5051       if( sCtx.cTerm==sCtx.cColSep ){
5052         do{
5053           xRead(&sCtx);
5054           i++;
5055         }while( sCtx.cTerm==sCtx.cColSep );
5056         utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5057                         "extras ignored\n",
5058                         sCtx.zFile, startLine, nCol, i);
5059       }
5060       if( i>=nCol ){
5061         sqlite3_step(pStmt);
5062         rc = sqlite3_reset(pStmt);
5063         if( rc!=SQLITE_OK ){
5064           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5065                       startLine, sqlite3_errmsg(p->db));
5066         }
5067       }
5068     }while( sCtx.cTerm!=EOF );
5069
5070     xCloser(sCtx.in);
5071     sqlite3_free(sCtx.z);
5072     sqlite3_finalize(pStmt);
5073     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5074   }else
5075
5076 #ifndef SQLITE_UNTESTABLE
5077   if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5078     char *zSql;
5079     char *zCollist = 0;
5080     sqlite3_stmt *pStmt;
5081     int tnum = 0;
5082     int i;
5083     if( nArg!=3 ){
5084       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5085       rc = 1;
5086       goto meta_command_exit;
5087     }
5088     open_db(p, 0);
5089     zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5090                            " WHERE name='%q' AND type='index'", azArg[1]);
5091     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5092     sqlite3_free(zSql);
5093     if( sqlite3_step(pStmt)==SQLITE_ROW ){
5094       tnum = sqlite3_column_int(pStmt, 0);
5095     }
5096     sqlite3_finalize(pStmt);
5097     if( tnum==0 ){
5098       utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5099       rc = 1;
5100       goto meta_command_exit;
5101     }
5102     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5103     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5104     sqlite3_free(zSql);
5105     i = 0;
5106     while( sqlite3_step(pStmt)==SQLITE_ROW ){
5107       char zLabel[20];
5108       const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5109       i++;
5110       if( zCol==0 ){
5111         if( sqlite3_column_int(pStmt,1)==-1 ){
5112           zCol = "_ROWID_";
5113         }else{
5114           sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5115           zCol = zLabel;
5116         }
5117       }
5118       if( zCollist==0 ){
5119         zCollist = sqlite3_mprintf("\"%w\"", zCol);
5120       }else{
5121         zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5122       }
5123     }
5124     sqlite3_finalize(pStmt);
5125     zSql = sqlite3_mprintf(
5126           "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5127           azArg[2], zCollist, zCollist);
5128     sqlite3_free(zCollist);
5129     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5130     if( rc==SQLITE_OK ){
5131       rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5132       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5133       if( rc ){
5134         utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5135       }else{
5136         utf8_printf(stdout, "%s;\n", zSql);
5137         raw_printf(stdout,
5138            "WARNING: writing to an imposter table will corrupt the index!\n"
5139         );
5140       }
5141     }else{
5142       raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5143       rc = 1;
5144     }
5145     sqlite3_free(zSql);
5146   }else
5147 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5148
5149 #ifdef SQLITE_ENABLE_IOTRACE
5150   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5151     SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5152     if( iotrace && iotrace!=stdout ) fclose(iotrace);
5153     iotrace = 0;
5154     if( nArg<2 ){
5155       sqlite3IoTrace = 0;
5156     }else if( strcmp(azArg[1], "-")==0 ){
5157       sqlite3IoTrace = iotracePrintf;
5158       iotrace = stdout;
5159     }else{
5160       iotrace = fopen(azArg[1], "w");
5161       if( iotrace==0 ){
5162         utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5163         sqlite3IoTrace = 0;
5164         rc = 1;
5165       }else{
5166         sqlite3IoTrace = iotracePrintf;
5167       }
5168     }
5169   }else
5170 #endif
5171
5172   if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5173     static const struct {
5174        const char *zLimitName;   /* Name of a limit */
5175        int limitCode;            /* Integer code for that limit */
5176     } aLimit[] = {
5177       { "length",                SQLITE_LIMIT_LENGTH                    },
5178       { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
5179       { "column",                SQLITE_LIMIT_COLUMN                    },
5180       { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
5181       { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
5182       { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
5183       { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
5184       { "attached",              SQLITE_LIMIT_ATTACHED                  },
5185       { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
5186       { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
5187       { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
5188       { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
5189     };
5190     int i, n2;
5191     open_db(p, 0);
5192     if( nArg==1 ){
5193       for(i=0; i<ArraySize(aLimit); i++){
5194         printf("%20s %d\n", aLimit[i].zLimitName,
5195                sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5196       }
5197     }else if( nArg>3 ){
5198       raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5199       rc = 1;
5200       goto meta_command_exit;
5201     }else{
5202       int iLimit = -1;
5203       n2 = strlen30(azArg[1]);
5204       for(i=0; i<ArraySize(aLimit); i++){
5205         if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5206           if( iLimit<0 ){
5207             iLimit = i;
5208           }else{
5209             utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5210             rc = 1;
5211             goto meta_command_exit;
5212           }
5213         }
5214       }
5215       if( iLimit<0 ){
5216         utf8_printf(stderr, "unknown limit: \"%s\"\n"
5217                         "enter \".limits\" with no arguments for a list.\n",
5218                          azArg[1]);
5219         rc = 1;
5220         goto meta_command_exit;
5221       }
5222       if( nArg==3 ){
5223         sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5224                       (int)integerValue(azArg[2]));
5225       }
5226       printf("%20s %d\n", aLimit[iLimit].zLimitName,
5227              sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5228     }
5229   }else
5230
5231   if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5232     open_db(p, 0);
5233     lintDotCommand(p, azArg, nArg);
5234   }else
5235
5236 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5237   if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5238     const char *zFile, *zProc;
5239     char *zErrMsg = 0;
5240     if( nArg<2 ){
5241       raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5242       rc = 1;
5243       goto meta_command_exit;
5244     }
5245     zFile = azArg[1];
5246     zProc = nArg>=3 ? azArg[2] : 0;
5247     open_db(p, 0);
5248     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5249     if( rc!=SQLITE_OK ){
5250       utf8_printf(stderr, "Error: %s\n", zErrMsg);
5251       sqlite3_free(zErrMsg);
5252       rc = 1;
5253     }
5254   }else
5255 #endif
5256
5257   if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5258     if( nArg!=2 ){
5259       raw_printf(stderr, "Usage: .log FILENAME\n");
5260       rc = 1;
5261     }else{
5262       const char *zFile = azArg[1];
5263       output_file_close(p->pLog);
5264       p->pLog = output_file_open(zFile);
5265     }
5266   }else
5267
5268   if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5269     const char *zMode = nArg>=2 ? azArg[1] : "";
5270     int n2 = (int)strlen(zMode);
5271     int c2 = zMode[0];
5272     if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
5273       p->mode = MODE_Line;
5274       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5275     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
5276       p->mode = MODE_Column;
5277       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5278     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
5279       p->mode = MODE_List;
5280       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5281       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5282     }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
5283       p->mode = MODE_Html;
5284     }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
5285       p->mode = MODE_Tcl;
5286       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
5287       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5288     }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
5289       p->mode = MODE_Csv;
5290       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
5291       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
5292     }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
5293       p->mode = MODE_List;
5294       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
5295     }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
5296       p->mode = MODE_Insert;
5297       set_table_name(p, nArg>=3 ? azArg[2] : "table");
5298     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5299       p->mode = MODE_Quote;
5300     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5301       p->mode = MODE_Ascii;
5302       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5303       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
5304     }else {
5305       raw_printf(stderr, "Error: mode should be one of: "
5306          "ascii column csv html insert line list quote tabs tcl\n");
5307       rc = 1;
5308     }
5309     p->cMode = p->mode;
5310   }else
5311
5312   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5313     if( nArg==2 ){
5314       sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5315                        "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
5316     }else{
5317       raw_printf(stderr, "Usage: .nullvalue STRING\n");
5318       rc = 1;
5319     }
5320   }else
5321
5322   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
5323     char *zNewFilename;  /* Name of the database file to open */
5324     int iName = 1;       /* Index in azArg[] of the filename */
5325     int newFlag = 0;     /* True to delete file before opening */
5326     /* Close the existing database */
5327     session_close_all(p);
5328     sqlite3_close(p->db);
5329     p->db = 0;
5330     p->zDbFilename = 0;
5331     sqlite3_free(p->zFreeOnClose);
5332     p->zFreeOnClose = 0;
5333     /* Check for command-line arguments */
5334     for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5335       const char *z = azArg[iName];
5336       if( optionMatch(z,"new") ){
5337         newFlag = 1;
5338       }else if( z[0]=='-' ){
5339         utf8_printf(stderr, "unknown option: %s\n", z);
5340         rc = 1;
5341         goto meta_command_exit;
5342       }
5343     }
5344     /* If a filename is specified, try to open it first */
5345     zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5346     if( zNewFilename ){
5347       if( newFlag ) shellDeleteFile(zNewFilename);
5348       p->zDbFilename = zNewFilename;
5349       open_db(p, 1);
5350       if( p->db==0 ){
5351         utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5352         sqlite3_free(zNewFilename);
5353       }else{
5354         p->zFreeOnClose = zNewFilename;
5355       }
5356     }
5357     if( p->db==0 ){
5358       /* As a fall-back open a TEMP database */
5359       p->zDbFilename = 0;
5360       open_db(p, 0);
5361     }
5362   }else
5363
5364   if( c=='o'
5365    && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5366   ){
5367     const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5368     if( nArg>2 ){
5369       utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
5370       rc = 1;
5371       goto meta_command_exit;
5372     }
5373     if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5374       if( nArg<2 ){
5375         raw_printf(stderr, "Usage: .once FILE\n");
5376         rc = 1;
5377         goto meta_command_exit;
5378       }
5379       p->outCount = 2;
5380     }else{
5381       p->outCount = 0;
5382     }
5383     output_reset(p);
5384     if( zFile[0]=='|' ){
5385 #ifdef SQLITE_OMIT_POPEN
5386       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5387       rc = 1;
5388       p->out = stdout;
5389 #else
5390       p->out = popen(zFile + 1, "w");
5391       if( p->out==0 ){
5392         utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
5393         p->out = stdout;
5394         rc = 1;
5395       }else{
5396         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5397       }
5398 #endif
5399     }else{
5400       p->out = output_file_open(zFile);
5401       if( p->out==0 ){
5402         if( strcmp(zFile,"off")!=0 ){
5403           utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
5404         }
5405         p->out = stdout;
5406         rc = 1;
5407       } else {
5408         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5409       }
5410     }
5411   }else
5412
5413   if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5414     int i;
5415     for(i=1; i<nArg; i++){
5416       if( i>1 ) raw_printf(p->out, " ");
5417       utf8_printf(p->out, "%s", azArg[i]);
5418     }
5419     raw_printf(p->out, "\n");
5420   }else
5421
5422   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
5423     if( nArg >= 2) {
5424       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5425     }
5426     if( nArg >= 3) {
5427       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5428     }
5429   }else
5430
5431   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
5432     rc = 2;
5433   }else
5434
5435   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5436     FILE *alt;
5437     if( nArg!=2 ){
5438       raw_printf(stderr, "Usage: .read FILE\n");
5439       rc = 1;
5440       goto meta_command_exit;
5441     }
5442     alt = fopen(azArg[1], "rb");
5443     if( alt==0 ){
5444       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5445       rc = 1;
5446     }else{
5447       rc = process_input(p, alt);
5448       fclose(alt);
5449     }
5450   }else
5451
5452   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
5453     const char *zSrcFile;
5454     const char *zDb;
5455     sqlite3 *pSrc;
5456     sqlite3_backup *pBackup;
5457     int nTimeout = 0;
5458
5459     if( nArg==2 ){
5460       zSrcFile = azArg[1];
5461       zDb = "main";
5462     }else if( nArg==3 ){
5463       zSrcFile = azArg[2];
5464       zDb = azArg[1];
5465     }else{
5466       raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
5467       rc = 1;
5468       goto meta_command_exit;
5469     }
5470     rc = sqlite3_open(zSrcFile, &pSrc);
5471     if( rc!=SQLITE_OK ){
5472       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
5473       sqlite3_close(pSrc);
5474       return 1;
5475     }
5476     open_db(p, 0);
5477     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5478     if( pBackup==0 ){
5479       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5480       sqlite3_close(pSrc);
5481       return 1;
5482     }
5483     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5484           || rc==SQLITE_BUSY  ){
5485       if( rc==SQLITE_BUSY ){
5486         if( nTimeout++ >= 3 ) break;
5487         sqlite3_sleep(100);
5488       }
5489     }
5490     sqlite3_backup_finish(pBackup);
5491     if( rc==SQLITE_DONE ){
5492       rc = 0;
5493     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
5494       raw_printf(stderr, "Error: source database is busy\n");
5495       rc = 1;
5496     }else{
5497       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5498       rc = 1;
5499     }
5500     sqlite3_close(pSrc);
5501   }else
5502
5503
5504   if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5505     if( nArg==2 ){
5506       p->scanstatsOn = booleanValue(azArg[1]);
5507 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5508       raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
5509 #endif
5510     }else{
5511       raw_printf(stderr, "Usage: .scanstats on|off\n");
5512       rc = 1;
5513     }
5514   }else
5515
5516   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
5517     ShellState data;
5518     char *zErrMsg = 0;
5519     open_db(p, 0);
5520     memcpy(&data, p, sizeof(data));
5521     data.showHeader = 0;
5522     data.cMode = data.mode = MODE_Semi;
5523     if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5524       data.cMode = data.mode = MODE_Pretty;
5525       nArg--;
5526       if( nArg==2 ) azArg[1] = azArg[2];
5527     }
5528     if( nArg==2 && azArg[1][0]!='-' ){
5529       int i;
5530       for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
5531       if( strcmp(azArg[1],"sqlite_master")==0 ){
5532         char *new_argv[2], *new_colv[2];
5533         new_argv[0] = "CREATE TABLE sqlite_master (\n"
5534                       "  type text,\n"
5535                       "  name text,\n"
5536                       "  tbl_name text,\n"
5537                       "  rootpage integer,\n"
5538                       "  sql text\n"
5539                       ")";
5540         new_argv[1] = 0;
5541         new_colv[0] = "sql";
5542         new_colv[1] = 0;
5543         callback(&data, 1, new_argv, new_colv);
5544         rc = SQLITE_OK;
5545       }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
5546         char *new_argv[2], *new_colv[2];
5547         new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5548                       "  type text,\n"
5549                       "  name text,\n"
5550                       "  tbl_name text,\n"
5551                       "  rootpage integer,\n"
5552                       "  sql text\n"
5553                       ")";
5554         new_argv[1] = 0;
5555         new_colv[0] = "sql";
5556         new_colv[1] = 0;
5557         callback(&data, 1, new_argv, new_colv);
5558         rc = SQLITE_OK;
5559       }else{
5560         char *zSql;
5561         zSql = sqlite3_mprintf(
5562           "SELECT sql FROM "
5563           "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5564           "     FROM sqlite_master UNION ALL"
5565           "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5566           "WHERE lower(tbl_name) LIKE %Q"
5567           "  AND type!='meta' AND sql NOTNULL "
5568           "ORDER BY rowid", azArg[1]);
5569         rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
5570         sqlite3_free(zSql);
5571       }
5572     }else if( nArg==1 ){
5573       rc = sqlite3_exec(p->db,
5574          "SELECT sql FROM "
5575          "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5576          "     FROM sqlite_master UNION ALL"
5577          "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5578          "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5579          "ORDER BY rowid",
5580          callback, &data, &zErrMsg
5581       );
5582     }else{
5583       raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5584       rc = 1;
5585       goto meta_command_exit;
5586     }
5587     if( zErrMsg ){
5588       utf8_printf(stderr,"Error: %s\n", zErrMsg);
5589       sqlite3_free(zErrMsg);
5590       rc = 1;
5591     }else if( rc != SQLITE_OK ){
5592       raw_printf(stderr,"Error: querying schema information\n");
5593       rc = 1;
5594     }else{
5595       rc = 0;
5596     }
5597   }else
5598
5599 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5600   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
5601     sqlite3SelectTrace = (int)integerValue(azArg[1]);
5602   }else
5603 #endif
5604
5605 #if defined(SQLITE_ENABLE_SESSION)
5606   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5607     OpenSession *pSession = &p->aSession[0];
5608     char **azCmd = &azArg[1];
5609     int iSes = 0;
5610     int nCmd = nArg - 1;
5611     int i;
5612     if( nArg<=1 ) goto session_syntax_error;
5613     open_db(p, 0);
5614     if( nArg>=3 ){
5615       for(iSes=0; iSes<p->nSession; iSes++){
5616         if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5617       }
5618       if( iSes<p->nSession ){
5619         pSession = &p->aSession[iSes];
5620         azCmd++;
5621         nCmd--;
5622       }else{
5623         pSession = &p->aSession[0];
5624         iSes = 0;
5625       }
5626     }
5627
5628     /* .session attach TABLE
5629     ** Invoke the sqlite3session_attach() interface to attach a particular
5630     ** table so that it is never filtered.
5631     */
5632     if( strcmp(azCmd[0],"attach")==0 ){
5633       if( nCmd!=2 ) goto session_syntax_error;
5634       if( pSession->p==0 ){
5635         session_not_open:
5636         raw_printf(stderr, "ERROR: No sessions are open\n");
5637       }else{
5638         rc = sqlite3session_attach(pSession->p, azCmd[1]);
5639         if( rc ){
5640           raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
5641           rc = 0;
5642         }
5643       }
5644     }else
5645
5646     /* .session changeset FILE
5647     ** .session patchset FILE
5648     ** Write a changeset or patchset into a file.  The file is overwritten.
5649     */
5650     if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5651       FILE *out = 0;
5652       if( nCmd!=2 ) goto session_syntax_error;
5653       if( pSession->p==0 ) goto session_not_open;
5654       out = fopen(azCmd[1], "wb");
5655       if( out==0 ){
5656         utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
5657       }else{
5658         int szChng;
5659         void *pChng;
5660         if( azCmd[0][0]=='c' ){
5661           rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
5662         }else{
5663           rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5664         }
5665         if( rc ){
5666           printf("Error: error code %d\n", rc);
5667           rc = 0;
5668         }
5669         if( pChng
5670           && fwrite(pChng, szChng, 1, out)!=1 ){
5671           raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
5672                   szChng);
5673         }
5674         sqlite3_free(pChng);
5675         fclose(out);
5676       }
5677     }else
5678
5679     /* .session close
5680     ** Close the identified session
5681     */
5682     if( strcmp(azCmd[0], "close")==0 ){
5683       if( nCmd!=1 ) goto session_syntax_error;
5684       if( p->nSession ){
5685         session_close(pSession);
5686         p->aSession[iSes] = p->aSession[--p->nSession];
5687       }
5688     }else
5689
5690     /* .session enable ?BOOLEAN?
5691     ** Query or set the enable flag
5692     */
5693     if( strcmp(azCmd[0], "enable")==0 ){
5694       int ii;
5695       if( nCmd>2 ) goto session_syntax_error;
5696       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5697       if( p->nSession ){
5698         ii = sqlite3session_enable(pSession->p, ii);
5699         utf8_printf(p->out, "session %s enable flag = %d\n",
5700                     pSession->zName, ii);
5701       }
5702     }else
5703
5704     /* .session filter GLOB ....
5705     ** Set a list of GLOB patterns of table names to be excluded.
5706     */
5707     if( strcmp(azCmd[0], "filter")==0 ){
5708       int ii, nByte;
5709       if( nCmd<2 ) goto session_syntax_error;
5710       if( p->nSession ){
5711         for(ii=0; ii<pSession->nFilter; ii++){
5712           sqlite3_free(pSession->azFilter[ii]);
5713         }
5714         sqlite3_free(pSession->azFilter);
5715         nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5716         pSession->azFilter = sqlite3_malloc( nByte );
5717         if( pSession->azFilter==0 ){
5718           raw_printf(stderr, "Error: out or memory\n");
5719           exit(1);
5720         }
5721         for(ii=1; ii<nCmd; ii++){
5722           pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
5723         }
5724         pSession->nFilter = ii-1;
5725       }
5726     }else
5727
5728     /* .session indirect ?BOOLEAN?
5729     ** Query or set the indirect flag
5730     */
5731     if( strcmp(azCmd[0], "indirect")==0 ){
5732       int ii;
5733       if( nCmd>2 ) goto session_syntax_error;
5734       ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5735       if( p->nSession ){
5736         ii = sqlite3session_indirect(pSession->p, ii);
5737         utf8_printf(p->out, "session %s indirect flag = %d\n",
5738                     pSession->zName, ii);
5739       }
5740     }else
5741
5742     /* .session isempty
5743     ** Determine if the session is empty
5744     */
5745     if( strcmp(azCmd[0], "isempty")==0 ){
5746       int ii;
5747       if( nCmd!=1 ) goto session_syntax_error;
5748       if( p->nSession ){
5749         ii = sqlite3session_isempty(pSession->p);
5750         utf8_printf(p->out, "session %s isempty flag = %d\n",
5751                     pSession->zName, ii);
5752       }
5753     }else
5754
5755     /* .session list
5756     ** List all currently open sessions
5757     */
5758     if( strcmp(azCmd[0],"list")==0 ){
5759       for(i=0; i<p->nSession; i++){
5760         utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
5761       }
5762     }else
5763
5764     /* .session open DB NAME
5765     ** Open a new session called NAME on the attached database DB.
5766     ** DB is normally "main".
5767     */
5768     if( strcmp(azCmd[0],"open")==0 ){
5769       char *zName;
5770       if( nCmd!=3 ) goto session_syntax_error;
5771       zName = azCmd[2];
5772       if( zName[0]==0 ) goto session_syntax_error;
5773       for(i=0; i<p->nSession; i++){
5774         if( strcmp(p->aSession[i].zName,zName)==0 ){
5775           utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
5776           goto meta_command_exit;
5777         }
5778       }
5779       if( p->nSession>=ArraySize(p->aSession) ){
5780         raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
5781         goto meta_command_exit;
5782       }
5783       pSession = &p->aSession[p->nSession];
5784       rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5785       if( rc ){
5786         raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
5787         rc = 0;
5788         goto meta_command_exit;
5789       }
5790       pSession->nFilter = 0;
5791       sqlite3session_table_filter(pSession->p, session_filter, pSession);
5792       p->nSession++;
5793       pSession->zName = sqlite3_mprintf("%s", zName);
5794     }else
5795     /* If no command name matches, show a syntax error */
5796     session_syntax_error:
5797     session_help(p);
5798   }else
5799 #endif
5800
5801 #ifdef SQLITE_DEBUG
5802   /* Undocumented commands for internal testing.  Subject to change
5803   ** without notice. */
5804   if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5805     if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5806       int i, v;
5807       for(i=1; i<nArg; i++){
5808         v = booleanValue(azArg[i]);
5809         utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
5810       }
5811     }
5812     if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5813       int i; sqlite3_int64 v;
5814       for(i=1; i<nArg; i++){
5815         char zBuf[200];
5816         v = integerValue(azArg[i]);
5817         sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
5818         utf8_printf(p->out, "%s", zBuf);
5819       }
5820     }
5821   }else
5822 #endif
5823
5824   if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5825     int bIsInit = 0;         /* True to initialize the SELFTEST table */
5826     int bVerbose = 0;        /* Verbose output */
5827     int bSelftestExists;     /* True if SELFTEST already exists */
5828     char **azTest = 0;       /* Content of the SELFTEST table */
5829     int nRow = 0;            /* Number of rows in the SELFTEST table */
5830     int nCol = 4;            /* Number of columns in the SELFTEST table */
5831     int i;                   /* Loop counter */
5832     int nTest = 0;           /* Number of tests runs */
5833     int nErr = 0;            /* Number of errors seen */
5834     ShellText str;           /* Answer for a query */
5835     static char *azDefaultTest[] = {
5836        0, 0, 0, 0,
5837        "0", "memo", "Missing SELFTEST table - default checks only", "",
5838        "1", "run", "PRAGMA integrity_check", "ok"
5839     };
5840     static const int nDefaultRow = 2;
5841
5842     open_db(p,0);
5843     for(i=1; i<nArg; i++){
5844       const char *z = azArg[i];
5845       if( z[0]=='-' && z[1]=='-' ) z++;
5846       if( strcmp(z,"-init")==0 ){
5847         bIsInit = 1;
5848       }else
5849       if( strcmp(z,"-v")==0 ){
5850         bVerbose++;
5851       }else
5852       {
5853         utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5854                     azArg[i], azArg[0]);
5855         raw_printf(stderr, "Should be one of: --init -v\n");
5856         rc = 1;
5857         goto meta_command_exit;
5858       }
5859     }
5860     if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5861            != SQLITE_OK ){
5862       bSelftestExists = 0;
5863     }else{
5864       bSelftestExists = 1;
5865     }
5866     if( bIsInit ){
5867       createSelftestTable(p);
5868       bSelftestExists = 1;
5869     }
5870     if( bSelftestExists ){
5871       rc = sqlite3_get_table(p->db, 
5872           "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5873           &azTest, &nRow, &nCol, 0);
5874       if( rc ){
5875         raw_printf(stderr, "Error querying the selftest table\n");
5876         rc = 1;
5877         sqlite3_free_table(azTest);
5878         goto meta_command_exit;
5879       }else if( nRow==0 ){
5880         sqlite3_free_table(azTest);
5881         azTest = azDefaultTest;
5882         nRow = nDefaultRow;
5883       }
5884     }else{
5885       azTest = azDefaultTest;
5886       nRow = nDefaultRow;
5887     }
5888     initText(&str);
5889     appendText(&str, "x", 0);
5890     for(i=1; i<=nRow; i++){
5891       int tno = atoi(azTest[i*nCol]);
5892       const char *zOp = azTest[i*nCol+1];
5893       const char *zSql = azTest[i*nCol+2];
5894       const char *zAns = azTest[i*nCol+3];
5895   
5896       if( bVerbose>0 ){
5897         char *zQuote = sqlite3_mprintf("%q", zSql);
5898         printf("%d: %s %s\n", tno, zOp, zSql);
5899         sqlite3_free(zQuote);
5900       }
5901       if( strcmp(zOp,"memo")==0 ){
5902         utf8_printf(p->out, "%s\n", zSql);
5903       }else
5904       if( strcmp(zOp,"run")==0 ){
5905         char *zErrMsg = 0;
5906         str.n = 0;
5907         str.z[0] = 0;
5908         rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5909         nTest++;
5910         if( bVerbose ){
5911           utf8_printf(p->out, "Result: %s\n", str.z);
5912         }
5913         if( rc || zErrMsg ){
5914           nErr++;
5915           rc = 1;
5916           utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5917           sqlite3_free(zErrMsg);
5918         }else if( strcmp(zAns,str.z)!=0 ){
5919           nErr++;
5920           rc = 1;
5921           utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5922           utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
5923         }
5924       }else
5925       {
5926         utf8_printf(stderr,
5927           "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5928         rc = 1;
5929         break;
5930       }
5931     }
5932     freeText(&str);
5933     if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
5934     utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5935   }else
5936
5937   if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
5938     if( nArg<2 || nArg>3 ){
5939       raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
5940       rc = 1;
5941     }
5942     if( nArg>=2 ){
5943       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
5944                        "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
5945     }
5946     if( nArg>=3 ){
5947       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5948                        "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
5949     }
5950   }else
5951
5952   if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5953     const char *zLike = 0;   /* Which table to checksum. 0 means everything */
5954     int i;                   /* Loop counter */
5955     int bSchema = 0;         /* Also hash the schema */
5956     int bSeparate = 0;       /* Hash each table separately */
5957     int iSize = 224;         /* Hash algorithm to use */
5958     int bDebug = 0;          /* Only show the query that would have run */
5959     sqlite3_stmt *pStmt;     /* For querying tables names */
5960     char *zSql;              /* SQL to be run */
5961     char *zSep;              /* Separator */
5962     ShellText sSql;          /* Complete SQL for the query to run the hash */
5963     ShellText sQuery;        /* Set of queries used to read all content */
5964     open_db(p, 0);
5965     for(i=1; i<nArg; i++){
5966       const char *z = azArg[i];
5967       if( z[0]=='-' ){
5968         z++;
5969         if( z[0]=='-' ) z++;
5970         if( strcmp(z,"schema")==0 ){
5971           bSchema = 1;
5972         }else
5973         if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 
5974          || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 
5975         ){
5976           iSize = atoi(&z[5]);
5977         }else
5978         if( strcmp(z,"debug")==0 ){
5979           bDebug = 1;
5980         }else
5981         {
5982           utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5983                       azArg[i], azArg[0]);
5984           raw_printf(stderr, "Should be one of: --schema"
5985                              " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5986           rc = 1;
5987           goto meta_command_exit;
5988         }
5989       }else if( zLike ){
5990         raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5991         rc = 1;
5992         goto meta_command_exit;
5993       }else{
5994         zLike = z;
5995         bSeparate = 1;
5996         if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
5997       }
5998     }
5999     if( bSchema ){
6000       zSql = "SELECT lower(name) FROM sqlite_master"
6001              " WHERE type='table' AND coalesce(rootpage,0)>1"
6002              " UNION ALL SELECT 'sqlite_master'"
6003              " ORDER BY 1 collate nocase";
6004     }else{
6005       zSql = "SELECT lower(name) FROM sqlite_master"
6006              " WHERE type='table' AND coalesce(rootpage,0)>1"
6007              " AND name NOT LIKE 'sqlite_%'"
6008              " ORDER BY 1 collate nocase";
6009     }
6010     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6011     initText(&sQuery);
6012     initText(&sSql);
6013     appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6014     zSep = "VALUES(";
6015     while( SQLITE_ROW==sqlite3_step(pStmt) ){
6016       const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6017       if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6018       if( strncmp(zTab, "sqlite_",7)!=0 ){
6019         appendText(&sQuery,"SELECT * FROM ", 0);
6020         appendText(&sQuery,zTab,'"');
6021         appendText(&sQuery," NOT INDEXED;", 0);
6022       }else if( strcmp(zTab, "sqlite_master")==0 ){
6023         appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6024                            " ORDER BY name;", 0);
6025       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6026         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6027                            " ORDER BY name;", 0);
6028       }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6029         appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6030                            " ORDER BY tbl,idx;", 0);
6031       }else if( strcmp(zTab, "sqlite_stat3")==0
6032              || strcmp(zTab, "sqlite_stat4")==0 ){
6033         appendText(&sQuery, "SELECT * FROM ", 0);
6034         appendText(&sQuery, zTab, 0);
6035         appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6036       }
6037       appendText(&sSql, zSep, 0);
6038       appendText(&sSql, sQuery.z, '\'');
6039       sQuery.n = 0;
6040       appendText(&sSql, ",", 0);
6041       appendText(&sSql, zTab, '\'');
6042       zSep = "),(";
6043     }
6044     sqlite3_finalize(pStmt);
6045     if( bSeparate ){
6046       zSql = sqlite3_mprintf(
6047           "%s))"
6048           " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6049           "   FROM [sha3sum$query]",
6050           sSql.z, iSize);
6051     }else{
6052       zSql = sqlite3_mprintf(
6053           "%s))"
6054           " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6055           "   FROM [sha3sum$query]",
6056           sSql.z, iSize);
6057     }
6058     freeText(&sQuery);
6059     freeText(&sSql);
6060     if( bDebug ){
6061       utf8_printf(p->out, "%s\n", zSql);
6062     }else{
6063       shell_exec(p->db, zSql, shell_callback, p, 0);
6064     }
6065     sqlite3_free(zSql);
6066   }else
6067
6068   if( c=='s'
6069    && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6070   ){
6071     char *zCmd;
6072     int i, x;
6073     if( nArg<2 ){
6074       raw_printf(stderr, "Usage: .system COMMAND\n");
6075       rc = 1;
6076       goto meta_command_exit;
6077     }
6078     zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6079     for(i=2; i<nArg; i++){
6080       zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6081                              zCmd, azArg[i]);
6082     }
6083     x = system(zCmd);
6084     sqlite3_free(zCmd);
6085     if( x ) raw_printf(stderr, "System command returns %d\n", x);
6086   }else
6087
6088   if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
6089     static const char *azBool[] = { "off", "on", "full", "unk" };
6090     int i;
6091     if( nArg!=1 ){
6092       raw_printf(stderr, "Usage: .show\n");
6093       rc = 1;
6094       goto meta_command_exit;
6095     }
6096     utf8_printf(p->out, "%12.12s: %s\n","echo",
6097                                   azBool[ShellHasFlag(p, SHFLG_Echo)]);
6098     utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6099     utf8_printf(p->out, "%12.12s: %s\n","explain",
6100          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6101     utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6102     utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6103     utf8_printf(p->out, "%12.12s: ", "nullvalue");
6104       output_c_string(p->out, p->nullValue);
6105       raw_printf(p->out, "\n");
6106     utf8_printf(p->out,"%12.12s: %s\n","output",
6107             strlen30(p->outfile) ? p->outfile : "stdout");
6108     utf8_printf(p->out,"%12.12s: ", "colseparator");
6109       output_c_string(p->out, p->colSeparator);
6110       raw_printf(p->out, "\n");
6111     utf8_printf(p->out,"%12.12s: ", "rowseparator");
6112       output_c_string(p->out, p->rowSeparator);
6113       raw_printf(p->out, "\n");
6114     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6115     utf8_printf(p->out, "%12.12s: ", "width");
6116     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6117       raw_printf(p->out, "%d ", p->colWidth[i]);
6118     }
6119     raw_printf(p->out, "\n");
6120     utf8_printf(p->out, "%12.12s: %s\n", "filename",
6121                 p->zDbFilename ? p->zDbFilename : "");
6122   }else
6123
6124   if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6125     if( nArg==2 ){
6126       p->statsOn = booleanValue(azArg[1]);
6127     }else if( nArg==1 ){
6128       display_stats(p->db, p, 0);
6129     }else{
6130       raw_printf(stderr, "Usage: .stats ?on|off?\n");
6131       rc = 1;
6132     }
6133   }else
6134
6135   if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6136    || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6137                  || strncmp(azArg[0], "indexes", n)==0) )
6138   ){
6139     sqlite3_stmt *pStmt;
6140     char **azResult;
6141     int nRow, nAlloc;
6142     char *zSql = 0;
6143     int ii;
6144     open_db(p, 0);
6145     rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6146     if( rc ) return shellDatabaseError(p->db);
6147
6148     /* Create an SQL statement to query for the list of tables in the
6149     ** main and all attached databases where the table name matches the
6150     ** LIKE pattern bound to variable "?1". */
6151     if( c=='t' ){
6152       zSql = sqlite3_mprintf(
6153           "SELECT name FROM sqlite_master"
6154           " WHERE type IN ('table','view')"
6155           "   AND name NOT LIKE 'sqlite_%%'"
6156           "   AND name LIKE ?1");
6157     }else if( nArg>2 ){
6158       /* It is an historical accident that the .indexes command shows an error
6159       ** when called with the wrong number of arguments whereas the .tables
6160       ** command does not. */
6161       raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6162       rc = 1;
6163       goto meta_command_exit;
6164     }else{
6165       zSql = sqlite3_mprintf(
6166           "SELECT name FROM sqlite_master"
6167           " WHERE type='index'"
6168           "   AND tbl_name LIKE ?1");
6169     }
6170     for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6171       const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6172       if( zDbName==0 || ii==0 ) continue;
6173       if( c=='t' ){
6174         zSql = sqlite3_mprintf(
6175                  "%z UNION ALL "
6176                  "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6177                  " WHERE type IN ('table','view')"
6178                  "   AND name NOT LIKE 'sqlite_%%'"
6179                  "   AND name LIKE ?1", zSql, zDbName, zDbName);
6180       }else{
6181         zSql = sqlite3_mprintf(
6182                  "%z UNION ALL "
6183                  "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6184                  " WHERE type='index'"
6185                  "   AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
6186       }
6187     }
6188     rc = sqlite3_finalize(pStmt);
6189     if( zSql && rc==SQLITE_OK ){
6190       zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6191       if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6192     }
6193     sqlite3_free(zSql);
6194     if( !zSql ) return shellNomemError();
6195     if( rc ) return shellDatabaseError(p->db);
6196
6197     /* Run the SQL statement prepared by the above block. Store the results
6198     ** as an array of nul-terminated strings in azResult[].  */
6199     nRow = nAlloc = 0;
6200     azResult = 0;
6201     if( nArg>1 ){
6202       sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6203     }else{
6204       sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6205     }
6206     while( sqlite3_step(pStmt)==SQLITE_ROW ){
6207       if( nRow>=nAlloc ){
6208         char **azNew;
6209         int n2 = nAlloc*2 + 10;
6210         azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6211         if( azNew==0 ){
6212           rc = shellNomemError();
6213           break;
6214         }
6215         nAlloc = n2;
6216         azResult = azNew;
6217       }
6218       azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6219       if( 0==azResult[nRow] ){
6220         rc = shellNomemError();
6221         break;
6222       }
6223       nRow++;
6224     }
6225     if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6226       rc = shellDatabaseError(p->db);
6227     }
6228
6229     /* Pretty-print the contents of array azResult[] to the output */
6230     if( rc==0 && nRow>0 ){
6231       int len, maxlen = 0;
6232       int i, j;
6233       int nPrintCol, nPrintRow;
6234       for(i=0; i<nRow; i++){
6235         len = strlen30(azResult[i]);
6236         if( len>maxlen ) maxlen = len;
6237       }
6238       nPrintCol = 80/(maxlen+2);
6239       if( nPrintCol<1 ) nPrintCol = 1;
6240       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6241       for(i=0; i<nPrintRow; i++){
6242         for(j=i; j<nRow; j+=nPrintRow){
6243           char *zSp = j<nPrintRow ? "" : "  ";
6244           utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6245                       azResult[j] ? azResult[j]:"");
6246         }
6247         raw_printf(p->out, "\n");
6248       }
6249     }
6250
6251     for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6252     sqlite3_free(azResult);
6253   }else
6254
6255   /* Begin redirecting output to the file "testcase-out.txt" */
6256   if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6257     output_reset(p);
6258     p->out = output_file_open("testcase-out.txt");
6259     if( p->out==0 ){
6260       raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
6261     }
6262     if( nArg>=2 ){
6263       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6264     }else{
6265       sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6266     }
6267   }else
6268
6269 #ifndef SQLITE_UNTESTABLE
6270   if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
6271     static const struct {
6272        const char *zCtrlName;   /* Name of a test-control option */
6273        int ctrlCode;            /* Integer code for that option */
6274     } aCtrl[] = {
6275       { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
6276       { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
6277       { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
6278       { "bitvec_test",           SQLITE_TESTCTRL_BITVEC_TEST            },
6279       { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
6280       { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
6281       { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
6282       { "assert",                SQLITE_TESTCTRL_ASSERT                 },
6283       { "always",                SQLITE_TESTCTRL_ALWAYS                 },
6284       { "reserve",               SQLITE_TESTCTRL_RESERVE                },
6285       { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
6286       { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
6287       { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
6288       { "byteorder",             SQLITE_TESTCTRL_BYTEORDER              },
6289       { "never_corrupt",         SQLITE_TESTCTRL_NEVER_CORRUPT          },
6290       { "imposter",              SQLITE_TESTCTRL_IMPOSTER               },
6291     };
6292     int testctrl = -1;
6293     int rc2 = 0;
6294     int i, n2;
6295     open_db(p, 0);
6296
6297     /* convert testctrl text option to value. allow any unique prefix
6298     ** of the option name, or a numerical value. */
6299     n2 = strlen30(azArg[1]);
6300     for(i=0; i<ArraySize(aCtrl); i++){
6301       if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
6302         if( testctrl<0 ){
6303           testctrl = aCtrl[i].ctrlCode;
6304         }else{
6305           utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
6306           testctrl = -1;
6307           break;
6308         }
6309       }
6310     }
6311     if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
6312     if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
6313       utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
6314     }else{
6315       switch(testctrl){
6316
6317         /* sqlite3_test_control(int, db, int) */
6318         case SQLITE_TESTCTRL_OPTIMIZATIONS:
6319         case SQLITE_TESTCTRL_RESERVE:
6320           if( nArg==3 ){
6321             int opt = (int)strtol(azArg[2], 0, 0);
6322             rc2 = sqlite3_test_control(testctrl, p->db, opt);
6323             raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6324           } else {
6325             utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
6326                     azArg[1]);
6327           }
6328           break;
6329
6330         /* sqlite3_test_control(int) */
6331         case SQLITE_TESTCTRL_PRNG_SAVE:
6332         case SQLITE_TESTCTRL_PRNG_RESTORE:
6333         case SQLITE_TESTCTRL_PRNG_RESET:
6334         case SQLITE_TESTCTRL_BYTEORDER:
6335           if( nArg==2 ){
6336             rc2 = sqlite3_test_control(testctrl);
6337             raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6338           } else {
6339             utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6340                         azArg[1]);
6341           }
6342           break;
6343
6344         /* sqlite3_test_control(int, uint) */
6345         case SQLITE_TESTCTRL_PENDING_BYTE:
6346           if( nArg==3 ){
6347             unsigned int opt = (unsigned int)integerValue(azArg[2]);
6348             rc2 = sqlite3_test_control(testctrl, opt);
6349             raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6350           } else {
6351             utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
6352                            " int option\n", azArg[1]);
6353           }
6354           break;
6355
6356         /* sqlite3_test_control(int, int) */
6357         case SQLITE_TESTCTRL_ASSERT:
6358         case SQLITE_TESTCTRL_ALWAYS:
6359         case SQLITE_TESTCTRL_NEVER_CORRUPT:
6360           if( nArg==3 ){
6361             int opt = booleanValue(azArg[2]);
6362             rc2 = sqlite3_test_control(testctrl, opt);
6363             raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6364           } else {
6365             utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
6366                             azArg[1]);
6367           }
6368           break;
6369
6370         /* sqlite3_test_control(int, char *) */
6371 #ifdef SQLITE_N_KEYWORD
6372         case SQLITE_TESTCTRL_ISKEYWORD:
6373           if( nArg==3 ){
6374             const char *opt = azArg[2];
6375             rc2 = sqlite3_test_control(testctrl, opt);
6376             raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6377           } else {
6378             utf8_printf(stderr,
6379                         "Error: testctrl %s takes a single char * option\n",
6380                         azArg[1]);
6381           }
6382           break;
6383 #endif
6384
6385         case SQLITE_TESTCTRL_IMPOSTER:
6386           if( nArg==5 ){
6387             rc2 = sqlite3_test_control(testctrl, p->db,
6388                           azArg[2],
6389                           integerValue(azArg[3]),
6390                           integerValue(azArg[4]));
6391             raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6392           }else{
6393             raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
6394           }
6395           break;
6396
6397         case SQLITE_TESTCTRL_BITVEC_TEST:
6398         case SQLITE_TESTCTRL_FAULT_INSTALL:
6399         case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6400         case SQLITE_TESTCTRL_SCRATCHMALLOC:
6401         default:
6402           utf8_printf(stderr,
6403                       "Error: CLI support for testctrl %s not implemented\n",
6404                       azArg[1]);
6405           break;
6406       }
6407     }
6408   }else
6409 #endif /* !defined(SQLITE_UNTESTABLE) */
6410
6411   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
6412     open_db(p, 0);
6413     sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
6414   }else
6415
6416   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6417     if( nArg==2 ){
6418       enableTimer = booleanValue(azArg[1]);
6419       if( enableTimer && !HAS_TIMER ){
6420         raw_printf(stderr, "Error: timer not available on this system.\n");
6421         enableTimer = 0;
6422       }
6423     }else{
6424       raw_printf(stderr, "Usage: .timer on|off\n");
6425       rc = 1;
6426     }
6427   }else
6428
6429   if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
6430     open_db(p, 0);
6431     if( nArg!=2 ){
6432       raw_printf(stderr, "Usage: .trace FILE|off\n");
6433       rc = 1;
6434       goto meta_command_exit;
6435     }
6436     output_file_close(p->traceOut);
6437     p->traceOut = output_file_open(azArg[1]);
6438 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6439     if( p->traceOut==0 ){
6440       sqlite3_trace_v2(p->db, 0, 0, 0);
6441     }else{
6442       sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
6443     }
6444 #endif
6445   }else
6446
6447 #if SQLITE_USER_AUTHENTICATION
6448   if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6449     if( nArg<2 ){
6450       raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
6451       rc = 1;
6452       goto meta_command_exit;
6453     }
6454     open_db(p, 0);
6455     if( strcmp(azArg[1],"login")==0 ){
6456       if( nArg!=4 ){
6457         raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
6458         rc = 1;
6459         goto meta_command_exit;
6460       }
6461       rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6462                                     (int)strlen(azArg[3]));
6463       if( rc ){
6464         utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
6465         rc = 1;
6466       }
6467     }else if( strcmp(azArg[1],"add")==0 ){
6468       if( nArg!=5 ){
6469         raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
6470         rc = 1;
6471         goto meta_command_exit;
6472       }
6473       rc = sqlite3_user_add(p->db, azArg[2],
6474                             azArg[3], (int)strlen(azArg[3]),
6475                             booleanValue(azArg[4]));
6476       if( rc ){
6477         raw_printf(stderr, "User-Add failed: %d\n", rc);
6478         rc = 1;
6479       }
6480     }else if( strcmp(azArg[1],"edit")==0 ){
6481       if( nArg!=5 ){
6482         raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
6483         rc = 1;
6484         goto meta_command_exit;
6485       }
6486       rc = sqlite3_user_change(p->db, azArg[2],
6487                               azArg[3], (int)strlen(azArg[3]),
6488                               booleanValue(azArg[4]));
6489       if( rc ){
6490         raw_printf(stderr, "User-Edit failed: %d\n", rc);
6491         rc = 1;
6492       }
6493     }else if( strcmp(azArg[1],"delete")==0 ){
6494       if( nArg!=3 ){
6495         raw_printf(stderr, "Usage: .user delete USER\n");
6496         rc = 1;
6497         goto meta_command_exit;
6498       }
6499       rc = sqlite3_user_delete(p->db, azArg[2]);
6500       if( rc ){
6501         raw_printf(stderr, "User-Delete failed: %d\n", rc);
6502         rc = 1;
6503       }
6504     }else{
6505       raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
6506       rc = 1;
6507       goto meta_command_exit;
6508     }
6509   }else
6510 #endif /* SQLITE_USER_AUTHENTICATION */
6511
6512   if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
6513     utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
6514         sqlite3_libversion(), sqlite3_sourceid());
6515   }else
6516
6517   if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6518     const char *zDbName = nArg==2 ? azArg[1] : "main";
6519     sqlite3_vfs *pVfs = 0;
6520     if( p->db ){
6521       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6522       if( pVfs ){
6523         utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
6524         raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
6525         raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
6526         raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6527       }
6528     }
6529   }else
6530
6531   if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6532     sqlite3_vfs *pVfs;
6533     sqlite3_vfs *pCurrent = 0;
6534     if( p->db ){
6535       sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6536     }
6537     for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6538       utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
6539            pVfs==pCurrent ? "  <--- CURRENT" : "");
6540       raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
6541       raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
6542       raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6543       if( pVfs->pNext ){
6544         raw_printf(p->out, "-----------------------------------\n");
6545       }
6546     }
6547   }else
6548
6549   if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6550     const char *zDbName = nArg==2 ? azArg[1] : "main";
6551     char *zVfsName = 0;
6552     if( p->db ){
6553       sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6554       if( zVfsName ){
6555         utf8_printf(p->out, "%s\n", zVfsName);
6556         sqlite3_free(zVfsName);
6557       }
6558     }
6559   }else
6560
6561 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6562   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
6563     sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
6564   }else
6565 #endif
6566
6567   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
6568     int j;
6569     assert( nArg<=ArraySize(azArg) );
6570     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
6571       p->colWidth[j-1] = (int)integerValue(azArg[j]);
6572     }
6573   }else
6574
6575   {
6576     utf8_printf(stderr, "Error: unknown command or invalid arguments: "
6577       " \"%s\". Enter \".help\" for help\n", azArg[0]);
6578     rc = 1;
6579   }
6580
6581 meta_command_exit:
6582   if( p->outCount ){
6583     p->outCount--;
6584     if( p->outCount==0 ) output_reset(p);
6585   }
6586   return rc;
6587 }
6588
6589 /*
6590 ** Return TRUE if a semicolon occurs anywhere in the first N characters
6591 ** of string z[].
6592 */
6593 static int line_contains_semicolon(const char *z, int N){
6594   int i;
6595   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
6596   return 0;
6597 }
6598
6599 /*
6600 ** Test to see if a line consists entirely of whitespace.
6601 */
6602 static int _all_whitespace(const char *z){
6603   for(; *z; z++){
6604     if( IsSpace(z[0]) ) continue;
6605     if( *z=='/' && z[1]=='*' ){
6606       z += 2;
6607       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6608       if( *z==0 ) return 0;
6609       z++;
6610       continue;
6611     }
6612     if( *z=='-' && z[1]=='-' ){
6613       z += 2;
6614       while( *z && *z!='\n' ){ z++; }
6615       if( *z==0 ) return 1;
6616       continue;
6617     }
6618     return 0;
6619   }
6620   return 1;
6621 }
6622
6623 /*
6624 ** Return TRUE if the line typed in is an SQL command terminator other
6625 ** than a semi-colon.  The SQL Server style "go" command is understood
6626 ** as is the Oracle "/".
6627 */
6628 static int line_is_command_terminator(const char *zLine){
6629   while( IsSpace(zLine[0]) ){ zLine++; };
6630   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6631     return 1;  /* Oracle */
6632   }
6633   if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
6634          && _all_whitespace(&zLine[2]) ){
6635     return 1;  /* SQL Server */
6636   }
6637   return 0;
6638 }
6639
6640 /*
6641 ** Return true if zSql is a complete SQL statement.  Return false if it
6642 ** ends in the middle of a string literal or C-style comment.
6643 */
6644 static int line_is_complete(char *zSql, int nSql){
6645   int rc;
6646   if( zSql==0 ) return 1;
6647   zSql[nSql] = ';';
6648   zSql[nSql+1] = 0;
6649   rc = sqlite3_complete(zSql);
6650   zSql[nSql] = 0;
6651   return rc;
6652 }
6653
6654 /*
6655 ** Run a single line of SQL
6656 */
6657 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6658   int rc;
6659   char *zErrMsg = 0;
6660
6661   open_db(p, 0);
6662   if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
6663   BEGIN_TIMER;
6664   rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6665   END_TIMER;
6666   if( rc || zErrMsg ){
6667     char zPrefix[100];
6668     if( in!=0 || !stdin_is_interactive ){
6669       sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6670                        "Error: near line %d:", startline);
6671     }else{
6672       sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6673     }
6674     if( zErrMsg!=0 ){
6675       utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6676       sqlite3_free(zErrMsg);
6677       zErrMsg = 0;
6678     }else{
6679       utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6680     }
6681     return 1;
6682   }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
6683     raw_printf(p->out, "changes: %3d   total_changes: %d\n",
6684             sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6685   }
6686   return 0;
6687 }
6688
6689
6690 /*
6691 ** Read input from *in and process it.  If *in==0 then input
6692 ** is interactive - the user is typing it it.  Otherwise, input
6693 ** is coming from a file or device.  A prompt is issued and history
6694 ** is saved only if input is interactive.  An interrupt signal will
6695 ** cause this routine to exit immediately, unless input is interactive.
6696 **
6697 ** Return the number of errors.
6698 */
6699 static int process_input(ShellState *p, FILE *in){
6700   char *zLine = 0;          /* A single input line */
6701   char *zSql = 0;           /* Accumulated SQL text */
6702   int nLine;                /* Length of current line */
6703   int nSql = 0;             /* Bytes of zSql[] used */
6704   int nAlloc = 0;           /* Allocated zSql[] space */
6705   int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
6706   int rc;                   /* Error code */
6707   int errCnt = 0;           /* Number of errors seen */
6708   int lineno = 0;           /* Current line number */
6709   int startline = 0;        /* Line number for start of current input */
6710
6711   while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6712     fflush(p->out);
6713     zLine = one_input_line(in, zLine, nSql>0);
6714     if( zLine==0 ){
6715       /* End of input */
6716       if( in==0 && stdin_is_interactive ) printf("\n");
6717       break;
6718     }
6719     if( seenInterrupt ){
6720       if( in!=0 ) break;
6721       seenInterrupt = 0;
6722     }
6723     lineno++;
6724     if( nSql==0 && _all_whitespace(zLine) ){
6725       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6726       continue;
6727     }
6728     if( zLine && zLine[0]=='.' && nSql==0 ){
6729       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6730       rc = do_meta_command(zLine, p);
6731       if( rc==2 ){ /* exit requested */
6732         break;
6733       }else if( rc ){
6734         errCnt++;
6735       }
6736       continue;
6737     }
6738     if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
6739       memcpy(zLine,";",2);
6740     }
6741     nLine = strlen30(zLine);
6742     if( nSql+nLine+2>=nAlloc ){
6743       nAlloc = nSql+nLine+100;
6744       zSql = realloc(zSql, nAlloc);
6745       if( zSql==0 ){
6746         raw_printf(stderr, "Error: out of memory\n");
6747         exit(1);
6748       }
6749     }
6750     nSqlPrior = nSql;
6751     if( nSql==0 ){
6752       int i;
6753       for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
6754       assert( nAlloc>0 && zSql!=0 );
6755       memcpy(zSql, zLine+i, nLine+1-i);
6756       startline = lineno;
6757       nSql = nLine-i;
6758     }else{
6759       zSql[nSql++] = '\n';
6760       memcpy(zSql+nSql, zLine, nLine+1);
6761       nSql += nLine;
6762     }
6763     if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
6764                 && sqlite3_complete(zSql) ){
6765       errCnt += runOneSqlLine(p, zSql, in, startline);
6766       nSql = 0;
6767       if( p->outCount ){
6768         output_reset(p);
6769         p->outCount = 0;
6770       }
6771     }else if( nSql && _all_whitespace(zSql) ){
6772       if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
6773       nSql = 0;
6774     }
6775   }
6776   if( nSql && !_all_whitespace(zSql) ){
6777     runOneSqlLine(p, zSql, in, startline);
6778   }
6779   free(zSql);
6780   free(zLine);
6781   return errCnt>0;
6782 }
6783
6784 /*
6785 ** Return a pathname which is the user's home directory.  A
6786 ** 0 return indicates an error of some kind.
6787 */
6788 static char *find_home_dir(int clearFlag){
6789   static char *home_dir = NULL;
6790   if( clearFlag ){
6791     free(home_dir);
6792     home_dir = 0;
6793     return 0;
6794   }
6795   if( home_dir ) return home_dir;
6796
6797 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6798      && !defined(__RTP__) && !defined(_WRS_KERNEL)
6799   {
6800     struct passwd *pwent;
6801     uid_t uid = getuid();
6802     if( (pwent=getpwuid(uid)) != NULL) {
6803       home_dir = pwent->pw_dir;
6804     }
6805   }
6806 #endif
6807
6808 #if defined(_WIN32_WCE)
6809   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6810    */
6811   home_dir = "/";
6812 #else
6813
6814 #if defined(_WIN32) || defined(WIN32)
6815   if (!home_dir) {
6816     home_dir = getenv("USERPROFILE");
6817   }
6818 #endif
6819
6820   if (!home_dir) {
6821     home_dir = getenv("HOME");
6822   }
6823
6824 #if defined(_WIN32) || defined(WIN32)
6825   if (!home_dir) {
6826     char *zDrive, *zPath;
6827     int n;
6828     zDrive = getenv("HOMEDRIVE");
6829     zPath = getenv("HOMEPATH");
6830     if( zDrive && zPath ){
6831       n = strlen30(zDrive) + strlen30(zPath) + 1;
6832       home_dir = malloc( n );
6833       if( home_dir==0 ) return 0;
6834       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6835       return home_dir;
6836     }
6837     home_dir = "c:\\";
6838   }
6839 #endif
6840
6841 #endif /* !_WIN32_WCE */
6842
6843   if( home_dir ){
6844     int n = strlen30(home_dir) + 1;
6845     char *z = malloc( n );
6846     if( z ) memcpy(z, home_dir, n);
6847     home_dir = z;
6848   }
6849
6850   return home_dir;
6851 }
6852
6853 /*
6854 ** Read input from the file given by sqliterc_override.  Or if that
6855 ** parameter is NULL, take input from ~/.sqliterc
6856 **
6857 ** Returns the number of errors.
6858 */
6859 static void process_sqliterc(
6860   ShellState *p,                  /* Configuration data */
6861   const char *sqliterc_override   /* Name of config file. NULL to use default */
6862 ){
6863   char *home_dir = NULL;
6864   const char *sqliterc = sqliterc_override;
6865   char *zBuf = 0;
6866   FILE *in = NULL;
6867
6868   if (sqliterc == NULL) {
6869     home_dir = find_home_dir(0);
6870     if( home_dir==0 ){
6871       raw_printf(stderr, "-- warning: cannot find home directory;"
6872                       " cannot read ~/.sqliterc\n");
6873       return;
6874     }
6875     sqlite3_initialize();
6876     zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6877     sqliterc = zBuf;
6878   }
6879   in = fopen(sqliterc,"rb");
6880   if( in ){
6881     if( stdin_is_interactive ){
6882       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
6883     }
6884     process_input(p,in);
6885     fclose(in);
6886   }
6887   sqlite3_free(zBuf);
6888 }
6889
6890 /*
6891 ** Show available command line options
6892 */
6893 static const char zOptions[] =
6894   "   -ascii               set output mode to 'ascii'\n"
6895   "   -bail                stop after hitting an error\n"
6896   "   -batch               force batch I/O\n"
6897   "   -column              set output mode to 'column'\n"
6898   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
6899   "   -csv                 set output mode to 'csv'\n"
6900   "   -echo                print commands before execution\n"
6901   "   -init FILENAME       read/process named file\n"
6902   "   -[no]header          turn headers on or off\n"
6903 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6904   "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
6905 #endif
6906   "   -help                show this message\n"
6907   "   -html                set output mode to HTML\n"
6908   "   -interactive         force interactive I/O\n"
6909   "   -line                set output mode to 'line'\n"
6910   "   -list                set output mode to 'list'\n"
6911   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
6912   "   -mmap N              default mmap size set to N\n"
6913 #ifdef SQLITE_ENABLE_MULTIPLEX
6914   "   -multiplex           enable the multiplexor VFS\n"
6915 #endif
6916   "   -newline SEP         set output row separator. Default: '\\n'\n"
6917   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
6918   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
6919   "   -scratch SIZE N      use N slots of SZ bytes each for scratch memory\n"
6920   "   -separator SEP       set output column separator. Default: '|'\n"
6921   "   -stats               print memory stats before each finalize\n"
6922   "   -version             show SQLite version\n"
6923   "   -vfs NAME            use NAME as the default VFS\n"
6924 #ifdef SQLITE_ENABLE_VFSTRACE
6925   "   -vfstrace            enable tracing of all VFS calls\n"
6926 #endif
6927 ;
6928 static void usage(int showDetail){
6929   utf8_printf(stderr,
6930       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6931       "FILENAME is the name of an SQLite database. A new database is created\n"
6932       "if the file does not previously exist.\n", Argv0);
6933   if( showDetail ){
6934     utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
6935   }else{
6936     raw_printf(stderr, "Use the -help option for additional information\n");
6937   }
6938   exit(1);
6939 }
6940
6941 /*
6942 ** Initialize the state information in data
6943 */
6944 static void main_init(ShellState *data) {
6945   memset(data, 0, sizeof(*data));
6946   data->normalMode = data->cMode = data->mode = MODE_List;
6947   data->autoExplain = 1;
6948   memcpy(data->colSeparator,SEP_Column, 2);
6949   memcpy(data->rowSeparator,SEP_Row, 2);
6950   data->showHeader = 0;
6951   data->shellFlgs = SHFLG_Lookaside;
6952   sqlite3_config(SQLITE_CONFIG_URI, 1);
6953   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
6954   sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
6955   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6956   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
6957 }
6958
6959 /*
6960 ** Output text to the console in a font that attracts extra attention.
6961 */
6962 #ifdef _WIN32
6963 static void printBold(const char *zText){
6964   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
6965   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
6966   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
6967   SetConsoleTextAttribute(out,
6968          FOREGROUND_RED|FOREGROUND_INTENSITY
6969   );
6970   printf("%s", zText);
6971   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
6972 }
6973 #else
6974 static void printBold(const char *zText){
6975   printf("\033[1m%s\033[0m", zText);
6976 }
6977 #endif
6978
6979 /*
6980 ** Get the argument to an --option.  Throw an error and die if no argument
6981 ** is available.
6982 */
6983 static char *cmdline_option_value(int argc, char **argv, int i){
6984   if( i==argc ){
6985     utf8_printf(stderr, "%s: Error: missing argument to %s\n",
6986             argv[0], argv[argc-1]);
6987     exit(1);
6988   }
6989   return argv[i];
6990 }
6991
6992 #ifndef SQLITE_SHELL_IS_UTF8
6993 #  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6994 #    define SQLITE_SHELL_IS_UTF8          (0)
6995 #  else
6996 #    define SQLITE_SHELL_IS_UTF8          (1)
6997 #  endif
6998 #endif
6999
7000 #if SQLITE_SHELL_IS_UTF8
7001 int SQLITE_CDECL main(int argc, char **argv){
7002 #else
7003 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7004   char **argv;
7005 #endif
7006   char *zErrMsg = 0;
7007   ShellState data;
7008   const char *zInitFile = 0;
7009   int i;
7010   int rc = 0;
7011   int warnInmemoryDb = 0;
7012   int readStdin = 1;
7013   int nCmd = 0;
7014   char **azCmd = 0;
7015
7016   setBinaryMode(stdin, 0);
7017   setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7018   stdin_is_interactive = isatty(0);
7019   stdout_is_console = isatty(1);
7020
7021 #if USE_SYSTEM_SQLITE+0!=1
7022   if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
7023     utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7024             sqlite3_sourceid(), SQLITE_SOURCE_ID);
7025     exit(1);
7026   }
7027 #endif
7028   main_init(&data);
7029 #if !SQLITE_SHELL_IS_UTF8
7030   sqlite3_initialize();
7031   argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7032   if( argv==0 ){
7033     raw_printf(stderr, "out of memory\n");
7034     exit(1);
7035   }
7036   for(i=0; i<argc; i++){
7037     argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7038     if( argv[i]==0 ){
7039       raw_printf(stderr, "out of memory\n");
7040       exit(1);
7041     }
7042   }
7043 #endif
7044   assert( argc>=1 && argv && argv[0] );
7045   Argv0 = argv[0];
7046
7047   /* Make sure we have a valid signal handler early, before anything
7048   ** else is done.
7049   */
7050 #ifdef SIGINT
7051   signal(SIGINT, interrupt_handler);
7052 #endif
7053
7054 #ifdef SQLITE_SHELL_DBNAME_PROC
7055   {
7056     /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7057     ** of a C-function that will provide the name of the database file.  Use
7058     ** this compile-time option to embed this shell program in larger
7059     ** applications. */
7060     extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7061     SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7062     warnInmemoryDb = 0;
7063   }
7064 #endif
7065
7066   /* Do an initial pass through the command-line argument to locate
7067   ** the name of the database file, the name of the initialization file,
7068   ** the size of the alternative malloc heap,
7069   ** and the first command to execute.
7070   */
7071   for(i=1; i<argc; i++){
7072     char *z;
7073     z = argv[i];
7074     if( z[0]!='-' ){
7075       if( data.zDbFilename==0 ){
7076         data.zDbFilename = z;
7077       }else{
7078         /* Excesss arguments are interpreted as SQL (or dot-commands) and
7079         ** mean that nothing is read from stdin */
7080         readStdin = 0;
7081         nCmd++;
7082         azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7083         if( azCmd==0 ){
7084           raw_printf(stderr, "out of memory\n");
7085           exit(1);
7086         }
7087         azCmd[nCmd-1] = z;
7088       }
7089     }
7090     if( z[1]=='-' ) z++;
7091     if( strcmp(z,"-separator")==0
7092      || strcmp(z,"-nullvalue")==0
7093      || strcmp(z,"-newline")==0
7094      || strcmp(z,"-cmd")==0
7095     ){
7096       (void)cmdline_option_value(argc, argv, ++i);
7097     }else if( strcmp(z,"-init")==0 ){
7098       zInitFile = cmdline_option_value(argc, argv, ++i);
7099     }else if( strcmp(z,"-batch")==0 ){
7100       /* Need to check for batch mode here to so we can avoid printing
7101       ** informational messages (like from process_sqliterc) before
7102       ** we do the actual processing of arguments later in a second pass.
7103       */
7104       stdin_is_interactive = 0;
7105     }else if( strcmp(z,"-heap")==0 ){
7106 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7107       const char *zSize;
7108       sqlite3_int64 szHeap;
7109
7110       zSize = cmdline_option_value(argc, argv, ++i);
7111       szHeap = integerValue(zSize);
7112       if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7113       sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7114 #else
7115       (void)cmdline_option_value(argc, argv, ++i);
7116 #endif
7117     }else if( strcmp(z,"-scratch")==0 ){
7118       int n, sz;
7119       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7120       if( sz>400000 ) sz = 400000;
7121       if( sz<2500 ) sz = 2500;
7122       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7123       if( n>10 ) n = 10;
7124       if( n<1 ) n = 1;
7125       sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7126       data.shellFlgs |= SHFLG_Scratch;
7127     }else if( strcmp(z,"-pagecache")==0 ){
7128       int n, sz;
7129       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7130       if( sz>70000 ) sz = 70000;
7131       if( sz<0 ) sz = 0;
7132       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7133       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7134                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7135       data.shellFlgs |= SHFLG_Pagecache;
7136     }else if( strcmp(z,"-lookaside")==0 ){
7137       int n, sz;
7138       sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7139       if( sz<0 ) sz = 0;
7140       n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7141       if( n<0 ) n = 0;
7142       sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7143       if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7144 #ifdef SQLITE_ENABLE_VFSTRACE
7145     }else if( strcmp(z,"-vfstrace")==0 ){
7146       extern int vfstrace_register(
7147          const char *zTraceName,
7148          const char *zOldVfsName,
7149          int (*xOut)(const char*,void*),
7150          void *pOutArg,
7151          int makeDefault
7152       );
7153       vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7154 #endif
7155 #ifdef SQLITE_ENABLE_MULTIPLEX
7156     }else if( strcmp(z,"-multiplex")==0 ){
7157       extern int sqlite3_multiple_initialize(const char*,int);
7158       sqlite3_multiplex_initialize(0, 1);
7159 #endif
7160     }else if( strcmp(z,"-mmap")==0 ){
7161       sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7162       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7163     }else if( strcmp(z,"-vfs")==0 ){
7164       sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7165       if( pVfs ){
7166         sqlite3_vfs_register(pVfs, 1);
7167       }else{
7168         utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7169         exit(1);
7170       }
7171     }
7172   }
7173   if( data.zDbFilename==0 ){
7174 #ifndef SQLITE_OMIT_MEMORYDB
7175     data.zDbFilename = ":memory:";
7176     warnInmemoryDb = argc==1;
7177 #else
7178     utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7179     return 1;
7180 #endif
7181   }
7182   data.out = stdout;
7183
7184   /* Go ahead and open the database file if it already exists.  If the
7185   ** file does not exist, delay opening it.  This prevents empty database
7186   ** files from being created if a user mistypes the database name argument
7187   ** to the sqlite command-line tool.
7188   */
7189   if( access(data.zDbFilename, 0)==0 ){
7190     open_db(&data, 0);
7191   }
7192
7193   /* Process the initialization file if there is one.  If no -init option
7194   ** is given on the command line, look for a file named ~/.sqliterc and
7195   ** try to process it.
7196   */
7197   process_sqliterc(&data,zInitFile);
7198
7199   /* Make a second pass through the command-line argument and set
7200   ** options.  This second pass is delayed until after the initialization
7201   ** file is processed so that the command-line arguments will override
7202   ** settings in the initialization file.
7203   */
7204   for(i=1; i<argc; i++){
7205     char *z = argv[i];
7206     if( z[0]!='-' ) continue;
7207     if( z[1]=='-' ){ z++; }
7208     if( strcmp(z,"-init")==0 ){
7209       i++;
7210     }else if( strcmp(z,"-html")==0 ){
7211       data.mode = MODE_Html;
7212     }else if( strcmp(z,"-list")==0 ){
7213       data.mode = MODE_List;
7214     }else if( strcmp(z,"-line")==0 ){
7215       data.mode = MODE_Line;
7216     }else if( strcmp(z,"-column")==0 ){
7217       data.mode = MODE_Column;
7218     }else if( strcmp(z,"-csv")==0 ){
7219       data.mode = MODE_Csv;
7220       memcpy(data.colSeparator,",",2);
7221     }else if( strcmp(z,"-ascii")==0 ){
7222       data.mode = MODE_Ascii;
7223       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7224                        SEP_Unit);
7225       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7226                        SEP_Record);
7227     }else if( strcmp(z,"-separator")==0 ){
7228       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7229                        "%s",cmdline_option_value(argc,argv,++i));
7230     }else if( strcmp(z,"-newline")==0 ){
7231       sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7232                        "%s",cmdline_option_value(argc,argv,++i));
7233     }else if( strcmp(z,"-nullvalue")==0 ){
7234       sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
7235                        "%s",cmdline_option_value(argc,argv,++i));
7236     }else if( strcmp(z,"-header")==0 ){
7237       data.showHeader = 1;
7238     }else if( strcmp(z,"-noheader")==0 ){
7239       data.showHeader = 0;
7240     }else if( strcmp(z,"-echo")==0 ){
7241       ShellSetFlag(&data, SHFLG_Echo);
7242     }else if( strcmp(z,"-eqp")==0 ){
7243       data.autoEQP = 1;
7244     }else if( strcmp(z,"-eqpfull")==0 ){
7245       data.autoEQP = 2;
7246     }else if( strcmp(z,"-stats")==0 ){
7247       data.statsOn = 1;
7248     }else if( strcmp(z,"-scanstats")==0 ){
7249       data.scanstatsOn = 1;
7250     }else if( strcmp(z,"-backslash")==0 ){
7251       /* Undocumented command-line option: -backslash
7252       ** Causes C-style backslash escapes to be evaluated in SQL statements
7253       ** prior to sending the SQL into SQLite.  Useful for injecting
7254       ** crazy bytes in the middle of SQL statements for testing and debugging.
7255       */
7256       ShellSetFlag(&data, SHFLG_Backslash);
7257     }else if( strcmp(z,"-bail")==0 ){
7258       bail_on_error = 1;
7259     }else if( strcmp(z,"-version")==0 ){
7260       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
7261       return 0;
7262     }else if( strcmp(z,"-interactive")==0 ){
7263       stdin_is_interactive = 1;
7264     }else if( strcmp(z,"-batch")==0 ){
7265       stdin_is_interactive = 0;
7266     }else if( strcmp(z,"-heap")==0 ){
7267       i++;
7268     }else if( strcmp(z,"-scratch")==0 ){
7269       i+=2;
7270     }else if( strcmp(z,"-pagecache")==0 ){
7271       i+=2;
7272     }else if( strcmp(z,"-lookaside")==0 ){
7273       i+=2;
7274     }else if( strcmp(z,"-mmap")==0 ){
7275       i++;
7276     }else if( strcmp(z,"-vfs")==0 ){
7277       i++;
7278 #ifdef SQLITE_ENABLE_VFSTRACE
7279     }else if( strcmp(z,"-vfstrace")==0 ){
7280       i++;
7281 #endif
7282 #ifdef SQLITE_ENABLE_MULTIPLEX
7283     }else if( strcmp(z,"-multiplex")==0 ){
7284       i++;
7285 #endif
7286     }else if( strcmp(z,"-help")==0 ){
7287       usage(1);
7288     }else if( strcmp(z,"-cmd")==0 ){
7289       /* Run commands that follow -cmd first and separately from commands
7290       ** that simply appear on the command-line.  This seems goofy.  It would
7291       ** be better if all commands ran in the order that they appear.  But
7292       ** we retain the goofy behavior for historical compatibility. */
7293       if( i==argc-1 ) break;
7294       z = cmdline_option_value(argc,argv,++i);
7295       if( z[0]=='.' ){
7296         rc = do_meta_command(z, &data);
7297         if( rc && bail_on_error ) return rc==2 ? 0 : rc;
7298       }else{
7299         open_db(&data, 0);
7300         rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7301         if( zErrMsg!=0 ){
7302           utf8_printf(stderr,"Error: %s\n", zErrMsg);
7303           if( bail_on_error ) return rc!=0 ? rc : 1;
7304         }else if( rc!=0 ){
7305           utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
7306           if( bail_on_error ) return rc;
7307         }
7308       }
7309     }else{
7310       utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7311       raw_printf(stderr,"Use -help for a list of options.\n");
7312       return 1;
7313     }
7314     data.cMode = data.mode;
7315   }
7316
7317   if( !readStdin ){
7318     /* Run all arguments that do not begin with '-' as if they were separate
7319     ** command-line inputs, except for the argToSkip argument which contains
7320     ** the database filename.
7321     */
7322     for(i=0; i<nCmd; i++){
7323       if( azCmd[i][0]=='.' ){
7324         rc = do_meta_command(azCmd[i], &data);
7325         if( rc ) return rc==2 ? 0 : rc;
7326       }else{
7327         open_db(&data, 0);
7328         rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7329         if( zErrMsg!=0 ){
7330           utf8_printf(stderr,"Error: %s\n", zErrMsg);
7331           return rc!=0 ? rc : 1;
7332         }else if( rc!=0 ){
7333           utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
7334           return rc;
7335         }
7336       }
7337     }
7338     free(azCmd);
7339   }else{
7340     /* Run commands received from standard input
7341     */
7342     if( stdin_is_interactive ){
7343       char *zHome;
7344       char *zHistory = 0;
7345       int nHistory;
7346       printf(
7347         "SQLite version %s %.19s\n" /*extra-version-info*/
7348         "Enter \".help\" for usage hints.\n",
7349         sqlite3_libversion(), sqlite3_sourceid()
7350       );
7351       if( warnInmemoryDb ){
7352         printf("Connected to a ");
7353         printBold("transient in-memory database");
7354         printf(".\nUse \".open FILENAME\" to reopen on a "
7355                "persistent database.\n");
7356       }
7357       zHome = find_home_dir(0);
7358       if( zHome ){
7359         nHistory = strlen30(zHome) + 20;
7360         if( (zHistory = malloc(nHistory))!=0 ){
7361           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7362         }
7363       }
7364       if( zHistory ){ shell_read_history(zHistory); }
7365       rc = process_input(&data, 0);
7366       if( zHistory ){
7367         shell_stifle_history(100);
7368         shell_write_history(zHistory);
7369         free(zHistory);
7370       }
7371     }else{
7372       rc = process_input(&data, stdin);
7373     }
7374   }
7375   set_table_name(&data, 0);
7376   if( data.db ){
7377     session_close_all(&data);
7378     sqlite3_close(data.db);
7379   }
7380   sqlite3_free(data.zFreeOnClose);
7381   find_home_dir(1);
7382 #if !SQLITE_SHELL_IS_UTF8
7383   for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7384   sqlite3_free(argv);
7385 #endif
7386   return rc;
7387 }