In the fileio.c extension, change the filetype(MODE) function into lsmode(MODE).
[sqlite.git] / src / shell.c.in
blobb6d51e081d49b444052e385d5043098b29d65934
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 # undef popen
136 # define popen _popen
137 # undef pclose
138 # define pclose _pclose
139 #else
140 /* Make sure isatty() has a prototype. */
141 extern int isatty(int);
143 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
144 /* popen and pclose are not C89 functions and so are
145 ** sometimes omitted from the <stdio.h> header */
146 extern FILE *popen(const char*,const char*);
147 extern int pclose(FILE*);
148 # else
149 # define SQLITE_OMIT_POPEN 1
150 # endif
151 #endif
153 #if defined(_WIN32_WCE)
154 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
155 * thus we always assume that we have a console. That can be
156 * overridden with the -batch command line option.
158 #define isatty(x) 1
159 #endif
161 /* ctype macros that work with signed characters */
162 #define IsSpace(X) isspace((unsigned char)X)
163 #define IsDigit(X) isdigit((unsigned char)X)
164 #define ToLower(X) (char)tolower((unsigned char)X)
166 #if defined(_WIN32) || defined(WIN32)
167 #include <windows.h>
169 /* string conversion routines only needed on Win32 */
170 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
171 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
172 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
173 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
174 #endif
176 /* On Windows, we normally run with output mode of TEXT so that \n characters
177 ** are automatically translated into \r\n. However, this behavior needs
178 ** to be disabled in some cases (ex: when generating CSV output and when
179 ** rendering quoted strings that contain \n characters). The following
180 ** routines take care of that.
182 #if defined(_WIN32) || defined(WIN32)
183 static void setBinaryMode(FILE *file, int isOutput){
184 if( isOutput ) fflush(file);
185 _setmode(_fileno(file), _O_BINARY);
187 static void setTextMode(FILE *file, int isOutput){
188 if( isOutput ) fflush(file);
189 _setmode(_fileno(file), _O_TEXT);
191 #else
192 # define setBinaryMode(X,Y)
193 # define setTextMode(X,Y)
194 #endif
197 /* True if the timer is enabled */
198 static int enableTimer = 0;
200 /* Return the current wall-clock time */
201 static sqlite3_int64 timeOfDay(void){
202 static sqlite3_vfs *clockVfs = 0;
203 sqlite3_int64 t;
204 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
205 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
206 clockVfs->xCurrentTimeInt64(clockVfs, &t);
207 }else{
208 double r;
209 clockVfs->xCurrentTime(clockVfs, &r);
210 t = (sqlite3_int64)(r*86400000.0);
212 return t;
215 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
216 #include <sys/time.h>
217 #include <sys/resource.h>
219 /* VxWorks does not support getrusage() as far as we can determine */
220 #if defined(_WRS_KERNEL) || defined(__RTP__)
221 struct rusage {
222 struct timeval ru_utime; /* user CPU time used */
223 struct timeval ru_stime; /* system CPU time used */
225 #define getrusage(A,B) memset(B,0,sizeof(*B))
226 #endif
228 /* Saved resource information for the beginning of an operation */
229 static struct rusage sBegin; /* CPU time at start */
230 static sqlite3_int64 iBegin; /* Wall-clock time at start */
233 ** Begin timing an operation
235 static void beginTimer(void){
236 if( enableTimer ){
237 getrusage(RUSAGE_SELF, &sBegin);
238 iBegin = timeOfDay();
242 /* Return the difference of two time_structs in seconds */
243 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
244 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
245 (double)(pEnd->tv_sec - pStart->tv_sec);
249 ** Print the timing results.
251 static void endTimer(void){
252 if( enableTimer ){
253 sqlite3_int64 iEnd = timeOfDay();
254 struct rusage sEnd;
255 getrusage(RUSAGE_SELF, &sEnd);
256 printf("Run Time: real %.3f user %f sys %f\n",
257 (iEnd - iBegin)*0.001,
258 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
259 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
263 #define BEGIN_TIMER beginTimer()
264 #define END_TIMER endTimer()
265 #define HAS_TIMER 1
267 #elif (defined(_WIN32) || defined(WIN32))
269 /* Saved resource information for the beginning of an operation */
270 static HANDLE hProcess;
271 static FILETIME ftKernelBegin;
272 static FILETIME ftUserBegin;
273 static sqlite3_int64 ftWallBegin;
274 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
275 LPFILETIME, LPFILETIME);
276 static GETPROCTIMES getProcessTimesAddr = NULL;
279 ** Check to see if we have timer support. Return 1 if necessary
280 ** support found (or found previously).
282 static int hasTimer(void){
283 if( getProcessTimesAddr ){
284 return 1;
285 } else {
286 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
287 ** versions. See if the version we are running on has it, and if it
288 ** does, save off a pointer to it and the current process handle.
290 hProcess = GetCurrentProcess();
291 if( hProcess ){
292 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
293 if( NULL != hinstLib ){
294 getProcessTimesAddr =
295 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
296 if( NULL != getProcessTimesAddr ){
297 return 1;
299 FreeLibrary(hinstLib);
303 return 0;
307 ** Begin timing an operation
309 static void beginTimer(void){
310 if( enableTimer && getProcessTimesAddr ){
311 FILETIME ftCreation, ftExit;
312 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
313 &ftKernelBegin,&ftUserBegin);
314 ftWallBegin = timeOfDay();
318 /* Return the difference of two FILETIME structs in seconds */
319 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
320 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
321 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
322 return (double) ((i64End - i64Start) / 10000000.0);
326 ** Print the timing results.
328 static void endTimer(void){
329 if( enableTimer && getProcessTimesAddr){
330 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
331 sqlite3_int64 ftWallEnd = timeOfDay();
332 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
333 printf("Run Time: real %.3f user %f sys %f\n",
334 (ftWallEnd - ftWallBegin)*0.001,
335 timeDiff(&ftUserBegin, &ftUserEnd),
336 timeDiff(&ftKernelBegin, &ftKernelEnd));
340 #define BEGIN_TIMER beginTimer()
341 #define END_TIMER endTimer()
342 #define HAS_TIMER hasTimer()
344 #else
345 #define BEGIN_TIMER
346 #define END_TIMER
347 #define HAS_TIMER 0
348 #endif
351 ** Used to prevent warnings about unused parameters
353 #define UNUSED_PARAMETER(x) (void)(x)
356 ** Number of elements in an array
358 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
361 ** If the following flag is set, then command execution stops
362 ** at an error if we are not interactive.
364 static int bail_on_error = 0;
367 ** Threat stdin as an interactive input if the following variable
368 ** is true. Otherwise, assume stdin is connected to a file or pipe.
370 static int stdin_is_interactive = 1;
373 ** On Windows systems we have to know if standard output is a console
374 ** in order to translate UTF-8 into MBCS. The following variable is
375 ** true if translation is required.
377 static int stdout_is_console = 1;
380 ** The following is the open SQLite database. We make a pointer
381 ** to this database a static variable so that it can be accessed
382 ** by the SIGINT handler to interrupt database processing.
384 static sqlite3 *globalDb = 0;
387 ** True if an interrupt (Control-C) has been received.
389 static volatile int seenInterrupt = 0;
392 ** This is the name of our program. It is set in main(), used
393 ** in a number of other places, mostly for error messages.
395 static char *Argv0;
398 ** Prompt strings. Initialized in main. Settable with
399 ** .prompt main continue
401 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
402 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
405 ** Render output like fprintf(). Except, if the output is going to the
406 ** console and if this is running on a Windows machine, translate the
407 ** output from UTF-8 into MBCS.
409 #if defined(_WIN32) || defined(WIN32)
410 void utf8_printf(FILE *out, const char *zFormat, ...){
411 va_list ap;
412 va_start(ap, zFormat);
413 if( stdout_is_console && (out==stdout || out==stderr) ){
414 char *z1 = sqlite3_vmprintf(zFormat, ap);
415 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
416 sqlite3_free(z1);
417 fputs(z2, out);
418 sqlite3_free(z2);
419 }else{
420 vfprintf(out, zFormat, ap);
422 va_end(ap);
424 #elif !defined(utf8_printf)
425 # define utf8_printf fprintf
426 #endif
429 ** Render output like fprintf(). This should not be used on anything that
430 ** includes string formatting (e.g. "%s").
432 #if !defined(raw_printf)
433 # define raw_printf fprintf
434 #endif
437 ** Write I/O traces to the following stream.
439 #ifdef SQLITE_ENABLE_IOTRACE
440 static FILE *iotrace = 0;
441 #endif
444 ** This routine works like printf in that its first argument is a
445 ** format string and subsequent arguments are values to be substituted
446 ** in place of % fields. The result of formatting this string
447 ** is written to iotrace.
449 #ifdef SQLITE_ENABLE_IOTRACE
450 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
451 va_list ap;
452 char *z;
453 if( iotrace==0 ) return;
454 va_start(ap, zFormat);
455 z = sqlite3_vmprintf(zFormat, ap);
456 va_end(ap);
457 utf8_printf(iotrace, "%s", z);
458 sqlite3_free(z);
460 #endif
463 ** Output string zUtf to stream pOut as w characters. If w is negative,
464 ** then right-justify the text. W is the width in UTF-8 characters, not
465 ** in bytes. This is different from the %*.*s specification in printf
466 ** since with %*.*s the width is measured in bytes, not characters.
468 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
469 int i;
470 int n;
471 int aw = w<0 ? -w : w;
472 char zBuf[1000];
473 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
474 for(i=n=0; zUtf[i]; i++){
475 if( (zUtf[i]&0xc0)!=0x80 ){
476 n++;
477 if( n==aw ){
478 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
479 break;
483 if( n>=aw ){
484 utf8_printf(pOut, "%.*s", i, zUtf);
485 }else if( w<0 ){
486 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
487 }else{
488 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
494 ** Determines if a string is a number of not.
496 static int isNumber(const char *z, int *realnum){
497 if( *z=='-' || *z=='+' ) z++;
498 if( !IsDigit(*z) ){
499 return 0;
501 z++;
502 if( realnum ) *realnum = 0;
503 while( IsDigit(*z) ){ z++; }
504 if( *z=='.' ){
505 z++;
506 if( !IsDigit(*z) ) return 0;
507 while( IsDigit(*z) ){ z++; }
508 if( realnum ) *realnum = 1;
510 if( *z=='e' || *z=='E' ){
511 z++;
512 if( *z=='+' || *z=='-' ) z++;
513 if( !IsDigit(*z) ) return 0;
514 while( IsDigit(*z) ){ z++; }
515 if( realnum ) *realnum = 1;
517 return *z==0;
521 ** Compute a string length that is limited to what can be stored in
522 ** lower 30 bits of a 32-bit signed integer.
524 static int strlen30(const char *z){
525 const char *z2 = z;
526 while( *z2 ){ z2++; }
527 return 0x3fffffff & (int)(z2 - z);
531 ** Return the length of a string in characters. Multibyte UTF8 characters
532 ** count as a single character.
534 static int strlenChar(const char *z){
535 int n = 0;
536 while( *z ){
537 if( (0xc0&*(z++))!=0x80 ) n++;
539 return n;
543 ** This routine reads a line of text from FILE in, stores
544 ** the text in memory obtained from malloc() and returns a pointer
545 ** to the text. NULL is returned at end of file, or if malloc()
546 ** fails.
548 ** If zLine is not NULL then it is a malloced buffer returned from
549 ** a previous call to this routine that may be reused.
551 static char *local_getline(char *zLine, FILE *in){
552 int nLine = zLine==0 ? 0 : 100;
553 int n = 0;
555 while( 1 ){
556 if( n+100>nLine ){
557 nLine = nLine*2 + 100;
558 zLine = realloc(zLine, nLine);
559 if( zLine==0 ) return 0;
561 if( fgets(&zLine[n], nLine - n, in)==0 ){
562 if( n==0 ){
563 free(zLine);
564 return 0;
566 zLine[n] = 0;
567 break;
569 while( zLine[n] ) n++;
570 if( n>0 && zLine[n-1]=='\n' ){
571 n--;
572 if( n>0 && zLine[n-1]=='\r' ) n--;
573 zLine[n] = 0;
574 break;
577 #if defined(_WIN32) || defined(WIN32)
578 /* For interactive input on Windows systems, translate the
579 ** multi-byte characterset characters into UTF-8. */
580 if( stdin_is_interactive && in==stdin ){
581 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
582 if( zTrans ){
583 int nTrans = strlen30(zTrans)+1;
584 if( nTrans>nLine ){
585 zLine = realloc(zLine, nTrans);
586 if( zLine==0 ){
587 sqlite3_free(zTrans);
588 return 0;
591 memcpy(zLine, zTrans, nTrans);
592 sqlite3_free(zTrans);
595 #endif /* defined(_WIN32) || defined(WIN32) */
596 return zLine;
600 ** Retrieve a single line of input text.
602 ** If in==0 then read from standard input and prompt before each line.
603 ** If isContinuation is true, then a continuation prompt is appropriate.
604 ** If isContinuation is zero, then the main prompt should be used.
606 ** If zPrior is not NULL then it is a buffer from a prior call to this
607 ** routine that can be reused.
609 ** The result is stored in space obtained from malloc() and must either
610 ** be freed by the caller or else passed back into this routine via the
611 ** zPrior argument for reuse.
613 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
614 char *zPrompt;
615 char *zResult;
616 if( in!=0 ){
617 zResult = local_getline(zPrior, in);
618 }else{
619 zPrompt = isContinuation ? continuePrompt : mainPrompt;
620 #if SHELL_USE_LOCAL_GETLINE
621 printf("%s", zPrompt);
622 fflush(stdout);
623 zResult = local_getline(zPrior, stdin);
624 #else
625 free(zPrior);
626 zResult = shell_readline(zPrompt);
627 if( zResult && *zResult ) shell_add_history(zResult);
628 #endif
630 return zResult;
635 ** Return the value of a hexadecimal digit. Return -1 if the input
636 ** is not a hex digit.
638 static int hexDigitValue(char c){
639 if( c>='0' && c<='9' ) return c - '0';
640 if( c>='a' && c<='f' ) return c - 'a' + 10;
641 if( c>='A' && c<='F' ) return c - 'A' + 10;
642 return -1;
646 ** Interpret zArg as an integer value, possibly with suffixes.
648 static sqlite3_int64 integerValue(const char *zArg){
649 sqlite3_int64 v = 0;
650 static const struct { char *zSuffix; int iMult; } aMult[] = {
651 { "KiB", 1024 },
652 { "MiB", 1024*1024 },
653 { "GiB", 1024*1024*1024 },
654 { "KB", 1000 },
655 { "MB", 1000000 },
656 { "GB", 1000000000 },
657 { "K", 1000 },
658 { "M", 1000000 },
659 { "G", 1000000000 },
661 int i;
662 int isNeg = 0;
663 if( zArg[0]=='-' ){
664 isNeg = 1;
665 zArg++;
666 }else if( zArg[0]=='+' ){
667 zArg++;
669 if( zArg[0]=='0' && zArg[1]=='x' ){
670 int x;
671 zArg += 2;
672 while( (x = hexDigitValue(zArg[0]))>=0 ){
673 v = (v<<4) + x;
674 zArg++;
676 }else{
677 while( IsDigit(zArg[0]) ){
678 v = v*10 + zArg[0] - '0';
679 zArg++;
682 for(i=0; i<ArraySize(aMult); i++){
683 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
684 v *= aMult[i].iMult;
685 break;
688 return isNeg? -v : v;
692 ** A variable length string to which one can append text.
694 typedef struct ShellText ShellText;
695 struct ShellText {
696 char *z;
697 int n;
698 int nAlloc;
702 ** Initialize and destroy a ShellText object
704 static void initText(ShellText *p){
705 memset(p, 0, sizeof(*p));
707 static void freeText(ShellText *p){
708 free(p->z);
709 initText(p);
712 /* zIn is either a pointer to a NULL-terminated string in memory obtained
713 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
714 ** added to zIn, and the result returned in memory obtained from malloc().
715 ** zIn, if it was not NULL, is freed.
717 ** If the third argument, quote, is not '\0', then it is used as a
718 ** quote character for zAppend.
720 static void appendText(ShellText *p, char const *zAppend, char quote){
721 int len;
722 int i;
723 int nAppend = strlen30(zAppend);
725 len = nAppend+p->n+1;
726 if( quote ){
727 len += 2;
728 for(i=0; i<nAppend; i++){
729 if( zAppend[i]==quote ) len++;
733 if( p->n+len>=p->nAlloc ){
734 p->nAlloc = p->nAlloc*2 + len + 20;
735 p->z = realloc(p->z, p->nAlloc);
736 if( p->z==0 ){
737 memset(p, 0, sizeof(*p));
738 return;
742 if( quote ){
743 char *zCsr = p->z+p->n;
744 *zCsr++ = quote;
745 for(i=0; i<nAppend; i++){
746 *zCsr++ = zAppend[i];
747 if( zAppend[i]==quote ) *zCsr++ = quote;
749 *zCsr++ = quote;
750 p->n = (int)(zCsr - p->z);
751 *zCsr = '\0';
752 }else{
753 memcpy(p->z+p->n, zAppend, nAppend);
754 p->n += nAppend;
755 p->z[p->n] = '\0';
760 ** Attempt to determine if identifier zName needs to be quoted, either
761 ** because it contains non-alphanumeric characters, or because it is an
762 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
763 ** that quoting is required.
765 ** Return '"' if quoting is required. Return 0 if no quoting is required.
767 static char quoteChar(const char *zName){
768 /* All SQLite keywords, in alphabetical order */
769 static const char *azKeywords[] = {
770 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
771 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
772 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
773 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
774 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
775 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
776 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
777 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
778 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
779 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
780 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
781 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
782 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
783 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
784 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
785 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
786 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
787 "WITH", "WITHOUT",
789 int i, lwr, upr, mid, c;
790 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
791 for(i=0; zName[i]; i++){
792 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
794 lwr = 0;
795 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
796 while( lwr<=upr ){
797 mid = (lwr+upr)/2;
798 c = sqlite3_stricmp(azKeywords[mid], zName);
799 if( c==0 ) return '"';
800 if( c<0 ){
801 lwr = mid+1;
802 }else{
803 upr = mid-1;
806 return 0;
810 ** Construct a fake object name and column list to describe the structure
811 ** of the view, virtual table, or table valued function zSchema.zName.
813 static char *shellFakeSchema(
814 sqlite3 *db, /* The database connection containing the vtab */
815 const char *zSchema, /* Schema of the database holding the vtab */
816 const char *zName /* The name of the virtual table */
818 sqlite3_stmt *pStmt = 0;
819 char *zSql;
820 ShellText s;
821 char cQuote;
822 char *zDiv = "(";
823 int nRow = 0;
825 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
826 zSchema ? zSchema : "main", zName);
827 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
828 sqlite3_free(zSql);
829 initText(&s);
830 if( zSchema ){
831 cQuote = quoteChar(zSchema);
832 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
833 appendText(&s, zSchema, cQuote);
834 appendText(&s, ".", 0);
836 cQuote = quoteChar(zName);
837 appendText(&s, zName, cQuote);
838 while( sqlite3_step(pStmt)==SQLITE_ROW ){
839 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
840 nRow++;
841 appendText(&s, zDiv, 0);
842 zDiv = ",";
843 cQuote = quoteChar(zCol);
844 appendText(&s, zCol, cQuote);
846 appendText(&s, ")", 0);
847 sqlite3_finalize(pStmt);
848 if( nRow==0 ){
849 freeText(&s);
850 s.z = 0;
852 return s.z;
856 ** SQL function: shell_module_schema(X)
858 ** Return a fake schema for the table-valued function or eponymous virtual
859 ** table X.
861 static void shellModuleSchema(
862 sqlite3_context *pCtx,
863 int nVal,
864 sqlite3_value **apVal
866 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
867 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
868 if( zFake ){
869 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
870 -1, sqlite3_free);
871 free(zFake);
876 ** SQL function: shell_add_schema(S,X)
878 ** Add the schema name X to the CREATE statement in S and return the result.
879 ** Examples:
881 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
883 ** Also works on
885 ** CREATE INDEX
886 ** CREATE UNIQUE INDEX
887 ** CREATE VIEW
888 ** CREATE TRIGGER
889 ** CREATE VIRTUAL TABLE
891 ** This UDF is used by the .schema command to insert the schema name of
892 ** attached databases into the middle of the sqlite_master.sql field.
894 static void shellAddSchemaName(
895 sqlite3_context *pCtx,
896 int nVal,
897 sqlite3_value **apVal
899 static const char *aPrefix[] = {
900 "TABLE",
901 "INDEX",
902 "UNIQUE INDEX",
903 "VIEW",
904 "TRIGGER",
905 "VIRTUAL TABLE"
907 int i = 0;
908 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
909 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
910 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
911 sqlite3 *db = sqlite3_context_db_handle(pCtx);
912 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
913 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
914 int n = strlen30(aPrefix[i]);
915 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
916 char *z = 0;
917 char *zFake = 0;
918 if( zSchema ){
919 char cQuote = quoteChar(zSchema);
920 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
921 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
922 }else{
923 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
926 if( zName
927 && aPrefix[i][0]=='V'
928 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
930 if( z==0 ){
931 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
932 }else{
933 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
935 free(zFake);
937 if( z ){
938 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
939 return;
944 sqlite3_result_value(pCtx, apVal[0]);
948 ** The source code for several run-time loadable extensions is inserted
949 ** below by the ../tool/mkshellc.tcl script. Before processing that included
950 ** code, we need to override some macros to make the included program code
951 ** work here in the middle of this regular program.
953 #define SQLITE_EXTENSION_INIT1
954 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
956 #if defined(_WIN32) && defined(_MSC_VER)
957 INCLUDE test_windirent.h
958 INCLUDE test_windirent.c
959 #define dirent DIRENT
960 #endif
961 INCLUDE ../ext/misc/shathree.c
962 INCLUDE ../ext/misc/fileio.c
963 INCLUDE ../ext/misc/completion.c
964 INCLUDE ../ext/misc/appendvfs.c
965 #ifdef SQLITE_HAVE_ZLIB
966 INCLUDE ../ext/misc/zipfile.c
967 INCLUDE ../ext/misc/sqlar.c
968 #endif
969 INCLUDE ../ext/expert/sqlite3expert.h
970 INCLUDE ../ext/expert/sqlite3expert.c
972 #if defined(SQLITE_ENABLE_SESSION)
974 ** State information for a single open session
976 typedef struct OpenSession OpenSession;
977 struct OpenSession {
978 char *zName; /* Symbolic name for this session */
979 int nFilter; /* Number of xFilter rejection GLOB patterns */
980 char **azFilter; /* Array of xFilter rejection GLOB patterns */
981 sqlite3_session *p; /* The open session */
983 #endif
986 ** Shell output mode information from before ".explain on",
987 ** saved so that it can be restored by ".explain off"
989 typedef struct SavedModeInfo SavedModeInfo;
990 struct SavedModeInfo {
991 int valid; /* Is there legit data in here? */
992 int mode; /* Mode prior to ".explain on" */
993 int showHeader; /* The ".header" setting prior to ".explain on" */
994 int colWidth[100]; /* Column widths prior to ".explain on" */
997 typedef struct ExpertInfo ExpertInfo;
998 struct ExpertInfo {
999 sqlite3expert *pExpert;
1000 int bVerbose;
1004 ** State information about the database connection is contained in an
1005 ** instance of the following structure.
1007 typedef struct ShellState ShellState;
1008 struct ShellState {
1009 sqlite3 *db; /* The database */
1010 u8 autoExplain; /* Automatically turn on .explain mode */
1011 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1012 u8 statsOn; /* True to display memory stats before each finalize */
1013 u8 scanstatsOn; /* True to display scan stats before each finalize */
1014 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1015 int outCount; /* Revert to stdout when reaching zero */
1016 int cnt; /* Number of records displayed so far */
1017 FILE *out; /* Write results here */
1018 FILE *traceOut; /* Output for sqlite3_trace() */
1019 int nErr; /* Number of errors seen */
1020 int mode; /* An output mode setting */
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 zTestcase[30]; /* Name of current test case */
1029 char colSeparator[20]; /* Column separator character for several modes */
1030 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1031 int colWidth[100]; /* Requested width of each column when in column mode*/
1032 int actualWidth[100]; /* Actual width of each column */
1033 char nullValue[20]; /* The text to print when a NULL comes back from
1034 ** the database */
1035 char outfile[FILENAME_MAX]; /* Filename for *out */
1036 const char *zDbFilename; /* name of the database file */
1037 char *zFreeOnClose; /* Filename to free when closing */
1038 const char *zVfs; /* Name of VFS to use */
1039 sqlite3_stmt *pStmt; /* Current statement if any. */
1040 FILE *pLog; /* Write log output here */
1041 int *aiIndent; /* Array of indents used in MODE_Explain */
1042 int nIndent; /* Size of array aiIndent[] */
1043 int iIndent; /* Index of current op in aiIndent[] */
1044 #if defined(SQLITE_ENABLE_SESSION)
1045 int nSession; /* Number of active sessions */
1046 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1047 #endif
1048 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1052 /* Allowed values for ShellState.autoEQP
1054 #define AUTOEQP_off 0
1055 #define AUTOEQP_on 1
1056 #define AUTOEQP_trigger 2
1057 #define AUTOEQP_full 3
1059 /* Allowed values for ShellState.openMode
1061 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1062 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1063 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1064 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1067 ** These are the allowed shellFlgs values
1069 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1070 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1071 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1072 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1073 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1074 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1075 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1078 ** Macros for testing and setting shellFlgs
1080 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1081 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1082 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1085 ** These are the allowed modes.
1087 #define MODE_Line 0 /* One column per line. Blank line between records */
1088 #define MODE_Column 1 /* One record per line in neat columns */
1089 #define MODE_List 2 /* One record per line with a separator */
1090 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1091 #define MODE_Html 4 /* Generate an XHTML table */
1092 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1093 #define MODE_Quote 6 /* Quote values as for SQL */
1094 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1095 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1096 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1097 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1098 #define MODE_Pretty 11 /* Pretty-print schemas */
1100 static const char *modeDescr[] = {
1101 "line",
1102 "column",
1103 "list",
1104 "semi",
1105 "html",
1106 "insert",
1107 "quote",
1108 "tcl",
1109 "csv",
1110 "explain",
1111 "ascii",
1112 "prettyprint",
1116 ** These are the column/row/line separators used by the various
1117 ** import/export modes.
1119 #define SEP_Column "|"
1120 #define SEP_Row "\n"
1121 #define SEP_Tab "\t"
1122 #define SEP_Space " "
1123 #define SEP_Comma ","
1124 #define SEP_CrLf "\r\n"
1125 #define SEP_Unit "\x1F"
1126 #define SEP_Record "\x1E"
1129 ** A callback for the sqlite3_log() interface.
1131 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1132 ShellState *p = (ShellState*)pArg;
1133 if( p->pLog==0 ) return;
1134 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1135 fflush(p->pLog);
1139 ** SQL function: shell_putsnl(X)
1141 ** Write the text X to the screen (or whatever output is being directed)
1142 ** adding a newline at the end, and then return X.
1144 static void shellPutsFunc(
1145 sqlite3_context *pCtx,
1146 int nVal,
1147 sqlite3_value **apVal
1149 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1150 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1151 sqlite3_result_value(pCtx, apVal[0]);
1155 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1157 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1158 int i;
1159 char *zBlob = (char *)pBlob;
1160 raw_printf(out,"X'");
1161 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1162 raw_printf(out,"'");
1166 ** Find a string that is not found anywhere in z[]. Return a pointer
1167 ** to that string.
1169 ** Try to use zA and zB first. If both of those are already found in z[]
1170 ** then make up some string and store it in the buffer zBuf.
1172 static const char *unused_string(
1173 const char *z, /* Result must not appear anywhere in z */
1174 const char *zA, const char *zB, /* Try these first */
1175 char *zBuf /* Space to store a generated string */
1177 unsigned i = 0;
1178 if( strstr(z, zA)==0 ) return zA;
1179 if( strstr(z, zB)==0 ) return zB;
1181 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1182 }while( strstr(z,zBuf)!=0 );
1183 return zBuf;
1187 ** Output the given string as a quoted string using SQL quoting conventions.
1189 ** See also: output_quoted_escaped_string()
1191 static void output_quoted_string(FILE *out, const char *z){
1192 int i;
1193 char c;
1194 setBinaryMode(out, 1);
1195 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1196 if( c==0 ){
1197 utf8_printf(out,"'%s'",z);
1198 }else{
1199 raw_printf(out, "'");
1200 while( *z ){
1201 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1202 if( c=='\'' ) i++;
1203 if( i ){
1204 utf8_printf(out, "%.*s", i, z);
1205 z += i;
1207 if( c=='\'' ){
1208 raw_printf(out, "'");
1209 continue;
1211 if( c==0 ){
1212 break;
1214 z++;
1216 raw_printf(out, "'");
1218 setTextMode(out, 1);
1222 ** Output the given string as a quoted string using SQL quoting conventions.
1223 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1224 ** get corrupted by end-of-line translation facilities in some operating
1225 ** systems.
1227 ** This is like output_quoted_string() but with the addition of the \r\n
1228 ** escape mechanism.
1230 static void output_quoted_escaped_string(FILE *out, const char *z){
1231 int i;
1232 char c;
1233 setBinaryMode(out, 1);
1234 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1235 if( c==0 ){
1236 utf8_printf(out,"'%s'",z);
1237 }else{
1238 const char *zNL = 0;
1239 const char *zCR = 0;
1240 int nNL = 0;
1241 int nCR = 0;
1242 char zBuf1[20], zBuf2[20];
1243 for(i=0; z[i]; i++){
1244 if( z[i]=='\n' ) nNL++;
1245 if( z[i]=='\r' ) nCR++;
1247 if( nNL ){
1248 raw_printf(out, "replace(");
1249 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1251 if( nCR ){
1252 raw_printf(out, "replace(");
1253 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1255 raw_printf(out, "'");
1256 while( *z ){
1257 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1258 if( c=='\'' ) i++;
1259 if( i ){
1260 utf8_printf(out, "%.*s", i, z);
1261 z += i;
1263 if( c=='\'' ){
1264 raw_printf(out, "'");
1265 continue;
1267 if( c==0 ){
1268 break;
1270 z++;
1271 if( c=='\n' ){
1272 raw_printf(out, "%s", zNL);
1273 continue;
1275 raw_printf(out, "%s", zCR);
1277 raw_printf(out, "'");
1278 if( nCR ){
1279 raw_printf(out, ",'%s',char(13))", zCR);
1281 if( nNL ){
1282 raw_printf(out, ",'%s',char(10))", zNL);
1285 setTextMode(out, 1);
1289 ** Output the given string as a quoted according to C or TCL quoting rules.
1291 static void output_c_string(FILE *out, const char *z){
1292 unsigned int c;
1293 fputc('"', out);
1294 while( (c = *(z++))!=0 ){
1295 if( c=='\\' ){
1296 fputc(c, out);
1297 fputc(c, out);
1298 }else if( c=='"' ){
1299 fputc('\\', out);
1300 fputc('"', out);
1301 }else if( c=='\t' ){
1302 fputc('\\', out);
1303 fputc('t', out);
1304 }else if( c=='\n' ){
1305 fputc('\\', out);
1306 fputc('n', out);
1307 }else if( c=='\r' ){
1308 fputc('\\', out);
1309 fputc('r', out);
1310 }else if( !isprint(c&0xff) ){
1311 raw_printf(out, "\\%03o", c&0xff);
1312 }else{
1313 fputc(c, out);
1316 fputc('"', out);
1320 ** Output the given string with characters that are special to
1321 ** HTML escaped.
1323 static void output_html_string(FILE *out, const char *z){
1324 int i;
1325 if( z==0 ) z = "";
1326 while( *z ){
1327 for(i=0; z[i]
1328 && z[i]!='<'
1329 && z[i]!='&'
1330 && z[i]!='>'
1331 && z[i]!='\"'
1332 && z[i]!='\'';
1333 i++){}
1334 if( i>0 ){
1335 utf8_printf(out,"%.*s",i,z);
1337 if( z[i]=='<' ){
1338 raw_printf(out,"&lt;");
1339 }else if( z[i]=='&' ){
1340 raw_printf(out,"&amp;");
1341 }else if( z[i]=='>' ){
1342 raw_printf(out,"&gt;");
1343 }else if( z[i]=='\"' ){
1344 raw_printf(out,"&quot;");
1345 }else if( z[i]=='\'' ){
1346 raw_printf(out,"&#39;");
1347 }else{
1348 break;
1350 z += i + 1;
1355 ** If a field contains any character identified by a 1 in the following
1356 ** array, then the string must be quoted for CSV.
1358 static const char needCsvQuote[] = {
1359 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1360 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1361 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1362 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1363 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1364 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1365 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1366 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1367 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1368 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1369 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1370 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1371 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1372 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1373 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1374 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1378 ** Output a single term of CSV. Actually, p->colSeparator is used for
1379 ** the separator, which may or may not be a comma. p->nullValue is
1380 ** the null value. Strings are quoted if necessary. The separator
1381 ** is only issued if bSep is true.
1383 static void output_csv(ShellState *p, const char *z, int bSep){
1384 FILE *out = p->out;
1385 if( z==0 ){
1386 utf8_printf(out,"%s",p->nullValue);
1387 }else{
1388 int i;
1389 int nSep = strlen30(p->colSeparator);
1390 for(i=0; z[i]; i++){
1391 if( needCsvQuote[((unsigned char*)z)[i]]
1392 || (z[i]==p->colSeparator[0] &&
1393 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1394 i = 0;
1395 break;
1398 if( i==0 ){
1399 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1400 utf8_printf(out, "%s", zQuoted);
1401 sqlite3_free(zQuoted);
1402 }else{
1403 utf8_printf(out, "%s", z);
1406 if( bSep ){
1407 utf8_printf(p->out, "%s", p->colSeparator);
1412 ** This routine runs when the user presses Ctrl-C
1414 static void interrupt_handler(int NotUsed){
1415 UNUSED_PARAMETER(NotUsed);
1416 seenInterrupt++;
1417 if( seenInterrupt>2 ) exit(1);
1418 if( globalDb ) sqlite3_interrupt(globalDb);
1421 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1423 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1425 static BOOL WINAPI ConsoleCtrlHandler(
1426 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1428 if( dwCtrlType==CTRL_C_EVENT ){
1429 interrupt_handler(0);
1430 return TRUE;
1432 return FALSE;
1434 #endif
1436 #ifndef SQLITE_OMIT_AUTHORIZATION
1438 ** When the ".auth ON" is set, the following authorizer callback is
1439 ** invoked. It always returns SQLITE_OK.
1441 static int shellAuth(
1442 void *pClientData,
1443 int op,
1444 const char *zA1,
1445 const char *zA2,
1446 const char *zA3,
1447 const char *zA4
1449 ShellState *p = (ShellState*)pClientData;
1450 static const char *azAction[] = { 0,
1451 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1452 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1453 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1454 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1455 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1456 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1457 "PRAGMA", "READ", "SELECT",
1458 "TRANSACTION", "UPDATE", "ATTACH",
1459 "DETACH", "ALTER_TABLE", "REINDEX",
1460 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1461 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1463 int i;
1464 const char *az[4];
1465 az[0] = zA1;
1466 az[1] = zA2;
1467 az[2] = zA3;
1468 az[3] = zA4;
1469 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1470 for(i=0; i<4; i++){
1471 raw_printf(p->out, " ");
1472 if( az[i] ){
1473 output_c_string(p->out, az[i]);
1474 }else{
1475 raw_printf(p->out, "NULL");
1478 raw_printf(p->out, "\n");
1479 return SQLITE_OK;
1481 #endif
1484 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1486 ** This routine converts some CREATE TABLE statements for shadow tables
1487 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1489 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1490 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1491 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1492 }else{
1493 utf8_printf(out, "%s%s", z, zTail);
1496 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1497 char c = z[n];
1498 z[n] = 0;
1499 printSchemaLine(out, z, zTail);
1500 z[n] = c;
1504 ** Return true if string z[] has nothing but whitespace and comments to the
1505 ** end of the first line.
1507 static int wsToEol(const char *z){
1508 int i;
1509 for(i=0; z[i]; i++){
1510 if( z[i]=='\n' ) return 1;
1511 if( IsSpace(z[i]) ) continue;
1512 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1513 return 0;
1515 return 1;
1520 ** This is the callback routine that the shell
1521 ** invokes for each row of a query result.
1523 static int shell_callback(
1524 void *pArg,
1525 int nArg, /* Number of result columns */
1526 char **azArg, /* Text of each result column */
1527 char **azCol, /* Column names */
1528 int *aiType /* Column types */
1530 int i;
1531 ShellState *p = (ShellState*)pArg;
1533 if( azArg==0 ) return 0;
1534 switch( p->cMode ){
1535 case MODE_Line: {
1536 int w = 5;
1537 if( azArg==0 ) break;
1538 for(i=0; i<nArg; i++){
1539 int len = strlen30(azCol[i] ? azCol[i] : "");
1540 if( len>w ) w = len;
1542 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1543 for(i=0; i<nArg; i++){
1544 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1545 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1547 break;
1549 case MODE_Explain:
1550 case MODE_Column: {
1551 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1552 const int *colWidth;
1553 int showHdr;
1554 char *rowSep;
1555 if( p->cMode==MODE_Column ){
1556 colWidth = p->colWidth;
1557 showHdr = p->showHeader;
1558 rowSep = p->rowSeparator;
1559 }else{
1560 colWidth = aExplainWidths;
1561 showHdr = 1;
1562 rowSep = SEP_Row;
1564 if( p->cnt++==0 ){
1565 for(i=0; i<nArg; i++){
1566 int w, n;
1567 if( i<ArraySize(p->colWidth) ){
1568 w = colWidth[i];
1569 }else{
1570 w = 0;
1572 if( w==0 ){
1573 w = strlenChar(azCol[i] ? azCol[i] : "");
1574 if( w<10 ) w = 10;
1575 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1576 if( w<n ) w = n;
1578 if( i<ArraySize(p->actualWidth) ){
1579 p->actualWidth[i] = w;
1581 if( showHdr ){
1582 utf8_width_print(p->out, w, azCol[i]);
1583 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1586 if( showHdr ){
1587 for(i=0; i<nArg; i++){
1588 int w;
1589 if( i<ArraySize(p->actualWidth) ){
1590 w = p->actualWidth[i];
1591 if( w<0 ) w = -w;
1592 }else{
1593 w = 10;
1595 utf8_printf(p->out,"%-*.*s%s",w,w,
1596 "----------------------------------------------------------"
1597 "----------------------------------------------------------",
1598 i==nArg-1 ? rowSep : " ");
1602 if( azArg==0 ) break;
1603 for(i=0; i<nArg; i++){
1604 int w;
1605 if( i<ArraySize(p->actualWidth) ){
1606 w = p->actualWidth[i];
1607 }else{
1608 w = 10;
1610 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1611 w = strlenChar(azArg[i]);
1613 if( i==1 && p->aiIndent && p->pStmt ){
1614 if( p->iIndent<p->nIndent ){
1615 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1617 p->iIndent++;
1619 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1620 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1622 break;
1624 case MODE_Semi: { /* .schema and .fullschema output */
1625 printSchemaLine(p->out, azArg[0], ";\n");
1626 break;
1628 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1629 char *z;
1630 int j;
1631 int nParen = 0;
1632 char cEnd = 0;
1633 char c;
1634 int nLine = 0;
1635 assert( nArg==1 );
1636 if( azArg[0]==0 ) break;
1637 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1638 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1640 utf8_printf(p->out, "%s;\n", azArg[0]);
1641 break;
1643 z = sqlite3_mprintf("%s", azArg[0]);
1644 j = 0;
1645 for(i=0; IsSpace(z[i]); i++){}
1646 for(; (c = z[i])!=0; i++){
1647 if( IsSpace(c) ){
1648 if( z[j-1]=='\r' ) z[j-1] = '\n';
1649 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1650 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1651 j--;
1653 z[j++] = c;
1655 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1656 z[j] = 0;
1657 if( strlen30(z)>=79 ){
1658 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
1659 if( c==cEnd ){
1660 cEnd = 0;
1661 }else if( c=='"' || c=='\'' || c=='`' ){
1662 cEnd = c;
1663 }else if( c=='[' ){
1664 cEnd = ']';
1665 }else if( c=='-' && z[i+1]=='-' ){
1666 cEnd = '\n';
1667 }else if( c=='(' ){
1668 nParen++;
1669 }else if( c==')' ){
1670 nParen--;
1671 if( nLine>0 && nParen==0 && j>0 ){
1672 printSchemaLineN(p->out, z, j, "\n");
1673 j = 0;
1676 z[j++] = c;
1677 if( nParen==1 && cEnd==0
1678 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1680 if( c=='\n' ) j--;
1681 printSchemaLineN(p->out, z, j, "\n ");
1682 j = 0;
1683 nLine++;
1684 while( IsSpace(z[i+1]) ){ i++; }
1687 z[j] = 0;
1689 printSchemaLine(p->out, z, ";\n");
1690 sqlite3_free(z);
1691 break;
1693 case MODE_List: {
1694 if( p->cnt++==0 && p->showHeader ){
1695 for(i=0; i<nArg; i++){
1696 utf8_printf(p->out,"%s%s",azCol[i],
1697 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1700 if( azArg==0 ) break;
1701 for(i=0; i<nArg; i++){
1702 char *z = azArg[i];
1703 if( z==0 ) z = p->nullValue;
1704 utf8_printf(p->out, "%s", z);
1705 if( i<nArg-1 ){
1706 utf8_printf(p->out, "%s", p->colSeparator);
1707 }else{
1708 utf8_printf(p->out, "%s", p->rowSeparator);
1711 break;
1713 case MODE_Html: {
1714 if( p->cnt++==0 && p->showHeader ){
1715 raw_printf(p->out,"<TR>");
1716 for(i=0; i<nArg; i++){
1717 raw_printf(p->out,"<TH>");
1718 output_html_string(p->out, azCol[i]);
1719 raw_printf(p->out,"</TH>\n");
1721 raw_printf(p->out,"</TR>\n");
1723 if( azArg==0 ) break;
1724 raw_printf(p->out,"<TR>");
1725 for(i=0; i<nArg; i++){
1726 raw_printf(p->out,"<TD>");
1727 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1728 raw_printf(p->out,"</TD>\n");
1730 raw_printf(p->out,"</TR>\n");
1731 break;
1733 case MODE_Tcl: {
1734 if( p->cnt++==0 && p->showHeader ){
1735 for(i=0; i<nArg; i++){
1736 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1737 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1739 utf8_printf(p->out, "%s", p->rowSeparator);
1741 if( azArg==0 ) break;
1742 for(i=0; i<nArg; i++){
1743 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1744 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1746 utf8_printf(p->out, "%s", p->rowSeparator);
1747 break;
1749 case MODE_Csv: {
1750 setBinaryMode(p->out, 1);
1751 if( p->cnt++==0 && p->showHeader ){
1752 for(i=0; i<nArg; i++){
1753 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1755 utf8_printf(p->out, "%s", p->rowSeparator);
1757 if( nArg>0 ){
1758 for(i=0; i<nArg; i++){
1759 output_csv(p, azArg[i], i<nArg-1);
1761 utf8_printf(p->out, "%s", p->rowSeparator);
1763 setTextMode(p->out, 1);
1764 break;
1766 case MODE_Insert: {
1767 if( azArg==0 ) break;
1768 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1769 if( p->showHeader ){
1770 raw_printf(p->out,"(");
1771 for(i=0; i<nArg; i++){
1772 if( i>0 ) raw_printf(p->out, ",");
1773 if( quoteChar(azCol[i]) ){
1774 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1775 utf8_printf(p->out, "%s", z);
1776 sqlite3_free(z);
1777 }else{
1778 raw_printf(p->out, "%s", azCol[i]);
1781 raw_printf(p->out,")");
1783 p->cnt++;
1784 for(i=0; i<nArg; i++){
1785 raw_printf(p->out, i>0 ? "," : " VALUES(");
1786 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1787 utf8_printf(p->out,"NULL");
1788 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1789 if( ShellHasFlag(p, SHFLG_Newlines) ){
1790 output_quoted_string(p->out, azArg[i]);
1791 }else{
1792 output_quoted_escaped_string(p->out, azArg[i]);
1794 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1795 utf8_printf(p->out,"%s", azArg[i]);
1796 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1797 char z[50];
1798 double r = sqlite3_column_double(p->pStmt, i);
1799 sqlite3_snprintf(50,z,"%!.20g", r);
1800 raw_printf(p->out, "%s", z);
1801 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1802 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1803 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1804 output_hex_blob(p->out, pBlob, nBlob);
1805 }else if( isNumber(azArg[i], 0) ){
1806 utf8_printf(p->out,"%s", azArg[i]);
1807 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1808 output_quoted_string(p->out, azArg[i]);
1809 }else{
1810 output_quoted_escaped_string(p->out, azArg[i]);
1813 raw_printf(p->out,");\n");
1814 break;
1816 case MODE_Quote: {
1817 if( azArg==0 ) break;
1818 if( p->cnt==0 && p->showHeader ){
1819 for(i=0; i<nArg; i++){
1820 if( i>0 ) raw_printf(p->out, ",");
1821 output_quoted_string(p->out, azCol[i]);
1823 raw_printf(p->out,"\n");
1825 p->cnt++;
1826 for(i=0; i<nArg; i++){
1827 if( i>0 ) raw_printf(p->out, ",");
1828 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1829 utf8_printf(p->out,"NULL");
1830 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1831 output_quoted_string(p->out, azArg[i]);
1832 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1833 utf8_printf(p->out,"%s", azArg[i]);
1834 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1835 char z[50];
1836 double r = sqlite3_column_double(p->pStmt, i);
1837 sqlite3_snprintf(50,z,"%!.20g", r);
1838 raw_printf(p->out, "%s", z);
1839 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1840 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1841 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1842 output_hex_blob(p->out, pBlob, nBlob);
1843 }else if( isNumber(azArg[i], 0) ){
1844 utf8_printf(p->out,"%s", azArg[i]);
1845 }else{
1846 output_quoted_string(p->out, azArg[i]);
1849 raw_printf(p->out,"\n");
1850 break;
1852 case MODE_Ascii: {
1853 if( p->cnt++==0 && p->showHeader ){
1854 for(i=0; i<nArg; i++){
1855 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1856 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1858 utf8_printf(p->out, "%s", p->rowSeparator);
1860 if( azArg==0 ) break;
1861 for(i=0; i<nArg; i++){
1862 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1863 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1865 utf8_printf(p->out, "%s", p->rowSeparator);
1866 break;
1869 return 0;
1873 ** This is the callback routine that the SQLite library
1874 ** invokes for each row of a query result.
1876 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1877 /* since we don't have type info, call the shell_callback with a NULL value */
1878 return shell_callback(pArg, nArg, azArg, azCol, NULL);
1882 ** This is the callback routine from sqlite3_exec() that appends all
1883 ** output onto the end of a ShellText object.
1885 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1886 ShellText *p = (ShellText*)pArg;
1887 int i;
1888 UNUSED_PARAMETER(az);
1889 if( azArg==0 ) return 0;
1890 if( p->n ) appendText(p, "|", 0);
1891 for(i=0; i<nArg; i++){
1892 if( i ) appendText(p, ",", 0);
1893 if( azArg[i] ) appendText(p, azArg[i], 0);
1895 return 0;
1899 ** Generate an appropriate SELFTEST table in the main database.
1901 static void createSelftestTable(ShellState *p){
1902 char *zErrMsg = 0;
1903 sqlite3_exec(p->db,
1904 "SAVEPOINT selftest_init;\n"
1905 "CREATE TABLE IF NOT EXISTS selftest(\n"
1906 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1907 " op TEXT,\n" /* Operator: memo run */
1908 " cmd TEXT,\n" /* Command text */
1909 " ans TEXT\n" /* Desired answer */
1910 ");"
1911 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1912 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1913 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1914 " 'memo','Tests generated by --init');\n"
1915 "INSERT INTO [_shell$self]\n"
1916 " SELECT 'run',\n"
1917 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1918 "FROM sqlite_master ORDER BY 2'',224))',\n"
1919 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1920 "FROM sqlite_master ORDER BY 2',224));\n"
1921 "INSERT INTO [_shell$self]\n"
1922 " SELECT 'run',"
1923 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1924 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1925 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1926 " FROM (\n"
1927 " SELECT name FROM sqlite_master\n"
1928 " WHERE type='table'\n"
1929 " AND name<>'selftest'\n"
1930 " AND coalesce(rootpage,0)>0\n"
1931 " )\n"
1932 " ORDER BY name;\n"
1933 "INSERT INTO [_shell$self]\n"
1934 " VALUES('run','PRAGMA integrity_check','ok');\n"
1935 "INSERT INTO selftest(tno,op,cmd,ans)"
1936 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1937 "DROP TABLE [_shell$self];"
1938 ,0,0,&zErrMsg);
1939 if( zErrMsg ){
1940 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1941 sqlite3_free(zErrMsg);
1943 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1948 ** Set the destination table field of the ShellState structure to
1949 ** the name of the table given. Escape any quote characters in the
1950 ** table name.
1952 static void set_table_name(ShellState *p, const char *zName){
1953 int i, n;
1954 char cQuote;
1955 char *z;
1957 if( p->zDestTable ){
1958 free(p->zDestTable);
1959 p->zDestTable = 0;
1961 if( zName==0 ) return;
1962 cQuote = quoteChar(zName);
1963 n = strlen30(zName);
1964 if( cQuote ) n += n+2;
1965 z = p->zDestTable = malloc( n+1 );
1966 if( z==0 ){
1967 raw_printf(stderr,"Error: out of memory\n");
1968 exit(1);
1970 n = 0;
1971 if( cQuote ) z[n++] = cQuote;
1972 for(i=0; zName[i]; i++){
1973 z[n++] = zName[i];
1974 if( zName[i]==cQuote ) z[n++] = cQuote;
1976 if( cQuote ) z[n++] = cQuote;
1977 z[n] = 0;
1982 ** Execute a query statement that will generate SQL output. Print
1983 ** the result columns, comma-separated, on a line and then add a
1984 ** semicolon terminator to the end of that line.
1986 ** If the number of columns is 1 and that column contains text "--"
1987 ** then write the semicolon on a separate line. That way, if a
1988 ** "--" comment occurs at the end of the statement, the comment
1989 ** won't consume the semicolon terminator.
1991 static int run_table_dump_query(
1992 ShellState *p, /* Query context */
1993 const char *zSelect, /* SELECT statement to extract content */
1994 const char *zFirstRow /* Print before first row, if not NULL */
1996 sqlite3_stmt *pSelect;
1997 int rc;
1998 int nResult;
1999 int i;
2000 const char *z;
2001 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2002 if( rc!=SQLITE_OK || !pSelect ){
2003 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2004 sqlite3_errmsg(p->db));
2005 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2006 return rc;
2008 rc = sqlite3_step(pSelect);
2009 nResult = sqlite3_column_count(pSelect);
2010 while( rc==SQLITE_ROW ){
2011 if( zFirstRow ){
2012 utf8_printf(p->out, "%s", zFirstRow);
2013 zFirstRow = 0;
2015 z = (const char*)sqlite3_column_text(pSelect, 0);
2016 utf8_printf(p->out, "%s", z);
2017 for(i=1; i<nResult; i++){
2018 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2020 if( z==0 ) z = "";
2021 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2022 if( z[0] ){
2023 raw_printf(p->out, "\n;\n");
2024 }else{
2025 raw_printf(p->out, ";\n");
2027 rc = sqlite3_step(pSelect);
2029 rc = sqlite3_finalize(pSelect);
2030 if( rc!=SQLITE_OK ){
2031 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2032 sqlite3_errmsg(p->db));
2033 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2035 return rc;
2039 ** Allocate space and save off current error string.
2041 static char *save_err_msg(
2042 sqlite3 *db /* Database to query */
2044 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2045 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2046 if( zErrMsg ){
2047 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2049 return zErrMsg;
2052 #ifdef __linux__
2054 ** Attempt to display I/O stats on Linux using /proc/PID/io
2056 static void displayLinuxIoStats(FILE *out){
2057 FILE *in;
2058 char z[200];
2059 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2060 in = fopen(z, "rb");
2061 if( in==0 ) return;
2062 while( fgets(z, sizeof(z), in)!=0 ){
2063 static const struct {
2064 const char *zPattern;
2065 const char *zDesc;
2066 } aTrans[] = {
2067 { "rchar: ", "Bytes received by read():" },
2068 { "wchar: ", "Bytes sent to write():" },
2069 { "syscr: ", "Read() system calls:" },
2070 { "syscw: ", "Write() system calls:" },
2071 { "read_bytes: ", "Bytes read from storage:" },
2072 { "write_bytes: ", "Bytes written to storage:" },
2073 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2075 int i;
2076 for(i=0; i<ArraySize(aTrans); i++){
2077 int n = strlen30(aTrans[i].zPattern);
2078 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2079 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2080 break;
2084 fclose(in);
2086 #endif
2089 ** Display a single line of status using 64-bit values.
2091 static void displayStatLine(
2092 ShellState *p, /* The shell context */
2093 char *zLabel, /* Label for this one line */
2094 char *zFormat, /* Format for the result */
2095 int iStatusCtrl, /* Which status to display */
2096 int bReset /* True to reset the stats */
2098 sqlite3_int64 iCur = -1;
2099 sqlite3_int64 iHiwtr = -1;
2100 int i, nPercent;
2101 char zLine[200];
2102 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2103 for(i=0, nPercent=0; zFormat[i]; i++){
2104 if( zFormat[i]=='%' ) nPercent++;
2106 if( nPercent>1 ){
2107 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2108 }else{
2109 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2111 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2115 ** Display memory stats.
2117 static int display_stats(
2118 sqlite3 *db, /* Database to query */
2119 ShellState *pArg, /* Pointer to ShellState */
2120 int bReset /* True to reset the stats */
2122 int iCur;
2123 int iHiwtr;
2125 if( pArg && pArg->out ){
2126 displayStatLine(pArg, "Memory Used:",
2127 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2128 displayStatLine(pArg, "Number of Outstanding Allocations:",
2129 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2130 if( pArg->shellFlgs & SHFLG_Pagecache ){
2131 displayStatLine(pArg, "Number of Pcache Pages Used:",
2132 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2134 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2135 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2136 displayStatLine(pArg, "Largest Allocation:",
2137 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2138 displayStatLine(pArg, "Largest Pcache Allocation:",
2139 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2140 #ifdef YYTRACKMAXSTACKDEPTH
2141 displayStatLine(pArg, "Deepest Parser Stack:",
2142 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2143 #endif
2146 if( pArg && pArg->out && db ){
2147 if( pArg->shellFlgs & SHFLG_Lookaside ){
2148 iHiwtr = iCur = -1;
2149 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2150 &iCur, &iHiwtr, bReset);
2151 raw_printf(pArg->out,
2152 "Lookaside Slots Used: %d (max %d)\n",
2153 iCur, iHiwtr);
2154 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2155 &iCur, &iHiwtr, bReset);
2156 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2157 iHiwtr);
2158 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2159 &iCur, &iHiwtr, bReset);
2160 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2161 iHiwtr);
2162 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2163 &iCur, &iHiwtr, bReset);
2164 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2165 iHiwtr);
2167 iHiwtr = iCur = -1;
2168 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2169 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2170 iCur);
2171 iHiwtr = iCur = -1;
2172 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2173 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2174 iHiwtr = iCur = -1;
2175 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2176 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2177 iHiwtr = iCur = -1;
2178 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2179 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2180 iHiwtr = iCur = -1;
2181 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2182 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2183 iCur);
2184 iHiwtr = iCur = -1;
2185 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2186 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2187 iCur);
2190 if( pArg && pArg->out && db && pArg->pStmt ){
2191 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2192 bReset);
2193 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2194 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2195 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2196 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2197 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2198 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2199 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2202 #ifdef __linux__
2203 displayLinuxIoStats(pArg->out);
2204 #endif
2206 /* Do not remove this machine readable comment: extra-stats-output-here */
2208 return 0;
2212 ** Display scan stats.
2214 static void display_scanstats(
2215 sqlite3 *db, /* Database to query */
2216 ShellState *pArg /* Pointer to ShellState */
2218 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2219 UNUSED_PARAMETER(db);
2220 UNUSED_PARAMETER(pArg);
2221 #else
2222 int i, k, n, mx;
2223 raw_printf(pArg->out, "-------- scanstats --------\n");
2224 mx = 0;
2225 for(k=0; k<=mx; k++){
2226 double rEstLoop = 1.0;
2227 for(i=n=0; 1; i++){
2228 sqlite3_stmt *p = pArg->pStmt;
2229 sqlite3_int64 nLoop, nVisit;
2230 double rEst;
2231 int iSid;
2232 const char *zExplain;
2233 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2234 break;
2236 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2237 if( iSid>mx ) mx = iSid;
2238 if( iSid!=k ) continue;
2239 if( n==0 ){
2240 rEstLoop = (double)nLoop;
2241 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2243 n++;
2244 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2245 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2246 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2247 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2248 rEstLoop *= rEst;
2249 raw_printf(pArg->out,
2250 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2251 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2255 raw_printf(pArg->out, "---------------------------\n");
2256 #endif
2260 ** Parameter azArray points to a zero-terminated array of strings. zStr
2261 ** points to a single nul-terminated string. Return non-zero if zStr
2262 ** is equal, according to strcmp(), to any of the strings in the array.
2263 ** Otherwise, return zero.
2265 static int str_in_array(const char *zStr, const char **azArray){
2266 int i;
2267 for(i=0; azArray[i]; i++){
2268 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2270 return 0;
2274 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2275 ** and populate the ShellState.aiIndent[] array with the number of
2276 ** spaces each opcode should be indented before it is output.
2278 ** The indenting rules are:
2280 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2281 ** all opcodes that occur between the p2 jump destination and the opcode
2282 ** itself by 2 spaces.
2284 ** * For each "Goto", if the jump destination is earlier in the program
2285 ** and ends on one of:
2286 ** Yield SeekGt SeekLt RowSetRead Rewind
2287 ** or if the P1 parameter is one instead of zero,
2288 ** then indent all opcodes between the earlier instruction
2289 ** and "Goto" by 2 spaces.
2291 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2292 const char *zSql; /* The text of the SQL statement */
2293 const char *z; /* Used to check if this is an EXPLAIN */
2294 int *abYield = 0; /* True if op is an OP_Yield */
2295 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2296 int iOp; /* Index of operation in p->aiIndent[] */
2298 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2299 "NextIfOpen", "PrevIfOpen", 0 };
2300 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2301 "Rewind", 0 };
2302 const char *azGoto[] = { "Goto", 0 };
2304 /* Try to figure out if this is really an EXPLAIN statement. If this
2305 ** cannot be verified, return early. */
2306 if( sqlite3_column_count(pSql)!=8 ){
2307 p->cMode = p->mode;
2308 return;
2310 zSql = sqlite3_sql(pSql);
2311 if( zSql==0 ) return;
2312 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2313 if( sqlite3_strnicmp(z, "explain", 7) ){
2314 p->cMode = p->mode;
2315 return;
2318 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2319 int i;
2320 int iAddr = sqlite3_column_int(pSql, 0);
2321 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2323 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2324 ** p2 is an instruction address, set variable p2op to the index of that
2325 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2326 ** the current instruction is part of a sub-program generated by an
2327 ** SQL trigger or foreign key. */
2328 int p2 = sqlite3_column_int(pSql, 3);
2329 int p2op = (p2 + (iOp-iAddr));
2331 /* Grow the p->aiIndent array as required */
2332 if( iOp>=nAlloc ){
2333 if( iOp==0 ){
2334 /* Do further verfication that this is explain output. Abort if
2335 ** it is not */
2336 static const char *explainCols[] = {
2337 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2338 int jj;
2339 for(jj=0; jj<ArraySize(explainCols); jj++){
2340 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2341 p->cMode = p->mode;
2342 sqlite3_reset(pSql);
2343 return;
2347 nAlloc += 100;
2348 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2349 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2351 abYield[iOp] = str_in_array(zOp, azYield);
2352 p->aiIndent[iOp] = 0;
2353 p->nIndent = iOp+1;
2355 if( str_in_array(zOp, azNext) ){
2356 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2358 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2359 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2361 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2365 p->iIndent = 0;
2366 sqlite3_free(abYield);
2367 sqlite3_reset(pSql);
2371 ** Free the array allocated by explain_data_prepare().
2373 static void explain_data_delete(ShellState *p){
2374 sqlite3_free(p->aiIndent);
2375 p->aiIndent = 0;
2376 p->nIndent = 0;
2377 p->iIndent = 0;
2381 ** Disable and restore .wheretrace and .selecttrace settings.
2383 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2384 extern int sqlite3SelectTrace;
2385 static int savedSelectTrace;
2386 #endif
2387 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2388 extern int sqlite3WhereTrace;
2389 static int savedWhereTrace;
2390 #endif
2391 static void disable_debug_trace_modes(void){
2392 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2393 savedSelectTrace = sqlite3SelectTrace;
2394 sqlite3SelectTrace = 0;
2395 #endif
2396 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2397 savedWhereTrace = sqlite3WhereTrace;
2398 sqlite3WhereTrace = 0;
2399 #endif
2401 static void restore_debug_trace_modes(void){
2402 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2403 sqlite3SelectTrace = savedSelectTrace;
2404 #endif
2405 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2406 sqlite3WhereTrace = savedWhereTrace;
2407 #endif
2411 ** Run a prepared statement
2413 static void exec_prepared_stmt(
2414 ShellState *pArg, /* Pointer to ShellState */
2415 sqlite3_stmt *pStmt, /* Statment to run */
2416 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2418 int rc;
2420 /* perform the first step. this will tell us if we
2421 ** have a result set or not and how wide it is.
2423 rc = sqlite3_step(pStmt);
2424 /* if we have a result set... */
2425 if( SQLITE_ROW == rc ){
2426 /* if we have a callback... */
2427 if( xCallback ){
2428 /* allocate space for col name ptr, value ptr, and type */
2429 int nCol = sqlite3_column_count(pStmt);
2430 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2431 if( !pData ){
2432 rc = SQLITE_NOMEM;
2433 }else{
2434 char **azCols = (char **)pData; /* Names of result columns */
2435 char **azVals = &azCols[nCol]; /* Results */
2436 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2437 int i, x;
2438 assert(sizeof(int) <= sizeof(char *));
2439 /* save off ptrs to column names */
2440 for(i=0; i<nCol; i++){
2441 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2444 /* extract the data and data types */
2445 for(i=0; i<nCol; i++){
2446 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2447 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2448 azVals[i] = "";
2449 }else{
2450 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2452 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2453 rc = SQLITE_NOMEM;
2454 break; /* from for */
2456 } /* end for */
2458 /* if data and types extracted successfully... */
2459 if( SQLITE_ROW == rc ){
2460 /* call the supplied callback with the result row data */
2461 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2462 rc = SQLITE_ABORT;
2463 }else{
2464 rc = sqlite3_step(pStmt);
2467 } while( SQLITE_ROW == rc );
2468 sqlite3_free(pData);
2470 }else{
2472 rc = sqlite3_step(pStmt);
2473 } while( rc == SQLITE_ROW );
2478 #ifndef SQLITE_OMIT_VIRTUALTABLE
2480 ** This function is called to process SQL if the previous shell command
2481 ** was ".expert". It passes the SQL in the second argument directly to
2482 ** the sqlite3expert object.
2484 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2485 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2486 ** an English language error message. It is the responsibility of the
2487 ** caller to eventually free this buffer using sqlite3_free().
2489 static int expertHandleSQL(
2490 ShellState *pState,
2491 const char *zSql,
2492 char **pzErr
2494 assert( pState->expert.pExpert );
2495 assert( pzErr==0 || *pzErr==0 );
2496 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2500 ** This function is called either to silently clean up the object
2501 ** created by the ".expert" command (if bCancel==1), or to generate a
2502 ** report from it and then clean it up (if bCancel==0).
2504 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2505 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2506 ** an English language error message. It is the responsibility of the
2507 ** caller to eventually free this buffer using sqlite3_free().
2509 static int expertFinish(
2510 ShellState *pState,
2511 int bCancel,
2512 char **pzErr
2514 int rc = SQLITE_OK;
2515 sqlite3expert *p = pState->expert.pExpert;
2516 assert( p );
2517 assert( bCancel || pzErr==0 || *pzErr==0 );
2518 if( bCancel==0 ){
2519 FILE *out = pState->out;
2520 int bVerbose = pState->expert.bVerbose;
2522 rc = sqlite3_expert_analyze(p, pzErr);
2523 if( rc==SQLITE_OK ){
2524 int nQuery = sqlite3_expert_count(p);
2525 int i;
2527 if( bVerbose ){
2528 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2529 raw_printf(out, "-- Candidates -----------------------------\n");
2530 raw_printf(out, "%s\n", zCand);
2532 for(i=0; i<nQuery; i++){
2533 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2534 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2535 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2536 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2537 if( bVerbose ){
2538 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2539 raw_printf(out, "%s\n\n", zSql);
2541 raw_printf(out, "%s\n", zIdx);
2542 raw_printf(out, "%s\n", zEQP);
2546 sqlite3_expert_destroy(p);
2547 pState->expert.pExpert = 0;
2548 return rc;
2552 ** Implementation of ".expert" dot command.
2554 static int expertDotCommand(
2555 ShellState *pState, /* Current shell tool state */
2556 char **azArg, /* Array of arguments passed to dot command */
2557 int nArg /* Number of entries in azArg[] */
2559 int rc = SQLITE_OK;
2560 char *zErr = 0;
2561 int i;
2562 int iSample = 0;
2564 assert( pState->expert.pExpert==0 );
2565 memset(&pState->expert, 0, sizeof(ExpertInfo));
2567 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2568 char *z = azArg[i];
2569 int n;
2570 if( z[0]=='-' && z[1]=='-' ) z++;
2571 n = strlen30(z);
2572 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2573 pState->expert.bVerbose = 1;
2575 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2576 if( i==(nArg-1) ){
2577 raw_printf(stderr, "option requires an argument: %s\n", z);
2578 rc = SQLITE_ERROR;
2579 }else{
2580 iSample = (int)integerValue(azArg[++i]);
2581 if( iSample<0 || iSample>100 ){
2582 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2583 rc = SQLITE_ERROR;
2587 else{
2588 raw_printf(stderr, "unknown option: %s\n", z);
2589 rc = SQLITE_ERROR;
2593 if( rc==SQLITE_OK ){
2594 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2595 if( pState->expert.pExpert==0 ){
2596 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2597 rc = SQLITE_ERROR;
2598 }else{
2599 sqlite3_expert_config(
2600 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2605 return rc;
2607 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2610 ** Execute a statement or set of statements. Print
2611 ** any result rows/columns depending on the current mode
2612 ** set via the supplied callback.
2614 ** This is very similar to SQLite's built-in sqlite3_exec()
2615 ** function except it takes a slightly different callback
2616 ** and callback data argument.
2618 static int shell_exec(
2619 sqlite3 *db, /* An open database */
2620 const char *zSql, /* SQL to be evaluated */
2621 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2622 /* (not the same as sqlite3_exec) */
2623 ShellState *pArg, /* Pointer to ShellState */
2624 char **pzErrMsg /* Error msg written here */
2626 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2627 int rc = SQLITE_OK; /* Return Code */
2628 int rc2;
2629 const char *zLeftover; /* Tail of unprocessed SQL */
2631 if( pzErrMsg ){
2632 *pzErrMsg = NULL;
2635 #ifndef SQLITE_OMIT_VIRTUALTABLE
2636 if( pArg->expert.pExpert ){
2637 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2638 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2640 #endif
2642 while( zSql[0] && (SQLITE_OK == rc) ){
2643 static const char *zStmtSql;
2644 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2645 if( SQLITE_OK != rc ){
2646 if( pzErrMsg ){
2647 *pzErrMsg = save_err_msg(db);
2649 }else{
2650 if( !pStmt ){
2651 /* this happens for a comment or white-space */
2652 zSql = zLeftover;
2653 while( IsSpace(zSql[0]) ) zSql++;
2654 continue;
2656 zStmtSql = sqlite3_sql(pStmt);
2657 if( zStmtSql==0 ) zStmtSql = "";
2658 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2660 /* save off the prepared statment handle and reset row count */
2661 if( pArg ){
2662 pArg->pStmt = pStmt;
2663 pArg->cnt = 0;
2666 /* echo the sql statement if echo on */
2667 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2668 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2671 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2672 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2673 sqlite3_stmt *pExplain;
2674 char *zEQP;
2675 int triggerEQP = 0;
2676 disable_debug_trace_modes();
2677 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2678 if( pArg->autoEQP>=AUTOEQP_trigger ){
2679 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2681 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2682 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2683 if( rc==SQLITE_OK ){
2684 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2685 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2686 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2687 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2688 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2691 sqlite3_finalize(pExplain);
2692 sqlite3_free(zEQP);
2693 if( pArg->autoEQP>=AUTOEQP_full ){
2694 /* Also do an EXPLAIN for ".eqp full" mode */
2695 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2696 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2697 if( rc==SQLITE_OK ){
2698 pArg->cMode = MODE_Explain;
2699 explain_data_prepare(pArg, pExplain);
2700 exec_prepared_stmt(pArg, pExplain, xCallback);
2701 explain_data_delete(pArg);
2703 sqlite3_finalize(pExplain);
2704 sqlite3_free(zEQP);
2706 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
2707 restore_debug_trace_modes();
2710 if( pArg ){
2711 pArg->cMode = pArg->mode;
2712 if( pArg->autoExplain
2713 && sqlite3_column_count(pStmt)==8
2714 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2716 pArg->cMode = MODE_Explain;
2719 /* If the shell is currently in ".explain" mode, gather the extra
2720 ** data required to add indents to the output.*/
2721 if( pArg->cMode==MODE_Explain ){
2722 explain_data_prepare(pArg, pStmt);
2726 exec_prepared_stmt(pArg, pStmt, xCallback);
2727 explain_data_delete(pArg);
2729 /* print usage stats if stats on */
2730 if( pArg && pArg->statsOn ){
2731 display_stats(db, pArg, 0);
2734 /* print loop-counters if required */
2735 if( pArg && pArg->scanstatsOn ){
2736 display_scanstats(db, pArg);
2739 /* Finalize the statement just executed. If this fails, save a
2740 ** copy of the error message. Otherwise, set zSql to point to the
2741 ** next statement to execute. */
2742 rc2 = sqlite3_finalize(pStmt);
2743 if( rc!=SQLITE_NOMEM ) rc = rc2;
2744 if( rc==SQLITE_OK ){
2745 zSql = zLeftover;
2746 while( IsSpace(zSql[0]) ) zSql++;
2747 }else if( pzErrMsg ){
2748 *pzErrMsg = save_err_msg(db);
2751 /* clear saved stmt handle */
2752 if( pArg ){
2753 pArg->pStmt = NULL;
2756 } /* end while */
2758 return rc;
2762 ** Release memory previously allocated by tableColumnList().
2764 static void freeColumnList(char **azCol){
2765 int i;
2766 for(i=1; azCol[i]; i++){
2767 sqlite3_free(azCol[i]);
2769 /* azCol[0] is a static string */
2770 sqlite3_free(azCol);
2774 ** Return a list of pointers to strings which are the names of all
2775 ** columns in table zTab. The memory to hold the names is dynamically
2776 ** allocated and must be released by the caller using a subsequent call
2777 ** to freeColumnList().
2779 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2780 ** value that needs to be preserved, then azCol[0] is filled in with the
2781 ** name of the rowid column.
2783 ** The first regular column in the table is azCol[1]. The list is terminated
2784 ** by an entry with azCol[i]==0.
2786 static char **tableColumnList(ShellState *p, const char *zTab){
2787 char **azCol = 0;
2788 sqlite3_stmt *pStmt;
2789 char *zSql;
2790 int nCol = 0;
2791 int nAlloc = 0;
2792 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2793 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2794 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2795 int rc;
2797 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2798 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2799 sqlite3_free(zSql);
2800 if( rc ) return 0;
2801 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2802 if( nCol>=nAlloc-2 ){
2803 nAlloc = nAlloc*2 + nCol + 10;
2804 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2805 if( azCol==0 ){
2806 raw_printf(stderr, "Error: out of memory\n");
2807 exit(1);
2810 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2811 if( sqlite3_column_int(pStmt, 5) ){
2812 nPK++;
2813 if( nPK==1
2814 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2815 "INTEGER")==0
2817 isIPK = 1;
2818 }else{
2819 isIPK = 0;
2823 sqlite3_finalize(pStmt);
2824 if( azCol==0 ) return 0;
2825 azCol[0] = 0;
2826 azCol[nCol+1] = 0;
2828 /* The decision of whether or not a rowid really needs to be preserved
2829 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2830 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2831 ** rowids on tables where the rowid is inaccessible because there are other
2832 ** columns in the table named "rowid", "_rowid_", and "oid".
2834 if( preserveRowid && isIPK ){
2835 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2836 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2837 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2838 ** ROWID aliases. To distinguish these cases, check to see if
2839 ** there is a "pk" entry in "PRAGMA index_list". There will be
2840 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2842 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2843 " WHERE origin='pk'", zTab);
2844 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2845 sqlite3_free(zSql);
2846 if( rc ){
2847 freeColumnList(azCol);
2848 return 0;
2850 rc = sqlite3_step(pStmt);
2851 sqlite3_finalize(pStmt);
2852 preserveRowid = rc==SQLITE_ROW;
2854 if( preserveRowid ){
2855 /* Only preserve the rowid if we can find a name to use for the
2856 ** rowid */
2857 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2858 int i, j;
2859 for(j=0; j<3; j++){
2860 for(i=1; i<=nCol; i++){
2861 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2863 if( i>nCol ){
2864 /* At this point, we know that azRowid[j] is not the name of any
2865 ** ordinary column in the table. Verify that azRowid[j] is a valid
2866 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2867 ** tables will fail this last check */
2868 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2869 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2870 break;
2874 return azCol;
2878 ** Toggle the reverse_unordered_selects setting.
2880 static void toggleSelectOrder(sqlite3 *db){
2881 sqlite3_stmt *pStmt = 0;
2882 int iSetting = 0;
2883 char zStmt[100];
2884 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2885 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2886 iSetting = sqlite3_column_int(pStmt, 0);
2888 sqlite3_finalize(pStmt);
2889 sqlite3_snprintf(sizeof(zStmt), zStmt,
2890 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2891 sqlite3_exec(db, zStmt, 0, 0, 0);
2895 ** This is a different callback routine used for dumping the database.
2896 ** Each row received by this callback consists of a table name,
2897 ** the table type ("index" or "table") and SQL to create the table.
2898 ** This routine should print text sufficient to recreate the table.
2900 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2901 int rc;
2902 const char *zTable;
2903 const char *zType;
2904 const char *zSql;
2905 ShellState *p = (ShellState *)pArg;
2907 UNUSED_PARAMETER(azNotUsed);
2908 if( nArg!=3 || azArg==0 ) return 0;
2909 zTable = azArg[0];
2910 zType = azArg[1];
2911 zSql = azArg[2];
2913 if( strcmp(zTable, "sqlite_sequence")==0 ){
2914 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2915 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2916 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2917 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2918 return 0;
2919 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2920 char *zIns;
2921 if( !p->writableSchema ){
2922 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2923 p->writableSchema = 1;
2925 zIns = sqlite3_mprintf(
2926 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2927 "VALUES('table','%q','%q',0,'%q');",
2928 zTable, zTable, zSql);
2929 utf8_printf(p->out, "%s\n", zIns);
2930 sqlite3_free(zIns);
2931 return 0;
2932 }else{
2933 printSchemaLine(p->out, zSql, ";\n");
2936 if( strcmp(zType, "table")==0 ){
2937 ShellText sSelect;
2938 ShellText sTable;
2939 char **azCol;
2940 int i;
2941 char *savedDestTable;
2942 int savedMode;
2944 azCol = tableColumnList(p, zTable);
2945 if( azCol==0 ){
2946 p->nErr++;
2947 return 0;
2950 /* Always quote the table name, even if it appears to be pure ascii,
2951 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2952 initText(&sTable);
2953 appendText(&sTable, zTable, quoteChar(zTable));
2954 /* If preserving the rowid, add a column list after the table name.
2955 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2956 ** instead of the usual "INSERT INTO tab VALUES(...)".
2958 if( azCol[0] ){
2959 appendText(&sTable, "(", 0);
2960 appendText(&sTable, azCol[0], 0);
2961 for(i=1; azCol[i]; i++){
2962 appendText(&sTable, ",", 0);
2963 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2965 appendText(&sTable, ")", 0);
2968 /* Build an appropriate SELECT statement */
2969 initText(&sSelect);
2970 appendText(&sSelect, "SELECT ", 0);
2971 if( azCol[0] ){
2972 appendText(&sSelect, azCol[0], 0);
2973 appendText(&sSelect, ",", 0);
2975 for(i=1; azCol[i]; i++){
2976 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2977 if( azCol[i+1] ){
2978 appendText(&sSelect, ",", 0);
2981 freeColumnList(azCol);
2982 appendText(&sSelect, " FROM ", 0);
2983 appendText(&sSelect, zTable, quoteChar(zTable));
2985 savedDestTable = p->zDestTable;
2986 savedMode = p->mode;
2987 p->zDestTable = sTable.z;
2988 p->mode = p->cMode = MODE_Insert;
2989 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2990 if( (rc&0xff)==SQLITE_CORRUPT ){
2991 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2992 toggleSelectOrder(p->db);
2993 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2994 toggleSelectOrder(p->db);
2996 p->zDestTable = savedDestTable;
2997 p->mode = savedMode;
2998 freeText(&sTable);
2999 freeText(&sSelect);
3000 if( rc ) p->nErr++;
3002 return 0;
3006 ** Run zQuery. Use dump_callback() as the callback routine so that
3007 ** the contents of the query are output as SQL statements.
3009 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3010 ** "ORDER BY rowid DESC" to the end.
3012 static int run_schema_dump_query(
3013 ShellState *p,
3014 const char *zQuery
3016 int rc;
3017 char *zErr = 0;
3018 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3019 if( rc==SQLITE_CORRUPT ){
3020 char *zQ2;
3021 int len = strlen30(zQuery);
3022 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3023 if( zErr ){
3024 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3025 sqlite3_free(zErr);
3026 zErr = 0;
3028 zQ2 = malloc( len+100 );
3029 if( zQ2==0 ) return rc;
3030 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3031 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3032 if( rc ){
3033 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3034 }else{
3035 rc = SQLITE_CORRUPT;
3037 sqlite3_free(zErr);
3038 free(zQ2);
3040 return rc;
3044 ** Text of a help message
3046 static char zHelp[] =
3047 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3048 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3049 #endif
3050 #ifndef SQLITE_OMIT_AUTHORIZATION
3051 ".auth ON|OFF Show authorizer callbacks\n"
3052 #endif
3053 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3054 ".bail on|off Stop after hitting an error. Default OFF\n"
3055 ".binary on|off Turn binary output on or off. Default OFF\n"
3056 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3057 ".changes on|off Show number of rows changed by SQL\n"
3058 ".check GLOB Fail if output since .testcase does not match\n"
3059 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3060 ".databases List names and files of attached databases\n"
3061 ".dbinfo ?DB? Show status information about the database\n"
3062 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3063 " If TABLE specified, only dump tables matching\n"
3064 " LIKE pattern TABLE.\n"
3065 ".echo on|off Turn command echo on or off\n"
3066 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3067 ".exit Exit this program\n"
3068 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
3069 /* Because explain mode comes on automatically now, the ".explain" mode
3070 ** is removed from the help screen. It is still supported for legacy, however */
3071 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3072 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3073 ".headers on|off Turn display of headers on or off\n"
3074 ".help Show this message\n"
3075 ".import FILE TABLE Import data from FILE into TABLE\n"
3076 #ifndef SQLITE_OMIT_TEST_CONTROL
3077 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3078 #endif
3079 ".indexes ?TABLE? Show names of all indexes\n"
3080 " If TABLE specified, only show indexes for tables\n"
3081 " matching LIKE pattern TABLE.\n"
3082 #ifdef SQLITE_ENABLE_IOTRACE
3083 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3084 #endif
3085 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3086 ".lint OPTIONS Report potential schema issues. Options:\n"
3087 " fkey-indexes Find missing foreign key indexes\n"
3088 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3089 ".load FILE ?ENTRY? Load an extension library\n"
3090 #endif
3091 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3092 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3093 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3094 " csv Comma-separated values\n"
3095 " column Left-aligned columns. (See .width)\n"
3096 " html HTML <table> code\n"
3097 " insert SQL insert statements for TABLE\n"
3098 " line One value per line\n"
3099 " list Values delimited by \"|\"\n"
3100 " quote Escape answers as for SQL\n"
3101 " tabs Tab-separated values\n"
3102 " tcl TCL list elements\n"
3103 ".nullvalue STRING Use STRING in place of NULL values\n"
3104 ".once FILENAME Output for the next SQL command only to FILENAME\n"
3105 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3106 " The --new option starts with an empty file\n"
3107 ".output ?FILENAME? Send output to FILENAME or stdout\n"
3108 ".print STRING... Print literal STRING\n"
3109 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3110 ".quit Exit this program\n"
3111 ".read FILENAME Execute SQL in FILENAME\n"
3112 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3113 ".save FILE Write in-memory database into FILE\n"
3114 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3115 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3116 " Add --indent for pretty-printing\n"
3117 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3118 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3119 " separator for both the output mode and .import\n"
3120 #if defined(SQLITE_ENABLE_SESSION)
3121 ".session CMD ... Create or control sessions\n"
3122 #endif
3123 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3124 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3125 ".show Show the current values for various settings\n"
3126 ".stats ?on|off? Show stats or turn stats on or off\n"
3127 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3128 ".tables ?TABLE? List names of tables\n"
3129 " If TABLE specified, only list tables matching\n"
3130 " LIKE pattern TABLE.\n"
3131 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3132 ".timeout MS Try opening locked tables for MS milliseconds\n"
3133 ".timer on|off Turn SQL timer on or off\n"
3134 ".trace FILE|off Output each SQL statement as it is run\n"
3135 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3136 ".vfslist List all available VFSes\n"
3137 ".vfsname ?AUX? Print the name of the VFS stack\n"
3138 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3139 " Negative values right-justify\n"
3142 #if defined(SQLITE_ENABLE_SESSION)
3144 ** Print help information for the ".sessions" command
3146 void session_help(ShellState *p){
3147 raw_printf(p->out,
3148 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3149 "If ?NAME? is omitted, the first defined session is used.\n"
3150 "Subcommands:\n"
3151 " attach TABLE Attach TABLE\n"
3152 " changeset FILE Write a changeset into FILE\n"
3153 " close Close one session\n"
3154 " enable ?BOOLEAN? Set or query the enable bit\n"
3155 " filter GLOB... Reject tables matching GLOBs\n"
3156 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3157 " isempty Query whether the session is empty\n"
3158 " list List currently open session names\n"
3159 " open DB NAME Open a new session on DB\n"
3160 " patchset FILE Write a patchset into FILE\n"
3163 #endif
3166 /* Forward reference */
3167 static int process_input(ShellState *p, FILE *in);
3170 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3171 ** and return a pointer to the buffer. The caller is responsible for freeing
3172 ** the memory.
3174 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3175 ** read.
3177 ** For convenience, a nul-terminator byte is always appended to the data read
3178 ** from the file before the buffer is returned. This byte is not included in
3179 ** the final value of (*pnByte), if applicable.
3181 ** NULL is returned if any error is encountered. The final value of *pnByte
3182 ** is undefined in this case.
3184 static char *readFile(const char *zName, int *pnByte){
3185 FILE *in = fopen(zName, "rb");
3186 long nIn;
3187 size_t nRead;
3188 char *pBuf;
3189 if( in==0 ) return 0;
3190 fseek(in, 0, SEEK_END);
3191 nIn = ftell(in);
3192 rewind(in);
3193 pBuf = sqlite3_malloc64( nIn+1 );
3194 if( pBuf==0 ) return 0;
3195 nRead = fread(pBuf, nIn, 1, in);
3196 fclose(in);
3197 if( nRead!=1 ){
3198 sqlite3_free(pBuf);
3199 return 0;
3201 pBuf[nIn] = 0;
3202 if( pnByte ) *pnByte = nIn;
3203 return pBuf;
3206 #if defined(SQLITE_ENABLE_SESSION)
3208 ** Close a single OpenSession object and release all of its associated
3209 ** resources.
3211 static void session_close(OpenSession *pSession){
3212 int i;
3213 sqlite3session_delete(pSession->p);
3214 sqlite3_free(pSession->zName);
3215 for(i=0; i<pSession->nFilter; i++){
3216 sqlite3_free(pSession->azFilter[i]);
3218 sqlite3_free(pSession->azFilter);
3219 memset(pSession, 0, sizeof(OpenSession));
3221 #endif
3224 ** Close all OpenSession objects and release all associated resources.
3226 #if defined(SQLITE_ENABLE_SESSION)
3227 static void session_close_all(ShellState *p){
3228 int i;
3229 for(i=0; i<p->nSession; i++){
3230 session_close(&p->aSession[i]);
3232 p->nSession = 0;
3234 #else
3235 # define session_close_all(X)
3236 #endif
3239 ** Implementation of the xFilter function for an open session. Omit
3240 ** any tables named by ".session filter" but let all other table through.
3242 #if defined(SQLITE_ENABLE_SESSION)
3243 static int session_filter(void *pCtx, const char *zTab){
3244 OpenSession *pSession = (OpenSession*)pCtx;
3245 int i;
3246 for(i=0; i<pSession->nFilter; i++){
3247 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3249 return 1;
3251 #endif
3254 ** Try to deduce the type of file for zName based on its content. Return
3255 ** one of the SHELL_OPEN_* constants.
3257 static int deduceDatabaseType(const char *zName){
3258 FILE *f = fopen(zName, "rb");
3259 size_t n;
3260 int rc = SHELL_OPEN_UNSPEC;
3261 char zBuf[100];
3262 if( f==0 ) return SHELL_OPEN_NORMAL;
3263 fseek(f, -25, SEEK_END);
3264 n = fread(zBuf, 25, 1, f);
3265 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3266 rc = SHELL_OPEN_APPENDVFS;
3267 }else{
3268 fseek(f, -22, SEEK_END);
3269 n = fread(zBuf, 22, 1, f);
3270 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3271 && zBuf[3]==0x06 ){
3272 rc = SHELL_OPEN_ZIPFILE;
3275 fclose(f);
3276 return rc;
3280 ** Make sure the database is open. If it is not, then open it. If
3281 ** the database fails to open, print an error message and exit.
3283 static void open_db(ShellState *p, int keepAlive){
3284 if( p->db==0 ){
3285 sqlite3_initialize();
3286 if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){
3287 p->openMode = deduceDatabaseType(p->zDbFilename);
3289 switch( p->openMode ){
3290 case SHELL_OPEN_APPENDVFS: {
3291 sqlite3_open_v2(p->zDbFilename, &p->db,
3292 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3293 break;
3295 case SHELL_OPEN_ZIPFILE: {
3296 sqlite3_open(":memory:", &p->db);
3297 break;
3299 case SHELL_OPEN_UNSPEC:
3300 case SHELL_OPEN_NORMAL: {
3301 sqlite3_open(p->zDbFilename, &p->db);
3302 break;
3305 globalDb = p->db;
3306 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3307 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3308 p->zDbFilename, sqlite3_errmsg(p->db));
3309 if( keepAlive ) return;
3310 exit(1);
3312 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3313 sqlite3_enable_load_extension(p->db, 1);
3314 #endif
3315 sqlite3_fileio_init(p->db, 0, 0);
3316 sqlite3_shathree_init(p->db, 0, 0);
3317 sqlite3_completion_init(p->db, 0, 0);
3318 #ifdef SQLITE_HAVE_ZLIB
3319 sqlite3_zipfile_init(p->db, 0, 0);
3320 sqlite3_sqlar_init(p->db, 0, 0);
3321 #endif
3322 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
3323 shellAddSchemaName, 0, 0);
3324 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3325 shellModuleSchema, 0, 0);
3326 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3327 shellPutsFunc, 0, 0);
3328 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3329 char *zSql = sqlite3_mprintf(
3330 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3331 sqlite3_exec(p->db, zSql, 0, 0, 0);
3332 sqlite3_free(zSql);
3337 #if HAVE_READLINE || HAVE_EDITLINE
3339 ** Readline completion callbacks
3341 static char *readline_completion_generator(const char *text, int state){
3342 static sqlite3_stmt *pStmt = 0;
3343 char *zRet;
3344 if( state==0 ){
3345 char *zSql;
3346 sqlite3_finalize(pStmt);
3347 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3348 " FROM completion(%Q) ORDER BY 1", text);
3349 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3350 sqlite3_free(zSql);
3352 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3353 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
3354 }else{
3355 sqlite3_finalize(pStmt);
3356 pStmt = 0;
3357 zRet = 0;
3359 return zRet;
3361 static char **readline_completion(const char *zText, int iStart, int iEnd){
3362 rl_attempted_completion_over = 1;
3363 return rl_completion_matches(zText, readline_completion_generator);
3366 #elif HAVE_LINENOISE
3368 ** Linenoise completion callback
3370 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
3371 int nLine = strlen30(zLine);
3372 int i, iStart;
3373 sqlite3_stmt *pStmt = 0;
3374 char *zSql;
3375 char zBuf[1000];
3377 if( nLine>sizeof(zBuf)-30 ) return;
3378 if( zLine[0]=='.' ) return;
3379 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3380 if( i==nLine-1 ) return;
3381 iStart = i+1;
3382 memcpy(zBuf, zLine, iStart);
3383 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3384 " FROM completion(%Q,%Q) ORDER BY 1",
3385 &zLine[iStart], zLine);
3386 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3387 sqlite3_free(zSql);
3388 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3389 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3390 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3391 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3392 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3393 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3394 linenoiseAddCompletion(lc, zBuf);
3397 sqlite3_finalize(pStmt);
3399 #endif
3402 ** Do C-language style dequoting.
3404 ** \a -> alarm
3405 ** \b -> backspace
3406 ** \t -> tab
3407 ** \n -> newline
3408 ** \v -> vertical tab
3409 ** \f -> form feed
3410 ** \r -> carriage return
3411 ** \s -> space
3412 ** \" -> "
3413 ** \' -> '
3414 ** \\ -> backslash
3415 ** \NNN -> ascii character NNN in octal
3417 static void resolve_backslashes(char *z){
3418 int i, j;
3419 char c;
3420 while( *z && *z!='\\' ) z++;
3421 for(i=j=0; (c = z[i])!=0; i++, j++){
3422 if( c=='\\' && z[i+1]!=0 ){
3423 c = z[++i];
3424 if( c=='a' ){
3425 c = '\a';
3426 }else if( c=='b' ){
3427 c = '\b';
3428 }else if( c=='t' ){
3429 c = '\t';
3430 }else if( c=='n' ){
3431 c = '\n';
3432 }else if( c=='v' ){
3433 c = '\v';
3434 }else if( c=='f' ){
3435 c = '\f';
3436 }else if( c=='r' ){
3437 c = '\r';
3438 }else if( c=='"' ){
3439 c = '"';
3440 }else if( c=='\'' ){
3441 c = '\'';
3442 }else if( c=='\\' ){
3443 c = '\\';
3444 }else if( c>='0' && c<='7' ){
3445 c -= '0';
3446 if( z[i+1]>='0' && z[i+1]<='7' ){
3447 i++;
3448 c = (c<<3) + z[i] - '0';
3449 if( z[i+1]>='0' && z[i+1]<='7' ){
3450 i++;
3451 c = (c<<3) + z[i] - '0';
3456 z[j] = c;
3458 if( j<i ) z[j] = 0;
3462 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3463 ** for TRUE and FALSE. Return the integer value if appropriate.
3465 static int booleanValue(const char *zArg){
3466 int i;
3467 if( zArg[0]=='0' && zArg[1]=='x' ){
3468 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3469 }else{
3470 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3472 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3473 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3474 return 1;
3476 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3477 return 0;
3479 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3480 zArg);
3481 return 0;
3485 ** Set or clear a shell flag according to a boolean value.
3487 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3488 if( booleanValue(zArg) ){
3489 ShellSetFlag(p, mFlag);
3490 }else{
3491 ShellClearFlag(p, mFlag);
3496 ** Close an output file, assuming it is not stderr or stdout
3498 static void output_file_close(FILE *f){
3499 if( f && f!=stdout && f!=stderr ) fclose(f);
3503 ** Try to open an output file. The names "stdout" and "stderr" are
3504 ** recognized and do the right thing. NULL is returned if the output
3505 ** filename is "off".
3507 static FILE *output_file_open(const char *zFile){
3508 FILE *f;
3509 if( strcmp(zFile,"stdout")==0 ){
3510 f = stdout;
3511 }else if( strcmp(zFile, "stderr")==0 ){
3512 f = stderr;
3513 }else if( strcmp(zFile, "off")==0 ){
3514 f = 0;
3515 }else{
3516 f = fopen(zFile, "wb");
3517 if( f==0 ){
3518 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3521 return f;
3524 #if !defined(SQLITE_UNTESTABLE)
3525 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3527 ** A routine for handling output from sqlite3_trace().
3529 static int sql_trace_callback(
3530 unsigned mType,
3531 void *pArg,
3532 void *pP,
3533 void *pX
3535 FILE *f = (FILE*)pArg;
3536 UNUSED_PARAMETER(mType);
3537 UNUSED_PARAMETER(pP);
3538 if( f ){
3539 const char *z = (const char*)pX;
3540 int i = strlen30(z);
3541 while( i>0 && z[i-1]==';' ){ i--; }
3542 utf8_printf(f, "%.*s;\n", i, z);
3544 return 0;
3546 #endif
3547 #endif
3550 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3551 ** a useful spot to set a debugger breakpoint.
3553 static void test_breakpoint(void){
3554 static int nCall = 0;
3555 nCall++;
3559 ** An object used to read a CSV and other files for import.
3561 typedef struct ImportCtx ImportCtx;
3562 struct ImportCtx {
3563 const char *zFile; /* Name of the input file */
3564 FILE *in; /* Read the CSV text from this input stream */
3565 char *z; /* Accumulated text for a field */
3566 int n; /* Number of bytes in z */
3567 int nAlloc; /* Space allocated for z[] */
3568 int nLine; /* Current line number */
3569 int bNotFirst; /* True if one or more bytes already read */
3570 int cTerm; /* Character that terminated the most recent field */
3571 int cColSep; /* The column separator character. (Usually ",") */
3572 int cRowSep; /* The row separator character. (Usually "\n") */
3575 /* Append a single byte to z[] */
3576 static void import_append_char(ImportCtx *p, int c){
3577 if( p->n+1>=p->nAlloc ){
3578 p->nAlloc += p->nAlloc + 100;
3579 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3580 if( p->z==0 ){
3581 raw_printf(stderr, "out of memory\n");
3582 exit(1);
3585 p->z[p->n++] = (char)c;
3588 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3589 ** with the option of having a separator other than ",".
3591 ** + Input comes from p->in.
3592 ** + Store results in p->z of length p->n. Space to hold p->z comes
3593 ** from sqlite3_malloc64().
3594 ** + Use p->cSep as the column separator. The default is ",".
3595 ** + Use p->rSep as the row separator. The default is "\n".
3596 ** + Keep track of the line number in p->nLine.
3597 ** + Store the character that terminates the field in p->cTerm. Store
3598 ** EOF on end-of-file.
3599 ** + Report syntax errors on stderr
3601 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3602 int c;
3603 int cSep = p->cColSep;
3604 int rSep = p->cRowSep;
3605 p->n = 0;
3606 c = fgetc(p->in);
3607 if( c==EOF || seenInterrupt ){
3608 p->cTerm = EOF;
3609 return 0;
3611 if( c=='"' ){
3612 int pc, ppc;
3613 int startLine = p->nLine;
3614 int cQuote = c;
3615 pc = ppc = 0;
3616 while( 1 ){
3617 c = fgetc(p->in);
3618 if( c==rSep ) p->nLine++;
3619 if( c==cQuote ){
3620 if( pc==cQuote ){
3621 pc = 0;
3622 continue;
3625 if( (c==cSep && pc==cQuote)
3626 || (c==rSep && pc==cQuote)
3627 || (c==rSep && pc=='\r' && ppc==cQuote)
3628 || (c==EOF && pc==cQuote)
3630 do{ p->n--; }while( p->z[p->n]!=cQuote );
3631 p->cTerm = c;
3632 break;
3634 if( pc==cQuote && c!='\r' ){
3635 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3636 p->zFile, p->nLine, cQuote);
3638 if( c==EOF ){
3639 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3640 p->zFile, startLine, cQuote);
3641 p->cTerm = c;
3642 break;
3644 import_append_char(p, c);
3645 ppc = pc;
3646 pc = c;
3648 }else{
3649 /* If this is the first field being parsed and it begins with the
3650 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3651 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3652 import_append_char(p, c);
3653 c = fgetc(p->in);
3654 if( (c&0xff)==0xbb ){
3655 import_append_char(p, c);
3656 c = fgetc(p->in);
3657 if( (c&0xff)==0xbf ){
3658 p->bNotFirst = 1;
3659 p->n = 0;
3660 return csv_read_one_field(p);
3664 while( c!=EOF && c!=cSep && c!=rSep ){
3665 import_append_char(p, c);
3666 c = fgetc(p->in);
3668 if( c==rSep ){
3669 p->nLine++;
3670 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3672 p->cTerm = c;
3674 if( p->z ) p->z[p->n] = 0;
3675 p->bNotFirst = 1;
3676 return p->z;
3679 /* Read a single field of ASCII delimited text.
3681 ** + Input comes from p->in.
3682 ** + Store results in p->z of length p->n. Space to hold p->z comes
3683 ** from sqlite3_malloc64().
3684 ** + Use p->cSep as the column separator. The default is "\x1F".
3685 ** + Use p->rSep as the row separator. The default is "\x1E".
3686 ** + Keep track of the row number in p->nLine.
3687 ** + Store the character that terminates the field in p->cTerm. Store
3688 ** EOF on end-of-file.
3689 ** + Report syntax errors on stderr
3691 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3692 int c;
3693 int cSep = p->cColSep;
3694 int rSep = p->cRowSep;
3695 p->n = 0;
3696 c = fgetc(p->in);
3697 if( c==EOF || seenInterrupt ){
3698 p->cTerm = EOF;
3699 return 0;
3701 while( c!=EOF && c!=cSep && c!=rSep ){
3702 import_append_char(p, c);
3703 c = fgetc(p->in);
3705 if( c==rSep ){
3706 p->nLine++;
3708 p->cTerm = c;
3709 if( p->z ) p->z[p->n] = 0;
3710 return p->z;
3714 ** Try to transfer data for table zTable. If an error is seen while
3715 ** moving forward, try to go backwards. The backwards movement won't
3716 ** work for WITHOUT ROWID tables.
3718 static void tryToCloneData(
3719 ShellState *p,
3720 sqlite3 *newDb,
3721 const char *zTable
3723 sqlite3_stmt *pQuery = 0;
3724 sqlite3_stmt *pInsert = 0;
3725 char *zQuery = 0;
3726 char *zInsert = 0;
3727 int rc;
3728 int i, j, n;
3729 int nTable = strlen30(zTable);
3730 int k = 0;
3731 int cnt = 0;
3732 const int spinRate = 10000;
3734 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3735 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3736 if( rc ){
3737 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3738 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3739 zQuery);
3740 goto end_data_xfer;
3742 n = sqlite3_column_count(pQuery);
3743 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3744 if( zInsert==0 ){
3745 raw_printf(stderr, "out of memory\n");
3746 goto end_data_xfer;
3748 sqlite3_snprintf(200+nTable,zInsert,
3749 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3750 i = strlen30(zInsert);
3751 for(j=1; j<n; j++){
3752 memcpy(zInsert+i, ",?", 2);
3753 i += 2;
3755 memcpy(zInsert+i, ");", 3);
3756 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3757 if( rc ){
3758 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3759 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3760 zQuery);
3761 goto end_data_xfer;
3763 for(k=0; k<2; k++){
3764 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3765 for(i=0; i<n; i++){
3766 switch( sqlite3_column_type(pQuery, i) ){
3767 case SQLITE_NULL: {
3768 sqlite3_bind_null(pInsert, i+1);
3769 break;
3771 case SQLITE_INTEGER: {
3772 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3773 break;
3775 case SQLITE_FLOAT: {
3776 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3777 break;
3779 case SQLITE_TEXT: {
3780 sqlite3_bind_text(pInsert, i+1,
3781 (const char*)sqlite3_column_text(pQuery,i),
3782 -1, SQLITE_STATIC);
3783 break;
3785 case SQLITE_BLOB: {
3786 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3787 sqlite3_column_bytes(pQuery,i),
3788 SQLITE_STATIC);
3789 break;
3792 } /* End for */
3793 rc = sqlite3_step(pInsert);
3794 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3795 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3796 sqlite3_errmsg(newDb));
3798 sqlite3_reset(pInsert);
3799 cnt++;
3800 if( (cnt%spinRate)==0 ){
3801 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3802 fflush(stdout);
3804 } /* End while */
3805 if( rc==SQLITE_DONE ) break;
3806 sqlite3_finalize(pQuery);
3807 sqlite3_free(zQuery);
3808 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3809 zTable);
3810 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3811 if( rc ){
3812 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3813 break;
3815 } /* End for(k=0...) */
3817 end_data_xfer:
3818 sqlite3_finalize(pQuery);
3819 sqlite3_finalize(pInsert);
3820 sqlite3_free(zQuery);
3821 sqlite3_free(zInsert);
3826 ** Try to transfer all rows of the schema that match zWhere. For
3827 ** each row, invoke xForEach() on the object defined by that row.
3828 ** If an error is encountered while moving forward through the
3829 ** sqlite_master table, try again moving backwards.
3831 static void tryToCloneSchema(
3832 ShellState *p,
3833 sqlite3 *newDb,
3834 const char *zWhere,
3835 void (*xForEach)(ShellState*,sqlite3*,const char*)
3837 sqlite3_stmt *pQuery = 0;
3838 char *zQuery = 0;
3839 int rc;
3840 const unsigned char *zName;
3841 const unsigned char *zSql;
3842 char *zErrMsg = 0;
3844 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3845 " WHERE %s", zWhere);
3846 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3847 if( rc ){
3848 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3849 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3850 zQuery);
3851 goto end_schema_xfer;
3853 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3854 zName = sqlite3_column_text(pQuery, 0);
3855 zSql = sqlite3_column_text(pQuery, 1);
3856 printf("%s... ", zName); fflush(stdout);
3857 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3858 if( zErrMsg ){
3859 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3860 sqlite3_free(zErrMsg);
3861 zErrMsg = 0;
3863 if( xForEach ){
3864 xForEach(p, newDb, (const char*)zName);
3866 printf("done\n");
3868 if( rc!=SQLITE_DONE ){
3869 sqlite3_finalize(pQuery);
3870 sqlite3_free(zQuery);
3871 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3872 " WHERE %s ORDER BY rowid DESC", zWhere);
3873 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3874 if( rc ){
3875 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3876 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3877 zQuery);
3878 goto end_schema_xfer;
3880 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3881 zName = sqlite3_column_text(pQuery, 0);
3882 zSql = sqlite3_column_text(pQuery, 1);
3883 printf("%s... ", zName); fflush(stdout);
3884 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3885 if( zErrMsg ){
3886 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3887 sqlite3_free(zErrMsg);
3888 zErrMsg = 0;
3890 if( xForEach ){
3891 xForEach(p, newDb, (const char*)zName);
3893 printf("done\n");
3896 end_schema_xfer:
3897 sqlite3_finalize(pQuery);
3898 sqlite3_free(zQuery);
3902 ** Open a new database file named "zNewDb". Try to recover as much information
3903 ** as possible out of the main database (which might be corrupt) and write it
3904 ** into zNewDb.
3906 static void tryToClone(ShellState *p, const char *zNewDb){
3907 int rc;
3908 sqlite3 *newDb = 0;
3909 if( access(zNewDb,0)==0 ){
3910 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3911 return;
3913 rc = sqlite3_open(zNewDb, &newDb);
3914 if( rc ){
3915 utf8_printf(stderr, "Cannot create output database: %s\n",
3916 sqlite3_errmsg(newDb));
3917 }else{
3918 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3919 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3920 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3921 tryToCloneSchema(p, newDb, "type!='table'", 0);
3922 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3923 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3925 sqlite3_close(newDb);
3929 ** Change the output file back to stdout
3931 static void output_reset(ShellState *p){
3932 if( p->outfile[0]=='|' ){
3933 #ifndef SQLITE_OMIT_POPEN
3934 pclose(p->out);
3935 #endif
3936 }else{
3937 output_file_close(p->out);
3939 p->outfile[0] = 0;
3940 p->out = stdout;
3944 ** Run an SQL command and return the single integer result.
3946 static int db_int(ShellState *p, const char *zSql){
3947 sqlite3_stmt *pStmt;
3948 int res = 0;
3949 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3950 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3951 res = sqlite3_column_int(pStmt,0);
3953 sqlite3_finalize(pStmt);
3954 return res;
3958 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3960 static unsigned int get2byteInt(unsigned char *a){
3961 return (a[0]<<8) + a[1];
3963 static unsigned int get4byteInt(unsigned char *a){
3964 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3968 ** Implementation of the ".info" command.
3970 ** Return 1 on error, 2 to exit, and 0 otherwise.
3972 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3973 static const struct { const char *zName; int ofst; } aField[] = {
3974 { "file change counter:", 24 },
3975 { "database page count:", 28 },
3976 { "freelist page count:", 36 },
3977 { "schema cookie:", 40 },
3978 { "schema format:", 44 },
3979 { "default cache size:", 48 },
3980 { "autovacuum top root:", 52 },
3981 { "incremental vacuum:", 64 },
3982 { "text encoding:", 56 },
3983 { "user version:", 60 },
3984 { "application id:", 68 },
3985 { "software version:", 96 },
3987 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3988 { "number of tables:",
3989 "SELECT count(*) FROM %s WHERE type='table'" },
3990 { "number of indexes:",
3991 "SELECT count(*) FROM %s WHERE type='index'" },
3992 { "number of triggers:",
3993 "SELECT count(*) FROM %s WHERE type='trigger'" },
3994 { "number of views:",
3995 "SELECT count(*) FROM %s WHERE type='view'" },
3996 { "schema size:",
3997 "SELECT total(length(sql)) FROM %s" },
3999 int i;
4000 char *zSchemaTab;
4001 char *zDb = nArg>=2 ? azArg[1] : "main";
4002 sqlite3_stmt *pStmt = 0;
4003 unsigned char aHdr[100];
4004 open_db(p, 0);
4005 if( p->db==0 ) return 1;
4006 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4007 -1, &pStmt, 0);
4008 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4009 if( sqlite3_step(pStmt)==SQLITE_ROW
4010 && sqlite3_column_bytes(pStmt,0)>100
4012 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4013 sqlite3_finalize(pStmt);
4014 }else{
4015 raw_printf(stderr, "unable to read database header\n");
4016 sqlite3_finalize(pStmt);
4017 return 1;
4019 i = get2byteInt(aHdr+16);
4020 if( i==1 ) i = 65536;
4021 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4022 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4023 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4024 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4025 for(i=0; i<ArraySize(aField); i++){
4026 int ofst = aField[i].ofst;
4027 unsigned int val = get4byteInt(aHdr + ofst);
4028 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4029 switch( ofst ){
4030 case 56: {
4031 if( val==1 ) raw_printf(p->out, " (utf8)");
4032 if( val==2 ) raw_printf(p->out, " (utf16le)");
4033 if( val==3 ) raw_printf(p->out, " (utf16be)");
4036 raw_printf(p->out, "\n");
4038 if( zDb==0 ){
4039 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4040 }else if( strcmp(zDb,"temp")==0 ){
4041 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4042 }else{
4043 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4045 for(i=0; i<ArraySize(aQuery); i++){
4046 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4047 int val = db_int(p, zSql);
4048 sqlite3_free(zSql);
4049 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4051 sqlite3_free(zSchemaTab);
4052 return 0;
4056 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4058 static int shellDatabaseError(sqlite3 *db){
4059 const char *zErr = sqlite3_errmsg(db);
4060 utf8_printf(stderr, "Error: %s\n", zErr);
4061 return 1;
4065 ** Print an out-of-memory message to stderr and return 1.
4067 static int shellNomemError(void){
4068 raw_printf(stderr, "Error: out of memory\n");
4069 return 1;
4073 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4074 ** if they match and FALSE (0) if they do not match.
4076 ** Globbing rules:
4078 ** '*' Matches any sequence of zero or more characters.
4080 ** '?' Matches exactly one character.
4082 ** [...] Matches one character from the enclosed list of
4083 ** characters.
4085 ** [^...] Matches one character not in the enclosed list.
4087 ** '#' Matches any sequence of one or more digits with an
4088 ** optional + or - sign in front
4090 ** ' ' Any span of whitespace matches any other span of
4091 ** whitespace.
4093 ** Extra whitespace at the end of z[] is ignored.
4095 static int testcase_glob(const char *zGlob, const char *z){
4096 int c, c2;
4097 int invert;
4098 int seen;
4100 while( (c = (*(zGlob++)))!=0 ){
4101 if( IsSpace(c) ){
4102 if( !IsSpace(*z) ) return 0;
4103 while( IsSpace(*zGlob) ) zGlob++;
4104 while( IsSpace(*z) ) z++;
4105 }else if( c=='*' ){
4106 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4107 if( c=='?' && (*(z++))==0 ) return 0;
4109 if( c==0 ){
4110 return 1;
4111 }else if( c=='[' ){
4112 while( *z && testcase_glob(zGlob-1,z)==0 ){
4113 z++;
4115 return (*z)!=0;
4117 while( (c2 = (*(z++)))!=0 ){
4118 while( c2!=c ){
4119 c2 = *(z++);
4120 if( c2==0 ) return 0;
4122 if( testcase_glob(zGlob,z) ) return 1;
4124 return 0;
4125 }else if( c=='?' ){
4126 if( (*(z++))==0 ) return 0;
4127 }else if( c=='[' ){
4128 int prior_c = 0;
4129 seen = 0;
4130 invert = 0;
4131 c = *(z++);
4132 if( c==0 ) return 0;
4133 c2 = *(zGlob++);
4134 if( c2=='^' ){
4135 invert = 1;
4136 c2 = *(zGlob++);
4138 if( c2==']' ){
4139 if( c==']' ) seen = 1;
4140 c2 = *(zGlob++);
4142 while( c2 && c2!=']' ){
4143 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4144 c2 = *(zGlob++);
4145 if( c>=prior_c && c<=c2 ) seen = 1;
4146 prior_c = 0;
4147 }else{
4148 if( c==c2 ){
4149 seen = 1;
4151 prior_c = c2;
4153 c2 = *(zGlob++);
4155 if( c2==0 || (seen ^ invert)==0 ) return 0;
4156 }else if( c=='#' ){
4157 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4158 if( !IsDigit(z[0]) ) return 0;
4159 z++;
4160 while( IsDigit(z[0]) ){ z++; }
4161 }else{
4162 if( c!=(*(z++)) ) return 0;
4165 while( IsSpace(*z) ){ z++; }
4166 return *z==0;
4171 ** Compare the string as a command-line option with either one or two
4172 ** initial "-" characters.
4174 static int optionMatch(const char *zStr, const char *zOpt){
4175 if( zStr[0]!='-' ) return 0;
4176 zStr++;
4177 if( zStr[0]=='-' ) zStr++;
4178 return strcmp(zStr, zOpt)==0;
4182 ** Delete a file.
4184 int shellDeleteFile(const char *zFilename){
4185 int rc;
4186 #ifdef _WIN32
4187 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4188 rc = _wunlink(z);
4189 sqlite3_free(z);
4190 #else
4191 rc = unlink(zFilename);
4192 #endif
4193 return rc;
4198 ** The implementation of SQL scalar function fkey_collate_clause(), used
4199 ** by the ".lint fkey-indexes" command. This scalar function is always
4200 ** called with four arguments - the parent table name, the parent column name,
4201 ** the child table name and the child column name.
4203 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4205 ** If either of the named tables or columns do not exist, this function
4206 ** returns an empty string. An empty string is also returned if both tables
4207 ** and columns exist but have the same default collation sequence. Or,
4208 ** if both exist but the default collation sequences are different, this
4209 ** function returns the string " COLLATE <parent-collation>", where
4210 ** <parent-collation> is the default collation sequence of the parent column.
4212 static void shellFkeyCollateClause(
4213 sqlite3_context *pCtx,
4214 int nVal,
4215 sqlite3_value **apVal
4217 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4218 const char *zParent;
4219 const char *zParentCol;
4220 const char *zParentSeq;
4221 const char *zChild;
4222 const char *zChildCol;
4223 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4224 int rc;
4226 assert( nVal==4 );
4227 zParent = (const char*)sqlite3_value_text(apVal[0]);
4228 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4229 zChild = (const char*)sqlite3_value_text(apVal[2]);
4230 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4232 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4233 rc = sqlite3_table_column_metadata(
4234 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4236 if( rc==SQLITE_OK ){
4237 rc = sqlite3_table_column_metadata(
4238 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4242 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4243 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4244 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4245 sqlite3_free(z);
4251 ** The implementation of dot-command ".lint fkey-indexes".
4253 static int lintFkeyIndexes(
4254 ShellState *pState, /* Current shell tool state */
4255 char **azArg, /* Array of arguments passed to dot command */
4256 int nArg /* Number of entries in azArg[] */
4258 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4259 FILE *out = pState->out; /* Stream to write non-error output to */
4260 int bVerbose = 0; /* If -verbose is present */
4261 int bGroupByParent = 0; /* If -groupbyparent is present */
4262 int i; /* To iterate through azArg[] */
4263 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4264 int rc; /* Return code */
4265 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4268 ** This SELECT statement returns one row for each foreign key constraint
4269 ** in the schema of the main database. The column values are:
4271 ** 0. The text of an SQL statement similar to:
4273 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4275 ** This SELECT is similar to the one that the foreign keys implementation
4276 ** needs to run internally on child tables. If there is an index that can
4277 ** be used to optimize this query, then it can also be used by the FK
4278 ** implementation to optimize DELETE or UPDATE statements on the parent
4279 ** table.
4281 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4282 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4283 ** contains an index that can be used to optimize the query.
4285 ** 2. Human readable text that describes the child table and columns. e.g.
4287 ** "child_table(child_key1, child_key2)"
4289 ** 3. Human readable text that describes the parent table and columns. e.g.
4291 ** "parent_table(parent_key1, parent_key2)"
4293 ** 4. A full CREATE INDEX statement for an index that could be used to
4294 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4296 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4298 ** 5. The name of the parent table.
4300 ** These six values are used by the C logic below to generate the report.
4302 const char *zSql =
4303 "SELECT "
4304 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4305 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4306 " || fkey_collate_clause("
4307 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4308 ", "
4309 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4310 " || group_concat('*=?', ' AND ') || ')'"
4311 ", "
4312 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4313 ", "
4314 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4315 ", "
4316 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4317 " || ' ON ' || quote(s.name) || '('"
4318 " || group_concat(quote(f.[from]) ||"
4319 " fkey_collate_clause("
4320 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4321 " || ');'"
4322 ", "
4323 " f.[table] "
4324 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4325 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4326 "GROUP BY s.name, f.id "
4327 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4329 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4331 for(i=2; i<nArg; i++){
4332 int n = strlen30(azArg[i]);
4333 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4334 bVerbose = 1;
4336 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4337 bGroupByParent = 1;
4338 zIndent = " ";
4340 else{
4341 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4342 azArg[0], azArg[1]
4344 return SQLITE_ERROR;
4348 /* Register the fkey_collate_clause() SQL function */
4349 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4350 0, shellFkeyCollateClause, 0, 0
4354 if( rc==SQLITE_OK ){
4355 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4357 if( rc==SQLITE_OK ){
4358 sqlite3_bind_int(pSql, 1, bGroupByParent);
4361 if( rc==SQLITE_OK ){
4362 int rc2;
4363 char *zPrev = 0;
4364 while( SQLITE_ROW==sqlite3_step(pSql) ){
4365 int res = -1;
4366 sqlite3_stmt *pExplain = 0;
4367 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4368 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4369 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4370 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4371 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4372 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4374 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4375 if( rc!=SQLITE_OK ) break;
4376 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4377 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4378 res = (
4379 0==sqlite3_strglob(zGlob, zPlan)
4380 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4383 rc = sqlite3_finalize(pExplain);
4384 if( rc!=SQLITE_OK ) break;
4386 if( res<0 ){
4387 raw_printf(stderr, "Error: internal error");
4388 break;
4389 }else{
4390 if( bGroupByParent
4391 && (bVerbose || res==0)
4392 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4394 raw_printf(out, "-- Parent table %s\n", zParent);
4395 sqlite3_free(zPrev);
4396 zPrev = sqlite3_mprintf("%s", zParent);
4399 if( res==0 ){
4400 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4401 }else if( bVerbose ){
4402 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4403 zIndent, zFrom, zTarget
4408 sqlite3_free(zPrev);
4410 if( rc!=SQLITE_OK ){
4411 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4414 rc2 = sqlite3_finalize(pSql);
4415 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4416 rc = rc2;
4417 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4419 }else{
4420 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4423 return rc;
4427 ** Implementation of ".lint" dot command.
4429 static int lintDotCommand(
4430 ShellState *pState, /* Current shell tool state */
4431 char **azArg, /* Array of arguments passed to dot command */
4432 int nArg /* Number of entries in azArg[] */
4434 int n;
4435 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
4436 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4437 return lintFkeyIndexes(pState, azArg, nArg);
4439 usage:
4440 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4441 raw_printf(stderr, "Where sub-commands are:\n");
4442 raw_printf(stderr, " fkey-indexes\n");
4443 return SQLITE_ERROR;
4446 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4447 /*********************************************************************************
4448 ** The ".archive" or ".ar" command.
4450 static void shellPrepare(
4451 sqlite3 *db,
4452 int *pRc,
4453 const char *zSql,
4454 sqlite3_stmt **ppStmt
4456 *ppStmt = 0;
4457 if( *pRc==SQLITE_OK ){
4458 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
4459 if( rc!=SQLITE_OK ){
4460 raw_printf(stderr, "sql error: %s (%d)\n",
4461 sqlite3_errmsg(db), sqlite3_errcode(db)
4463 *pRc = rc;
4468 static void shellPreparePrintf(
4469 sqlite3 *db,
4470 int *pRc,
4471 sqlite3_stmt **ppStmt,
4472 const char *zFmt,
4475 *ppStmt = 0;
4476 if( *pRc==SQLITE_OK ){
4477 va_list ap;
4478 char *z;
4479 va_start(ap, zFmt);
4480 z = sqlite3_vmprintf(zFmt, ap);
4481 if( z==0 ){
4482 *pRc = SQLITE_NOMEM;
4483 }else{
4484 shellPrepare(db, pRc, z, ppStmt);
4485 sqlite3_free(z);
4490 static void shellFinalize(
4491 int *pRc,
4492 sqlite3_stmt *pStmt
4494 if( pStmt ){
4495 sqlite3 *db = sqlite3_db_handle(pStmt);
4496 int rc = sqlite3_finalize(pStmt);
4497 if( *pRc==SQLITE_OK ){
4498 if( rc!=SQLITE_OK ){
4499 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4501 *pRc = rc;
4506 static void shellReset(
4507 int *pRc,
4508 sqlite3_stmt *pStmt
4510 int rc = sqlite3_reset(pStmt);
4511 if( *pRc==SQLITE_OK ){
4512 if( rc!=SQLITE_OK ){
4513 sqlite3 *db = sqlite3_db_handle(pStmt);
4514 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4516 *pRc = rc;
4520 ** Structure representing a single ".ar" command.
4522 typedef struct ArCommand ArCommand;
4523 struct ArCommand {
4524 u8 eCmd; /* An AR_CMD_* value */
4525 u8 bVerbose; /* True if --verbose */
4526 u8 bZip; /* True if the archive is a ZIP */
4527 u8 bDryRun; /* True if --dry-run */
4528 u8 bAppend; /* True if --append */
4529 int nArg; /* Number of command arguments */
4530 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
4531 const char *zFile; /* --file argument, or NULL */
4532 const char *zDir; /* --directory argument, or NULL */
4533 char **azArg; /* Array of command arguments */
4534 ShellState *p; /* Shell state */
4535 sqlite3 *db; /* Database containing the archive */
4539 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4541 static int arUsage(FILE *f){
4542 raw_printf(f,
4543 "\n"
4544 "Usage: .ar [OPTION...] [FILE...]\n"
4545 "The .ar command manages sqlar archives.\n"
4546 "\n"
4547 "Examples:\n"
4548 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4549 " .ar -tf archive.sar # List members of archive.sar\n"
4550 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4551 "\n"
4552 "Each command line must feature exactly one command option:\n"
4553 " -c, --create Create a new archive\n"
4554 " -u, --update Update or add files to an existing archive\n"
4555 " -t, --list List contents of archive\n"
4556 " -x, --extract Extract files from archive\n"
4557 "\n"
4558 "And zero or more optional options:\n"
4559 " -v, --verbose Print each filename as it is processed\n"
4560 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4561 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4562 " -n, --dryrun Show the SQL that would have occurred\n"
4563 " -a, --append Append the SQLAR to an existing file\n"
4564 "\n"
4565 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4566 "\n"
4568 return SQLITE_ERROR;
4572 ** Print an error message for the .ar command to stderr and return
4573 ** SQLITE_ERROR.
4575 static int arErrorMsg(const char *zFmt, ...){
4576 va_list ap;
4577 char *z;
4578 va_start(ap, zFmt);
4579 z = sqlite3_vmprintf(zFmt, ap);
4580 va_end(ap);
4581 raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
4582 sqlite3_free(z);
4583 return SQLITE_ERROR;
4587 ** Values for ArCommand.eCmd.
4589 #define AR_CMD_CREATE 1
4590 #define AR_CMD_EXTRACT 2
4591 #define AR_CMD_LIST 3
4592 #define AR_CMD_UPDATE 4
4593 #define AR_CMD_HELP 5
4596 ** Other (non-command) switches.
4598 #define AR_SWITCH_VERBOSE 6
4599 #define AR_SWITCH_FILE 7
4600 #define AR_SWITCH_DIRECTORY 8
4601 #define AR_SWITCH_APPEND 9
4602 #define AR_SWITCH_DRYRUN 10
4604 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4605 switch( eSwitch ){
4606 case AR_CMD_CREATE:
4607 case AR_CMD_EXTRACT:
4608 case AR_CMD_LIST:
4609 case AR_CMD_UPDATE:
4610 case AR_CMD_HELP:
4611 if( pAr->eCmd ){
4612 return arErrorMsg("multiple command options");
4614 pAr->eCmd = eSwitch;
4615 break;
4617 case AR_SWITCH_DRYRUN:
4618 pAr->bDryRun = 1;
4619 break;
4620 case AR_SWITCH_VERBOSE:
4621 pAr->bVerbose = 1;
4622 break;
4623 case AR_SWITCH_APPEND:
4624 pAr->bAppend = 1;
4625 break;
4627 case AR_SWITCH_FILE:
4628 pAr->zFile = zArg;
4629 break;
4630 case AR_SWITCH_DIRECTORY:
4631 pAr->zDir = zArg;
4632 break;
4635 return SQLITE_OK;
4639 ** Parse the command line for an ".ar" command. The results are written into
4640 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4641 ** successfully, otherwise an error message is written to stderr and
4642 ** SQLITE_ERROR returned.
4644 static int arParseCommand(
4645 char **azArg, /* Array of arguments passed to dot command */
4646 int nArg, /* Number of entries in azArg[] */
4647 ArCommand *pAr /* Populate this object */
4649 struct ArSwitch {
4650 const char *zLong;
4651 char cShort;
4652 u8 eSwitch;
4653 u8 bArg;
4654 } aSwitch[] = {
4655 { "create", 'c', AR_CMD_CREATE, 0 },
4656 { "extract", 'x', AR_CMD_EXTRACT, 0 },
4657 { "list", 't', AR_CMD_LIST, 0 },
4658 { "update", 'u', AR_CMD_UPDATE, 0 },
4659 { "help", 'h', AR_CMD_HELP, 0 },
4660 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
4661 { "file", 'f', AR_SWITCH_FILE, 1 },
4662 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
4663 { "append", 'a', AR_SWITCH_APPEND, 0 },
4664 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
4666 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
4667 struct ArSwitch *pEnd = &aSwitch[nSwitch];
4669 if( nArg<=1 ){
4670 return arUsage(stderr);
4671 }else{
4672 char *z = azArg[1];
4673 memset(pAr, 0, sizeof(ArCommand));
4675 if( z[0]!='-' ){
4676 /* Traditional style [tar] invocation */
4677 int i;
4678 int iArg = 2;
4679 for(i=0; z[i]; i++){
4680 const char *zArg = 0;
4681 struct ArSwitch *pOpt;
4682 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4683 if( z[i]==pOpt->cShort ) break;
4685 if( pOpt==pEnd ){
4686 return arErrorMsg("unrecognized option: %c", z[i]);
4688 if( pOpt->bArg ){
4689 if( iArg>=nArg ){
4690 return arErrorMsg("option requires an argument: %c",z[i]);
4692 zArg = azArg[iArg++];
4694 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4696 pAr->nArg = nArg-iArg;
4697 if( pAr->nArg>0 ){
4698 pAr->azArg = &azArg[iArg];
4700 }else{
4701 /* Non-traditional invocation */
4702 int iArg;
4703 for(iArg=1; iArg<nArg; iArg++){
4704 int n;
4705 z = azArg[iArg];
4706 if( z[0]!='-' ){
4707 /* All remaining command line words are command arguments. */
4708 pAr->azArg = &azArg[iArg];
4709 pAr->nArg = nArg-iArg;
4710 break;
4712 n = strlen30(z);
4714 if( z[1]!='-' ){
4715 int i;
4716 /* One or more short options */
4717 for(i=1; i<n; i++){
4718 const char *zArg = 0;
4719 struct ArSwitch *pOpt;
4720 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4721 if( z[i]==pOpt->cShort ) break;
4723 if( pOpt==pEnd ){
4724 return arErrorMsg("unrecognized option: %c\n", z[i]);
4726 if( pOpt->bArg ){
4727 if( i<(n-1) ){
4728 zArg = &z[i+1];
4729 i = n;
4730 }else{
4731 if( iArg>=(nArg-1) ){
4732 return arErrorMsg("option requires an argument: %c\n",z[i]);
4734 zArg = azArg[++iArg];
4737 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4739 }else if( z[2]=='\0' ){
4740 /* A -- option, indicating that all remaining command line words
4741 ** are command arguments. */
4742 pAr->azArg = &azArg[iArg+1];
4743 pAr->nArg = nArg-iArg-1;
4744 break;
4745 }else{
4746 /* A long option */
4747 const char *zArg = 0; /* Argument for option, if any */
4748 struct ArSwitch *pMatch = 0; /* Matching option */
4749 struct ArSwitch *pOpt; /* Iterator */
4750 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4751 const char *zLong = pOpt->zLong;
4752 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
4753 if( pMatch ){
4754 return arErrorMsg("ambiguous option: %s",z);
4755 }else{
4756 pMatch = pOpt;
4761 if( pMatch==0 ){
4762 return arErrorMsg("unrecognized option: %s", z);
4764 if( pMatch->bArg ){
4765 if( iArg>=(nArg-1) ){
4766 return arErrorMsg("option requires an argument: %s", z);
4768 zArg = azArg[++iArg];
4770 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
4776 return SQLITE_OK;
4780 ** This function assumes that all arguments within the ArCommand.azArg[]
4781 ** array refer to archive members, as for the --extract or --list commands.
4782 ** It checks that each of them are present. If any specified file is not
4783 ** present in the archive, an error is printed to stderr and an error
4784 ** code returned. Otherwise, if all specified arguments are present in
4785 ** the archive, SQLITE_OK is returned.
4787 ** This function strips any trailing '/' characters from each argument.
4788 ** This is consistent with the way the [tar] command seems to work on
4789 ** Linux.
4791 static int arCheckEntries(ArCommand *pAr){
4792 int rc = SQLITE_OK;
4793 if( pAr->nArg ){
4794 int i, j;
4795 sqlite3_stmt *pTest = 0;
4797 shellPreparePrintf(pAr->db, &rc, &pTest,
4798 "SELECT name FROM %s WHERE name=$name",
4799 pAr->zSrcTable
4801 j = sqlite3_bind_parameter_index(pTest, "$name");
4802 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4803 char *z = pAr->azArg[i];
4804 int n = strlen30(z);
4805 int bOk = 0;
4806 while( n>0 && z[n-1]=='/' ) n--;
4807 z[n] = '\0';
4808 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
4809 if( SQLITE_ROW==sqlite3_step(pTest) ){
4810 bOk = 1;
4812 shellReset(&rc, pTest);
4813 if( rc==SQLITE_OK && bOk==0 ){
4814 utf8_printf(stderr, "not found in archive: %s\n", z);
4815 rc = SQLITE_ERROR;
4818 shellFinalize(&rc, pTest);
4820 return rc;
4824 ** Format a WHERE clause that can be used against the "sqlar" table to
4825 ** identify all archive members that match the command arguments held
4826 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
4827 ** The caller is responsible for eventually calling sqlite3_free() on
4828 ** any non-NULL (*pzWhere) value.
4830 static void arWhereClause(
4831 int *pRc,
4832 ArCommand *pAr,
4833 char **pzWhere /* OUT: New WHERE clause */
4835 char *zWhere = 0;
4836 if( *pRc==SQLITE_OK ){
4837 if( pAr->nArg==0 ){
4838 zWhere = sqlite3_mprintf("1");
4839 }else{
4840 int i;
4841 const char *zSep = "";
4842 for(i=0; i<pAr->nArg; i++){
4843 const char *z = pAr->azArg[i];
4844 zWhere = sqlite3_mprintf(
4845 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
4846 zWhere, zSep, z, strlen30(z)+1, z
4848 if( zWhere==0 ){
4849 *pRc = SQLITE_NOMEM;
4850 break;
4852 zSep = " OR ";
4856 *pzWhere = zWhere;
4860 ** Implementation of .ar "lisT" command.
4862 static int arListCommand(ArCommand *pAr){
4863 const char *zSql = "SELECT %s FROM %s WHERE %s";
4864 const char *azCols[] = {
4865 "name",
4866 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
4869 char *zWhere = 0;
4870 sqlite3_stmt *pSql = 0;
4871 int rc;
4873 rc = arCheckEntries(pAr);
4874 arWhereClause(&rc, pAr, &zWhere);
4876 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
4877 pAr->zSrcTable, zWhere);
4878 if( pAr->bDryRun ){
4879 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
4880 }else{
4881 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4882 if( pAr->bVerbose ){
4883 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
4884 sqlite3_column_text(pSql, 0),
4885 sqlite3_column_int(pSql, 1),
4886 sqlite3_column_text(pSql, 2),
4887 sqlite3_column_text(pSql, 3)
4889 }else{
4890 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
4894 shellFinalize(&rc, pSql);
4895 return rc;
4900 ** Implementation of .ar "eXtract" command.
4902 static int arExtractCommand(ArCommand *pAr){
4903 const char *zSql1 =
4904 "SELECT "
4905 " ($dir || name),"
4906 " writefile(($dir || name), %s, mode, mtime) "
4907 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
4909 const char *azExtraArg[] = {
4910 "sqlar_uncompress(data, sz)",
4911 "data"
4914 sqlite3_stmt *pSql = 0;
4915 int rc = SQLITE_OK;
4916 char *zDir = 0;
4917 char *zWhere = 0;
4918 int i, j;
4920 /* If arguments are specified, check that they actually exist within
4921 ** the archive before proceeding. And formulate a WHERE clause to
4922 ** match them. */
4923 rc = arCheckEntries(pAr);
4924 arWhereClause(&rc, pAr, &zWhere);
4926 if( rc==SQLITE_OK ){
4927 if( pAr->zDir ){
4928 zDir = sqlite3_mprintf("%s/", pAr->zDir);
4929 }else{
4930 zDir = sqlite3_mprintf("");
4932 if( zDir==0 ) rc = SQLITE_NOMEM;
4935 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
4936 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
4939 if( rc==SQLITE_OK ){
4940 j = sqlite3_bind_parameter_index(pSql, "$dir");
4941 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
4943 /* Run the SELECT statement twice. The first time, writefile() is called
4944 ** for all archive members that should be extracted. The second time,
4945 ** only for the directories. This is because the timestamps for
4946 ** extracted directories must be reset after they are populated (as
4947 ** populating them changes the timestamp). */
4948 for(i=0; i<2; i++){
4949 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
4950 sqlite3_bind_int(pSql, j, i);
4951 if( pAr->bDryRun ){
4952 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
4953 }else{
4954 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4955 if( i==0 && pAr->bVerbose ){
4956 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
4960 shellReset(&rc, pSql);
4962 shellFinalize(&rc, pSql);
4965 sqlite3_free(zDir);
4966 sqlite3_free(zWhere);
4967 return rc;
4971 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
4973 static int arExecSql(ArCommand *pAr, const char *zSql){
4974 int rc;
4975 if( pAr->bDryRun ){
4976 utf8_printf(pAr->p->out, "%s\n", zSql);
4977 rc = SQLITE_OK;
4978 }else{
4979 char *zErr = 0;
4980 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
4981 if( zErr ){
4982 utf8_printf(stdout, "ERROR: %s\n", zErr);
4983 sqlite3_free(zErr);
4986 return rc;
4991 ** Implementation of .ar "create" and "update" commands.
4993 ** Create the "sqlar" table in the database if it does not already exist.
4994 ** Then add each file in the azFile[] array to the archive. Directories
4995 ** are added recursively. If argument bVerbose is non-zero, a message is
4996 ** printed on stdout for each file archived.
4998 ** The create command is the same as update, except that it drops
4999 ** any existing "sqlar" table before beginning.
5001 static int arCreateOrUpdateCommand(
5002 ArCommand *pAr, /* Command arguments and options */
5003 int bUpdate /* true for a --create. false for --update */
5005 const char *zCreate =
5006 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5007 " name TEXT PRIMARY KEY, -- name of the file\n"
5008 " mode INT, -- access permissions\n"
5009 " mtime INT, -- last modification time\n"
5010 " sz INT, -- original file size\n"
5011 " data BLOB -- compressed content\n"
5012 ")";
5013 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
5014 const char *zInsertFmt =
5015 "REPLACE INTO sqlar(name,mode,mtime,sz,data)\n"
5016 " SELECT\n"
5017 " %s,\n"
5018 " mode,\n"
5019 " mtime,\n"
5020 " CASE substr(lsmode(mode),1,1)\n"
5021 " WHEN '-' THEN length(data)\n"
5022 " WHEN 'd' THEN 0\n"
5023 " ELSE -1 END,\n"
5024 " CASE WHEN lsmode(mode) LIKE 'd%%' THEN NULL else data END\n"
5025 " FROM fsdir(%Q,%Q)\n"
5026 " WHERE lsmode(mode) NOT LIKE '?%%';";
5027 int i; /* For iterating through azFile[] */
5028 int rc; /* Return code */
5030 rc = arExecSql(pAr, "SAVEPOINT ar;");
5031 if( rc!=SQLITE_OK ) return rc;
5032 if( bUpdate==0 ){
5033 rc = arExecSql(pAr, zDrop);
5034 if( rc!=SQLITE_OK ) return rc;
5036 rc = arExecSql(pAr, zCreate);
5037 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5038 char *zSql = sqlite3_mprintf(zInsertFmt,
5039 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5040 pAr->azArg[i], pAr->zDir);
5041 rc = arExecSql(pAr, zSql);
5042 sqlite3_free(zSql);
5044 if( rc!=SQLITE_OK ){
5045 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
5046 }else{
5047 rc = arExecSql(pAr, "RELEASE ar;");
5049 return rc;
5053 ** Implementation of ".ar" dot command.
5055 static int arDotCommand(
5056 ShellState *pState, /* Current shell tool state */
5057 char **azArg, /* Array of arguments passed to dot command */
5058 int nArg /* Number of entries in azArg[] */
5060 ArCommand cmd;
5061 int rc;
5062 rc = arParseCommand(azArg, nArg, &cmd);
5063 if( rc==SQLITE_OK ){
5064 int eDbType = SHELL_OPEN_UNSPEC;
5065 cmd.p = pState;
5066 cmd.db = pState->db;
5067 cmd.zSrcTable = 0;
5068 if( cmd.zFile ){
5069 eDbType = deduceDatabaseType(cmd.zFile);
5070 }else{
5071 eDbType = pState->openMode;
5073 if( eDbType==SHELL_OPEN_ZIPFILE ){
5074 if( cmd.zFile==0 ){
5075 cmd.zSrcTable = sqlite3_mprintf("zip");
5076 }else{
5077 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5079 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5080 utf8_printf(stderr, "zip archives are read-only\n");
5081 rc = SQLITE_ERROR;
5082 goto end_ar_command;
5084 cmd.bZip = 1;
5085 }else if( cmd.zFile ){
5086 int flags;
5087 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
5088 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5089 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5090 }else{
5091 flags = SQLITE_OPEN_READONLY;
5093 cmd.db = 0;
5094 if( cmd.bDryRun ){
5095 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5096 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5098 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5099 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
5100 if( rc!=SQLITE_OK ){
5101 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5102 cmd.zFile, sqlite3_errmsg(cmd.db)
5104 goto end_ar_command;
5106 sqlite3_fileio_init(cmd.db, 0, 0);
5107 #ifdef SQLITE_HAVE_ZLIB
5108 sqlite3_sqlar_init(cmd.db, 0, 0);
5109 #endif
5111 if( cmd.zSrcTable==0 ){
5112 if( cmd.eCmd!=AR_CMD_CREATE
5113 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5115 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5116 rc = SQLITE_ERROR;
5117 goto end_ar_command;
5119 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5122 switch( cmd.eCmd ){
5123 case AR_CMD_CREATE:
5124 rc = arCreateOrUpdateCommand(&cmd, 0);
5125 break;
5127 case AR_CMD_EXTRACT:
5128 rc = arExtractCommand(&cmd);
5129 break;
5131 case AR_CMD_LIST:
5132 rc = arListCommand(&cmd);
5133 break;
5135 case AR_CMD_HELP:
5136 arUsage(pState->out);
5137 break;
5139 default:
5140 assert( cmd.eCmd==AR_CMD_UPDATE );
5141 rc = arCreateOrUpdateCommand(&cmd, 1);
5142 break;
5145 end_ar_command:
5146 if( cmd.db!=pState->db ){
5147 sqlite3_close(cmd.db);
5149 sqlite3_free(cmd.zSrcTable);
5151 return rc;
5153 /* End of the ".archive" or ".ar" command logic
5154 **********************************************************************************/
5155 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5159 ** If an input line begins with "." then invoke this routine to
5160 ** process that line.
5162 ** Return 1 on error, 2 to exit, and 0 otherwise.
5164 static int do_meta_command(char *zLine, ShellState *p){
5165 int h = 1;
5166 int nArg = 0;
5167 int n, c;
5168 int rc = 0;
5169 char *azArg[50];
5171 #ifndef SQLITE_OMIT_VIRTUALTABLE
5172 if( p->expert.pExpert ){
5173 expertFinish(p, 1, 0);
5175 #endif
5177 /* Parse the input line into tokens.
5179 while( zLine[h] && nArg<ArraySize(azArg) ){
5180 while( IsSpace(zLine[h]) ){ h++; }
5181 if( zLine[h]==0 ) break;
5182 if( zLine[h]=='\'' || zLine[h]=='"' ){
5183 int delim = zLine[h++];
5184 azArg[nArg++] = &zLine[h];
5185 while( zLine[h] && zLine[h]!=delim ){
5186 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5187 h++;
5189 if( zLine[h]==delim ){
5190 zLine[h++] = 0;
5192 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5193 }else{
5194 azArg[nArg++] = &zLine[h];
5195 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5196 if( zLine[h] ) zLine[h++] = 0;
5197 resolve_backslashes(azArg[nArg-1]);
5201 /* Process the input line.
5203 if( nArg==0 ) return 0; /* no tokens, no error */
5204 n = strlen30(azArg[0]);
5205 c = azArg[0][0];
5207 #ifndef SQLITE_OMIT_AUTHORIZATION
5208 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5209 if( nArg!=2 ){
5210 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5211 rc = 1;
5212 goto meta_command_exit;
5214 open_db(p, 0);
5215 if( booleanValue(azArg[1]) ){
5216 sqlite3_set_authorizer(p->db, shellAuth, p);
5217 }else{
5218 sqlite3_set_authorizer(p->db, 0, 0);
5220 }else
5221 #endif
5223 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5224 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
5225 open_db(p, 0);
5226 rc = arDotCommand(p, azArg, nArg);
5227 }else
5228 #endif
5230 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5231 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5233 const char *zDestFile = 0;
5234 const char *zDb = 0;
5235 sqlite3 *pDest;
5236 sqlite3_backup *pBackup;
5237 int j;
5238 for(j=1; j<nArg; j++){
5239 const char *z = azArg[j];
5240 if( z[0]=='-' ){
5241 while( z[0]=='-' ) z++;
5242 /* No options to process at this time */
5244 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5245 return 1;
5247 }else if( zDestFile==0 ){
5248 zDestFile = azArg[j];
5249 }else if( zDb==0 ){
5250 zDb = zDestFile;
5251 zDestFile = azArg[j];
5252 }else{
5253 raw_printf(stderr, "too many arguments to .backup\n");
5254 return 1;
5257 if( zDestFile==0 ){
5258 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5259 return 1;
5261 if( zDb==0 ) zDb = "main";
5262 rc = sqlite3_open(zDestFile, &pDest);
5263 if( rc!=SQLITE_OK ){
5264 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5265 sqlite3_close(pDest);
5266 return 1;
5268 open_db(p, 0);
5269 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5270 if( pBackup==0 ){
5271 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5272 sqlite3_close(pDest);
5273 return 1;
5275 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5276 sqlite3_backup_finish(pBackup);
5277 if( rc==SQLITE_DONE ){
5278 rc = 0;
5279 }else{
5280 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5281 rc = 1;
5283 sqlite3_close(pDest);
5284 }else
5286 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5287 if( nArg==2 ){
5288 bail_on_error = booleanValue(azArg[1]);
5289 }else{
5290 raw_printf(stderr, "Usage: .bail on|off\n");
5291 rc = 1;
5293 }else
5295 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5296 if( nArg==2 ){
5297 if( booleanValue(azArg[1]) ){
5298 setBinaryMode(p->out, 1);
5299 }else{
5300 setTextMode(p->out, 1);
5302 }else{
5303 raw_printf(stderr, "Usage: .binary on|off\n");
5304 rc = 1;
5306 }else
5308 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5309 if( nArg==2 ){
5310 #if defined(_WIN32) || defined(WIN32)
5311 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5312 rc = !SetCurrentDirectoryW(z);
5313 sqlite3_free(z);
5314 #else
5315 rc = chdir(azArg[1]);
5316 #endif
5317 if( rc ){
5318 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5319 rc = 1;
5321 }else{
5322 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5323 rc = 1;
5325 }else
5327 /* The undocumented ".breakpoint" command causes a call to the no-op
5328 ** routine named test_breakpoint().
5330 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5331 test_breakpoint();
5332 }else
5334 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5335 if( nArg==2 ){
5336 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5337 }else{
5338 raw_printf(stderr, "Usage: .changes on|off\n");
5339 rc = 1;
5341 }else
5343 /* Cancel output redirection, if it is currently set (by .testcase)
5344 ** Then read the content of the testcase-out.txt file and compare against
5345 ** azArg[1]. If there are differences, report an error and exit.
5347 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5348 char *zRes = 0;
5349 output_reset(p);
5350 if( nArg!=2 ){
5351 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5352 rc = 2;
5353 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5354 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5355 rc = 2;
5356 }else if( testcase_glob(azArg[1],zRes)==0 ){
5357 utf8_printf(stderr,
5358 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5359 p->zTestcase, azArg[1], zRes);
5360 rc = 1;
5361 }else{
5362 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5363 p->nCheck++;
5365 sqlite3_free(zRes);
5366 }else
5368 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5369 if( nArg==2 ){
5370 tryToClone(p, azArg[1]);
5371 }else{
5372 raw_printf(stderr, "Usage: .clone FILENAME\n");
5373 rc = 1;
5375 }else
5377 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5378 ShellState data;
5379 char *zErrMsg = 0;
5380 open_db(p, 0);
5381 memcpy(&data, p, sizeof(data));
5382 data.showHeader = 0;
5383 data.cMode = data.mode = MODE_List;
5384 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5385 data.cnt = 0;
5386 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5387 callback, &data, &zErrMsg);
5388 if( zErrMsg ){
5389 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5390 sqlite3_free(zErrMsg);
5391 rc = 1;
5393 }else
5395 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5396 rc = shell_dbinfo_command(p, nArg, azArg);
5397 }else
5399 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5400 const char *zLike = 0;
5401 int i;
5402 int savedShowHeader = p->showHeader;
5403 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5404 for(i=1; i<nArg; i++){
5405 if( azArg[i][0]=='-' ){
5406 const char *z = azArg[i]+1;
5407 if( z[0]=='-' ) z++;
5408 if( strcmp(z,"preserve-rowids")==0 ){
5409 #ifdef SQLITE_OMIT_VIRTUALTABLE
5410 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5411 " with SQLITE_OMIT_VIRTUALTABLE\n");
5412 rc = 1;
5413 goto meta_command_exit;
5414 #else
5415 ShellSetFlag(p, SHFLG_PreserveRowid);
5416 #endif
5417 }else
5418 if( strcmp(z,"newlines")==0 ){
5419 ShellSetFlag(p, SHFLG_Newlines);
5420 }else
5422 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5423 rc = 1;
5424 goto meta_command_exit;
5426 }else if( zLike ){
5427 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5428 "?--newlines? ?LIKE-PATTERN?\n");
5429 rc = 1;
5430 goto meta_command_exit;
5431 }else{
5432 zLike = azArg[i];
5435 open_db(p, 0);
5436 /* When playing back a "dump", the content might appear in an order
5437 ** which causes immediate foreign key constraints to be violated.
5438 ** So disable foreign-key constraint enforcement to prevent problems. */
5439 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5440 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5441 p->writableSchema = 0;
5442 p->showHeader = 0;
5443 /* Set writable_schema=ON since doing so forces SQLite to initialize
5444 ** as much of the schema as it can even if the sqlite_master table is
5445 ** corrupt. */
5446 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5447 p->nErr = 0;
5448 if( zLike==0 ){
5449 run_schema_dump_query(p,
5450 "SELECT name, type, sql FROM sqlite_master "
5451 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5453 run_schema_dump_query(p,
5454 "SELECT name, type, sql FROM sqlite_master "
5455 "WHERE name=='sqlite_sequence'"
5457 run_table_dump_query(p,
5458 "SELECT sql FROM sqlite_master "
5459 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5461 }else{
5462 char *zSql;
5463 zSql = sqlite3_mprintf(
5464 "SELECT name, type, sql FROM sqlite_master "
5465 "WHERE tbl_name LIKE %Q AND type=='table'"
5466 " AND sql NOT NULL", zLike);
5467 run_schema_dump_query(p,zSql);
5468 sqlite3_free(zSql);
5469 zSql = sqlite3_mprintf(
5470 "SELECT sql FROM sqlite_master "
5471 "WHERE sql NOT NULL"
5472 " AND type IN ('index','trigger','view')"
5473 " AND tbl_name LIKE %Q", zLike);
5474 run_table_dump_query(p, zSql, 0);
5475 sqlite3_free(zSql);
5477 if( p->writableSchema ){
5478 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5479 p->writableSchema = 0;
5481 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5482 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5483 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5484 p->showHeader = savedShowHeader;
5485 }else
5487 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5488 if( nArg==2 ){
5489 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5490 }else{
5491 raw_printf(stderr, "Usage: .echo on|off\n");
5492 rc = 1;
5494 }else
5496 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5497 if( nArg==2 ){
5498 if( strcmp(azArg[1],"full")==0 ){
5499 p->autoEQP = AUTOEQP_full;
5500 }else if( strcmp(azArg[1],"trigger")==0 ){
5501 p->autoEQP = AUTOEQP_trigger;
5502 }else{
5503 p->autoEQP = booleanValue(azArg[1]);
5505 }else{
5506 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
5507 rc = 1;
5509 }else
5511 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5512 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5513 rc = 2;
5514 }else
5516 /* The ".explain" command is automatic now. It is largely pointless. It
5517 ** retained purely for backwards compatibility */
5518 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5519 int val = 1;
5520 if( nArg>=2 ){
5521 if( strcmp(azArg[1],"auto")==0 ){
5522 val = 99;
5523 }else{
5524 val = booleanValue(azArg[1]);
5527 if( val==1 && p->mode!=MODE_Explain ){
5528 p->normalMode = p->mode;
5529 p->mode = MODE_Explain;
5530 p->autoExplain = 0;
5531 }else if( val==0 ){
5532 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5533 p->autoExplain = 0;
5534 }else if( val==99 ){
5535 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5536 p->autoExplain = 1;
5538 }else
5540 #ifndef SQLITE_OMIT_VIRTUALTABLE
5541 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
5542 open_db(p, 0);
5543 expertDotCommand(p, azArg, nArg);
5544 }else
5545 #endif
5547 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
5548 ShellState data;
5549 char *zErrMsg = 0;
5550 int doStats = 0;
5551 memcpy(&data, p, sizeof(data));
5552 data.showHeader = 0;
5553 data.cMode = data.mode = MODE_Semi;
5554 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5555 data.cMode = data.mode = MODE_Pretty;
5556 nArg = 1;
5558 if( nArg!=1 ){
5559 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
5560 rc = 1;
5561 goto meta_command_exit;
5563 open_db(p, 0);
5564 rc = sqlite3_exec(p->db,
5565 "SELECT sql FROM"
5566 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5567 " FROM sqlite_master UNION ALL"
5568 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5569 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5570 "ORDER BY rowid",
5571 callback, &data, &zErrMsg
5573 if( rc==SQLITE_OK ){
5574 sqlite3_stmt *pStmt;
5575 rc = sqlite3_prepare_v2(p->db,
5576 "SELECT rowid FROM sqlite_master"
5577 " WHERE name GLOB 'sqlite_stat[134]'",
5578 -1, &pStmt, 0);
5579 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5580 sqlite3_finalize(pStmt);
5582 if( doStats==0 ){
5583 raw_printf(p->out, "/* No STAT tables available */\n");
5584 }else{
5585 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5586 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5587 callback, &data, &zErrMsg);
5588 data.cMode = data.mode = MODE_Insert;
5589 data.zDestTable = "sqlite_stat1";
5590 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5591 shell_callback, &data,&zErrMsg);
5592 data.zDestTable = "sqlite_stat3";
5593 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5594 shell_callback, &data,&zErrMsg);
5595 data.zDestTable = "sqlite_stat4";
5596 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5597 shell_callback, &data, &zErrMsg);
5598 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5600 }else
5602 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5603 if( nArg==2 ){
5604 p->showHeader = booleanValue(azArg[1]);
5605 }else{
5606 raw_printf(stderr, "Usage: .headers on|off\n");
5607 rc = 1;
5609 }else
5611 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
5612 utf8_printf(p->out, "%s", zHelp);
5613 }else
5615 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
5616 char *zTable; /* Insert data into this table */
5617 char *zFile; /* Name of file to extra content from */
5618 sqlite3_stmt *pStmt = NULL; /* A statement */
5619 int nCol; /* Number of columns in the table */
5620 int nByte; /* Number of bytes in an SQL string */
5621 int i, j; /* Loop counters */
5622 int needCommit; /* True to COMMIT or ROLLBACK at end */
5623 int nSep; /* Number of bytes in p->colSeparator[] */
5624 char *zSql; /* An SQL statement */
5625 ImportCtx sCtx; /* Reader context */
5626 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5627 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
5629 if( nArg!=3 ){
5630 raw_printf(stderr, "Usage: .import FILE TABLE\n");
5631 goto meta_command_exit;
5633 zFile = azArg[1];
5634 zTable = azArg[2];
5635 seenInterrupt = 0;
5636 memset(&sCtx, 0, sizeof(sCtx));
5637 open_db(p, 0);
5638 nSep = strlen30(p->colSeparator);
5639 if( nSep==0 ){
5640 raw_printf(stderr,
5641 "Error: non-null column separator required for import\n");
5642 return 1;
5644 if( nSep>1 ){
5645 raw_printf(stderr, "Error: multi-character column separators not allowed"
5646 " for import\n");
5647 return 1;
5649 nSep = strlen30(p->rowSeparator);
5650 if( nSep==0 ){
5651 raw_printf(stderr, "Error: non-null row separator required for import\n");
5652 return 1;
5654 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5655 /* When importing CSV (only), if the row separator is set to the
5656 ** default output row separator, change it to the default input
5657 ** row separator. This avoids having to maintain different input
5658 ** and output row separators. */
5659 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5660 nSep = strlen30(p->rowSeparator);
5662 if( nSep>1 ){
5663 raw_printf(stderr, "Error: multi-character row separators not allowed"
5664 " for import\n");
5665 return 1;
5667 sCtx.zFile = zFile;
5668 sCtx.nLine = 1;
5669 if( sCtx.zFile[0]=='|' ){
5670 #ifdef SQLITE_OMIT_POPEN
5671 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5672 return 1;
5673 #else
5674 sCtx.in = popen(sCtx.zFile+1, "r");
5675 sCtx.zFile = "<pipe>";
5676 xCloser = pclose;
5677 #endif
5678 }else{
5679 sCtx.in = fopen(sCtx.zFile, "rb");
5680 xCloser = fclose;
5682 if( p->mode==MODE_Ascii ){
5683 xRead = ascii_read_one_field;
5684 }else{
5685 xRead = csv_read_one_field;
5687 if( sCtx.in==0 ){
5688 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5689 return 1;
5691 sCtx.cColSep = p->colSeparator[0];
5692 sCtx.cRowSep = p->rowSeparator[0];
5693 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
5694 if( zSql==0 ){
5695 raw_printf(stderr, "Error: out of memory\n");
5696 xCloser(sCtx.in);
5697 return 1;
5699 nByte = strlen30(zSql);
5700 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5701 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
5702 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
5703 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5704 char cSep = '(';
5705 while( xRead(&sCtx) ){
5706 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
5707 cSep = ',';
5708 if( sCtx.cTerm!=sCtx.cColSep ) break;
5710 if( cSep=='(' ){
5711 sqlite3_free(zCreate);
5712 sqlite3_free(sCtx.z);
5713 xCloser(sCtx.in);
5714 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
5715 return 1;
5717 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5718 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5719 sqlite3_free(zCreate);
5720 if( rc ){
5721 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
5722 sqlite3_errmsg(p->db));
5723 sqlite3_free(sCtx.z);
5724 xCloser(sCtx.in);
5725 return 1;
5727 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5729 sqlite3_free(zSql);
5730 if( rc ){
5731 if (pStmt) sqlite3_finalize(pStmt);
5732 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
5733 xCloser(sCtx.in);
5734 return 1;
5736 nCol = sqlite3_column_count(pStmt);
5737 sqlite3_finalize(pStmt);
5738 pStmt = 0;
5739 if( nCol==0 ) return 0; /* no columns, no error */
5740 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5741 if( zSql==0 ){
5742 raw_printf(stderr, "Error: out of memory\n");
5743 xCloser(sCtx.in);
5744 return 1;
5746 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5747 j = strlen30(zSql);
5748 for(i=1; i<nCol; i++){
5749 zSql[j++] = ',';
5750 zSql[j++] = '?';
5752 zSql[j++] = ')';
5753 zSql[j] = 0;
5754 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5755 sqlite3_free(zSql);
5756 if( rc ){
5757 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5758 if (pStmt) sqlite3_finalize(pStmt);
5759 xCloser(sCtx.in);
5760 return 1;
5762 needCommit = sqlite3_get_autocommit(p->db);
5763 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5765 int startLine = sCtx.nLine;
5766 for(i=0; i<nCol; i++){
5767 char *z = xRead(&sCtx);
5769 ** Did we reach end-of-file before finding any columns?
5770 ** If so, stop instead of NULL filling the remaining columns.
5772 if( z==0 && i==0 ) break;
5774 ** Did we reach end-of-file OR end-of-line before finding any
5775 ** columns in ASCII mode? If so, stop instead of NULL filling
5776 ** the remaining columns.
5778 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5779 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5780 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5781 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5782 "filling the rest with NULL\n",
5783 sCtx.zFile, startLine, nCol, i+1);
5784 i += 2;
5785 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5788 if( sCtx.cTerm==sCtx.cColSep ){
5790 xRead(&sCtx);
5791 i++;
5792 }while( sCtx.cTerm==sCtx.cColSep );
5793 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5794 "extras ignored\n",
5795 sCtx.zFile, startLine, nCol, i);
5797 if( i>=nCol ){
5798 sqlite3_step(pStmt);
5799 rc = sqlite3_reset(pStmt);
5800 if( rc!=SQLITE_OK ){
5801 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5802 startLine, sqlite3_errmsg(p->db));
5805 }while( sCtx.cTerm!=EOF );
5807 xCloser(sCtx.in);
5808 sqlite3_free(sCtx.z);
5809 sqlite3_finalize(pStmt);
5810 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5811 }else
5813 #ifndef SQLITE_UNTESTABLE
5814 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5815 char *zSql;
5816 char *zCollist = 0;
5817 sqlite3_stmt *pStmt;
5818 int tnum = 0;
5819 int i;
5820 if( nArg!=3 ){
5821 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5822 rc = 1;
5823 goto meta_command_exit;
5825 open_db(p, 0);
5826 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5827 " WHERE name='%q' AND type='index'", azArg[1]);
5828 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5829 sqlite3_free(zSql);
5830 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5831 tnum = sqlite3_column_int(pStmt, 0);
5833 sqlite3_finalize(pStmt);
5834 if( tnum==0 ){
5835 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5836 rc = 1;
5837 goto meta_command_exit;
5839 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5840 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5841 sqlite3_free(zSql);
5842 i = 0;
5843 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5844 char zLabel[20];
5845 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5846 i++;
5847 if( zCol==0 ){
5848 if( sqlite3_column_int(pStmt,1)==-1 ){
5849 zCol = "_ROWID_";
5850 }else{
5851 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5852 zCol = zLabel;
5855 if( zCollist==0 ){
5856 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5857 }else{
5858 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5861 sqlite3_finalize(pStmt);
5862 zSql = sqlite3_mprintf(
5863 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5864 azArg[2], zCollist, zCollist);
5865 sqlite3_free(zCollist);
5866 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5867 if( rc==SQLITE_OK ){
5868 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5869 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5870 if( rc ){
5871 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5872 }else{
5873 utf8_printf(stdout, "%s;\n", zSql);
5874 raw_printf(stdout,
5875 "WARNING: writing to an imposter table will corrupt the index!\n"
5878 }else{
5879 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5880 rc = 1;
5882 sqlite3_free(zSql);
5883 }else
5884 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5886 #ifdef SQLITE_ENABLE_IOTRACE
5887 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5888 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5889 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5890 iotrace = 0;
5891 if( nArg<2 ){
5892 sqlite3IoTrace = 0;
5893 }else if( strcmp(azArg[1], "-")==0 ){
5894 sqlite3IoTrace = iotracePrintf;
5895 iotrace = stdout;
5896 }else{
5897 iotrace = fopen(azArg[1], "w");
5898 if( iotrace==0 ){
5899 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5900 sqlite3IoTrace = 0;
5901 rc = 1;
5902 }else{
5903 sqlite3IoTrace = iotracePrintf;
5906 }else
5907 #endif
5909 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5910 static const struct {
5911 const char *zLimitName; /* Name of a limit */
5912 int limitCode; /* Integer code for that limit */
5913 } aLimit[] = {
5914 { "length", SQLITE_LIMIT_LENGTH },
5915 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5916 { "column", SQLITE_LIMIT_COLUMN },
5917 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5918 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5919 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5920 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5921 { "attached", SQLITE_LIMIT_ATTACHED },
5922 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5923 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5924 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5925 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5927 int i, n2;
5928 open_db(p, 0);
5929 if( nArg==1 ){
5930 for(i=0; i<ArraySize(aLimit); i++){
5931 printf("%20s %d\n", aLimit[i].zLimitName,
5932 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5934 }else if( nArg>3 ){
5935 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5936 rc = 1;
5937 goto meta_command_exit;
5938 }else{
5939 int iLimit = -1;
5940 n2 = strlen30(azArg[1]);
5941 for(i=0; i<ArraySize(aLimit); i++){
5942 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5943 if( iLimit<0 ){
5944 iLimit = i;
5945 }else{
5946 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5947 rc = 1;
5948 goto meta_command_exit;
5952 if( iLimit<0 ){
5953 utf8_printf(stderr, "unknown limit: \"%s\"\n"
5954 "enter \".limits\" with no arguments for a list.\n",
5955 azArg[1]);
5956 rc = 1;
5957 goto meta_command_exit;
5959 if( nArg==3 ){
5960 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5961 (int)integerValue(azArg[2]));
5963 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5964 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5966 }else
5968 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5969 open_db(p, 0);
5970 lintDotCommand(p, azArg, nArg);
5971 }else
5973 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5974 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5975 const char *zFile, *zProc;
5976 char *zErrMsg = 0;
5977 if( nArg<2 ){
5978 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5979 rc = 1;
5980 goto meta_command_exit;
5982 zFile = azArg[1];
5983 zProc = nArg>=3 ? azArg[2] : 0;
5984 open_db(p, 0);
5985 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5986 if( rc!=SQLITE_OK ){
5987 utf8_printf(stderr, "Error: %s\n", zErrMsg);
5988 sqlite3_free(zErrMsg);
5989 rc = 1;
5991 }else
5992 #endif
5994 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5995 if( nArg!=2 ){
5996 raw_printf(stderr, "Usage: .log FILENAME\n");
5997 rc = 1;
5998 }else{
5999 const char *zFile = azArg[1];
6000 output_file_close(p->pLog);
6001 p->pLog = output_file_open(zFile);
6003 }else
6005 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6006 const char *zMode = nArg>=2 ? azArg[1] : "";
6007 int n2 = strlen30(zMode);
6008 int c2 = zMode[0];
6009 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6010 p->mode = MODE_Line;
6011 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6012 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6013 p->mode = MODE_Column;
6014 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6015 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6016 p->mode = MODE_List;
6017 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6018 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6019 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6020 p->mode = MODE_Html;
6021 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6022 p->mode = MODE_Tcl;
6023 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6024 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6025 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6026 p->mode = MODE_Csv;
6027 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6028 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6029 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6030 p->mode = MODE_List;
6031 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6032 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6033 p->mode = MODE_Insert;
6034 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6035 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6036 p->mode = MODE_Quote;
6037 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6038 p->mode = MODE_Ascii;
6039 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6040 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6041 }else if( nArg==1 ){
6042 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6043 }else{
6044 raw_printf(stderr, "Error: mode should be one of: "
6045 "ascii column csv html insert line list quote tabs tcl\n");
6046 rc = 1;
6048 p->cMode = p->mode;
6049 }else
6051 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6052 if( nArg==2 ){
6053 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6054 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6055 }else{
6056 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6057 rc = 1;
6059 }else
6061 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6062 char *zNewFilename; /* Name of the database file to open */
6063 int iName = 1; /* Index in azArg[] of the filename */
6064 int newFlag = 0; /* True to delete file before opening */
6065 /* Close the existing database */
6066 session_close_all(p);
6067 sqlite3_close(p->db);
6068 p->db = 0;
6069 p->zDbFilename = 0;
6070 sqlite3_free(p->zFreeOnClose);
6071 p->zFreeOnClose = 0;
6072 p->openMode = SHELL_OPEN_UNSPEC;
6073 /* Check for command-line arguments */
6074 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6075 const char *z = azArg[iName];
6076 if( optionMatch(z,"new") ){
6077 newFlag = 1;
6078 #ifdef SQLITE_HAVE_ZIP
6079 }else if( optionMatch(z, "zip") ){
6080 p->openMode = SHELL_OPEN_ZIPFILE;
6081 #endif
6082 }else if( optionMatch(z, "append") ){
6083 p->openMode = SHELL_OPEN_APPENDVFS;
6084 }else if( z[0]=='-' ){
6085 utf8_printf(stderr, "unknown option: %s\n", z);
6086 rc = 1;
6087 goto meta_command_exit;
6090 /* If a filename is specified, try to open it first */
6091 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6092 if( zNewFilename ){
6093 if( newFlag ) shellDeleteFile(zNewFilename);
6094 p->zDbFilename = zNewFilename;
6095 open_db(p, 1);
6096 if( p->db==0 ){
6097 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6098 sqlite3_free(zNewFilename);
6099 }else{
6100 p->zFreeOnClose = zNewFilename;
6103 if( p->db==0 ){
6104 /* As a fall-back open a TEMP database */
6105 p->zDbFilename = 0;
6106 open_db(p, 0);
6108 }else
6110 if( c=='o'
6111 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
6113 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6114 if( nArg>2 ){
6115 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
6116 rc = 1;
6117 goto meta_command_exit;
6119 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6120 if( nArg<2 ){
6121 raw_printf(stderr, "Usage: .once FILE\n");
6122 rc = 1;
6123 goto meta_command_exit;
6125 p->outCount = 2;
6126 }else{
6127 p->outCount = 0;
6129 output_reset(p);
6130 if( zFile[0]=='|' ){
6131 #ifdef SQLITE_OMIT_POPEN
6132 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6133 rc = 1;
6134 p->out = stdout;
6135 #else
6136 p->out = popen(zFile + 1, "w");
6137 if( p->out==0 ){
6138 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6139 p->out = stdout;
6140 rc = 1;
6141 }else{
6142 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6144 #endif
6145 }else{
6146 p->out = output_file_open(zFile);
6147 if( p->out==0 ){
6148 if( strcmp(zFile,"off")!=0 ){
6149 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6151 p->out = stdout;
6152 rc = 1;
6153 } else {
6154 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6157 }else
6159 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6160 int i;
6161 for(i=1; i<nArg; i++){
6162 if( i>1 ) raw_printf(p->out, " ");
6163 utf8_printf(p->out, "%s", azArg[i]);
6165 raw_printf(p->out, "\n");
6166 }else
6168 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6169 if( nArg >= 2) {
6170 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6172 if( nArg >= 3) {
6173 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6175 }else
6177 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6178 rc = 2;
6179 }else
6181 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6182 FILE *alt;
6183 if( nArg!=2 ){
6184 raw_printf(stderr, "Usage: .read FILE\n");
6185 rc = 1;
6186 goto meta_command_exit;
6188 alt = fopen(azArg[1], "rb");
6189 if( alt==0 ){
6190 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6191 rc = 1;
6192 }else{
6193 rc = process_input(p, alt);
6194 fclose(alt);
6196 }else
6198 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6199 const char *zSrcFile;
6200 const char *zDb;
6201 sqlite3 *pSrc;
6202 sqlite3_backup *pBackup;
6203 int nTimeout = 0;
6205 if( nArg==2 ){
6206 zSrcFile = azArg[1];
6207 zDb = "main";
6208 }else if( nArg==3 ){
6209 zSrcFile = azArg[2];
6210 zDb = azArg[1];
6211 }else{
6212 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6213 rc = 1;
6214 goto meta_command_exit;
6216 rc = sqlite3_open(zSrcFile, &pSrc);
6217 if( rc!=SQLITE_OK ){
6218 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6219 sqlite3_close(pSrc);
6220 return 1;
6222 open_db(p, 0);
6223 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6224 if( pBackup==0 ){
6225 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6226 sqlite3_close(pSrc);
6227 return 1;
6229 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6230 || rc==SQLITE_BUSY ){
6231 if( rc==SQLITE_BUSY ){
6232 if( nTimeout++ >= 3 ) break;
6233 sqlite3_sleep(100);
6236 sqlite3_backup_finish(pBackup);
6237 if( rc==SQLITE_DONE ){
6238 rc = 0;
6239 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6240 raw_printf(stderr, "Error: source database is busy\n");
6241 rc = 1;
6242 }else{
6243 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6244 rc = 1;
6246 sqlite3_close(pSrc);
6247 }else
6250 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6251 if( nArg==2 ){
6252 p->scanstatsOn = booleanValue(azArg[1]);
6253 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6254 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6255 #endif
6256 }else{
6257 raw_printf(stderr, "Usage: .scanstats on|off\n");
6258 rc = 1;
6260 }else
6262 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6263 ShellText sSelect;
6264 ShellState data;
6265 char *zErrMsg = 0;
6266 const char *zDiv = "(";
6267 const char *zName = 0;
6268 int iSchema = 0;
6269 int bDebug = 0;
6270 int ii;
6272 open_db(p, 0);
6273 memcpy(&data, p, sizeof(data));
6274 data.showHeader = 0;
6275 data.cMode = data.mode = MODE_Semi;
6276 initText(&sSelect);
6277 for(ii=1; ii<nArg; ii++){
6278 if( optionMatch(azArg[ii],"indent") ){
6279 data.cMode = data.mode = MODE_Pretty;
6280 }else if( optionMatch(azArg[ii],"debug") ){
6281 bDebug = 1;
6282 }else if( zName==0 ){
6283 zName = azArg[ii];
6284 }else{
6285 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6286 rc = 1;
6287 goto meta_command_exit;
6290 if( zName!=0 ){
6291 int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
6292 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
6293 char *new_argv[2], *new_colv[2];
6294 new_argv[0] = sqlite3_mprintf(
6295 "CREATE TABLE %s (\n"
6296 " type text,\n"
6297 " name text,\n"
6298 " tbl_name text,\n"
6299 " rootpage integer,\n"
6300 " sql text\n"
6301 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
6302 new_argv[1] = 0;
6303 new_colv[0] = "sql";
6304 new_colv[1] = 0;
6305 callback(&data, 1, new_argv, new_colv);
6306 sqlite3_free(new_argv[0]);
6309 if( zDiv ){
6310 sqlite3_stmt *pStmt = 0;
6311 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6312 -1, &pStmt, 0);
6313 if( rc ){
6314 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6315 sqlite3_finalize(pStmt);
6316 rc = 1;
6317 goto meta_command_exit;
6319 appendText(&sSelect, "SELECT sql FROM", 0);
6320 iSchema = 0;
6321 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6322 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6323 char zScNum[30];
6324 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6325 appendText(&sSelect, zDiv, 0);
6326 zDiv = " UNION ALL ";
6327 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6328 if( sqlite3_stricmp(zDb, "main")!=0 ){
6329 appendText(&sSelect, zDb, '"');
6330 }else{
6331 appendText(&sSelect, "NULL", 0);
6333 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6334 appendText(&sSelect, zScNum, 0);
6335 appendText(&sSelect, " AS snum, ", 0);
6336 appendText(&sSelect, zDb, '\'');
6337 appendText(&sSelect, " AS sname FROM ", 0);
6338 appendText(&sSelect, zDb, '"');
6339 appendText(&sSelect, ".sqlite_master", 0);
6341 sqlite3_finalize(pStmt);
6342 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6343 if( zName ){
6344 appendText(&sSelect,
6345 " UNION ALL SELECT shell_module_schema(name),"
6346 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6348 #endif
6349 appendText(&sSelect, ") WHERE ", 0);
6350 if( zName ){
6351 char *zQarg = sqlite3_mprintf("%Q", zName);
6352 if( strchr(zName, '.') ){
6353 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6354 }else{
6355 appendText(&sSelect, "lower(tbl_name)", 0);
6357 appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
6358 appendText(&sSelect, zQarg, 0);
6359 appendText(&sSelect, " AND ", 0);
6360 sqlite3_free(zQarg);
6362 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6363 " ORDER BY snum, rowid", 0);
6364 if( bDebug ){
6365 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6366 }else{
6367 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6369 freeText(&sSelect);
6371 if( zErrMsg ){
6372 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6373 sqlite3_free(zErrMsg);
6374 rc = 1;
6375 }else if( rc != SQLITE_OK ){
6376 raw_printf(stderr,"Error: querying schema information\n");
6377 rc = 1;
6378 }else{
6379 rc = 0;
6381 }else
6383 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6384 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6385 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6386 }else
6387 #endif
6389 #if defined(SQLITE_ENABLE_SESSION)
6390 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6391 OpenSession *pSession = &p->aSession[0];
6392 char **azCmd = &azArg[1];
6393 int iSes = 0;
6394 int nCmd = nArg - 1;
6395 int i;
6396 if( nArg<=1 ) goto session_syntax_error;
6397 open_db(p, 0);
6398 if( nArg>=3 ){
6399 for(iSes=0; iSes<p->nSession; iSes++){
6400 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6402 if( iSes<p->nSession ){
6403 pSession = &p->aSession[iSes];
6404 azCmd++;
6405 nCmd--;
6406 }else{
6407 pSession = &p->aSession[0];
6408 iSes = 0;
6412 /* .session attach TABLE
6413 ** Invoke the sqlite3session_attach() interface to attach a particular
6414 ** table so that it is never filtered.
6416 if( strcmp(azCmd[0],"attach")==0 ){
6417 if( nCmd!=2 ) goto session_syntax_error;
6418 if( pSession->p==0 ){
6419 session_not_open:
6420 raw_printf(stderr, "ERROR: No sessions are open\n");
6421 }else{
6422 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6423 if( rc ){
6424 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6425 rc = 0;
6428 }else
6430 /* .session changeset FILE
6431 ** .session patchset FILE
6432 ** Write a changeset or patchset into a file. The file is overwritten.
6434 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6435 FILE *out = 0;
6436 if( nCmd!=2 ) goto session_syntax_error;
6437 if( pSession->p==0 ) goto session_not_open;
6438 out = fopen(azCmd[1], "wb");
6439 if( out==0 ){
6440 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6441 }else{
6442 int szChng;
6443 void *pChng;
6444 if( azCmd[0][0]=='c' ){
6445 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6446 }else{
6447 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6449 if( rc ){
6450 printf("Error: error code %d\n", rc);
6451 rc = 0;
6453 if( pChng
6454 && fwrite(pChng, szChng, 1, out)!=1 ){
6455 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6456 szChng);
6458 sqlite3_free(pChng);
6459 fclose(out);
6461 }else
6463 /* .session close
6464 ** Close the identified session
6466 if( strcmp(azCmd[0], "close")==0 ){
6467 if( nCmd!=1 ) goto session_syntax_error;
6468 if( p->nSession ){
6469 session_close(pSession);
6470 p->aSession[iSes] = p->aSession[--p->nSession];
6472 }else
6474 /* .session enable ?BOOLEAN?
6475 ** Query or set the enable flag
6477 if( strcmp(azCmd[0], "enable")==0 ){
6478 int ii;
6479 if( nCmd>2 ) goto session_syntax_error;
6480 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6481 if( p->nSession ){
6482 ii = sqlite3session_enable(pSession->p, ii);
6483 utf8_printf(p->out, "session %s enable flag = %d\n",
6484 pSession->zName, ii);
6486 }else
6488 /* .session filter GLOB ....
6489 ** Set a list of GLOB patterns of table names to be excluded.
6491 if( strcmp(azCmd[0], "filter")==0 ){
6492 int ii, nByte;
6493 if( nCmd<2 ) goto session_syntax_error;
6494 if( p->nSession ){
6495 for(ii=0; ii<pSession->nFilter; ii++){
6496 sqlite3_free(pSession->azFilter[ii]);
6498 sqlite3_free(pSession->azFilter);
6499 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6500 pSession->azFilter = sqlite3_malloc( nByte );
6501 if( pSession->azFilter==0 ){
6502 raw_printf(stderr, "Error: out or memory\n");
6503 exit(1);
6505 for(ii=1; ii<nCmd; ii++){
6506 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6508 pSession->nFilter = ii-1;
6510 }else
6512 /* .session indirect ?BOOLEAN?
6513 ** Query or set the indirect flag
6515 if( strcmp(azCmd[0], "indirect")==0 ){
6516 int ii;
6517 if( nCmd>2 ) goto session_syntax_error;
6518 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6519 if( p->nSession ){
6520 ii = sqlite3session_indirect(pSession->p, ii);
6521 utf8_printf(p->out, "session %s indirect flag = %d\n",
6522 pSession->zName, ii);
6524 }else
6526 /* .session isempty
6527 ** Determine if the session is empty
6529 if( strcmp(azCmd[0], "isempty")==0 ){
6530 int ii;
6531 if( nCmd!=1 ) goto session_syntax_error;
6532 if( p->nSession ){
6533 ii = sqlite3session_isempty(pSession->p);
6534 utf8_printf(p->out, "session %s isempty flag = %d\n",
6535 pSession->zName, ii);
6537 }else
6539 /* .session list
6540 ** List all currently open sessions
6542 if( strcmp(azCmd[0],"list")==0 ){
6543 for(i=0; i<p->nSession; i++){
6544 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
6546 }else
6548 /* .session open DB NAME
6549 ** Open a new session called NAME on the attached database DB.
6550 ** DB is normally "main".
6552 if( strcmp(azCmd[0],"open")==0 ){
6553 char *zName;
6554 if( nCmd!=3 ) goto session_syntax_error;
6555 zName = azCmd[2];
6556 if( zName[0]==0 ) goto session_syntax_error;
6557 for(i=0; i<p->nSession; i++){
6558 if( strcmp(p->aSession[i].zName,zName)==0 ){
6559 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
6560 goto meta_command_exit;
6563 if( p->nSession>=ArraySize(p->aSession) ){
6564 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
6565 goto meta_command_exit;
6567 pSession = &p->aSession[p->nSession];
6568 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6569 if( rc ){
6570 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
6571 rc = 0;
6572 goto meta_command_exit;
6574 pSession->nFilter = 0;
6575 sqlite3session_table_filter(pSession->p, session_filter, pSession);
6576 p->nSession++;
6577 pSession->zName = sqlite3_mprintf("%s", zName);
6578 }else
6579 /* If no command name matches, show a syntax error */
6580 session_syntax_error:
6581 session_help(p);
6582 }else
6583 #endif
6585 #ifdef SQLITE_DEBUG
6586 /* Undocumented commands for internal testing. Subject to change
6587 ** without notice. */
6588 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6589 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6590 int i, v;
6591 for(i=1; i<nArg; i++){
6592 v = booleanValue(azArg[i]);
6593 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
6596 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6597 int i; sqlite3_int64 v;
6598 for(i=1; i<nArg; i++){
6599 char zBuf[200];
6600 v = integerValue(azArg[i]);
6601 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
6602 utf8_printf(p->out, "%s", zBuf);
6605 }else
6606 #endif
6608 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6609 int bIsInit = 0; /* True to initialize the SELFTEST table */
6610 int bVerbose = 0; /* Verbose output */
6611 int bSelftestExists; /* True if SELFTEST already exists */
6612 int i, k; /* Loop counters */
6613 int nTest = 0; /* Number of tests runs */
6614 int nErr = 0; /* Number of errors seen */
6615 ShellText str; /* Answer for a query */
6616 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
6618 open_db(p,0);
6619 for(i=1; i<nArg; i++){
6620 const char *z = azArg[i];
6621 if( z[0]=='-' && z[1]=='-' ) z++;
6622 if( strcmp(z,"-init")==0 ){
6623 bIsInit = 1;
6624 }else
6625 if( strcmp(z,"-v")==0 ){
6626 bVerbose++;
6627 }else
6629 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6630 azArg[i], azArg[0]);
6631 raw_printf(stderr, "Should be one of: --init -v\n");
6632 rc = 1;
6633 goto meta_command_exit;
6636 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6637 != SQLITE_OK ){
6638 bSelftestExists = 0;
6639 }else{
6640 bSelftestExists = 1;
6642 if( bIsInit ){
6643 createSelftestTable(p);
6644 bSelftestExists = 1;
6646 initText(&str);
6647 appendText(&str, "x", 0);
6648 for(k=bSelftestExists; k>=0; k--){
6649 if( k==1 ){
6650 rc = sqlite3_prepare_v2(p->db,
6651 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6652 -1, &pStmt, 0);
6653 }else{
6654 rc = sqlite3_prepare_v2(p->db,
6655 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6656 " (1,'run','PRAGMA integrity_check','ok')",
6657 -1, &pStmt, 0);
6659 if( rc ){
6660 raw_printf(stderr, "Error querying the selftest table\n");
6661 rc = 1;
6662 sqlite3_finalize(pStmt);
6663 goto meta_command_exit;
6665 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6666 int tno = sqlite3_column_int(pStmt, 0);
6667 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6668 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6669 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
6671 k = 0;
6672 if( bVerbose>0 ){
6673 char *zQuote = sqlite3_mprintf("%q", zSql);
6674 printf("%d: %s %s\n", tno, zOp, zSql);
6675 sqlite3_free(zQuote);
6677 if( strcmp(zOp,"memo")==0 ){
6678 utf8_printf(p->out, "%s\n", zSql);
6679 }else
6680 if( strcmp(zOp,"run")==0 ){
6681 char *zErrMsg = 0;
6682 str.n = 0;
6683 str.z[0] = 0;
6684 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6685 nTest++;
6686 if( bVerbose ){
6687 utf8_printf(p->out, "Result: %s\n", str.z);
6689 if( rc || zErrMsg ){
6690 nErr++;
6691 rc = 1;
6692 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6693 sqlite3_free(zErrMsg);
6694 }else if( strcmp(zAns,str.z)!=0 ){
6695 nErr++;
6696 rc = 1;
6697 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6698 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6700 }else
6702 utf8_printf(stderr,
6703 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6704 rc = 1;
6705 break;
6707 } /* End loop over rows of content from SELFTEST */
6708 sqlite3_finalize(pStmt);
6709 } /* End loop over k */
6710 freeText(&str);
6711 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6712 }else
6714 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
6715 if( nArg<2 || nArg>3 ){
6716 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
6717 rc = 1;
6719 if( nArg>=2 ){
6720 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
6721 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
6723 if( nArg>=3 ){
6724 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6725 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
6727 }else
6729 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6730 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6731 int i; /* Loop counter */
6732 int bSchema = 0; /* Also hash the schema */
6733 int bSeparate = 0; /* Hash each table separately */
6734 int iSize = 224; /* Hash algorithm to use */
6735 int bDebug = 0; /* Only show the query that would have run */
6736 sqlite3_stmt *pStmt; /* For querying tables names */
6737 char *zSql; /* SQL to be run */
6738 char *zSep; /* Separator */
6739 ShellText sSql; /* Complete SQL for the query to run the hash */
6740 ShellText sQuery; /* Set of queries used to read all content */
6741 open_db(p, 0);
6742 for(i=1; i<nArg; i++){
6743 const char *z = azArg[i];
6744 if( z[0]=='-' ){
6745 z++;
6746 if( z[0]=='-' ) z++;
6747 if( strcmp(z,"schema")==0 ){
6748 bSchema = 1;
6749 }else
6750 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6751 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6753 iSize = atoi(&z[5]);
6754 }else
6755 if( strcmp(z,"debug")==0 ){
6756 bDebug = 1;
6757 }else
6759 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6760 azArg[i], azArg[0]);
6761 raw_printf(stderr, "Should be one of: --schema"
6762 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6763 rc = 1;
6764 goto meta_command_exit;
6766 }else if( zLike ){
6767 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6768 rc = 1;
6769 goto meta_command_exit;
6770 }else{
6771 zLike = z;
6772 bSeparate = 1;
6773 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
6776 if( bSchema ){
6777 zSql = "SELECT lower(name) FROM sqlite_master"
6778 " WHERE type='table' AND coalesce(rootpage,0)>1"
6779 " UNION ALL SELECT 'sqlite_master'"
6780 " ORDER BY 1 collate nocase";
6781 }else{
6782 zSql = "SELECT lower(name) FROM sqlite_master"
6783 " WHERE type='table' AND coalesce(rootpage,0)>1"
6784 " AND name NOT LIKE 'sqlite_%'"
6785 " ORDER BY 1 collate nocase";
6787 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6788 initText(&sQuery);
6789 initText(&sSql);
6790 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6791 zSep = "VALUES(";
6792 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6793 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6794 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6795 if( strncmp(zTab, "sqlite_",7)!=0 ){
6796 appendText(&sQuery,"SELECT * FROM ", 0);
6797 appendText(&sQuery,zTab,'"');
6798 appendText(&sQuery," NOT INDEXED;", 0);
6799 }else if( strcmp(zTab, "sqlite_master")==0 ){
6800 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6801 " ORDER BY name;", 0);
6802 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6803 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6804 " ORDER BY name;", 0);
6805 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6806 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6807 " ORDER BY tbl,idx;", 0);
6808 }else if( strcmp(zTab, "sqlite_stat3")==0
6809 || strcmp(zTab, "sqlite_stat4")==0 ){
6810 appendText(&sQuery, "SELECT * FROM ", 0);
6811 appendText(&sQuery, zTab, 0);
6812 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6814 appendText(&sSql, zSep, 0);
6815 appendText(&sSql, sQuery.z, '\'');
6816 sQuery.n = 0;
6817 appendText(&sSql, ",", 0);
6818 appendText(&sSql, zTab, '\'');
6819 zSep = "),(";
6821 sqlite3_finalize(pStmt);
6822 if( bSeparate ){
6823 zSql = sqlite3_mprintf(
6824 "%s))"
6825 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6826 " FROM [sha3sum$query]",
6827 sSql.z, iSize);
6828 }else{
6829 zSql = sqlite3_mprintf(
6830 "%s))"
6831 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6832 " FROM [sha3sum$query]",
6833 sSql.z, iSize);
6835 freeText(&sQuery);
6836 freeText(&sSql);
6837 if( bDebug ){
6838 utf8_printf(p->out, "%s\n", zSql);
6839 }else{
6840 shell_exec(p->db, zSql, shell_callback, p, 0);
6842 sqlite3_free(zSql);
6843 }else
6845 if( c=='s'
6846 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6848 char *zCmd;
6849 int i, x;
6850 if( nArg<2 ){
6851 raw_printf(stderr, "Usage: .system COMMAND\n");
6852 rc = 1;
6853 goto meta_command_exit;
6855 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6856 for(i=2; i<nArg; i++){
6857 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6858 zCmd, azArg[i]);
6860 x = system(zCmd);
6861 sqlite3_free(zCmd);
6862 if( x ) raw_printf(stderr, "System command returns %d\n", x);
6863 }else
6865 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
6866 static const char *azBool[] = { "off", "on", "trigger", "full"};
6867 int i;
6868 if( nArg!=1 ){
6869 raw_printf(stderr, "Usage: .show\n");
6870 rc = 1;
6871 goto meta_command_exit;
6873 utf8_printf(p->out, "%12.12s: %s\n","echo",
6874 azBool[ShellHasFlag(p, SHFLG_Echo)]);
6875 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6876 utf8_printf(p->out, "%12.12s: %s\n","explain",
6877 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6878 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6879 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6880 utf8_printf(p->out, "%12.12s: ", "nullvalue");
6881 output_c_string(p->out, p->nullValue);
6882 raw_printf(p->out, "\n");
6883 utf8_printf(p->out,"%12.12s: %s\n","output",
6884 strlen30(p->outfile) ? p->outfile : "stdout");
6885 utf8_printf(p->out,"%12.12s: ", "colseparator");
6886 output_c_string(p->out, p->colSeparator);
6887 raw_printf(p->out, "\n");
6888 utf8_printf(p->out,"%12.12s: ", "rowseparator");
6889 output_c_string(p->out, p->rowSeparator);
6890 raw_printf(p->out, "\n");
6891 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6892 utf8_printf(p->out, "%12.12s: ", "width");
6893 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6894 raw_printf(p->out, "%d ", p->colWidth[i]);
6896 raw_printf(p->out, "\n");
6897 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6898 p->zDbFilename ? p->zDbFilename : "");
6899 }else
6901 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6902 if( nArg==2 ){
6903 p->statsOn = booleanValue(azArg[1]);
6904 }else if( nArg==1 ){
6905 display_stats(p->db, p, 0);
6906 }else{
6907 raw_printf(stderr, "Usage: .stats ?on|off?\n");
6908 rc = 1;
6910 }else
6912 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6913 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6914 || strncmp(azArg[0], "indexes", n)==0) )
6916 sqlite3_stmt *pStmt;
6917 char **azResult;
6918 int nRow, nAlloc;
6919 int ii;
6920 ShellText s;
6921 initText(&s);
6922 open_db(p, 0);
6923 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6924 if( rc ) return shellDatabaseError(p->db);
6926 if( nArg>2 && c=='i' ){
6927 /* It is an historical accident that the .indexes command shows an error
6928 ** when called with the wrong number of arguments whereas the .tables
6929 ** command does not. */
6930 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6931 rc = 1;
6932 goto meta_command_exit;
6934 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6935 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6936 if( zDbName==0 ) continue;
6937 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6938 if( sqlite3_stricmp(zDbName, "main")==0 ){
6939 appendText(&s, "SELECT name FROM ", 0);
6940 }else{
6941 appendText(&s, "SELECT ", 0);
6942 appendText(&s, zDbName, '\'');
6943 appendText(&s, "||'.'||name FROM ", 0);
6945 appendText(&s, zDbName, '"');
6946 appendText(&s, ".sqlite_master ", 0);
6947 if( c=='t' ){
6948 appendText(&s," WHERE type IN ('table','view')"
6949 " AND name NOT LIKE 'sqlite_%'"
6950 " AND name LIKE ?1", 0);
6951 }else{
6952 appendText(&s," WHERE type='index'"
6953 " AND tbl_name LIKE ?1", 0);
6956 rc = sqlite3_finalize(pStmt);
6957 appendText(&s, " ORDER BY 1", 0);
6958 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6959 freeText(&s);
6960 if( rc ) return shellDatabaseError(p->db);
6962 /* Run the SQL statement prepared by the above block. Store the results
6963 ** as an array of nul-terminated strings in azResult[]. */
6964 nRow = nAlloc = 0;
6965 azResult = 0;
6966 if( nArg>1 ){
6967 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6968 }else{
6969 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6971 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6972 if( nRow>=nAlloc ){
6973 char **azNew;
6974 int n2 = nAlloc*2 + 10;
6975 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6976 if( azNew==0 ){
6977 rc = shellNomemError();
6978 break;
6980 nAlloc = n2;
6981 azResult = azNew;
6983 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6984 if( 0==azResult[nRow] ){
6985 rc = shellNomemError();
6986 break;
6988 nRow++;
6990 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6991 rc = shellDatabaseError(p->db);
6994 /* Pretty-print the contents of array azResult[] to the output */
6995 if( rc==0 && nRow>0 ){
6996 int len, maxlen = 0;
6997 int i, j;
6998 int nPrintCol, nPrintRow;
6999 for(i=0; i<nRow; i++){
7000 len = strlen30(azResult[i]);
7001 if( len>maxlen ) maxlen = len;
7003 nPrintCol = 80/(maxlen+2);
7004 if( nPrintCol<1 ) nPrintCol = 1;
7005 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7006 for(i=0; i<nPrintRow; i++){
7007 for(j=i; j<nRow; j+=nPrintRow){
7008 char *zSp = j<nPrintRow ? "" : " ";
7009 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7010 azResult[j] ? azResult[j]:"");
7012 raw_printf(p->out, "\n");
7016 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7017 sqlite3_free(azResult);
7018 }else
7020 /* Begin redirecting output to the file "testcase-out.txt" */
7021 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7022 output_reset(p);
7023 p->out = output_file_open("testcase-out.txt");
7024 if( p->out==0 ){
7025 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7027 if( nArg>=2 ){
7028 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7029 }else{
7030 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7032 }else
7034 #ifndef SQLITE_UNTESTABLE
7035 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
7036 static const struct {
7037 const char *zCtrlName; /* Name of a test-control option */
7038 int ctrlCode; /* Integer code for that option */
7039 const char *zUsage; /* Usage notes */
7040 } aCtrl[] = {
7041 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7042 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7043 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7044 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7045 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7046 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7047 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
7048 #ifdef SQLITE_N_KEYWORD
7049 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" },
7050 #endif
7051 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7052 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7053 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
7054 #ifdef YYCOVERAGE
7055 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7056 #endif
7057 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7058 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7059 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7060 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7061 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
7063 int testctrl = -1;
7064 int iCtrl = -1;
7065 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7066 int isOk = 0;
7067 int i, n2;
7068 const char *zCmd = 0;
7070 open_db(p, 0);
7071 zCmd = nArg>=2 ? azArg[1] : "help";
7073 /* The argument can optionally begin with "-" or "--" */
7074 if( zCmd[0]=='-' && zCmd[1] ){
7075 zCmd++;
7076 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7079 /* --help lists all test-controls */
7080 if( strcmp(zCmd,"help")==0 ){
7081 utf8_printf(p->out, "Available test-controls:\n");
7082 for(i=0; i<ArraySize(aCtrl); i++){
7083 utf8_printf(p->out, " .testctrl %s %s\n",
7084 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7086 rc = 1;
7087 goto meta_command_exit;
7090 /* convert testctrl text option to value. allow any unique prefix
7091 ** of the option name, or a numerical value. */
7092 n2 = strlen30(zCmd);
7093 for(i=0; i<ArraySize(aCtrl); i++){
7094 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7095 if( testctrl<0 ){
7096 testctrl = aCtrl[i].ctrlCode;
7097 iCtrl = i;
7098 }else{
7099 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7100 "Use \".testctrl --help\" for help\n", zCmd);
7101 rc = 1;
7102 goto meta_command_exit;
7106 if( testctrl<0 ){
7107 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7108 "Use \".testctrl --help\" for help\n", zCmd);
7109 }else{
7110 switch(testctrl){
7112 /* sqlite3_test_control(int, db, int) */
7113 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7114 case SQLITE_TESTCTRL_RESERVE:
7115 if( nArg==3 ){
7116 int opt = (int)strtol(azArg[2], 0, 0);
7117 rc2 = sqlite3_test_control(testctrl, p->db, opt);
7118 isOk = 3;
7120 break;
7122 /* sqlite3_test_control(int) */
7123 case SQLITE_TESTCTRL_PRNG_SAVE:
7124 case SQLITE_TESTCTRL_PRNG_RESTORE:
7125 case SQLITE_TESTCTRL_PRNG_RESET:
7126 case SQLITE_TESTCTRL_BYTEORDER:
7127 if( nArg==2 ){
7128 rc2 = sqlite3_test_control(testctrl);
7129 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
7131 break;
7133 /* sqlite3_test_control(int, uint) */
7134 case SQLITE_TESTCTRL_PENDING_BYTE:
7135 if( nArg==3 ){
7136 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7137 rc2 = sqlite3_test_control(testctrl, opt);
7138 isOk = 3;
7140 break;
7142 /* sqlite3_test_control(int, int) */
7143 case SQLITE_TESTCTRL_ASSERT:
7144 case SQLITE_TESTCTRL_ALWAYS:
7145 if( nArg==3 ){
7146 int opt = booleanValue(azArg[2]);
7147 rc2 = sqlite3_test_control(testctrl, opt);
7148 isOk = 1;
7150 break;
7152 /* sqlite3_test_control(int, int) */
7153 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
7154 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7155 if( nArg==3 ){
7156 int opt = booleanValue(azArg[2]);
7157 rc2 = sqlite3_test_control(testctrl, opt);
7158 isOk = 3;
7160 break;
7162 /* sqlite3_test_control(int, char *) */
7163 #ifdef SQLITE_N_KEYWORD
7164 case SQLITE_TESTCTRL_ISKEYWORD:
7165 if( nArg==3 ){
7166 const char *opt = azArg[2];
7167 rc2 = sqlite3_test_control(testctrl, opt);
7168 isOk = 1;
7170 break;
7171 #endif
7173 case SQLITE_TESTCTRL_IMPOSTER:
7174 if( nArg==5 ){
7175 rc2 = sqlite3_test_control(testctrl, p->db,
7176 azArg[2],
7177 integerValue(azArg[3]),
7178 integerValue(azArg[4]));
7179 isOk = 3;
7181 break;
7183 #ifdef YYCOVERAGE
7184 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7185 if( nArg==2 ){
7186 sqlite3_test_control(testctrl, p->out);
7187 isOk = 3;
7189 #endif
7192 if( isOk==0 && iCtrl>=0 ){
7193 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7194 rc = 1;
7195 }else if( isOk==1 ){
7196 raw_printf(p->out, "%d\n", rc2);
7197 }else if( isOk==2 ){
7198 raw_printf(p->out, "0x%08x\n", rc2);
7200 }else
7201 #endif /* !defined(SQLITE_UNTESTABLE) */
7203 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7204 open_db(p, 0);
7205 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7206 }else
7208 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7209 if( nArg==2 ){
7210 enableTimer = booleanValue(azArg[1]);
7211 if( enableTimer && !HAS_TIMER ){
7212 raw_printf(stderr, "Error: timer not available on this system.\n");
7213 enableTimer = 0;
7215 }else{
7216 raw_printf(stderr, "Usage: .timer on|off\n");
7217 rc = 1;
7219 }else
7221 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7222 open_db(p, 0);
7223 if( nArg!=2 ){
7224 raw_printf(stderr, "Usage: .trace FILE|off\n");
7225 rc = 1;
7226 goto meta_command_exit;
7228 output_file_close(p->traceOut);
7229 p->traceOut = output_file_open(azArg[1]);
7230 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7231 if( p->traceOut==0 ){
7232 sqlite3_trace_v2(p->db, 0, 0, 0);
7233 }else{
7234 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7236 #endif
7237 }else
7239 #if SQLITE_USER_AUTHENTICATION
7240 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7241 if( nArg<2 ){
7242 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7243 rc = 1;
7244 goto meta_command_exit;
7246 open_db(p, 0);
7247 if( strcmp(azArg[1],"login")==0 ){
7248 if( nArg!=4 ){
7249 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7250 rc = 1;
7251 goto meta_command_exit;
7253 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
7254 if( rc ){
7255 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7256 rc = 1;
7258 }else if( strcmp(azArg[1],"add")==0 ){
7259 if( nArg!=5 ){
7260 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7261 rc = 1;
7262 goto meta_command_exit;
7264 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
7265 booleanValue(azArg[4]));
7266 if( rc ){
7267 raw_printf(stderr, "User-Add failed: %d\n", rc);
7268 rc = 1;
7270 }else if( strcmp(azArg[1],"edit")==0 ){
7271 if( nArg!=5 ){
7272 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7273 rc = 1;
7274 goto meta_command_exit;
7276 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
7277 booleanValue(azArg[4]));
7278 if( rc ){
7279 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7280 rc = 1;
7282 }else if( strcmp(azArg[1],"delete")==0 ){
7283 if( nArg!=3 ){
7284 raw_printf(stderr, "Usage: .user delete USER\n");
7285 rc = 1;
7286 goto meta_command_exit;
7288 rc = sqlite3_user_delete(p->db, azArg[2]);
7289 if( rc ){
7290 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7291 rc = 1;
7293 }else{
7294 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7295 rc = 1;
7296 goto meta_command_exit;
7298 }else
7299 #endif /* SQLITE_USER_AUTHENTICATION */
7301 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7302 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7303 sqlite3_libversion(), sqlite3_sourceid());
7304 }else
7306 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7307 const char *zDbName = nArg==2 ? azArg[1] : "main";
7308 sqlite3_vfs *pVfs = 0;
7309 if( p->db ){
7310 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7311 if( pVfs ){
7312 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7313 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7314 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7315 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7318 }else
7320 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7321 sqlite3_vfs *pVfs;
7322 sqlite3_vfs *pCurrent = 0;
7323 if( p->db ){
7324 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7326 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7327 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7328 pVfs==pCurrent ? " <--- CURRENT" : "");
7329 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7330 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7331 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7332 if( pVfs->pNext ){
7333 raw_printf(p->out, "-----------------------------------\n");
7336 }else
7338 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7339 const char *zDbName = nArg==2 ? azArg[1] : "main";
7340 char *zVfsName = 0;
7341 if( p->db ){
7342 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7343 if( zVfsName ){
7344 utf8_printf(p->out, "%s\n", zVfsName);
7345 sqlite3_free(zVfsName);
7348 }else
7350 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7351 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7352 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7353 }else
7354 #endif
7356 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7357 int j;
7358 assert( nArg<=ArraySize(azArg) );
7359 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7360 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7362 }else
7365 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7366 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7367 rc = 1;
7370 meta_command_exit:
7371 if( p->outCount ){
7372 p->outCount--;
7373 if( p->outCount==0 ) output_reset(p);
7375 return rc;
7379 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7380 ** of string z[].
7382 static int line_contains_semicolon(const char *z, int N){
7383 int i;
7384 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7385 return 0;
7389 ** Test to see if a line consists entirely of whitespace.
7391 static int _all_whitespace(const char *z){
7392 for(; *z; z++){
7393 if( IsSpace(z[0]) ) continue;
7394 if( *z=='/' && z[1]=='*' ){
7395 z += 2;
7396 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7397 if( *z==0 ) return 0;
7398 z++;
7399 continue;
7401 if( *z=='-' && z[1]=='-' ){
7402 z += 2;
7403 while( *z && *z!='\n' ){ z++; }
7404 if( *z==0 ) return 1;
7405 continue;
7407 return 0;
7409 return 1;
7413 ** Return TRUE if the line typed in is an SQL command terminator other
7414 ** than a semi-colon. The SQL Server style "go" command is understood
7415 ** as is the Oracle "/".
7417 static int line_is_command_terminator(const char *zLine){
7418 while( IsSpace(zLine[0]) ){ zLine++; };
7419 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7420 return 1; /* Oracle */
7422 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7423 && _all_whitespace(&zLine[2]) ){
7424 return 1; /* SQL Server */
7426 return 0;
7430 ** Return true if zSql is a complete SQL statement. Return false if it
7431 ** ends in the middle of a string literal or C-style comment.
7433 static int line_is_complete(char *zSql, int nSql){
7434 int rc;
7435 if( zSql==0 ) return 1;
7436 zSql[nSql] = ';';
7437 zSql[nSql+1] = 0;
7438 rc = sqlite3_complete(zSql);
7439 zSql[nSql] = 0;
7440 return rc;
7444 ** Run a single line of SQL
7446 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7447 int rc;
7448 char *zErrMsg = 0;
7450 open_db(p, 0);
7451 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7452 BEGIN_TIMER;
7453 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
7454 END_TIMER;
7455 if( rc || zErrMsg ){
7456 char zPrefix[100];
7457 if( in!=0 || !stdin_is_interactive ){
7458 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7459 "Error: near line %d:", startline);
7460 }else{
7461 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7463 if( zErrMsg!=0 ){
7464 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7465 sqlite3_free(zErrMsg);
7466 zErrMsg = 0;
7467 }else{
7468 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7470 return 1;
7471 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7472 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7473 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7475 return 0;
7480 ** Read input from *in and process it. If *in==0 then input
7481 ** is interactive - the user is typing it it. Otherwise, input
7482 ** is coming from a file or device. A prompt is issued and history
7483 ** is saved only if input is interactive. An interrupt signal will
7484 ** cause this routine to exit immediately, unless input is interactive.
7486 ** Return the number of errors.
7488 static int process_input(ShellState *p, FILE *in){
7489 char *zLine = 0; /* A single input line */
7490 char *zSql = 0; /* Accumulated SQL text */
7491 int nLine; /* Length of current line */
7492 int nSql = 0; /* Bytes of zSql[] used */
7493 int nAlloc = 0; /* Allocated zSql[] space */
7494 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7495 int rc; /* Error code */
7496 int errCnt = 0; /* Number of errors seen */
7497 int lineno = 0; /* Current line number */
7498 int startline = 0; /* Line number for start of current input */
7500 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7501 fflush(p->out);
7502 zLine = one_input_line(in, zLine, nSql>0);
7503 if( zLine==0 ){
7504 /* End of input */
7505 if( in==0 && stdin_is_interactive ) printf("\n");
7506 break;
7508 if( seenInterrupt ){
7509 if( in!=0 ) break;
7510 seenInterrupt = 0;
7512 lineno++;
7513 if( nSql==0 && _all_whitespace(zLine) ){
7514 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7515 continue;
7517 if( zLine && zLine[0]=='.' && nSql==0 ){
7518 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7519 rc = do_meta_command(zLine, p);
7520 if( rc==2 ){ /* exit requested */
7521 break;
7522 }else if( rc ){
7523 errCnt++;
7525 continue;
7527 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
7528 memcpy(zLine,";",2);
7530 nLine = strlen30(zLine);
7531 if( nSql+nLine+2>=nAlloc ){
7532 nAlloc = nSql+nLine+100;
7533 zSql = realloc(zSql, nAlloc);
7534 if( zSql==0 ){
7535 raw_printf(stderr, "Error: out of memory\n");
7536 exit(1);
7539 nSqlPrior = nSql;
7540 if( nSql==0 ){
7541 int i;
7542 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
7543 assert( nAlloc>0 && zSql!=0 );
7544 memcpy(zSql, zLine+i, nLine+1-i);
7545 startline = lineno;
7546 nSql = nLine-i;
7547 }else{
7548 zSql[nSql++] = '\n';
7549 memcpy(zSql+nSql, zLine, nLine+1);
7550 nSql += nLine;
7552 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
7553 && sqlite3_complete(zSql) ){
7554 errCnt += runOneSqlLine(p, zSql, in, startline);
7555 nSql = 0;
7556 if( p->outCount ){
7557 output_reset(p);
7558 p->outCount = 0;
7560 }else if( nSql && _all_whitespace(zSql) ){
7561 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
7562 nSql = 0;
7565 if( nSql && !_all_whitespace(zSql) ){
7566 runOneSqlLine(p, zSql, in, startline);
7568 free(zSql);
7569 free(zLine);
7570 return errCnt>0;
7574 ** Return a pathname which is the user's home directory. A
7575 ** 0 return indicates an error of some kind.
7577 static char *find_home_dir(int clearFlag){
7578 static char *home_dir = NULL;
7579 if( clearFlag ){
7580 free(home_dir);
7581 home_dir = 0;
7582 return 0;
7584 if( home_dir ) return home_dir;
7586 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7587 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7589 struct passwd *pwent;
7590 uid_t uid = getuid();
7591 if( (pwent=getpwuid(uid)) != NULL) {
7592 home_dir = pwent->pw_dir;
7595 #endif
7597 #if defined(_WIN32_WCE)
7598 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7600 home_dir = "/";
7601 #else
7603 #if defined(_WIN32) || defined(WIN32)
7604 if (!home_dir) {
7605 home_dir = getenv("USERPROFILE");
7607 #endif
7609 if (!home_dir) {
7610 home_dir = getenv("HOME");
7613 #if defined(_WIN32) || defined(WIN32)
7614 if (!home_dir) {
7615 char *zDrive, *zPath;
7616 int n;
7617 zDrive = getenv("HOMEDRIVE");
7618 zPath = getenv("HOMEPATH");
7619 if( zDrive && zPath ){
7620 n = strlen30(zDrive) + strlen30(zPath) + 1;
7621 home_dir = malloc( n );
7622 if( home_dir==0 ) return 0;
7623 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7624 return home_dir;
7626 home_dir = "c:\\";
7628 #endif
7630 #endif /* !_WIN32_WCE */
7632 if( home_dir ){
7633 int n = strlen30(home_dir) + 1;
7634 char *z = malloc( n );
7635 if( z ) memcpy(z, home_dir, n);
7636 home_dir = z;
7639 return home_dir;
7643 ** Read input from the file given by sqliterc_override. Or if that
7644 ** parameter is NULL, take input from ~/.sqliterc
7646 ** Returns the number of errors.
7648 static void process_sqliterc(
7649 ShellState *p, /* Configuration data */
7650 const char *sqliterc_override /* Name of config file. NULL to use default */
7652 char *home_dir = NULL;
7653 const char *sqliterc = sqliterc_override;
7654 char *zBuf = 0;
7655 FILE *in = NULL;
7657 if (sqliterc == NULL) {
7658 home_dir = find_home_dir(0);
7659 if( home_dir==0 ){
7660 raw_printf(stderr, "-- warning: cannot find home directory;"
7661 " cannot read ~/.sqliterc\n");
7662 return;
7664 sqlite3_initialize();
7665 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7666 sqliterc = zBuf;
7668 in = fopen(sqliterc,"rb");
7669 if( in ){
7670 if( stdin_is_interactive ){
7671 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
7673 process_input(p,in);
7674 fclose(in);
7676 sqlite3_free(zBuf);
7680 ** Show available command line options
7682 static const char zOptions[] =
7683 " -ascii set output mode to 'ascii'\n"
7684 " -bail stop after hitting an error\n"
7685 " -batch force batch I/O\n"
7686 " -column set output mode to 'column'\n"
7687 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7688 " -csv set output mode to 'csv'\n"
7689 " -echo print commands before execution\n"
7690 " -init FILENAME read/process named file\n"
7691 " -[no]header turn headers on or off\n"
7692 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7693 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7694 #endif
7695 " -help show this message\n"
7696 " -html set output mode to HTML\n"
7697 " -interactive force interactive I/O\n"
7698 " -line set output mode to 'line'\n"
7699 " -list set output mode to 'list'\n"
7700 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7701 " -mmap N default mmap size set to N\n"
7702 #ifdef SQLITE_ENABLE_MULTIPLEX
7703 " -multiplex enable the multiplexor VFS\n"
7704 #endif
7705 " -newline SEP set output row separator. Default: '\\n'\n"
7706 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7707 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7708 " -quote set output mode to 'quote'\n"
7709 " -separator SEP set output column separator. Default: '|'\n"
7710 " -stats print memory stats before each finalize\n"
7711 " -version show SQLite version\n"
7712 " -vfs NAME use NAME as the default VFS\n"
7713 #ifdef SQLITE_ENABLE_VFSTRACE
7714 " -vfstrace enable tracing of all VFS calls\n"
7715 #endif
7717 static void usage(int showDetail){
7718 utf8_printf(stderr,
7719 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7720 "FILENAME is the name of an SQLite database. A new database is created\n"
7721 "if the file does not previously exist.\n", Argv0);
7722 if( showDetail ){
7723 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
7724 }else{
7725 raw_printf(stderr, "Use the -help option for additional information\n");
7727 exit(1);
7731 ** Initialize the state information in data
7733 static void main_init(ShellState *data) {
7734 memset(data, 0, sizeof(*data));
7735 data->normalMode = data->cMode = data->mode = MODE_List;
7736 data->autoExplain = 1;
7737 memcpy(data->colSeparator,SEP_Column, 2);
7738 memcpy(data->rowSeparator,SEP_Row, 2);
7739 data->showHeader = 0;
7740 data->shellFlgs = SHFLG_Lookaside;
7741 sqlite3_config(SQLITE_CONFIG_URI, 1);
7742 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
7743 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
7744 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7745 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
7749 ** Output text to the console in a font that attracts extra attention.
7751 #ifdef _WIN32
7752 static void printBold(const char *zText){
7753 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7754 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7755 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7756 SetConsoleTextAttribute(out,
7757 FOREGROUND_RED|FOREGROUND_INTENSITY
7759 printf("%s", zText);
7760 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
7762 #else
7763 static void printBold(const char *zText){
7764 printf("\033[1m%s\033[0m", zText);
7766 #endif
7769 ** Get the argument to an --option. Throw an error and die if no argument
7770 ** is available.
7772 static char *cmdline_option_value(int argc, char **argv, int i){
7773 if( i==argc ){
7774 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
7775 argv[0], argv[argc-1]);
7776 exit(1);
7778 return argv[i];
7781 #ifndef SQLITE_SHELL_IS_UTF8
7782 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7783 # define SQLITE_SHELL_IS_UTF8 (0)
7784 # else
7785 # define SQLITE_SHELL_IS_UTF8 (1)
7786 # endif
7787 #endif
7789 #if SQLITE_SHELL_IS_UTF8
7790 int SQLITE_CDECL main(int argc, char **argv){
7791 #else
7792 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7793 char **argv;
7794 #endif
7795 char *zErrMsg = 0;
7796 ShellState data;
7797 const char *zInitFile = 0;
7798 int i;
7799 int rc = 0;
7800 int warnInmemoryDb = 0;
7801 int readStdin = 1;
7802 int nCmd = 0;
7803 char **azCmd = 0;
7805 setBinaryMode(stdin, 0);
7806 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7807 stdin_is_interactive = isatty(0);
7808 stdout_is_console = isatty(1);
7810 #if USE_SYSTEM_SQLITE+0!=1
7811 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
7812 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7813 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7814 exit(1);
7816 #endif
7817 main_init(&data);
7818 #if !SQLITE_SHELL_IS_UTF8
7819 sqlite3_initialize();
7820 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7821 if( argv==0 ){
7822 raw_printf(stderr, "out of memory\n");
7823 exit(1);
7825 for(i=0; i<argc; i++){
7826 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7827 if( argv[i]==0 ){
7828 raw_printf(stderr, "out of memory\n");
7829 exit(1);
7832 #endif
7833 assert( argc>=1 && argv && argv[0] );
7834 Argv0 = argv[0];
7836 /* Make sure we have a valid signal handler early, before anything
7837 ** else is done.
7839 #ifdef SIGINT
7840 signal(SIGINT, interrupt_handler);
7841 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
7842 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
7843 #endif
7845 #ifdef SQLITE_SHELL_DBNAME_PROC
7847 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7848 ** of a C-function that will provide the name of the database file. Use
7849 ** this compile-time option to embed this shell program in larger
7850 ** applications. */
7851 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7852 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7853 warnInmemoryDb = 0;
7855 #endif
7857 /* Do an initial pass through the command-line argument to locate
7858 ** the name of the database file, the name of the initialization file,
7859 ** the size of the alternative malloc heap,
7860 ** and the first command to execute.
7862 for(i=1; i<argc; i++){
7863 char *z;
7864 z = argv[i];
7865 if( z[0]!='-' ){
7866 if( data.zDbFilename==0 ){
7867 data.zDbFilename = z;
7868 }else{
7869 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7870 ** mean that nothing is read from stdin */
7871 readStdin = 0;
7872 nCmd++;
7873 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7874 if( azCmd==0 ){
7875 raw_printf(stderr, "out of memory\n");
7876 exit(1);
7878 azCmd[nCmd-1] = z;
7881 if( z[1]=='-' ) z++;
7882 if( strcmp(z,"-separator")==0
7883 || strcmp(z,"-nullvalue")==0
7884 || strcmp(z,"-newline")==0
7885 || strcmp(z,"-cmd")==0
7887 (void)cmdline_option_value(argc, argv, ++i);
7888 }else if( strcmp(z,"-init")==0 ){
7889 zInitFile = cmdline_option_value(argc, argv, ++i);
7890 }else if( strcmp(z,"-batch")==0 ){
7891 /* Need to check for batch mode here to so we can avoid printing
7892 ** informational messages (like from process_sqliterc) before
7893 ** we do the actual processing of arguments later in a second pass.
7895 stdin_is_interactive = 0;
7896 }else if( strcmp(z,"-heap")==0 ){
7897 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7898 const char *zSize;
7899 sqlite3_int64 szHeap;
7901 zSize = cmdline_option_value(argc, argv, ++i);
7902 szHeap = integerValue(zSize);
7903 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7904 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7905 #else
7906 (void)cmdline_option_value(argc, argv, ++i);
7907 #endif
7908 }else if( strcmp(z,"-pagecache")==0 ){
7909 int n, sz;
7910 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7911 if( sz>70000 ) sz = 70000;
7912 if( sz<0 ) sz = 0;
7913 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7914 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7915 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7916 data.shellFlgs |= SHFLG_Pagecache;
7917 }else if( strcmp(z,"-lookaside")==0 ){
7918 int n, sz;
7919 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7920 if( sz<0 ) sz = 0;
7921 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7922 if( n<0 ) n = 0;
7923 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7924 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7925 #ifdef SQLITE_ENABLE_VFSTRACE
7926 }else if( strcmp(z,"-vfstrace")==0 ){
7927 extern int vfstrace_register(
7928 const char *zTraceName,
7929 const char *zOldVfsName,
7930 int (*xOut)(const char*,void*),
7931 void *pOutArg,
7932 int makeDefault
7934 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7935 #endif
7936 #ifdef SQLITE_ENABLE_MULTIPLEX
7937 }else if( strcmp(z,"-multiplex")==0 ){
7938 extern int sqlite3_multiple_initialize(const char*,int);
7939 sqlite3_multiplex_initialize(0, 1);
7940 #endif
7941 }else if( strcmp(z,"-mmap")==0 ){
7942 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7943 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7944 }else if( strcmp(z,"-vfs")==0 ){
7945 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7946 if( pVfs ){
7947 sqlite3_vfs_register(pVfs, 1);
7948 }else{
7949 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7950 exit(1);
7952 #ifdef SQLITE_HAVE_ZIP
7953 }else if( strcmp(z,"-zip")==0 ){
7954 data.openMode = SHELL_OPEN_ZIPFILE;
7955 #endif
7956 }else if( strcmp(z,"-append")==0 ){
7957 data.openMode = SHELL_OPEN_APPENDVFS;
7960 if( data.zDbFilename==0 ){
7961 #ifndef SQLITE_OMIT_MEMORYDB
7962 data.zDbFilename = ":memory:";
7963 warnInmemoryDb = argc==1;
7964 #else
7965 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7966 return 1;
7967 #endif
7969 data.out = stdout;
7970 sqlite3_appendvfs_init(0,0,0);
7972 /* Go ahead and open the database file if it already exists. If the
7973 ** file does not exist, delay opening it. This prevents empty database
7974 ** files from being created if a user mistypes the database name argument
7975 ** to the sqlite command-line tool.
7977 if( access(data.zDbFilename, 0)==0 ){
7978 open_db(&data, 0);
7981 /* Process the initialization file if there is one. If no -init option
7982 ** is given on the command line, look for a file named ~/.sqliterc and
7983 ** try to process it.
7985 process_sqliterc(&data,zInitFile);
7987 /* Make a second pass through the command-line argument and set
7988 ** options. This second pass is delayed until after the initialization
7989 ** file is processed so that the command-line arguments will override
7990 ** settings in the initialization file.
7992 for(i=1; i<argc; i++){
7993 char *z = argv[i];
7994 if( z[0]!='-' ) continue;
7995 if( z[1]=='-' ){ z++; }
7996 if( strcmp(z,"-init")==0 ){
7997 i++;
7998 }else if( strcmp(z,"-html")==0 ){
7999 data.mode = MODE_Html;
8000 }else if( strcmp(z,"-list")==0 ){
8001 data.mode = MODE_List;
8002 }else if( strcmp(z,"-quote")==0 ){
8003 data.mode = MODE_Quote;
8004 }else if( strcmp(z,"-line")==0 ){
8005 data.mode = MODE_Line;
8006 }else if( strcmp(z,"-column")==0 ){
8007 data.mode = MODE_Column;
8008 }else if( strcmp(z,"-csv")==0 ){
8009 data.mode = MODE_Csv;
8010 memcpy(data.colSeparator,",",2);
8011 #ifdef SQLITE_HAVE_ZIP
8012 }else if( strcmp(z,"-zip")==0 ){
8013 data.openMode = SHELL_OPEN_ZIPFILE;
8014 #endif
8015 }else if( strcmp(z,"-append")==0 ){
8016 data.openMode = SHELL_OPEN_APPENDVFS;
8017 }else if( strcmp(z,"-ascii")==0 ){
8018 data.mode = MODE_Ascii;
8019 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8020 SEP_Unit);
8021 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8022 SEP_Record);
8023 }else if( strcmp(z,"-separator")==0 ){
8024 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8025 "%s",cmdline_option_value(argc,argv,++i));
8026 }else if( strcmp(z,"-newline")==0 ){
8027 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8028 "%s",cmdline_option_value(argc,argv,++i));
8029 }else if( strcmp(z,"-nullvalue")==0 ){
8030 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8031 "%s",cmdline_option_value(argc,argv,++i));
8032 }else if( strcmp(z,"-header")==0 ){
8033 data.showHeader = 1;
8034 }else if( strcmp(z,"-noheader")==0 ){
8035 data.showHeader = 0;
8036 }else if( strcmp(z,"-echo")==0 ){
8037 ShellSetFlag(&data, SHFLG_Echo);
8038 }else if( strcmp(z,"-eqp")==0 ){
8039 data.autoEQP = AUTOEQP_on;
8040 }else if( strcmp(z,"-eqpfull")==0 ){
8041 data.autoEQP = AUTOEQP_full;
8042 }else if( strcmp(z,"-stats")==0 ){
8043 data.statsOn = 1;
8044 }else if( strcmp(z,"-scanstats")==0 ){
8045 data.scanstatsOn = 1;
8046 }else if( strcmp(z,"-backslash")==0 ){
8047 /* Undocumented command-line option: -backslash
8048 ** Causes C-style backslash escapes to be evaluated in SQL statements
8049 ** prior to sending the SQL into SQLite. Useful for injecting
8050 ** crazy bytes in the middle of SQL statements for testing and debugging.
8052 ShellSetFlag(&data, SHFLG_Backslash);
8053 }else if( strcmp(z,"-bail")==0 ){
8054 bail_on_error = 1;
8055 }else if( strcmp(z,"-version")==0 ){
8056 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8057 return 0;
8058 }else if( strcmp(z,"-interactive")==0 ){
8059 stdin_is_interactive = 1;
8060 }else if( strcmp(z,"-batch")==0 ){
8061 stdin_is_interactive = 0;
8062 }else if( strcmp(z,"-heap")==0 ){
8063 i++;
8064 }else if( strcmp(z,"-pagecache")==0 ){
8065 i+=2;
8066 }else if( strcmp(z,"-lookaside")==0 ){
8067 i+=2;
8068 }else if( strcmp(z,"-mmap")==0 ){
8069 i++;
8070 }else if( strcmp(z,"-vfs")==0 ){
8071 i++;
8072 #ifdef SQLITE_ENABLE_VFSTRACE
8073 }else if( strcmp(z,"-vfstrace")==0 ){
8074 i++;
8075 #endif
8076 #ifdef SQLITE_ENABLE_MULTIPLEX
8077 }else if( strcmp(z,"-multiplex")==0 ){
8078 i++;
8079 #endif
8080 }else if( strcmp(z,"-help")==0 ){
8081 usage(1);
8082 }else if( strcmp(z,"-cmd")==0 ){
8083 /* Run commands that follow -cmd first and separately from commands
8084 ** that simply appear on the command-line. This seems goofy. It would
8085 ** be better if all commands ran in the order that they appear. But
8086 ** we retain the goofy behavior for historical compatibility. */
8087 if( i==argc-1 ) break;
8088 z = cmdline_option_value(argc,argv,++i);
8089 if( z[0]=='.' ){
8090 rc = do_meta_command(z, &data);
8091 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8092 }else{
8093 open_db(&data, 0);
8094 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
8095 if( zErrMsg!=0 ){
8096 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8097 if( bail_on_error ) return rc!=0 ? rc : 1;
8098 }else if( rc!=0 ){
8099 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8100 if( bail_on_error ) return rc;
8103 }else{
8104 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8105 raw_printf(stderr,"Use -help for a list of options.\n");
8106 return 1;
8108 data.cMode = data.mode;
8111 if( !readStdin ){
8112 /* Run all arguments that do not begin with '-' as if they were separate
8113 ** command-line inputs, except for the argToSkip argument which contains
8114 ** the database filename.
8116 for(i=0; i<nCmd; i++){
8117 if( azCmd[i][0]=='.' ){
8118 rc = do_meta_command(azCmd[i], &data);
8119 if( rc ) return rc==2 ? 0 : rc;
8120 }else{
8121 open_db(&data, 0);
8122 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
8123 if( zErrMsg!=0 ){
8124 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8125 return rc!=0 ? rc : 1;
8126 }else if( rc!=0 ){
8127 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8128 return rc;
8132 free(azCmd);
8133 }else{
8134 /* Run commands received from standard input
8136 if( stdin_is_interactive ){
8137 char *zHome;
8138 char *zHistory = 0;
8139 int nHistory;
8140 printf(
8141 "SQLite version %s %.19s\n" /*extra-version-info*/
8142 "Enter \".help\" for usage hints.\n",
8143 sqlite3_libversion(), sqlite3_sourceid()
8145 if( warnInmemoryDb ){
8146 printf("Connected to a ");
8147 printBold("transient in-memory database");
8148 printf(".\nUse \".open FILENAME\" to reopen on a "
8149 "persistent database.\n");
8151 zHome = find_home_dir(0);
8152 if( zHome ){
8153 nHistory = strlen30(zHome) + 20;
8154 if( (zHistory = malloc(nHistory))!=0 ){
8155 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8158 if( zHistory ){ shell_read_history(zHistory); }
8159 #if HAVE_READLINE || HAVE_EDITLINE
8160 rl_attempted_completion_function = readline_completion;
8161 #elif HAVE_LINENOISE
8162 linenoiseSetCompletionCallback(linenoise_completion);
8163 #endif
8164 rc = process_input(&data, 0);
8165 if( zHistory ){
8166 shell_stifle_history(2000);
8167 shell_write_history(zHistory);
8168 free(zHistory);
8170 }else{
8171 rc = process_input(&data, stdin);
8174 set_table_name(&data, 0);
8175 if( data.db ){
8176 session_close_all(&data);
8177 sqlite3_close(data.db);
8179 sqlite3_free(data.zFreeOnClose);
8180 find_home_dir(1);
8181 #if !SQLITE_SHELL_IS_UTF8
8182 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
8183 sqlite3_free(argv);
8184 #endif
8185 return rc;