Merge the ".stat/.eqp" CLI fix from trunk.
[sqlite.git] / src / shell.c.in
blob9032e44d691d8133a823e688a3abb12dbd62ccab
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.
11 *************************************************************************
12 ** This file contains code to implement the "sqlite" command line
13 ** utility for accessing SQLite databases.
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
21 ** Warning pragmas copied from msvc.h in the core.
23 #if defined(_MSC_VER)
24 #pragma warning(disable : 4054)
25 #pragma warning(disable : 4055)
26 #pragma warning(disable : 4100)
27 #pragma warning(disable : 4127)
28 #pragma warning(disable : 4130)
29 #pragma warning(disable : 4152)
30 #pragma warning(disable : 4189)
31 #pragma warning(disable : 4206)
32 #pragma warning(disable : 4210)
33 #pragma warning(disable : 4232)
34 #pragma warning(disable : 4244)
35 #pragma warning(disable : 4305)
36 #pragma warning(disable : 4306)
37 #pragma warning(disable : 4702)
38 #pragma warning(disable : 4706)
39 #endif /* defined(_MSC_VER) */
42 ** No support for loadable extensions in VxWorks.
44 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45 # define SQLITE_OMIT_LOAD_EXTENSION 1
46 #endif
49 ** Enable large-file support for fopen() and friends on unix.
51 #ifndef SQLITE_DISABLE_LFS
52 # define _LARGE_FILE 1
53 # ifndef _FILE_OFFSET_BITS
54 # define _FILE_OFFSET_BITS 64
55 # endif
56 # define _LARGEFILE_SOURCE 1
57 #endif
59 #include <stdlib.h>
60 #include <string.h>
61 #include <stdio.h>
62 #include <assert.h>
63 #include "sqlite3.h"
64 typedef sqlite3_int64 i64;
65 typedef sqlite3_uint64 u64;
66 typedef unsigned char u8;
67 #if SQLITE_USER_AUTHENTICATION
68 # include "sqlite3userauth.h"
69 #endif
70 #include <ctype.h>
71 #include <stdarg.h>
73 #if !defined(_WIN32) && !defined(WIN32)
74 # include <signal.h>
75 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
76 # include <pwd.h>
77 # endif
78 #endif
79 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
80 # include <unistd.h>
81 # include <dirent.h>
82 # if defined(__MINGW32__)
83 # define DIRENT dirent
84 # ifndef S_ISLNK
85 # define S_ISLNK(mode) (0)
86 # endif
87 # endif
88 #endif
89 #include <sys/types.h>
90 #include <sys/stat.h>
92 #if HAVE_READLINE
93 # include <readline/readline.h>
94 # include <readline/history.h>
95 #endif
97 #if HAVE_EDITLINE
98 # include <editline/readline.h>
99 #endif
101 #if HAVE_EDITLINE || HAVE_READLINE
103 # define shell_add_history(X) add_history(X)
104 # define shell_read_history(X) read_history(X)
105 # define shell_write_history(X) write_history(X)
106 # define shell_stifle_history(X) stifle_history(X)
107 # define shell_readline(X) readline(X)
109 #elif HAVE_LINENOISE
111 # include "linenoise.h"
112 # define shell_add_history(X) linenoiseHistoryAdd(X)
113 # define shell_read_history(X) linenoiseHistoryLoad(X)
114 # define shell_write_history(X) linenoiseHistorySave(X)
115 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
116 # define shell_readline(X) linenoise(X)
118 #else
120 # define shell_read_history(X)
121 # define shell_write_history(X)
122 # define shell_stifle_history(X)
124 # define SHELL_USE_LOCAL_GETLINE 1
125 #endif
128 #if defined(_WIN32) || defined(WIN32)
129 # include <io.h>
130 # include <fcntl.h>
131 # define isatty(h) _isatty(h)
132 # ifndef access
133 # define access(f,m) _access((f),(m))
134 # endif
135 # ifndef unlink
136 # define unlink _unlink
137 # endif
138 # undef popen
139 # define popen _popen
140 # undef pclose
141 # define pclose _pclose
142 #else
143 /* Make sure isatty() has a prototype. */
144 extern int isatty(int);
146 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
147 /* popen and pclose are not C89 functions and so are
148 ** sometimes omitted from the <stdio.h> header */
149 extern FILE *popen(const char*,const char*);
150 extern int pclose(FILE*);
151 # else
152 # define SQLITE_OMIT_POPEN 1
153 # endif
154 #endif
156 #if defined(_WIN32_WCE)
157 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
158 * thus we always assume that we have a console. That can be
159 * overridden with the -batch command line option.
161 #define isatty(x) 1
162 #endif
164 /* ctype macros that work with signed characters */
165 #define IsSpace(X) isspace((unsigned char)X)
166 #define IsDigit(X) isdigit((unsigned char)X)
167 #define ToLower(X) (char)tolower((unsigned char)X)
169 #if defined(_WIN32) || defined(WIN32)
170 #include <windows.h>
172 /* string conversion routines only needed on Win32 */
173 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
174 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
175 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
176 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
177 #endif
179 /* On Windows, we normally run with output mode of TEXT so that \n characters
180 ** are automatically translated into \r\n. However, this behavior needs
181 ** to be disabled in some cases (ex: when generating CSV output and when
182 ** rendering quoted strings that contain \n characters). The following
183 ** routines take care of that.
185 #if defined(_WIN32) || defined(WIN32)
186 static void setBinaryMode(FILE *file, int isOutput){
187 if( isOutput ) fflush(file);
188 _setmode(_fileno(file), _O_BINARY);
190 static void setTextMode(FILE *file, int isOutput){
191 if( isOutput ) fflush(file);
192 _setmode(_fileno(file), _O_TEXT);
194 #else
195 # define setBinaryMode(X,Y)
196 # define setTextMode(X,Y)
197 #endif
200 /* True if the timer is enabled */
201 static int enableTimer = 0;
203 /* Return the current wall-clock time */
204 static sqlite3_int64 timeOfDay(void){
205 static sqlite3_vfs *clockVfs = 0;
206 sqlite3_int64 t;
207 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
208 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
209 clockVfs->xCurrentTimeInt64(clockVfs, &t);
210 }else{
211 double r;
212 clockVfs->xCurrentTime(clockVfs, &r);
213 t = (sqlite3_int64)(r*86400000.0);
215 return t;
218 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
219 #include <sys/time.h>
220 #include <sys/resource.h>
222 /* VxWorks does not support getrusage() as far as we can determine */
223 #if defined(_WRS_KERNEL) || defined(__RTP__)
224 struct rusage {
225 struct timeval ru_utime; /* user CPU time used */
226 struct timeval ru_stime; /* system CPU time used */
228 #define getrusage(A,B) memset(B,0,sizeof(*B))
229 #endif
231 /* Saved resource information for the beginning of an operation */
232 static struct rusage sBegin; /* CPU time at start */
233 static sqlite3_int64 iBegin; /* Wall-clock time at start */
236 ** Begin timing an operation
238 static void beginTimer(void){
239 if( enableTimer ){
240 getrusage(RUSAGE_SELF, &sBegin);
241 iBegin = timeOfDay();
245 /* Return the difference of two time_structs in seconds */
246 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
247 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
248 (double)(pEnd->tv_sec - pStart->tv_sec);
252 ** Print the timing results.
254 static void endTimer(void){
255 if( enableTimer ){
256 sqlite3_int64 iEnd = timeOfDay();
257 struct rusage sEnd;
258 getrusage(RUSAGE_SELF, &sEnd);
259 printf("Run Time: real %.3f user %f sys %f\n",
260 (iEnd - iBegin)*0.001,
261 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
262 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
266 #define BEGIN_TIMER beginTimer()
267 #define END_TIMER endTimer()
268 #define HAS_TIMER 1
270 #elif (defined(_WIN32) || defined(WIN32))
272 /* Saved resource information for the beginning of an operation */
273 static HANDLE hProcess;
274 static FILETIME ftKernelBegin;
275 static FILETIME ftUserBegin;
276 static sqlite3_int64 ftWallBegin;
277 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
278 LPFILETIME, LPFILETIME);
279 static GETPROCTIMES getProcessTimesAddr = NULL;
282 ** Check to see if we have timer support. Return 1 if necessary
283 ** support found (or found previously).
285 static int hasTimer(void){
286 if( getProcessTimesAddr ){
287 return 1;
288 } else {
289 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
290 ** versions. See if the version we are running on has it, and if it
291 ** does, save off a pointer to it and the current process handle.
293 hProcess = GetCurrentProcess();
294 if( hProcess ){
295 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
296 if( NULL != hinstLib ){
297 getProcessTimesAddr =
298 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
299 if( NULL != getProcessTimesAddr ){
300 return 1;
302 FreeLibrary(hinstLib);
306 return 0;
310 ** Begin timing an operation
312 static void beginTimer(void){
313 if( enableTimer && getProcessTimesAddr ){
314 FILETIME ftCreation, ftExit;
315 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
316 &ftKernelBegin,&ftUserBegin);
317 ftWallBegin = timeOfDay();
321 /* Return the difference of two FILETIME structs in seconds */
322 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
323 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
324 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
325 return (double) ((i64End - i64Start) / 10000000.0);
329 ** Print the timing results.
331 static void endTimer(void){
332 if( enableTimer && getProcessTimesAddr){
333 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
334 sqlite3_int64 ftWallEnd = timeOfDay();
335 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
336 printf("Run Time: real %.3f user %f sys %f\n",
337 (ftWallEnd - ftWallBegin)*0.001,
338 timeDiff(&ftUserBegin, &ftUserEnd),
339 timeDiff(&ftKernelBegin, &ftKernelEnd));
343 #define BEGIN_TIMER beginTimer()
344 #define END_TIMER endTimer()
345 #define HAS_TIMER hasTimer()
347 #else
348 #define BEGIN_TIMER
349 #define END_TIMER
350 #define HAS_TIMER 0
351 #endif
354 ** Used to prevent warnings about unused parameters
356 #define UNUSED_PARAMETER(x) (void)(x)
359 ** Number of elements in an array
361 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
364 ** If the following flag is set, then command execution stops
365 ** at an error if we are not interactive.
367 static int bail_on_error = 0;
370 ** Threat stdin as an interactive input if the following variable
371 ** is true. Otherwise, assume stdin is connected to a file or pipe.
373 static int stdin_is_interactive = 1;
376 ** On Windows systems we have to know if standard output is a console
377 ** in order to translate UTF-8 into MBCS. The following variable is
378 ** true if translation is required.
380 static int stdout_is_console = 1;
383 ** The following is the open SQLite database. We make a pointer
384 ** to this database a static variable so that it can be accessed
385 ** by the SIGINT handler to interrupt database processing.
387 static sqlite3 *globalDb = 0;
390 ** True if an interrupt (Control-C) has been received.
392 static volatile int seenInterrupt = 0;
395 ** This is the name of our program. It is set in main(), used
396 ** in a number of other places, mostly for error messages.
398 static char *Argv0;
401 ** Prompt strings. Initialized in main. Settable with
402 ** .prompt main continue
404 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
405 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
408 ** Render output like fprintf(). Except, if the output is going to the
409 ** console and if this is running on a Windows machine, translate the
410 ** output from UTF-8 into MBCS.
412 #if defined(_WIN32) || defined(WIN32)
413 void utf8_printf(FILE *out, const char *zFormat, ...){
414 va_list ap;
415 va_start(ap, zFormat);
416 if( stdout_is_console && (out==stdout || out==stderr) ){
417 char *z1 = sqlite3_vmprintf(zFormat, ap);
418 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
419 sqlite3_free(z1);
420 fputs(z2, out);
421 sqlite3_free(z2);
422 }else{
423 vfprintf(out, zFormat, ap);
425 va_end(ap);
427 #elif !defined(utf8_printf)
428 # define utf8_printf fprintf
429 #endif
432 ** Render output like fprintf(). This should not be used on anything that
433 ** includes string formatting (e.g. "%s").
435 #if !defined(raw_printf)
436 # define raw_printf fprintf
437 #endif
439 /* Indicate out-of-memory and exit. */
440 static void shell_out_of_memory(void){
441 raw_printf(stderr,"Error: out of memory\n");
442 exit(1);
446 ** Write I/O traces to the following stream.
448 #ifdef SQLITE_ENABLE_IOTRACE
449 static FILE *iotrace = 0;
450 #endif
453 ** This routine works like printf in that its first argument is a
454 ** format string and subsequent arguments are values to be substituted
455 ** in place of % fields. The result of formatting this string
456 ** is written to iotrace.
458 #ifdef SQLITE_ENABLE_IOTRACE
459 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
460 va_list ap;
461 char *z;
462 if( iotrace==0 ) return;
463 va_start(ap, zFormat);
464 z = sqlite3_vmprintf(zFormat, ap);
465 va_end(ap);
466 utf8_printf(iotrace, "%s", z);
467 sqlite3_free(z);
469 #endif
472 ** Output string zUtf to stream pOut as w characters. If w is negative,
473 ** then right-justify the text. W is the width in UTF-8 characters, not
474 ** in bytes. This is different from the %*.*s specification in printf
475 ** since with %*.*s the width is measured in bytes, not characters.
477 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
478 int i;
479 int n;
480 int aw = w<0 ? -w : w;
481 char zBuf[1000];
482 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
483 for(i=n=0; zUtf[i]; i++){
484 if( (zUtf[i]&0xc0)!=0x80 ){
485 n++;
486 if( n==aw ){
487 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
488 break;
492 if( n>=aw ){
493 utf8_printf(pOut, "%.*s", i, zUtf);
494 }else if( w<0 ){
495 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
496 }else{
497 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
503 ** Determines if a string is a number of not.
505 static int isNumber(const char *z, int *realnum){
506 if( *z=='-' || *z=='+' ) z++;
507 if( !IsDigit(*z) ){
508 return 0;
510 z++;
511 if( realnum ) *realnum = 0;
512 while( IsDigit(*z) ){ z++; }
513 if( *z=='.' ){
514 z++;
515 if( !IsDigit(*z) ) return 0;
516 while( IsDigit(*z) ){ z++; }
517 if( realnum ) *realnum = 1;
519 if( *z=='e' || *z=='E' ){
520 z++;
521 if( *z=='+' || *z=='-' ) z++;
522 if( !IsDigit(*z) ) return 0;
523 while( IsDigit(*z) ){ z++; }
524 if( realnum ) *realnum = 1;
526 return *z==0;
530 ** Compute a string length that is limited to what can be stored in
531 ** lower 30 bits of a 32-bit signed integer.
533 static int strlen30(const char *z){
534 const char *z2 = z;
535 while( *z2 ){ z2++; }
536 return 0x3fffffff & (int)(z2 - z);
540 ** Return the length of a string in characters. Multibyte UTF8 characters
541 ** count as a single character.
543 static int strlenChar(const char *z){
544 int n = 0;
545 while( *z ){
546 if( (0xc0&*(z++))!=0x80 ) n++;
548 return n;
552 ** This routine reads a line of text from FILE in, stores
553 ** the text in memory obtained from malloc() and returns a pointer
554 ** to the text. NULL is returned at end of file, or if malloc()
555 ** fails.
557 ** If zLine is not NULL then it is a malloced buffer returned from
558 ** a previous call to this routine that may be reused.
560 static char *local_getline(char *zLine, FILE *in){
561 int nLine = zLine==0 ? 0 : 100;
562 int n = 0;
564 while( 1 ){
565 if( n+100>nLine ){
566 nLine = nLine*2 + 100;
567 zLine = realloc(zLine, nLine);
568 if( zLine==0 ) return 0;
570 if( fgets(&zLine[n], nLine - n, in)==0 ){
571 if( n==0 ){
572 free(zLine);
573 return 0;
575 zLine[n] = 0;
576 break;
578 while( zLine[n] ) n++;
579 if( n>0 && zLine[n-1]=='\n' ){
580 n--;
581 if( n>0 && zLine[n-1]=='\r' ) n--;
582 zLine[n] = 0;
583 break;
586 #if defined(_WIN32) || defined(WIN32)
587 /* For interactive input on Windows systems, translate the
588 ** multi-byte characterset characters into UTF-8. */
589 if( stdin_is_interactive && in==stdin ){
590 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
591 if( zTrans ){
592 int nTrans = strlen30(zTrans)+1;
593 if( nTrans>nLine ){
594 zLine = realloc(zLine, nTrans);
595 if( zLine==0 ){
596 sqlite3_free(zTrans);
597 return 0;
600 memcpy(zLine, zTrans, nTrans);
601 sqlite3_free(zTrans);
604 #endif /* defined(_WIN32) || defined(WIN32) */
605 return zLine;
609 ** Retrieve a single line of input text.
611 ** If in==0 then read from standard input and prompt before each line.
612 ** If isContinuation is true, then a continuation prompt is appropriate.
613 ** If isContinuation is zero, then the main prompt should be used.
615 ** If zPrior is not NULL then it is a buffer from a prior call to this
616 ** routine that can be reused.
618 ** The result is stored in space obtained from malloc() and must either
619 ** be freed by the caller or else passed back into this routine via the
620 ** zPrior argument for reuse.
622 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
623 char *zPrompt;
624 char *zResult;
625 if( in!=0 ){
626 zResult = local_getline(zPrior, in);
627 }else{
628 zPrompt = isContinuation ? continuePrompt : mainPrompt;
629 #if SHELL_USE_LOCAL_GETLINE
630 printf("%s", zPrompt);
631 fflush(stdout);
632 zResult = local_getline(zPrior, stdin);
633 #else
634 free(zPrior);
635 zResult = shell_readline(zPrompt);
636 if( zResult && *zResult ) shell_add_history(zResult);
637 #endif
639 return zResult;
644 ** Return the value of a hexadecimal digit. Return -1 if the input
645 ** is not a hex digit.
647 static int hexDigitValue(char c){
648 if( c>='0' && c<='9' ) return c - '0';
649 if( c>='a' && c<='f' ) return c - 'a' + 10;
650 if( c>='A' && c<='F' ) return c - 'A' + 10;
651 return -1;
655 ** Interpret zArg as an integer value, possibly with suffixes.
657 static sqlite3_int64 integerValue(const char *zArg){
658 sqlite3_int64 v = 0;
659 static const struct { char *zSuffix; int iMult; } aMult[] = {
660 { "KiB", 1024 },
661 { "MiB", 1024*1024 },
662 { "GiB", 1024*1024*1024 },
663 { "KB", 1000 },
664 { "MB", 1000000 },
665 { "GB", 1000000000 },
666 { "K", 1000 },
667 { "M", 1000000 },
668 { "G", 1000000000 },
670 int i;
671 int isNeg = 0;
672 if( zArg[0]=='-' ){
673 isNeg = 1;
674 zArg++;
675 }else if( zArg[0]=='+' ){
676 zArg++;
678 if( zArg[0]=='0' && zArg[1]=='x' ){
679 int x;
680 zArg += 2;
681 while( (x = hexDigitValue(zArg[0]))>=0 ){
682 v = (v<<4) + x;
683 zArg++;
685 }else{
686 while( IsDigit(zArg[0]) ){
687 v = v*10 + zArg[0] - '0';
688 zArg++;
691 for(i=0; i<ArraySize(aMult); i++){
692 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
693 v *= aMult[i].iMult;
694 break;
697 return isNeg? -v : v;
701 ** A variable length string to which one can append text.
703 typedef struct ShellText ShellText;
704 struct ShellText {
705 char *z;
706 int n;
707 int nAlloc;
711 ** Initialize and destroy a ShellText object
713 static void initText(ShellText *p){
714 memset(p, 0, sizeof(*p));
716 static void freeText(ShellText *p){
717 free(p->z);
718 initText(p);
721 /* zIn is either a pointer to a NULL-terminated string in memory obtained
722 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
723 ** added to zIn, and the result returned in memory obtained from malloc().
724 ** zIn, if it was not NULL, is freed.
726 ** If the third argument, quote, is not '\0', then it is used as a
727 ** quote character for zAppend.
729 static void appendText(ShellText *p, char const *zAppend, char quote){
730 int len;
731 int i;
732 int nAppend = strlen30(zAppend);
734 len = nAppend+p->n+1;
735 if( quote ){
736 len += 2;
737 for(i=0; i<nAppend; i++){
738 if( zAppend[i]==quote ) len++;
742 if( p->n+len>=p->nAlloc ){
743 p->nAlloc = p->nAlloc*2 + len + 20;
744 p->z = realloc(p->z, p->nAlloc);
745 if( p->z==0 ){
746 memset(p, 0, sizeof(*p));
747 return;
751 if( quote ){
752 char *zCsr = p->z+p->n;
753 *zCsr++ = quote;
754 for(i=0; i<nAppend; i++){
755 *zCsr++ = zAppend[i];
756 if( zAppend[i]==quote ) *zCsr++ = quote;
758 *zCsr++ = quote;
759 p->n = (int)(zCsr - p->z);
760 *zCsr = '\0';
761 }else{
762 memcpy(p->z+p->n, zAppend, nAppend);
763 p->n += nAppend;
764 p->z[p->n] = '\0';
769 ** Attempt to determine if identifier zName needs to be quoted, either
770 ** because it contains non-alphanumeric characters, or because it is an
771 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
772 ** that quoting is required.
774 ** Return '"' if quoting is required. Return 0 if no quoting is required.
776 static char quoteChar(const char *zName){
777 int i;
778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
779 for(i=0; zName[i]; i++){
780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
782 return sqlite3_keyword_check(zName, i) ? '"' : 0;
786 ** Construct a fake object name and column list to describe the structure
787 ** of the view, virtual table, or table valued function zSchema.zName.
789 static char *shellFakeSchema(
790 sqlite3 *db, /* The database connection containing the vtab */
791 const char *zSchema, /* Schema of the database holding the vtab */
792 const char *zName /* The name of the virtual table */
794 sqlite3_stmt *pStmt = 0;
795 char *zSql;
796 ShellText s;
797 char cQuote;
798 char *zDiv = "(";
799 int nRow = 0;
801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802 zSchema ? zSchema : "main", zName);
803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
804 sqlite3_free(zSql);
805 initText(&s);
806 if( zSchema ){
807 cQuote = quoteChar(zSchema);
808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
809 appendText(&s, zSchema, cQuote);
810 appendText(&s, ".", 0);
812 cQuote = quoteChar(zName);
813 appendText(&s, zName, cQuote);
814 while( sqlite3_step(pStmt)==SQLITE_ROW ){
815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
816 nRow++;
817 appendText(&s, zDiv, 0);
818 zDiv = ",";
819 cQuote = quoteChar(zCol);
820 appendText(&s, zCol, cQuote);
822 appendText(&s, ")", 0);
823 sqlite3_finalize(pStmt);
824 if( nRow==0 ){
825 freeText(&s);
826 s.z = 0;
828 return s.z;
832 ** SQL function: shell_module_schema(X)
834 ** Return a fake schema for the table-valued function or eponymous virtual
835 ** table X.
837 static void shellModuleSchema(
838 sqlite3_context *pCtx,
839 int nVal,
840 sqlite3_value **apVal
842 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
844 UNUSED_PARAMETER(nVal);
845 if( zFake ){
846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
847 -1, sqlite3_free);
848 free(zFake);
853 ** SQL function: shell_add_schema(S,X)
855 ** Add the schema name X to the CREATE statement in S and return the result.
856 ** Examples:
858 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
860 ** Also works on
862 ** CREATE INDEX
863 ** CREATE UNIQUE INDEX
864 ** CREATE VIEW
865 ** CREATE TRIGGER
866 ** CREATE VIRTUAL TABLE
868 ** This UDF is used by the .schema command to insert the schema name of
869 ** attached databases into the middle of the sqlite_master.sql field.
871 static void shellAddSchemaName(
872 sqlite3_context *pCtx,
873 int nVal,
874 sqlite3_value **apVal
876 static const char *aPrefix[] = {
877 "TABLE",
878 "INDEX",
879 "UNIQUE INDEX",
880 "VIEW",
881 "TRIGGER",
882 "VIRTUAL TABLE"
884 int i = 0;
885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
887 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
888 sqlite3 *db = sqlite3_context_db_handle(pCtx);
889 UNUSED_PARAMETER(nVal);
890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
892 int n = strlen30(aPrefix[i]);
893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
894 char *z = 0;
895 char *zFake = 0;
896 if( zSchema ){
897 char cQuote = quoteChar(zSchema);
898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
900 }else{
901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
904 if( zName
905 && aPrefix[i][0]=='V'
906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
908 if( z==0 ){
909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
910 }else{
911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
913 free(zFake);
915 if( z ){
916 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
917 return;
922 sqlite3_result_value(pCtx, apVal[0]);
926 ** The source code for several run-time loadable extensions is inserted
927 ** below by the ../tool/mkshellc.tcl script. Before processing that included
928 ** code, we need to override some macros to make the included program code
929 ** work here in the middle of this regular program.
931 #define SQLITE_EXTENSION_INIT1
932 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
934 #if defined(_WIN32) && defined(_MSC_VER)
935 INCLUDE test_windirent.h
936 INCLUDE test_windirent.c
937 #define dirent DIRENT
938 #endif
939 INCLUDE ../ext/misc/shathree.c
940 INCLUDE ../ext/misc/fileio.c
941 INCLUDE ../ext/misc/completion.c
942 INCLUDE ../ext/misc/appendvfs.c
943 #ifdef SQLITE_HAVE_ZLIB
944 INCLUDE ../ext/misc/zipfile.c
945 INCLUDE ../ext/misc/sqlar.c
946 #endif
947 INCLUDE ../ext/expert/sqlite3expert.h
948 INCLUDE ../ext/expert/sqlite3expert.c
950 #if defined(SQLITE_ENABLE_SESSION)
952 ** State information for a single open session
954 typedef struct OpenSession OpenSession;
955 struct OpenSession {
956 char *zName; /* Symbolic name for this session */
957 int nFilter; /* Number of xFilter rejection GLOB patterns */
958 char **azFilter; /* Array of xFilter rejection GLOB patterns */
959 sqlite3_session *p; /* The open session */
961 #endif
964 ** Shell output mode information from before ".explain on",
965 ** saved so that it can be restored by ".explain off"
967 typedef struct SavedModeInfo SavedModeInfo;
968 struct SavedModeInfo {
969 int valid; /* Is there legit data in here? */
970 int mode; /* Mode prior to ".explain on" */
971 int showHeader; /* The ".header" setting prior to ".explain on" */
972 int colWidth[100]; /* Column widths prior to ".explain on" */
975 typedef struct ExpertInfo ExpertInfo;
976 struct ExpertInfo {
977 sqlite3expert *pExpert;
978 int bVerbose;
981 /* A single line in the EQP output */
982 typedef struct EQPGraphRow EQPGraphRow;
983 struct EQPGraphRow {
984 int iEqpId; /* ID for this row */
985 int iParentId; /* ID of the parent row */
986 EQPGraphRow *pNext; /* Next row in sequence */
987 char zText[1]; /* Text to display for this row */
990 /* All EQP output is collected into an instance of the following */
991 typedef struct EQPGraph EQPGraph;
992 struct EQPGraph {
993 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
994 EQPGraphRow *pLast; /* Last element of the pRow list */
995 char zPrefix[100]; /* Graph prefix */
999 ** State information about the database connection is contained in an
1000 ** instance of the following structure.
1002 typedef struct ShellState ShellState;
1003 struct ShellState {
1004 sqlite3 *db; /* The database */
1005 u8 autoExplain; /* Automatically turn on .explain mode */
1006 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1007 u8 autoEQPtest; /* autoEQP is in test mode */
1008 u8 statsOn; /* True to display memory stats before each finalize */
1009 u8 scanstatsOn; /* True to display scan stats before each finalize */
1010 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1011 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1012 u8 nEqpLevel; /* Depth of the EQP output graph */
1013 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
1014 int outCount; /* Revert to stdout when reaching zero */
1015 int cnt; /* Number of records displayed so far */
1016 FILE *out; /* Write results here */
1017 FILE *traceOut; /* Output for sqlite3_trace() */
1018 int nErr; /* Number of errors seen */
1019 int mode; /* An output mode setting */
1020 int modePrior; /* Saved mode */
1021 int cMode; /* temporary output mode for the current query */
1022 int normalMode; /* Output mode before ".explain on" */
1023 int writableSchema; /* True if PRAGMA writable_schema=ON */
1024 int showHeader; /* True to show column names in List or Column mode */
1025 int nCheck; /* Number of ".check" commands run */
1026 unsigned shellFlgs; /* Various flags */
1027 char *zDestTable; /* Name of destination table when MODE_Insert */
1028 char *zTempFile; /* Temporary file that might need deleting */
1029 char zTestcase[30]; /* Name of current test case */
1030 char colSeparator[20]; /* Column separator character for several modes */
1031 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1032 char colSepPrior[20]; /* Saved column separator */
1033 char rowSepPrior[20]; /* Saved row separator */
1034 int colWidth[100]; /* Requested width of each column when in column mode*/
1035 int actualWidth[100]; /* Actual width of each column */
1036 char nullValue[20]; /* The text to print when a NULL comes back from
1037 ** the database */
1038 char outfile[FILENAME_MAX]; /* Filename for *out */
1039 const char *zDbFilename; /* name of the database file */
1040 char *zFreeOnClose; /* Filename to free when closing */
1041 const char *zVfs; /* Name of VFS to use */
1042 sqlite3_stmt *pStmt; /* Current statement if any. */
1043 FILE *pLog; /* Write log output here */
1044 int *aiIndent; /* Array of indents used in MODE_Explain */
1045 int nIndent; /* Size of array aiIndent[] */
1046 int iIndent; /* Index of current op in aiIndent[] */
1047 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1048 #if defined(SQLITE_ENABLE_SESSION)
1049 int nSession; /* Number of active sessions */
1050 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1051 #endif
1052 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1056 /* Allowed values for ShellState.autoEQP
1058 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1059 #define AUTOEQP_on 1 /* Automatic EQP is on */
1060 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1061 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1063 /* Allowed values for ShellState.openMode
1065 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1066 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1067 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1068 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1069 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1072 ** These are the allowed shellFlgs values
1074 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1075 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1076 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1077 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1078 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1079 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1080 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1083 ** Macros for testing and setting shellFlgs
1085 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1086 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1087 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1090 ** These are the allowed modes.
1092 #define MODE_Line 0 /* One column per line. Blank line between records */
1093 #define MODE_Column 1 /* One record per line in neat columns */
1094 #define MODE_List 2 /* One record per line with a separator */
1095 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1096 #define MODE_Html 4 /* Generate an XHTML table */
1097 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1098 #define MODE_Quote 6 /* Quote values as for SQL */
1099 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1100 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1101 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1102 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1103 #define MODE_Pretty 11 /* Pretty-print schemas */
1104 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1106 static const char *modeDescr[] = {
1107 "line",
1108 "column",
1109 "list",
1110 "semi",
1111 "html",
1112 "insert",
1113 "quote",
1114 "tcl",
1115 "csv",
1116 "explain",
1117 "ascii",
1118 "prettyprint",
1119 "eqp"
1123 ** These are the column/row/line separators used by the various
1124 ** import/export modes.
1126 #define SEP_Column "|"
1127 #define SEP_Row "\n"
1128 #define SEP_Tab "\t"
1129 #define SEP_Space " "
1130 #define SEP_Comma ","
1131 #define SEP_CrLf "\r\n"
1132 #define SEP_Unit "\x1F"
1133 #define SEP_Record "\x1E"
1136 ** A callback for the sqlite3_log() interface.
1138 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1139 ShellState *p = (ShellState*)pArg;
1140 if( p->pLog==0 ) return;
1141 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1142 fflush(p->pLog);
1146 ** SQL function: shell_putsnl(X)
1148 ** Write the text X to the screen (or whatever output is being directed)
1149 ** adding a newline at the end, and then return X.
1151 static void shellPutsFunc(
1152 sqlite3_context *pCtx,
1153 int nVal,
1154 sqlite3_value **apVal
1156 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1157 (void)nVal;
1158 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1159 sqlite3_result_value(pCtx, apVal[0]);
1163 ** SQL function: edit(VALUE)
1164 ** edit(VALUE,EDITOR)
1166 ** These steps:
1168 ** (1) Write VALUE into a temporary file.
1169 ** (2) Run program EDITOR on that temporary file.
1170 ** (3) Read the temporary file back and return its content as the result.
1171 ** (4) Delete the temporary file
1173 ** If the EDITOR argument is omitted, use the value in the VISUAL
1174 ** environment variable. If still there is no EDITOR, through an error.
1176 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1178 #ifndef SQLITE_NOHAVE_SYSTEM
1179 static void editFunc(
1180 sqlite3_context *context,
1181 int argc,
1182 sqlite3_value **argv
1184 const char *zEditor;
1185 char *zTempFile = 0;
1186 sqlite3 *db;
1187 char *zCmd = 0;
1188 int bBin;
1189 int rc;
1190 FILE *f = 0;
1191 sqlite3_int64 sz;
1192 sqlite3_int64 x;
1193 unsigned char *p = 0;
1195 if( argc==2 ){
1196 zEditor = (const char*)sqlite3_value_text(argv[1]);
1197 }else{
1198 zEditor = getenv("VISUAL");
1200 if( zEditor==0 ){
1201 sqlite3_result_error(context, "no editor for edit()", -1);
1202 return;
1204 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1205 sqlite3_result_error(context, "NULL input to edit()", -1);
1206 return;
1208 db = sqlite3_context_db_handle(context);
1209 zTempFile = 0;
1210 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1211 if( zTempFile==0 ){
1212 sqlite3_uint64 r = 0;
1213 sqlite3_randomness(sizeof(r), &r);
1214 zTempFile = sqlite3_mprintf("temp%llx", r);
1215 if( zTempFile==0 ){
1216 sqlite3_result_error_nomem(context);
1217 return;
1220 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1221 f = fopen(zTempFile, bBin ? "wb" : "w");
1222 if( f==0 ){
1223 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1224 goto edit_func_end;
1226 sz = sqlite3_value_bytes(argv[0]);
1227 if( bBin ){
1228 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1229 }else{
1230 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1232 fclose(f);
1233 f = 0;
1234 if( x!=sz ){
1235 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1236 goto edit_func_end;
1238 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1239 if( zCmd==0 ){
1240 sqlite3_result_error_nomem(context);
1241 goto edit_func_end;
1243 rc = system(zCmd);
1244 sqlite3_free(zCmd);
1245 if( rc ){
1246 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1247 goto edit_func_end;
1249 f = fopen(zTempFile, bBin ? "rb" : "r");
1250 if( f==0 ){
1251 sqlite3_result_error(context,
1252 "edit() cannot reopen temp file after edit", -1);
1253 goto edit_func_end;
1255 fseek(f, 0, SEEK_END);
1256 sz = ftell(f);
1257 rewind(f);
1258 p = sqlite3_malloc64( sz+(bBin==0) );
1259 if( p==0 ){
1260 sqlite3_result_error_nomem(context);
1261 goto edit_func_end;
1263 if( bBin ){
1264 x = fread(p, 1, sz, f);
1265 }else{
1266 x = fread(p, 1, sz, f);
1267 p[sz] = 0;
1269 fclose(f);
1270 f = 0;
1271 if( x!=sz ){
1272 sqlite3_result_error(context, "could not read back the whole file", -1);
1273 goto edit_func_end;
1275 if( bBin ){
1276 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1277 }else{
1278 sqlite3_result_text64(context, (const char*)p, sz,
1279 sqlite3_free, SQLITE_UTF8);
1281 p = 0;
1283 edit_func_end:
1284 if( f ) fclose(f);
1285 unlink(zTempFile);
1286 sqlite3_free(zTempFile);
1287 sqlite3_free(p);
1289 #endif /* SQLITE_NOHAVE_SYSTEM */
1292 ** Save or restore the current output mode
1294 static void outputModePush(ShellState *p){
1295 p->modePrior = p->mode;
1296 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1297 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1299 static void outputModePop(ShellState *p){
1300 p->mode = p->modePrior;
1301 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1302 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1306 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1308 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1309 int i;
1310 char *zBlob = (char *)pBlob;
1311 raw_printf(out,"X'");
1312 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1313 raw_printf(out,"'");
1317 ** Find a string that is not found anywhere in z[]. Return a pointer
1318 ** to that string.
1320 ** Try to use zA and zB first. If both of those are already found in z[]
1321 ** then make up some string and store it in the buffer zBuf.
1323 static const char *unused_string(
1324 const char *z, /* Result must not appear anywhere in z */
1325 const char *zA, const char *zB, /* Try these first */
1326 char *zBuf /* Space to store a generated string */
1328 unsigned i = 0;
1329 if( strstr(z, zA)==0 ) return zA;
1330 if( strstr(z, zB)==0 ) return zB;
1332 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1333 }while( strstr(z,zBuf)!=0 );
1334 return zBuf;
1338 ** Output the given string as a quoted string using SQL quoting conventions.
1340 ** See also: output_quoted_escaped_string()
1342 static void output_quoted_string(FILE *out, const char *z){
1343 int i;
1344 char c;
1345 setBinaryMode(out, 1);
1346 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1347 if( c==0 ){
1348 utf8_printf(out,"'%s'",z);
1349 }else{
1350 raw_printf(out, "'");
1351 while( *z ){
1352 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1353 if( c=='\'' ) i++;
1354 if( i ){
1355 utf8_printf(out, "%.*s", i, z);
1356 z += i;
1358 if( c=='\'' ){
1359 raw_printf(out, "'");
1360 continue;
1362 if( c==0 ){
1363 break;
1365 z++;
1367 raw_printf(out, "'");
1369 setTextMode(out, 1);
1373 ** Output the given string as a quoted string using SQL quoting conventions.
1374 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1375 ** get corrupted by end-of-line translation facilities in some operating
1376 ** systems.
1378 ** This is like output_quoted_string() but with the addition of the \r\n
1379 ** escape mechanism.
1381 static void output_quoted_escaped_string(FILE *out, const char *z){
1382 int i;
1383 char c;
1384 setBinaryMode(out, 1);
1385 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1386 if( c==0 ){
1387 utf8_printf(out,"'%s'",z);
1388 }else{
1389 const char *zNL = 0;
1390 const char *zCR = 0;
1391 int nNL = 0;
1392 int nCR = 0;
1393 char zBuf1[20], zBuf2[20];
1394 for(i=0; z[i]; i++){
1395 if( z[i]=='\n' ) nNL++;
1396 if( z[i]=='\r' ) nCR++;
1398 if( nNL ){
1399 raw_printf(out, "replace(");
1400 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1402 if( nCR ){
1403 raw_printf(out, "replace(");
1404 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1406 raw_printf(out, "'");
1407 while( *z ){
1408 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1409 if( c=='\'' ) i++;
1410 if( i ){
1411 utf8_printf(out, "%.*s", i, z);
1412 z += i;
1414 if( c=='\'' ){
1415 raw_printf(out, "'");
1416 continue;
1418 if( c==0 ){
1419 break;
1421 z++;
1422 if( c=='\n' ){
1423 raw_printf(out, "%s", zNL);
1424 continue;
1426 raw_printf(out, "%s", zCR);
1428 raw_printf(out, "'");
1429 if( nCR ){
1430 raw_printf(out, ",'%s',char(13))", zCR);
1432 if( nNL ){
1433 raw_printf(out, ",'%s',char(10))", zNL);
1436 setTextMode(out, 1);
1440 ** Output the given string as a quoted according to C or TCL quoting rules.
1442 static void output_c_string(FILE *out, const char *z){
1443 unsigned int c;
1444 fputc('"', out);
1445 while( (c = *(z++))!=0 ){
1446 if( c=='\\' ){
1447 fputc(c, out);
1448 fputc(c, out);
1449 }else if( c=='"' ){
1450 fputc('\\', out);
1451 fputc('"', out);
1452 }else if( c=='\t' ){
1453 fputc('\\', out);
1454 fputc('t', out);
1455 }else if( c=='\n' ){
1456 fputc('\\', out);
1457 fputc('n', out);
1458 }else if( c=='\r' ){
1459 fputc('\\', out);
1460 fputc('r', out);
1461 }else if( !isprint(c&0xff) ){
1462 raw_printf(out, "\\%03o", c&0xff);
1463 }else{
1464 fputc(c, out);
1467 fputc('"', out);
1471 ** Output the given string with characters that are special to
1472 ** HTML escaped.
1474 static void output_html_string(FILE *out, const char *z){
1475 int i;
1476 if( z==0 ) z = "";
1477 while( *z ){
1478 for(i=0; z[i]
1479 && z[i]!='<'
1480 && z[i]!='&'
1481 && z[i]!='>'
1482 && z[i]!='\"'
1483 && z[i]!='\'';
1484 i++){}
1485 if( i>0 ){
1486 utf8_printf(out,"%.*s",i,z);
1488 if( z[i]=='<' ){
1489 raw_printf(out,"&lt;");
1490 }else if( z[i]=='&' ){
1491 raw_printf(out,"&amp;");
1492 }else if( z[i]=='>' ){
1493 raw_printf(out,"&gt;");
1494 }else if( z[i]=='\"' ){
1495 raw_printf(out,"&quot;");
1496 }else if( z[i]=='\'' ){
1497 raw_printf(out,"&#39;");
1498 }else{
1499 break;
1501 z += i + 1;
1506 ** If a field contains any character identified by a 1 in the following
1507 ** array, then the string must be quoted for CSV.
1509 static const char needCsvQuote[] = {
1510 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1511 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1512 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1513 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1514 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1515 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1516 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1518 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1519 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1520 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1529 ** Output a single term of CSV. Actually, p->colSeparator is used for
1530 ** the separator, which may or may not be a comma. p->nullValue is
1531 ** the null value. Strings are quoted if necessary. The separator
1532 ** is only issued if bSep is true.
1534 static void output_csv(ShellState *p, const char *z, int bSep){
1535 FILE *out = p->out;
1536 if( z==0 ){
1537 utf8_printf(out,"%s",p->nullValue);
1538 }else{
1539 int i;
1540 int nSep = strlen30(p->colSeparator);
1541 for(i=0; z[i]; i++){
1542 if( needCsvQuote[((unsigned char*)z)[i]]
1543 || (z[i]==p->colSeparator[0] &&
1544 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1545 i = 0;
1546 break;
1549 if( i==0 ){
1550 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1551 utf8_printf(out, "%s", zQuoted);
1552 sqlite3_free(zQuoted);
1553 }else{
1554 utf8_printf(out, "%s", z);
1557 if( bSep ){
1558 utf8_printf(p->out, "%s", p->colSeparator);
1563 ** This routine runs when the user presses Ctrl-C
1565 static void interrupt_handler(int NotUsed){
1566 UNUSED_PARAMETER(NotUsed);
1567 seenInterrupt++;
1568 if( seenInterrupt>2 ) exit(1);
1569 if( globalDb ) sqlite3_interrupt(globalDb);
1572 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1574 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1576 static BOOL WINAPI ConsoleCtrlHandler(
1577 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1579 if( dwCtrlType==CTRL_C_EVENT ){
1580 interrupt_handler(0);
1581 return TRUE;
1583 return FALSE;
1585 #endif
1587 #ifndef SQLITE_OMIT_AUTHORIZATION
1589 ** When the ".auth ON" is set, the following authorizer callback is
1590 ** invoked. It always returns SQLITE_OK.
1592 static int shellAuth(
1593 void *pClientData,
1594 int op,
1595 const char *zA1,
1596 const char *zA2,
1597 const char *zA3,
1598 const char *zA4
1600 ShellState *p = (ShellState*)pClientData;
1601 static const char *azAction[] = { 0,
1602 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1603 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1604 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1605 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1606 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1607 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1608 "PRAGMA", "READ", "SELECT",
1609 "TRANSACTION", "UPDATE", "ATTACH",
1610 "DETACH", "ALTER_TABLE", "REINDEX",
1611 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1612 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1614 int i;
1615 const char *az[4];
1616 az[0] = zA1;
1617 az[1] = zA2;
1618 az[2] = zA3;
1619 az[3] = zA4;
1620 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1621 for(i=0; i<4; i++){
1622 raw_printf(p->out, " ");
1623 if( az[i] ){
1624 output_c_string(p->out, az[i]);
1625 }else{
1626 raw_printf(p->out, "NULL");
1629 raw_printf(p->out, "\n");
1630 return SQLITE_OK;
1632 #endif
1635 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1637 ** This routine converts some CREATE TABLE statements for shadow tables
1638 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1640 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1641 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1642 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1643 }else{
1644 utf8_printf(out, "%s%s", z, zTail);
1647 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1648 char c = z[n];
1649 z[n] = 0;
1650 printSchemaLine(out, z, zTail);
1651 z[n] = c;
1655 ** Return true if string z[] has nothing but whitespace and comments to the
1656 ** end of the first line.
1658 static int wsToEol(const char *z){
1659 int i;
1660 for(i=0; z[i]; i++){
1661 if( z[i]=='\n' ) return 1;
1662 if( IsSpace(z[i]) ) continue;
1663 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1664 return 0;
1666 return 1;
1670 ** Add a new entry to the EXPLAIN QUERY PLAN data
1672 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1673 EQPGraphRow *pNew;
1674 int nText = strlen30(zText);
1675 if( p->autoEQPtest ){
1676 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1678 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1679 if( pNew==0 ) shell_out_of_memory();
1680 pNew->iEqpId = iEqpId;
1681 pNew->iParentId = p2;
1682 memcpy(pNew->zText, zText, nText+1);
1683 pNew->pNext = 0;
1684 if( p->sGraph.pLast ){
1685 p->sGraph.pLast->pNext = pNew;
1686 }else{
1687 p->sGraph.pRow = pNew;
1689 p->sGraph.pLast = pNew;
1693 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1694 ** in p->sGraph.
1696 static void eqp_reset(ShellState *p){
1697 EQPGraphRow *pRow, *pNext;
1698 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1699 pNext = pRow->pNext;
1700 sqlite3_free(pRow);
1702 memset(&p->sGraph, 0, sizeof(p->sGraph));
1705 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1706 ** pOld, or return the first such line if pOld is NULL
1708 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1709 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1710 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1711 return pRow;
1714 /* Render a single level of the graph that has iEqpId as its parent. Called
1715 ** recursively to render sublevels.
1717 static void eqp_render_level(ShellState *p, int iEqpId){
1718 EQPGraphRow *pRow, *pNext;
1719 int n = strlen30(p->sGraph.zPrefix);
1720 char *z;
1721 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1722 pNext = eqp_next_row(p, iEqpId, pRow);
1723 z = pRow->zText;
1724 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
1725 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1726 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
1727 eqp_render_level(p, pRow->iEqpId);
1728 p->sGraph.zPrefix[n] = 0;
1734 ** Display and reset the EXPLAIN QUERY PLAN data
1736 static void eqp_render(ShellState *p){
1737 EQPGraphRow *pRow = p->sGraph.pRow;
1738 if( pRow ){
1739 if( pRow->zText[0]=='-' ){
1740 if( pRow->pNext==0 ){
1741 eqp_reset(p);
1742 return;
1744 utf8_printf(p->out, "%s\n", pRow->zText+3);
1745 p->sGraph.pRow = pRow->pNext;
1746 sqlite3_free(pRow);
1747 }else{
1748 utf8_printf(p->out, "QUERY PLAN\n");
1750 p->sGraph.zPrefix[0] = 0;
1751 eqp_render_level(p, 0);
1752 eqp_reset(p);
1757 ** This is the callback routine that the shell
1758 ** invokes for each row of a query result.
1760 static int shell_callback(
1761 void *pArg,
1762 int nArg, /* Number of result columns */
1763 char **azArg, /* Text of each result column */
1764 char **azCol, /* Column names */
1765 int *aiType /* Column types */
1767 int i;
1768 ShellState *p = (ShellState*)pArg;
1770 if( azArg==0 ) return 0;
1771 switch( p->cMode ){
1772 case MODE_Line: {
1773 int w = 5;
1774 if( azArg==0 ) break;
1775 for(i=0; i<nArg; i++){
1776 int len = strlen30(azCol[i] ? azCol[i] : "");
1777 if( len>w ) w = len;
1779 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1780 for(i=0; i<nArg; i++){
1781 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1782 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1784 break;
1786 case MODE_Explain:
1787 case MODE_Column: {
1788 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1789 const int *colWidth;
1790 int showHdr;
1791 char *rowSep;
1792 if( p->cMode==MODE_Column ){
1793 colWidth = p->colWidth;
1794 showHdr = p->showHeader;
1795 rowSep = p->rowSeparator;
1796 }else{
1797 colWidth = aExplainWidths;
1798 showHdr = 1;
1799 rowSep = SEP_Row;
1801 if( p->cnt++==0 ){
1802 for(i=0; i<nArg; i++){
1803 int w, n;
1804 if( i<ArraySize(p->colWidth) ){
1805 w = colWidth[i];
1806 }else{
1807 w = 0;
1809 if( w==0 ){
1810 w = strlenChar(azCol[i] ? azCol[i] : "");
1811 if( w<10 ) w = 10;
1812 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1813 if( w<n ) w = n;
1815 if( i<ArraySize(p->actualWidth) ){
1816 p->actualWidth[i] = w;
1818 if( showHdr ){
1819 utf8_width_print(p->out, w, azCol[i]);
1820 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1823 if( showHdr ){
1824 for(i=0; i<nArg; i++){
1825 int w;
1826 if( i<ArraySize(p->actualWidth) ){
1827 w = p->actualWidth[i];
1828 if( w<0 ) w = -w;
1829 }else{
1830 w = 10;
1832 utf8_printf(p->out,"%-*.*s%s",w,w,
1833 "----------------------------------------------------------"
1834 "----------------------------------------------------------",
1835 i==nArg-1 ? rowSep : " ");
1839 if( azArg==0 ) break;
1840 for(i=0; i<nArg; i++){
1841 int w;
1842 if( i<ArraySize(p->actualWidth) ){
1843 w = p->actualWidth[i];
1844 }else{
1845 w = 10;
1847 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1848 w = strlenChar(azArg[i]);
1850 if( i==1 && p->aiIndent && p->pStmt ){
1851 if( p->iIndent<p->nIndent ){
1852 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1854 p->iIndent++;
1856 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1857 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1859 break;
1861 case MODE_Semi: { /* .schema and .fullschema output */
1862 printSchemaLine(p->out, azArg[0], ";\n");
1863 break;
1865 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1866 char *z;
1867 int j;
1868 int nParen = 0;
1869 char cEnd = 0;
1870 char c;
1871 int nLine = 0;
1872 assert( nArg==1 );
1873 if( azArg[0]==0 ) break;
1874 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1875 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1877 utf8_printf(p->out, "%s;\n", azArg[0]);
1878 break;
1880 z = sqlite3_mprintf("%s", azArg[0]);
1881 j = 0;
1882 for(i=0; IsSpace(z[i]); i++){}
1883 for(; (c = z[i])!=0; i++){
1884 if( IsSpace(c) ){
1885 if( z[j-1]=='\r' ) z[j-1] = '\n';
1886 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1887 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1888 j--;
1890 z[j++] = c;
1892 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1893 z[j] = 0;
1894 if( strlen30(z)>=79 ){
1895 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
1896 if( c==cEnd ){
1897 cEnd = 0;
1898 }else if( c=='"' || c=='\'' || c=='`' ){
1899 cEnd = c;
1900 }else if( c=='[' ){
1901 cEnd = ']';
1902 }else if( c=='-' && z[i+1]=='-' ){
1903 cEnd = '\n';
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;
1913 z[j++] = c;
1914 if( nParen==1 && cEnd==0
1915 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1917 if( c=='\n' ) j--;
1918 printSchemaLineN(p->out, z, j, "\n ");
1919 j = 0;
1920 nLine++;
1921 while( IsSpace(z[i+1]) ){ i++; }
1924 z[j] = 0;
1926 printSchemaLine(p->out, z, ";\n");
1927 sqlite3_free(z);
1928 break;
1930 case MODE_List: {
1931 if( p->cnt++==0 && p->showHeader ){
1932 for(i=0; i<nArg; i++){
1933 utf8_printf(p->out,"%s%s",azCol[i],
1934 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1937 if( azArg==0 ) break;
1938 for(i=0; i<nArg; i++){
1939 char *z = azArg[i];
1940 if( z==0 ) z = p->nullValue;
1941 utf8_printf(p->out, "%s", z);
1942 if( i<nArg-1 ){
1943 utf8_printf(p->out, "%s", p->colSeparator);
1944 }else{
1945 utf8_printf(p->out, "%s", p->rowSeparator);
1948 break;
1950 case MODE_Html: {
1951 if( p->cnt++==0 && p->showHeader ){
1952 raw_printf(p->out,"<TR>");
1953 for(i=0; i<nArg; i++){
1954 raw_printf(p->out,"<TH>");
1955 output_html_string(p->out, azCol[i]);
1956 raw_printf(p->out,"</TH>\n");
1958 raw_printf(p->out,"</TR>\n");
1960 if( azArg==0 ) break;
1961 raw_printf(p->out,"<TR>");
1962 for(i=0; i<nArg; i++){
1963 raw_printf(p->out,"<TD>");
1964 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1965 raw_printf(p->out,"</TD>\n");
1967 raw_printf(p->out,"</TR>\n");
1968 break;
1970 case MODE_Tcl: {
1971 if( p->cnt++==0 && p->showHeader ){
1972 for(i=0; i<nArg; i++){
1973 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1974 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1976 utf8_printf(p->out, "%s", p->rowSeparator);
1978 if( azArg==0 ) break;
1979 for(i=0; i<nArg; i++){
1980 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1981 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1983 utf8_printf(p->out, "%s", p->rowSeparator);
1984 break;
1986 case MODE_Csv: {
1987 setBinaryMode(p->out, 1);
1988 if( p->cnt++==0 && p->showHeader ){
1989 for(i=0; i<nArg; i++){
1990 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1992 utf8_printf(p->out, "%s", p->rowSeparator);
1994 if( nArg>0 ){
1995 for(i=0; i<nArg; i++){
1996 output_csv(p, azArg[i], i<nArg-1);
1998 utf8_printf(p->out, "%s", p->rowSeparator);
2000 setTextMode(p->out, 1);
2001 break;
2003 case MODE_Insert: {
2004 if( azArg==0 ) break;
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 if( i>0 ) raw_printf(p->out, ",");
2010 if( quoteChar(azCol[i]) ){
2011 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2012 utf8_printf(p->out, "%s", z);
2013 sqlite3_free(z);
2014 }else{
2015 raw_printf(p->out, "%s", azCol[i]);
2018 raw_printf(p->out,")");
2020 p->cnt++;
2021 for(i=0; i<nArg; i++){
2022 raw_printf(p->out, i>0 ? "," : " VALUES(");
2023 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2024 utf8_printf(p->out,"NULL");
2025 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2026 if( ShellHasFlag(p, SHFLG_Newlines) ){
2027 output_quoted_string(p->out, azArg[i]);
2028 }else{
2029 output_quoted_escaped_string(p->out, azArg[i]);
2031 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2032 utf8_printf(p->out,"%s", azArg[i]);
2033 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2034 char z[50];
2035 double r = sqlite3_column_double(p->pStmt, i);
2036 sqlite3_snprintf(50,z,"%!.20g", r);
2037 raw_printf(p->out, "%s", z);
2038 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2039 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2040 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2041 output_hex_blob(p->out, pBlob, nBlob);
2042 }else if( isNumber(azArg[i], 0) ){
2043 utf8_printf(p->out,"%s", azArg[i]);
2044 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2045 output_quoted_string(p->out, azArg[i]);
2046 }else{
2047 output_quoted_escaped_string(p->out, azArg[i]);
2050 raw_printf(p->out,");\n");
2051 break;
2053 case MODE_Quote: {
2054 if( azArg==0 ) break;
2055 if( p->cnt==0 && p->showHeader ){
2056 for(i=0; i<nArg; i++){
2057 if( i>0 ) raw_printf(p->out, ",");
2058 output_quoted_string(p->out, azCol[i]);
2060 raw_printf(p->out,"\n");
2062 p->cnt++;
2063 for(i=0; i<nArg; i++){
2064 if( i>0 ) raw_printf(p->out, ",");
2065 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2066 utf8_printf(p->out,"NULL");
2067 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2068 output_quoted_string(p->out, azArg[i]);
2069 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2070 utf8_printf(p->out,"%s", azArg[i]);
2071 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2072 char z[50];
2073 double r = sqlite3_column_double(p->pStmt, i);
2074 sqlite3_snprintf(50,z,"%!.20g", r);
2075 raw_printf(p->out, "%s", z);
2076 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2077 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2078 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2079 output_hex_blob(p->out, pBlob, nBlob);
2080 }else if( isNumber(azArg[i], 0) ){
2081 utf8_printf(p->out,"%s", azArg[i]);
2082 }else{
2083 output_quoted_string(p->out, azArg[i]);
2086 raw_printf(p->out,"\n");
2087 break;
2089 case MODE_Ascii: {
2090 if( p->cnt++==0 && p->showHeader ){
2091 for(i=0; i<nArg; i++){
2092 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2093 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2095 utf8_printf(p->out, "%s", p->rowSeparator);
2097 if( azArg==0 ) break;
2098 for(i=0; i<nArg; i++){
2099 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2100 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2102 utf8_printf(p->out, "%s", p->rowSeparator);
2103 break;
2105 case MODE_EQP: {
2106 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2107 break;
2110 return 0;
2114 ** This is the callback routine that the SQLite library
2115 ** invokes for each row of a query result.
2117 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2118 /* since we don't have type info, call the shell_callback with a NULL value */
2119 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2123 ** This is the callback routine from sqlite3_exec() that appends all
2124 ** output onto the end of a ShellText object.
2126 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2127 ShellText *p = (ShellText*)pArg;
2128 int i;
2129 UNUSED_PARAMETER(az);
2130 if( azArg==0 ) return 0;
2131 if( p->n ) appendText(p, "|", 0);
2132 for(i=0; i<nArg; i++){
2133 if( i ) appendText(p, ",", 0);
2134 if( azArg[i] ) appendText(p, azArg[i], 0);
2136 return 0;
2140 ** Generate an appropriate SELFTEST table in the main database.
2142 static void createSelftestTable(ShellState *p){
2143 char *zErrMsg = 0;
2144 sqlite3_exec(p->db,
2145 "SAVEPOINT selftest_init;\n"
2146 "CREATE TABLE IF NOT EXISTS selftest(\n"
2147 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2148 " op TEXT,\n" /* Operator: memo run */
2149 " cmd TEXT,\n" /* Command text */
2150 " ans TEXT\n" /* Desired answer */
2151 ");"
2152 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2153 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2154 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2155 " 'memo','Tests generated by --init');\n"
2156 "INSERT INTO [_shell$self]\n"
2157 " SELECT 'run',\n"
2158 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2159 "FROM sqlite_master ORDER BY 2'',224))',\n"
2160 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2161 "FROM sqlite_master ORDER BY 2',224));\n"
2162 "INSERT INTO [_shell$self]\n"
2163 " SELECT 'run',"
2164 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2165 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2166 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2167 " FROM (\n"
2168 " SELECT name FROM sqlite_master\n"
2169 " WHERE type='table'\n"
2170 " AND name<>'selftest'\n"
2171 " AND coalesce(rootpage,0)>0\n"
2172 " )\n"
2173 " ORDER BY name;\n"
2174 "INSERT INTO [_shell$self]\n"
2175 " VALUES('run','PRAGMA integrity_check','ok');\n"
2176 "INSERT INTO selftest(tno,op,cmd,ans)"
2177 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2178 "DROP TABLE [_shell$self];"
2179 ,0,0,&zErrMsg);
2180 if( zErrMsg ){
2181 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2182 sqlite3_free(zErrMsg);
2184 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2189 ** Set the destination table field of the ShellState structure to
2190 ** the name of the table given. Escape any quote characters in the
2191 ** table name.
2193 static void set_table_name(ShellState *p, const char *zName){
2194 int i, n;
2195 char cQuote;
2196 char *z;
2198 if( p->zDestTable ){
2199 free(p->zDestTable);
2200 p->zDestTable = 0;
2202 if( zName==0 ) return;
2203 cQuote = quoteChar(zName);
2204 n = strlen30(zName);
2205 if( cQuote ) n += n+2;
2206 z = p->zDestTable = malloc( n+1 );
2207 if( z==0 ) shell_out_of_memory();
2208 n = 0;
2209 if( cQuote ) z[n++] = cQuote;
2210 for(i=0; zName[i]; i++){
2211 z[n++] = zName[i];
2212 if( zName[i]==cQuote ) z[n++] = cQuote;
2214 if( cQuote ) z[n++] = cQuote;
2215 z[n] = 0;
2220 ** Execute a query statement that will generate SQL output. Print
2221 ** the result columns, comma-separated, on a line and then add a
2222 ** semicolon terminator to the end of that line.
2224 ** If the number of columns is 1 and that column contains text "--"
2225 ** then write the semicolon on a separate line. That way, if a
2226 ** "--" comment occurs at the end of the statement, the comment
2227 ** won't consume the semicolon terminator.
2229 static int run_table_dump_query(
2230 ShellState *p, /* Query context */
2231 const char *zSelect, /* SELECT statement to extract content */
2232 const char *zFirstRow /* Print before first row, if not NULL */
2234 sqlite3_stmt *pSelect;
2235 int rc;
2236 int nResult;
2237 int i;
2238 const char *z;
2239 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2240 if( rc!=SQLITE_OK || !pSelect ){
2241 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2242 sqlite3_errmsg(p->db));
2243 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2244 return rc;
2246 rc = sqlite3_step(pSelect);
2247 nResult = sqlite3_column_count(pSelect);
2248 while( rc==SQLITE_ROW ){
2249 if( zFirstRow ){
2250 utf8_printf(p->out, "%s", zFirstRow);
2251 zFirstRow = 0;
2253 z = (const char*)sqlite3_column_text(pSelect, 0);
2254 utf8_printf(p->out, "%s", z);
2255 for(i=1; i<nResult; i++){
2256 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2258 if( z==0 ) z = "";
2259 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2260 if( z[0] ){
2261 raw_printf(p->out, "\n;\n");
2262 }else{
2263 raw_printf(p->out, ";\n");
2265 rc = sqlite3_step(pSelect);
2267 rc = sqlite3_finalize(pSelect);
2268 if( rc!=SQLITE_OK ){
2269 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2270 sqlite3_errmsg(p->db));
2271 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2273 return rc;
2277 ** Allocate space and save off current error string.
2279 static char *save_err_msg(
2280 sqlite3 *db /* Database to query */
2282 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2283 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2284 if( zErrMsg ){
2285 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2287 return zErrMsg;
2290 #ifdef __linux__
2292 ** Attempt to display I/O stats on Linux using /proc/PID/io
2294 static void displayLinuxIoStats(FILE *out){
2295 FILE *in;
2296 char z[200];
2297 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2298 in = fopen(z, "rb");
2299 if( in==0 ) return;
2300 while( fgets(z, sizeof(z), in)!=0 ){
2301 static const struct {
2302 const char *zPattern;
2303 const char *zDesc;
2304 } aTrans[] = {
2305 { "rchar: ", "Bytes received by read():" },
2306 { "wchar: ", "Bytes sent to write():" },
2307 { "syscr: ", "Read() system calls:" },
2308 { "syscw: ", "Write() system calls:" },
2309 { "read_bytes: ", "Bytes read from storage:" },
2310 { "write_bytes: ", "Bytes written to storage:" },
2311 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2313 int i;
2314 for(i=0; i<ArraySize(aTrans); i++){
2315 int n = strlen30(aTrans[i].zPattern);
2316 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2317 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2318 break;
2322 fclose(in);
2324 #endif
2327 ** Display a single line of status using 64-bit values.
2329 static void displayStatLine(
2330 ShellState *p, /* The shell context */
2331 char *zLabel, /* Label for this one line */
2332 char *zFormat, /* Format for the result */
2333 int iStatusCtrl, /* Which status to display */
2334 int bReset /* True to reset the stats */
2336 sqlite3_int64 iCur = -1;
2337 sqlite3_int64 iHiwtr = -1;
2338 int i, nPercent;
2339 char zLine[200];
2340 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2341 for(i=0, nPercent=0; zFormat[i]; i++){
2342 if( zFormat[i]=='%' ) nPercent++;
2344 if( nPercent>1 ){
2345 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2346 }else{
2347 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2349 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2353 ** Display memory stats.
2355 static int display_stats(
2356 sqlite3 *db, /* Database to query */
2357 ShellState *pArg, /* Pointer to ShellState */
2358 int bReset /* True to reset the stats */
2360 int iCur;
2361 int iHiwtr;
2362 FILE *out;
2363 if( pArg==0 || pArg->out==0 ) return 0;
2364 out = pArg->out;
2366 if( pArg->pStmt && (pArg->statsOn & 2) ){
2367 int nCol, i, x;
2368 sqlite3_stmt *pStmt = pArg->pStmt;
2369 char z[100];
2370 nCol = sqlite3_column_count(pStmt);
2371 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2372 for(i=0; i<nCol; i++){
2373 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2374 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2375 #ifndef SQLITE_OMIT_DECLTYPE
2376 sqlite3_snprintf(30, z+x, "declared type:");
2377 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2378 #endif
2379 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2380 sqlite3_snprintf(30, z+x, "database name:");
2381 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2382 sqlite3_snprintf(30, z+x, "table name:");
2383 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2384 sqlite3_snprintf(30, z+x, "origin name:");
2385 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2386 #endif
2390 displayStatLine(pArg, "Memory Used:",
2391 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2392 displayStatLine(pArg, "Number of Outstanding Allocations:",
2393 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2394 if( pArg->shellFlgs & SHFLG_Pagecache ){
2395 displayStatLine(pArg, "Number of Pcache Pages Used:",
2396 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2398 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2399 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2400 displayStatLine(pArg, "Largest Allocation:",
2401 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2402 displayStatLine(pArg, "Largest Pcache Allocation:",
2403 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2404 #ifdef YYTRACKMAXSTACKDEPTH
2405 displayStatLine(pArg, "Deepest Parser Stack:",
2406 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2407 #endif
2409 if( db ){
2410 if( pArg->shellFlgs & SHFLG_Lookaside ){
2411 iHiwtr = iCur = -1;
2412 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2413 &iCur, &iHiwtr, bReset);
2414 raw_printf(pArg->out,
2415 "Lookaside Slots Used: %d (max %d)\n",
2416 iCur, iHiwtr);
2417 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2418 &iCur, &iHiwtr, bReset);
2419 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2420 iHiwtr);
2421 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2422 &iCur, &iHiwtr, bReset);
2423 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2424 iHiwtr);
2425 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2426 &iCur, &iHiwtr, bReset);
2427 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2428 iHiwtr);
2430 iHiwtr = iCur = -1;
2431 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2432 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2433 iCur);
2434 iHiwtr = iCur = -1;
2435 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2436 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2437 iHiwtr = iCur = -1;
2438 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2439 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2440 iHiwtr = iCur = -1;
2441 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2442 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2443 iHiwtr = iCur = -1;
2444 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2445 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2446 iHiwtr = iCur = -1;
2447 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2448 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2449 iCur);
2450 iHiwtr = iCur = -1;
2451 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2452 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2453 iCur);
2456 if( pArg->pStmt ){
2457 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2458 bReset);
2459 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2460 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2461 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2462 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2463 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2464 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2465 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2466 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2467 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2468 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2469 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2470 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2471 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
2474 #ifdef __linux__
2475 displayLinuxIoStats(pArg->out);
2476 #endif
2478 /* Do not remove this machine readable comment: extra-stats-output-here */
2480 return 0;
2484 ** Display scan stats.
2486 static void display_scanstats(
2487 sqlite3 *db, /* Database to query */
2488 ShellState *pArg /* Pointer to ShellState */
2490 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2491 UNUSED_PARAMETER(db);
2492 UNUSED_PARAMETER(pArg);
2493 #else
2494 int i, k, n, mx;
2495 raw_printf(pArg->out, "-------- scanstats --------\n");
2496 mx = 0;
2497 for(k=0; k<=mx; k++){
2498 double rEstLoop = 1.0;
2499 for(i=n=0; 1; i++){
2500 sqlite3_stmt *p = pArg->pStmt;
2501 sqlite3_int64 nLoop, nVisit;
2502 double rEst;
2503 int iSid;
2504 const char *zExplain;
2505 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2506 break;
2508 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2509 if( iSid>mx ) mx = iSid;
2510 if( iSid!=k ) continue;
2511 if( n==0 ){
2512 rEstLoop = (double)nLoop;
2513 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2515 n++;
2516 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2517 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2518 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2519 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2520 rEstLoop *= rEst;
2521 raw_printf(pArg->out,
2522 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2523 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2527 raw_printf(pArg->out, "---------------------------\n");
2528 #endif
2532 ** Parameter azArray points to a zero-terminated array of strings. zStr
2533 ** points to a single nul-terminated string. Return non-zero if zStr
2534 ** is equal, according to strcmp(), to any of the strings in the array.
2535 ** Otherwise, return zero.
2537 static int str_in_array(const char *zStr, const char **azArray){
2538 int i;
2539 for(i=0; azArray[i]; i++){
2540 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2542 return 0;
2546 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2547 ** and populate the ShellState.aiIndent[] array with the number of
2548 ** spaces each opcode should be indented before it is output.
2550 ** The indenting rules are:
2552 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2553 ** all opcodes that occur between the p2 jump destination and the opcode
2554 ** itself by 2 spaces.
2556 ** * For each "Goto", if the jump destination is earlier in the program
2557 ** and ends on one of:
2558 ** Yield SeekGt SeekLt RowSetRead Rewind
2559 ** or if the P1 parameter is one instead of zero,
2560 ** then indent all opcodes between the earlier instruction
2561 ** and "Goto" by 2 spaces.
2563 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2564 const char *zSql; /* The text of the SQL statement */
2565 const char *z; /* Used to check if this is an EXPLAIN */
2566 int *abYield = 0; /* True if op is an OP_Yield */
2567 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2568 int iOp; /* Index of operation in p->aiIndent[] */
2570 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2571 "NextIfOpen", "PrevIfOpen", 0 };
2572 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2573 "Rewind", 0 };
2574 const char *azGoto[] = { "Goto", 0 };
2576 /* Try to figure out if this is really an EXPLAIN statement. If this
2577 ** cannot be verified, return early. */
2578 if( sqlite3_column_count(pSql)!=8 ){
2579 p->cMode = p->mode;
2580 return;
2582 zSql = sqlite3_sql(pSql);
2583 if( zSql==0 ) return;
2584 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2585 if( sqlite3_strnicmp(z, "explain", 7) ){
2586 p->cMode = p->mode;
2587 return;
2590 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2591 int i;
2592 int iAddr = sqlite3_column_int(pSql, 0);
2593 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2595 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2596 ** p2 is an instruction address, set variable p2op to the index of that
2597 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2598 ** the current instruction is part of a sub-program generated by an
2599 ** SQL trigger or foreign key. */
2600 int p2 = sqlite3_column_int(pSql, 3);
2601 int p2op = (p2 + (iOp-iAddr));
2603 /* Grow the p->aiIndent array as required */
2604 if( iOp>=nAlloc ){
2605 if( iOp==0 ){
2606 /* Do further verfication that this is explain output. Abort if
2607 ** it is not */
2608 static const char *explainCols[] = {
2609 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2610 int jj;
2611 for(jj=0; jj<ArraySize(explainCols); jj++){
2612 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2613 p->cMode = p->mode;
2614 sqlite3_reset(pSql);
2615 return;
2619 nAlloc += 100;
2620 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2621 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2623 abYield[iOp] = str_in_array(zOp, azYield);
2624 p->aiIndent[iOp] = 0;
2625 p->nIndent = iOp+1;
2627 if( str_in_array(zOp, azNext) ){
2628 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2630 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2631 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2633 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2637 p->iIndent = 0;
2638 sqlite3_free(abYield);
2639 sqlite3_reset(pSql);
2643 ** Free the array allocated by explain_data_prepare().
2645 static void explain_data_delete(ShellState *p){
2646 sqlite3_free(p->aiIndent);
2647 p->aiIndent = 0;
2648 p->nIndent = 0;
2649 p->iIndent = 0;
2653 ** Disable and restore .wheretrace and .selecttrace settings.
2655 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2656 extern int sqlite3SelectTrace;
2657 static int savedSelectTrace;
2658 #endif
2659 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2660 extern int sqlite3WhereTrace;
2661 static int savedWhereTrace;
2662 #endif
2663 static void disable_debug_trace_modes(void){
2664 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2665 savedSelectTrace = sqlite3SelectTrace;
2666 sqlite3SelectTrace = 0;
2667 #endif
2668 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2669 savedWhereTrace = sqlite3WhereTrace;
2670 sqlite3WhereTrace = 0;
2671 #endif
2673 static void restore_debug_trace_modes(void){
2674 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2675 sqlite3SelectTrace = savedSelectTrace;
2676 #endif
2677 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2678 sqlite3WhereTrace = savedWhereTrace;
2679 #endif
2683 ** Run a prepared statement
2685 static void exec_prepared_stmt(
2686 ShellState *pArg, /* Pointer to ShellState */
2687 sqlite3_stmt *pStmt /* Statment to run */
2689 int rc;
2691 /* perform the first step. this will tell us if we
2692 ** have a result set or not and how wide it is.
2694 rc = sqlite3_step(pStmt);
2695 /* if we have a result set... */
2696 if( SQLITE_ROW == rc ){
2697 /* allocate space for col name ptr, value ptr, and type */
2698 int nCol = sqlite3_column_count(pStmt);
2699 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2700 if( !pData ){
2701 rc = SQLITE_NOMEM;
2702 }else{
2703 char **azCols = (char **)pData; /* Names of result columns */
2704 char **azVals = &azCols[nCol]; /* Results */
2705 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2706 int i, x;
2707 assert(sizeof(int) <= sizeof(char *));
2708 /* save off ptrs to column names */
2709 for(i=0; i<nCol; i++){
2710 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2713 /* extract the data and data types */
2714 for(i=0; i<nCol; i++){
2715 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2716 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2717 azVals[i] = "";
2718 }else{
2719 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2721 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2722 rc = SQLITE_NOMEM;
2723 break; /* from for */
2725 } /* end for */
2727 /* if data and types extracted successfully... */
2728 if( SQLITE_ROW == rc ){
2729 /* call the supplied callback with the result row data */
2730 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2731 rc = SQLITE_ABORT;
2732 }else{
2733 rc = sqlite3_step(pStmt);
2736 } while( SQLITE_ROW == rc );
2737 sqlite3_free(pData);
2742 #ifndef SQLITE_OMIT_VIRTUALTABLE
2744 ** This function is called to process SQL if the previous shell command
2745 ** was ".expert". It passes the SQL in the second argument directly to
2746 ** the sqlite3expert object.
2748 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2749 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2750 ** an English language error message. It is the responsibility of the
2751 ** caller to eventually free this buffer using sqlite3_free().
2753 static int expertHandleSQL(
2754 ShellState *pState,
2755 const char *zSql,
2756 char **pzErr
2758 assert( pState->expert.pExpert );
2759 assert( pzErr==0 || *pzErr==0 );
2760 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2764 ** This function is called either to silently clean up the object
2765 ** created by the ".expert" command (if bCancel==1), or to generate a
2766 ** report from it and then clean it up (if bCancel==0).
2768 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2769 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2770 ** an English language error message. It is the responsibility of the
2771 ** caller to eventually free this buffer using sqlite3_free().
2773 static int expertFinish(
2774 ShellState *pState,
2775 int bCancel,
2776 char **pzErr
2778 int rc = SQLITE_OK;
2779 sqlite3expert *p = pState->expert.pExpert;
2780 assert( p );
2781 assert( bCancel || pzErr==0 || *pzErr==0 );
2782 if( bCancel==0 ){
2783 FILE *out = pState->out;
2784 int bVerbose = pState->expert.bVerbose;
2786 rc = sqlite3_expert_analyze(p, pzErr);
2787 if( rc==SQLITE_OK ){
2788 int nQuery = sqlite3_expert_count(p);
2789 int i;
2791 if( bVerbose ){
2792 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2793 raw_printf(out, "-- Candidates -----------------------------\n");
2794 raw_printf(out, "%s\n", zCand);
2796 for(i=0; i<nQuery; i++){
2797 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2798 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2799 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2800 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2801 if( bVerbose ){
2802 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2803 raw_printf(out, "%s\n\n", zSql);
2805 raw_printf(out, "%s\n", zIdx);
2806 raw_printf(out, "%s\n", zEQP);
2810 sqlite3_expert_destroy(p);
2811 pState->expert.pExpert = 0;
2812 return rc;
2816 ** Implementation of ".expert" dot command.
2818 static int expertDotCommand(
2819 ShellState *pState, /* Current shell tool state */
2820 char **azArg, /* Array of arguments passed to dot command */
2821 int nArg /* Number of entries in azArg[] */
2823 int rc = SQLITE_OK;
2824 char *zErr = 0;
2825 int i;
2826 int iSample = 0;
2828 assert( pState->expert.pExpert==0 );
2829 memset(&pState->expert, 0, sizeof(ExpertInfo));
2831 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2832 char *z = azArg[i];
2833 int n;
2834 if( z[0]=='-' && z[1]=='-' ) z++;
2835 n = strlen30(z);
2836 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2837 pState->expert.bVerbose = 1;
2839 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2840 if( i==(nArg-1) ){
2841 raw_printf(stderr, "option requires an argument: %s\n", z);
2842 rc = SQLITE_ERROR;
2843 }else{
2844 iSample = (int)integerValue(azArg[++i]);
2845 if( iSample<0 || iSample>100 ){
2846 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2847 rc = SQLITE_ERROR;
2851 else{
2852 raw_printf(stderr, "unknown option: %s\n", z);
2853 rc = SQLITE_ERROR;
2857 if( rc==SQLITE_OK ){
2858 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2859 if( pState->expert.pExpert==0 ){
2860 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2861 rc = SQLITE_ERROR;
2862 }else{
2863 sqlite3_expert_config(
2864 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2869 return rc;
2871 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2874 ** Execute a statement or set of statements. Print
2875 ** any result rows/columns depending on the current mode
2876 ** set via the supplied callback.
2878 ** This is very similar to SQLite's built-in sqlite3_exec()
2879 ** function except it takes a slightly different callback
2880 ** and callback data argument.
2882 static int shell_exec(
2883 ShellState *pArg, /* Pointer to ShellState */
2884 const char *zSql, /* SQL to be evaluated */
2885 char **pzErrMsg /* Error msg written here */
2887 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2888 int rc = SQLITE_OK; /* Return Code */
2889 int rc2;
2890 const char *zLeftover; /* Tail of unprocessed SQL */
2891 sqlite3 *db = pArg->db;
2893 if( pzErrMsg ){
2894 *pzErrMsg = NULL;
2897 #ifndef SQLITE_OMIT_VIRTUALTABLE
2898 if( pArg->expert.pExpert ){
2899 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2900 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2902 #endif
2904 while( zSql[0] && (SQLITE_OK == rc) ){
2905 static const char *zStmtSql;
2906 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2907 if( SQLITE_OK != rc ){
2908 if( pzErrMsg ){
2909 *pzErrMsg = save_err_msg(db);
2911 }else{
2912 if( !pStmt ){
2913 /* this happens for a comment or white-space */
2914 zSql = zLeftover;
2915 while( IsSpace(zSql[0]) ) zSql++;
2916 continue;
2918 zStmtSql = sqlite3_sql(pStmt);
2919 if( zStmtSql==0 ) zStmtSql = "";
2920 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2922 /* save off the prepared statment handle and reset row count */
2923 if( pArg ){
2924 pArg->pStmt = pStmt;
2925 pArg->cnt = 0;
2928 /* echo the sql statement if echo on */
2929 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2930 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2933 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2934 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2935 sqlite3_stmt *pExplain;
2936 char *zEQP;
2937 int triggerEQP = 0;
2938 disable_debug_trace_modes();
2939 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2940 if( pArg->autoEQP>=AUTOEQP_trigger ){
2941 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2943 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2944 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2945 if( rc==SQLITE_OK ){
2946 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2947 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
2948 int iEqpId = sqlite3_column_int(pExplain, 0);
2949 int iParentId = sqlite3_column_int(pExplain, 1);
2950 if( zEQPLine[0]=='-' ) eqp_render(pArg);
2951 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
2953 eqp_render(pArg);
2955 sqlite3_finalize(pExplain);
2956 sqlite3_free(zEQP);
2957 if( pArg->autoEQP>=AUTOEQP_full ){
2958 /* Also do an EXPLAIN for ".eqp full" mode */
2959 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2960 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2961 if( rc==SQLITE_OK ){
2962 pArg->cMode = MODE_Explain;
2963 explain_data_prepare(pArg, pExplain);
2964 exec_prepared_stmt(pArg, pExplain);
2965 explain_data_delete(pArg);
2967 sqlite3_finalize(pExplain);
2968 sqlite3_free(zEQP);
2970 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
2971 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
2972 /* Reprepare pStmt before reactiving trace modes */
2973 sqlite3_finalize(pStmt);
2974 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
2975 if( pArg ) pArg->pStmt = pStmt;
2977 restore_debug_trace_modes();
2980 if( pArg ){
2981 pArg->cMode = pArg->mode;
2982 if( pArg->autoExplain ){
2983 if( sqlite3_column_count(pStmt)==8
2984 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2986 pArg->cMode = MODE_Explain;
2988 if( sqlite3_column_count(pStmt)==4
2989 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
2990 pArg->cMode = MODE_EQP;
2994 /* If the shell is currently in ".explain" mode, gather the extra
2995 ** data required to add indents to the output.*/
2996 if( pArg->cMode==MODE_Explain ){
2997 explain_data_prepare(pArg, pStmt);
3001 exec_prepared_stmt(pArg, pStmt);
3002 explain_data_delete(pArg);
3003 eqp_render(pArg);
3005 /* print usage stats if stats on */
3006 if( pArg && pArg->statsOn ){
3007 display_stats(db, pArg, 0);
3010 /* print loop-counters if required */
3011 if( pArg && pArg->scanstatsOn ){
3012 display_scanstats(db, pArg);
3015 /* Finalize the statement just executed. If this fails, save a
3016 ** copy of the error message. Otherwise, set zSql to point to the
3017 ** next statement to execute. */
3018 rc2 = sqlite3_finalize(pStmt);
3019 if( rc!=SQLITE_NOMEM ) rc = rc2;
3020 if( rc==SQLITE_OK ){
3021 zSql = zLeftover;
3022 while( IsSpace(zSql[0]) ) zSql++;
3023 }else if( pzErrMsg ){
3024 *pzErrMsg = save_err_msg(db);
3027 /* clear saved stmt handle */
3028 if( pArg ){
3029 pArg->pStmt = NULL;
3032 } /* end while */
3034 return rc;
3038 ** Release memory previously allocated by tableColumnList().
3040 static void freeColumnList(char **azCol){
3041 int i;
3042 for(i=1; azCol[i]; i++){
3043 sqlite3_free(azCol[i]);
3045 /* azCol[0] is a static string */
3046 sqlite3_free(azCol);
3050 ** Return a list of pointers to strings which are the names of all
3051 ** columns in table zTab. The memory to hold the names is dynamically
3052 ** allocated and must be released by the caller using a subsequent call
3053 ** to freeColumnList().
3055 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3056 ** value that needs to be preserved, then azCol[0] is filled in with the
3057 ** name of the rowid column.
3059 ** The first regular column in the table is azCol[1]. The list is terminated
3060 ** by an entry with azCol[i]==0.
3062 static char **tableColumnList(ShellState *p, const char *zTab){
3063 char **azCol = 0;
3064 sqlite3_stmt *pStmt;
3065 char *zSql;
3066 int nCol = 0;
3067 int nAlloc = 0;
3068 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3069 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3070 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3071 int rc;
3073 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3074 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3075 sqlite3_free(zSql);
3076 if( rc ) return 0;
3077 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3078 if( nCol>=nAlloc-2 ){
3079 nAlloc = nAlloc*2 + nCol + 10;
3080 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3081 if( azCol==0 ) shell_out_of_memory();
3083 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3084 if( sqlite3_column_int(pStmt, 5) ){
3085 nPK++;
3086 if( nPK==1
3087 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3088 "INTEGER")==0
3090 isIPK = 1;
3091 }else{
3092 isIPK = 0;
3096 sqlite3_finalize(pStmt);
3097 if( azCol==0 ) return 0;
3098 azCol[0] = 0;
3099 azCol[nCol+1] = 0;
3101 /* The decision of whether or not a rowid really needs to be preserved
3102 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3103 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3104 ** rowids on tables where the rowid is inaccessible because there are other
3105 ** columns in the table named "rowid", "_rowid_", and "oid".
3107 if( preserveRowid && isIPK ){
3108 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3109 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3110 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3111 ** ROWID aliases. To distinguish these cases, check to see if
3112 ** there is a "pk" entry in "PRAGMA index_list". There will be
3113 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3115 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3116 " WHERE origin='pk'", zTab);
3117 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3118 sqlite3_free(zSql);
3119 if( rc ){
3120 freeColumnList(azCol);
3121 return 0;
3123 rc = sqlite3_step(pStmt);
3124 sqlite3_finalize(pStmt);
3125 preserveRowid = rc==SQLITE_ROW;
3127 if( preserveRowid ){
3128 /* Only preserve the rowid if we can find a name to use for the
3129 ** rowid */
3130 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3131 int i, j;
3132 for(j=0; j<3; j++){
3133 for(i=1; i<=nCol; i++){
3134 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3136 if( i>nCol ){
3137 /* At this point, we know that azRowid[j] is not the name of any
3138 ** ordinary column in the table. Verify that azRowid[j] is a valid
3139 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3140 ** tables will fail this last check */
3141 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3142 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3143 break;
3147 return azCol;
3151 ** Toggle the reverse_unordered_selects setting.
3153 static void toggleSelectOrder(sqlite3 *db){
3154 sqlite3_stmt *pStmt = 0;
3155 int iSetting = 0;
3156 char zStmt[100];
3157 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3158 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3159 iSetting = sqlite3_column_int(pStmt, 0);
3161 sqlite3_finalize(pStmt);
3162 sqlite3_snprintf(sizeof(zStmt), zStmt,
3163 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3164 sqlite3_exec(db, zStmt, 0, 0, 0);
3168 ** This is a different callback routine used for dumping the database.
3169 ** Each row received by this callback consists of a table name,
3170 ** the table type ("index" or "table") and SQL to create the table.
3171 ** This routine should print text sufficient to recreate the table.
3173 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3174 int rc;
3175 const char *zTable;
3176 const char *zType;
3177 const char *zSql;
3178 ShellState *p = (ShellState *)pArg;
3180 UNUSED_PARAMETER(azNotUsed);
3181 if( nArg!=3 || azArg==0 ) return 0;
3182 zTable = azArg[0];
3183 zType = azArg[1];
3184 zSql = azArg[2];
3186 if( strcmp(zTable, "sqlite_sequence")==0 ){
3187 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3188 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3189 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3190 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3191 return 0;
3192 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3193 char *zIns;
3194 if( !p->writableSchema ){
3195 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3196 p->writableSchema = 1;
3198 zIns = sqlite3_mprintf(
3199 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3200 "VALUES('table','%q','%q',0,'%q');",
3201 zTable, zTable, zSql);
3202 utf8_printf(p->out, "%s\n", zIns);
3203 sqlite3_free(zIns);
3204 return 0;
3205 }else{
3206 printSchemaLine(p->out, zSql, ";\n");
3209 if( strcmp(zType, "table")==0 ){
3210 ShellText sSelect;
3211 ShellText sTable;
3212 char **azCol;
3213 int i;
3214 char *savedDestTable;
3215 int savedMode;
3217 azCol = tableColumnList(p, zTable);
3218 if( azCol==0 ){
3219 p->nErr++;
3220 return 0;
3223 /* Always quote the table name, even if it appears to be pure ascii,
3224 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3225 initText(&sTable);
3226 appendText(&sTable, zTable, quoteChar(zTable));
3227 /* If preserving the rowid, add a column list after the table name.
3228 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3229 ** instead of the usual "INSERT INTO tab VALUES(...)".
3231 if( azCol[0] ){
3232 appendText(&sTable, "(", 0);
3233 appendText(&sTable, azCol[0], 0);
3234 for(i=1; azCol[i]; i++){
3235 appendText(&sTable, ",", 0);
3236 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3238 appendText(&sTable, ")", 0);
3241 /* Build an appropriate SELECT statement */
3242 initText(&sSelect);
3243 appendText(&sSelect, "SELECT ", 0);
3244 if( azCol[0] ){
3245 appendText(&sSelect, azCol[0], 0);
3246 appendText(&sSelect, ",", 0);
3248 for(i=1; azCol[i]; i++){
3249 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3250 if( azCol[i+1] ){
3251 appendText(&sSelect, ",", 0);
3254 freeColumnList(azCol);
3255 appendText(&sSelect, " FROM ", 0);
3256 appendText(&sSelect, zTable, quoteChar(zTable));
3258 savedDestTable = p->zDestTable;
3259 savedMode = p->mode;
3260 p->zDestTable = sTable.z;
3261 p->mode = p->cMode = MODE_Insert;
3262 rc = shell_exec(p, sSelect.z, 0);
3263 if( (rc&0xff)==SQLITE_CORRUPT ){
3264 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3265 toggleSelectOrder(p->db);
3266 shell_exec(p, sSelect.z, 0);
3267 toggleSelectOrder(p->db);
3269 p->zDestTable = savedDestTable;
3270 p->mode = savedMode;
3271 freeText(&sTable);
3272 freeText(&sSelect);
3273 if( rc ) p->nErr++;
3275 return 0;
3279 ** Run zQuery. Use dump_callback() as the callback routine so that
3280 ** the contents of the query are output as SQL statements.
3282 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3283 ** "ORDER BY rowid DESC" to the end.
3285 static int run_schema_dump_query(
3286 ShellState *p,
3287 const char *zQuery
3289 int rc;
3290 char *zErr = 0;
3291 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3292 if( rc==SQLITE_CORRUPT ){
3293 char *zQ2;
3294 int len = strlen30(zQuery);
3295 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3296 if( zErr ){
3297 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3298 sqlite3_free(zErr);
3299 zErr = 0;
3301 zQ2 = malloc( len+100 );
3302 if( zQ2==0 ) return rc;
3303 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3304 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3305 if( rc ){
3306 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3307 }else{
3308 rc = SQLITE_CORRUPT;
3310 sqlite3_free(zErr);
3311 free(zQ2);
3313 return rc;
3317 ** Text of a help message
3319 static char zHelp[] =
3320 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3321 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3322 #endif
3323 #ifndef SQLITE_OMIT_AUTHORIZATION
3324 ".auth ON|OFF Show authorizer callbacks\n"
3325 #endif
3326 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3327 " Add \"--append\" to open using appendvfs.\n"
3328 ".bail on|off Stop after hitting an error. Default OFF\n"
3329 ".binary on|off Turn binary output on or off. Default OFF\n"
3330 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3331 ".changes on|off Show number of rows changed by SQL\n"
3332 ".check GLOB Fail if output since .testcase does not match\n"
3333 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3334 ".databases List names and files of attached databases\n"
3335 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options\n"
3336 ".dbinfo ?DB? Show status information about the database\n"
3337 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3338 " If TABLE specified, only dump tables matching\n"
3339 " LIKE pattern TABLE.\n"
3340 ".echo on|off Turn command echo on or off\n"
3341 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3342 ".excel Display the output of next command in a spreadsheet\n"
3343 ".exit Exit this program\n"
3344 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
3345 /* Because explain mode comes on automatically now, the ".explain" mode
3346 ** is removed from the help screen. It is still supported for legacy, however */
3347 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3348 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3349 ".headers on|off Turn display of headers on or off\n"
3350 ".help Show this message\n"
3351 ".import FILE TABLE Import data from FILE into TABLE\n"
3352 #ifndef SQLITE_OMIT_TEST_CONTROL
3353 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3354 #endif
3355 ".indexes ?TABLE? Show names of all indexes\n"
3356 " If TABLE specified, only show indexes for tables\n"
3357 " matching LIKE pattern TABLE.\n"
3358 #ifdef SQLITE_ENABLE_IOTRACE
3359 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3360 #endif
3361 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3362 ".lint OPTIONS Report potential schema issues. Options:\n"
3363 " fkey-indexes Find missing foreign key indexes\n"
3364 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3365 ".load FILE ?ENTRY? Load an extension library\n"
3366 #endif
3367 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3368 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3369 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3370 " csv Comma-separated values\n"
3371 " column Left-aligned columns. (See .width)\n"
3372 " html HTML <table> code\n"
3373 " insert SQL insert statements for TABLE\n"
3374 " line One value per line\n"
3375 " list Values delimited by \"|\"\n"
3376 " quote Escape answers as for SQL\n"
3377 " tabs Tab-separated values\n"
3378 " tcl TCL list elements\n"
3379 ".nullvalue STRING Use STRING in place of NULL values\n"
3380 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
3381 " or invoke system text editor (-e) or spreadsheet (-x)\n"
3382 " on the output.\n"
3383 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3384 " The --new option starts with an empty file\n"
3385 " Other options: --readonly --append --zip\n"
3386 ".output ?FILE? Send output to FILE or stdout\n"
3387 ".print STRING... Print literal STRING\n"
3388 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3389 ".quit Exit this program\n"
3390 ".read FILENAME Execute SQL in FILENAME\n"
3391 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3392 ".save FILE Write in-memory database into FILE\n"
3393 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3394 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3395 " Add --indent for pretty-printing\n"
3396 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3397 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3398 " separator for both the output mode and .import\n"
3399 #if defined(SQLITE_ENABLE_SESSION)
3400 ".session CMD ... Create or control sessions\n"
3401 #endif
3402 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3403 #ifndef SQLITE_NOHAVE_SYSTEM
3404 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3405 #endif
3406 ".show Show the current values for various settings\n"
3407 ".stats ?on|off? Show stats or turn stats on or off\n"
3408 #ifndef SQLITE_NOHAVE_SYSTEM
3409 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3410 #endif
3411 ".tables ?TABLE? List names of tables\n"
3412 " If TABLE specified, only list tables matching\n"
3413 " LIKE pattern TABLE.\n"
3414 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3415 ".timeout MS Try opening locked tables for MS milliseconds\n"
3416 ".timer on|off Turn SQL timer on or off\n"
3417 ".trace FILE|off Output each SQL statement as it is run\n"
3418 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3419 ".vfslist List all available VFSes\n"
3420 ".vfsname ?AUX? Print the name of the VFS stack\n"
3421 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3422 " Negative values right-justify\n"
3425 #if defined(SQLITE_ENABLE_SESSION)
3427 ** Print help information for the ".sessions" command
3429 void session_help(ShellState *p){
3430 raw_printf(p->out,
3431 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3432 "If ?NAME? is omitted, the first defined session is used.\n"
3433 "Subcommands:\n"
3434 " attach TABLE Attach TABLE\n"
3435 " changeset FILE Write a changeset into FILE\n"
3436 " close Close one session\n"
3437 " enable ?BOOLEAN? Set or query the enable bit\n"
3438 " filter GLOB... Reject tables matching GLOBs\n"
3439 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3440 " isempty Query whether the session is empty\n"
3441 " list List currently open session names\n"
3442 " open DB NAME Open a new session on DB\n"
3443 " patchset FILE Write a patchset into FILE\n"
3446 #endif
3449 /* Forward reference */
3450 static int process_input(ShellState *p, FILE *in);
3453 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3454 ** and return a pointer to the buffer. The caller is responsible for freeing
3455 ** the memory.
3457 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3458 ** read.
3460 ** For convenience, a nul-terminator byte is always appended to the data read
3461 ** from the file before the buffer is returned. This byte is not included in
3462 ** the final value of (*pnByte), if applicable.
3464 ** NULL is returned if any error is encountered. The final value of *pnByte
3465 ** is undefined in this case.
3467 static char *readFile(const char *zName, int *pnByte){
3468 FILE *in = fopen(zName, "rb");
3469 long nIn;
3470 size_t nRead;
3471 char *pBuf;
3472 if( in==0 ) return 0;
3473 fseek(in, 0, SEEK_END);
3474 nIn = ftell(in);
3475 rewind(in);
3476 pBuf = sqlite3_malloc64( nIn+1 );
3477 if( pBuf==0 ) return 0;
3478 nRead = fread(pBuf, nIn, 1, in);
3479 fclose(in);
3480 if( nRead!=1 ){
3481 sqlite3_free(pBuf);
3482 return 0;
3484 pBuf[nIn] = 0;
3485 if( pnByte ) *pnByte = nIn;
3486 return pBuf;
3489 #if defined(SQLITE_ENABLE_SESSION)
3491 ** Close a single OpenSession object and release all of its associated
3492 ** resources.
3494 static void session_close(OpenSession *pSession){
3495 int i;
3496 sqlite3session_delete(pSession->p);
3497 sqlite3_free(pSession->zName);
3498 for(i=0; i<pSession->nFilter; i++){
3499 sqlite3_free(pSession->azFilter[i]);
3501 sqlite3_free(pSession->azFilter);
3502 memset(pSession, 0, sizeof(OpenSession));
3504 #endif
3507 ** Close all OpenSession objects and release all associated resources.
3509 #if defined(SQLITE_ENABLE_SESSION)
3510 static void session_close_all(ShellState *p){
3511 int i;
3512 for(i=0; i<p->nSession; i++){
3513 session_close(&p->aSession[i]);
3515 p->nSession = 0;
3517 #else
3518 # define session_close_all(X)
3519 #endif
3522 ** Implementation of the xFilter function for an open session. Omit
3523 ** any tables named by ".session filter" but let all other table through.
3525 #if defined(SQLITE_ENABLE_SESSION)
3526 static int session_filter(void *pCtx, const char *zTab){
3527 OpenSession *pSession = (OpenSession*)pCtx;
3528 int i;
3529 for(i=0; i<pSession->nFilter; i++){
3530 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3532 return 1;
3534 #endif
3537 ** Try to deduce the type of file for zName based on its content. Return
3538 ** one of the SHELL_OPEN_* constants.
3540 ** If the file does not exist or is empty but its name looks like a ZIP
3541 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3542 ** Otherwise, assume an ordinary database regardless of the filename if
3543 ** the type cannot be determined from content.
3545 int deduceDatabaseType(const char *zName, int dfltZip){
3546 FILE *f = fopen(zName, "rb");
3547 size_t n;
3548 int rc = SHELL_OPEN_UNSPEC;
3549 char zBuf[100];
3550 if( f==0 ){
3551 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3552 return SHELL_OPEN_ZIPFILE;
3553 }else{
3554 return SHELL_OPEN_NORMAL;
3557 fseek(f, -25, SEEK_END);
3558 n = fread(zBuf, 25, 1, f);
3559 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3560 rc = SHELL_OPEN_APPENDVFS;
3561 }else{
3562 fseek(f, -22, SEEK_END);
3563 n = fread(zBuf, 22, 1, f);
3564 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3565 && zBuf[3]==0x06 ){
3566 rc = SHELL_OPEN_ZIPFILE;
3567 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3568 rc = SHELL_OPEN_ZIPFILE;
3571 fclose(f);
3572 return rc;
3575 /* Flags for open_db().
3577 ** The default behavior of open_db() is to exit(1) if the database fails to
3578 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3579 ** but still returns without calling exit.
3581 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3582 ** ZIP archive if the file does not exist or is empty and its name matches
3583 ** the *.zip pattern.
3585 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3586 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3589 ** Make sure the database is open. If it is not, then open it. If
3590 ** the database fails to open, print an error message and exit.
3592 static void open_db(ShellState *p, int openFlags){
3593 if( p->db==0 ){
3594 if( p->openMode==SHELL_OPEN_UNSPEC ){
3595 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3596 p->openMode = SHELL_OPEN_NORMAL;
3597 }else{
3598 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3599 (openFlags & OPEN_DB_ZIPFILE)!=0);
3602 switch( p->openMode ){
3603 case SHELL_OPEN_APPENDVFS: {
3604 sqlite3_open_v2(p->zDbFilename, &p->db,
3605 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3606 break;
3608 case SHELL_OPEN_ZIPFILE: {
3609 sqlite3_open(":memory:", &p->db);
3610 break;
3612 case SHELL_OPEN_READONLY: {
3613 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3614 break;
3616 case SHELL_OPEN_UNSPEC:
3617 case SHELL_OPEN_NORMAL: {
3618 sqlite3_open(p->zDbFilename, &p->db);
3619 break;
3622 globalDb = p->db;
3623 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3624 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3625 p->zDbFilename, sqlite3_errmsg(p->db));
3626 if( openFlags & OPEN_DB_KEEPALIVE ) return;
3627 exit(1);
3629 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3630 sqlite3_enable_load_extension(p->db, 1);
3631 #endif
3632 sqlite3_fileio_init(p->db, 0, 0);
3633 sqlite3_shathree_init(p->db, 0, 0);
3634 sqlite3_completion_init(p->db, 0, 0);
3635 #ifdef SQLITE_HAVE_ZLIB
3636 sqlite3_zipfile_init(p->db, 0, 0);
3637 sqlite3_sqlar_init(p->db, 0, 0);
3638 #endif
3639 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
3640 shellAddSchemaName, 0, 0);
3641 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3642 shellModuleSchema, 0, 0);
3643 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3644 shellPutsFunc, 0, 0);
3645 #ifndef SQLITE_NOHAVE_SYSTEM
3646 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3647 editFunc, 0, 0);
3648 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3649 editFunc, 0, 0);
3650 #endif
3651 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3652 char *zSql = sqlite3_mprintf(
3653 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3654 sqlite3_exec(p->db, zSql, 0, 0, 0);
3655 sqlite3_free(zSql);
3661 ** Attempt to close the databaes connection. Report errors.
3663 void close_db(sqlite3 *db){
3664 int rc = sqlite3_close(db);
3665 if( rc ){
3666 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
3667 rc, sqlite3_errmsg(db));
3671 #if HAVE_READLINE || HAVE_EDITLINE
3673 ** Readline completion callbacks
3675 static char *readline_completion_generator(const char *text, int state){
3676 static sqlite3_stmt *pStmt = 0;
3677 char *zRet;
3678 if( state==0 ){
3679 char *zSql;
3680 sqlite3_finalize(pStmt);
3681 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3682 " FROM completion(%Q) ORDER BY 1", text);
3683 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3684 sqlite3_free(zSql);
3686 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3687 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
3688 }else{
3689 sqlite3_finalize(pStmt);
3690 pStmt = 0;
3691 zRet = 0;
3693 return zRet;
3695 static char **readline_completion(const char *zText, int iStart, int iEnd){
3696 rl_attempted_completion_over = 1;
3697 return rl_completion_matches(zText, readline_completion_generator);
3700 #elif HAVE_LINENOISE
3702 ** Linenoise completion callback
3704 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
3705 int nLine = strlen30(zLine);
3706 int i, iStart;
3707 sqlite3_stmt *pStmt = 0;
3708 char *zSql;
3709 char zBuf[1000];
3711 if( nLine>sizeof(zBuf)-30 ) return;
3712 if( zLine[0]=='.' || zLine[0]=='#') return;
3713 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3714 if( i==nLine-1 ) return;
3715 iStart = i+1;
3716 memcpy(zBuf, zLine, iStart);
3717 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3718 " FROM completion(%Q,%Q) ORDER BY 1",
3719 &zLine[iStart], zLine);
3720 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3721 sqlite3_free(zSql);
3722 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3723 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3724 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3725 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3726 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3727 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3728 linenoiseAddCompletion(lc, zBuf);
3731 sqlite3_finalize(pStmt);
3733 #endif
3736 ** Do C-language style dequoting.
3738 ** \a -> alarm
3739 ** \b -> backspace
3740 ** \t -> tab
3741 ** \n -> newline
3742 ** \v -> vertical tab
3743 ** \f -> form feed
3744 ** \r -> carriage return
3745 ** \s -> space
3746 ** \" -> "
3747 ** \' -> '
3748 ** \\ -> backslash
3749 ** \NNN -> ascii character NNN in octal
3751 static void resolve_backslashes(char *z){
3752 int i, j;
3753 char c;
3754 while( *z && *z!='\\' ) z++;
3755 for(i=j=0; (c = z[i])!=0; i++, j++){
3756 if( c=='\\' && z[i+1]!=0 ){
3757 c = z[++i];
3758 if( c=='a' ){
3759 c = '\a';
3760 }else if( c=='b' ){
3761 c = '\b';
3762 }else if( c=='t' ){
3763 c = '\t';
3764 }else if( c=='n' ){
3765 c = '\n';
3766 }else if( c=='v' ){
3767 c = '\v';
3768 }else if( c=='f' ){
3769 c = '\f';
3770 }else if( c=='r' ){
3771 c = '\r';
3772 }else if( c=='"' ){
3773 c = '"';
3774 }else if( c=='\'' ){
3775 c = '\'';
3776 }else if( c=='\\' ){
3777 c = '\\';
3778 }else if( c>='0' && c<='7' ){
3779 c -= '0';
3780 if( z[i+1]>='0' && z[i+1]<='7' ){
3781 i++;
3782 c = (c<<3) + z[i] - '0';
3783 if( z[i+1]>='0' && z[i+1]<='7' ){
3784 i++;
3785 c = (c<<3) + z[i] - '0';
3790 z[j] = c;
3792 if( j<i ) z[j] = 0;
3796 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3797 ** for TRUE and FALSE. Return the integer value if appropriate.
3799 static int booleanValue(const char *zArg){
3800 int i;
3801 if( zArg[0]=='0' && zArg[1]=='x' ){
3802 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3803 }else{
3804 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3806 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3807 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3808 return 1;
3810 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3811 return 0;
3813 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3814 zArg);
3815 return 0;
3819 ** Set or clear a shell flag according to a boolean value.
3821 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3822 if( booleanValue(zArg) ){
3823 ShellSetFlag(p, mFlag);
3824 }else{
3825 ShellClearFlag(p, mFlag);
3830 ** Close an output file, assuming it is not stderr or stdout
3832 static void output_file_close(FILE *f){
3833 if( f && f!=stdout && f!=stderr ) fclose(f);
3837 ** Try to open an output file. The names "stdout" and "stderr" are
3838 ** recognized and do the right thing. NULL is returned if the output
3839 ** filename is "off".
3841 static FILE *output_file_open(const char *zFile, int bTextMode){
3842 FILE *f;
3843 if( strcmp(zFile,"stdout")==0 ){
3844 f = stdout;
3845 }else if( strcmp(zFile, "stderr")==0 ){
3846 f = stderr;
3847 }else if( strcmp(zFile, "off")==0 ){
3848 f = 0;
3849 }else{
3850 f = fopen(zFile, bTextMode ? "w" : "wb");
3851 if( f==0 ){
3852 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3855 return f;
3858 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3860 ** A routine for handling output from sqlite3_trace().
3862 static int sql_trace_callback(
3863 unsigned mType,
3864 void *pArg,
3865 void *pP,
3866 void *pX
3868 FILE *f = (FILE*)pArg;
3869 UNUSED_PARAMETER(mType);
3870 UNUSED_PARAMETER(pP);
3871 if( f ){
3872 const char *z = (const char*)pX;
3873 int i = strlen30(z);
3874 while( i>0 && z[i-1]==';' ){ i--; }
3875 utf8_printf(f, "%.*s;\n", i, z);
3877 return 0;
3879 #endif
3882 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3883 ** a useful spot to set a debugger breakpoint.
3885 static void test_breakpoint(void){
3886 static int nCall = 0;
3887 nCall++;
3891 ** An object used to read a CSV and other files for import.
3893 typedef struct ImportCtx ImportCtx;
3894 struct ImportCtx {
3895 const char *zFile; /* Name of the input file */
3896 FILE *in; /* Read the CSV text from this input stream */
3897 char *z; /* Accumulated text for a field */
3898 int n; /* Number of bytes in z */
3899 int nAlloc; /* Space allocated for z[] */
3900 int nLine; /* Current line number */
3901 int bNotFirst; /* True if one or more bytes already read */
3902 int cTerm; /* Character that terminated the most recent field */
3903 int cColSep; /* The column separator character. (Usually ",") */
3904 int cRowSep; /* The row separator character. (Usually "\n") */
3907 /* Append a single byte to z[] */
3908 static void import_append_char(ImportCtx *p, int c){
3909 if( p->n+1>=p->nAlloc ){
3910 p->nAlloc += p->nAlloc + 100;
3911 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3912 if( p->z==0 ) shell_out_of_memory();
3914 p->z[p->n++] = (char)c;
3917 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3918 ** with the option of having a separator other than ",".
3920 ** + Input comes from p->in.
3921 ** + Store results in p->z of length p->n. Space to hold p->z comes
3922 ** from sqlite3_malloc64().
3923 ** + Use p->cSep as the column separator. The default is ",".
3924 ** + Use p->rSep as the row separator. The default is "\n".
3925 ** + Keep track of the line number in p->nLine.
3926 ** + Store the character that terminates the field in p->cTerm. Store
3927 ** EOF on end-of-file.
3928 ** + Report syntax errors on stderr
3930 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3931 int c;
3932 int cSep = p->cColSep;
3933 int rSep = p->cRowSep;
3934 p->n = 0;
3935 c = fgetc(p->in);
3936 if( c==EOF || seenInterrupt ){
3937 p->cTerm = EOF;
3938 return 0;
3940 if( c=='"' ){
3941 int pc, ppc;
3942 int startLine = p->nLine;
3943 int cQuote = c;
3944 pc = ppc = 0;
3945 while( 1 ){
3946 c = fgetc(p->in);
3947 if( c==rSep ) p->nLine++;
3948 if( c==cQuote ){
3949 if( pc==cQuote ){
3950 pc = 0;
3951 continue;
3954 if( (c==cSep && pc==cQuote)
3955 || (c==rSep && pc==cQuote)
3956 || (c==rSep && pc=='\r' && ppc==cQuote)
3957 || (c==EOF && pc==cQuote)
3959 do{ p->n--; }while( p->z[p->n]!=cQuote );
3960 p->cTerm = c;
3961 break;
3963 if( pc==cQuote && c!='\r' ){
3964 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3965 p->zFile, p->nLine, cQuote);
3967 if( c==EOF ){
3968 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3969 p->zFile, startLine, cQuote);
3970 p->cTerm = c;
3971 break;
3973 import_append_char(p, c);
3974 ppc = pc;
3975 pc = c;
3977 }else{
3978 /* If this is the first field being parsed and it begins with the
3979 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3980 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3981 import_append_char(p, c);
3982 c = fgetc(p->in);
3983 if( (c&0xff)==0xbb ){
3984 import_append_char(p, c);
3985 c = fgetc(p->in);
3986 if( (c&0xff)==0xbf ){
3987 p->bNotFirst = 1;
3988 p->n = 0;
3989 return csv_read_one_field(p);
3993 while( c!=EOF && c!=cSep && c!=rSep ){
3994 import_append_char(p, c);
3995 c = fgetc(p->in);
3997 if( c==rSep ){
3998 p->nLine++;
3999 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4001 p->cTerm = c;
4003 if( p->z ) p->z[p->n] = 0;
4004 p->bNotFirst = 1;
4005 return p->z;
4008 /* Read a single field of ASCII delimited text.
4010 ** + Input comes from p->in.
4011 ** + Store results in p->z of length p->n. Space to hold p->z comes
4012 ** from sqlite3_malloc64().
4013 ** + Use p->cSep as the column separator. The default is "\x1F".
4014 ** + Use p->rSep as the row separator. The default is "\x1E".
4015 ** + Keep track of the row number in p->nLine.
4016 ** + Store the character that terminates the field in p->cTerm. Store
4017 ** EOF on end-of-file.
4018 ** + Report syntax errors on stderr
4020 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4021 int c;
4022 int cSep = p->cColSep;
4023 int rSep = p->cRowSep;
4024 p->n = 0;
4025 c = fgetc(p->in);
4026 if( c==EOF || seenInterrupt ){
4027 p->cTerm = EOF;
4028 return 0;
4030 while( c!=EOF && c!=cSep && c!=rSep ){
4031 import_append_char(p, c);
4032 c = fgetc(p->in);
4034 if( c==rSep ){
4035 p->nLine++;
4037 p->cTerm = c;
4038 if( p->z ) p->z[p->n] = 0;
4039 return p->z;
4043 ** Try to transfer data for table zTable. If an error is seen while
4044 ** moving forward, try to go backwards. The backwards movement won't
4045 ** work for WITHOUT ROWID tables.
4047 static void tryToCloneData(
4048 ShellState *p,
4049 sqlite3 *newDb,
4050 const char *zTable
4052 sqlite3_stmt *pQuery = 0;
4053 sqlite3_stmt *pInsert = 0;
4054 char *zQuery = 0;
4055 char *zInsert = 0;
4056 int rc;
4057 int i, j, n;
4058 int nTable = strlen30(zTable);
4059 int k = 0;
4060 int cnt = 0;
4061 const int spinRate = 10000;
4063 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4064 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4065 if( rc ){
4066 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4067 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4068 zQuery);
4069 goto end_data_xfer;
4071 n = sqlite3_column_count(pQuery);
4072 zInsert = sqlite3_malloc64(200 + nTable + n*3);
4073 if( zInsert==0 ) shell_out_of_memory();
4074 sqlite3_snprintf(200+nTable,zInsert,
4075 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4076 i = strlen30(zInsert);
4077 for(j=1; j<n; j++){
4078 memcpy(zInsert+i, ",?", 2);
4079 i += 2;
4081 memcpy(zInsert+i, ");", 3);
4082 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4083 if( rc ){
4084 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4085 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4086 zQuery);
4087 goto end_data_xfer;
4089 for(k=0; k<2; k++){
4090 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4091 for(i=0; i<n; i++){
4092 switch( sqlite3_column_type(pQuery, i) ){
4093 case SQLITE_NULL: {
4094 sqlite3_bind_null(pInsert, i+1);
4095 break;
4097 case SQLITE_INTEGER: {
4098 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4099 break;
4101 case SQLITE_FLOAT: {
4102 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4103 break;
4105 case SQLITE_TEXT: {
4106 sqlite3_bind_text(pInsert, i+1,
4107 (const char*)sqlite3_column_text(pQuery,i),
4108 -1, SQLITE_STATIC);
4109 break;
4111 case SQLITE_BLOB: {
4112 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4113 sqlite3_column_bytes(pQuery,i),
4114 SQLITE_STATIC);
4115 break;
4118 } /* End for */
4119 rc = sqlite3_step(pInsert);
4120 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4121 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4122 sqlite3_errmsg(newDb));
4124 sqlite3_reset(pInsert);
4125 cnt++;
4126 if( (cnt%spinRate)==0 ){
4127 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4128 fflush(stdout);
4130 } /* End while */
4131 if( rc==SQLITE_DONE ) break;
4132 sqlite3_finalize(pQuery);
4133 sqlite3_free(zQuery);
4134 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4135 zTable);
4136 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4137 if( rc ){
4138 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4139 break;
4141 } /* End for(k=0...) */
4143 end_data_xfer:
4144 sqlite3_finalize(pQuery);
4145 sqlite3_finalize(pInsert);
4146 sqlite3_free(zQuery);
4147 sqlite3_free(zInsert);
4152 ** Try to transfer all rows of the schema that match zWhere. For
4153 ** each row, invoke xForEach() on the object defined by that row.
4154 ** If an error is encountered while moving forward through the
4155 ** sqlite_master table, try again moving backwards.
4157 static void tryToCloneSchema(
4158 ShellState *p,
4159 sqlite3 *newDb,
4160 const char *zWhere,
4161 void (*xForEach)(ShellState*,sqlite3*,const char*)
4163 sqlite3_stmt *pQuery = 0;
4164 char *zQuery = 0;
4165 int rc;
4166 const unsigned char *zName;
4167 const unsigned char *zSql;
4168 char *zErrMsg = 0;
4170 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4171 " WHERE %s", zWhere);
4172 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4173 if( rc ){
4174 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4175 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4176 zQuery);
4177 goto end_schema_xfer;
4179 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4180 zName = sqlite3_column_text(pQuery, 0);
4181 zSql = sqlite3_column_text(pQuery, 1);
4182 printf("%s... ", zName); fflush(stdout);
4183 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4184 if( zErrMsg ){
4185 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4186 sqlite3_free(zErrMsg);
4187 zErrMsg = 0;
4189 if( xForEach ){
4190 xForEach(p, newDb, (const char*)zName);
4192 printf("done\n");
4194 if( rc!=SQLITE_DONE ){
4195 sqlite3_finalize(pQuery);
4196 sqlite3_free(zQuery);
4197 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4198 " WHERE %s ORDER BY rowid DESC", zWhere);
4199 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4200 if( rc ){
4201 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4202 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4203 zQuery);
4204 goto end_schema_xfer;
4206 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4207 zName = sqlite3_column_text(pQuery, 0);
4208 zSql = sqlite3_column_text(pQuery, 1);
4209 printf("%s... ", zName); fflush(stdout);
4210 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4211 if( zErrMsg ){
4212 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4213 sqlite3_free(zErrMsg);
4214 zErrMsg = 0;
4216 if( xForEach ){
4217 xForEach(p, newDb, (const char*)zName);
4219 printf("done\n");
4222 end_schema_xfer:
4223 sqlite3_finalize(pQuery);
4224 sqlite3_free(zQuery);
4228 ** Open a new database file named "zNewDb". Try to recover as much information
4229 ** as possible out of the main database (which might be corrupt) and write it
4230 ** into zNewDb.
4232 static void tryToClone(ShellState *p, const char *zNewDb){
4233 int rc;
4234 sqlite3 *newDb = 0;
4235 if( access(zNewDb,0)==0 ){
4236 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4237 return;
4239 rc = sqlite3_open(zNewDb, &newDb);
4240 if( rc ){
4241 utf8_printf(stderr, "Cannot create output database: %s\n",
4242 sqlite3_errmsg(newDb));
4243 }else{
4244 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4245 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4246 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4247 tryToCloneSchema(p, newDb, "type!='table'", 0);
4248 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4249 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4251 close_db(newDb);
4255 ** Change the output file back to stdout.
4257 ** If the p->doXdgOpen flag is set, that means the output was being
4258 ** redirected to a temporary file named by p->zTempFile. In that case,
4259 ** launch start/open/xdg-open on that temporary file.
4261 static void output_reset(ShellState *p){
4262 if( p->outfile[0]=='|' ){
4263 #ifndef SQLITE_OMIT_POPEN
4264 pclose(p->out);
4265 #endif
4266 }else{
4267 output_file_close(p->out);
4268 #ifndef SQLITE_NOHAVE_SYSTEM
4269 if( p->doXdgOpen ){
4270 const char *zXdgOpenCmd =
4271 #if defined(_WIN32)
4272 "start";
4273 #elif defined(__APPLE__)
4274 "open";
4275 #else
4276 "xdg-open";
4277 #endif
4278 char *zCmd;
4279 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
4280 if( system(zCmd) ){
4281 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4283 sqlite3_free(zCmd);
4284 outputModePop(p);
4285 p->doXdgOpen = 0;
4287 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4289 p->outfile[0] = 0;
4290 p->out = stdout;
4294 ** Run an SQL command and return the single integer result.
4296 static int db_int(ShellState *p, const char *zSql){
4297 sqlite3_stmt *pStmt;
4298 int res = 0;
4299 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4300 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4301 res = sqlite3_column_int(pStmt,0);
4303 sqlite3_finalize(pStmt);
4304 return res;
4308 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
4310 static unsigned int get2byteInt(unsigned char *a){
4311 return (a[0]<<8) + a[1];
4313 static unsigned int get4byteInt(unsigned char *a){
4314 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4318 ** Implementation of the ".info" command.
4320 ** Return 1 on error, 2 to exit, and 0 otherwise.
4322 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4323 static const struct { const char *zName; int ofst; } aField[] = {
4324 { "file change counter:", 24 },
4325 { "database page count:", 28 },
4326 { "freelist page count:", 36 },
4327 { "schema cookie:", 40 },
4328 { "schema format:", 44 },
4329 { "default cache size:", 48 },
4330 { "autovacuum top root:", 52 },
4331 { "incremental vacuum:", 64 },
4332 { "text encoding:", 56 },
4333 { "user version:", 60 },
4334 { "application id:", 68 },
4335 { "software version:", 96 },
4337 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4338 { "number of tables:",
4339 "SELECT count(*) FROM %s WHERE type='table'" },
4340 { "number of indexes:",
4341 "SELECT count(*) FROM %s WHERE type='index'" },
4342 { "number of triggers:",
4343 "SELECT count(*) FROM %s WHERE type='trigger'" },
4344 { "number of views:",
4345 "SELECT count(*) FROM %s WHERE type='view'" },
4346 { "schema size:",
4347 "SELECT total(length(sql)) FROM %s" },
4349 int i;
4350 char *zSchemaTab;
4351 char *zDb = nArg>=2 ? azArg[1] : "main";
4352 sqlite3_stmt *pStmt = 0;
4353 unsigned char aHdr[100];
4354 open_db(p, 0);
4355 if( p->db==0 ) return 1;
4356 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4357 -1, &pStmt, 0);
4358 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4359 if( sqlite3_step(pStmt)==SQLITE_ROW
4360 && sqlite3_column_bytes(pStmt,0)>100
4362 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4363 sqlite3_finalize(pStmt);
4364 }else{
4365 raw_printf(stderr, "unable to read database header\n");
4366 sqlite3_finalize(pStmt);
4367 return 1;
4369 i = get2byteInt(aHdr+16);
4370 if( i==1 ) i = 65536;
4371 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4372 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4373 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4374 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4375 for(i=0; i<ArraySize(aField); i++){
4376 int ofst = aField[i].ofst;
4377 unsigned int val = get4byteInt(aHdr + ofst);
4378 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4379 switch( ofst ){
4380 case 56: {
4381 if( val==1 ) raw_printf(p->out, " (utf8)");
4382 if( val==2 ) raw_printf(p->out, " (utf16le)");
4383 if( val==3 ) raw_printf(p->out, " (utf16be)");
4386 raw_printf(p->out, "\n");
4388 if( zDb==0 ){
4389 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4390 }else if( strcmp(zDb,"temp")==0 ){
4391 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4392 }else{
4393 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4395 for(i=0; i<ArraySize(aQuery); i++){
4396 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4397 int val = db_int(p, zSql);
4398 sqlite3_free(zSql);
4399 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4401 sqlite3_free(zSchemaTab);
4402 return 0;
4406 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4408 static int shellDatabaseError(sqlite3 *db){
4409 const char *zErr = sqlite3_errmsg(db);
4410 utf8_printf(stderr, "Error: %s\n", zErr);
4411 return 1;
4415 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4416 ** if they match and FALSE (0) if they do not match.
4418 ** Globbing rules:
4420 ** '*' Matches any sequence of zero or more characters.
4422 ** '?' Matches exactly one character.
4424 ** [...] Matches one character from the enclosed list of
4425 ** characters.
4427 ** [^...] Matches one character not in the enclosed list.
4429 ** '#' Matches any sequence of one or more digits with an
4430 ** optional + or - sign in front
4432 ** ' ' Any span of whitespace matches any other span of
4433 ** whitespace.
4435 ** Extra whitespace at the end of z[] is ignored.
4437 static int testcase_glob(const char *zGlob, const char *z){
4438 int c, c2;
4439 int invert;
4440 int seen;
4442 while( (c = (*(zGlob++)))!=0 ){
4443 if( IsSpace(c) ){
4444 if( !IsSpace(*z) ) return 0;
4445 while( IsSpace(*zGlob) ) zGlob++;
4446 while( IsSpace(*z) ) z++;
4447 }else if( c=='*' ){
4448 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4449 if( c=='?' && (*(z++))==0 ) return 0;
4451 if( c==0 ){
4452 return 1;
4453 }else if( c=='[' ){
4454 while( *z && testcase_glob(zGlob-1,z)==0 ){
4455 z++;
4457 return (*z)!=0;
4459 while( (c2 = (*(z++)))!=0 ){
4460 while( c2!=c ){
4461 c2 = *(z++);
4462 if( c2==0 ) return 0;
4464 if( testcase_glob(zGlob,z) ) return 1;
4466 return 0;
4467 }else if( c=='?' ){
4468 if( (*(z++))==0 ) return 0;
4469 }else if( c=='[' ){
4470 int prior_c = 0;
4471 seen = 0;
4472 invert = 0;
4473 c = *(z++);
4474 if( c==0 ) return 0;
4475 c2 = *(zGlob++);
4476 if( c2=='^' ){
4477 invert = 1;
4478 c2 = *(zGlob++);
4480 if( c2==']' ){
4481 if( c==']' ) seen = 1;
4482 c2 = *(zGlob++);
4484 while( c2 && c2!=']' ){
4485 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4486 c2 = *(zGlob++);
4487 if( c>=prior_c && c<=c2 ) seen = 1;
4488 prior_c = 0;
4489 }else{
4490 if( c==c2 ){
4491 seen = 1;
4493 prior_c = c2;
4495 c2 = *(zGlob++);
4497 if( c2==0 || (seen ^ invert)==0 ) return 0;
4498 }else if( c=='#' ){
4499 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4500 if( !IsDigit(z[0]) ) return 0;
4501 z++;
4502 while( IsDigit(z[0]) ){ z++; }
4503 }else{
4504 if( c!=(*(z++)) ) return 0;
4507 while( IsSpace(*z) ){ z++; }
4508 return *z==0;
4513 ** Compare the string as a command-line option with either one or two
4514 ** initial "-" characters.
4516 static int optionMatch(const char *zStr, const char *zOpt){
4517 if( zStr[0]!='-' ) return 0;
4518 zStr++;
4519 if( zStr[0]=='-' ) zStr++;
4520 return strcmp(zStr, zOpt)==0;
4524 ** Delete a file.
4526 int shellDeleteFile(const char *zFilename){
4527 int rc;
4528 #ifdef _WIN32
4529 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4530 rc = _wunlink(z);
4531 sqlite3_free(z);
4532 #else
4533 rc = unlink(zFilename);
4534 #endif
4535 return rc;
4539 ** Try to delete the temporary file (if there is one) and free the
4540 ** memory used to hold the name of the temp file.
4542 static void clearTempFile(ShellState *p){
4543 if( p->zTempFile==0 ) return;
4544 if( p->doXdgOpen ) return;
4545 if( shellDeleteFile(p->zTempFile) ) return;
4546 sqlite3_free(p->zTempFile);
4547 p->zTempFile = 0;
4551 ** Create a new temp file name with the given suffix.
4553 static void newTempFile(ShellState *p, const char *zSuffix){
4554 clearTempFile(p);
4555 sqlite3_free(p->zTempFile);
4556 p->zTempFile = 0;
4557 if( p->db ){
4558 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
4560 if( p->zTempFile==0 ){
4561 sqlite3_uint64 r;
4562 sqlite3_randomness(sizeof(r), &r);
4563 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
4564 }else{
4565 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
4567 if( p->zTempFile==0 ){
4568 raw_printf(stderr, "out of memory\n");
4569 exit(1);
4575 ** The implementation of SQL scalar function fkey_collate_clause(), used
4576 ** by the ".lint fkey-indexes" command. This scalar function is always
4577 ** called with four arguments - the parent table name, the parent column name,
4578 ** the child table name and the child column name.
4580 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4582 ** If either of the named tables or columns do not exist, this function
4583 ** returns an empty string. An empty string is also returned if both tables
4584 ** and columns exist but have the same default collation sequence. Or,
4585 ** if both exist but the default collation sequences are different, this
4586 ** function returns the string " COLLATE <parent-collation>", where
4587 ** <parent-collation> is the default collation sequence of the parent column.
4589 static void shellFkeyCollateClause(
4590 sqlite3_context *pCtx,
4591 int nVal,
4592 sqlite3_value **apVal
4594 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4595 const char *zParent;
4596 const char *zParentCol;
4597 const char *zParentSeq;
4598 const char *zChild;
4599 const char *zChildCol;
4600 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4601 int rc;
4603 assert( nVal==4 );
4604 zParent = (const char*)sqlite3_value_text(apVal[0]);
4605 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4606 zChild = (const char*)sqlite3_value_text(apVal[2]);
4607 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4609 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4610 rc = sqlite3_table_column_metadata(
4611 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4613 if( rc==SQLITE_OK ){
4614 rc = sqlite3_table_column_metadata(
4615 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4619 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4620 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4621 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4622 sqlite3_free(z);
4628 ** The implementation of dot-command ".lint fkey-indexes".
4630 static int lintFkeyIndexes(
4631 ShellState *pState, /* Current shell tool state */
4632 char **azArg, /* Array of arguments passed to dot command */
4633 int nArg /* Number of entries in azArg[] */
4635 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4636 FILE *out = pState->out; /* Stream to write non-error output to */
4637 int bVerbose = 0; /* If -verbose is present */
4638 int bGroupByParent = 0; /* If -groupbyparent is present */
4639 int i; /* To iterate through azArg[] */
4640 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4641 int rc; /* Return code */
4642 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4645 ** This SELECT statement returns one row for each foreign key constraint
4646 ** in the schema of the main database. The column values are:
4648 ** 0. The text of an SQL statement similar to:
4650 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4652 ** This SELECT is similar to the one that the foreign keys implementation
4653 ** needs to run internally on child tables. If there is an index that can
4654 ** be used to optimize this query, then it can also be used by the FK
4655 ** implementation to optimize DELETE or UPDATE statements on the parent
4656 ** table.
4658 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4659 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4660 ** contains an index that can be used to optimize the query.
4662 ** 2. Human readable text that describes the child table and columns. e.g.
4664 ** "child_table(child_key1, child_key2)"
4666 ** 3. Human readable text that describes the parent table and columns. e.g.
4668 ** "parent_table(parent_key1, parent_key2)"
4670 ** 4. A full CREATE INDEX statement for an index that could be used to
4671 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4673 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4675 ** 5. The name of the parent table.
4677 ** These six values are used by the C logic below to generate the report.
4679 const char *zSql =
4680 "SELECT "
4681 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4682 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4683 " || fkey_collate_clause("
4684 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4685 ", "
4686 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4687 " || group_concat('*=?', ' AND ') || ')'"
4688 ", "
4689 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4690 ", "
4691 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4692 ", "
4693 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4694 " || ' ON ' || quote(s.name) || '('"
4695 " || group_concat(quote(f.[from]) ||"
4696 " fkey_collate_clause("
4697 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4698 " || ');'"
4699 ", "
4700 " f.[table] "
4701 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4702 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4703 "GROUP BY s.name, f.id "
4704 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4706 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4708 for(i=2; i<nArg; i++){
4709 int n = strlen30(azArg[i]);
4710 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4711 bVerbose = 1;
4713 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4714 bGroupByParent = 1;
4715 zIndent = " ";
4717 else{
4718 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4719 azArg[0], azArg[1]
4721 return SQLITE_ERROR;
4725 /* Register the fkey_collate_clause() SQL function */
4726 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4727 0, shellFkeyCollateClause, 0, 0
4731 if( rc==SQLITE_OK ){
4732 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4734 if( rc==SQLITE_OK ){
4735 sqlite3_bind_int(pSql, 1, bGroupByParent);
4738 if( rc==SQLITE_OK ){
4739 int rc2;
4740 char *zPrev = 0;
4741 while( SQLITE_ROW==sqlite3_step(pSql) ){
4742 int res = -1;
4743 sqlite3_stmt *pExplain = 0;
4744 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4745 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4746 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4747 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4748 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4749 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4751 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4752 if( rc!=SQLITE_OK ) break;
4753 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4754 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4755 res = (
4756 0==sqlite3_strglob(zGlob, zPlan)
4757 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4760 rc = sqlite3_finalize(pExplain);
4761 if( rc!=SQLITE_OK ) break;
4763 if( res<0 ){
4764 raw_printf(stderr, "Error: internal error");
4765 break;
4766 }else{
4767 if( bGroupByParent
4768 && (bVerbose || res==0)
4769 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4771 raw_printf(out, "-- Parent table %s\n", zParent);
4772 sqlite3_free(zPrev);
4773 zPrev = sqlite3_mprintf("%s", zParent);
4776 if( res==0 ){
4777 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4778 }else if( bVerbose ){
4779 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4780 zIndent, zFrom, zTarget
4785 sqlite3_free(zPrev);
4787 if( rc!=SQLITE_OK ){
4788 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4791 rc2 = sqlite3_finalize(pSql);
4792 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4793 rc = rc2;
4794 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4796 }else{
4797 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4800 return rc;
4804 ** Implementation of ".lint" dot command.
4806 static int lintDotCommand(
4807 ShellState *pState, /* Current shell tool state */
4808 char **azArg, /* Array of arguments passed to dot command */
4809 int nArg /* Number of entries in azArg[] */
4811 int n;
4812 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
4813 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4814 return lintFkeyIndexes(pState, azArg, nArg);
4816 usage:
4817 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4818 raw_printf(stderr, "Where sub-commands are:\n");
4819 raw_printf(stderr, " fkey-indexes\n");
4820 return SQLITE_ERROR;
4823 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4824 /*********************************************************************************
4825 ** The ".archive" or ".ar" command.
4827 static void shellPrepare(
4828 sqlite3 *db,
4829 int *pRc,
4830 const char *zSql,
4831 sqlite3_stmt **ppStmt
4833 *ppStmt = 0;
4834 if( *pRc==SQLITE_OK ){
4835 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
4836 if( rc!=SQLITE_OK ){
4837 raw_printf(stderr, "sql error: %s (%d)\n",
4838 sqlite3_errmsg(db), sqlite3_errcode(db)
4840 *pRc = rc;
4845 static void shellPreparePrintf(
4846 sqlite3 *db,
4847 int *pRc,
4848 sqlite3_stmt **ppStmt,
4849 const char *zFmt,
4852 *ppStmt = 0;
4853 if( *pRc==SQLITE_OK ){
4854 va_list ap;
4855 char *z;
4856 va_start(ap, zFmt);
4857 z = sqlite3_vmprintf(zFmt, ap);
4858 if( z==0 ){
4859 *pRc = SQLITE_NOMEM;
4860 }else{
4861 shellPrepare(db, pRc, z, ppStmt);
4862 sqlite3_free(z);
4867 static void shellFinalize(
4868 int *pRc,
4869 sqlite3_stmt *pStmt
4871 if( pStmt ){
4872 sqlite3 *db = sqlite3_db_handle(pStmt);
4873 int rc = sqlite3_finalize(pStmt);
4874 if( *pRc==SQLITE_OK ){
4875 if( rc!=SQLITE_OK ){
4876 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4878 *pRc = rc;
4883 static void shellReset(
4884 int *pRc,
4885 sqlite3_stmt *pStmt
4887 int rc = sqlite3_reset(pStmt);
4888 if( *pRc==SQLITE_OK ){
4889 if( rc!=SQLITE_OK ){
4890 sqlite3 *db = sqlite3_db_handle(pStmt);
4891 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4893 *pRc = rc;
4897 ** Structure representing a single ".ar" command.
4899 typedef struct ArCommand ArCommand;
4900 struct ArCommand {
4901 u8 eCmd; /* An AR_CMD_* value */
4902 u8 bVerbose; /* True if --verbose */
4903 u8 bZip; /* True if the archive is a ZIP */
4904 u8 bDryRun; /* True if --dry-run */
4905 u8 bAppend; /* True if --append */
4906 u8 fromCmdLine; /* Run from -A instead of .archive */
4907 int nArg; /* Number of command arguments */
4908 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
4909 const char *zFile; /* --file argument, or NULL */
4910 const char *zDir; /* --directory argument, or NULL */
4911 char **azArg; /* Array of command arguments */
4912 ShellState *p; /* Shell state */
4913 sqlite3 *db; /* Database containing the archive */
4917 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4919 static int arUsage(FILE *f){
4920 raw_printf(f,
4921 "\n"
4922 "Usage: .ar [OPTION...] [FILE...]\n"
4923 "The .ar command manages sqlar archives.\n"
4924 "\n"
4925 "Examples:\n"
4926 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4927 " .ar -tf archive.sar # List members of archive.sar\n"
4928 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4929 "\n"
4930 "Each command line must feature exactly one command option:\n"
4931 " -c, --create Create a new archive\n"
4932 " -u, --update Update or add files to an existing archive\n"
4933 " -t, --list List contents of archive\n"
4934 " -x, --extract Extract files from archive\n"
4935 "\n"
4936 "And zero or more optional options:\n"
4937 " -v, --verbose Print each filename as it is processed\n"
4938 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4939 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
4940 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4941 " -n, --dryrun Show the SQL that would have occurred\n"
4942 "\n"
4943 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4944 "\n"
4946 return SQLITE_ERROR;
4950 ** Print an error message for the .ar command to stderr and return
4951 ** SQLITE_ERROR.
4953 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
4954 va_list ap;
4955 char *z;
4956 va_start(ap, zFmt);
4957 z = sqlite3_vmprintf(zFmt, ap);
4958 va_end(ap);
4959 utf8_printf(stderr, "Error: %s\n", z);
4960 if( pAr->fromCmdLine ){
4961 utf8_printf(stderr, "Use \"-A\" for more help\n");
4962 }else{
4963 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
4965 sqlite3_free(z);
4966 return SQLITE_ERROR;
4970 ** Values for ArCommand.eCmd.
4972 #define AR_CMD_CREATE 1
4973 #define AR_CMD_EXTRACT 2
4974 #define AR_CMD_LIST 3
4975 #define AR_CMD_UPDATE 4
4976 #define AR_CMD_HELP 5
4979 ** Other (non-command) switches.
4981 #define AR_SWITCH_VERBOSE 6
4982 #define AR_SWITCH_FILE 7
4983 #define AR_SWITCH_DIRECTORY 8
4984 #define AR_SWITCH_APPEND 9
4985 #define AR_SWITCH_DRYRUN 10
4987 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4988 switch( eSwitch ){
4989 case AR_CMD_CREATE:
4990 case AR_CMD_EXTRACT:
4991 case AR_CMD_LIST:
4992 case AR_CMD_UPDATE:
4993 case AR_CMD_HELP:
4994 if( pAr->eCmd ){
4995 return arErrorMsg(pAr, "multiple command options");
4997 pAr->eCmd = eSwitch;
4998 break;
5000 case AR_SWITCH_DRYRUN:
5001 pAr->bDryRun = 1;
5002 break;
5003 case AR_SWITCH_VERBOSE:
5004 pAr->bVerbose = 1;
5005 break;
5006 case AR_SWITCH_APPEND:
5007 pAr->bAppend = 1;
5008 /* Fall thru into --file */
5009 case AR_SWITCH_FILE:
5010 pAr->zFile = zArg;
5011 break;
5012 case AR_SWITCH_DIRECTORY:
5013 pAr->zDir = zArg;
5014 break;
5017 return SQLITE_OK;
5021 ** Parse the command line for an ".ar" command. The results are written into
5022 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5023 ** successfully, otherwise an error message is written to stderr and
5024 ** SQLITE_ERROR returned.
5026 static int arParseCommand(
5027 char **azArg, /* Array of arguments passed to dot command */
5028 int nArg, /* Number of entries in azArg[] */
5029 ArCommand *pAr /* Populate this object */
5031 struct ArSwitch {
5032 const char *zLong;
5033 char cShort;
5034 u8 eSwitch;
5035 u8 bArg;
5036 } aSwitch[] = {
5037 { "create", 'c', AR_CMD_CREATE, 0 },
5038 { "extract", 'x', AR_CMD_EXTRACT, 0 },
5039 { "list", 't', AR_CMD_LIST, 0 },
5040 { "update", 'u', AR_CMD_UPDATE, 0 },
5041 { "help", 'h', AR_CMD_HELP, 0 },
5042 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5043 { "file", 'f', AR_SWITCH_FILE, 1 },
5044 { "append", 'a', AR_SWITCH_APPEND, 1 },
5045 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
5046 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
5048 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5049 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5051 if( nArg<=1 ){
5052 return arUsage(stderr);
5053 }else{
5054 char *z = azArg[1];
5055 if( z[0]!='-' ){
5056 /* Traditional style [tar] invocation */
5057 int i;
5058 int iArg = 2;
5059 for(i=0; z[i]; i++){
5060 const char *zArg = 0;
5061 struct ArSwitch *pOpt;
5062 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5063 if( z[i]==pOpt->cShort ) break;
5065 if( pOpt==pEnd ){
5066 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5068 if( pOpt->bArg ){
5069 if( iArg>=nArg ){
5070 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5072 zArg = azArg[iArg++];
5074 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5076 pAr->nArg = nArg-iArg;
5077 if( pAr->nArg>0 ){
5078 pAr->azArg = &azArg[iArg];
5080 }else{
5081 /* Non-traditional invocation */
5082 int iArg;
5083 for(iArg=1; iArg<nArg; iArg++){
5084 int n;
5085 z = azArg[iArg];
5086 if( z[0]!='-' ){
5087 /* All remaining command line words are command arguments. */
5088 pAr->azArg = &azArg[iArg];
5089 pAr->nArg = nArg-iArg;
5090 break;
5092 n = strlen30(z);
5094 if( z[1]!='-' ){
5095 int i;
5096 /* One or more short options */
5097 for(i=1; i<n; i++){
5098 const char *zArg = 0;
5099 struct ArSwitch *pOpt;
5100 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5101 if( z[i]==pOpt->cShort ) break;
5103 if( pOpt==pEnd ){
5104 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5106 if( pOpt->bArg ){
5107 if( i<(n-1) ){
5108 zArg = &z[i+1];
5109 i = n;
5110 }else{
5111 if( iArg>=(nArg-1) ){
5112 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5114 zArg = azArg[++iArg];
5117 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5119 }else if( z[2]=='\0' ){
5120 /* A -- option, indicating that all remaining command line words
5121 ** are command arguments. */
5122 pAr->azArg = &azArg[iArg+1];
5123 pAr->nArg = nArg-iArg-1;
5124 break;
5125 }else{
5126 /* A long option */
5127 const char *zArg = 0; /* Argument for option, if any */
5128 struct ArSwitch *pMatch = 0; /* Matching option */
5129 struct ArSwitch *pOpt; /* Iterator */
5130 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5131 const char *zLong = pOpt->zLong;
5132 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
5133 if( pMatch ){
5134 return arErrorMsg(pAr, "ambiguous option: %s",z);
5135 }else{
5136 pMatch = pOpt;
5141 if( pMatch==0 ){
5142 return arErrorMsg(pAr, "unrecognized option: %s", z);
5144 if( pMatch->bArg ){
5145 if( iArg>=(nArg-1) ){
5146 return arErrorMsg(pAr, "option requires an argument: %s", z);
5148 zArg = azArg[++iArg];
5150 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5156 return SQLITE_OK;
5160 ** This function assumes that all arguments within the ArCommand.azArg[]
5161 ** array refer to archive members, as for the --extract or --list commands.
5162 ** It checks that each of them are present. If any specified file is not
5163 ** present in the archive, an error is printed to stderr and an error
5164 ** code returned. Otherwise, if all specified arguments are present in
5165 ** the archive, SQLITE_OK is returned.
5167 ** This function strips any trailing '/' characters from each argument.
5168 ** This is consistent with the way the [tar] command seems to work on
5169 ** Linux.
5171 static int arCheckEntries(ArCommand *pAr){
5172 int rc = SQLITE_OK;
5173 if( pAr->nArg ){
5174 int i, j;
5175 sqlite3_stmt *pTest = 0;
5177 shellPreparePrintf(pAr->db, &rc, &pTest,
5178 "SELECT name FROM %s WHERE name=$name",
5179 pAr->zSrcTable
5181 j = sqlite3_bind_parameter_index(pTest, "$name");
5182 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5183 char *z = pAr->azArg[i];
5184 int n = strlen30(z);
5185 int bOk = 0;
5186 while( n>0 && z[n-1]=='/' ) n--;
5187 z[n] = '\0';
5188 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
5189 if( SQLITE_ROW==sqlite3_step(pTest) ){
5190 bOk = 1;
5192 shellReset(&rc, pTest);
5193 if( rc==SQLITE_OK && bOk==0 ){
5194 utf8_printf(stderr, "not found in archive: %s\n", z);
5195 rc = SQLITE_ERROR;
5198 shellFinalize(&rc, pTest);
5200 return rc;
5204 ** Format a WHERE clause that can be used against the "sqlar" table to
5205 ** identify all archive members that match the command arguments held
5206 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5207 ** The caller is responsible for eventually calling sqlite3_free() on
5208 ** any non-NULL (*pzWhere) value.
5210 static void arWhereClause(
5211 int *pRc,
5212 ArCommand *pAr,
5213 char **pzWhere /* OUT: New WHERE clause */
5215 char *zWhere = 0;
5216 if( *pRc==SQLITE_OK ){
5217 if( pAr->nArg==0 ){
5218 zWhere = sqlite3_mprintf("1");
5219 }else{
5220 int i;
5221 const char *zSep = "";
5222 for(i=0; i<pAr->nArg; i++){
5223 const char *z = pAr->azArg[i];
5224 zWhere = sqlite3_mprintf(
5225 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5226 zWhere, zSep, z, strlen30(z)+1, z
5228 if( zWhere==0 ){
5229 *pRc = SQLITE_NOMEM;
5230 break;
5232 zSep = " OR ";
5236 *pzWhere = zWhere;
5240 ** Implementation of .ar "lisT" command.
5242 static int arListCommand(ArCommand *pAr){
5243 const char *zSql = "SELECT %s FROM %s WHERE %s";
5244 const char *azCols[] = {
5245 "name",
5246 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5249 char *zWhere = 0;
5250 sqlite3_stmt *pSql = 0;
5251 int rc;
5253 rc = arCheckEntries(pAr);
5254 arWhereClause(&rc, pAr, &zWhere);
5256 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5257 pAr->zSrcTable, zWhere);
5258 if( pAr->bDryRun ){
5259 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5260 }else{
5261 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5262 if( pAr->bVerbose ){
5263 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5264 sqlite3_column_text(pSql, 0),
5265 sqlite3_column_int(pSql, 1),
5266 sqlite3_column_text(pSql, 2),
5267 sqlite3_column_text(pSql, 3)
5269 }else{
5270 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5274 shellFinalize(&rc, pSql);
5275 sqlite3_free(zWhere);
5276 return rc;
5281 ** Implementation of .ar "eXtract" command.
5283 static int arExtractCommand(ArCommand *pAr){
5284 const char *zSql1 =
5285 "SELECT "
5286 " ($dir || name),"
5287 " writefile(($dir || name), %s, mode, mtime) "
5288 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5289 " AND name NOT GLOB '*..[/\\]*'";
5291 const char *azExtraArg[] = {
5292 "sqlar_uncompress(data, sz)",
5293 "data"
5296 sqlite3_stmt *pSql = 0;
5297 int rc = SQLITE_OK;
5298 char *zDir = 0;
5299 char *zWhere = 0;
5300 int i, j;
5302 /* If arguments are specified, check that they actually exist within
5303 ** the archive before proceeding. And formulate a WHERE clause to
5304 ** match them. */
5305 rc = arCheckEntries(pAr);
5306 arWhereClause(&rc, pAr, &zWhere);
5308 if( rc==SQLITE_OK ){
5309 if( pAr->zDir ){
5310 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5311 }else{
5312 zDir = sqlite3_mprintf("");
5314 if( zDir==0 ) rc = SQLITE_NOMEM;
5317 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5318 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
5321 if( rc==SQLITE_OK ){
5322 j = sqlite3_bind_parameter_index(pSql, "$dir");
5323 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
5325 /* Run the SELECT statement twice. The first time, writefile() is called
5326 ** for all archive members that should be extracted. The second time,
5327 ** only for the directories. This is because the timestamps for
5328 ** extracted directories must be reset after they are populated (as
5329 ** populating them changes the timestamp). */
5330 for(i=0; i<2; i++){
5331 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5332 sqlite3_bind_int(pSql, j, i);
5333 if( pAr->bDryRun ){
5334 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5335 }else{
5336 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5337 if( i==0 && pAr->bVerbose ){
5338 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5342 shellReset(&rc, pSql);
5344 shellFinalize(&rc, pSql);
5347 sqlite3_free(zDir);
5348 sqlite3_free(zWhere);
5349 return rc;
5353 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5355 static int arExecSql(ArCommand *pAr, const char *zSql){
5356 int rc;
5357 if( pAr->bDryRun ){
5358 utf8_printf(pAr->p->out, "%s\n", zSql);
5359 rc = SQLITE_OK;
5360 }else{
5361 char *zErr = 0;
5362 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5363 if( zErr ){
5364 utf8_printf(stdout, "ERROR: %s\n", zErr);
5365 sqlite3_free(zErr);
5368 return rc;
5373 ** Implementation of .ar "create" and "update" commands.
5375 ** Create the "sqlar" table in the database if it does not already exist.
5376 ** Then add each file in the azFile[] array to the archive. Directories
5377 ** are added recursively. If argument bVerbose is non-zero, a message is
5378 ** printed on stdout for each file archived.
5380 ** The create command is the same as update, except that it drops
5381 ** any existing "sqlar" table before beginning.
5383 static int arCreateOrUpdateCommand(
5384 ArCommand *pAr, /* Command arguments and options */
5385 int bUpdate /* true for a --create. false for --update */
5387 const char *zCreate =
5388 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5389 " name TEXT PRIMARY KEY, -- name of the file\n"
5390 " mode INT, -- access permissions\n"
5391 " mtime INT, -- last modification time\n"
5392 " sz INT, -- original file size\n"
5393 " data BLOB -- compressed content\n"
5394 ")";
5395 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
5396 const char *zInsertFmt[2] = {
5397 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
5398 " SELECT\n"
5399 " %s,\n"
5400 " mode,\n"
5401 " mtime,\n"
5402 " CASE substr(lsmode(mode),1,1)\n"
5403 " WHEN '-' THEN length(data)\n"
5404 " WHEN 'd' THEN 0\n"
5405 " ELSE -1 END,\n"
5406 " sqlar_compress(data)\n"
5407 " FROM fsdir(%Q,%Q)\n"
5408 " WHERE lsmode(mode) NOT LIKE '?%%';",
5409 "REPLACE INTO %s(name,mode,mtime,data)\n"
5410 " SELECT\n"
5411 " %s,\n"
5412 " mode,\n"
5413 " mtime,\n"
5414 " data\n"
5415 " FROM fsdir(%Q,%Q)\n"
5416 " WHERE lsmode(mode) NOT LIKE '?%%';"
5418 int i; /* For iterating through azFile[] */
5419 int rc; /* Return code */
5420 const char *zTab = 0; /* SQL table into which to insert */
5421 char *zSql;
5422 char zTemp[50];
5424 arExecSql(pAr, "PRAGMA page_size=512");
5425 rc = arExecSql(pAr, "SAVEPOINT ar;");
5426 if( rc!=SQLITE_OK ) return rc;
5427 zTemp[0] = 0;
5428 if( pAr->bZip ){
5429 /* Initialize the zipfile virtual table, if necessary */
5430 if( pAr->zFile ){
5431 sqlite3_uint64 r;
5432 sqlite3_randomness(sizeof(r),&r);
5433 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5434 zTab = zTemp;
5435 zSql = sqlite3_mprintf(
5436 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5437 zTab, pAr->zFile
5439 rc = arExecSql(pAr, zSql);
5440 sqlite3_free(zSql);
5441 }else{
5442 zTab = "zip";
5444 }else{
5445 /* Initialize the table for an SQLAR */
5446 zTab = "sqlar";
5447 if( bUpdate==0 ){
5448 rc = arExecSql(pAr, zDrop);
5449 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5451 rc = arExecSql(pAr, zCreate);
5453 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5454 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
5455 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5456 pAr->azArg[i], pAr->zDir);
5457 rc = arExecSql(pAr, zSql2);
5458 sqlite3_free(zSql2);
5460 end_ar_transaction:
5461 if( rc!=SQLITE_OK ){
5462 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
5463 }else{
5464 rc = arExecSql(pAr, "RELEASE ar;");
5465 if( pAr->bZip && pAr->zFile ){
5466 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5467 arExecSql(pAr, zSql);
5468 sqlite3_free(zSql);
5471 return rc;
5475 ** Implementation of ".ar" dot command.
5477 static int arDotCommand(
5478 ShellState *pState, /* Current shell tool state */
5479 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
5480 char **azArg, /* Array of arguments passed to dot command */
5481 int nArg /* Number of entries in azArg[] */
5483 ArCommand cmd;
5484 int rc;
5485 memset(&cmd, 0, sizeof(cmd));
5486 cmd.fromCmdLine = fromCmdLine;
5487 rc = arParseCommand(azArg, nArg, &cmd);
5488 if( rc==SQLITE_OK ){
5489 int eDbType = SHELL_OPEN_UNSPEC;
5490 cmd.p = pState;
5491 cmd.db = pState->db;
5492 if( cmd.zFile ){
5493 eDbType = deduceDatabaseType(cmd.zFile, 1);
5494 }else{
5495 eDbType = pState->openMode;
5497 if( eDbType==SHELL_OPEN_ZIPFILE ){
5498 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5499 if( cmd.zFile==0 ){
5500 cmd.zSrcTable = sqlite3_mprintf("zip");
5501 }else{
5502 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5505 cmd.bZip = 1;
5506 }else if( cmd.zFile ){
5507 int flags;
5508 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
5509 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5510 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5511 }else{
5512 flags = SQLITE_OPEN_READONLY;
5514 cmd.db = 0;
5515 if( cmd.bDryRun ){
5516 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5517 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5519 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5520 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
5521 if( rc!=SQLITE_OK ){
5522 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5523 cmd.zFile, sqlite3_errmsg(cmd.db)
5525 goto end_ar_command;
5527 sqlite3_fileio_init(cmd.db, 0, 0);
5528 sqlite3_sqlar_init(cmd.db, 0, 0);
5529 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5530 shellPutsFunc, 0, 0);
5533 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
5534 if( cmd.eCmd!=AR_CMD_CREATE
5535 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5537 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5538 rc = SQLITE_ERROR;
5539 goto end_ar_command;
5541 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5544 switch( cmd.eCmd ){
5545 case AR_CMD_CREATE:
5546 rc = arCreateOrUpdateCommand(&cmd, 0);
5547 break;
5549 case AR_CMD_EXTRACT:
5550 rc = arExtractCommand(&cmd);
5551 break;
5553 case AR_CMD_LIST:
5554 rc = arListCommand(&cmd);
5555 break;
5557 case AR_CMD_HELP:
5558 arUsage(pState->out);
5559 break;
5561 default:
5562 assert( cmd.eCmd==AR_CMD_UPDATE );
5563 rc = arCreateOrUpdateCommand(&cmd, 1);
5564 break;
5567 end_ar_command:
5568 if( cmd.db!=pState->db ){
5569 close_db(cmd.db);
5571 sqlite3_free(cmd.zSrcTable);
5573 return rc;
5575 /* End of the ".archive" or ".ar" command logic
5576 **********************************************************************************/
5577 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5581 ** If an input line begins with "." then invoke this routine to
5582 ** process that line.
5584 ** Return 1 on error, 2 to exit, and 0 otherwise.
5586 static int do_meta_command(char *zLine, ShellState *p){
5587 int h = 1;
5588 int nArg = 0;
5589 int n, c;
5590 int rc = 0;
5591 char *azArg[50];
5593 #ifndef SQLITE_OMIT_VIRTUALTABLE
5594 if( p->expert.pExpert ){
5595 expertFinish(p, 1, 0);
5597 #endif
5599 /* Parse the input line into tokens.
5601 while( zLine[h] && nArg<ArraySize(azArg) ){
5602 while( IsSpace(zLine[h]) ){ h++; }
5603 if( zLine[h]==0 ) break;
5604 if( zLine[h]=='\'' || zLine[h]=='"' ){
5605 int delim = zLine[h++];
5606 azArg[nArg++] = &zLine[h];
5607 while( zLine[h] && zLine[h]!=delim ){
5608 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5609 h++;
5611 if( zLine[h]==delim ){
5612 zLine[h++] = 0;
5614 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5615 }else{
5616 azArg[nArg++] = &zLine[h];
5617 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5618 if( zLine[h] ) zLine[h++] = 0;
5619 resolve_backslashes(azArg[nArg-1]);
5623 /* Process the input line.
5625 if( nArg==0 ) return 0; /* no tokens, no error */
5626 n = strlen30(azArg[0]);
5627 c = azArg[0][0];
5628 clearTempFile(p);
5630 #ifndef SQLITE_OMIT_AUTHORIZATION
5631 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5632 if( nArg!=2 ){
5633 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5634 rc = 1;
5635 goto meta_command_exit;
5637 open_db(p, 0);
5638 if( booleanValue(azArg[1]) ){
5639 sqlite3_set_authorizer(p->db, shellAuth, p);
5640 }else{
5641 sqlite3_set_authorizer(p->db, 0, 0);
5643 }else
5644 #endif
5646 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5647 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
5648 open_db(p, 0);
5649 rc = arDotCommand(p, 0, azArg, nArg);
5650 }else
5651 #endif
5653 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5654 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5656 const char *zDestFile = 0;
5657 const char *zDb = 0;
5658 sqlite3 *pDest;
5659 sqlite3_backup *pBackup;
5660 int j;
5661 const char *zVfs = 0;
5662 for(j=1; j<nArg; j++){
5663 const char *z = azArg[j];
5664 if( z[0]=='-' ){
5665 if( z[1]=='-' ) z++;
5666 if( strcmp(z, "-append")==0 ){
5667 zVfs = "apndvfs";
5668 }else
5670 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5671 return 1;
5673 }else if( zDestFile==0 ){
5674 zDestFile = azArg[j];
5675 }else if( zDb==0 ){
5676 zDb = zDestFile;
5677 zDestFile = azArg[j];
5678 }else{
5679 raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
5680 return 1;
5683 if( zDestFile==0 ){
5684 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5685 return 1;
5687 if( zDb==0 ) zDb = "main";
5688 rc = sqlite3_open_v2(zDestFile, &pDest,
5689 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
5690 if( rc!=SQLITE_OK ){
5691 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5692 close_db(pDest);
5693 return 1;
5695 open_db(p, 0);
5696 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5697 if( pBackup==0 ){
5698 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5699 close_db(pDest);
5700 return 1;
5702 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5703 sqlite3_backup_finish(pBackup);
5704 if( rc==SQLITE_DONE ){
5705 rc = 0;
5706 }else{
5707 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5708 rc = 1;
5710 close_db(pDest);
5711 }else
5713 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5714 if( nArg==2 ){
5715 bail_on_error = booleanValue(azArg[1]);
5716 }else{
5717 raw_printf(stderr, "Usage: .bail on|off\n");
5718 rc = 1;
5720 }else
5722 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5723 if( nArg==2 ){
5724 if( booleanValue(azArg[1]) ){
5725 setBinaryMode(p->out, 1);
5726 }else{
5727 setTextMode(p->out, 1);
5729 }else{
5730 raw_printf(stderr, "Usage: .binary on|off\n");
5731 rc = 1;
5733 }else
5735 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5736 if( nArg==2 ){
5737 #if defined(_WIN32) || defined(WIN32)
5738 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5739 rc = !SetCurrentDirectoryW(z);
5740 sqlite3_free(z);
5741 #else
5742 rc = chdir(azArg[1]);
5743 #endif
5744 if( rc ){
5745 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5746 rc = 1;
5748 }else{
5749 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5750 rc = 1;
5752 }else
5754 /* The undocumented ".breakpoint" command causes a call to the no-op
5755 ** routine named test_breakpoint().
5757 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5758 test_breakpoint();
5759 }else
5761 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5762 if( nArg==2 ){
5763 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5764 }else{
5765 raw_printf(stderr, "Usage: .changes on|off\n");
5766 rc = 1;
5768 }else
5770 /* Cancel output redirection, if it is currently set (by .testcase)
5771 ** Then read the content of the testcase-out.txt file and compare against
5772 ** azArg[1]. If there are differences, report an error and exit.
5774 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5775 char *zRes = 0;
5776 output_reset(p);
5777 if( nArg!=2 ){
5778 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5779 rc = 2;
5780 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5781 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5782 rc = 2;
5783 }else if( testcase_glob(azArg[1],zRes)==0 ){
5784 utf8_printf(stderr,
5785 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5786 p->zTestcase, azArg[1], zRes);
5787 rc = 1;
5788 }else{
5789 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5790 p->nCheck++;
5792 sqlite3_free(zRes);
5793 }else
5795 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5796 if( nArg==2 ){
5797 tryToClone(p, azArg[1]);
5798 }else{
5799 raw_printf(stderr, "Usage: .clone FILENAME\n");
5800 rc = 1;
5802 }else
5804 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5805 ShellState data;
5806 char *zErrMsg = 0;
5807 open_db(p, 0);
5808 memcpy(&data, p, sizeof(data));
5809 data.showHeader = 0;
5810 data.cMode = data.mode = MODE_List;
5811 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5812 data.cnt = 0;
5813 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5814 callback, &data, &zErrMsg);
5815 if( zErrMsg ){
5816 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5817 sqlite3_free(zErrMsg);
5818 rc = 1;
5820 }else
5822 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
5823 static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
5824 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
5825 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
5826 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
5827 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
5828 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
5829 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
5830 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
5831 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
5833 int ii, v;
5834 open_db(p, 0);
5835 for(ii=0; ii<ArraySize(aDbConfig); ii++){
5836 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
5837 if( nArg>=3 ){
5838 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
5840 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
5841 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
5842 if( nArg>1 ) break;
5844 if( nArg>1 && ii==ArraySize(aDbConfig) ){
5845 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
5846 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
5848 }else
5850 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
5851 rc = shell_dbinfo_command(p, nArg, azArg);
5852 }else
5854 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5855 const char *zLike = 0;
5856 int i;
5857 int savedShowHeader = p->showHeader;
5858 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5859 for(i=1; i<nArg; i++){
5860 if( azArg[i][0]=='-' ){
5861 const char *z = azArg[i]+1;
5862 if( z[0]=='-' ) z++;
5863 if( strcmp(z,"preserve-rowids")==0 ){
5864 #ifdef SQLITE_OMIT_VIRTUALTABLE
5865 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5866 " with SQLITE_OMIT_VIRTUALTABLE\n");
5867 rc = 1;
5868 goto meta_command_exit;
5869 #else
5870 ShellSetFlag(p, SHFLG_PreserveRowid);
5871 #endif
5872 }else
5873 if( strcmp(z,"newlines")==0 ){
5874 ShellSetFlag(p, SHFLG_Newlines);
5875 }else
5877 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5878 rc = 1;
5879 goto meta_command_exit;
5881 }else if( zLike ){
5882 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5883 "?--newlines? ?LIKE-PATTERN?\n");
5884 rc = 1;
5885 goto meta_command_exit;
5886 }else{
5887 zLike = azArg[i];
5890 open_db(p, 0);
5891 /* When playing back a "dump", the content might appear in an order
5892 ** which causes immediate foreign key constraints to be violated.
5893 ** So disable foreign-key constraint enforcement to prevent problems. */
5894 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5895 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5896 p->writableSchema = 0;
5897 p->showHeader = 0;
5898 /* Set writable_schema=ON since doing so forces SQLite to initialize
5899 ** as much of the schema as it can even if the sqlite_master table is
5900 ** corrupt. */
5901 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5902 p->nErr = 0;
5903 if( zLike==0 ){
5904 run_schema_dump_query(p,
5905 "SELECT name, type, sql FROM sqlite_master "
5906 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5908 run_schema_dump_query(p,
5909 "SELECT name, type, sql FROM sqlite_master "
5910 "WHERE name=='sqlite_sequence'"
5912 run_table_dump_query(p,
5913 "SELECT sql FROM sqlite_master "
5914 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5916 }else{
5917 char *zSql;
5918 zSql = sqlite3_mprintf(
5919 "SELECT name, type, sql FROM sqlite_master "
5920 "WHERE tbl_name LIKE %Q AND type=='table'"
5921 " AND sql NOT NULL", zLike);
5922 run_schema_dump_query(p,zSql);
5923 sqlite3_free(zSql);
5924 zSql = sqlite3_mprintf(
5925 "SELECT sql FROM sqlite_master "
5926 "WHERE sql NOT NULL"
5927 " AND type IN ('index','trigger','view')"
5928 " AND tbl_name LIKE %Q", zLike);
5929 run_table_dump_query(p, zSql, 0);
5930 sqlite3_free(zSql);
5932 if( p->writableSchema ){
5933 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5934 p->writableSchema = 0;
5936 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5937 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5938 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5939 p->showHeader = savedShowHeader;
5940 }else
5942 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5943 if( nArg==2 ){
5944 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5945 }else{
5946 raw_printf(stderr, "Usage: .echo on|off\n");
5947 rc = 1;
5949 }else
5951 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5952 if( nArg==2 ){
5953 p->autoEQPtest = 0;
5954 if( strcmp(azArg[1],"full")==0 ){
5955 p->autoEQP = AUTOEQP_full;
5956 }else if( strcmp(azArg[1],"trigger")==0 ){
5957 p->autoEQP = AUTOEQP_trigger;
5958 }else if( strcmp(azArg[1],"test")==0 ){
5959 p->autoEQP = AUTOEQP_on;
5960 p->autoEQPtest = 1;
5961 }else{
5962 p->autoEQP = (u8)booleanValue(azArg[1]);
5964 }else{
5965 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
5966 rc = 1;
5968 }else
5970 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5971 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5972 rc = 2;
5973 }else
5975 /* The ".explain" command is automatic now. It is largely pointless. It
5976 ** retained purely for backwards compatibility */
5977 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5978 int val = 1;
5979 if( nArg>=2 ){
5980 if( strcmp(azArg[1],"auto")==0 ){
5981 val = 99;
5982 }else{
5983 val = booleanValue(azArg[1]);
5986 if( val==1 && p->mode!=MODE_Explain ){
5987 p->normalMode = p->mode;
5988 p->mode = MODE_Explain;
5989 p->autoExplain = 0;
5990 }else if( val==0 ){
5991 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5992 p->autoExplain = 0;
5993 }else if( val==99 ){
5994 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5995 p->autoExplain = 1;
5997 }else
5999 #ifndef SQLITE_OMIT_VIRTUALTABLE
6000 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6001 open_db(p, 0);
6002 expertDotCommand(p, azArg, nArg);
6003 }else
6004 #endif
6006 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6007 ShellState data;
6008 char *zErrMsg = 0;
6009 int doStats = 0;
6010 memcpy(&data, p, sizeof(data));
6011 data.showHeader = 0;
6012 data.cMode = data.mode = MODE_Semi;
6013 if( nArg==2 && optionMatch(azArg[1], "indent") ){
6014 data.cMode = data.mode = MODE_Pretty;
6015 nArg = 1;
6017 if( nArg!=1 ){
6018 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6019 rc = 1;
6020 goto meta_command_exit;
6022 open_db(p, 0);
6023 rc = sqlite3_exec(p->db,
6024 "SELECT sql FROM"
6025 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6026 " FROM sqlite_master UNION ALL"
6027 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6028 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6029 "ORDER BY rowid",
6030 callback, &data, &zErrMsg
6032 if( rc==SQLITE_OK ){
6033 sqlite3_stmt *pStmt;
6034 rc = sqlite3_prepare_v2(p->db,
6035 "SELECT rowid FROM sqlite_master"
6036 " WHERE name GLOB 'sqlite_stat[134]'",
6037 -1, &pStmt, 0);
6038 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6039 sqlite3_finalize(pStmt);
6041 if( doStats==0 ){
6042 raw_printf(p->out, "/* No STAT tables available */\n");
6043 }else{
6044 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6045 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6046 callback, &data, &zErrMsg);
6047 data.cMode = data.mode = MODE_Insert;
6048 data.zDestTable = "sqlite_stat1";
6049 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
6050 data.zDestTable = "sqlite_stat3";
6051 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
6052 data.zDestTable = "sqlite_stat4";
6053 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
6054 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6056 }else
6058 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6059 if( nArg==2 ){
6060 p->showHeader = booleanValue(azArg[1]);
6061 }else{
6062 raw_printf(stderr, "Usage: .headers on|off\n");
6063 rc = 1;
6065 }else
6067 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
6068 utf8_printf(p->out, "%s", zHelp);
6069 }else
6071 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6072 char *zTable; /* Insert data into this table */
6073 char *zFile; /* Name of file to extra content from */
6074 sqlite3_stmt *pStmt = NULL; /* A statement */
6075 int nCol; /* Number of columns in the table */
6076 int nByte; /* Number of bytes in an SQL string */
6077 int i, j; /* Loop counters */
6078 int needCommit; /* True to COMMIT or ROLLBACK at end */
6079 int nSep; /* Number of bytes in p->colSeparator[] */
6080 char *zSql; /* An SQL statement */
6081 ImportCtx sCtx; /* Reader context */
6082 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6083 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
6085 if( nArg!=3 ){
6086 raw_printf(stderr, "Usage: .import FILE TABLE\n");
6087 goto meta_command_exit;
6089 zFile = azArg[1];
6090 zTable = azArg[2];
6091 seenInterrupt = 0;
6092 memset(&sCtx, 0, sizeof(sCtx));
6093 open_db(p, 0);
6094 nSep = strlen30(p->colSeparator);
6095 if( nSep==0 ){
6096 raw_printf(stderr,
6097 "Error: non-null column separator required for import\n");
6098 return 1;
6100 if( nSep>1 ){
6101 raw_printf(stderr, "Error: multi-character column separators not allowed"
6102 " for import\n");
6103 return 1;
6105 nSep = strlen30(p->rowSeparator);
6106 if( nSep==0 ){
6107 raw_printf(stderr, "Error: non-null row separator required for import\n");
6108 return 1;
6110 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6111 /* When importing CSV (only), if the row separator is set to the
6112 ** default output row separator, change it to the default input
6113 ** row separator. This avoids having to maintain different input
6114 ** and output row separators. */
6115 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6116 nSep = strlen30(p->rowSeparator);
6118 if( nSep>1 ){
6119 raw_printf(stderr, "Error: multi-character row separators not allowed"
6120 " for import\n");
6121 return 1;
6123 sCtx.zFile = zFile;
6124 sCtx.nLine = 1;
6125 if( sCtx.zFile[0]=='|' ){
6126 #ifdef SQLITE_OMIT_POPEN
6127 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6128 return 1;
6129 #else
6130 sCtx.in = popen(sCtx.zFile+1, "r");
6131 sCtx.zFile = "<pipe>";
6132 xCloser = pclose;
6133 #endif
6134 }else{
6135 sCtx.in = fopen(sCtx.zFile, "rb");
6136 xCloser = fclose;
6138 if( p->mode==MODE_Ascii ){
6139 xRead = ascii_read_one_field;
6140 }else{
6141 xRead = csv_read_one_field;
6143 if( sCtx.in==0 ){
6144 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6145 return 1;
6147 sCtx.cColSep = p->colSeparator[0];
6148 sCtx.cRowSep = p->rowSeparator[0];
6149 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6150 if( zSql==0 ){
6151 xCloser(sCtx.in);
6152 shell_out_of_memory();
6154 nByte = strlen30(zSql);
6155 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6156 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
6157 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6158 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6159 char cSep = '(';
6160 while( xRead(&sCtx) ){
6161 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6162 cSep = ',';
6163 if( sCtx.cTerm!=sCtx.cColSep ) break;
6165 if( cSep=='(' ){
6166 sqlite3_free(zCreate);
6167 sqlite3_free(sCtx.z);
6168 xCloser(sCtx.in);
6169 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6170 return 1;
6172 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6173 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6174 sqlite3_free(zCreate);
6175 if( rc ){
6176 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6177 sqlite3_errmsg(p->db));
6178 sqlite3_free(sCtx.z);
6179 xCloser(sCtx.in);
6180 return 1;
6182 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6184 sqlite3_free(zSql);
6185 if( rc ){
6186 if (pStmt) sqlite3_finalize(pStmt);
6187 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6188 xCloser(sCtx.in);
6189 return 1;
6191 nCol = sqlite3_column_count(pStmt);
6192 sqlite3_finalize(pStmt);
6193 pStmt = 0;
6194 if( nCol==0 ) return 0; /* no columns, no error */
6195 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6196 if( zSql==0 ){
6197 xCloser(sCtx.in);
6198 shell_out_of_memory();
6200 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6201 j = strlen30(zSql);
6202 for(i=1; i<nCol; i++){
6203 zSql[j++] = ',';
6204 zSql[j++] = '?';
6206 zSql[j++] = ')';
6207 zSql[j] = 0;
6208 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6209 sqlite3_free(zSql);
6210 if( rc ){
6211 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6212 if (pStmt) sqlite3_finalize(pStmt);
6213 xCloser(sCtx.in);
6214 return 1;
6216 needCommit = sqlite3_get_autocommit(p->db);
6217 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6219 int startLine = sCtx.nLine;
6220 for(i=0; i<nCol; i++){
6221 char *z = xRead(&sCtx);
6223 ** Did we reach end-of-file before finding any columns?
6224 ** If so, stop instead of NULL filling the remaining columns.
6226 if( z==0 && i==0 ) break;
6228 ** Did we reach end-of-file OR end-of-line before finding any
6229 ** columns in ASCII mode? If so, stop instead of NULL filling
6230 ** the remaining columns.
6232 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6233 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6234 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6235 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6236 "filling the rest with NULL\n",
6237 sCtx.zFile, startLine, nCol, i+1);
6238 i += 2;
6239 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6242 if( sCtx.cTerm==sCtx.cColSep ){
6244 xRead(&sCtx);
6245 i++;
6246 }while( sCtx.cTerm==sCtx.cColSep );
6247 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6248 "extras ignored\n",
6249 sCtx.zFile, startLine, nCol, i);
6251 if( i>=nCol ){
6252 sqlite3_step(pStmt);
6253 rc = sqlite3_reset(pStmt);
6254 if( rc!=SQLITE_OK ){
6255 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6256 startLine, sqlite3_errmsg(p->db));
6259 }while( sCtx.cTerm!=EOF );
6261 xCloser(sCtx.in);
6262 sqlite3_free(sCtx.z);
6263 sqlite3_finalize(pStmt);
6264 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6265 }else
6267 #ifndef SQLITE_UNTESTABLE
6268 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6269 char *zSql;
6270 char *zCollist = 0;
6271 sqlite3_stmt *pStmt;
6272 int tnum = 0;
6273 int i;
6274 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6275 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6276 " .imposter off\n");
6277 rc = 1;
6278 goto meta_command_exit;
6280 open_db(p, 0);
6281 if( nArg==2 ){
6282 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6283 goto meta_command_exit;
6285 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6286 " WHERE name='%q' AND type='index'", azArg[1]);
6287 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6288 sqlite3_free(zSql);
6289 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6290 tnum = sqlite3_column_int(pStmt, 0);
6292 sqlite3_finalize(pStmt);
6293 if( tnum==0 ){
6294 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6295 rc = 1;
6296 goto meta_command_exit;
6298 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6299 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6300 sqlite3_free(zSql);
6301 i = 0;
6302 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6303 char zLabel[20];
6304 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6305 i++;
6306 if( zCol==0 ){
6307 if( sqlite3_column_int(pStmt,1)==-1 ){
6308 zCol = "_ROWID_";
6309 }else{
6310 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6311 zCol = zLabel;
6314 if( zCollist==0 ){
6315 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6316 }else{
6317 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6320 sqlite3_finalize(pStmt);
6321 zSql = sqlite3_mprintf(
6322 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6323 azArg[2], zCollist, zCollist);
6324 sqlite3_free(zCollist);
6325 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6326 if( rc==SQLITE_OK ){
6327 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6328 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6329 if( rc ){
6330 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6331 }else{
6332 utf8_printf(stdout, "%s;\n", zSql);
6333 raw_printf(stdout,
6334 "WARNING: writing to an imposter table will corrupt the index!\n"
6337 }else{
6338 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6339 rc = 1;
6341 sqlite3_free(zSql);
6342 }else
6343 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6345 #ifdef SQLITE_ENABLE_IOTRACE
6346 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6347 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6348 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6349 iotrace = 0;
6350 if( nArg<2 ){
6351 sqlite3IoTrace = 0;
6352 }else if( strcmp(azArg[1], "-")==0 ){
6353 sqlite3IoTrace = iotracePrintf;
6354 iotrace = stdout;
6355 }else{
6356 iotrace = fopen(azArg[1], "w");
6357 if( iotrace==0 ){
6358 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6359 sqlite3IoTrace = 0;
6360 rc = 1;
6361 }else{
6362 sqlite3IoTrace = iotracePrintf;
6365 }else
6366 #endif
6368 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6369 static const struct {
6370 const char *zLimitName; /* Name of a limit */
6371 int limitCode; /* Integer code for that limit */
6372 } aLimit[] = {
6373 { "length", SQLITE_LIMIT_LENGTH },
6374 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6375 { "column", SQLITE_LIMIT_COLUMN },
6376 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6377 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6378 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6379 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6380 { "attached", SQLITE_LIMIT_ATTACHED },
6381 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6382 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6383 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6384 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6386 int i, n2;
6387 open_db(p, 0);
6388 if( nArg==1 ){
6389 for(i=0; i<ArraySize(aLimit); i++){
6390 printf("%20s %d\n", aLimit[i].zLimitName,
6391 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6393 }else if( nArg>3 ){
6394 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6395 rc = 1;
6396 goto meta_command_exit;
6397 }else{
6398 int iLimit = -1;
6399 n2 = strlen30(azArg[1]);
6400 for(i=0; i<ArraySize(aLimit); i++){
6401 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6402 if( iLimit<0 ){
6403 iLimit = i;
6404 }else{
6405 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6406 rc = 1;
6407 goto meta_command_exit;
6411 if( iLimit<0 ){
6412 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6413 "enter \".limits\" with no arguments for a list.\n",
6414 azArg[1]);
6415 rc = 1;
6416 goto meta_command_exit;
6418 if( nArg==3 ){
6419 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6420 (int)integerValue(azArg[2]));
6422 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6423 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6425 }else
6427 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6428 open_db(p, 0);
6429 lintDotCommand(p, azArg, nArg);
6430 }else
6432 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6433 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6434 const char *zFile, *zProc;
6435 char *zErrMsg = 0;
6436 if( nArg<2 ){
6437 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6438 rc = 1;
6439 goto meta_command_exit;
6441 zFile = azArg[1];
6442 zProc = nArg>=3 ? azArg[2] : 0;
6443 open_db(p, 0);
6444 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6445 if( rc!=SQLITE_OK ){
6446 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6447 sqlite3_free(zErrMsg);
6448 rc = 1;
6450 }else
6451 #endif
6453 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6454 if( nArg!=2 ){
6455 raw_printf(stderr, "Usage: .log FILENAME\n");
6456 rc = 1;
6457 }else{
6458 const char *zFile = azArg[1];
6459 output_file_close(p->pLog);
6460 p->pLog = output_file_open(zFile, 0);
6462 }else
6464 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6465 const char *zMode = nArg>=2 ? azArg[1] : "";
6466 int n2 = strlen30(zMode);
6467 int c2 = zMode[0];
6468 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6469 p->mode = MODE_Line;
6470 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6471 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6472 p->mode = MODE_Column;
6473 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6474 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6475 p->mode = MODE_List;
6476 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6477 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6478 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6479 p->mode = MODE_Html;
6480 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6481 p->mode = MODE_Tcl;
6482 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6483 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6484 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6485 p->mode = MODE_Csv;
6486 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6487 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6488 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6489 p->mode = MODE_List;
6490 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6491 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6492 p->mode = MODE_Insert;
6493 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6494 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6495 p->mode = MODE_Quote;
6496 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6497 p->mode = MODE_Ascii;
6498 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6499 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6500 }else if( nArg==1 ){
6501 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6502 }else{
6503 raw_printf(stderr, "Error: mode should be one of: "
6504 "ascii column csv html insert line list quote tabs tcl\n");
6505 rc = 1;
6507 p->cMode = p->mode;
6508 }else
6510 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6511 if( nArg==2 ){
6512 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6513 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6514 }else{
6515 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6516 rc = 1;
6518 }else
6520 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6521 char *zNewFilename; /* Name of the database file to open */
6522 int iName = 1; /* Index in azArg[] of the filename */
6523 int newFlag = 0; /* True to delete file before opening */
6524 /* Close the existing database */
6525 session_close_all(p);
6526 close_db(p->db);
6527 p->db = 0;
6528 p->zDbFilename = 0;
6529 sqlite3_free(p->zFreeOnClose);
6530 p->zFreeOnClose = 0;
6531 p->openMode = SHELL_OPEN_UNSPEC;
6532 /* Check for command-line arguments */
6533 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6534 const char *z = azArg[iName];
6535 if( optionMatch(z,"new") ){
6536 newFlag = 1;
6537 #ifdef SQLITE_HAVE_ZLIB
6538 }else if( optionMatch(z, "zip") ){
6539 p->openMode = SHELL_OPEN_ZIPFILE;
6540 #endif
6541 }else if( optionMatch(z, "append") ){
6542 p->openMode = SHELL_OPEN_APPENDVFS;
6543 }else if( optionMatch(z, "readonly") ){
6544 p->openMode = SHELL_OPEN_READONLY;
6545 }else if( z[0]=='-' ){
6546 utf8_printf(stderr, "unknown option: %s\n", z);
6547 rc = 1;
6548 goto meta_command_exit;
6551 /* If a filename is specified, try to open it first */
6552 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6553 if( zNewFilename ){
6554 if( newFlag ) shellDeleteFile(zNewFilename);
6555 p->zDbFilename = zNewFilename;
6556 open_db(p, OPEN_DB_KEEPALIVE);
6557 if( p->db==0 ){
6558 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6559 sqlite3_free(zNewFilename);
6560 }else{
6561 p->zFreeOnClose = zNewFilename;
6564 if( p->db==0 ){
6565 /* As a fall-back open a TEMP database */
6566 p->zDbFilename = 0;
6567 open_db(p, 0);
6569 }else
6571 if( (c=='o'
6572 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
6573 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
6575 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6576 int bTxtMode = 0;
6577 if( azArg[0][0]=='e' ){
6578 /* Transform the ".excel" command into ".once -x" */
6579 nArg = 2;
6580 azArg[0] = "once";
6581 zFile = azArg[1] = "-x";
6582 n = 4;
6584 if( nArg>2 ){
6585 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
6586 rc = 1;
6587 goto meta_command_exit;
6589 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6590 if( nArg<2 ){
6591 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
6592 rc = 1;
6593 goto meta_command_exit;
6595 p->outCount = 2;
6596 }else{
6597 p->outCount = 0;
6599 output_reset(p);
6600 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
6601 #ifndef SQLITE_NOHAVE_SYSTEM
6602 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
6603 p->doXdgOpen = 1;
6604 outputModePush(p);
6605 if( zFile[1]=='x' ){
6606 newTempFile(p, "csv");
6607 p->mode = MODE_Csv;
6608 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6609 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6610 }else{
6611 newTempFile(p, "txt");
6612 bTxtMode = 1;
6614 zFile = p->zTempFile;
6616 #endif /* SQLITE_NOHAVE_SYSTEM */
6617 if( zFile[0]=='|' ){
6618 #ifdef SQLITE_OMIT_POPEN
6619 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6620 rc = 1;
6621 p->out = stdout;
6622 #else
6623 p->out = popen(zFile + 1, "w");
6624 if( p->out==0 ){
6625 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6626 p->out = stdout;
6627 rc = 1;
6628 }else{
6629 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6631 #endif
6632 }else{
6633 p->out = output_file_open(zFile, bTxtMode);
6634 if( p->out==0 ){
6635 if( strcmp(zFile,"off")!=0 ){
6636 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6638 p->out = stdout;
6639 rc = 1;
6640 } else {
6641 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6644 }else
6646 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6647 int i;
6648 for(i=1; i<nArg; i++){
6649 if( i>1 ) raw_printf(p->out, " ");
6650 utf8_printf(p->out, "%s", azArg[i]);
6652 raw_printf(p->out, "\n");
6653 }else
6655 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6656 if( nArg >= 2) {
6657 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6659 if( nArg >= 3) {
6660 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6662 }else
6664 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6665 rc = 2;
6666 }else
6668 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6669 FILE *alt;
6670 if( nArg!=2 ){
6671 raw_printf(stderr, "Usage: .read FILE\n");
6672 rc = 1;
6673 goto meta_command_exit;
6675 alt = fopen(azArg[1], "rb");
6676 if( alt==0 ){
6677 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6678 rc = 1;
6679 }else{
6680 rc = process_input(p, alt);
6681 fclose(alt);
6683 }else
6685 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6686 const char *zSrcFile;
6687 const char *zDb;
6688 sqlite3 *pSrc;
6689 sqlite3_backup *pBackup;
6690 int nTimeout = 0;
6692 if( nArg==2 ){
6693 zSrcFile = azArg[1];
6694 zDb = "main";
6695 }else if( nArg==3 ){
6696 zSrcFile = azArg[2];
6697 zDb = azArg[1];
6698 }else{
6699 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6700 rc = 1;
6701 goto meta_command_exit;
6703 rc = sqlite3_open(zSrcFile, &pSrc);
6704 if( rc!=SQLITE_OK ){
6705 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6706 close_db(pSrc);
6707 return 1;
6709 open_db(p, 0);
6710 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6711 if( pBackup==0 ){
6712 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6713 close_db(pSrc);
6714 return 1;
6716 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6717 || rc==SQLITE_BUSY ){
6718 if( rc==SQLITE_BUSY ){
6719 if( nTimeout++ >= 3 ) break;
6720 sqlite3_sleep(100);
6723 sqlite3_backup_finish(pBackup);
6724 if( rc==SQLITE_DONE ){
6725 rc = 0;
6726 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6727 raw_printf(stderr, "Error: source database is busy\n");
6728 rc = 1;
6729 }else{
6730 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6731 rc = 1;
6733 close_db(pSrc);
6734 }else
6736 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6737 if( nArg==2 ){
6738 p->scanstatsOn = (u8)booleanValue(azArg[1]);
6739 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6740 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6741 #endif
6742 }else{
6743 raw_printf(stderr, "Usage: .scanstats on|off\n");
6744 rc = 1;
6746 }else
6748 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6749 ShellText sSelect;
6750 ShellState data;
6751 char *zErrMsg = 0;
6752 const char *zDiv = "(";
6753 const char *zName = 0;
6754 int iSchema = 0;
6755 int bDebug = 0;
6756 int ii;
6758 open_db(p, 0);
6759 memcpy(&data, p, sizeof(data));
6760 data.showHeader = 0;
6761 data.cMode = data.mode = MODE_Semi;
6762 initText(&sSelect);
6763 for(ii=1; ii<nArg; ii++){
6764 if( optionMatch(azArg[ii],"indent") ){
6765 data.cMode = data.mode = MODE_Pretty;
6766 }else if( optionMatch(azArg[ii],"debug") ){
6767 bDebug = 1;
6768 }else if( zName==0 ){
6769 zName = azArg[ii];
6770 }else{
6771 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6772 rc = 1;
6773 goto meta_command_exit;
6776 if( zName!=0 ){
6777 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
6778 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
6779 char *new_argv[2], *new_colv[2];
6780 new_argv[0] = sqlite3_mprintf(
6781 "CREATE TABLE %s (\n"
6782 " type text,\n"
6783 " name text,\n"
6784 " tbl_name text,\n"
6785 " rootpage integer,\n"
6786 " sql text\n"
6787 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
6788 new_argv[1] = 0;
6789 new_colv[0] = "sql";
6790 new_colv[1] = 0;
6791 callback(&data, 1, new_argv, new_colv);
6792 sqlite3_free(new_argv[0]);
6795 if( zDiv ){
6796 sqlite3_stmt *pStmt = 0;
6797 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6798 -1, &pStmt, 0);
6799 if( rc ){
6800 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6801 sqlite3_finalize(pStmt);
6802 rc = 1;
6803 goto meta_command_exit;
6805 appendText(&sSelect, "SELECT sql FROM", 0);
6806 iSchema = 0;
6807 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6808 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6809 char zScNum[30];
6810 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6811 appendText(&sSelect, zDiv, 0);
6812 zDiv = " UNION ALL ";
6813 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6814 if( sqlite3_stricmp(zDb, "main")!=0 ){
6815 appendText(&sSelect, zDb, '"');
6816 }else{
6817 appendText(&sSelect, "NULL", 0);
6819 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6820 appendText(&sSelect, zScNum, 0);
6821 appendText(&sSelect, " AS snum, ", 0);
6822 appendText(&sSelect, zDb, '\'');
6823 appendText(&sSelect, " AS sname FROM ", 0);
6824 appendText(&sSelect, zDb, '"');
6825 appendText(&sSelect, ".sqlite_master", 0);
6827 sqlite3_finalize(pStmt);
6828 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6829 if( zName ){
6830 appendText(&sSelect,
6831 " UNION ALL SELECT shell_module_schema(name),"
6832 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6834 #endif
6835 appendText(&sSelect, ") WHERE ", 0);
6836 if( zName ){
6837 char *zQarg = sqlite3_mprintf("%Q", zName);
6838 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
6839 strchr(zName, '[') != 0;
6840 if( strchr(zName, '.') ){
6841 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6842 }else{
6843 appendText(&sSelect, "lower(tbl_name)", 0);
6845 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
6846 appendText(&sSelect, zQarg, 0);
6847 if( !bGlob ){
6848 appendText(&sSelect, " ESCAPE '\\' ", 0);
6850 appendText(&sSelect, " AND ", 0);
6851 sqlite3_free(zQarg);
6853 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6854 " ORDER BY snum, rowid", 0);
6855 if( bDebug ){
6856 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6857 }else{
6858 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6860 freeText(&sSelect);
6862 if( zErrMsg ){
6863 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6864 sqlite3_free(zErrMsg);
6865 rc = 1;
6866 }else if( rc != SQLITE_OK ){
6867 raw_printf(stderr,"Error: querying schema information\n");
6868 rc = 1;
6869 }else{
6870 rc = 0;
6872 }else
6874 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6875 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6876 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6877 }else
6878 #endif
6880 #if defined(SQLITE_ENABLE_SESSION)
6881 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6882 OpenSession *pSession = &p->aSession[0];
6883 char **azCmd = &azArg[1];
6884 int iSes = 0;
6885 int nCmd = nArg - 1;
6886 int i;
6887 if( nArg<=1 ) goto session_syntax_error;
6888 open_db(p, 0);
6889 if( nArg>=3 ){
6890 for(iSes=0; iSes<p->nSession; iSes++){
6891 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6893 if( iSes<p->nSession ){
6894 pSession = &p->aSession[iSes];
6895 azCmd++;
6896 nCmd--;
6897 }else{
6898 pSession = &p->aSession[0];
6899 iSes = 0;
6903 /* .session attach TABLE
6904 ** Invoke the sqlite3session_attach() interface to attach a particular
6905 ** table so that it is never filtered.
6907 if( strcmp(azCmd[0],"attach")==0 ){
6908 if( nCmd!=2 ) goto session_syntax_error;
6909 if( pSession->p==0 ){
6910 session_not_open:
6911 raw_printf(stderr, "ERROR: No sessions are open\n");
6912 }else{
6913 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6914 if( rc ){
6915 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6916 rc = 0;
6919 }else
6921 /* .session changeset FILE
6922 ** .session patchset FILE
6923 ** Write a changeset or patchset into a file. The file is overwritten.
6925 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6926 FILE *out = 0;
6927 if( nCmd!=2 ) goto session_syntax_error;
6928 if( pSession->p==0 ) goto session_not_open;
6929 out = fopen(azCmd[1], "wb");
6930 if( out==0 ){
6931 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6932 }else{
6933 int szChng;
6934 void *pChng;
6935 if( azCmd[0][0]=='c' ){
6936 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6937 }else{
6938 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6940 if( rc ){
6941 printf("Error: error code %d\n", rc);
6942 rc = 0;
6944 if( pChng
6945 && fwrite(pChng, szChng, 1, out)!=1 ){
6946 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6947 szChng);
6949 sqlite3_free(pChng);
6950 fclose(out);
6952 }else
6954 /* .session close
6955 ** Close the identified session
6957 if( strcmp(azCmd[0], "close")==0 ){
6958 if( nCmd!=1 ) goto session_syntax_error;
6959 if( p->nSession ){
6960 session_close(pSession);
6961 p->aSession[iSes] = p->aSession[--p->nSession];
6963 }else
6965 /* .session enable ?BOOLEAN?
6966 ** Query or set the enable flag
6968 if( strcmp(azCmd[0], "enable")==0 ){
6969 int ii;
6970 if( nCmd>2 ) goto session_syntax_error;
6971 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6972 if( p->nSession ){
6973 ii = sqlite3session_enable(pSession->p, ii);
6974 utf8_printf(p->out, "session %s enable flag = %d\n",
6975 pSession->zName, ii);
6977 }else
6979 /* .session filter GLOB ....
6980 ** Set a list of GLOB patterns of table names to be excluded.
6982 if( strcmp(azCmd[0], "filter")==0 ){
6983 int ii, nByte;
6984 if( nCmd<2 ) goto session_syntax_error;
6985 if( p->nSession ){
6986 for(ii=0; ii<pSession->nFilter; ii++){
6987 sqlite3_free(pSession->azFilter[ii]);
6989 sqlite3_free(pSession->azFilter);
6990 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6991 pSession->azFilter = sqlite3_malloc( nByte );
6992 if( pSession->azFilter==0 ){
6993 raw_printf(stderr, "Error: out or memory\n");
6994 exit(1);
6996 for(ii=1; ii<nCmd; ii++){
6997 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6999 pSession->nFilter = ii-1;
7001 }else
7003 /* .session indirect ?BOOLEAN?
7004 ** Query or set the indirect flag
7006 if( strcmp(azCmd[0], "indirect")==0 ){
7007 int ii;
7008 if( nCmd>2 ) goto session_syntax_error;
7009 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7010 if( p->nSession ){
7011 ii = sqlite3session_indirect(pSession->p, ii);
7012 utf8_printf(p->out, "session %s indirect flag = %d\n",
7013 pSession->zName, ii);
7015 }else
7017 /* .session isempty
7018 ** Determine if the session is empty
7020 if( strcmp(azCmd[0], "isempty")==0 ){
7021 int ii;
7022 if( nCmd!=1 ) goto session_syntax_error;
7023 if( p->nSession ){
7024 ii = sqlite3session_isempty(pSession->p);
7025 utf8_printf(p->out, "session %s isempty flag = %d\n",
7026 pSession->zName, ii);
7028 }else
7030 /* .session list
7031 ** List all currently open sessions
7033 if( strcmp(azCmd[0],"list")==0 ){
7034 for(i=0; i<p->nSession; i++){
7035 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7037 }else
7039 /* .session open DB NAME
7040 ** Open a new session called NAME on the attached database DB.
7041 ** DB is normally "main".
7043 if( strcmp(azCmd[0],"open")==0 ){
7044 char *zName;
7045 if( nCmd!=3 ) goto session_syntax_error;
7046 zName = azCmd[2];
7047 if( zName[0]==0 ) goto session_syntax_error;
7048 for(i=0; i<p->nSession; i++){
7049 if( strcmp(p->aSession[i].zName,zName)==0 ){
7050 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7051 goto meta_command_exit;
7054 if( p->nSession>=ArraySize(p->aSession) ){
7055 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7056 goto meta_command_exit;
7058 pSession = &p->aSession[p->nSession];
7059 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7060 if( rc ){
7061 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7062 rc = 0;
7063 goto meta_command_exit;
7065 pSession->nFilter = 0;
7066 sqlite3session_table_filter(pSession->p, session_filter, pSession);
7067 p->nSession++;
7068 pSession->zName = sqlite3_mprintf("%s", zName);
7069 }else
7070 /* If no command name matches, show a syntax error */
7071 session_syntax_error:
7072 session_help(p);
7073 }else
7074 #endif
7076 #ifdef SQLITE_DEBUG
7077 /* Undocumented commands for internal testing. Subject to change
7078 ** without notice. */
7079 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7080 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7081 int i, v;
7082 for(i=1; i<nArg; i++){
7083 v = booleanValue(azArg[i]);
7084 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7087 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7088 int i; sqlite3_int64 v;
7089 for(i=1; i<nArg; i++){
7090 char zBuf[200];
7091 v = integerValue(azArg[i]);
7092 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7093 utf8_printf(p->out, "%s", zBuf);
7096 }else
7097 #endif
7099 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7100 int bIsInit = 0; /* True to initialize the SELFTEST table */
7101 int bVerbose = 0; /* Verbose output */
7102 int bSelftestExists; /* True if SELFTEST already exists */
7103 int i, k; /* Loop counters */
7104 int nTest = 0; /* Number of tests runs */
7105 int nErr = 0; /* Number of errors seen */
7106 ShellText str; /* Answer for a query */
7107 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7109 open_db(p,0);
7110 for(i=1; i<nArg; i++){
7111 const char *z = azArg[i];
7112 if( z[0]=='-' && z[1]=='-' ) z++;
7113 if( strcmp(z,"-init")==0 ){
7114 bIsInit = 1;
7115 }else
7116 if( strcmp(z,"-v")==0 ){
7117 bVerbose++;
7118 }else
7120 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7121 azArg[i], azArg[0]);
7122 raw_printf(stderr, "Should be one of: --init -v\n");
7123 rc = 1;
7124 goto meta_command_exit;
7127 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7128 != SQLITE_OK ){
7129 bSelftestExists = 0;
7130 }else{
7131 bSelftestExists = 1;
7133 if( bIsInit ){
7134 createSelftestTable(p);
7135 bSelftestExists = 1;
7137 initText(&str);
7138 appendText(&str, "x", 0);
7139 for(k=bSelftestExists; k>=0; k--){
7140 if( k==1 ){
7141 rc = sqlite3_prepare_v2(p->db,
7142 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7143 -1, &pStmt, 0);
7144 }else{
7145 rc = sqlite3_prepare_v2(p->db,
7146 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7147 " (1,'run','PRAGMA integrity_check','ok')",
7148 -1, &pStmt, 0);
7150 if( rc ){
7151 raw_printf(stderr, "Error querying the selftest table\n");
7152 rc = 1;
7153 sqlite3_finalize(pStmt);
7154 goto meta_command_exit;
7156 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7157 int tno = sqlite3_column_int(pStmt, 0);
7158 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7159 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7160 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7162 k = 0;
7163 if( bVerbose>0 ){
7164 char *zQuote = sqlite3_mprintf("%q", zSql);
7165 printf("%d: %s %s\n", tno, zOp, zSql);
7166 sqlite3_free(zQuote);
7168 if( strcmp(zOp,"memo")==0 ){
7169 utf8_printf(p->out, "%s\n", zSql);
7170 }else
7171 if( strcmp(zOp,"run")==0 ){
7172 char *zErrMsg = 0;
7173 str.n = 0;
7174 str.z[0] = 0;
7175 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7176 nTest++;
7177 if( bVerbose ){
7178 utf8_printf(p->out, "Result: %s\n", str.z);
7180 if( rc || zErrMsg ){
7181 nErr++;
7182 rc = 1;
7183 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7184 sqlite3_free(zErrMsg);
7185 }else if( strcmp(zAns,str.z)!=0 ){
7186 nErr++;
7187 rc = 1;
7188 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7189 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7191 }else
7193 utf8_printf(stderr,
7194 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7195 rc = 1;
7196 break;
7198 } /* End loop over rows of content from SELFTEST */
7199 sqlite3_finalize(pStmt);
7200 } /* End loop over k */
7201 freeText(&str);
7202 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7203 }else
7205 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7206 if( nArg<2 || nArg>3 ){
7207 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7208 rc = 1;
7210 if( nArg>=2 ){
7211 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7212 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7214 if( nArg>=3 ){
7215 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7216 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7218 }else
7220 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7221 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7222 int i; /* Loop counter */
7223 int bSchema = 0; /* Also hash the schema */
7224 int bSeparate = 0; /* Hash each table separately */
7225 int iSize = 224; /* Hash algorithm to use */
7226 int bDebug = 0; /* Only show the query that would have run */
7227 sqlite3_stmt *pStmt; /* For querying tables names */
7228 char *zSql; /* SQL to be run */
7229 char *zSep; /* Separator */
7230 ShellText sSql; /* Complete SQL for the query to run the hash */
7231 ShellText sQuery; /* Set of queries used to read all content */
7232 open_db(p, 0);
7233 for(i=1; i<nArg; i++){
7234 const char *z = azArg[i];
7235 if( z[0]=='-' ){
7236 z++;
7237 if( z[0]=='-' ) z++;
7238 if( strcmp(z,"schema")==0 ){
7239 bSchema = 1;
7240 }else
7241 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7242 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7244 iSize = atoi(&z[5]);
7245 }else
7246 if( strcmp(z,"debug")==0 ){
7247 bDebug = 1;
7248 }else
7250 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7251 azArg[i], azArg[0]);
7252 raw_printf(stderr, "Should be one of: --schema"
7253 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
7254 rc = 1;
7255 goto meta_command_exit;
7257 }else if( zLike ){
7258 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7259 rc = 1;
7260 goto meta_command_exit;
7261 }else{
7262 zLike = z;
7263 bSeparate = 1;
7264 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
7267 if( bSchema ){
7268 zSql = "SELECT lower(name) FROM sqlite_master"
7269 " WHERE type='table' AND coalesce(rootpage,0)>1"
7270 " UNION ALL SELECT 'sqlite_master'"
7271 " ORDER BY 1 collate nocase";
7272 }else{
7273 zSql = "SELECT lower(name) FROM sqlite_master"
7274 " WHERE type='table' AND coalesce(rootpage,0)>1"
7275 " AND name NOT LIKE 'sqlite_%'"
7276 " ORDER BY 1 collate nocase";
7278 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7279 initText(&sQuery);
7280 initText(&sSql);
7281 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7282 zSep = "VALUES(";
7283 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7284 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7285 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7286 if( strncmp(zTab, "sqlite_",7)!=0 ){
7287 appendText(&sQuery,"SELECT * FROM ", 0);
7288 appendText(&sQuery,zTab,'"');
7289 appendText(&sQuery," NOT INDEXED;", 0);
7290 }else if( strcmp(zTab, "sqlite_master")==0 ){
7291 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7292 " ORDER BY name;", 0);
7293 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7294 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7295 " ORDER BY name;", 0);
7296 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7297 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7298 " ORDER BY tbl,idx;", 0);
7299 }else if( strcmp(zTab, "sqlite_stat3")==0
7300 || strcmp(zTab, "sqlite_stat4")==0 ){
7301 appendText(&sQuery, "SELECT * FROM ", 0);
7302 appendText(&sQuery, zTab, 0);
7303 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7305 appendText(&sSql, zSep, 0);
7306 appendText(&sSql, sQuery.z, '\'');
7307 sQuery.n = 0;
7308 appendText(&sSql, ",", 0);
7309 appendText(&sSql, zTab, '\'');
7310 zSep = "),(";
7312 sqlite3_finalize(pStmt);
7313 if( bSeparate ){
7314 zSql = sqlite3_mprintf(
7315 "%s))"
7316 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7317 " FROM [sha3sum$query]",
7318 sSql.z, iSize);
7319 }else{
7320 zSql = sqlite3_mprintf(
7321 "%s))"
7322 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7323 " FROM [sha3sum$query]",
7324 sSql.z, iSize);
7326 freeText(&sQuery);
7327 freeText(&sSql);
7328 if( bDebug ){
7329 utf8_printf(p->out, "%s\n", zSql);
7330 }else{
7331 shell_exec(p, zSql, 0);
7333 sqlite3_free(zSql);
7334 }else
7336 #ifndef SQLITE_NOHAVE_SYSTEM
7337 if( c=='s'
7338 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7340 char *zCmd;
7341 int i, x;
7342 if( nArg<2 ){
7343 raw_printf(stderr, "Usage: .system COMMAND\n");
7344 rc = 1;
7345 goto meta_command_exit;
7347 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7348 for(i=2; i<nArg; i++){
7349 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7350 zCmd, azArg[i]);
7352 x = system(zCmd);
7353 sqlite3_free(zCmd);
7354 if( x ) raw_printf(stderr, "System command returns %d\n", x);
7355 }else
7356 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
7358 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
7359 static const char *azBool[] = { "off", "on", "trigger", "full"};
7360 int i;
7361 if( nArg!=1 ){
7362 raw_printf(stderr, "Usage: .show\n");
7363 rc = 1;
7364 goto meta_command_exit;
7366 utf8_printf(p->out, "%12.12s: %s\n","echo",
7367 azBool[ShellHasFlag(p, SHFLG_Echo)]);
7368 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7369 utf8_printf(p->out, "%12.12s: %s\n","explain",
7370 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7371 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7372 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7373 utf8_printf(p->out, "%12.12s: ", "nullvalue");
7374 output_c_string(p->out, p->nullValue);
7375 raw_printf(p->out, "\n");
7376 utf8_printf(p->out,"%12.12s: %s\n","output",
7377 strlen30(p->outfile) ? p->outfile : "stdout");
7378 utf8_printf(p->out,"%12.12s: ", "colseparator");
7379 output_c_string(p->out, p->colSeparator);
7380 raw_printf(p->out, "\n");
7381 utf8_printf(p->out,"%12.12s: ", "rowseparator");
7382 output_c_string(p->out, p->rowSeparator);
7383 raw_printf(p->out, "\n");
7384 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7385 utf8_printf(p->out, "%12.12s: ", "width");
7386 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
7387 raw_printf(p->out, "%d ", p->colWidth[i]);
7389 raw_printf(p->out, "\n");
7390 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7391 p->zDbFilename ? p->zDbFilename : "");
7392 }else
7394 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7395 if( nArg==2 ){
7396 p->statsOn = (u8)booleanValue(azArg[1]);
7397 }else if( nArg==1 ){
7398 display_stats(p->db, p, 0);
7399 }else{
7400 raw_printf(stderr, "Usage: .stats ?on|off?\n");
7401 rc = 1;
7403 }else
7405 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7406 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7407 || strncmp(azArg[0], "indexes", n)==0) )
7409 sqlite3_stmt *pStmt;
7410 char **azResult;
7411 int nRow, nAlloc;
7412 int ii;
7413 ShellText s;
7414 initText(&s);
7415 open_db(p, 0);
7416 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7417 if( rc ){
7418 sqlite3_finalize(pStmt);
7419 return shellDatabaseError(p->db);
7422 if( nArg>2 && c=='i' ){
7423 /* It is an historical accident that the .indexes command shows an error
7424 ** when called with the wrong number of arguments whereas the .tables
7425 ** command does not. */
7426 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7427 rc = 1;
7428 sqlite3_finalize(pStmt);
7429 goto meta_command_exit;
7431 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
7432 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
7433 if( zDbName==0 ) continue;
7434 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7435 if( sqlite3_stricmp(zDbName, "main")==0 ){
7436 appendText(&s, "SELECT name FROM ", 0);
7437 }else{
7438 appendText(&s, "SELECT ", 0);
7439 appendText(&s, zDbName, '\'');
7440 appendText(&s, "||'.'||name FROM ", 0);
7442 appendText(&s, zDbName, '"');
7443 appendText(&s, ".sqlite_master ", 0);
7444 if( c=='t' ){
7445 appendText(&s," WHERE type IN ('table','view')"
7446 " AND name NOT LIKE 'sqlite_%'"
7447 " AND name LIKE ?1", 0);
7448 }else{
7449 appendText(&s," WHERE type='index'"
7450 " AND tbl_name LIKE ?1", 0);
7453 rc = sqlite3_finalize(pStmt);
7454 appendText(&s, " ORDER BY 1", 0);
7455 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7456 freeText(&s);
7457 if( rc ) return shellDatabaseError(p->db);
7459 /* Run the SQL statement prepared by the above block. Store the results
7460 ** as an array of nul-terminated strings in azResult[]. */
7461 nRow = nAlloc = 0;
7462 azResult = 0;
7463 if( nArg>1 ){
7464 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
7465 }else{
7466 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7468 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7469 if( nRow>=nAlloc ){
7470 char **azNew;
7471 int n2 = nAlloc*2 + 10;
7472 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
7473 if( azNew==0 ) shell_out_of_memory();
7474 nAlloc = n2;
7475 azResult = azNew;
7477 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7478 if( 0==azResult[nRow] ) shell_out_of_memory();
7479 nRow++;
7481 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7482 rc = shellDatabaseError(p->db);
7485 /* Pretty-print the contents of array azResult[] to the output */
7486 if( rc==0 && nRow>0 ){
7487 int len, maxlen = 0;
7488 int i, j;
7489 int nPrintCol, nPrintRow;
7490 for(i=0; i<nRow; i++){
7491 len = strlen30(azResult[i]);
7492 if( len>maxlen ) maxlen = len;
7494 nPrintCol = 80/(maxlen+2);
7495 if( nPrintCol<1 ) nPrintCol = 1;
7496 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7497 for(i=0; i<nPrintRow; i++){
7498 for(j=i; j<nRow; j+=nPrintRow){
7499 char *zSp = j<nPrintRow ? "" : " ";
7500 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7501 azResult[j] ? azResult[j]:"");
7503 raw_printf(p->out, "\n");
7507 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7508 sqlite3_free(azResult);
7509 }else
7511 /* Begin redirecting output to the file "testcase-out.txt" */
7512 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7513 output_reset(p);
7514 p->out = output_file_open("testcase-out.txt", 0);
7515 if( p->out==0 ){
7516 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7518 if( nArg>=2 ){
7519 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7520 }else{
7521 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7523 }else
7525 #ifndef SQLITE_UNTESTABLE
7526 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
7527 static const struct {
7528 const char *zCtrlName; /* Name of a test-control option */
7529 int ctrlCode; /* Integer code for that option */
7530 const char *zUsage; /* Usage notes */
7531 } aCtrl[] = {
7532 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7533 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7534 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7535 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7536 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7537 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7538 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
7539 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7540 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7541 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
7542 #ifdef YYCOVERAGE
7543 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7544 #endif
7545 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7546 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7547 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7548 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7549 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
7551 int testctrl = -1;
7552 int iCtrl = -1;
7553 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7554 int isOk = 0;
7555 int i, n2;
7556 const char *zCmd = 0;
7558 open_db(p, 0);
7559 zCmd = nArg>=2 ? azArg[1] : "help";
7561 /* The argument can optionally begin with "-" or "--" */
7562 if( zCmd[0]=='-' && zCmd[1] ){
7563 zCmd++;
7564 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7567 /* --help lists all test-controls */
7568 if( strcmp(zCmd,"help")==0 ){
7569 utf8_printf(p->out, "Available test-controls:\n");
7570 for(i=0; i<ArraySize(aCtrl); i++){
7571 utf8_printf(p->out, " .testctrl %s %s\n",
7572 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7574 rc = 1;
7575 goto meta_command_exit;
7578 /* convert testctrl text option to value. allow any unique prefix
7579 ** of the option name, or a numerical value. */
7580 n2 = strlen30(zCmd);
7581 for(i=0; i<ArraySize(aCtrl); i++){
7582 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7583 if( testctrl<0 ){
7584 testctrl = aCtrl[i].ctrlCode;
7585 iCtrl = i;
7586 }else{
7587 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7588 "Use \".testctrl --help\" for help\n", zCmd);
7589 rc = 1;
7590 goto meta_command_exit;
7594 if( testctrl<0 ){
7595 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7596 "Use \".testctrl --help\" for help\n", zCmd);
7597 }else{
7598 switch(testctrl){
7600 /* sqlite3_test_control(int, db, int) */
7601 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7602 case SQLITE_TESTCTRL_RESERVE:
7603 if( nArg==3 ){
7604 int opt = (int)strtol(azArg[2], 0, 0);
7605 rc2 = sqlite3_test_control(testctrl, p->db, opt);
7606 isOk = 3;
7608 break;
7610 /* sqlite3_test_control(int) */
7611 case SQLITE_TESTCTRL_PRNG_SAVE:
7612 case SQLITE_TESTCTRL_PRNG_RESTORE:
7613 case SQLITE_TESTCTRL_PRNG_RESET:
7614 case SQLITE_TESTCTRL_BYTEORDER:
7615 if( nArg==2 ){
7616 rc2 = sqlite3_test_control(testctrl);
7617 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
7619 break;
7621 /* sqlite3_test_control(int, uint) */
7622 case SQLITE_TESTCTRL_PENDING_BYTE:
7623 if( nArg==3 ){
7624 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7625 rc2 = sqlite3_test_control(testctrl, opt);
7626 isOk = 3;
7628 break;
7630 /* sqlite3_test_control(int, int) */
7631 case SQLITE_TESTCTRL_ASSERT:
7632 case SQLITE_TESTCTRL_ALWAYS:
7633 if( nArg==3 ){
7634 int opt = booleanValue(azArg[2]);
7635 rc2 = sqlite3_test_control(testctrl, opt);
7636 isOk = 1;
7638 break;
7640 /* sqlite3_test_control(int, int) */
7641 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
7642 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7643 if( nArg==3 ){
7644 int opt = booleanValue(azArg[2]);
7645 rc2 = sqlite3_test_control(testctrl, opt);
7646 isOk = 3;
7648 break;
7650 case SQLITE_TESTCTRL_IMPOSTER:
7651 if( nArg==5 ){
7652 rc2 = sqlite3_test_control(testctrl, p->db,
7653 azArg[2],
7654 integerValue(azArg[3]),
7655 integerValue(azArg[4]));
7656 isOk = 3;
7658 break;
7660 #ifdef YYCOVERAGE
7661 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7662 if( nArg==2 ){
7663 sqlite3_test_control(testctrl, p->out);
7664 isOk = 3;
7666 #endif
7669 if( isOk==0 && iCtrl>=0 ){
7670 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7671 rc = 1;
7672 }else if( isOk==1 ){
7673 raw_printf(p->out, "%d\n", rc2);
7674 }else if( isOk==2 ){
7675 raw_printf(p->out, "0x%08x\n", rc2);
7677 }else
7678 #endif /* !defined(SQLITE_UNTESTABLE) */
7680 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7681 open_db(p, 0);
7682 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7683 }else
7685 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7686 if( nArg==2 ){
7687 enableTimer = booleanValue(azArg[1]);
7688 if( enableTimer && !HAS_TIMER ){
7689 raw_printf(stderr, "Error: timer not available on this system.\n");
7690 enableTimer = 0;
7692 }else{
7693 raw_printf(stderr, "Usage: .timer on|off\n");
7694 rc = 1;
7696 }else
7698 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7699 open_db(p, 0);
7700 if( nArg!=2 ){
7701 raw_printf(stderr, "Usage: .trace FILE|off\n");
7702 rc = 1;
7703 goto meta_command_exit;
7705 output_file_close(p->traceOut);
7706 p->traceOut = output_file_open(azArg[1], 0);
7707 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7708 if( p->traceOut==0 ){
7709 sqlite3_trace_v2(p->db, 0, 0, 0);
7710 }else{
7711 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7713 #endif
7714 }else
7716 #if SQLITE_USER_AUTHENTICATION
7717 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7718 if( nArg<2 ){
7719 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7720 rc = 1;
7721 goto meta_command_exit;
7723 open_db(p, 0);
7724 if( strcmp(azArg[1],"login")==0 ){
7725 if( nArg!=4 ){
7726 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7727 rc = 1;
7728 goto meta_command_exit;
7730 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
7731 if( rc ){
7732 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7733 rc = 1;
7735 }else if( strcmp(azArg[1],"add")==0 ){
7736 if( nArg!=5 ){
7737 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7738 rc = 1;
7739 goto meta_command_exit;
7741 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
7742 booleanValue(azArg[4]));
7743 if( rc ){
7744 raw_printf(stderr, "User-Add failed: %d\n", rc);
7745 rc = 1;
7747 }else if( strcmp(azArg[1],"edit")==0 ){
7748 if( nArg!=5 ){
7749 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7750 rc = 1;
7751 goto meta_command_exit;
7753 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
7754 booleanValue(azArg[4]));
7755 if( rc ){
7756 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7757 rc = 1;
7759 }else if( strcmp(azArg[1],"delete")==0 ){
7760 if( nArg!=3 ){
7761 raw_printf(stderr, "Usage: .user delete USER\n");
7762 rc = 1;
7763 goto meta_command_exit;
7765 rc = sqlite3_user_delete(p->db, azArg[2]);
7766 if( rc ){
7767 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7768 rc = 1;
7770 }else{
7771 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7772 rc = 1;
7773 goto meta_command_exit;
7775 }else
7776 #endif /* SQLITE_USER_AUTHENTICATION */
7778 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7779 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7780 sqlite3_libversion(), sqlite3_sourceid());
7781 #if SQLITE_HAVE_ZLIB
7782 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
7783 #endif
7784 #define CTIMEOPT_VAL_(opt) #opt
7785 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7786 #if defined(__clang__) && defined(__clang_major__)
7787 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
7788 CTIMEOPT_VAL(__clang_minor__) "."
7789 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
7790 #elif defined(_MSC_VER)
7791 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
7792 #elif defined(__GNUC__) && defined(__VERSION__)
7793 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
7794 #endif
7795 }else
7797 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7798 const char *zDbName = nArg==2 ? azArg[1] : "main";
7799 sqlite3_vfs *pVfs = 0;
7800 if( p->db ){
7801 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7802 if( pVfs ){
7803 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7804 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7805 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7806 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7809 }else
7811 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7812 sqlite3_vfs *pVfs;
7813 sqlite3_vfs *pCurrent = 0;
7814 if( p->db ){
7815 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7817 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7818 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7819 pVfs==pCurrent ? " <--- CURRENT" : "");
7820 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7821 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7822 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7823 if( pVfs->pNext ){
7824 raw_printf(p->out, "-----------------------------------\n");
7827 }else
7829 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7830 const char *zDbName = nArg==2 ? azArg[1] : "main";
7831 char *zVfsName = 0;
7832 if( p->db ){
7833 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7834 if( zVfsName ){
7835 utf8_printf(p->out, "%s\n", zVfsName);
7836 sqlite3_free(zVfsName);
7839 }else
7841 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7842 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7843 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7844 }else
7845 #endif
7847 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7848 int j;
7849 assert( nArg<=ArraySize(azArg) );
7850 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7851 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7853 }else
7856 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7857 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7858 rc = 1;
7861 meta_command_exit:
7862 if( p->outCount ){
7863 p->outCount--;
7864 if( p->outCount==0 ) output_reset(p);
7866 return rc;
7870 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7871 ** of string z[].
7873 static int line_contains_semicolon(const char *z, int N){
7874 int i;
7875 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7876 return 0;
7880 ** Test to see if a line consists entirely of whitespace.
7882 static int _all_whitespace(const char *z){
7883 for(; *z; z++){
7884 if( IsSpace(z[0]) ) continue;
7885 if( *z=='/' && z[1]=='*' ){
7886 z += 2;
7887 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7888 if( *z==0 ) return 0;
7889 z++;
7890 continue;
7892 if( *z=='-' && z[1]=='-' ){
7893 z += 2;
7894 while( *z && *z!='\n' ){ z++; }
7895 if( *z==0 ) return 1;
7896 continue;
7898 return 0;
7900 return 1;
7904 ** Return TRUE if the line typed in is an SQL command terminator other
7905 ** than a semi-colon. The SQL Server style "go" command is understood
7906 ** as is the Oracle "/".
7908 static int line_is_command_terminator(const char *zLine){
7909 while( IsSpace(zLine[0]) ){ zLine++; };
7910 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7911 return 1; /* Oracle */
7913 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7914 && _all_whitespace(&zLine[2]) ){
7915 return 1; /* SQL Server */
7917 return 0;
7921 ** We need a default sqlite3_complete() implementation to use in case
7922 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
7923 ** any arbitrary text is a complete SQL statement. This is not very
7924 ** user-friendly, but it does seem to work.
7926 #ifdef SQLITE_OMIT_COMPLETE
7927 int sqlite3_complete(const char *zSql){ return 1; }
7928 #endif
7931 ** Return true if zSql is a complete SQL statement. Return false if it
7932 ** ends in the middle of a string literal or C-style comment.
7934 static int line_is_complete(char *zSql, int nSql){
7935 int rc;
7936 if( zSql==0 ) return 1;
7937 zSql[nSql] = ';';
7938 zSql[nSql+1] = 0;
7939 rc = sqlite3_complete(zSql);
7940 zSql[nSql] = 0;
7941 return rc;
7945 ** Run a single line of SQL. Return the number of errors.
7947 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7948 int rc;
7949 char *zErrMsg = 0;
7951 open_db(p, 0);
7952 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7953 BEGIN_TIMER;
7954 rc = shell_exec(p, zSql, &zErrMsg);
7955 END_TIMER;
7956 if( rc || zErrMsg ){
7957 char zPrefix[100];
7958 if( in!=0 || !stdin_is_interactive ){
7959 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7960 "Error: near line %d:", startline);
7961 }else{
7962 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7964 if( zErrMsg!=0 ){
7965 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7966 sqlite3_free(zErrMsg);
7967 zErrMsg = 0;
7968 }else{
7969 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7971 return 1;
7972 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7973 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7974 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7976 return 0;
7981 ** Read input from *in and process it. If *in==0 then input
7982 ** is interactive - the user is typing it it. Otherwise, input
7983 ** is coming from a file or device. A prompt is issued and history
7984 ** is saved only if input is interactive. An interrupt signal will
7985 ** cause this routine to exit immediately, unless input is interactive.
7987 ** Return the number of errors.
7989 static int process_input(ShellState *p, FILE *in){
7990 char *zLine = 0; /* A single input line */
7991 char *zSql = 0; /* Accumulated SQL text */
7992 int nLine; /* Length of current line */
7993 int nSql = 0; /* Bytes of zSql[] used */
7994 int nAlloc = 0; /* Allocated zSql[] space */
7995 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7996 int rc; /* Error code */
7997 int errCnt = 0; /* Number of errors seen */
7998 int lineno = 0; /* Current line number */
7999 int startline = 0; /* Line number for start of current input */
8001 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
8002 fflush(p->out);
8003 zLine = one_input_line(in, zLine, nSql>0);
8004 if( zLine==0 ){
8005 /* End of input */
8006 if( in==0 && stdin_is_interactive ) printf("\n");
8007 break;
8009 if( seenInterrupt ){
8010 if( in!=0 ) break;
8011 seenInterrupt = 0;
8013 lineno++;
8014 if( nSql==0 && _all_whitespace(zLine) ){
8015 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8016 continue;
8018 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
8019 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8020 if( zLine[0]=='.' ){
8021 rc = do_meta_command(zLine, p);
8022 if( rc==2 ){ /* exit requested */
8023 break;
8024 }else if( rc ){
8025 errCnt++;
8028 continue;
8030 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8031 memcpy(zLine,";",2);
8033 nLine = strlen30(zLine);
8034 if( nSql+nLine+2>=nAlloc ){
8035 nAlloc = nSql+nLine+100;
8036 zSql = realloc(zSql, nAlloc);
8037 if( zSql==0 ) shell_out_of_memory();
8039 nSqlPrior = nSql;
8040 if( nSql==0 ){
8041 int i;
8042 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8043 assert( nAlloc>0 && zSql!=0 );
8044 memcpy(zSql, zLine+i, nLine+1-i);
8045 startline = lineno;
8046 nSql = nLine-i;
8047 }else{
8048 zSql[nSql++] = '\n';
8049 memcpy(zSql+nSql, zLine, nLine+1);
8050 nSql += nLine;
8052 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8053 && sqlite3_complete(zSql) ){
8054 errCnt += runOneSqlLine(p, zSql, in, startline);
8055 nSql = 0;
8056 if( p->outCount ){
8057 output_reset(p);
8058 p->outCount = 0;
8059 }else{
8060 clearTempFile(p);
8062 }else if( nSql && _all_whitespace(zSql) ){
8063 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8064 nSql = 0;
8067 if( nSql && !_all_whitespace(zSql) ){
8068 errCnt += runOneSqlLine(p, zSql, in, startline);
8070 free(zSql);
8071 free(zLine);
8072 return errCnt>0;
8076 ** Return a pathname which is the user's home directory. A
8077 ** 0 return indicates an error of some kind.
8079 static char *find_home_dir(int clearFlag){
8080 static char *home_dir = NULL;
8081 if( clearFlag ){
8082 free(home_dir);
8083 home_dir = 0;
8084 return 0;
8086 if( home_dir ) return home_dir;
8088 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8089 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8091 struct passwd *pwent;
8092 uid_t uid = getuid();
8093 if( (pwent=getpwuid(uid)) != NULL) {
8094 home_dir = pwent->pw_dir;
8097 #endif
8099 #if defined(_WIN32_WCE)
8100 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8102 home_dir = "/";
8103 #else
8105 #if defined(_WIN32) || defined(WIN32)
8106 if (!home_dir) {
8107 home_dir = getenv("USERPROFILE");
8109 #endif
8111 if (!home_dir) {
8112 home_dir = getenv("HOME");
8115 #if defined(_WIN32) || defined(WIN32)
8116 if (!home_dir) {
8117 char *zDrive, *zPath;
8118 int n;
8119 zDrive = getenv("HOMEDRIVE");
8120 zPath = getenv("HOMEPATH");
8121 if( zDrive && zPath ){
8122 n = strlen30(zDrive) + strlen30(zPath) + 1;
8123 home_dir = malloc( n );
8124 if( home_dir==0 ) return 0;
8125 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8126 return home_dir;
8128 home_dir = "c:\\";
8130 #endif
8132 #endif /* !_WIN32_WCE */
8134 if( home_dir ){
8135 int n = strlen30(home_dir) + 1;
8136 char *z = malloc( n );
8137 if( z ) memcpy(z, home_dir, n);
8138 home_dir = z;
8141 return home_dir;
8145 ** Read input from the file given by sqliterc_override. Or if that
8146 ** parameter is NULL, take input from ~/.sqliterc
8148 ** Returns the number of errors.
8150 static void process_sqliterc(
8151 ShellState *p, /* Configuration data */
8152 const char *sqliterc_override /* Name of config file. NULL to use default */
8154 char *home_dir = NULL;
8155 const char *sqliterc = sqliterc_override;
8156 char *zBuf = 0;
8157 FILE *in = NULL;
8159 if (sqliterc == NULL) {
8160 home_dir = find_home_dir(0);
8161 if( home_dir==0 ){
8162 raw_printf(stderr, "-- warning: cannot find home directory;"
8163 " cannot read ~/.sqliterc\n");
8164 return;
8166 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8167 sqliterc = zBuf;
8169 in = fopen(sqliterc,"rb");
8170 if( in ){
8171 if( stdin_is_interactive ){
8172 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8174 process_input(p,in);
8175 fclose(in);
8177 sqlite3_free(zBuf);
8181 ** Show available command line options
8183 static const char zOptions[] =
8184 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
8185 " -A ARGS... run \".archive ARGS\" and exit\n"
8186 #endif
8187 " -append append the database to the end of the file\n"
8188 " -ascii set output mode to 'ascii'\n"
8189 " -bail stop after hitting an error\n"
8190 " -batch force batch I/O\n"
8191 " -column set output mode to 'column'\n"
8192 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8193 " -csv set output mode to 'csv'\n"
8194 " -echo print commands before execution\n"
8195 " -init FILENAME read/process named file\n"
8196 " -[no]header turn headers on or off\n"
8197 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8198 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8199 #endif
8200 " -help show this message\n"
8201 " -html set output mode to HTML\n"
8202 " -interactive force interactive I/O\n"
8203 " -line set output mode to 'line'\n"
8204 " -list set output mode to 'list'\n"
8205 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8206 " -mmap N default mmap size set to N\n"
8207 #ifdef SQLITE_ENABLE_MULTIPLEX
8208 " -multiplex enable the multiplexor VFS\n"
8209 #endif
8210 " -newline SEP set output row separator. Default: '\\n'\n"
8211 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8212 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8213 " -quote set output mode to 'quote'\n"
8214 " -readonly open the database read-only\n"
8215 " -separator SEP set output column separator. Default: '|'\n"
8216 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8217 " -sorterref SIZE sorter references threshold size\n"
8218 #endif
8219 " -stats print memory stats before each finalize\n"
8220 " -version show SQLite version\n"
8221 " -vfs NAME use NAME as the default VFS\n"
8222 #ifdef SQLITE_ENABLE_VFSTRACE
8223 " -vfstrace enable tracing of all VFS calls\n"
8224 #endif
8225 #ifdef SQLITE_HAVE_ZLIB
8226 " -zip open the file as a ZIP Archive\n"
8227 #endif
8229 static void usage(int showDetail){
8230 utf8_printf(stderr,
8231 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8232 "FILENAME is the name of an SQLite database. A new database is created\n"
8233 "if the file does not previously exist.\n", Argv0);
8234 if( showDetail ){
8235 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8236 }else{
8237 raw_printf(stderr, "Use the -help option for additional information\n");
8239 exit(1);
8243 ** Internal check: Verify that the SQLite is uninitialized. Print a
8244 ** error message if it is initialized.
8246 static void verify_uninitialized(void){
8247 if( sqlite3_config(-1)==SQLITE_MISUSE ){
8248 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
8249 " initialization.\n");
8254 ** Initialize the state information in data
8256 static void main_init(ShellState *data) {
8257 memset(data, 0, sizeof(*data));
8258 data->normalMode = data->cMode = data->mode = MODE_List;
8259 data->autoExplain = 1;
8260 memcpy(data->colSeparator,SEP_Column, 2);
8261 memcpy(data->rowSeparator,SEP_Row, 2);
8262 data->showHeader = 0;
8263 data->shellFlgs = SHFLG_Lookaside;
8264 verify_uninitialized();
8265 sqlite3_config(SQLITE_CONFIG_URI, 1);
8266 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8267 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8268 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8269 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8273 ** Output text to the console in a font that attracts extra attention.
8275 #ifdef _WIN32
8276 static void printBold(const char *zText){
8277 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8278 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8279 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8280 SetConsoleTextAttribute(out,
8281 FOREGROUND_RED|FOREGROUND_INTENSITY
8283 printf("%s", zText);
8284 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8286 #else
8287 static void printBold(const char *zText){
8288 printf("\033[1m%s\033[0m", zText);
8290 #endif
8293 ** Get the argument to an --option. Throw an error and die if no argument
8294 ** is available.
8296 static char *cmdline_option_value(int argc, char **argv, int i){
8297 if( i==argc ){
8298 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8299 argv[0], argv[argc-1]);
8300 exit(1);
8302 return argv[i];
8305 #ifndef SQLITE_SHELL_IS_UTF8
8306 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8307 # define SQLITE_SHELL_IS_UTF8 (0)
8308 # else
8309 # define SQLITE_SHELL_IS_UTF8 (1)
8310 # endif
8311 #endif
8313 #if SQLITE_SHELL_IS_UTF8
8314 int SQLITE_CDECL main(int argc, char **argv){
8315 #else
8316 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8317 char **argv;
8318 #endif
8319 char *zErrMsg = 0;
8320 ShellState data;
8321 const char *zInitFile = 0;
8322 int i;
8323 int rc = 0;
8324 int warnInmemoryDb = 0;
8325 int readStdin = 1;
8326 int nCmd = 0;
8327 char **azCmd = 0;
8328 const char *zVfs = 0; /* Value of -vfs command-line option */
8329 #if !SQLITE_SHELL_IS_UTF8
8330 char **argvToFree = 0;
8331 int argcToFree = 0;
8332 #endif
8334 setBinaryMode(stdin, 0);
8335 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8336 stdin_is_interactive = isatty(0);
8337 stdout_is_console = isatty(1);
8339 #if USE_SYSTEM_SQLITE+0!=1
8340 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
8341 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
8342 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8343 exit(1);
8345 #endif
8346 main_init(&data);
8348 /* On Windows, we must translate command-line arguments into UTF-8.
8349 ** The SQLite memory allocator subsystem has to be enabled in order to
8350 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8351 ** subsequent sqlite3_config() calls will work. So copy all results into
8352 ** memory that does not come from the SQLite memory allocator.
8354 #if !SQLITE_SHELL_IS_UTF8
8355 sqlite3_initialize();
8356 argvToFree = malloc(sizeof(argv[0])*argc*2);
8357 argcToFree = argc;
8358 argv = argvToFree + argc;
8359 if( argv==0 ) shell_out_of_memory();
8360 for(i=0; i<argc; i++){
8361 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
8362 int n;
8363 if( z==0 ) shell_out_of_memory();
8364 n = (int)strlen(z);
8365 argv[i] = malloc( n+1 );
8366 if( argv[i]==0 ) shell_out_of_memory();
8367 memcpy(argv[i], z, n+1);
8368 argvToFree[i] = argv[i];
8369 sqlite3_free(z);
8371 sqlite3_shutdown();
8372 #endif
8374 assert( argc>=1 && argv && argv[0] );
8375 Argv0 = argv[0];
8377 /* Make sure we have a valid signal handler early, before anything
8378 ** else is done.
8380 #ifdef SIGINT
8381 signal(SIGINT, interrupt_handler);
8382 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8383 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
8384 #endif
8386 #ifdef SQLITE_SHELL_DBNAME_PROC
8388 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8389 ** of a C-function that will provide the name of the database file. Use
8390 ** this compile-time option to embed this shell program in larger
8391 ** applications. */
8392 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8393 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8394 warnInmemoryDb = 0;
8396 #endif
8398 /* Do an initial pass through the command-line argument to locate
8399 ** the name of the database file, the name of the initialization file,
8400 ** the size of the alternative malloc heap,
8401 ** and the first command to execute.
8403 verify_uninitialized();
8404 for(i=1; i<argc; i++){
8405 char *z;
8406 z = argv[i];
8407 if( z[0]!='-' ){
8408 if( data.zDbFilename==0 ){
8409 data.zDbFilename = z;
8410 }else{
8411 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8412 ** mean that nothing is read from stdin */
8413 readStdin = 0;
8414 nCmd++;
8415 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
8416 if( azCmd==0 ) shell_out_of_memory();
8417 azCmd[nCmd-1] = z;
8420 if( z[1]=='-' ) z++;
8421 if( strcmp(z,"-separator")==0
8422 || strcmp(z,"-nullvalue")==0
8423 || strcmp(z,"-newline")==0
8424 || strcmp(z,"-cmd")==0
8426 (void)cmdline_option_value(argc, argv, ++i);
8427 }else if( strcmp(z,"-init")==0 ){
8428 zInitFile = cmdline_option_value(argc, argv, ++i);
8429 }else if( strcmp(z,"-batch")==0 ){
8430 /* Need to check for batch mode here to so we can avoid printing
8431 ** informational messages (like from process_sqliterc) before
8432 ** we do the actual processing of arguments later in a second pass.
8434 stdin_is_interactive = 0;
8435 }else if( strcmp(z,"-heap")==0 ){
8436 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8437 const char *zSize;
8438 sqlite3_int64 szHeap;
8440 zSize = cmdline_option_value(argc, argv, ++i);
8441 szHeap = integerValue(zSize);
8442 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
8443 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
8444 #else
8445 (void)cmdline_option_value(argc, argv, ++i);
8446 #endif
8447 }else if( strcmp(z,"-pagecache")==0 ){
8448 int n, sz;
8449 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8450 if( sz>70000 ) sz = 70000;
8451 if( sz<0 ) sz = 0;
8452 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8453 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8454 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
8455 data.shellFlgs |= SHFLG_Pagecache;
8456 }else if( strcmp(z,"-lookaside")==0 ){
8457 int n, sz;
8458 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8459 if( sz<0 ) sz = 0;
8460 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8461 if( n<0 ) n = 0;
8462 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8463 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
8464 #ifdef SQLITE_ENABLE_VFSTRACE
8465 }else if( strcmp(z,"-vfstrace")==0 ){
8466 extern int vfstrace_register(
8467 const char *zTraceName,
8468 const char *zOldVfsName,
8469 int (*xOut)(const char*,void*),
8470 void *pOutArg,
8471 int makeDefault
8473 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
8474 #endif
8475 #ifdef SQLITE_ENABLE_MULTIPLEX
8476 }else if( strcmp(z,"-multiplex")==0 ){
8477 extern int sqlite3_multiple_initialize(const char*,int);
8478 sqlite3_multiplex_initialize(0, 1);
8479 #endif
8480 }else if( strcmp(z,"-mmap")==0 ){
8481 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8482 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
8483 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8484 }else if( strcmp(z,"-sorterref")==0 ){
8485 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8486 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
8487 #endif
8488 }else if( strcmp(z,"-vfs")==0 ){
8489 zVfs = cmdline_option_value(argc, argv, ++i);
8490 #ifdef SQLITE_HAVE_ZLIB
8491 }else if( strcmp(z,"-zip")==0 ){
8492 data.openMode = SHELL_OPEN_ZIPFILE;
8493 #endif
8494 }else if( strcmp(z,"-append")==0 ){
8495 data.openMode = SHELL_OPEN_APPENDVFS;
8496 }else if( strcmp(z,"-readonly")==0 ){
8497 data.openMode = SHELL_OPEN_READONLY;
8498 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8499 }else if( strncmp(z, "-A",2)==0 ){
8500 /* All remaining command-line arguments are passed to the ".archive"
8501 ** command, so ignore them */
8502 break;
8503 #endif
8506 verify_uninitialized();
8509 #ifdef SQLITE_SHELL_INIT_PROC
8511 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8512 ** of a C-function that will perform initialization actions on SQLite that
8513 ** occur just before or after sqlite3_initialize(). Use this compile-time
8514 ** option to embed this shell program in larger applications. */
8515 extern void SQLITE_SHELL_INIT_PROC(void);
8516 SQLITE_SHELL_INIT_PROC();
8518 #else
8519 /* All the sqlite3_config() calls have now been made. So it is safe
8520 ** to call sqlite3_initialize() and process any command line -vfs option. */
8521 sqlite3_initialize();
8522 #endif
8524 if( zVfs ){
8525 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
8526 if( pVfs ){
8527 sqlite3_vfs_register(pVfs, 1);
8528 }else{
8529 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
8530 exit(1);
8534 if( data.zDbFilename==0 ){
8535 #ifndef SQLITE_OMIT_MEMORYDB
8536 data.zDbFilename = ":memory:";
8537 warnInmemoryDb = argc==1;
8538 #else
8539 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
8540 return 1;
8541 #endif
8543 data.out = stdout;
8544 sqlite3_appendvfs_init(0,0,0);
8546 /* Go ahead and open the database file if it already exists. If the
8547 ** file does not exist, delay opening it. This prevents empty database
8548 ** files from being created if a user mistypes the database name argument
8549 ** to the sqlite command-line tool.
8551 if( access(data.zDbFilename, 0)==0 ){
8552 open_db(&data, 0);
8555 /* Process the initialization file if there is one. If no -init option
8556 ** is given on the command line, look for a file named ~/.sqliterc and
8557 ** try to process it.
8559 process_sqliterc(&data,zInitFile);
8561 /* Make a second pass through the command-line argument and set
8562 ** options. This second pass is delayed until after the initialization
8563 ** file is processed so that the command-line arguments will override
8564 ** settings in the initialization file.
8566 for(i=1; i<argc; i++){
8567 char *z = argv[i];
8568 if( z[0]!='-' ) continue;
8569 if( z[1]=='-' ){ z++; }
8570 if( strcmp(z,"-init")==0 ){
8571 i++;
8572 }else if( strcmp(z,"-html")==0 ){
8573 data.mode = MODE_Html;
8574 }else if( strcmp(z,"-list")==0 ){
8575 data.mode = MODE_List;
8576 }else if( strcmp(z,"-quote")==0 ){
8577 data.mode = MODE_Quote;
8578 }else if( strcmp(z,"-line")==0 ){
8579 data.mode = MODE_Line;
8580 }else if( strcmp(z,"-column")==0 ){
8581 data.mode = MODE_Column;
8582 }else if( strcmp(z,"-csv")==0 ){
8583 data.mode = MODE_Csv;
8584 memcpy(data.colSeparator,",",2);
8585 #ifdef SQLITE_HAVE_ZLIB
8586 }else if( strcmp(z,"-zip")==0 ){
8587 data.openMode = SHELL_OPEN_ZIPFILE;
8588 #endif
8589 }else if( strcmp(z,"-append")==0 ){
8590 data.openMode = SHELL_OPEN_APPENDVFS;
8591 }else if( strcmp(z,"-readonly")==0 ){
8592 data.openMode = SHELL_OPEN_READONLY;
8593 }else if( strcmp(z,"-ascii")==0 ){
8594 data.mode = MODE_Ascii;
8595 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8596 SEP_Unit);
8597 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8598 SEP_Record);
8599 }else if( strcmp(z,"-separator")==0 ){
8600 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8601 "%s",cmdline_option_value(argc,argv,++i));
8602 }else if( strcmp(z,"-newline")==0 ){
8603 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8604 "%s",cmdline_option_value(argc,argv,++i));
8605 }else if( strcmp(z,"-nullvalue")==0 ){
8606 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8607 "%s",cmdline_option_value(argc,argv,++i));
8608 }else if( strcmp(z,"-header")==0 ){
8609 data.showHeader = 1;
8610 }else if( strcmp(z,"-noheader")==0 ){
8611 data.showHeader = 0;
8612 }else if( strcmp(z,"-echo")==0 ){
8613 ShellSetFlag(&data, SHFLG_Echo);
8614 }else if( strcmp(z,"-eqp")==0 ){
8615 data.autoEQP = AUTOEQP_on;
8616 }else if( strcmp(z,"-eqpfull")==0 ){
8617 data.autoEQP = AUTOEQP_full;
8618 }else if( strcmp(z,"-stats")==0 ){
8619 data.statsOn = 1;
8620 }else if( strcmp(z,"-scanstats")==0 ){
8621 data.scanstatsOn = 1;
8622 }else if( strcmp(z,"-backslash")==0 ){
8623 /* Undocumented command-line option: -backslash
8624 ** Causes C-style backslash escapes to be evaluated in SQL statements
8625 ** prior to sending the SQL into SQLite. Useful for injecting
8626 ** crazy bytes in the middle of SQL statements for testing and debugging.
8628 ShellSetFlag(&data, SHFLG_Backslash);
8629 }else if( strcmp(z,"-bail")==0 ){
8630 bail_on_error = 1;
8631 }else if( strcmp(z,"-version")==0 ){
8632 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8633 return 0;
8634 }else if( strcmp(z,"-interactive")==0 ){
8635 stdin_is_interactive = 1;
8636 }else if( strcmp(z,"-batch")==0 ){
8637 stdin_is_interactive = 0;
8638 }else if( strcmp(z,"-heap")==0 ){
8639 i++;
8640 }else if( strcmp(z,"-pagecache")==0 ){
8641 i+=2;
8642 }else if( strcmp(z,"-lookaside")==0 ){
8643 i+=2;
8644 }else if( strcmp(z,"-mmap")==0 ){
8645 i++;
8646 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8647 }else if( strcmp(z,"-sorterref")==0 ){
8648 i++;
8649 #endif
8650 }else if( strcmp(z,"-vfs")==0 ){
8651 i++;
8652 #ifdef SQLITE_ENABLE_VFSTRACE
8653 }else if( strcmp(z,"-vfstrace")==0 ){
8654 i++;
8655 #endif
8656 #ifdef SQLITE_ENABLE_MULTIPLEX
8657 }else if( strcmp(z,"-multiplex")==0 ){
8658 i++;
8659 #endif
8660 }else if( strcmp(z,"-help")==0 ){
8661 usage(1);
8662 }else if( strcmp(z,"-cmd")==0 ){
8663 /* Run commands that follow -cmd first and separately from commands
8664 ** that simply appear on the command-line. This seems goofy. It would
8665 ** be better if all commands ran in the order that they appear. But
8666 ** we retain the goofy behavior for historical compatibility. */
8667 if( i==argc-1 ) break;
8668 z = cmdline_option_value(argc,argv,++i);
8669 if( z[0]=='.' ){
8670 rc = do_meta_command(z, &data);
8671 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8672 }else{
8673 open_db(&data, 0);
8674 rc = shell_exec(&data, z, &zErrMsg);
8675 if( zErrMsg!=0 ){
8676 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8677 if( bail_on_error ) return rc!=0 ? rc : 1;
8678 }else if( rc!=0 ){
8679 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8680 if( bail_on_error ) return rc;
8683 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8684 }else if( strncmp(z, "-A", 2)==0 ){
8685 if( nCmd>0 ){
8686 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
8687 " with \"%s\"\n", z);
8688 return 1;
8690 open_db(&data, OPEN_DB_ZIPFILE);
8691 if( z[2] ){
8692 argv[i] = &z[2];
8693 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
8694 }else{
8695 arDotCommand(&data, 1, argv+i, argc-i);
8697 readStdin = 0;
8698 break;
8699 #endif
8700 }else{
8701 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8702 raw_printf(stderr,"Use -help for a list of options.\n");
8703 return 1;
8705 data.cMode = data.mode;
8708 if( !readStdin ){
8709 /* Run all arguments that do not begin with '-' as if they were separate
8710 ** command-line inputs, except for the argToSkip argument which contains
8711 ** the database filename.
8713 for(i=0; i<nCmd; i++){
8714 if( azCmd[i][0]=='.' ){
8715 rc = do_meta_command(azCmd[i], &data);
8716 if( rc ) return rc==2 ? 0 : rc;
8717 }else{
8718 open_db(&data, 0);
8719 rc = shell_exec(&data, azCmd[i], &zErrMsg);
8720 if( zErrMsg!=0 ){
8721 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8722 return rc!=0 ? rc : 1;
8723 }else if( rc!=0 ){
8724 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8725 return rc;
8729 free(azCmd);
8730 }else{
8731 /* Run commands received from standard input
8733 if( stdin_is_interactive ){
8734 char *zHome;
8735 char *zHistory = 0;
8736 int nHistory;
8737 printf(
8738 "SQLite version %s %.19s\n" /*extra-version-info*/
8739 "Enter \".help\" for usage hints.\n",
8740 sqlite3_libversion(), sqlite3_sourceid()
8742 if( warnInmemoryDb ){
8743 printf("Connected to a ");
8744 printBold("transient in-memory database");
8745 printf(".\nUse \".open FILENAME\" to reopen on a "
8746 "persistent database.\n");
8748 zHome = find_home_dir(0);
8749 if( zHome ){
8750 nHistory = strlen30(zHome) + 20;
8751 if( (zHistory = malloc(nHistory))!=0 ){
8752 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8755 if( zHistory ){ shell_read_history(zHistory); }
8756 #if HAVE_READLINE || HAVE_EDITLINE
8757 rl_attempted_completion_function = readline_completion;
8758 #elif HAVE_LINENOISE
8759 linenoiseSetCompletionCallback(linenoise_completion);
8760 #endif
8761 rc = process_input(&data, 0);
8762 if( zHistory ){
8763 shell_stifle_history(2000);
8764 shell_write_history(zHistory);
8765 free(zHistory);
8767 }else{
8768 rc = process_input(&data, stdin);
8771 set_table_name(&data, 0);
8772 if( data.db ){
8773 session_close_all(&data);
8774 close_db(data.db);
8776 sqlite3_free(data.zFreeOnClose);
8777 find_home_dir(1);
8778 output_reset(&data);
8779 data.doXdgOpen = 0;
8780 clearTempFile(&data);
8781 #if !SQLITE_SHELL_IS_UTF8
8782 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
8783 free(argvToFree);
8784 #endif
8785 /* Clear the global data structure so that valgrind will detect memory
8786 ** leaks */
8787 memset(&data, 0, sizeof(data));
8788 return rc;