replace use of sqlite3StrICmp with public sqlite3_stricmp API
[sqlcipher.git] / src / shell.c.in
blobecde9d8c6d250c72a8c419a40b29342ab8d126cb
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 ** Determine if we are dealing with WinRT, which provides only a subset of
22 ** the full Win32 API.
24 #if !defined(SQLITE_OS_WINRT)
25 # define SQLITE_OS_WINRT 0
26 #endif
29 ** Warning pragmas copied from msvc.h in the core.
31 #if defined(_MSC_VER)
32 #pragma warning(disable : 4054)
33 #pragma warning(disable : 4055)
34 #pragma warning(disable : 4100)
35 #pragma warning(disable : 4127)
36 #pragma warning(disable : 4130)
37 #pragma warning(disable : 4152)
38 #pragma warning(disable : 4189)
39 #pragma warning(disable : 4206)
40 #pragma warning(disable : 4210)
41 #pragma warning(disable : 4232)
42 #pragma warning(disable : 4244)
43 #pragma warning(disable : 4305)
44 #pragma warning(disable : 4306)
45 #pragma warning(disable : 4702)
46 #pragma warning(disable : 4706)
47 #endif /* defined(_MSC_VER) */
50 ** No support for loadable extensions in VxWorks.
52 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
53 # define SQLITE_OMIT_LOAD_EXTENSION 1
54 #endif
57 ** Enable large-file support for fopen() and friends on unix.
59 #ifndef SQLITE_DISABLE_LFS
60 # define _LARGE_FILE 1
61 # ifndef _FILE_OFFSET_BITS
62 # define _FILE_OFFSET_BITS 64
63 # endif
64 # define _LARGEFILE_SOURCE 1
65 #endif
67 #include <stdlib.h>
68 #include <string.h>
69 #include <stdio.h>
70 #include <assert.h>
71 #include "sqlite3.h"
72 typedef sqlite3_int64 i64;
73 typedef sqlite3_uint64 u64;
74 typedef unsigned char u8;
75 #if SQLITE_USER_AUTHENTICATION
76 # include "sqlite3userauth.h"
77 #endif
78 #include <ctype.h>
79 #include <stdarg.h>
81 #if !defined(_WIN32) && !defined(WIN32)
82 # include <signal.h>
83 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
84 # include <pwd.h>
85 # endif
86 #endif
87 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
88 # include <unistd.h>
89 # include <dirent.h>
90 # define GETPID getpid
91 # if defined(__MINGW32__)
92 # define DIRENT dirent
93 # ifndef S_ISLNK
94 # define S_ISLNK(mode) (0)
95 # endif
96 # endif
97 #else
98 # define GETPID (int)GetCurrentProcessId
99 #endif
100 #include <sys/types.h>
101 #include <sys/stat.h>
103 #if HAVE_READLINE
104 # include <readline/readline.h>
105 # include <readline/history.h>
106 #endif
108 #if HAVE_EDITLINE
109 # include <editline/readline.h>
110 #endif
112 #if HAVE_EDITLINE || HAVE_READLINE
114 # define shell_add_history(X) add_history(X)
115 # define shell_read_history(X) read_history(X)
116 # define shell_write_history(X) write_history(X)
117 # define shell_stifle_history(X) stifle_history(X)
118 # define shell_readline(X) readline(X)
120 #elif HAVE_LINENOISE
122 # include "linenoise.h"
123 # define shell_add_history(X) linenoiseHistoryAdd(X)
124 # define shell_read_history(X) linenoiseHistoryLoad(X)
125 # define shell_write_history(X) linenoiseHistorySave(X)
126 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
127 # define shell_readline(X) linenoise(X)
129 #else
131 # define shell_read_history(X)
132 # define shell_write_history(X)
133 # define shell_stifle_history(X)
135 # define SHELL_USE_LOCAL_GETLINE 1
136 #endif
139 #if defined(_WIN32) || defined(WIN32)
140 # if SQLITE_OS_WINRT
141 # define SQLITE_OMIT_POPEN 1
142 # else
143 # include <io.h>
144 # include <fcntl.h>
145 # define isatty(h) _isatty(h)
146 # ifndef access
147 # define access(f,m) _access((f),(m))
148 # endif
149 # ifndef unlink
150 # define unlink _unlink
151 # endif
152 # ifndef strdup
153 # define strdup _strdup
154 # endif
155 # undef popen
156 # define popen _popen
157 # undef pclose
158 # define pclose _pclose
159 # endif
160 #else
161 /* Make sure isatty() has a prototype. */
162 extern int isatty(int);
164 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
165 /* popen and pclose are not C89 functions and so are
166 ** sometimes omitted from the <stdio.h> header */
167 extern FILE *popen(const char*,const char*);
168 extern int pclose(FILE*);
169 # else
170 # define SQLITE_OMIT_POPEN 1
171 # endif
172 #endif
174 #if defined(_WIN32_WCE)
175 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
176 * thus we always assume that we have a console. That can be
177 * overridden with the -batch command line option.
179 #define isatty(x) 1
180 #endif
182 /* ctype macros that work with signed characters */
183 #define IsSpace(X) isspace((unsigned char)X)
184 #define IsDigit(X) isdigit((unsigned char)X)
185 #define ToLower(X) (char)tolower((unsigned char)X)
187 #if defined(_WIN32) || defined(WIN32)
188 #if SQLITE_OS_WINRT
189 #include <intrin.h>
190 #endif
191 #include <windows.h>
193 /* string conversion routines only needed on Win32 */
194 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
195 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
196 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
197 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
198 #endif
200 /* On Windows, we normally run with output mode of TEXT so that \n characters
201 ** are automatically translated into \r\n. However, this behavior needs
202 ** to be disabled in some cases (ex: when generating CSV output and when
203 ** rendering quoted strings that contain \n characters). The following
204 ** routines take care of that.
206 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
207 static void setBinaryMode(FILE *file, int isOutput){
208 if( isOutput ) fflush(file);
209 _setmode(_fileno(file), _O_BINARY);
211 static void setTextMode(FILE *file, int isOutput){
212 if( isOutput ) fflush(file);
213 _setmode(_fileno(file), _O_TEXT);
215 #else
216 # define setBinaryMode(X,Y)
217 # define setTextMode(X,Y)
218 #endif
221 /* True if the timer is enabled */
222 static int enableTimer = 0;
224 /* Return the current wall-clock time */
225 static sqlite3_int64 timeOfDay(void){
226 static sqlite3_vfs *clockVfs = 0;
227 sqlite3_int64 t;
228 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
229 if( clockVfs==0 ) return 0; /* Never actually happens */
230 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
231 clockVfs->xCurrentTimeInt64(clockVfs, &t);
232 }else{
233 double r;
234 clockVfs->xCurrentTime(clockVfs, &r);
235 t = (sqlite3_int64)(r*86400000.0);
237 return t;
240 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
241 #include <sys/time.h>
242 #include <sys/resource.h>
244 /* VxWorks does not support getrusage() as far as we can determine */
245 #if defined(_WRS_KERNEL) || defined(__RTP__)
246 struct rusage {
247 struct timeval ru_utime; /* user CPU time used */
248 struct timeval ru_stime; /* system CPU time used */
250 #define getrusage(A,B) memset(B,0,sizeof(*B))
251 #endif
253 /* Saved resource information for the beginning of an operation */
254 static struct rusage sBegin; /* CPU time at start */
255 static sqlite3_int64 iBegin; /* Wall-clock time at start */
258 ** Begin timing an operation
260 static void beginTimer(void){
261 if( enableTimer ){
262 getrusage(RUSAGE_SELF, &sBegin);
263 iBegin = timeOfDay();
267 /* Return the difference of two time_structs in seconds */
268 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
269 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
270 (double)(pEnd->tv_sec - pStart->tv_sec);
274 ** Print the timing results.
276 static void endTimer(void){
277 if( enableTimer ){
278 sqlite3_int64 iEnd = timeOfDay();
279 struct rusage sEnd;
280 getrusage(RUSAGE_SELF, &sEnd);
281 printf("Run Time: real %.3f user %f sys %f\n",
282 (iEnd - iBegin)*0.001,
283 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
284 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
288 #define BEGIN_TIMER beginTimer()
289 #define END_TIMER endTimer()
290 #define HAS_TIMER 1
292 #elif (defined(_WIN32) || defined(WIN32))
294 /* Saved resource information for the beginning of an operation */
295 static HANDLE hProcess;
296 static FILETIME ftKernelBegin;
297 static FILETIME ftUserBegin;
298 static sqlite3_int64 ftWallBegin;
299 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
300 LPFILETIME, LPFILETIME);
301 static GETPROCTIMES getProcessTimesAddr = NULL;
304 ** Check to see if we have timer support. Return 1 if necessary
305 ** support found (or found previously).
307 static int hasTimer(void){
308 if( getProcessTimesAddr ){
309 return 1;
310 } else {
311 #if !SQLITE_OS_WINRT
312 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
313 ** versions. See if the version we are running on has it, and if it
314 ** does, save off a pointer to it and the current process handle.
316 hProcess = GetCurrentProcess();
317 if( hProcess ){
318 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
319 if( NULL != hinstLib ){
320 getProcessTimesAddr =
321 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
322 if( NULL != getProcessTimesAddr ){
323 return 1;
325 FreeLibrary(hinstLib);
328 #endif
330 return 0;
334 ** Begin timing an operation
336 static void beginTimer(void){
337 if( enableTimer && getProcessTimesAddr ){
338 FILETIME ftCreation, ftExit;
339 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
340 &ftKernelBegin,&ftUserBegin);
341 ftWallBegin = timeOfDay();
345 /* Return the difference of two FILETIME structs in seconds */
346 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
347 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
348 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
349 return (double) ((i64End - i64Start) / 10000000.0);
353 ** Print the timing results.
355 static void endTimer(void){
356 if( enableTimer && getProcessTimesAddr){
357 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
358 sqlite3_int64 ftWallEnd = timeOfDay();
359 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
360 printf("Run Time: real %.3f user %f sys %f\n",
361 (ftWallEnd - ftWallBegin)*0.001,
362 timeDiff(&ftUserBegin, &ftUserEnd),
363 timeDiff(&ftKernelBegin, &ftKernelEnd));
367 #define BEGIN_TIMER beginTimer()
368 #define END_TIMER endTimer()
369 #define HAS_TIMER hasTimer()
371 #else
372 #define BEGIN_TIMER
373 #define END_TIMER
374 #define HAS_TIMER 0
375 #endif
378 ** Used to prevent warnings about unused parameters
380 #define UNUSED_PARAMETER(x) (void)(x)
383 ** Number of elements in an array
385 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
388 ** If the following flag is set, then command execution stops
389 ** at an error if we are not interactive.
391 static int bail_on_error = 0;
394 ** Threat stdin as an interactive input if the following variable
395 ** is true. Otherwise, assume stdin is connected to a file or pipe.
397 static int stdin_is_interactive = 1;
400 ** On Windows systems we have to know if standard output is a console
401 ** in order to translate UTF-8 into MBCS. The following variable is
402 ** true if translation is required.
404 static int stdout_is_console = 1;
407 ** The following is the open SQLite database. We make a pointer
408 ** to this database a static variable so that it can be accessed
409 ** by the SIGINT handler to interrupt database processing.
411 static sqlite3 *globalDb = 0;
414 ** True if an interrupt (Control-C) has been received.
416 static volatile int seenInterrupt = 0;
418 #ifdef SQLITE_DEBUG
420 ** Out-of-memory simulator variables
422 static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
423 static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
424 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
425 #endif /* SQLITE_DEBUG */
428 ** This is the name of our program. It is set in main(), used
429 ** in a number of other places, mostly for error messages.
431 static char *Argv0;
434 ** Prompt strings. Initialized in main. Settable with
435 ** .prompt main continue
437 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
438 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
441 ** Render output like fprintf(). Except, if the output is going to the
442 ** console and if this is running on a Windows machine, translate the
443 ** output from UTF-8 into MBCS.
445 #if defined(_WIN32) || defined(WIN32)
446 void utf8_printf(FILE *out, const char *zFormat, ...){
447 va_list ap;
448 va_start(ap, zFormat);
449 if( stdout_is_console && (out==stdout || out==stderr) ){
450 char *z1 = sqlite3_vmprintf(zFormat, ap);
451 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
452 sqlite3_free(z1);
453 fputs(z2, out);
454 sqlite3_free(z2);
455 }else{
456 vfprintf(out, zFormat, ap);
458 va_end(ap);
460 #elif !defined(utf8_printf)
461 # define utf8_printf fprintf
462 #endif
465 ** Render output like fprintf(). This should not be used on anything that
466 ** includes string formatting (e.g. "%s").
468 #if !defined(raw_printf)
469 # define raw_printf fprintf
470 #endif
472 /* Indicate out-of-memory and exit. */
473 static void shell_out_of_memory(void){
474 raw_printf(stderr,"Error: out of memory\n");
475 exit(1);
478 #ifdef SQLITE_DEBUG
479 /* This routine is called when a simulated OOM occurs. It is broken
480 ** out as a separate routine to make it easy to set a breakpoint on
481 ** the OOM
483 void shellOomFault(void){
484 if( oomRepeat>0 ){
485 oomRepeat--;
486 }else{
487 oomCounter--;
490 #endif /* SQLITE_DEBUG */
492 #ifdef SQLITE_DEBUG
493 /* This routine is a replacement malloc() that is used to simulate
494 ** Out-Of-Memory (OOM) errors for testing purposes.
496 static void *oomMalloc(int nByte){
497 if( oomCounter ){
498 if( oomCounter==1 ){
499 shellOomFault();
500 return 0;
501 }else{
502 oomCounter--;
505 return defaultMalloc(nByte);
507 #endif /* SQLITE_DEBUG */
509 #ifdef SQLITE_DEBUG
510 /* Register the OOM simulator. This must occur before any memory
511 ** allocations */
512 static void registerOomSimulator(void){
513 sqlite3_mem_methods mem;
514 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
515 defaultMalloc = mem.xMalloc;
516 mem.xMalloc = oomMalloc;
517 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
519 #endif
522 ** Write I/O traces to the following stream.
524 #ifdef SQLITE_ENABLE_IOTRACE
525 static FILE *iotrace = 0;
526 #endif
529 ** This routine works like printf in that its first argument is a
530 ** format string and subsequent arguments are values to be substituted
531 ** in place of % fields. The result of formatting this string
532 ** is written to iotrace.
534 #ifdef SQLITE_ENABLE_IOTRACE
535 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
536 va_list ap;
537 char *z;
538 if( iotrace==0 ) return;
539 va_start(ap, zFormat);
540 z = sqlite3_vmprintf(zFormat, ap);
541 va_end(ap);
542 utf8_printf(iotrace, "%s", z);
543 sqlite3_free(z);
545 #endif
548 ** Output string zUtf to stream pOut as w characters. If w is negative,
549 ** then right-justify the text. W is the width in UTF-8 characters, not
550 ** in bytes. This is different from the %*.*s specification in printf
551 ** since with %*.*s the width is measured in bytes, not characters.
553 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
554 int i;
555 int n;
556 int aw = w<0 ? -w : w;
557 for(i=n=0; zUtf[i]; i++){
558 if( (zUtf[i]&0xc0)!=0x80 ){
559 n++;
560 if( n==aw ){
561 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
562 break;
566 if( n>=aw ){
567 utf8_printf(pOut, "%.*s", i, zUtf);
568 }else if( w<0 ){
569 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
570 }else{
571 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
577 ** Determines if a string is a number of not.
579 static int isNumber(const char *z, int *realnum){
580 if( *z=='-' || *z=='+' ) z++;
581 if( !IsDigit(*z) ){
582 return 0;
584 z++;
585 if( realnum ) *realnum = 0;
586 while( IsDigit(*z) ){ z++; }
587 if( *z=='.' ){
588 z++;
589 if( !IsDigit(*z) ) return 0;
590 while( IsDigit(*z) ){ z++; }
591 if( realnum ) *realnum = 1;
593 if( *z=='e' || *z=='E' ){
594 z++;
595 if( *z=='+' || *z=='-' ) z++;
596 if( !IsDigit(*z) ) return 0;
597 while( IsDigit(*z) ){ z++; }
598 if( realnum ) *realnum = 1;
600 return *z==0;
604 ** Compute a string length that is limited to what can be stored in
605 ** lower 30 bits of a 32-bit signed integer.
607 static int strlen30(const char *z){
608 const char *z2 = z;
609 while( *z2 ){ z2++; }
610 return 0x3fffffff & (int)(z2 - z);
614 ** Return the length of a string in characters. Multibyte UTF8 characters
615 ** count as a single character.
617 static int strlenChar(const char *z){
618 int n = 0;
619 while( *z ){
620 if( (0xc0&*(z++))!=0x80 ) n++;
622 return n;
626 ** Return true if zFile does not exist or if it is not an ordinary file.
628 #ifdef _WIN32
629 # define notNormalFile(X) 0
630 #else
631 static int notNormalFile(const char *zFile){
632 struct stat x;
633 int rc;
634 memset(&x, 0, sizeof(x));
635 rc = stat(zFile, &x);
636 return rc || !S_ISREG(x.st_mode);
638 #endif
641 ** This routine reads a line of text from FILE in, stores
642 ** the text in memory obtained from malloc() and returns a pointer
643 ** to the text. NULL is returned at end of file, or if malloc()
644 ** fails.
646 ** If zLine is not NULL then it is a malloced buffer returned from
647 ** a previous call to this routine that may be reused.
649 static char *local_getline(char *zLine, FILE *in){
650 int nLine = zLine==0 ? 0 : 100;
651 int n = 0;
653 while( 1 ){
654 if( n+100>nLine ){
655 nLine = nLine*2 + 100;
656 zLine = realloc(zLine, nLine);
657 if( zLine==0 ) shell_out_of_memory();
659 if( fgets(&zLine[n], nLine - n, in)==0 ){
660 if( n==0 ){
661 free(zLine);
662 return 0;
664 zLine[n] = 0;
665 break;
667 while( zLine[n] ) n++;
668 if( n>0 && zLine[n-1]=='\n' ){
669 n--;
670 if( n>0 && zLine[n-1]=='\r' ) n--;
671 zLine[n] = 0;
672 break;
675 #if defined(_WIN32) || defined(WIN32)
676 /* For interactive input on Windows systems, translate the
677 ** multi-byte characterset characters into UTF-8. */
678 if( stdin_is_interactive && in==stdin ){
679 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
680 if( zTrans ){
681 int nTrans = strlen30(zTrans)+1;
682 if( nTrans>nLine ){
683 zLine = realloc(zLine, nTrans);
684 if( zLine==0 ) shell_out_of_memory();
686 memcpy(zLine, zTrans, nTrans);
687 sqlite3_free(zTrans);
690 #endif /* defined(_WIN32) || defined(WIN32) */
691 return zLine;
695 ** Retrieve a single line of input text.
697 ** If in==0 then read from standard input and prompt before each line.
698 ** If isContinuation is true, then a continuation prompt is appropriate.
699 ** If isContinuation is zero, then the main prompt should be used.
701 ** If zPrior is not NULL then it is a buffer from a prior call to this
702 ** routine that can be reused.
704 ** The result is stored in space obtained from malloc() and must either
705 ** be freed by the caller or else passed back into this routine via the
706 ** zPrior argument for reuse.
708 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
709 char *zPrompt;
710 char *zResult;
711 if( in!=0 ){
712 zResult = local_getline(zPrior, in);
713 }else{
714 zPrompt = isContinuation ? continuePrompt : mainPrompt;
715 #if SHELL_USE_LOCAL_GETLINE
716 printf("%s", zPrompt);
717 fflush(stdout);
718 zResult = local_getline(zPrior, stdin);
719 #else
720 free(zPrior);
721 zResult = shell_readline(zPrompt);
722 /* BEGIN SQLCIPHER */
723 #ifdef SQLITE_HAS_CODEC
724 /* Simplistic filtering of input lines to prevent PRAGKA key and
725 PRAGMA rekey statements from being stored in readline history.
726 Note that this will only prevent single line statements, but that
727 will be sufficient for common cases. */
728 if(zResult && *zResult && (
729 sqlite3_strlike("%pragma%key%=%", zResult, 0)==0 ||
730 sqlite3_strlike("%attach%database%as%key%", zResult, 0)==0
732 ) return zResult;
733 #endif
734 /* END SQLCIPHER */
735 if( zResult && *zResult ) shell_add_history(zResult);
736 #endif
738 return zResult;
743 ** Return the value of a hexadecimal digit. Return -1 if the input
744 ** is not a hex digit.
746 static int hexDigitValue(char c){
747 if( c>='0' && c<='9' ) return c - '0';
748 if( c>='a' && c<='f' ) return c - 'a' + 10;
749 if( c>='A' && c<='F' ) return c - 'A' + 10;
750 return -1;
754 ** Interpret zArg as an integer value, possibly with suffixes.
756 static sqlite3_int64 integerValue(const char *zArg){
757 sqlite3_int64 v = 0;
758 static const struct { char *zSuffix; int iMult; } aMult[] = {
759 { "KiB", 1024 },
760 { "MiB", 1024*1024 },
761 { "GiB", 1024*1024*1024 },
762 { "KB", 1000 },
763 { "MB", 1000000 },
764 { "GB", 1000000000 },
765 { "K", 1000 },
766 { "M", 1000000 },
767 { "G", 1000000000 },
769 int i;
770 int isNeg = 0;
771 if( zArg[0]=='-' ){
772 isNeg = 1;
773 zArg++;
774 }else if( zArg[0]=='+' ){
775 zArg++;
777 if( zArg[0]=='0' && zArg[1]=='x' ){
778 int x;
779 zArg += 2;
780 while( (x = hexDigitValue(zArg[0]))>=0 ){
781 v = (v<<4) + x;
782 zArg++;
784 }else{
785 while( IsDigit(zArg[0]) ){
786 v = v*10 + zArg[0] - '0';
787 zArg++;
790 for(i=0; i<ArraySize(aMult); i++){
791 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
792 v *= aMult[i].iMult;
793 break;
796 return isNeg? -v : v;
800 ** A variable length string to which one can append text.
802 typedef struct ShellText ShellText;
803 struct ShellText {
804 char *z;
805 int n;
806 int nAlloc;
810 ** Initialize and destroy a ShellText object
812 static void initText(ShellText *p){
813 memset(p, 0, sizeof(*p));
815 static void freeText(ShellText *p){
816 free(p->z);
817 initText(p);
820 /* zIn is either a pointer to a NULL-terminated string in memory obtained
821 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
822 ** added to zIn, and the result returned in memory obtained from malloc().
823 ** zIn, if it was not NULL, is freed.
825 ** If the third argument, quote, is not '\0', then it is used as a
826 ** quote character for zAppend.
828 static void appendText(ShellText *p, char const *zAppend, char quote){
829 int len;
830 int i;
831 int nAppend = strlen30(zAppend);
833 len = nAppend+p->n+1;
834 if( quote ){
835 len += 2;
836 for(i=0; i<nAppend; i++){
837 if( zAppend[i]==quote ) len++;
841 if( p->n+len>=p->nAlloc ){
842 p->nAlloc = p->nAlloc*2 + len + 20;
843 p->z = realloc(p->z, p->nAlloc);
844 if( p->z==0 ) shell_out_of_memory();
847 if( quote ){
848 char *zCsr = p->z+p->n;
849 *zCsr++ = quote;
850 for(i=0; i<nAppend; i++){
851 *zCsr++ = zAppend[i];
852 if( zAppend[i]==quote ) *zCsr++ = quote;
854 *zCsr++ = quote;
855 p->n = (int)(zCsr - p->z);
856 *zCsr = '\0';
857 }else{
858 memcpy(p->z+p->n, zAppend, nAppend);
859 p->n += nAppend;
860 p->z[p->n] = '\0';
865 ** Attempt to determine if identifier zName needs to be quoted, either
866 ** because it contains non-alphanumeric characters, or because it is an
867 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
868 ** that quoting is required.
870 ** Return '"' if quoting is required. Return 0 if no quoting is required.
872 static char quoteChar(const char *zName){
873 int i;
874 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
875 for(i=0; zName[i]; i++){
876 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
878 return sqlite3_keyword_check(zName, i) ? '"' : 0;
882 ** Construct a fake object name and column list to describe the structure
883 ** of the view, virtual table, or table valued function zSchema.zName.
885 static char *shellFakeSchema(
886 sqlite3 *db, /* The database connection containing the vtab */
887 const char *zSchema, /* Schema of the database holding the vtab */
888 const char *zName /* The name of the virtual table */
890 sqlite3_stmt *pStmt = 0;
891 char *zSql;
892 ShellText s;
893 char cQuote;
894 char *zDiv = "(";
895 int nRow = 0;
897 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
898 zSchema ? zSchema : "main", zName);
899 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
900 sqlite3_free(zSql);
901 initText(&s);
902 if( zSchema ){
903 cQuote = quoteChar(zSchema);
904 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
905 appendText(&s, zSchema, cQuote);
906 appendText(&s, ".", 0);
908 cQuote = quoteChar(zName);
909 appendText(&s, zName, cQuote);
910 while( sqlite3_step(pStmt)==SQLITE_ROW ){
911 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
912 nRow++;
913 appendText(&s, zDiv, 0);
914 zDiv = ",";
915 cQuote = quoteChar(zCol);
916 appendText(&s, zCol, cQuote);
918 appendText(&s, ")", 0);
919 sqlite3_finalize(pStmt);
920 if( nRow==0 ){
921 freeText(&s);
922 s.z = 0;
924 return s.z;
928 ** SQL function: shell_module_schema(X)
930 ** Return a fake schema for the table-valued function or eponymous virtual
931 ** table X.
933 static void shellModuleSchema(
934 sqlite3_context *pCtx,
935 int nVal,
936 sqlite3_value **apVal
938 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
939 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
940 UNUSED_PARAMETER(nVal);
941 if( zFake ){
942 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
943 -1, sqlite3_free);
944 free(zFake);
949 ** SQL function: shell_add_schema(S,X)
951 ** Add the schema name X to the CREATE statement in S and return the result.
952 ** Examples:
954 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
956 ** Also works on
958 ** CREATE INDEX
959 ** CREATE UNIQUE INDEX
960 ** CREATE VIEW
961 ** CREATE TRIGGER
962 ** CREATE VIRTUAL TABLE
964 ** This UDF is used by the .schema command to insert the schema name of
965 ** attached databases into the middle of the sqlite_schema.sql field.
967 static void shellAddSchemaName(
968 sqlite3_context *pCtx,
969 int nVal,
970 sqlite3_value **apVal
972 static const char *aPrefix[] = {
973 "TABLE",
974 "INDEX",
975 "UNIQUE INDEX",
976 "VIEW",
977 "TRIGGER",
978 "VIRTUAL TABLE"
980 int i = 0;
981 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
982 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
983 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
984 sqlite3 *db = sqlite3_context_db_handle(pCtx);
985 UNUSED_PARAMETER(nVal);
986 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
987 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
988 int n = strlen30(aPrefix[i]);
989 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
990 char *z = 0;
991 char *zFake = 0;
992 if( zSchema ){
993 char cQuote = quoteChar(zSchema);
994 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
995 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
996 }else{
997 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1000 if( zName
1001 && aPrefix[i][0]=='V'
1002 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1004 if( z==0 ){
1005 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1006 }else{
1007 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1009 free(zFake);
1011 if( z ){
1012 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1013 return;
1018 sqlite3_result_value(pCtx, apVal[0]);
1022 ** The source code for several run-time loadable extensions is inserted
1023 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1024 ** code, we need to override some macros to make the included program code
1025 ** work here in the middle of this regular program.
1027 #define SQLITE_EXTENSION_INIT1
1028 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1030 #if defined(_WIN32) && defined(_MSC_VER)
1031 INCLUDE test_windirent.h
1032 INCLUDE test_windirent.c
1033 #define dirent DIRENT
1034 #endif
1035 INCLUDE ../ext/misc/shathree.c
1036 INCLUDE ../ext/misc/fileio.c
1037 INCLUDE ../ext/misc/completion.c
1038 INCLUDE ../ext/misc/appendvfs.c
1039 INCLUDE ../ext/misc/memtrace.c
1040 INCLUDE ../ext/misc/uint.c
1041 INCLUDE ../ext/misc/decimal.c
1042 INCLUDE ../ext/misc/ieee754.c
1043 INCLUDE ../ext/misc/series.c
1044 INCLUDE ../ext/misc/regexp.c
1045 #ifdef SQLITE_HAVE_ZLIB
1046 INCLUDE ../ext/misc/zipfile.c
1047 INCLUDE ../ext/misc/sqlar.c
1048 #endif
1049 INCLUDE ../ext/expert/sqlite3expert.h
1050 INCLUDE ../ext/expert/sqlite3expert.c
1052 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1053 INCLUDE ../ext/misc/dbdata.c
1054 #endif
1056 #if defined(SQLITE_ENABLE_SESSION)
1058 ** State information for a single open session
1060 typedef struct OpenSession OpenSession;
1061 struct OpenSession {
1062 char *zName; /* Symbolic name for this session */
1063 int nFilter; /* Number of xFilter rejection GLOB patterns */
1064 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1065 sqlite3_session *p; /* The open session */
1067 #endif
1069 typedef struct ExpertInfo ExpertInfo;
1070 struct ExpertInfo {
1071 sqlite3expert *pExpert;
1072 int bVerbose;
1075 /* A single line in the EQP output */
1076 typedef struct EQPGraphRow EQPGraphRow;
1077 struct EQPGraphRow {
1078 int iEqpId; /* ID for this row */
1079 int iParentId; /* ID of the parent row */
1080 EQPGraphRow *pNext; /* Next row in sequence */
1081 char zText[1]; /* Text to display for this row */
1084 /* All EQP output is collected into an instance of the following */
1085 typedef struct EQPGraph EQPGraph;
1086 struct EQPGraph {
1087 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1088 EQPGraphRow *pLast; /* Last element of the pRow list */
1089 char zPrefix[100]; /* Graph prefix */
1093 ** State information about the database connection is contained in an
1094 ** instance of the following structure.
1096 typedef struct ShellState ShellState;
1097 struct ShellState {
1098 sqlite3 *db; /* The database */
1099 u8 autoExplain; /* Automatically turn on .explain mode */
1100 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1101 u8 autoEQPtest; /* autoEQP is in test mode */
1102 u8 autoEQPtrace; /* autoEQP is in trace mode */
1103 u8 scanstatsOn; /* True to display scan stats before each finalize */
1104 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1105 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1106 u8 nEqpLevel; /* Depth of the EQP output graph */
1107 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1108 unsigned statsOn; /* True to display memory stats before each finalize */
1109 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
1110 int outCount; /* Revert to stdout when reaching zero */
1111 int cnt; /* Number of records displayed so far */
1112 int lineno; /* Line number of last line read from in */
1113 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1114 FILE *in; /* Read commands from this stream */
1115 FILE *out; /* Write results here */
1116 FILE *traceOut; /* Output for sqlite3_trace() */
1117 int nErr; /* Number of errors seen */
1118 int mode; /* An output mode setting */
1119 int modePrior; /* Saved mode */
1120 int cMode; /* temporary output mode for the current query */
1121 int normalMode; /* Output mode before ".explain on" */
1122 int writableSchema; /* True if PRAGMA writable_schema=ON */
1123 int showHeader; /* True to show column names in List or Column mode */
1124 int nCheck; /* Number of ".check" commands run */
1125 unsigned nProgress; /* Number of progress callbacks encountered */
1126 unsigned mxProgress; /* Maximum progress callbacks before failing */
1127 unsigned flgProgress; /* Flags for the progress callback */
1128 unsigned shellFlgs; /* Various flags */
1129 unsigned priorShFlgs; /* Saved copy of flags */
1130 sqlite3_int64 szMax; /* --maxsize argument to .open */
1131 char *zDestTable; /* Name of destination table when MODE_Insert */
1132 char *zTempFile; /* Temporary file that might need deleting */
1133 char zTestcase[30]; /* Name of current test case */
1134 char colSeparator[20]; /* Column separator character for several modes */
1135 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1136 char colSepPrior[20]; /* Saved column separator */
1137 char rowSepPrior[20]; /* Saved row separator */
1138 int *colWidth; /* Requested width of each column in columnar modes */
1139 int *actualWidth; /* Actual width of each column */
1140 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1141 char nullValue[20]; /* The text to print when a NULL comes back from
1142 ** the database */
1143 char outfile[FILENAME_MAX]; /* Filename for *out */
1144 const char *zDbFilename; /* name of the database file */
1145 char *zFreeOnClose; /* Filename to free when closing */
1146 const char *zVfs; /* Name of VFS to use */
1147 sqlite3_stmt *pStmt; /* Current statement if any. */
1148 FILE *pLog; /* Write log output here */
1149 int *aiIndent; /* Array of indents used in MODE_Explain */
1150 int nIndent; /* Size of array aiIndent[] */
1151 int iIndent; /* Index of current op in aiIndent[] */
1152 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1153 #if defined(SQLITE_ENABLE_SESSION)
1154 int nSession; /* Number of active sessions */
1155 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1156 #endif
1157 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1161 /* Allowed values for ShellState.autoEQP
1163 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1164 #define AUTOEQP_on 1 /* Automatic EQP is on */
1165 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1166 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1168 /* Allowed values for ShellState.openMode
1170 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1171 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1172 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1173 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1174 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1175 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1176 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1178 /* Allowed values for ShellState.eTraceType
1180 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1181 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1182 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1184 /* Bits in the ShellState.flgProgress variable */
1185 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1186 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1187 ** callback limit is reached, and for each
1188 ** top-level SQL statement */
1189 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1192 ** These are the allowed shellFlgs values
1194 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1195 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1196 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1197 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1198 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1199 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1200 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1201 #define SHFLG_HeaderSet 0x00000080 /* .header has been used */
1202 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1203 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1206 ** Macros for testing and setting shellFlgs
1208 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1209 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1210 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1213 ** These are the allowed modes.
1215 #define MODE_Line 0 /* One column per line. Blank line between records */
1216 #define MODE_Column 1 /* One record per line in neat columns */
1217 #define MODE_List 2 /* One record per line with a separator */
1218 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1219 #define MODE_Html 4 /* Generate an XHTML table */
1220 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1221 #define MODE_Quote 6 /* Quote values as for SQL */
1222 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1223 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1224 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1225 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1226 #define MODE_Pretty 11 /* Pretty-print schemas */
1227 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1228 #define MODE_Json 13 /* Output JSON */
1229 #define MODE_Markdown 14 /* Markdown formatting */
1230 #define MODE_Table 15 /* MySQL-style table formatting */
1231 #define MODE_Box 16 /* Unicode box-drawing characters */
1233 static const char *modeDescr[] = {
1234 "line",
1235 "column",
1236 "list",
1237 "semi",
1238 "html",
1239 "insert",
1240 "quote",
1241 "tcl",
1242 "csv",
1243 "explain",
1244 "ascii",
1245 "prettyprint",
1246 "eqp",
1247 "json",
1248 "markdown",
1249 "table",
1250 "box"
1254 ** These are the column/row/line separators used by the various
1255 ** import/export modes.
1257 #define SEP_Column "|"
1258 #define SEP_Row "\n"
1259 #define SEP_Tab "\t"
1260 #define SEP_Space " "
1261 #define SEP_Comma ","
1262 #define SEP_CrLf "\r\n"
1263 #define SEP_Unit "\x1F"
1264 #define SEP_Record "\x1E"
1267 ** A callback for the sqlite3_log() interface.
1269 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1270 ShellState *p = (ShellState*)pArg;
1271 if( p->pLog==0 ) return;
1272 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1273 fflush(p->pLog);
1277 ** SQL function: shell_putsnl(X)
1279 ** Write the text X to the screen (or whatever output is being directed)
1280 ** adding a newline at the end, and then return X.
1282 static void shellPutsFunc(
1283 sqlite3_context *pCtx,
1284 int nVal,
1285 sqlite3_value **apVal
1287 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1288 (void)nVal;
1289 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1290 sqlite3_result_value(pCtx, apVal[0]);
1294 ** SQL function: edit(VALUE)
1295 ** edit(VALUE,EDITOR)
1297 ** These steps:
1299 ** (1) Write VALUE into a temporary file.
1300 ** (2) Run program EDITOR on that temporary file.
1301 ** (3) Read the temporary file back and return its content as the result.
1302 ** (4) Delete the temporary file
1304 ** If the EDITOR argument is omitted, use the value in the VISUAL
1305 ** environment variable. If still there is no EDITOR, through an error.
1307 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1309 #ifndef SQLITE_NOHAVE_SYSTEM
1310 static void editFunc(
1311 sqlite3_context *context,
1312 int argc,
1313 sqlite3_value **argv
1315 const char *zEditor;
1316 char *zTempFile = 0;
1317 sqlite3 *db;
1318 char *zCmd = 0;
1319 int bBin;
1320 int rc;
1321 int hasCRNL = 0;
1322 FILE *f = 0;
1323 sqlite3_int64 sz;
1324 sqlite3_int64 x;
1325 unsigned char *p = 0;
1327 if( argc==2 ){
1328 zEditor = (const char*)sqlite3_value_text(argv[1]);
1329 }else{
1330 zEditor = getenv("VISUAL");
1332 if( zEditor==0 ){
1333 sqlite3_result_error(context, "no editor for edit()", -1);
1334 return;
1336 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1337 sqlite3_result_error(context, "NULL input to edit()", -1);
1338 return;
1340 db = sqlite3_context_db_handle(context);
1341 zTempFile = 0;
1342 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1343 if( zTempFile==0 ){
1344 sqlite3_uint64 r = 0;
1345 sqlite3_randomness(sizeof(r), &r);
1346 zTempFile = sqlite3_mprintf("temp%llx", r);
1347 if( zTempFile==0 ){
1348 sqlite3_result_error_nomem(context);
1349 return;
1352 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1353 /* When writing the file to be edited, do \n to \r\n conversions on systems
1354 ** that want \r\n line endings */
1355 f = fopen(zTempFile, bBin ? "wb" : "w");
1356 if( f==0 ){
1357 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1358 goto edit_func_end;
1360 sz = sqlite3_value_bytes(argv[0]);
1361 if( bBin ){
1362 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1363 }else{
1364 const char *z = (const char*)sqlite3_value_text(argv[0]);
1365 /* Remember whether or not the value originally contained \r\n */
1366 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1367 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1369 fclose(f);
1370 f = 0;
1371 if( x!=sz ){
1372 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1373 goto edit_func_end;
1375 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1376 if( zCmd==0 ){
1377 sqlite3_result_error_nomem(context);
1378 goto edit_func_end;
1380 rc = system(zCmd);
1381 sqlite3_free(zCmd);
1382 if( rc ){
1383 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1384 goto edit_func_end;
1386 f = fopen(zTempFile, "rb");
1387 if( f==0 ){
1388 sqlite3_result_error(context,
1389 "edit() cannot reopen temp file after edit", -1);
1390 goto edit_func_end;
1392 fseek(f, 0, SEEK_END);
1393 sz = ftell(f);
1394 rewind(f);
1395 p = sqlite3_malloc64( sz+1 );
1396 if( p==0 ){
1397 sqlite3_result_error_nomem(context);
1398 goto edit_func_end;
1400 x = fread(p, 1, (size_t)sz, f);
1401 fclose(f);
1402 f = 0;
1403 if( x!=sz ){
1404 sqlite3_result_error(context, "could not read back the whole file", -1);
1405 goto edit_func_end;
1407 if( bBin ){
1408 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1409 }else{
1410 sqlite3_int64 i, j;
1411 if( hasCRNL ){
1412 /* If the original contains \r\n then do no conversions back to \n */
1413 j = sz;
1414 }else{
1415 /* If the file did not originally contain \r\n then convert any new
1416 ** \r\n back into \n */
1417 for(i=j=0; i<sz; i++){
1418 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1419 p[j++] = p[i];
1421 sz = j;
1422 p[sz] = 0;
1424 sqlite3_result_text64(context, (const char*)p, sz,
1425 sqlite3_free, SQLITE_UTF8);
1427 p = 0;
1429 edit_func_end:
1430 if( f ) fclose(f);
1431 unlink(zTempFile);
1432 sqlite3_free(zTempFile);
1433 sqlite3_free(p);
1435 #endif /* SQLITE_NOHAVE_SYSTEM */
1438 ** Save or restore the current output mode
1440 static void outputModePush(ShellState *p){
1441 p->modePrior = p->mode;
1442 p->priorShFlgs = p->shellFlgs;
1443 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1444 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1446 static void outputModePop(ShellState *p){
1447 p->mode = p->modePrior;
1448 p->shellFlgs = p->priorShFlgs;
1449 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1450 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1454 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1456 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1457 int i;
1458 char *zBlob = (char *)pBlob;
1459 raw_printf(out,"X'");
1460 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1461 raw_printf(out,"'");
1465 ** Find a string that is not found anywhere in z[]. Return a pointer
1466 ** to that string.
1468 ** Try to use zA and zB first. If both of those are already found in z[]
1469 ** then make up some string and store it in the buffer zBuf.
1471 static const char *unused_string(
1472 const char *z, /* Result must not appear anywhere in z */
1473 const char *zA, const char *zB, /* Try these first */
1474 char *zBuf /* Space to store a generated string */
1476 unsigned i = 0;
1477 if( strstr(z, zA)==0 ) return zA;
1478 if( strstr(z, zB)==0 ) return zB;
1480 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1481 }while( strstr(z,zBuf)!=0 );
1482 return zBuf;
1486 ** Output the given string as a quoted string using SQL quoting conventions.
1488 ** See also: output_quoted_escaped_string()
1490 static void output_quoted_string(FILE *out, const char *z){
1491 int i;
1492 char c;
1493 setBinaryMode(out, 1);
1494 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1495 if( c==0 ){
1496 utf8_printf(out,"'%s'",z);
1497 }else{
1498 raw_printf(out, "'");
1499 while( *z ){
1500 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1501 if( c=='\'' ) i++;
1502 if( i ){
1503 utf8_printf(out, "%.*s", i, z);
1504 z += i;
1506 if( c=='\'' ){
1507 raw_printf(out, "'");
1508 continue;
1510 if( c==0 ){
1511 break;
1513 z++;
1515 raw_printf(out, "'");
1517 setTextMode(out, 1);
1521 ** Output the given string as a quoted string using SQL quoting conventions.
1522 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1523 ** get corrupted by end-of-line translation facilities in some operating
1524 ** systems.
1526 ** This is like output_quoted_string() but with the addition of the \r\n
1527 ** escape mechanism.
1529 static void output_quoted_escaped_string(FILE *out, const char *z){
1530 int i;
1531 char c;
1532 setBinaryMode(out, 1);
1533 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1534 if( c==0 ){
1535 utf8_printf(out,"'%s'",z);
1536 }else{
1537 const char *zNL = 0;
1538 const char *zCR = 0;
1539 int nNL = 0;
1540 int nCR = 0;
1541 char zBuf1[20], zBuf2[20];
1542 for(i=0; z[i]; i++){
1543 if( z[i]=='\n' ) nNL++;
1544 if( z[i]=='\r' ) nCR++;
1546 if( nNL ){
1547 raw_printf(out, "replace(");
1548 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1550 if( nCR ){
1551 raw_printf(out, "replace(");
1552 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1554 raw_printf(out, "'");
1555 while( *z ){
1556 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1557 if( c=='\'' ) i++;
1558 if( i ){
1559 utf8_printf(out, "%.*s", i, z);
1560 z += i;
1562 if( c=='\'' ){
1563 raw_printf(out, "'");
1564 continue;
1566 if( c==0 ){
1567 break;
1569 z++;
1570 if( c=='\n' ){
1571 raw_printf(out, "%s", zNL);
1572 continue;
1574 raw_printf(out, "%s", zCR);
1576 raw_printf(out, "'");
1577 if( nCR ){
1578 raw_printf(out, ",'%s',char(13))", zCR);
1580 if( nNL ){
1581 raw_printf(out, ",'%s',char(10))", zNL);
1584 setTextMode(out, 1);
1588 ** Output the given string as a quoted according to C or TCL quoting rules.
1590 static void output_c_string(FILE *out, const char *z){
1591 unsigned int c;
1592 fputc('"', out);
1593 while( (c = *(z++))!=0 ){
1594 if( c=='\\' ){
1595 fputc(c, out);
1596 fputc(c, out);
1597 }else if( c=='"' ){
1598 fputc('\\', out);
1599 fputc('"', out);
1600 }else if( c=='\t' ){
1601 fputc('\\', out);
1602 fputc('t', out);
1603 }else if( c=='\n' ){
1604 fputc('\\', out);
1605 fputc('n', out);
1606 }else if( c=='\r' ){
1607 fputc('\\', out);
1608 fputc('r', out);
1609 }else if( !isprint(c&0xff) ){
1610 raw_printf(out, "\\%03o", c&0xff);
1611 }else{
1612 fputc(c, out);
1615 fputc('"', out);
1619 ** Output the given string as a quoted according to JSON quoting rules.
1621 static void output_json_string(FILE *out, const char *z, int n){
1622 unsigned int c;
1623 if( n<0 ) n = (int)strlen(z);
1624 fputc('"', out);
1625 while( n-- ){
1626 c = *(z++);
1627 if( c=='\\' || c=='"' ){
1628 fputc('\\', out);
1629 fputc(c, out);
1630 }else if( c<=0x1f ){
1631 fputc('\\', out);
1632 if( c=='\b' ){
1633 fputc('b', out);
1634 }else if( c=='\f' ){
1635 fputc('f', out);
1636 }else if( c=='\n' ){
1637 fputc('n', out);
1638 }else if( c=='\r' ){
1639 fputc('r', out);
1640 }else if( c=='\t' ){
1641 fputc('t', out);
1642 }else{
1643 raw_printf(out, "u%04x",c);
1645 }else{
1646 fputc(c, out);
1649 fputc('"', out);
1653 ** Output the given string with characters that are special to
1654 ** HTML escaped.
1656 static void output_html_string(FILE *out, const char *z){
1657 int i;
1658 if( z==0 ) z = "";
1659 while( *z ){
1660 for(i=0; z[i]
1661 && z[i]!='<'
1662 && z[i]!='&'
1663 && z[i]!='>'
1664 && z[i]!='\"'
1665 && z[i]!='\'';
1666 i++){}
1667 if( i>0 ){
1668 utf8_printf(out,"%.*s",i,z);
1670 if( z[i]=='<' ){
1671 raw_printf(out,"&lt;");
1672 }else if( z[i]=='&' ){
1673 raw_printf(out,"&amp;");
1674 }else if( z[i]=='>' ){
1675 raw_printf(out,"&gt;");
1676 }else if( z[i]=='\"' ){
1677 raw_printf(out,"&quot;");
1678 }else if( z[i]=='\'' ){
1679 raw_printf(out,"&#39;");
1680 }else{
1681 break;
1683 z += i + 1;
1688 ** If a field contains any character identified by a 1 in the following
1689 ** array, then the string must be quoted for CSV.
1691 static const char needCsvQuote[] = {
1692 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1693 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1694 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1695 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1696 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1697 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1698 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1699 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1700 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1701 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1702 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1703 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1704 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1705 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1706 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1707 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1711 ** Output a single term of CSV. Actually, p->colSeparator is used for
1712 ** the separator, which may or may not be a comma. p->nullValue is
1713 ** the null value. Strings are quoted if necessary. The separator
1714 ** is only issued if bSep is true.
1716 static void output_csv(ShellState *p, const char *z, int bSep){
1717 FILE *out = p->out;
1718 if( z==0 ){
1719 utf8_printf(out,"%s",p->nullValue);
1720 }else{
1721 int i;
1722 int nSep = strlen30(p->colSeparator);
1723 for(i=0; z[i]; i++){
1724 if( needCsvQuote[((unsigned char*)z)[i]]
1725 || (z[i]==p->colSeparator[0] &&
1726 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1727 i = 0;
1728 break;
1731 if( i==0 ){
1732 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1733 utf8_printf(out, "%s", zQuoted);
1734 sqlite3_free(zQuoted);
1735 }else{
1736 utf8_printf(out, "%s", z);
1739 if( bSep ){
1740 utf8_printf(p->out, "%s", p->colSeparator);
1745 ** This routine runs when the user presses Ctrl-C
1747 static void interrupt_handler(int NotUsed){
1748 UNUSED_PARAMETER(NotUsed);
1749 seenInterrupt++;
1750 if( seenInterrupt>2 ) exit(1);
1751 if( globalDb ) sqlite3_interrupt(globalDb);
1754 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1756 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1758 static BOOL WINAPI ConsoleCtrlHandler(
1759 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1761 if( dwCtrlType==CTRL_C_EVENT ){
1762 interrupt_handler(0);
1763 return TRUE;
1765 return FALSE;
1767 #endif
1769 #ifndef SQLITE_OMIT_AUTHORIZATION
1771 ** When the ".auth ON" is set, the following authorizer callback is
1772 ** invoked. It always returns SQLITE_OK.
1774 static int shellAuth(
1775 void *pClientData,
1776 int op,
1777 const char *zA1,
1778 const char *zA2,
1779 const char *zA3,
1780 const char *zA4
1782 ShellState *p = (ShellState*)pClientData;
1783 static const char *azAction[] = { 0,
1784 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1785 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1786 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1787 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1788 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1789 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1790 "PRAGMA", "READ", "SELECT",
1791 "TRANSACTION", "UPDATE", "ATTACH",
1792 "DETACH", "ALTER_TABLE", "REINDEX",
1793 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1794 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1796 int i;
1797 const char *az[4];
1798 az[0] = zA1;
1799 az[1] = zA2;
1800 az[2] = zA3;
1801 az[3] = zA4;
1802 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1803 for(i=0; i<4; i++){
1804 raw_printf(p->out, " ");
1805 if( az[i] ){
1806 output_c_string(p->out, az[i]);
1807 }else{
1808 raw_printf(p->out, "NULL");
1811 raw_printf(p->out, "\n");
1812 return SQLITE_OK;
1814 #endif
1817 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1819 ** This routine converts some CREATE TABLE statements for shadow tables
1820 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1822 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1823 if( z==0 ) return;
1824 if( zTail==0 ) return;
1825 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1826 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1827 }else{
1828 utf8_printf(out, "%s%s", z, zTail);
1831 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1832 char c = z[n];
1833 z[n] = 0;
1834 printSchemaLine(out, z, zTail);
1835 z[n] = c;
1839 ** Return true if string z[] has nothing but whitespace and comments to the
1840 ** end of the first line.
1842 static int wsToEol(const char *z){
1843 int i;
1844 for(i=0; z[i]; i++){
1845 if( z[i]=='\n' ) return 1;
1846 if( IsSpace(z[i]) ) continue;
1847 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1848 return 0;
1850 return 1;
1854 ** Add a new entry to the EXPLAIN QUERY PLAN data
1856 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1857 EQPGraphRow *pNew;
1858 int nText = strlen30(zText);
1859 if( p->autoEQPtest ){
1860 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1862 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1863 if( pNew==0 ) shell_out_of_memory();
1864 pNew->iEqpId = iEqpId;
1865 pNew->iParentId = p2;
1866 memcpy(pNew->zText, zText, nText+1);
1867 pNew->pNext = 0;
1868 if( p->sGraph.pLast ){
1869 p->sGraph.pLast->pNext = pNew;
1870 }else{
1871 p->sGraph.pRow = pNew;
1873 p->sGraph.pLast = pNew;
1877 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1878 ** in p->sGraph.
1880 static void eqp_reset(ShellState *p){
1881 EQPGraphRow *pRow, *pNext;
1882 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1883 pNext = pRow->pNext;
1884 sqlite3_free(pRow);
1886 memset(&p->sGraph, 0, sizeof(p->sGraph));
1889 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1890 ** pOld, or return the first such line if pOld is NULL
1892 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1893 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1894 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1895 return pRow;
1898 /* Render a single level of the graph that has iEqpId as its parent. Called
1899 ** recursively to render sublevels.
1901 static void eqp_render_level(ShellState *p, int iEqpId){
1902 EQPGraphRow *pRow, *pNext;
1903 int n = strlen30(p->sGraph.zPrefix);
1904 char *z;
1905 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1906 pNext = eqp_next_row(p, iEqpId, pRow);
1907 z = pRow->zText;
1908 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1909 pNext ? "|--" : "`--", z);
1910 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1911 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
1912 eqp_render_level(p, pRow->iEqpId);
1913 p->sGraph.zPrefix[n] = 0;
1919 ** Display and reset the EXPLAIN QUERY PLAN data
1921 static void eqp_render(ShellState *p){
1922 EQPGraphRow *pRow = p->sGraph.pRow;
1923 if( pRow ){
1924 if( pRow->zText[0]=='-' ){
1925 if( pRow->pNext==0 ){
1926 eqp_reset(p);
1927 return;
1929 utf8_printf(p->out, "%s\n", pRow->zText+3);
1930 p->sGraph.pRow = pRow->pNext;
1931 sqlite3_free(pRow);
1932 }else{
1933 utf8_printf(p->out, "QUERY PLAN\n");
1935 p->sGraph.zPrefix[0] = 0;
1936 eqp_render_level(p, 0);
1937 eqp_reset(p);
1941 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1943 ** Progress handler callback.
1945 static int progress_handler(void *pClientData) {
1946 ShellState *p = (ShellState*)pClientData;
1947 p->nProgress++;
1948 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1949 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
1950 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1951 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
1952 return 1;
1954 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
1955 raw_printf(p->out, "Progress %u\n", p->nProgress);
1957 return 0;
1959 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
1962 ** Print N dashes
1964 static void print_dashes(FILE *out, int N){
1965 const char zDash[] = "--------------------------------------------------";
1966 const int nDash = sizeof(zDash) - 1;
1967 while( N>nDash ){
1968 fputs(zDash, out);
1969 N -= nDash;
1971 raw_printf(out, "%.*s", N, zDash);
1975 ** Print a markdown or table-style row separator using ascii-art
1977 static void print_row_separator(
1978 ShellState *p,
1979 int nArg,
1980 const char *zSep
1982 int i;
1983 if( nArg>0 ){
1984 fputs(zSep, p->out);
1985 print_dashes(p->out, p->actualWidth[0]+2);
1986 for(i=1; i<nArg; i++){
1987 fputs(zSep, p->out);
1988 print_dashes(p->out, p->actualWidth[i]+2);
1990 fputs(zSep, p->out);
1992 fputs("\n", p->out);
1996 ** This is the callback routine that the shell
1997 ** invokes for each row of a query result.
1999 static int shell_callback(
2000 void *pArg,
2001 int nArg, /* Number of result columns */
2002 char **azArg, /* Text of each result column */
2003 char **azCol, /* Column names */
2004 int *aiType /* Column types. Might be NULL */
2006 int i;
2007 ShellState *p = (ShellState*)pArg;
2009 if( azArg==0 ) return 0;
2010 switch( p->cMode ){
2011 case MODE_Line: {
2012 int w = 5;
2013 if( azArg==0 ) break;
2014 for(i=0; i<nArg; i++){
2015 int len = strlen30(azCol[i] ? azCol[i] : "");
2016 if( len>w ) w = len;
2018 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2019 for(i=0; i<nArg; i++){
2020 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2021 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2023 break;
2025 case MODE_Explain: {
2026 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2027 if( nArg>ArraySize(aExplainWidth) ){
2028 nArg = ArraySize(aExplainWidth);
2030 if( p->cnt++==0 ){
2031 for(i=0; i<nArg; i++){
2032 int w = aExplainWidth[i];
2033 utf8_width_print(p->out, w, azCol[i]);
2034 fputs(i==nArg-1 ? "\n" : " ", p->out);
2036 for(i=0; i<nArg; i++){
2037 int w = aExplainWidth[i];
2038 print_dashes(p->out, w);
2039 fputs(i==nArg-1 ? "\n" : " ", p->out);
2042 if( azArg==0 ) break;
2043 for(i=0; i<nArg; i++){
2044 int w = aExplainWidth[i];
2045 if( i==nArg-1 ) w = 0;
2046 if( azArg[i] && strlenChar(azArg[i])>w ){
2047 w = strlenChar(azArg[i]);
2049 if( i==1 && p->aiIndent && p->pStmt ){
2050 if( p->iIndent<p->nIndent ){
2051 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2053 p->iIndent++;
2055 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2056 fputs(i==nArg-1 ? "\n" : " ", p->out);
2058 break;
2060 case MODE_Semi: { /* .schema and .fullschema output */
2061 printSchemaLine(p->out, azArg[0], ";\n");
2062 break;
2064 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2065 char *z;
2066 int j;
2067 int nParen = 0;
2068 char cEnd = 0;
2069 char c;
2070 int nLine = 0;
2071 assert( nArg==1 );
2072 if( azArg[0]==0 ) break;
2073 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2074 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2076 utf8_printf(p->out, "%s;\n", azArg[0]);
2077 break;
2079 z = sqlite3_mprintf("%s", azArg[0]);
2080 j = 0;
2081 for(i=0; IsSpace(z[i]); i++){}
2082 for(; (c = z[i])!=0; i++){
2083 if( IsSpace(c) ){
2084 if( z[j-1]=='\r' ) z[j-1] = '\n';
2085 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2086 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2087 j--;
2089 z[j++] = c;
2091 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2092 z[j] = 0;
2093 if( strlen30(z)>=79 ){
2094 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2095 if( c==cEnd ){
2096 cEnd = 0;
2097 }else if( c=='"' || c=='\'' || c=='`' ){
2098 cEnd = c;
2099 }else if( c=='[' ){
2100 cEnd = ']';
2101 }else if( c=='-' && z[i+1]=='-' ){
2102 cEnd = '\n';
2103 }else if( c=='(' ){
2104 nParen++;
2105 }else if( c==')' ){
2106 nParen--;
2107 if( nLine>0 && nParen==0 && j>0 ){
2108 printSchemaLineN(p->out, z, j, "\n");
2109 j = 0;
2112 z[j++] = c;
2113 if( nParen==1 && cEnd==0
2114 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2116 if( c=='\n' ) j--;
2117 printSchemaLineN(p->out, z, j, "\n ");
2118 j = 0;
2119 nLine++;
2120 while( IsSpace(z[i+1]) ){ i++; }
2123 z[j] = 0;
2125 printSchemaLine(p->out, z, ";\n");
2126 sqlite3_free(z);
2127 break;
2129 case MODE_List: {
2130 if( p->cnt++==0 && p->showHeader ){
2131 for(i=0; i<nArg; i++){
2132 utf8_printf(p->out,"%s%s",azCol[i],
2133 i==nArg-1 ? p->rowSeparator : p->colSeparator);
2136 if( azArg==0 ) break;
2137 for(i=0; i<nArg; i++){
2138 char *z = azArg[i];
2139 if( z==0 ) z = p->nullValue;
2140 utf8_printf(p->out, "%s", z);
2141 if( i<nArg-1 ){
2142 utf8_printf(p->out, "%s", p->colSeparator);
2143 }else{
2144 utf8_printf(p->out, "%s", p->rowSeparator);
2147 break;
2149 case MODE_Html: {
2150 if( p->cnt++==0 && p->showHeader ){
2151 raw_printf(p->out,"<TR>");
2152 for(i=0; i<nArg; i++){
2153 raw_printf(p->out,"<TH>");
2154 output_html_string(p->out, azCol[i]);
2155 raw_printf(p->out,"</TH>\n");
2157 raw_printf(p->out,"</TR>\n");
2159 if( azArg==0 ) break;
2160 raw_printf(p->out,"<TR>");
2161 for(i=0; i<nArg; i++){
2162 raw_printf(p->out,"<TD>");
2163 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2164 raw_printf(p->out,"</TD>\n");
2166 raw_printf(p->out,"</TR>\n");
2167 break;
2169 case MODE_Tcl: {
2170 if( p->cnt++==0 && p->showHeader ){
2171 for(i=0; i<nArg; i++){
2172 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2173 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2175 utf8_printf(p->out, "%s", p->rowSeparator);
2177 if( azArg==0 ) break;
2178 for(i=0; i<nArg; i++){
2179 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2180 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2182 utf8_printf(p->out, "%s", p->rowSeparator);
2183 break;
2185 case MODE_Csv: {
2186 setBinaryMode(p->out, 1);
2187 if( p->cnt++==0 && p->showHeader ){
2188 for(i=0; i<nArg; i++){
2189 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2191 utf8_printf(p->out, "%s", p->rowSeparator);
2193 if( nArg>0 ){
2194 for(i=0; i<nArg; i++){
2195 output_csv(p, azArg[i], i<nArg-1);
2197 utf8_printf(p->out, "%s", p->rowSeparator);
2199 setTextMode(p->out, 1);
2200 break;
2202 case MODE_Insert: {
2203 if( azArg==0 ) break;
2204 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2205 if( p->showHeader ){
2206 raw_printf(p->out,"(");
2207 for(i=0; i<nArg; i++){
2208 if( i>0 ) raw_printf(p->out, ",");
2209 if( quoteChar(azCol[i]) ){
2210 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2211 utf8_printf(p->out, "%s", z);
2212 sqlite3_free(z);
2213 }else{
2214 raw_printf(p->out, "%s", azCol[i]);
2217 raw_printf(p->out,")");
2219 p->cnt++;
2220 for(i=0; i<nArg; i++){
2221 raw_printf(p->out, i>0 ? "," : " VALUES(");
2222 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2223 utf8_printf(p->out,"NULL");
2224 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2225 if( ShellHasFlag(p, SHFLG_Newlines) ){
2226 output_quoted_string(p->out, azArg[i]);
2227 }else{
2228 output_quoted_escaped_string(p->out, azArg[i]);
2230 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2231 utf8_printf(p->out,"%s", azArg[i]);
2232 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2233 char z[50];
2234 double r = sqlite3_column_double(p->pStmt, i);
2235 sqlite3_uint64 ur;
2236 memcpy(&ur,&r,sizeof(r));
2237 if( ur==0x7ff0000000000000LL ){
2238 raw_printf(p->out, "1e999");
2239 }else if( ur==0xfff0000000000000LL ){
2240 raw_printf(p->out, "-1e999");
2241 }else{
2242 sqlite3_snprintf(50,z,"%!.20g", r);
2243 raw_printf(p->out, "%s", z);
2245 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2246 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2247 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2248 output_hex_blob(p->out, pBlob, nBlob);
2249 }else if( isNumber(azArg[i], 0) ){
2250 utf8_printf(p->out,"%s", azArg[i]);
2251 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2252 output_quoted_string(p->out, azArg[i]);
2253 }else{
2254 output_quoted_escaped_string(p->out, azArg[i]);
2257 raw_printf(p->out,");\n");
2258 break;
2260 case MODE_Json: {
2261 if( azArg==0 ) break;
2262 if( p->cnt==0 ){
2263 fputs("[{", p->out);
2264 }else{
2265 fputs(",\n{", p->out);
2267 p->cnt++;
2268 for(i=0; i<nArg; i++){
2269 output_json_string(p->out, azCol[i], -1);
2270 putc(':', p->out);
2271 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2272 fputs("null",p->out);
2273 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2274 char z[50];
2275 double r = sqlite3_column_double(p->pStmt, i);
2276 sqlite3_uint64 ur;
2277 memcpy(&ur,&r,sizeof(r));
2278 if( ur==0x7ff0000000000000LL ){
2279 raw_printf(p->out, "1e999");
2280 }else if( ur==0xfff0000000000000LL ){
2281 raw_printf(p->out, "-1e999");
2282 }else{
2283 sqlite3_snprintf(50,z,"%!.20g", r);
2284 raw_printf(p->out, "%s", z);
2286 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2287 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2288 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2289 output_json_string(p->out, pBlob, nBlob);
2290 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2291 output_json_string(p->out, azArg[i], -1);
2292 }else{
2293 utf8_printf(p->out,"%s", azArg[i]);
2295 if( i<nArg-1 ){
2296 putc(',', p->out);
2299 putc('}', p->out);
2300 break;
2302 case MODE_Quote: {
2303 if( azArg==0 ) break;
2304 if( p->cnt==0 && p->showHeader ){
2305 for(i=0; i<nArg; i++){
2306 if( i>0 ) fputs(p->colSeparator, p->out);
2307 output_quoted_string(p->out, azCol[i]);
2309 fputs(p->rowSeparator, p->out);
2311 p->cnt++;
2312 for(i=0; i<nArg; i++){
2313 if( i>0 ) fputs(p->colSeparator, p->out);
2314 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2315 utf8_printf(p->out,"NULL");
2316 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2317 output_quoted_string(p->out, azArg[i]);
2318 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2319 utf8_printf(p->out,"%s", azArg[i]);
2320 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2321 char z[50];
2322 double r = sqlite3_column_double(p->pStmt, i);
2323 sqlite3_snprintf(50,z,"%!.20g", r);
2324 raw_printf(p->out, "%s", z);
2325 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2326 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2327 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2328 output_hex_blob(p->out, pBlob, nBlob);
2329 }else if( isNumber(azArg[i], 0) ){
2330 utf8_printf(p->out,"%s", azArg[i]);
2331 }else{
2332 output_quoted_string(p->out, azArg[i]);
2335 fputs(p->rowSeparator, p->out);
2336 break;
2338 case MODE_Ascii: {
2339 if( p->cnt++==0 && p->showHeader ){
2340 for(i=0; i<nArg; i++){
2341 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2342 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2344 utf8_printf(p->out, "%s", p->rowSeparator);
2346 if( azArg==0 ) break;
2347 for(i=0; i<nArg; i++){
2348 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2349 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2351 utf8_printf(p->out, "%s", p->rowSeparator);
2352 break;
2354 case MODE_EQP: {
2355 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2356 break;
2359 return 0;
2363 ** This is the callback routine that the SQLite library
2364 ** invokes for each row of a query result.
2366 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2367 /* since we don't have type info, call the shell_callback with a NULL value */
2368 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2372 ** This is the callback routine from sqlite3_exec() that appends all
2373 ** output onto the end of a ShellText object.
2375 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2376 ShellText *p = (ShellText*)pArg;
2377 int i;
2378 UNUSED_PARAMETER(az);
2379 if( azArg==0 ) return 0;
2380 if( p->n ) appendText(p, "|", 0);
2381 for(i=0; i<nArg; i++){
2382 if( i ) appendText(p, ",", 0);
2383 if( azArg[i] ) appendText(p, azArg[i], 0);
2385 return 0;
2389 ** Generate an appropriate SELFTEST table in the main database.
2391 static void createSelftestTable(ShellState *p){
2392 char *zErrMsg = 0;
2393 sqlite3_exec(p->db,
2394 "SAVEPOINT selftest_init;\n"
2395 "CREATE TABLE IF NOT EXISTS selftest(\n"
2396 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2397 " op TEXT,\n" /* Operator: memo run */
2398 " cmd TEXT,\n" /* Command text */
2399 " ans TEXT\n" /* Desired answer */
2400 ");"
2401 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2402 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2403 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2404 " 'memo','Tests generated by --init');\n"
2405 "INSERT INTO [_shell$self]\n"
2406 " SELECT 'run',\n"
2407 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2408 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2409 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2410 "FROM sqlite_schema ORDER BY 2',224));\n"
2411 "INSERT INTO [_shell$self]\n"
2412 " SELECT 'run',"
2413 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2414 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2415 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2416 " FROM (\n"
2417 " SELECT name FROM sqlite_schema\n"
2418 " WHERE type='table'\n"
2419 " AND name<>'selftest'\n"
2420 " AND coalesce(rootpage,0)>0\n"
2421 " )\n"
2422 " ORDER BY name;\n"
2423 "INSERT INTO [_shell$self]\n"
2424 " VALUES('run','PRAGMA integrity_check','ok');\n"
2425 "INSERT INTO selftest(tno,op,cmd,ans)"
2426 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2427 "DROP TABLE [_shell$self];"
2428 ,0,0,&zErrMsg);
2429 if( zErrMsg ){
2430 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2431 sqlite3_free(zErrMsg);
2433 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2438 ** Set the destination table field of the ShellState structure to
2439 ** the name of the table given. Escape any quote characters in the
2440 ** table name.
2442 static void set_table_name(ShellState *p, const char *zName){
2443 int i, n;
2444 char cQuote;
2445 char *z;
2447 if( p->zDestTable ){
2448 free(p->zDestTable);
2449 p->zDestTable = 0;
2451 if( zName==0 ) return;
2452 cQuote = quoteChar(zName);
2453 n = strlen30(zName);
2454 if( cQuote ) n += n+2;
2455 z = p->zDestTable = malloc( n+1 );
2456 if( z==0 ) shell_out_of_memory();
2457 n = 0;
2458 if( cQuote ) z[n++] = cQuote;
2459 for(i=0; zName[i]; i++){
2460 z[n++] = zName[i];
2461 if( zName[i]==cQuote ) z[n++] = cQuote;
2463 if( cQuote ) z[n++] = cQuote;
2464 z[n] = 0;
2469 ** Execute a query statement that will generate SQL output. Print
2470 ** the result columns, comma-separated, on a line and then add a
2471 ** semicolon terminator to the end of that line.
2473 ** If the number of columns is 1 and that column contains text "--"
2474 ** then write the semicolon on a separate line. That way, if a
2475 ** "--" comment occurs at the end of the statement, the comment
2476 ** won't consume the semicolon terminator.
2478 static int run_table_dump_query(
2479 ShellState *p, /* Query context */
2480 const char *zSelect /* SELECT statement to extract content */
2482 sqlite3_stmt *pSelect;
2483 int rc;
2484 int nResult;
2485 int i;
2486 const char *z;
2487 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2488 if( rc!=SQLITE_OK || !pSelect ){
2489 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2490 sqlite3_errmsg(p->db));
2491 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2492 return rc;
2494 rc = sqlite3_step(pSelect);
2495 nResult = sqlite3_column_count(pSelect);
2496 while( rc==SQLITE_ROW ){
2497 z = (const char*)sqlite3_column_text(pSelect, 0);
2498 utf8_printf(p->out, "%s", z);
2499 for(i=1; i<nResult; i++){
2500 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2502 if( z==0 ) z = "";
2503 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2504 if( z[0] ){
2505 raw_printf(p->out, "\n;\n");
2506 }else{
2507 raw_printf(p->out, ";\n");
2509 rc = sqlite3_step(pSelect);
2511 rc = sqlite3_finalize(pSelect);
2512 if( rc!=SQLITE_OK ){
2513 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2514 sqlite3_errmsg(p->db));
2515 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2517 return rc;
2521 ** Allocate space and save off current error string.
2523 static char *save_err_msg(
2524 sqlite3 *db /* Database to query */
2526 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2527 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2528 if( zErrMsg ){
2529 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2531 return zErrMsg;
2534 #ifdef __linux__
2536 ** Attempt to display I/O stats on Linux using /proc/PID/io
2538 static void displayLinuxIoStats(FILE *out){
2539 FILE *in;
2540 char z[200];
2541 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2542 in = fopen(z, "rb");
2543 if( in==0 ) return;
2544 while( fgets(z, sizeof(z), in)!=0 ){
2545 static const struct {
2546 const char *zPattern;
2547 const char *zDesc;
2548 } aTrans[] = {
2549 { "rchar: ", "Bytes received by read():" },
2550 { "wchar: ", "Bytes sent to write():" },
2551 { "syscr: ", "Read() system calls:" },
2552 { "syscw: ", "Write() system calls:" },
2553 { "read_bytes: ", "Bytes read from storage:" },
2554 { "write_bytes: ", "Bytes written to storage:" },
2555 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2557 int i;
2558 for(i=0; i<ArraySize(aTrans); i++){
2559 int n = strlen30(aTrans[i].zPattern);
2560 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2561 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2562 break;
2566 fclose(in);
2568 #endif
2571 ** Display a single line of status using 64-bit values.
2573 static void displayStatLine(
2574 ShellState *p, /* The shell context */
2575 char *zLabel, /* Label for this one line */
2576 char *zFormat, /* Format for the result */
2577 int iStatusCtrl, /* Which status to display */
2578 int bReset /* True to reset the stats */
2580 sqlite3_int64 iCur = -1;
2581 sqlite3_int64 iHiwtr = -1;
2582 int i, nPercent;
2583 char zLine[200];
2584 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2585 for(i=0, nPercent=0; zFormat[i]; i++){
2586 if( zFormat[i]=='%' ) nPercent++;
2588 if( nPercent>1 ){
2589 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2590 }else{
2591 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2593 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2597 ** Display memory stats.
2599 static int display_stats(
2600 sqlite3 *db, /* Database to query */
2601 ShellState *pArg, /* Pointer to ShellState */
2602 int bReset /* True to reset the stats */
2604 int iCur;
2605 int iHiwtr;
2606 FILE *out;
2607 if( pArg==0 || pArg->out==0 ) return 0;
2608 out = pArg->out;
2610 if( pArg->pStmt && pArg->statsOn==2 ){
2611 int nCol, i, x;
2612 sqlite3_stmt *pStmt = pArg->pStmt;
2613 char z[100];
2614 nCol = sqlite3_column_count(pStmt);
2615 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2616 for(i=0; i<nCol; i++){
2617 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2618 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2619 #ifndef SQLITE_OMIT_DECLTYPE
2620 sqlite3_snprintf(30, z+x, "declared type:");
2621 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2622 #endif
2623 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2624 sqlite3_snprintf(30, z+x, "database name:");
2625 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2626 sqlite3_snprintf(30, z+x, "table name:");
2627 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2628 sqlite3_snprintf(30, z+x, "origin name:");
2629 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2630 #endif
2634 if( pArg->statsOn==3 ){
2635 if( pArg->pStmt ){
2636 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2637 raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2639 return 0;
2642 displayStatLine(pArg, "Memory Used:",
2643 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2644 displayStatLine(pArg, "Number of Outstanding Allocations:",
2645 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2646 if( pArg->shellFlgs & SHFLG_Pagecache ){
2647 displayStatLine(pArg, "Number of Pcache Pages Used:",
2648 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2650 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2651 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2652 displayStatLine(pArg, "Largest Allocation:",
2653 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2654 displayStatLine(pArg, "Largest Pcache Allocation:",
2655 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2656 #ifdef YYTRACKMAXSTACKDEPTH
2657 displayStatLine(pArg, "Deepest Parser Stack:",
2658 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2659 #endif
2661 if( db ){
2662 if( pArg->shellFlgs & SHFLG_Lookaside ){
2663 iHiwtr = iCur = -1;
2664 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2665 &iCur, &iHiwtr, bReset);
2666 raw_printf(pArg->out,
2667 "Lookaside Slots Used: %d (max %d)\n",
2668 iCur, iHiwtr);
2669 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2670 &iCur, &iHiwtr, bReset);
2671 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2672 iHiwtr);
2673 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2674 &iCur, &iHiwtr, bReset);
2675 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2676 iHiwtr);
2677 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2678 &iCur, &iHiwtr, bReset);
2679 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2680 iHiwtr);
2682 iHiwtr = iCur = -1;
2683 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2684 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2685 iCur);
2686 iHiwtr = iCur = -1;
2687 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2688 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2689 iHiwtr = iCur = -1;
2690 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2691 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2692 iHiwtr = iCur = -1;
2693 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2694 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2695 iHiwtr = iCur = -1;
2696 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2697 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2698 iHiwtr = iCur = -1;
2699 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2700 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2701 iCur);
2702 iHiwtr = iCur = -1;
2703 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2704 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2705 iCur);
2708 if( pArg->pStmt ){
2709 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2710 bReset);
2711 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2712 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2713 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2714 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2715 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2716 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2717 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2718 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2719 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2720 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2721 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2722 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2723 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
2726 #ifdef __linux__
2727 displayLinuxIoStats(pArg->out);
2728 #endif
2730 /* Do not remove this machine readable comment: extra-stats-output-here */
2732 return 0;
2736 ** Display scan stats.
2738 static void display_scanstats(
2739 sqlite3 *db, /* Database to query */
2740 ShellState *pArg /* Pointer to ShellState */
2742 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2743 UNUSED_PARAMETER(db);
2744 UNUSED_PARAMETER(pArg);
2745 #else
2746 int i, k, n, mx;
2747 raw_printf(pArg->out, "-------- scanstats --------\n");
2748 mx = 0;
2749 for(k=0; k<=mx; k++){
2750 double rEstLoop = 1.0;
2751 for(i=n=0; 1; i++){
2752 sqlite3_stmt *p = pArg->pStmt;
2753 sqlite3_int64 nLoop, nVisit;
2754 double rEst;
2755 int iSid;
2756 const char *zExplain;
2757 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2758 break;
2760 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2761 if( iSid>mx ) mx = iSid;
2762 if( iSid!=k ) continue;
2763 if( n==0 ){
2764 rEstLoop = (double)nLoop;
2765 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2767 n++;
2768 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2769 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2770 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2771 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2772 rEstLoop *= rEst;
2773 raw_printf(pArg->out,
2774 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2775 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2779 raw_printf(pArg->out, "---------------------------\n");
2780 #endif
2784 ** Parameter azArray points to a zero-terminated array of strings. zStr
2785 ** points to a single nul-terminated string. Return non-zero if zStr
2786 ** is equal, according to strcmp(), to any of the strings in the array.
2787 ** Otherwise, return zero.
2789 static int str_in_array(const char *zStr, const char **azArray){
2790 int i;
2791 for(i=0; azArray[i]; i++){
2792 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2794 return 0;
2798 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2799 ** and populate the ShellState.aiIndent[] array with the number of
2800 ** spaces each opcode should be indented before it is output.
2802 ** The indenting rules are:
2804 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2805 ** all opcodes that occur between the p2 jump destination and the opcode
2806 ** itself by 2 spaces.
2808 ** * For each "Goto", if the jump destination is earlier in the program
2809 ** and ends on one of:
2810 ** Yield SeekGt SeekLt RowSetRead Rewind
2811 ** or if the P1 parameter is one instead of zero,
2812 ** then indent all opcodes between the earlier instruction
2813 ** and "Goto" by 2 spaces.
2815 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2816 const char *zSql; /* The text of the SQL statement */
2817 const char *z; /* Used to check if this is an EXPLAIN */
2818 int *abYield = 0; /* True if op is an OP_Yield */
2819 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2820 int iOp; /* Index of operation in p->aiIndent[] */
2822 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2823 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2824 "Rewind", 0 };
2825 const char *azGoto[] = { "Goto", 0 };
2827 /* Try to figure out if this is really an EXPLAIN statement. If this
2828 ** cannot be verified, return early. */
2829 if( sqlite3_column_count(pSql)!=8 ){
2830 p->cMode = p->mode;
2831 return;
2833 zSql = sqlite3_sql(pSql);
2834 if( zSql==0 ) return;
2835 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2836 if( sqlite3_strnicmp(z, "explain", 7) ){
2837 p->cMode = p->mode;
2838 return;
2841 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2842 int i;
2843 int iAddr = sqlite3_column_int(pSql, 0);
2844 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2846 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2847 ** p2 is an instruction address, set variable p2op to the index of that
2848 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2849 ** the current instruction is part of a sub-program generated by an
2850 ** SQL trigger or foreign key. */
2851 int p2 = sqlite3_column_int(pSql, 3);
2852 int p2op = (p2 + (iOp-iAddr));
2854 /* Grow the p->aiIndent array as required */
2855 if( iOp>=nAlloc ){
2856 if( iOp==0 ){
2857 /* Do further verfication that this is explain output. Abort if
2858 ** it is not */
2859 static const char *explainCols[] = {
2860 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2861 int jj;
2862 for(jj=0; jj<ArraySize(explainCols); jj++){
2863 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2864 p->cMode = p->mode;
2865 sqlite3_reset(pSql);
2866 return;
2870 nAlloc += 100;
2871 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2872 if( p->aiIndent==0 ) shell_out_of_memory();
2873 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2874 if( abYield==0 ) shell_out_of_memory();
2876 abYield[iOp] = str_in_array(zOp, azYield);
2877 p->aiIndent[iOp] = 0;
2878 p->nIndent = iOp+1;
2880 if( str_in_array(zOp, azNext) ){
2881 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2883 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2884 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2886 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2890 p->iIndent = 0;
2891 sqlite3_free(abYield);
2892 sqlite3_reset(pSql);
2896 ** Free the array allocated by explain_data_prepare().
2898 static void explain_data_delete(ShellState *p){
2899 sqlite3_free(p->aiIndent);
2900 p->aiIndent = 0;
2901 p->nIndent = 0;
2902 p->iIndent = 0;
2906 ** Disable and restore .wheretrace and .selecttrace settings.
2908 static unsigned int savedSelectTrace;
2909 static unsigned int savedWhereTrace;
2910 static void disable_debug_trace_modes(void){
2911 unsigned int zero = 0;
2912 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
2913 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
2914 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
2915 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
2917 static void restore_debug_trace_modes(void){
2918 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
2919 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
2922 /* Create the TEMP table used to store parameter bindings */
2923 static void bind_table_init(ShellState *p){
2924 int wrSchema = 0;
2925 int defensiveMode = 0;
2926 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
2927 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
2928 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2929 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
2930 sqlite3_exec(p->db,
2931 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
2932 " key TEXT PRIMARY KEY,\n"
2933 " value\n"
2934 ") WITHOUT ROWID;",
2935 0, 0, 0);
2936 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
2937 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
2941 ** Bind parameters on a prepared statement.
2943 ** Parameter bindings are taken from a TEMP table of the form:
2945 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
2946 ** WITHOUT ROWID;
2948 ** No bindings occur if this table does not exist. The name of the table
2949 ** begins with "sqlite_" so that it will not collide with ordinary application
2950 ** tables. The table must be in the TEMP schema.
2952 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2953 int nVar;
2954 int i;
2955 int rc;
2956 sqlite3_stmt *pQ = 0;
2958 nVar = sqlite3_bind_parameter_count(pStmt);
2959 if( nVar==0 ) return; /* Nothing to do */
2960 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
2961 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2962 return; /* Parameter table does not exist */
2964 rc = sqlite3_prepare_v2(pArg->db,
2965 "SELECT value FROM temp.sqlite_parameters"
2966 " WHERE key=?1", -1, &pQ, 0);
2967 if( rc || pQ==0 ) return;
2968 for(i=1; i<=nVar; i++){
2969 char zNum[30];
2970 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2971 if( zVar==0 ){
2972 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2973 zVar = zNum;
2975 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2976 if( sqlite3_step(pQ)==SQLITE_ROW ){
2977 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2978 }else{
2979 sqlite3_bind_null(pStmt, i);
2981 sqlite3_reset(pQ);
2983 sqlite3_finalize(pQ);
2987 ** UTF8 box-drawing characters. Imagine box lines like this:
2989 ** 1
2990 ** |
2991 ** 4 --+-- 2
2992 ** |
2993 ** 3
2995 ** Each box characters has between 2 and 4 of the lines leading from
2996 ** the center. The characters are here identified by the numbers of
2997 ** their corresponding lines.
2999 #define BOX_24 "\342\224\200" /* U+2500 --- */
3000 #define BOX_13 "\342\224\202" /* U+2502 | */
3001 #define BOX_23 "\342\224\214" /* U+250c ,- */
3002 #define BOX_34 "\342\224\220" /* U+2510 -, */
3003 #define BOX_12 "\342\224\224" /* U+2514 '- */
3004 #define BOX_14 "\342\224\230" /* U+2518 -' */
3005 #define BOX_123 "\342\224\234" /* U+251c |- */
3006 #define BOX_134 "\342\224\244" /* U+2524 -| */
3007 #define BOX_234 "\342\224\254" /* U+252c -,- */
3008 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3009 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3011 /* Draw horizontal line N characters long using unicode box
3012 ** characters
3014 static void print_box_line(FILE *out, int N){
3015 const char zDash[] =
3016 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3017 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3018 const int nDash = sizeof(zDash) - 1;
3019 N *= 3;
3020 while( N>nDash ){
3021 utf8_printf(out, zDash);
3022 N -= nDash;
3024 utf8_printf(out, "%.*s", N, zDash);
3028 ** Draw a horizontal separator for a MODE_Box table.
3030 static void print_box_row_separator(
3031 ShellState *p,
3032 int nArg,
3033 const char *zSep1,
3034 const char *zSep2,
3035 const char *zSep3
3037 int i;
3038 if( nArg>0 ){
3039 utf8_printf(p->out, "%s", zSep1);
3040 print_box_line(p->out, p->actualWidth[0]+2);
3041 for(i=1; i<nArg; i++){
3042 utf8_printf(p->out, "%s", zSep2);
3043 print_box_line(p->out, p->actualWidth[i]+2);
3045 utf8_printf(p->out, "%s", zSep3);
3047 fputs("\n", p->out);
3053 ** Run a prepared statement and output the result in one of the
3054 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3055 ** or MODE_Box.
3057 ** This is different from ordinary exec_prepared_stmt() in that
3058 ** it has to run the entire query and gather the results into memory
3059 ** first, in order to determine column widths, before providing
3060 ** any output.
3062 static void exec_prepared_stmt_columnar(
3063 ShellState *p, /* Pointer to ShellState */
3064 sqlite3_stmt *pStmt /* Statment to run */
3066 sqlite3_int64 nRow = 0;
3067 int nColumn = 0;
3068 char **azData = 0;
3069 sqlite3_int64 nAlloc = 0;
3070 const char *z;
3071 int rc;
3072 sqlite3_int64 i, nData;
3073 int j, nTotal, w, n;
3074 const char *colSep = 0;
3075 const char *rowSep = 0;
3077 rc = sqlite3_step(pStmt);
3078 if( rc!=SQLITE_ROW ) return;
3079 nColumn = sqlite3_column_count(pStmt);
3080 nAlloc = nColumn*4;
3081 if( nAlloc<=0 ) nAlloc = 1;
3082 azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3083 if( azData==0 ) shell_out_of_memory();
3084 for(i=0; i<nColumn; i++){
3085 azData[i] = strdup(sqlite3_column_name(pStmt,i));
3088 if( (nRow+2)*nColumn >= nAlloc ){
3089 nAlloc *= 2;
3090 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3091 if( azData==0 ) shell_out_of_memory();
3093 nRow++;
3094 for(i=0; i<nColumn; i++){
3095 z = (const char*)sqlite3_column_text(pStmt,i);
3096 azData[nRow*nColumn + i] = z ? strdup(z) : 0;
3098 }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
3099 if( nColumn>p->nWidth ){
3100 p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
3101 if( p->colWidth==0 ) shell_out_of_memory();
3102 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3103 p->nWidth = nColumn;
3104 p->actualWidth = &p->colWidth[nColumn];
3106 memset(p->actualWidth, 0, nColumn*sizeof(int));
3107 for(i=0; i<nColumn; i++){
3108 w = p->colWidth[i];
3109 if( w<0 ) w = -w;
3110 p->actualWidth[i] = w;
3112 nTotal = nColumn*(nRow+1);
3113 for(i=0; i<nTotal; i++){
3114 z = azData[i];
3115 if( z==0 ) z = p->nullValue;
3116 n = strlenChar(z);
3117 j = i%nColumn;
3118 if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3120 if( seenInterrupt ) goto columnar_end;
3121 if( nColumn==0 ) goto columnar_end;
3122 switch( p->cMode ){
3123 case MODE_Column: {
3124 colSep = " ";
3125 rowSep = "\n";
3126 if( p->showHeader ){
3127 for(i=0; i<nColumn; i++){
3128 w = p->actualWidth[i];
3129 if( p->colWidth[i]<0 ) w = -w;
3130 utf8_width_print(p->out, w, azData[i]);
3131 fputs(i==nColumn-1?"\n":" ", p->out);
3133 for(i=0; i<nColumn; i++){
3134 print_dashes(p->out, p->actualWidth[i]);
3135 fputs(i==nColumn-1?"\n":" ", p->out);
3138 break;
3140 case MODE_Table: {
3141 colSep = " | ";
3142 rowSep = " |\n";
3143 print_row_separator(p, nColumn, "+");
3144 fputs("| ", p->out);
3145 for(i=0; i<nColumn; i++){
3146 w = p->actualWidth[i];
3147 n = strlenChar(azData[i]);
3148 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3149 fputs(i==nColumn-1?" |\n":" | ", p->out);
3151 print_row_separator(p, nColumn, "+");
3152 break;
3154 case MODE_Markdown: {
3155 colSep = " | ";
3156 rowSep = " |\n";
3157 fputs("| ", p->out);
3158 for(i=0; i<nColumn; i++){
3159 w = p->actualWidth[i];
3160 n = strlenChar(azData[i]);
3161 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3162 fputs(i==nColumn-1?" |\n":" | ", p->out);
3164 print_row_separator(p, nColumn, "|");
3165 break;
3167 case MODE_Box: {
3168 colSep = " " BOX_13 " ";
3169 rowSep = " " BOX_13 "\n";
3170 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3171 utf8_printf(p->out, BOX_13 " ");
3172 for(i=0; i<nColumn; i++){
3173 w = p->actualWidth[i];
3174 n = strlenChar(azData[i]);
3175 utf8_printf(p->out, "%*s%s%*s%s",
3176 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3177 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3179 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3180 break;
3183 for(i=nColumn, j=0; i<nTotal; i++, j++){
3184 if( j==0 && p->cMode!=MODE_Column ){
3185 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3187 z = azData[i];
3188 if( z==0 ) z = p->nullValue;
3189 w = p->actualWidth[j];
3190 if( p->colWidth[j]<0 ) w = -w;
3191 utf8_width_print(p->out, w, z);
3192 if( j==nColumn-1 ){
3193 utf8_printf(p->out, "%s", rowSep);
3194 j = -1;
3195 if( seenInterrupt ) goto columnar_end;
3196 }else{
3197 utf8_printf(p->out, "%s", colSep);
3200 if( p->cMode==MODE_Table ){
3201 print_row_separator(p, nColumn, "+");
3202 }else if( p->cMode==MODE_Box ){
3203 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3205 columnar_end:
3206 if( seenInterrupt ){
3207 utf8_printf(p->out, "Interrupt\n");
3209 nData = (nRow+1)*nColumn;
3210 for(i=0; i<nData; i++) free(azData[i]);
3211 sqlite3_free(azData);
3215 ** Run a prepared statement
3217 static void exec_prepared_stmt(
3218 ShellState *pArg, /* Pointer to ShellState */
3219 sqlite3_stmt *pStmt /* Statment to run */
3221 int rc;
3223 if( pArg->cMode==MODE_Column
3224 || pArg->cMode==MODE_Table
3225 || pArg->cMode==MODE_Box
3226 || pArg->cMode==MODE_Markdown
3228 exec_prepared_stmt_columnar(pArg, pStmt);
3229 return;
3232 /* perform the first step. this will tell us if we
3233 ** have a result set or not and how wide it is.
3235 rc = sqlite3_step(pStmt);
3236 /* if we have a result set... */
3237 if( SQLITE_ROW == rc ){
3238 /* allocate space for col name ptr, value ptr, and type */
3239 int nCol = sqlite3_column_count(pStmt);
3240 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3241 if( !pData ){
3242 rc = SQLITE_NOMEM;
3243 }else{
3244 char **azCols = (char **)pData; /* Names of result columns */
3245 char **azVals = &azCols[nCol]; /* Results */
3246 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3247 int i, x;
3248 assert(sizeof(int) <= sizeof(char *));
3249 /* save off ptrs to column names */
3250 for(i=0; i<nCol; i++){
3251 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3254 /* extract the data and data types */
3255 for(i=0; i<nCol; i++){
3256 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3257 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3258 azVals[i] = "";
3259 }else{
3260 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3262 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3263 rc = SQLITE_NOMEM;
3264 break; /* from for */
3266 } /* end for */
3268 /* if data and types extracted successfully... */
3269 if( SQLITE_ROW == rc ){
3270 /* call the supplied callback with the result row data */
3271 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3272 rc = SQLITE_ABORT;
3273 }else{
3274 rc = sqlite3_step(pStmt);
3277 } while( SQLITE_ROW == rc );
3278 sqlite3_free(pData);
3279 if( pArg->cMode==MODE_Json ){
3280 fputs("]\n", pArg->out);
3286 #ifndef SQLITE_OMIT_VIRTUALTABLE
3288 ** This function is called to process SQL if the previous shell command
3289 ** was ".expert". It passes the SQL in the second argument directly to
3290 ** the sqlite3expert object.
3292 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3293 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3294 ** an English language error message. It is the responsibility of the
3295 ** caller to eventually free this buffer using sqlite3_free().
3297 static int expertHandleSQL(
3298 ShellState *pState,
3299 const char *zSql,
3300 char **pzErr
3302 assert( pState->expert.pExpert );
3303 assert( pzErr==0 || *pzErr==0 );
3304 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3308 ** This function is called either to silently clean up the object
3309 ** created by the ".expert" command (if bCancel==1), or to generate a
3310 ** report from it and then clean it up (if bCancel==0).
3312 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3313 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3314 ** an English language error message. It is the responsibility of the
3315 ** caller to eventually free this buffer using sqlite3_free().
3317 static int expertFinish(
3318 ShellState *pState,
3319 int bCancel,
3320 char **pzErr
3322 int rc = SQLITE_OK;
3323 sqlite3expert *p = pState->expert.pExpert;
3324 assert( p );
3325 assert( bCancel || pzErr==0 || *pzErr==0 );
3326 if( bCancel==0 ){
3327 FILE *out = pState->out;
3328 int bVerbose = pState->expert.bVerbose;
3330 rc = sqlite3_expert_analyze(p, pzErr);
3331 if( rc==SQLITE_OK ){
3332 int nQuery = sqlite3_expert_count(p);
3333 int i;
3335 if( bVerbose ){
3336 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3337 raw_printf(out, "-- Candidates -----------------------------\n");
3338 raw_printf(out, "%s\n", zCand);
3340 for(i=0; i<nQuery; i++){
3341 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3342 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3343 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3344 if( zIdx==0 ) zIdx = "(no new indexes)\n";
3345 if( bVerbose ){
3346 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3347 raw_printf(out, "%s\n\n", zSql);
3349 raw_printf(out, "%s\n", zIdx);
3350 raw_printf(out, "%s\n", zEQP);
3354 sqlite3_expert_destroy(p);
3355 pState->expert.pExpert = 0;
3356 return rc;
3360 ** Implementation of ".expert" dot command.
3362 static int expertDotCommand(
3363 ShellState *pState, /* Current shell tool state */
3364 char **azArg, /* Array of arguments passed to dot command */
3365 int nArg /* Number of entries in azArg[] */
3367 int rc = SQLITE_OK;
3368 char *zErr = 0;
3369 int i;
3370 int iSample = 0;
3372 assert( pState->expert.pExpert==0 );
3373 memset(&pState->expert, 0, sizeof(ExpertInfo));
3375 for(i=1; rc==SQLITE_OK && i<nArg; i++){
3376 char *z = azArg[i];
3377 int n;
3378 if( z[0]=='-' && z[1]=='-' ) z++;
3379 n = strlen30(z);
3380 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3381 pState->expert.bVerbose = 1;
3383 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3384 if( i==(nArg-1) ){
3385 raw_printf(stderr, "option requires an argument: %s\n", z);
3386 rc = SQLITE_ERROR;
3387 }else{
3388 iSample = (int)integerValue(azArg[++i]);
3389 if( iSample<0 || iSample>100 ){
3390 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3391 rc = SQLITE_ERROR;
3395 else{
3396 raw_printf(stderr, "unknown option: %s\n", z);
3397 rc = SQLITE_ERROR;
3401 if( rc==SQLITE_OK ){
3402 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3403 if( pState->expert.pExpert==0 ){
3404 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
3405 rc = SQLITE_ERROR;
3406 }else{
3407 sqlite3_expert_config(
3408 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3413 return rc;
3415 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3418 ** Execute a statement or set of statements. Print
3419 ** any result rows/columns depending on the current mode
3420 ** set via the supplied callback.
3422 ** This is very similar to SQLite's built-in sqlite3_exec()
3423 ** function except it takes a slightly different callback
3424 ** and callback data argument.
3426 static int shell_exec(
3427 ShellState *pArg, /* Pointer to ShellState */
3428 const char *zSql, /* SQL to be evaluated */
3429 char **pzErrMsg /* Error msg written here */
3431 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3432 int rc = SQLITE_OK; /* Return Code */
3433 int rc2;
3434 const char *zLeftover; /* Tail of unprocessed SQL */
3435 sqlite3 *db = pArg->db;
3437 if( pzErrMsg ){
3438 *pzErrMsg = NULL;
3441 #ifndef SQLITE_OMIT_VIRTUALTABLE
3442 if( pArg->expert.pExpert ){
3443 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3444 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3446 #endif
3448 while( zSql[0] && (SQLITE_OK == rc) ){
3449 static const char *zStmtSql;
3450 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3451 if( SQLITE_OK != rc ){
3452 if( pzErrMsg ){
3453 *pzErrMsg = save_err_msg(db);
3455 }else{
3456 if( !pStmt ){
3457 /* this happens for a comment or white-space */
3458 zSql = zLeftover;
3459 while( IsSpace(zSql[0]) ) zSql++;
3460 continue;
3462 zStmtSql = sqlite3_sql(pStmt);
3463 if( zStmtSql==0 ) zStmtSql = "";
3464 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3466 /* save off the prepared statment handle and reset row count */
3467 if( pArg ){
3468 pArg->pStmt = pStmt;
3469 pArg->cnt = 0;
3472 /* echo the sql statement if echo on */
3473 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3474 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3477 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3478 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3479 sqlite3_stmt *pExplain;
3480 char *zEQP;
3481 int triggerEQP = 0;
3482 disable_debug_trace_modes();
3483 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3484 if( pArg->autoEQP>=AUTOEQP_trigger ){
3485 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3487 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3488 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3489 if( rc==SQLITE_OK ){
3490 while( sqlite3_step(pExplain)==SQLITE_ROW ){
3491 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3492 int iEqpId = sqlite3_column_int(pExplain, 0);
3493 int iParentId = sqlite3_column_int(pExplain, 1);
3494 if( zEQPLine==0 ) zEQPLine = "";
3495 if( zEQPLine[0]=='-' ) eqp_render(pArg);
3496 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3498 eqp_render(pArg);
3500 sqlite3_finalize(pExplain);
3501 sqlite3_free(zEQP);
3502 if( pArg->autoEQP>=AUTOEQP_full ){
3503 /* Also do an EXPLAIN for ".eqp full" mode */
3504 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3505 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3506 if( rc==SQLITE_OK ){
3507 pArg->cMode = MODE_Explain;
3508 explain_data_prepare(pArg, pExplain);
3509 exec_prepared_stmt(pArg, pExplain);
3510 explain_data_delete(pArg);
3512 sqlite3_finalize(pExplain);
3513 sqlite3_free(zEQP);
3515 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3516 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3517 /* Reprepare pStmt before reactiving trace modes */
3518 sqlite3_finalize(pStmt);
3519 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3520 if( pArg ) pArg->pStmt = pStmt;
3522 restore_debug_trace_modes();
3525 if( pArg ){
3526 pArg->cMode = pArg->mode;
3527 if( pArg->autoExplain ){
3528 if( sqlite3_stmt_isexplain(pStmt)==1 ){
3529 pArg->cMode = MODE_Explain;
3531 if( sqlite3_stmt_isexplain(pStmt)==2 ){
3532 pArg->cMode = MODE_EQP;
3536 /* If the shell is currently in ".explain" mode, gather the extra
3537 ** data required to add indents to the output.*/
3538 if( pArg->cMode==MODE_Explain ){
3539 explain_data_prepare(pArg, pStmt);
3543 bind_prepared_stmt(pArg, pStmt);
3544 exec_prepared_stmt(pArg, pStmt);
3545 explain_data_delete(pArg);
3546 eqp_render(pArg);
3548 /* print usage stats if stats on */
3549 if( pArg && pArg->statsOn ){
3550 display_stats(db, pArg, 0);
3553 /* print loop-counters if required */
3554 if( pArg && pArg->scanstatsOn ){
3555 display_scanstats(db, pArg);
3558 /* Finalize the statement just executed. If this fails, save a
3559 ** copy of the error message. Otherwise, set zSql to point to the
3560 ** next statement to execute. */
3561 rc2 = sqlite3_finalize(pStmt);
3562 if( rc!=SQLITE_NOMEM ) rc = rc2;
3563 if( rc==SQLITE_OK ){
3564 zSql = zLeftover;
3565 while( IsSpace(zSql[0]) ) zSql++;
3566 }else if( pzErrMsg ){
3567 *pzErrMsg = save_err_msg(db);
3570 /* clear saved stmt handle */
3571 if( pArg ){
3572 pArg->pStmt = NULL;
3575 } /* end while */
3577 return rc;
3581 ** Release memory previously allocated by tableColumnList().
3583 static void freeColumnList(char **azCol){
3584 int i;
3585 for(i=1; azCol[i]; i++){
3586 sqlite3_free(azCol[i]);
3588 /* azCol[0] is a static string */
3589 sqlite3_free(azCol);
3593 ** Return a list of pointers to strings which are the names of all
3594 ** columns in table zTab. The memory to hold the names is dynamically
3595 ** allocated and must be released by the caller using a subsequent call
3596 ** to freeColumnList().
3598 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3599 ** value that needs to be preserved, then azCol[0] is filled in with the
3600 ** name of the rowid column.
3602 ** The first regular column in the table is azCol[1]. The list is terminated
3603 ** by an entry with azCol[i]==0.
3605 static char **tableColumnList(ShellState *p, const char *zTab){
3606 char **azCol = 0;
3607 sqlite3_stmt *pStmt;
3608 char *zSql;
3609 int nCol = 0;
3610 int nAlloc = 0;
3611 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3612 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3613 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3614 int rc;
3616 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3617 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3618 sqlite3_free(zSql);
3619 if( rc ) return 0;
3620 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3621 if( nCol>=nAlloc-2 ){
3622 nAlloc = nAlloc*2 + nCol + 10;
3623 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3624 if( azCol==0 ) shell_out_of_memory();
3626 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3627 if( sqlite3_column_int(pStmt, 5) ){
3628 nPK++;
3629 if( nPK==1
3630 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3631 "INTEGER")==0
3633 isIPK = 1;
3634 }else{
3635 isIPK = 0;
3639 sqlite3_finalize(pStmt);
3640 if( azCol==0 ) return 0;
3641 azCol[0] = 0;
3642 azCol[nCol+1] = 0;
3644 /* The decision of whether or not a rowid really needs to be preserved
3645 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3646 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3647 ** rowids on tables where the rowid is inaccessible because there are other
3648 ** columns in the table named "rowid", "_rowid_", and "oid".
3650 if( preserveRowid && isIPK ){
3651 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3652 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3653 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3654 ** ROWID aliases. To distinguish these cases, check to see if
3655 ** there is a "pk" entry in "PRAGMA index_list". There will be
3656 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3658 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3659 " WHERE origin='pk'", zTab);
3660 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3661 sqlite3_free(zSql);
3662 if( rc ){
3663 freeColumnList(azCol);
3664 return 0;
3666 rc = sqlite3_step(pStmt);
3667 sqlite3_finalize(pStmt);
3668 preserveRowid = rc==SQLITE_ROW;
3670 if( preserveRowid ){
3671 /* Only preserve the rowid if we can find a name to use for the
3672 ** rowid */
3673 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3674 int i, j;
3675 for(j=0; j<3; j++){
3676 for(i=1; i<=nCol; i++){
3677 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3679 if( i>nCol ){
3680 /* At this point, we know that azRowid[j] is not the name of any
3681 ** ordinary column in the table. Verify that azRowid[j] is a valid
3682 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3683 ** tables will fail this last check */
3684 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3685 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3686 break;
3690 return azCol;
3694 ** Toggle the reverse_unordered_selects setting.
3696 static void toggleSelectOrder(sqlite3 *db){
3697 sqlite3_stmt *pStmt = 0;
3698 int iSetting = 0;
3699 char zStmt[100];
3700 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3701 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3702 iSetting = sqlite3_column_int(pStmt, 0);
3704 sqlite3_finalize(pStmt);
3705 sqlite3_snprintf(sizeof(zStmt), zStmt,
3706 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3707 sqlite3_exec(db, zStmt, 0, 0, 0);
3711 ** This is a different callback routine used for dumping the database.
3712 ** Each row received by this callback consists of a table name,
3713 ** the table type ("index" or "table") and SQL to create the table.
3714 ** This routine should print text sufficient to recreate the table.
3716 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3717 int rc;
3718 const char *zTable;
3719 const char *zType;
3720 const char *zSql;
3721 ShellState *p = (ShellState *)pArg;
3722 int dataOnly;
3723 int noSys;
3725 UNUSED_PARAMETER(azNotUsed);
3726 if( nArg!=3 || azArg==0 ) return 0;
3727 zTable = azArg[0];
3728 zType = azArg[1];
3729 zSql = azArg[2];
3730 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
3731 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
3733 if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
3734 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3735 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
3736 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
3737 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3738 return 0;
3739 }else if( dataOnly ){
3740 /* no-op */
3741 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3742 char *zIns;
3743 if( !p->writableSchema ){
3744 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3745 p->writableSchema = 1;
3747 zIns = sqlite3_mprintf(
3748 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
3749 "VALUES('table','%q','%q',0,'%q');",
3750 zTable, zTable, zSql);
3751 utf8_printf(p->out, "%s\n", zIns);
3752 sqlite3_free(zIns);
3753 return 0;
3754 }else{
3755 printSchemaLine(p->out, zSql, ";\n");
3758 if( strcmp(zType, "table")==0 ){
3759 ShellText sSelect;
3760 ShellText sTable;
3761 char **azCol;
3762 int i;
3763 char *savedDestTable;
3764 int savedMode;
3766 azCol = tableColumnList(p, zTable);
3767 if( azCol==0 ){
3768 p->nErr++;
3769 return 0;
3772 /* Always quote the table name, even if it appears to be pure ascii,
3773 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3774 initText(&sTable);
3775 appendText(&sTable, zTable, quoteChar(zTable));
3776 /* If preserving the rowid, add a column list after the table name.
3777 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3778 ** instead of the usual "INSERT INTO tab VALUES(...)".
3780 if( azCol[0] ){
3781 appendText(&sTable, "(", 0);
3782 appendText(&sTable, azCol[0], 0);
3783 for(i=1; azCol[i]; i++){
3784 appendText(&sTable, ",", 0);
3785 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3787 appendText(&sTable, ")", 0);
3790 /* Build an appropriate SELECT statement */
3791 initText(&sSelect);
3792 appendText(&sSelect, "SELECT ", 0);
3793 if( azCol[0] ){
3794 appendText(&sSelect, azCol[0], 0);
3795 appendText(&sSelect, ",", 0);
3797 for(i=1; azCol[i]; i++){
3798 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3799 if( azCol[i+1] ){
3800 appendText(&sSelect, ",", 0);
3803 freeColumnList(azCol);
3804 appendText(&sSelect, " FROM ", 0);
3805 appendText(&sSelect, zTable, quoteChar(zTable));
3807 savedDestTable = p->zDestTable;
3808 savedMode = p->mode;
3809 p->zDestTable = sTable.z;
3810 p->mode = p->cMode = MODE_Insert;
3811 rc = shell_exec(p, sSelect.z, 0);
3812 if( (rc&0xff)==SQLITE_CORRUPT ){
3813 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3814 toggleSelectOrder(p->db);
3815 shell_exec(p, sSelect.z, 0);
3816 toggleSelectOrder(p->db);
3818 p->zDestTable = savedDestTable;
3819 p->mode = savedMode;
3820 freeText(&sTable);
3821 freeText(&sSelect);
3822 if( rc ) p->nErr++;
3824 return 0;
3828 ** Run zQuery. Use dump_callback() as the callback routine so that
3829 ** the contents of the query are output as SQL statements.
3831 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3832 ** "ORDER BY rowid DESC" to the end.
3834 static int run_schema_dump_query(
3835 ShellState *p,
3836 const char *zQuery
3838 int rc;
3839 char *zErr = 0;
3840 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3841 if( rc==SQLITE_CORRUPT ){
3842 char *zQ2;
3843 int len = strlen30(zQuery);
3844 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3845 if( zErr ){
3846 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3847 sqlite3_free(zErr);
3848 zErr = 0;
3850 zQ2 = malloc( len+100 );
3851 if( zQ2==0 ) return rc;
3852 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3853 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3854 if( rc ){
3855 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3856 }else{
3857 rc = SQLITE_CORRUPT;
3859 sqlite3_free(zErr);
3860 free(zQ2);
3862 return rc;
3866 ** Text of help messages.
3868 ** The help text for each individual command begins with a line that starts
3869 ** with ".". Subsequent lines are supplimental information.
3871 ** There must be two or more spaces between the end of the command and the
3872 ** start of the description of what that command does.
3874 static const char *(azHelp[]) = {
3875 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3876 ".archive ... Manage SQL archives",
3877 " Each command must have exactly one of the following options:",
3878 " -c, --create Create a new archive",
3879 " -u, --update Add or update files with changed mtime",
3880 " -i, --insert Like -u but always add even if unchanged",
3881 " -t, --list List contents of archive",
3882 " -x, --extract Extract files from archive",
3883 " Optional arguments:",
3884 " -v, --verbose Print each filename as it is processed",
3885 " -f FILE, --file FILE Use archive FILE (default is current db)",
3886 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
3887 " -C DIR, --directory DIR Read/extract files from directory DIR",
3888 " -n, --dryrun Show the SQL that would have occurred",
3889 " Examples:",
3890 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
3891 " .ar -tf ARCHIVE # List members of ARCHIVE",
3892 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
3893 " See also:",
3894 " http://sqlite.org/cli.html#sqlite_archive_support",
3895 #endif
3896 #ifndef SQLITE_OMIT_AUTHORIZATION
3897 ".auth ON|OFF Show authorizer callbacks",
3898 #endif
3899 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3900 " --append Use the appendvfs",
3901 " --async Write to FILE without journal and fsync()",
3902 ".bail on|off Stop after hitting an error. Default OFF",
3903 ".binary on|off Turn binary output on or off. Default OFF",
3904 ".cd DIRECTORY Change the working directory to DIRECTORY",
3905 ".changes on|off Show number of rows changed by SQL",
3906 ".check GLOB Fail if output since .testcase does not match",
3907 ".clone NEWDB Clone data into NEWDB from the existing database",
3908 ".databases List names and files of attached databases",
3909 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3910 ".dbinfo ?DB? Show status information about the database",
3911 ".dump ?OBJECTS? Render database content as SQL",
3912 " Options:",
3913 " --data-only Output only INSERT statements",
3914 " --newlines Allow unescaped newline characters in output",
3915 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
3916 " --preserve-rowids Include ROWID values in the output",
3917 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
3918 " Additional LIKE patterns can be given in subsequent arguments",
3919 ".echo on|off Turn command echo on or off",
3920 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3921 " Other Modes:",
3922 #ifdef SQLITE_DEBUG
3923 " test Show raw EXPLAIN QUERY PLAN output",
3924 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
3925 #endif
3926 " trigger Like \"full\" but also show trigger bytecode",
3927 ".excel Display the output of next command in spreadsheet",
3928 " --bom Put a UTF8 byte-order mark on intermediate file",
3929 ".exit ?CODE? Exit this program with return-code CODE",
3930 ".expert EXPERIMENTAL. Suggest indexes for queries",
3931 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
3932 ".filectrl CMD ... Run various sqlite3_file_control() operations",
3933 " --schema SCHEMA Use SCHEMA instead of \"main\"",
3934 " --help Show CMD details",
3935 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3936 ".headers on|off Turn display of headers on or off",
3937 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3938 ".import FILE TABLE Import data from FILE into TABLE",
3939 " Options:",
3940 " --ascii Use \\037 and \\036 as column and row separators",
3941 " --csv Use , and \\n as column and row separators",
3942 " --skip N Skip the first N rows of input",
3943 " -v \"Verbose\" - increase auxiliary output",
3944 " Notes:",
3945 " * If TABLE does not exist, it is created. The first row of input",
3946 " determines the column names.",
3947 " * If neither --csv or --ascii are used, the input mode is derived",
3948 " from the \".mode\" output mode",
3949 " * If FILE begins with \"|\" then it is a command that generates the",
3950 " input text.",
3951 #ifndef SQLITE_OMIT_TEST_CONTROL
3952 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
3953 #endif
3954 ".indexes ?TABLE? Show names of indexes",
3955 " If TABLE is specified, only show indexes for",
3956 " tables matching TABLE using the LIKE operator.",
3957 #ifdef SQLITE_ENABLE_IOTRACE
3958 ".iotrace FILE Enable I/O diagnostic logging to FILE",
3959 #endif
3960 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3961 ".lint OPTIONS Report potential schema issues.",
3962 " Options:",
3963 " fkey-indexes Find missing foreign key indexes",
3964 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3965 ".load FILE ?ENTRY? Load an extension library",
3966 #endif
3967 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3968 ".mode MODE ?TABLE? Set output mode",
3969 " MODE is one of:",
3970 " ascii Columns/rows delimited by 0x1F and 0x1E",
3971 " box Tables using unicode box-drawing characters",
3972 " csv Comma-separated values",
3973 " column Output in columns. (See .width)",
3974 " html HTML <table> code",
3975 " insert SQL insert statements for TABLE",
3976 " json Results in a JSON array",
3977 " line One value per line",
3978 " list Values delimited by \"|\"",
3979 " markdown Markdown table format",
3980 " quote Escape answers as for SQL",
3981 " table ASCII-art table",
3982 " tabs Tab-separated values",
3983 " tcl TCL list elements",
3984 ".nullvalue STRING Use STRING in place of NULL values",
3985 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
3986 " If FILE begins with '|' then open as a pipe",
3987 " --bom Put a UTF8 byte-order mark at the beginning",
3988 " -e Send output to the system text editor",
3989 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
3990 #ifdef SQLITE_DEBUG
3991 ".oom ?--repeat M? ?N? Simulate an OOM error on the N-th allocation",
3992 #endif
3993 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3994 " Options:",
3995 " --append Use appendvfs to append database to the end of FILE",
3996 #ifndef SQLITE_OMIT_DESERIALIZE
3997 " --deserialize Load into memory using sqlite3_deserialize()",
3998 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
3999 " --maxsize N Maximum size for --hexdb or --deserialized database",
4000 #endif
4001 " --new Initialize FILE to an empty database",
4002 " --nofollow Do not follow symbolic links",
4003 " --readonly Open FILE readonly",
4004 " --zip FILE is a ZIP archive",
4005 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4006 " If FILE begins with '|' then open it as a pipe.",
4007 " Options:",
4008 " --bom Prefix output with a UTF8 byte-order mark",
4009 " -e Send output to the system text editor",
4010 " -x Send output as CSV to a spreadsheet",
4011 ".parameter CMD ... Manage SQL parameter bindings",
4012 " clear Erase all bindings",
4013 " init Initialize the TEMP table that holds bindings",
4014 " list List the current parameter bindings",
4015 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4016 " PARAMETER should start with one of: $ : @ ?",
4017 " unset PARAMETER Remove PARAMETER from the binding table",
4018 ".print STRING... Print literal STRING",
4019 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4020 ".progress N Invoke progress handler after every N opcodes",
4021 " --limit N Interrupt after N progress callbacks",
4022 " --once Do no more than one progress interrupt",
4023 " --quiet|-q No output except at interrupts",
4024 " --reset Reset the count for each input and interrupt",
4025 #endif
4026 ".prompt MAIN CONTINUE Replace the standard prompts",
4027 ".quit Exit this program",
4028 ".read FILE Read input from FILE",
4029 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4030 ".recover Recover as much data as possible from corrupt db.",
4031 " --freelist-corrupt Assume the freelist is corrupt",
4032 " --recovery-db NAME Store recovery metadata in database file NAME",
4033 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4034 " --no-rowids Do not attempt to recover rowid values",
4035 " that are not also INTEGER PRIMARY KEYs",
4036 #endif
4037 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4038 ".save FILE Write in-memory database into FILE",
4039 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
4040 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4041 " Options:",
4042 " --indent Try to pretty-print the schema",
4043 " --nosys Omit objects whose names start with \"sqlite_\"",
4044 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4045 " Options:",
4046 " --init Create a new SELFTEST table",
4047 " -v Verbose output",
4048 ".separator COL ?ROW? Change the column and row separators",
4049 #if defined(SQLITE_ENABLE_SESSION)
4050 ".session ?NAME? CMD ... Create or control sessions",
4051 " Subcommands:",
4052 " attach TABLE Attach TABLE",
4053 " changeset FILE Write a changeset into FILE",
4054 " close Close one session",
4055 " enable ?BOOLEAN? Set or query the enable bit",
4056 " filter GLOB... Reject tables matching GLOBs",
4057 " indirect ?BOOLEAN? Mark or query the indirect status",
4058 " isempty Query whether the session is empty",
4059 " list List currently open session names",
4060 " open DB NAME Open a new session on DB",
4061 " patchset FILE Write a patchset into FILE",
4062 " If ?NAME? is omitted, the first defined session is used.",
4063 #endif
4064 ".sha3sum ... Compute a SHA3 hash of database content",
4065 " Options:",
4066 " --schema Also hash the sqlite_schema table",
4067 " --sha3-224 Use the sha3-224 algorithm",
4068 " --sha3-256 Use the sha3-256 algorithm (default)",
4069 " --sha3-384 Use the sha3-384 algorithm",
4070 " --sha3-512 Use the sha3-512 algorithm",
4071 " Any other argument is a LIKE pattern for tables to hash",
4072 #ifndef SQLITE_NOHAVE_SYSTEM
4073 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4074 #endif
4075 ".show Show the current values for various settings",
4076 ".stats ?ARG? Show stats or turn stats on or off",
4077 " off Turn off automatic stat display",
4078 " on Turn on automatic stat display",
4079 " stmt Show statement stats",
4080 " vmstep Show the virtual machine step count only",
4081 #ifndef SQLITE_NOHAVE_SYSTEM
4082 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4083 #endif
4084 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4085 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
4086 ".testctrl CMD ... Run various sqlite3_test_control() operations",
4087 " Run \".testctrl\" with no arguments for details",
4088 ".timeout MS Try opening locked tables for MS milliseconds",
4089 ".timer on|off Turn SQL timer on or off",
4090 #ifndef SQLITE_OMIT_TRACE
4091 ".trace ?OPTIONS? Output each SQL statement as it is run",
4092 " FILE Send output to FILE",
4093 " stdout Send output to stdout",
4094 " stderr Send output to stderr",
4095 " off Disable tracing",
4096 " --expanded Expand query parameters",
4097 #ifdef SQLITE_ENABLE_NORMALIZE
4098 " --normalized Normal the SQL statements",
4099 #endif
4100 " --plain Show SQL as it is input",
4101 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4102 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4103 " --row Trace each row (SQLITE_TRACE_ROW)",
4104 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4105 #endif /* SQLITE_OMIT_TRACE */
4106 #ifdef SQLITE_DEBUG
4107 ".unmodule NAME ... Unregister virtual table modules",
4108 " --allexcept Unregister everything except those named",
4109 #endif
4110 ".vfsinfo ?AUX? Information about the top-level VFS",
4111 ".vfslist List all available VFSes",
4112 ".vfsname ?AUX? Print the name of the VFS stack",
4113 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4114 " Negative values right-justify",
4118 ** Output help text.
4120 ** zPattern describes the set of commands for which help text is provided.
4121 ** If zPattern is NULL, then show all commands, but only give a one-line
4122 ** description of each.
4124 ** Return the number of matches.
4126 static int showHelp(FILE *out, const char *zPattern){
4127 int i = 0;
4128 int j = 0;
4129 int n = 0;
4130 char *zPat;
4131 if( zPattern==0
4132 || zPattern[0]=='0'
4133 || strcmp(zPattern,"-a")==0
4134 || strcmp(zPattern,"-all")==0
4135 || strcmp(zPattern,"--all")==0
4137 /* Show all commands, but only one line per command */
4138 if( zPattern==0 ) zPattern = "";
4139 for(i=0; i<ArraySize(azHelp); i++){
4140 if( azHelp[i][0]=='.' || zPattern[0] ){
4141 utf8_printf(out, "%s\n", azHelp[i]);
4142 n++;
4145 }else{
4146 /* Look for commands that for which zPattern is an exact prefix */
4147 zPat = sqlite3_mprintf(".%s*", zPattern);
4148 for(i=0; i<ArraySize(azHelp); i++){
4149 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4150 utf8_printf(out, "%s\n", azHelp[i]);
4151 j = i+1;
4152 n++;
4155 sqlite3_free(zPat);
4156 if( n ){
4157 if( n==1 ){
4158 /* when zPattern is a prefix of exactly one command, then include the
4159 ** details of that command, which should begin at offset j */
4160 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4161 utf8_printf(out, "%s\n", azHelp[j]);
4162 j++;
4165 return n;
4167 /* Look for commands that contain zPattern anywhere. Show the complete
4168 ** text of all commands that match. */
4169 zPat = sqlite3_mprintf("%%%s%%", zPattern);
4170 for(i=0; i<ArraySize(azHelp); i++){
4171 if( azHelp[i][0]=='.' ) j = i;
4172 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4173 utf8_printf(out, "%s\n", azHelp[j]);
4174 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4175 j++;
4176 utf8_printf(out, "%s\n", azHelp[j]);
4178 i = j;
4179 n++;
4182 sqlite3_free(zPat);
4184 return n;
4187 /* Forward reference */
4188 static int process_input(ShellState *p);
4191 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
4192 ** and return a pointer to the buffer. The caller is responsible for freeing
4193 ** the memory.
4195 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4196 ** read.
4198 ** For convenience, a nul-terminator byte is always appended to the data read
4199 ** from the file before the buffer is returned. This byte is not included in
4200 ** the final value of (*pnByte), if applicable.
4202 ** NULL is returned if any error is encountered. The final value of *pnByte
4203 ** is undefined in this case.
4205 static char *readFile(const char *zName, int *pnByte){
4206 FILE *in = fopen(zName, "rb");
4207 long nIn;
4208 size_t nRead;
4209 char *pBuf;
4210 if( in==0 ) return 0;
4211 fseek(in, 0, SEEK_END);
4212 nIn = ftell(in);
4213 rewind(in);
4214 pBuf = sqlite3_malloc64( nIn+1 );
4215 if( pBuf==0 ){ fclose(in); return 0; }
4216 nRead = fread(pBuf, nIn, 1, in);
4217 fclose(in);
4218 if( nRead!=1 ){
4219 sqlite3_free(pBuf);
4220 return 0;
4222 pBuf[nIn] = 0;
4223 if( pnByte ) *pnByte = nIn;
4224 return pBuf;
4227 #if defined(SQLITE_ENABLE_SESSION)
4229 ** Close a single OpenSession object and release all of its associated
4230 ** resources.
4232 static void session_close(OpenSession *pSession){
4233 int i;
4234 sqlite3session_delete(pSession->p);
4235 sqlite3_free(pSession->zName);
4236 for(i=0; i<pSession->nFilter; i++){
4237 sqlite3_free(pSession->azFilter[i]);
4239 sqlite3_free(pSession->azFilter);
4240 memset(pSession, 0, sizeof(OpenSession));
4242 #endif
4245 ** Close all OpenSession objects and release all associated resources.
4247 #if defined(SQLITE_ENABLE_SESSION)
4248 static void session_close_all(ShellState *p){
4249 int i;
4250 for(i=0; i<p->nSession; i++){
4251 session_close(&p->aSession[i]);
4253 p->nSession = 0;
4255 #else
4256 # define session_close_all(X)
4257 #endif
4260 ** Implementation of the xFilter function for an open session. Omit
4261 ** any tables named by ".session filter" but let all other table through.
4263 #if defined(SQLITE_ENABLE_SESSION)
4264 static int session_filter(void *pCtx, const char *zTab){
4265 OpenSession *pSession = (OpenSession*)pCtx;
4266 int i;
4267 for(i=0; i<pSession->nFilter; i++){
4268 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4270 return 1;
4272 #endif
4275 ** Try to deduce the type of file for zName based on its content. Return
4276 ** one of the SHELL_OPEN_* constants.
4278 ** If the file does not exist or is empty but its name looks like a ZIP
4279 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4280 ** Otherwise, assume an ordinary database regardless of the filename if
4281 ** the type cannot be determined from content.
4283 int deduceDatabaseType(const char *zName, int dfltZip){
4284 FILE *f = fopen(zName, "rb");
4285 size_t n;
4286 int rc = SHELL_OPEN_UNSPEC;
4287 char zBuf[100];
4288 if( f==0 ){
4289 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4290 return SHELL_OPEN_ZIPFILE;
4291 }else{
4292 return SHELL_OPEN_NORMAL;
4295 n = fread(zBuf, 16, 1, f);
4296 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4297 fclose(f);
4298 return SHELL_OPEN_NORMAL;
4300 fseek(f, -25, SEEK_END);
4301 n = fread(zBuf, 25, 1, f);
4302 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4303 rc = SHELL_OPEN_APPENDVFS;
4304 }else{
4305 fseek(f, -22, SEEK_END);
4306 n = fread(zBuf, 22, 1, f);
4307 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4308 && zBuf[3]==0x06 ){
4309 rc = SHELL_OPEN_ZIPFILE;
4310 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4311 rc = SHELL_OPEN_ZIPFILE;
4314 fclose(f);
4315 return rc;
4318 #ifndef SQLITE_OMIT_DESERIALIZE
4320 ** Reconstruct an in-memory database using the output from the "dbtotxt"
4321 ** program. Read content from the file in p->zDbFilename. If p->zDbFilename
4322 ** is 0, then read from standard input.
4324 static unsigned char *readHexDb(ShellState *p, int *pnData){
4325 unsigned char *a = 0;
4326 int nLine;
4327 int n = 0;
4328 int pgsz = 0;
4329 int iOffset = 0;
4330 int j, k;
4331 int rc;
4332 FILE *in;
4333 unsigned int x[16];
4334 char zLine[1000];
4335 if( p->zDbFilename ){
4336 in = fopen(p->zDbFilename, "r");
4337 if( in==0 ){
4338 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
4339 return 0;
4341 nLine = 0;
4342 }else{
4343 in = p->in;
4344 nLine = p->lineno;
4345 if( in==0 ) in = stdin;
4347 *pnData = 0;
4348 nLine++;
4349 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4350 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4351 if( rc!=2 ) goto readHexDb_error;
4352 if( n<0 ) goto readHexDb_error;
4353 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4354 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
4355 a = sqlite3_malloc( n ? n : 1 );
4356 if( a==0 ){
4357 utf8_printf(stderr, "Out of memory!\n");
4358 goto readHexDb_error;
4360 memset(a, 0, n);
4361 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4362 utf8_printf(stderr, "invalid pagesize\n");
4363 goto readHexDb_error;
4365 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4366 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4367 if( rc==2 ){
4368 iOffset = k;
4369 continue;
4371 if( strncmp(zLine, "| end ", 6)==0 ){
4372 break;
4374 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4375 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4376 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4377 if( rc==17 ){
4378 k = iOffset+j;
4379 if( k+16<=n ){
4380 int ii;
4381 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4385 *pnData = n;
4386 if( in!=p->in ){
4387 fclose(in);
4388 }else{
4389 p->lineno = nLine;
4391 return a;
4393 readHexDb_error:
4394 if( in!=p->in ){
4395 fclose(in);
4396 }else{
4397 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4398 nLine++;
4399 if(strncmp(zLine, "| end ", 6)==0 ) break;
4401 p->lineno = nLine;
4403 sqlite3_free(a);
4404 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4405 return 0;
4407 #endif /* SQLITE_OMIT_DESERIALIZE */
4410 ** Scalar function "shell_int32". The first argument to this function
4411 ** must be a blob. The second a non-negative integer. This function
4412 ** reads and returns a 32-bit big-endian integer from byte
4413 ** offset (4*<arg2>) of the blob.
4415 static void shellInt32(
4416 sqlite3_context *context,
4417 int argc,
4418 sqlite3_value **argv
4420 const unsigned char *pBlob;
4421 int nBlob;
4422 int iInt;
4424 UNUSED_PARAMETER(argc);
4425 nBlob = sqlite3_value_bytes(argv[0]);
4426 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4427 iInt = sqlite3_value_int(argv[1]);
4429 if( iInt>=0 && (iInt+1)*4<=nBlob ){
4430 const unsigned char *a = &pBlob[iInt*4];
4431 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4432 + ((sqlite3_int64)a[1]<<16)
4433 + ((sqlite3_int64)a[2]<< 8)
4434 + ((sqlite3_int64)a[3]<< 0);
4435 sqlite3_result_int64(context, iVal);
4440 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4441 ** using "..." with internal double-quote characters doubled.
4443 static void shellIdQuote(
4444 sqlite3_context *context,
4445 int argc,
4446 sqlite3_value **argv
4448 const char *zName = (const char*)sqlite3_value_text(argv[0]);
4449 UNUSED_PARAMETER(argc);
4450 if( zName ){
4451 char *z = sqlite3_mprintf("\"%w\"", zName);
4452 sqlite3_result_text(context, z, -1, sqlite3_free);
4457 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4459 static void shellUSleepFunc(
4460 sqlite3_context *context,
4461 int argcUnused,
4462 sqlite3_value **argv
4464 int sleep = sqlite3_value_int(argv[0]);
4465 (void)argcUnused;
4466 sqlite3_sleep(sleep/1000);
4467 sqlite3_result_int(context, sleep);
4471 ** Scalar function "shell_escape_crnl" used by the .recover command.
4472 ** The argument passed to this function is the output of built-in
4473 ** function quote(). If the first character of the input is "'",
4474 ** indicating that the value passed to quote() was a text value,
4475 ** then this function searches the input for "\n" and "\r" characters
4476 ** and adds a wrapper similar to the following:
4478 ** replace(replace(<input>, '\n', char(10), '\r', char(13));
4480 ** Or, if the first character of the input is not "'", then a copy
4481 ** of the input is returned.
4483 static void shellEscapeCrnl(
4484 sqlite3_context *context,
4485 int argc,
4486 sqlite3_value **argv
4488 const char *zText = (const char*)sqlite3_value_text(argv[0]);
4489 UNUSED_PARAMETER(argc);
4490 if( zText[0]=='\'' ){
4491 int nText = sqlite3_value_bytes(argv[0]);
4492 int i;
4493 char zBuf1[20];
4494 char zBuf2[20];
4495 const char *zNL = 0;
4496 const char *zCR = 0;
4497 int nCR = 0;
4498 int nNL = 0;
4500 for(i=0; zText[i]; i++){
4501 if( zNL==0 && zText[i]=='\n' ){
4502 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4503 nNL = (int)strlen(zNL);
4505 if( zCR==0 && zText[i]=='\r' ){
4506 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4507 nCR = (int)strlen(zCR);
4511 if( zNL || zCR ){
4512 int iOut = 0;
4513 i64 nMax = (nNL > nCR) ? nNL : nCR;
4514 i64 nAlloc = nMax * nText + (nMax+64)*2;
4515 char *zOut = (char*)sqlite3_malloc64(nAlloc);
4516 if( zOut==0 ){
4517 sqlite3_result_error_nomem(context);
4518 return;
4521 if( zNL && zCR ){
4522 memcpy(&zOut[iOut], "replace(replace(", 16);
4523 iOut += 16;
4524 }else{
4525 memcpy(&zOut[iOut], "replace(", 8);
4526 iOut += 8;
4528 for(i=0; zText[i]; i++){
4529 if( zText[i]=='\n' ){
4530 memcpy(&zOut[iOut], zNL, nNL);
4531 iOut += nNL;
4532 }else if( zText[i]=='\r' ){
4533 memcpy(&zOut[iOut], zCR, nCR);
4534 iOut += nCR;
4535 }else{
4536 zOut[iOut] = zText[i];
4537 iOut++;
4541 if( zNL ){
4542 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4543 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4544 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4546 if( zCR ){
4547 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4548 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4549 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4552 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4553 sqlite3_free(zOut);
4554 return;
4558 sqlite3_result_value(context, argv[0]);
4561 /* Flags for open_db().
4563 ** The default behavior of open_db() is to exit(1) if the database fails to
4564 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4565 ** but still returns without calling exit.
4567 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4568 ** ZIP archive if the file does not exist or is empty and its name matches
4569 ** the *.zip pattern.
4571 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
4572 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
4575 ** Make sure the database is open. If it is not, then open it. If
4576 ** the database fails to open, print an error message and exit.
4578 static void open_db(ShellState *p, int openFlags){
4579 if( p->db==0 ){
4580 if( p->openMode==SHELL_OPEN_UNSPEC ){
4581 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4582 p->openMode = SHELL_OPEN_NORMAL;
4583 }else{
4584 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4585 (openFlags & OPEN_DB_ZIPFILE)!=0);
4588 switch( p->openMode ){
4589 case SHELL_OPEN_APPENDVFS: {
4590 sqlite3_open_v2(p->zDbFilename, &p->db,
4591 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4592 break;
4594 case SHELL_OPEN_HEXDB:
4595 case SHELL_OPEN_DESERIALIZE: {
4596 sqlite3_open(0, &p->db);
4597 break;
4599 case SHELL_OPEN_ZIPFILE: {
4600 sqlite3_open(":memory:", &p->db);
4601 break;
4603 case SHELL_OPEN_READONLY: {
4604 sqlite3_open_v2(p->zDbFilename, &p->db,
4605 SQLITE_OPEN_READONLY|p->openFlags, 0);
4606 break;
4608 case SHELL_OPEN_UNSPEC:
4609 case SHELL_OPEN_NORMAL: {
4610 sqlite3_open_v2(p->zDbFilename, &p->db,
4611 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4612 break;
4615 globalDb = p->db;
4616 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4617 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4618 p->zDbFilename, sqlite3_errmsg(p->db));
4619 if( openFlags & OPEN_DB_KEEPALIVE ){
4620 sqlite3_open(":memory:", &p->db);
4621 return;
4623 exit(1);
4625 #ifndef SQLITE_OMIT_LOAD_EXTENSION
4626 sqlite3_enable_load_extension(p->db, 1);
4627 #endif
4628 sqlite3_fileio_init(p->db, 0, 0);
4629 sqlite3_shathree_init(p->db, 0, 0);
4630 sqlite3_completion_init(p->db, 0, 0);
4631 sqlite3_uint_init(p->db, 0, 0);
4632 sqlite3_decimal_init(p->db, 0, 0);
4633 sqlite3_regexp_init(p->db, 0, 0);
4634 sqlite3_ieee_init(p->db, 0, 0);
4635 sqlite3_series_init(p->db, 0, 0);
4636 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4637 sqlite3_dbdata_init(p->db, 0, 0);
4638 #endif
4639 #ifdef SQLITE_HAVE_ZLIB
4640 sqlite3_zipfile_init(p->db, 0, 0);
4641 sqlite3_sqlar_init(p->db, 0, 0);
4642 #endif
4643 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4644 shellAddSchemaName, 0, 0);
4645 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4646 shellModuleSchema, 0, 0);
4647 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4648 shellPutsFunc, 0, 0);
4649 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4650 shellEscapeCrnl, 0, 0);
4651 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4652 shellInt32, 0, 0);
4653 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4654 shellIdQuote, 0, 0);
4655 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
4656 shellUSleepFunc, 0, 0);
4657 #ifndef SQLITE_NOHAVE_SYSTEM
4658 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4659 editFunc, 0, 0);
4660 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4661 editFunc, 0, 0);
4662 #endif
4663 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4664 char *zSql = sqlite3_mprintf(
4665 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4666 sqlite3_exec(p->db, zSql, 0, 0, 0);
4667 sqlite3_free(zSql);
4669 #ifndef SQLITE_OMIT_DESERIALIZE
4670 else
4671 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4672 int rc;
4673 int nData = 0;
4674 unsigned char *aData;
4675 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4676 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4677 }else{
4678 aData = readHexDb(p, &nData);
4679 if( aData==0 ){
4680 return;
4683 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4684 SQLITE_DESERIALIZE_RESIZEABLE |
4685 SQLITE_DESERIALIZE_FREEONCLOSE);
4686 if( rc ){
4687 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4689 if( p->szMax>0 ){
4690 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4693 #endif
4698 ** Attempt to close the databaes connection. Report errors.
4700 void close_db(sqlite3 *db){
4701 int rc = sqlite3_close(db);
4702 if( rc ){
4703 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4704 rc, sqlite3_errmsg(db));
4708 #if HAVE_READLINE || HAVE_EDITLINE
4710 ** Readline completion callbacks
4712 static char *readline_completion_generator(const char *text, int state){
4713 static sqlite3_stmt *pStmt = 0;
4714 char *zRet;
4715 if( state==0 ){
4716 char *zSql;
4717 sqlite3_finalize(pStmt);
4718 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4719 " FROM completion(%Q) ORDER BY 1", text);
4720 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4721 sqlite3_free(zSql);
4723 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4724 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4725 }else{
4726 sqlite3_finalize(pStmt);
4727 pStmt = 0;
4728 zRet = 0;
4730 return zRet;
4732 static char **readline_completion(const char *zText, int iStart, int iEnd){
4733 rl_attempted_completion_over = 1;
4734 return rl_completion_matches(zText, readline_completion_generator);
4737 #elif HAVE_LINENOISE
4739 ** Linenoise completion callback
4741 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4742 int nLine = strlen30(zLine);
4743 int i, iStart;
4744 sqlite3_stmt *pStmt = 0;
4745 char *zSql;
4746 char zBuf[1000];
4748 if( nLine>sizeof(zBuf)-30 ) return;
4749 if( zLine[0]=='.' || zLine[0]=='#') return;
4750 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4751 if( i==nLine-1 ) return;
4752 iStart = i+1;
4753 memcpy(zBuf, zLine, iStart);
4754 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4755 " FROM completion(%Q,%Q) ORDER BY 1",
4756 &zLine[iStart], zLine);
4757 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4758 sqlite3_free(zSql);
4759 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4760 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4761 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4762 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4763 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4764 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4765 linenoiseAddCompletion(lc, zBuf);
4768 sqlite3_finalize(pStmt);
4770 #endif
4773 ** Do C-language style dequoting.
4775 ** \a -> alarm
4776 ** \b -> backspace
4777 ** \t -> tab
4778 ** \n -> newline
4779 ** \v -> vertical tab
4780 ** \f -> form feed
4781 ** \r -> carriage return
4782 ** \s -> space
4783 ** \" -> "
4784 ** \' -> '
4785 ** \\ -> backslash
4786 ** \NNN -> ascii character NNN in octal
4788 static void resolve_backslashes(char *z){
4789 int i, j;
4790 char c;
4791 while( *z && *z!='\\' ) z++;
4792 for(i=j=0; (c = z[i])!=0; i++, j++){
4793 if( c=='\\' && z[i+1]!=0 ){
4794 c = z[++i];
4795 if( c=='a' ){
4796 c = '\a';
4797 }else if( c=='b' ){
4798 c = '\b';
4799 }else if( c=='t' ){
4800 c = '\t';
4801 }else if( c=='n' ){
4802 c = '\n';
4803 }else if( c=='v' ){
4804 c = '\v';
4805 }else if( c=='f' ){
4806 c = '\f';
4807 }else if( c=='r' ){
4808 c = '\r';
4809 }else if( c=='"' ){
4810 c = '"';
4811 }else if( c=='\'' ){
4812 c = '\'';
4813 }else if( c=='\\' ){
4814 c = '\\';
4815 }else if( c>='0' && c<='7' ){
4816 c -= '0';
4817 if( z[i+1]>='0' && z[i+1]<='7' ){
4818 i++;
4819 c = (c<<3) + z[i] - '0';
4820 if( z[i+1]>='0' && z[i+1]<='7' ){
4821 i++;
4822 c = (c<<3) + z[i] - '0';
4827 z[j] = c;
4829 if( j<i ) z[j] = 0;
4833 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4834 ** for TRUE and FALSE. Return the integer value if appropriate.
4836 static int booleanValue(const char *zArg){
4837 int i;
4838 if( zArg[0]=='0' && zArg[1]=='x' ){
4839 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4840 }else{
4841 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4843 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4844 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4845 return 1;
4847 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4848 return 0;
4850 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4851 zArg);
4852 return 0;
4856 ** Set or clear a shell flag according to a boolean value.
4858 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4859 if( booleanValue(zArg) ){
4860 ShellSetFlag(p, mFlag);
4861 }else{
4862 ShellClearFlag(p, mFlag);
4867 ** Close an output file, assuming it is not stderr or stdout
4869 static void output_file_close(FILE *f){
4870 if( f && f!=stdout && f!=stderr ) fclose(f);
4874 ** Try to open an output file. The names "stdout" and "stderr" are
4875 ** recognized and do the right thing. NULL is returned if the output
4876 ** filename is "off".
4878 static FILE *output_file_open(const char *zFile, int bTextMode){
4879 FILE *f;
4880 if( strcmp(zFile,"stdout")==0 ){
4881 f = stdout;
4882 }else if( strcmp(zFile, "stderr")==0 ){
4883 f = stderr;
4884 }else if( strcmp(zFile, "off")==0 ){
4885 f = 0;
4886 }else{
4887 f = fopen(zFile, bTextMode ? "w" : "wb");
4888 if( f==0 ){
4889 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4892 return f;
4895 #ifndef SQLITE_OMIT_TRACE
4897 ** A routine for handling output from sqlite3_trace().
4899 static int sql_trace_callback(
4900 unsigned mType, /* The trace type */
4901 void *pArg, /* The ShellState pointer */
4902 void *pP, /* Usually a pointer to sqlite_stmt */
4903 void *pX /* Auxiliary output */
4905 ShellState *p = (ShellState*)pArg;
4906 sqlite3_stmt *pStmt;
4907 const char *zSql;
4908 int nSql;
4909 if( p->traceOut==0 ) return 0;
4910 if( mType==SQLITE_TRACE_CLOSE ){
4911 utf8_printf(p->traceOut, "-- closing database connection\n");
4912 return 0;
4914 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4915 zSql = (const char*)pX;
4916 }else{
4917 pStmt = (sqlite3_stmt*)pP;
4918 switch( p->eTraceType ){
4919 case SHELL_TRACE_EXPANDED: {
4920 zSql = sqlite3_expanded_sql(pStmt);
4921 break;
4923 #ifdef SQLITE_ENABLE_NORMALIZE
4924 case SHELL_TRACE_NORMALIZED: {
4925 zSql = sqlite3_normalized_sql(pStmt);
4926 break;
4928 #endif
4929 default: {
4930 zSql = sqlite3_sql(pStmt);
4931 break;
4935 if( zSql==0 ) return 0;
4936 nSql = strlen30(zSql);
4937 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4938 switch( mType ){
4939 case SQLITE_TRACE_ROW:
4940 case SQLITE_TRACE_STMT: {
4941 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4942 break;
4944 case SQLITE_TRACE_PROFILE: {
4945 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4946 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4947 break;
4950 return 0;
4952 #endif
4955 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
4956 ** a useful spot to set a debugger breakpoint.
4958 static void test_breakpoint(void){
4959 static int nCall = 0;
4960 nCall++;
4964 ** An object used to read a CSV and other files for import.
4966 typedef struct ImportCtx ImportCtx;
4967 struct ImportCtx {
4968 const char *zFile; /* Name of the input file */
4969 FILE *in; /* Read the CSV text from this input stream */
4970 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
4971 char *z; /* Accumulated text for a field */
4972 int n; /* Number of bytes in z */
4973 int nAlloc; /* Space allocated for z[] */
4974 int nLine; /* Current line number */
4975 int nRow; /* Number of rows imported */
4976 int nErr; /* Number of errors encountered */
4977 int bNotFirst; /* True if one or more bytes already read */
4978 int cTerm; /* Character that terminated the most recent field */
4979 int cColSep; /* The column separator character. (Usually ",") */
4980 int cRowSep; /* The row separator character. (Usually "\n") */
4983 /* Clean up resourced used by an ImportCtx */
4984 static void import_cleanup(ImportCtx *p){
4985 if( p->in!=0 && p->xCloser!=0 ){
4986 p->xCloser(p->in);
4987 p->in = 0;
4989 sqlite3_free(p->z);
4990 p->z = 0;
4993 /* Append a single byte to z[] */
4994 static void import_append_char(ImportCtx *p, int c){
4995 if( p->n+1>=p->nAlloc ){
4996 p->nAlloc += p->nAlloc + 100;
4997 p->z = sqlite3_realloc64(p->z, p->nAlloc);
4998 if( p->z==0 ) shell_out_of_memory();
5000 p->z[p->n++] = (char)c;
5003 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5004 ** with the option of having a separator other than ",".
5006 ** + Input comes from p->in.
5007 ** + Store results in p->z of length p->n. Space to hold p->z comes
5008 ** from sqlite3_malloc64().
5009 ** + Use p->cSep as the column separator. The default is ",".
5010 ** + Use p->rSep as the row separator. The default is "\n".
5011 ** + Keep track of the line number in p->nLine.
5012 ** + Store the character that terminates the field in p->cTerm. Store
5013 ** EOF on end-of-file.
5014 ** + Report syntax errors on stderr
5016 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5017 int c;
5018 int cSep = p->cColSep;
5019 int rSep = p->cRowSep;
5020 p->n = 0;
5021 c = fgetc(p->in);
5022 if( c==EOF || seenInterrupt ){
5023 p->cTerm = EOF;
5024 return 0;
5026 if( c=='"' ){
5027 int pc, ppc;
5028 int startLine = p->nLine;
5029 int cQuote = c;
5030 pc = ppc = 0;
5031 while( 1 ){
5032 c = fgetc(p->in);
5033 if( c==rSep ) p->nLine++;
5034 if( c==cQuote ){
5035 if( pc==cQuote ){
5036 pc = 0;
5037 continue;
5040 if( (c==cSep && pc==cQuote)
5041 || (c==rSep && pc==cQuote)
5042 || (c==rSep && pc=='\r' && ppc==cQuote)
5043 || (c==EOF && pc==cQuote)
5045 do{ p->n--; }while( p->z[p->n]!=cQuote );
5046 p->cTerm = c;
5047 break;
5049 if( pc==cQuote && c!='\r' ){
5050 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5051 p->zFile, p->nLine, cQuote);
5053 if( c==EOF ){
5054 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5055 p->zFile, startLine, cQuote);
5056 p->cTerm = c;
5057 break;
5059 import_append_char(p, c);
5060 ppc = pc;
5061 pc = c;
5063 }else{
5064 /* If this is the first field being parsed and it begins with the
5065 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5066 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5067 import_append_char(p, c);
5068 c = fgetc(p->in);
5069 if( (c&0xff)==0xbb ){
5070 import_append_char(p, c);
5071 c = fgetc(p->in);
5072 if( (c&0xff)==0xbf ){
5073 p->bNotFirst = 1;
5074 p->n = 0;
5075 return csv_read_one_field(p);
5079 while( c!=EOF && c!=cSep && c!=rSep ){
5080 import_append_char(p, c);
5081 c = fgetc(p->in);
5083 if( c==rSep ){
5084 p->nLine++;
5085 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5087 p->cTerm = c;
5089 if( p->z ) p->z[p->n] = 0;
5090 p->bNotFirst = 1;
5091 return p->z;
5094 /* Read a single field of ASCII delimited text.
5096 ** + Input comes from p->in.
5097 ** + Store results in p->z of length p->n. Space to hold p->z comes
5098 ** from sqlite3_malloc64().
5099 ** + Use p->cSep as the column separator. The default is "\x1F".
5100 ** + Use p->rSep as the row separator. The default is "\x1E".
5101 ** + Keep track of the row number in p->nLine.
5102 ** + Store the character that terminates the field in p->cTerm. Store
5103 ** EOF on end-of-file.
5104 ** + Report syntax errors on stderr
5106 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5107 int c;
5108 int cSep = p->cColSep;
5109 int rSep = p->cRowSep;
5110 p->n = 0;
5111 c = fgetc(p->in);
5112 if( c==EOF || seenInterrupt ){
5113 p->cTerm = EOF;
5114 return 0;
5116 while( c!=EOF && c!=cSep && c!=rSep ){
5117 import_append_char(p, c);
5118 c = fgetc(p->in);
5120 if( c==rSep ){
5121 p->nLine++;
5123 p->cTerm = c;
5124 if( p->z ) p->z[p->n] = 0;
5125 return p->z;
5129 ** Try to transfer data for table zTable. If an error is seen while
5130 ** moving forward, try to go backwards. The backwards movement won't
5131 ** work for WITHOUT ROWID tables.
5133 static void tryToCloneData(
5134 ShellState *p,
5135 sqlite3 *newDb,
5136 const char *zTable
5138 sqlite3_stmt *pQuery = 0;
5139 sqlite3_stmt *pInsert = 0;
5140 char *zQuery = 0;
5141 char *zInsert = 0;
5142 int rc;
5143 int i, j, n;
5144 int nTable = strlen30(zTable);
5145 int k = 0;
5146 int cnt = 0;
5147 const int spinRate = 10000;
5149 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5150 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5151 if( rc ){
5152 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5153 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5154 zQuery);
5155 goto end_data_xfer;
5157 n = sqlite3_column_count(pQuery);
5158 zInsert = sqlite3_malloc64(200 + nTable + n*3);
5159 if( zInsert==0 ) shell_out_of_memory();
5160 sqlite3_snprintf(200+nTable,zInsert,
5161 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5162 i = strlen30(zInsert);
5163 for(j=1; j<n; j++){
5164 memcpy(zInsert+i, ",?", 2);
5165 i += 2;
5167 memcpy(zInsert+i, ");", 3);
5168 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5169 if( rc ){
5170 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5171 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5172 zQuery);
5173 goto end_data_xfer;
5175 for(k=0; k<2; k++){
5176 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5177 for(i=0; i<n; i++){
5178 switch( sqlite3_column_type(pQuery, i) ){
5179 case SQLITE_NULL: {
5180 sqlite3_bind_null(pInsert, i+1);
5181 break;
5183 case SQLITE_INTEGER: {
5184 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5185 break;
5187 case SQLITE_FLOAT: {
5188 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5189 break;
5191 case SQLITE_TEXT: {
5192 sqlite3_bind_text(pInsert, i+1,
5193 (const char*)sqlite3_column_text(pQuery,i),
5194 -1, SQLITE_STATIC);
5195 break;
5197 case SQLITE_BLOB: {
5198 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5199 sqlite3_column_bytes(pQuery,i),
5200 SQLITE_STATIC);
5201 break;
5204 } /* End for */
5205 rc = sqlite3_step(pInsert);
5206 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5207 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5208 sqlite3_errmsg(newDb));
5210 sqlite3_reset(pInsert);
5211 cnt++;
5212 if( (cnt%spinRate)==0 ){
5213 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5214 fflush(stdout);
5216 } /* End while */
5217 if( rc==SQLITE_DONE ) break;
5218 sqlite3_finalize(pQuery);
5219 sqlite3_free(zQuery);
5220 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5221 zTable);
5222 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5223 if( rc ){
5224 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5225 break;
5227 } /* End for(k=0...) */
5229 end_data_xfer:
5230 sqlite3_finalize(pQuery);
5231 sqlite3_finalize(pInsert);
5232 sqlite3_free(zQuery);
5233 sqlite3_free(zInsert);
5238 ** Try to transfer all rows of the schema that match zWhere. For
5239 ** each row, invoke xForEach() on the object defined by that row.
5240 ** If an error is encountered while moving forward through the
5241 ** sqlite_schema table, try again moving backwards.
5243 static void tryToCloneSchema(
5244 ShellState *p,
5245 sqlite3 *newDb,
5246 const char *zWhere,
5247 void (*xForEach)(ShellState*,sqlite3*,const char*)
5249 sqlite3_stmt *pQuery = 0;
5250 char *zQuery = 0;
5251 int rc;
5252 const unsigned char *zName;
5253 const unsigned char *zSql;
5254 char *zErrMsg = 0;
5256 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5257 " WHERE %s", zWhere);
5258 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5259 if( rc ){
5260 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5261 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5262 zQuery);
5263 goto end_schema_xfer;
5265 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5266 zName = sqlite3_column_text(pQuery, 0);
5267 zSql = sqlite3_column_text(pQuery, 1);
5268 printf("%s... ", zName); fflush(stdout);
5269 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5270 if( zErrMsg ){
5271 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5272 sqlite3_free(zErrMsg);
5273 zErrMsg = 0;
5275 if( xForEach ){
5276 xForEach(p, newDb, (const char*)zName);
5278 printf("done\n");
5280 if( rc!=SQLITE_DONE ){
5281 sqlite3_finalize(pQuery);
5282 sqlite3_free(zQuery);
5283 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5284 " WHERE %s ORDER BY rowid DESC", zWhere);
5285 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5286 if( rc ){
5287 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5288 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5289 zQuery);
5290 goto end_schema_xfer;
5292 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5293 zName = sqlite3_column_text(pQuery, 0);
5294 zSql = sqlite3_column_text(pQuery, 1);
5295 printf("%s... ", zName); fflush(stdout);
5296 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5297 if( zErrMsg ){
5298 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5299 sqlite3_free(zErrMsg);
5300 zErrMsg = 0;
5302 if( xForEach ){
5303 xForEach(p, newDb, (const char*)zName);
5305 printf("done\n");
5308 end_schema_xfer:
5309 sqlite3_finalize(pQuery);
5310 sqlite3_free(zQuery);
5314 ** Open a new database file named "zNewDb". Try to recover as much information
5315 ** as possible out of the main database (which might be corrupt) and write it
5316 ** into zNewDb.
5318 static void tryToClone(ShellState *p, const char *zNewDb){
5319 int rc;
5320 sqlite3 *newDb = 0;
5321 if( access(zNewDb,0)==0 ){
5322 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5323 return;
5325 rc = sqlite3_open(zNewDb, &newDb);
5326 if( rc ){
5327 utf8_printf(stderr, "Cannot create output database: %s\n",
5328 sqlite3_errmsg(newDb));
5329 }else{
5330 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5331 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5332 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5333 tryToCloneSchema(p, newDb, "type!='table'", 0);
5334 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5335 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5337 close_db(newDb);
5341 ** Change the output file back to stdout.
5343 ** If the p->doXdgOpen flag is set, that means the output was being
5344 ** redirected to a temporary file named by p->zTempFile. In that case,
5345 ** launch start/open/xdg-open on that temporary file.
5347 static void output_reset(ShellState *p){
5348 if( p->outfile[0]=='|' ){
5349 #ifndef SQLITE_OMIT_POPEN
5350 pclose(p->out);
5351 #endif
5352 }else{
5353 output_file_close(p->out);
5354 #ifndef SQLITE_NOHAVE_SYSTEM
5355 if( p->doXdgOpen ){
5356 const char *zXdgOpenCmd =
5357 #if defined(_WIN32)
5358 "start";
5359 #elif defined(__APPLE__)
5360 "open";
5361 #else
5362 "xdg-open";
5363 #endif
5364 char *zCmd;
5365 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5366 if( system(zCmd) ){
5367 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5368 }else{
5369 /* Give the start/open/xdg-open command some time to get
5370 ** going before we continue, and potential delete the
5371 ** p->zTempFile data file out from under it */
5372 sqlite3_sleep(2000);
5374 sqlite3_free(zCmd);
5375 outputModePop(p);
5376 p->doXdgOpen = 0;
5378 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5380 p->outfile[0] = 0;
5381 p->out = stdout;
5385 ** Run an SQL command and return the single integer result.
5387 static int db_int(ShellState *p, const char *zSql){
5388 sqlite3_stmt *pStmt;
5389 int res = 0;
5390 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5391 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5392 res = sqlite3_column_int(pStmt,0);
5394 sqlite3_finalize(pStmt);
5395 return res;
5399 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
5401 static unsigned int get2byteInt(unsigned char *a){
5402 return (a[0]<<8) + a[1];
5404 static unsigned int get4byteInt(unsigned char *a){
5405 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5409 ** Implementation of the ".dbinfo" command.
5411 ** Return 1 on error, 2 to exit, and 0 otherwise.
5413 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5414 static const struct { const char *zName; int ofst; } aField[] = {
5415 { "file change counter:", 24 },
5416 { "database page count:", 28 },
5417 { "freelist page count:", 36 },
5418 { "schema cookie:", 40 },
5419 { "schema format:", 44 },
5420 { "default cache size:", 48 },
5421 { "autovacuum top root:", 52 },
5422 { "incremental vacuum:", 64 },
5423 { "text encoding:", 56 },
5424 { "user version:", 60 },
5425 { "application id:", 68 },
5426 { "software version:", 96 },
5428 static const struct { const char *zName; const char *zSql; } aQuery[] = {
5429 { "number of tables:",
5430 "SELECT count(*) FROM %s WHERE type='table'" },
5431 { "number of indexes:",
5432 "SELECT count(*) FROM %s WHERE type='index'" },
5433 { "number of triggers:",
5434 "SELECT count(*) FROM %s WHERE type='trigger'" },
5435 { "number of views:",
5436 "SELECT count(*) FROM %s WHERE type='view'" },
5437 { "schema size:",
5438 "SELECT total(length(sql)) FROM %s" },
5440 int i, rc;
5441 unsigned iDataVersion;
5442 char *zSchemaTab;
5443 char *zDb = nArg>=2 ? azArg[1] : "main";
5444 sqlite3_stmt *pStmt = 0;
5445 unsigned char aHdr[100];
5446 open_db(p, 0);
5447 if( p->db==0 ) return 1;
5448 rc = sqlite3_prepare_v2(p->db,
5449 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5450 -1, &pStmt, 0);
5451 if( rc ){
5452 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5453 sqlite3_finalize(pStmt);
5454 return 1;
5456 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5457 if( sqlite3_step(pStmt)==SQLITE_ROW
5458 && sqlite3_column_bytes(pStmt,0)>100
5460 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5461 sqlite3_finalize(pStmt);
5462 }else{
5463 raw_printf(stderr, "unable to read database header\n");
5464 sqlite3_finalize(pStmt);
5465 return 1;
5467 i = get2byteInt(aHdr+16);
5468 if( i==1 ) i = 65536;
5469 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5470 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5471 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5472 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5473 for(i=0; i<ArraySize(aField); i++){
5474 int ofst = aField[i].ofst;
5475 unsigned int val = get4byteInt(aHdr + ofst);
5476 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5477 switch( ofst ){
5478 case 56: {
5479 if( val==1 ) raw_printf(p->out, " (utf8)");
5480 if( val==2 ) raw_printf(p->out, " (utf16le)");
5481 if( val==3 ) raw_printf(p->out, " (utf16be)");
5484 raw_printf(p->out, "\n");
5486 if( zDb==0 ){
5487 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5488 }else if( strcmp(zDb,"temp")==0 ){
5489 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5490 }else{
5491 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5493 for(i=0; i<ArraySize(aQuery); i++){
5494 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5495 int val = db_int(p, zSql);
5496 sqlite3_free(zSql);
5497 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5499 sqlite3_free(zSchemaTab);
5500 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5501 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5502 return 0;
5506 ** Print the current sqlite3_errmsg() value to stderr and return 1.
5508 static int shellDatabaseError(sqlite3 *db){
5509 const char *zErr = sqlite3_errmsg(db);
5510 utf8_printf(stderr, "Error: %s\n", zErr);
5511 return 1;
5515 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
5516 ** if they match and FALSE (0) if they do not match.
5518 ** Globbing rules:
5520 ** '*' Matches any sequence of zero or more characters.
5522 ** '?' Matches exactly one character.
5524 ** [...] Matches one character from the enclosed list of
5525 ** characters.
5527 ** [^...] Matches one character not in the enclosed list.
5529 ** '#' Matches any sequence of one or more digits with an
5530 ** optional + or - sign in front
5532 ** ' ' Any span of whitespace matches any other span of
5533 ** whitespace.
5535 ** Extra whitespace at the end of z[] is ignored.
5537 static int testcase_glob(const char *zGlob, const char *z){
5538 int c, c2;
5539 int invert;
5540 int seen;
5542 while( (c = (*(zGlob++)))!=0 ){
5543 if( IsSpace(c) ){
5544 if( !IsSpace(*z) ) return 0;
5545 while( IsSpace(*zGlob) ) zGlob++;
5546 while( IsSpace(*z) ) z++;
5547 }else if( c=='*' ){
5548 while( (c=(*(zGlob++))) == '*' || c=='?' ){
5549 if( c=='?' && (*(z++))==0 ) return 0;
5551 if( c==0 ){
5552 return 1;
5553 }else if( c=='[' ){
5554 while( *z && testcase_glob(zGlob-1,z)==0 ){
5555 z++;
5557 return (*z)!=0;
5559 while( (c2 = (*(z++)))!=0 ){
5560 while( c2!=c ){
5561 c2 = *(z++);
5562 if( c2==0 ) return 0;
5564 if( testcase_glob(zGlob,z) ) return 1;
5566 return 0;
5567 }else if( c=='?' ){
5568 if( (*(z++))==0 ) return 0;
5569 }else if( c=='[' ){
5570 int prior_c = 0;
5571 seen = 0;
5572 invert = 0;
5573 c = *(z++);
5574 if( c==0 ) return 0;
5575 c2 = *(zGlob++);
5576 if( c2=='^' ){
5577 invert = 1;
5578 c2 = *(zGlob++);
5580 if( c2==']' ){
5581 if( c==']' ) seen = 1;
5582 c2 = *(zGlob++);
5584 while( c2 && c2!=']' ){
5585 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5586 c2 = *(zGlob++);
5587 if( c>=prior_c && c<=c2 ) seen = 1;
5588 prior_c = 0;
5589 }else{
5590 if( c==c2 ){
5591 seen = 1;
5593 prior_c = c2;
5595 c2 = *(zGlob++);
5597 if( c2==0 || (seen ^ invert)==0 ) return 0;
5598 }else if( c=='#' ){
5599 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5600 if( !IsDigit(z[0]) ) return 0;
5601 z++;
5602 while( IsDigit(z[0]) ){ z++; }
5603 }else{
5604 if( c!=(*(z++)) ) return 0;
5607 while( IsSpace(*z) ){ z++; }
5608 return *z==0;
5613 ** Compare the string as a command-line option with either one or two
5614 ** initial "-" characters.
5616 static int optionMatch(const char *zStr, const char *zOpt){
5617 if( zStr[0]!='-' ) return 0;
5618 zStr++;
5619 if( zStr[0]=='-' ) zStr++;
5620 return strcmp(zStr, zOpt)==0;
5624 ** Delete a file.
5626 int shellDeleteFile(const char *zFilename){
5627 int rc;
5628 #ifdef _WIN32
5629 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5630 rc = _wunlink(z);
5631 sqlite3_free(z);
5632 #else
5633 rc = unlink(zFilename);
5634 #endif
5635 return rc;
5639 ** Try to delete the temporary file (if there is one) and free the
5640 ** memory used to hold the name of the temp file.
5642 static void clearTempFile(ShellState *p){
5643 if( p->zTempFile==0 ) return;
5644 if( p->doXdgOpen ) return;
5645 if( shellDeleteFile(p->zTempFile) ) return;
5646 sqlite3_free(p->zTempFile);
5647 p->zTempFile = 0;
5651 ** Create a new temp file name with the given suffix.
5653 static void newTempFile(ShellState *p, const char *zSuffix){
5654 clearTempFile(p);
5655 sqlite3_free(p->zTempFile);
5656 p->zTempFile = 0;
5657 if( p->db ){
5658 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5660 if( p->zTempFile==0 ){
5661 /* If p->db is an in-memory database then the TEMPFILENAME file-control
5662 ** will not work and we will need to fallback to guessing */
5663 char *zTemp;
5664 sqlite3_uint64 r;
5665 sqlite3_randomness(sizeof(r), &r);
5666 zTemp = getenv("TEMP");
5667 if( zTemp==0 ) zTemp = getenv("TMP");
5668 if( zTemp==0 ){
5669 #ifdef _WIN32
5670 zTemp = "\\tmp";
5671 #else
5672 zTemp = "/tmp";
5673 #endif
5675 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
5676 }else{
5677 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5679 if( p->zTempFile==0 ){
5680 raw_printf(stderr, "out of memory\n");
5681 exit(1);
5687 ** The implementation of SQL scalar function fkey_collate_clause(), used
5688 ** by the ".lint fkey-indexes" command. This scalar function is always
5689 ** called with four arguments - the parent table name, the parent column name,
5690 ** the child table name and the child column name.
5692 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5694 ** If either of the named tables or columns do not exist, this function
5695 ** returns an empty string. An empty string is also returned if both tables
5696 ** and columns exist but have the same default collation sequence. Or,
5697 ** if both exist but the default collation sequences are different, this
5698 ** function returns the string " COLLATE <parent-collation>", where
5699 ** <parent-collation> is the default collation sequence of the parent column.
5701 static void shellFkeyCollateClause(
5702 sqlite3_context *pCtx,
5703 int nVal,
5704 sqlite3_value **apVal
5706 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5707 const char *zParent;
5708 const char *zParentCol;
5709 const char *zParentSeq;
5710 const char *zChild;
5711 const char *zChildCol;
5712 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5713 int rc;
5715 assert( nVal==4 );
5716 zParent = (const char*)sqlite3_value_text(apVal[0]);
5717 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5718 zChild = (const char*)sqlite3_value_text(apVal[2]);
5719 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5721 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5722 rc = sqlite3_table_column_metadata(
5723 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5725 if( rc==SQLITE_OK ){
5726 rc = sqlite3_table_column_metadata(
5727 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5731 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5732 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5733 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5734 sqlite3_free(z);
5740 ** The implementation of dot-command ".lint fkey-indexes".
5742 static int lintFkeyIndexes(
5743 ShellState *pState, /* Current shell tool state */
5744 char **azArg, /* Array of arguments passed to dot command */
5745 int nArg /* Number of entries in azArg[] */
5747 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5748 FILE *out = pState->out; /* Stream to write non-error output to */
5749 int bVerbose = 0; /* If -verbose is present */
5750 int bGroupByParent = 0; /* If -groupbyparent is present */
5751 int i; /* To iterate through azArg[] */
5752 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5753 int rc; /* Return code */
5754 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5757 ** This SELECT statement returns one row for each foreign key constraint
5758 ** in the schema of the main database. The column values are:
5760 ** 0. The text of an SQL statement similar to:
5762 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5764 ** This SELECT is similar to the one that the foreign keys implementation
5765 ** needs to run internally on child tables. If there is an index that can
5766 ** be used to optimize this query, then it can also be used by the FK
5767 ** implementation to optimize DELETE or UPDATE statements on the parent
5768 ** table.
5770 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5771 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5772 ** contains an index that can be used to optimize the query.
5774 ** 2. Human readable text that describes the child table and columns. e.g.
5776 ** "child_table(child_key1, child_key2)"
5778 ** 3. Human readable text that describes the parent table and columns. e.g.
5780 ** "parent_table(parent_key1, parent_key2)"
5782 ** 4. A full CREATE INDEX statement for an index that could be used to
5783 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5785 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5787 ** 5. The name of the parent table.
5789 ** These six values are used by the C logic below to generate the report.
5791 const char *zSql =
5792 "SELECT "
5793 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5794 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5795 " || fkey_collate_clause("
5796 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5797 ", "
5798 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
5799 " || group_concat('*=?', ' AND ') || ')'"
5800 ", "
5801 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5802 ", "
5803 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5804 ", "
5805 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5806 " || ' ON ' || quote(s.name) || '('"
5807 " || group_concat(quote(f.[from]) ||"
5808 " fkey_collate_clause("
5809 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5810 " || ');'"
5811 ", "
5812 " f.[table] "
5813 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
5814 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5815 "GROUP BY s.name, f.id "
5816 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5818 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
5820 for(i=2; i<nArg; i++){
5821 int n = strlen30(azArg[i]);
5822 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5823 bVerbose = 1;
5825 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5826 bGroupByParent = 1;
5827 zIndent = " ";
5829 else{
5830 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5831 azArg[0], azArg[1]
5833 return SQLITE_ERROR;
5837 /* Register the fkey_collate_clause() SQL function */
5838 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5839 0, shellFkeyCollateClause, 0, 0
5843 if( rc==SQLITE_OK ){
5844 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5846 if( rc==SQLITE_OK ){
5847 sqlite3_bind_int(pSql, 1, bGroupByParent);
5850 if( rc==SQLITE_OK ){
5851 int rc2;
5852 char *zPrev = 0;
5853 while( SQLITE_ROW==sqlite3_step(pSql) ){
5854 int res = -1;
5855 sqlite3_stmt *pExplain = 0;
5856 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5857 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5858 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5859 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5860 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5861 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5863 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5864 if( rc!=SQLITE_OK ) break;
5865 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5866 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5867 res = (
5868 0==sqlite3_strglob(zGlob, zPlan)
5869 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5872 rc = sqlite3_finalize(pExplain);
5873 if( rc!=SQLITE_OK ) break;
5875 if( res<0 ){
5876 raw_printf(stderr, "Error: internal error");
5877 break;
5878 }else{
5879 if( bGroupByParent
5880 && (bVerbose || res==0)
5881 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5883 raw_printf(out, "-- Parent table %s\n", zParent);
5884 sqlite3_free(zPrev);
5885 zPrev = sqlite3_mprintf("%s", zParent);
5888 if( res==0 ){
5889 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5890 }else if( bVerbose ){
5891 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5892 zIndent, zFrom, zTarget
5897 sqlite3_free(zPrev);
5899 if( rc!=SQLITE_OK ){
5900 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5903 rc2 = sqlite3_finalize(pSql);
5904 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5905 rc = rc2;
5906 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5908 }else{
5909 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5912 return rc;
5916 ** Implementation of ".lint" dot command.
5918 static int lintDotCommand(
5919 ShellState *pState, /* Current shell tool state */
5920 char **azArg, /* Array of arguments passed to dot command */
5921 int nArg /* Number of entries in azArg[] */
5923 int n;
5924 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
5925 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5926 return lintFkeyIndexes(pState, azArg, nArg);
5928 usage:
5929 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5930 raw_printf(stderr, "Where sub-commands are:\n");
5931 raw_printf(stderr, " fkey-indexes\n");
5932 return SQLITE_ERROR;
5935 #if !defined SQLITE_OMIT_VIRTUALTABLE
5936 static void shellPrepare(
5937 sqlite3 *db,
5938 int *pRc,
5939 const char *zSql,
5940 sqlite3_stmt **ppStmt
5942 *ppStmt = 0;
5943 if( *pRc==SQLITE_OK ){
5944 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
5945 if( rc!=SQLITE_OK ){
5946 raw_printf(stderr, "sql error: %s (%d)\n",
5947 sqlite3_errmsg(db), sqlite3_errcode(db)
5949 *pRc = rc;
5955 ** Create a prepared statement using printf-style arguments for the SQL.
5957 ** This routine is could be marked "static". But it is not always used,
5958 ** depending on compile-time options. By omitting the "static", we avoid
5959 ** nuisance compiler warnings about "defined but not used".
5961 void shellPreparePrintf(
5962 sqlite3 *db,
5963 int *pRc,
5964 sqlite3_stmt **ppStmt,
5965 const char *zFmt,
5968 *ppStmt = 0;
5969 if( *pRc==SQLITE_OK ){
5970 va_list ap;
5971 char *z;
5972 va_start(ap, zFmt);
5973 z = sqlite3_vmprintf(zFmt, ap);
5974 va_end(ap);
5975 if( z==0 ){
5976 *pRc = SQLITE_NOMEM;
5977 }else{
5978 shellPrepare(db, pRc, z, ppStmt);
5979 sqlite3_free(z);
5984 /* Finalize the prepared statement created using shellPreparePrintf().
5986 ** This routine is could be marked "static". But it is not always used,
5987 ** depending on compile-time options. By omitting the "static", we avoid
5988 ** nuisance compiler warnings about "defined but not used".
5990 void shellFinalize(
5991 int *pRc,
5992 sqlite3_stmt *pStmt
5994 if( pStmt ){
5995 sqlite3 *db = sqlite3_db_handle(pStmt);
5996 int rc = sqlite3_finalize(pStmt);
5997 if( *pRc==SQLITE_OK ){
5998 if( rc!=SQLITE_OK ){
5999 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6001 *pRc = rc;
6006 /* Reset the prepared statement created using shellPreparePrintf().
6008 ** This routine is could be marked "static". But it is not always used,
6009 ** depending on compile-time options. By omitting the "static", we avoid
6010 ** nuisance compiler warnings about "defined but not used".
6012 void shellReset(
6013 int *pRc,
6014 sqlite3_stmt *pStmt
6016 int rc = sqlite3_reset(pStmt);
6017 if( *pRc==SQLITE_OK ){
6018 if( rc!=SQLITE_OK ){
6019 sqlite3 *db = sqlite3_db_handle(pStmt);
6020 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6022 *pRc = rc;
6025 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6027 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6028 /******************************************************************************
6029 ** The ".archive" or ".ar" command.
6032 ** Structure representing a single ".ar" command.
6034 typedef struct ArCommand ArCommand;
6035 struct ArCommand {
6036 u8 eCmd; /* An AR_CMD_* value */
6037 u8 bVerbose; /* True if --verbose */
6038 u8 bZip; /* True if the archive is a ZIP */
6039 u8 bDryRun; /* True if --dry-run */
6040 u8 bAppend; /* True if --append */
6041 u8 fromCmdLine; /* Run from -A instead of .archive */
6042 int nArg; /* Number of command arguments */
6043 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6044 const char *zFile; /* --file argument, or NULL */
6045 const char *zDir; /* --directory argument, or NULL */
6046 char **azArg; /* Array of command arguments */
6047 ShellState *p; /* Shell state */
6048 sqlite3 *db; /* Database containing the archive */
6052 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6054 static int arUsage(FILE *f){
6055 showHelp(f,"archive");
6056 return SQLITE_ERROR;
6060 ** Print an error message for the .ar command to stderr and return
6061 ** SQLITE_ERROR.
6063 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6064 va_list ap;
6065 char *z;
6066 va_start(ap, zFmt);
6067 z = sqlite3_vmprintf(zFmt, ap);
6068 va_end(ap);
6069 utf8_printf(stderr, "Error: %s\n", z);
6070 if( pAr->fromCmdLine ){
6071 utf8_printf(stderr, "Use \"-A\" for more help\n");
6072 }else{
6073 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6075 sqlite3_free(z);
6076 return SQLITE_ERROR;
6080 ** Values for ArCommand.eCmd.
6082 #define AR_CMD_CREATE 1
6083 #define AR_CMD_UPDATE 2
6084 #define AR_CMD_INSERT 3
6085 #define AR_CMD_EXTRACT 4
6086 #define AR_CMD_LIST 5
6087 #define AR_CMD_HELP 6
6090 ** Other (non-command) switches.
6092 #define AR_SWITCH_VERBOSE 7
6093 #define AR_SWITCH_FILE 8
6094 #define AR_SWITCH_DIRECTORY 9
6095 #define AR_SWITCH_APPEND 10
6096 #define AR_SWITCH_DRYRUN 11
6098 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6099 switch( eSwitch ){
6100 case AR_CMD_CREATE:
6101 case AR_CMD_EXTRACT:
6102 case AR_CMD_LIST:
6103 case AR_CMD_UPDATE:
6104 case AR_CMD_INSERT:
6105 case AR_CMD_HELP:
6106 if( pAr->eCmd ){
6107 return arErrorMsg(pAr, "multiple command options");
6109 pAr->eCmd = eSwitch;
6110 break;
6112 case AR_SWITCH_DRYRUN:
6113 pAr->bDryRun = 1;
6114 break;
6115 case AR_SWITCH_VERBOSE:
6116 pAr->bVerbose = 1;
6117 break;
6118 case AR_SWITCH_APPEND:
6119 pAr->bAppend = 1;
6120 /* Fall thru into --file */
6121 case AR_SWITCH_FILE:
6122 pAr->zFile = zArg;
6123 break;
6124 case AR_SWITCH_DIRECTORY:
6125 pAr->zDir = zArg;
6126 break;
6129 return SQLITE_OK;
6133 ** Parse the command line for an ".ar" command. The results are written into
6134 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6135 ** successfully, otherwise an error message is written to stderr and
6136 ** SQLITE_ERROR returned.
6138 static int arParseCommand(
6139 char **azArg, /* Array of arguments passed to dot command */
6140 int nArg, /* Number of entries in azArg[] */
6141 ArCommand *pAr /* Populate this object */
6143 struct ArSwitch {
6144 const char *zLong;
6145 char cShort;
6146 u8 eSwitch;
6147 u8 bArg;
6148 } aSwitch[] = {
6149 { "create", 'c', AR_CMD_CREATE, 0 },
6150 { "extract", 'x', AR_CMD_EXTRACT, 0 },
6151 { "insert", 'i', AR_CMD_INSERT, 0 },
6152 { "list", 't', AR_CMD_LIST, 0 },
6153 { "update", 'u', AR_CMD_UPDATE, 0 },
6154 { "help", 'h', AR_CMD_HELP, 0 },
6155 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
6156 { "file", 'f', AR_SWITCH_FILE, 1 },
6157 { "append", 'a', AR_SWITCH_APPEND, 1 },
6158 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6159 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
6161 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6162 struct ArSwitch *pEnd = &aSwitch[nSwitch];
6164 if( nArg<=1 ){
6165 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
6166 return arUsage(stderr);
6167 }else{
6168 char *z = azArg[1];
6169 if( z[0]!='-' ){
6170 /* Traditional style [tar] invocation */
6171 int i;
6172 int iArg = 2;
6173 for(i=0; z[i]; i++){
6174 const char *zArg = 0;
6175 struct ArSwitch *pOpt;
6176 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6177 if( z[i]==pOpt->cShort ) break;
6179 if( pOpt==pEnd ){
6180 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6182 if( pOpt->bArg ){
6183 if( iArg>=nArg ){
6184 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6186 zArg = azArg[iArg++];
6188 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6190 pAr->nArg = nArg-iArg;
6191 if( pAr->nArg>0 ){
6192 pAr->azArg = &azArg[iArg];
6194 }else{
6195 /* Non-traditional invocation */
6196 int iArg;
6197 for(iArg=1; iArg<nArg; iArg++){
6198 int n;
6199 z = azArg[iArg];
6200 if( z[0]!='-' ){
6201 /* All remaining command line words are command arguments. */
6202 pAr->azArg = &azArg[iArg];
6203 pAr->nArg = nArg-iArg;
6204 break;
6206 n = strlen30(z);
6208 if( z[1]!='-' ){
6209 int i;
6210 /* One or more short options */
6211 for(i=1; i<n; i++){
6212 const char *zArg = 0;
6213 struct ArSwitch *pOpt;
6214 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6215 if( z[i]==pOpt->cShort ) break;
6217 if( pOpt==pEnd ){
6218 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6220 if( pOpt->bArg ){
6221 if( i<(n-1) ){
6222 zArg = &z[i+1];
6223 i = n;
6224 }else{
6225 if( iArg>=(nArg-1) ){
6226 return arErrorMsg(pAr, "option requires an argument: %c",
6227 z[i]);
6229 zArg = azArg[++iArg];
6232 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6234 }else if( z[2]=='\0' ){
6235 /* A -- option, indicating that all remaining command line words
6236 ** are command arguments. */
6237 pAr->azArg = &azArg[iArg+1];
6238 pAr->nArg = nArg-iArg-1;
6239 break;
6240 }else{
6241 /* A long option */
6242 const char *zArg = 0; /* Argument for option, if any */
6243 struct ArSwitch *pMatch = 0; /* Matching option */
6244 struct ArSwitch *pOpt; /* Iterator */
6245 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6246 const char *zLong = pOpt->zLong;
6247 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6248 if( pMatch ){
6249 return arErrorMsg(pAr, "ambiguous option: %s",z);
6250 }else{
6251 pMatch = pOpt;
6256 if( pMatch==0 ){
6257 return arErrorMsg(pAr, "unrecognized option: %s", z);
6259 if( pMatch->bArg ){
6260 if( iArg>=(nArg-1) ){
6261 return arErrorMsg(pAr, "option requires an argument: %s", z);
6263 zArg = azArg[++iArg];
6265 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6271 return SQLITE_OK;
6275 ** This function assumes that all arguments within the ArCommand.azArg[]
6276 ** array refer to archive members, as for the --extract or --list commands.
6277 ** It checks that each of them are present. If any specified file is not
6278 ** present in the archive, an error is printed to stderr and an error
6279 ** code returned. Otherwise, if all specified arguments are present in
6280 ** the archive, SQLITE_OK is returned.
6282 ** This function strips any trailing '/' characters from each argument.
6283 ** This is consistent with the way the [tar] command seems to work on
6284 ** Linux.
6286 static int arCheckEntries(ArCommand *pAr){
6287 int rc = SQLITE_OK;
6288 if( pAr->nArg ){
6289 int i, j;
6290 sqlite3_stmt *pTest = 0;
6292 shellPreparePrintf(pAr->db, &rc, &pTest,
6293 "SELECT name FROM %s WHERE name=$name",
6294 pAr->zSrcTable
6296 j = sqlite3_bind_parameter_index(pTest, "$name");
6297 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6298 char *z = pAr->azArg[i];
6299 int n = strlen30(z);
6300 int bOk = 0;
6301 while( n>0 && z[n-1]=='/' ) n--;
6302 z[n] = '\0';
6303 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6304 if( SQLITE_ROW==sqlite3_step(pTest) ){
6305 bOk = 1;
6307 shellReset(&rc, pTest);
6308 if( rc==SQLITE_OK && bOk==0 ){
6309 utf8_printf(stderr, "not found in archive: %s\n", z);
6310 rc = SQLITE_ERROR;
6313 shellFinalize(&rc, pTest);
6315 return rc;
6319 ** Format a WHERE clause that can be used against the "sqlar" table to
6320 ** identify all archive members that match the command arguments held
6321 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6322 ** The caller is responsible for eventually calling sqlite3_free() on
6323 ** any non-NULL (*pzWhere) value.
6325 static void arWhereClause(
6326 int *pRc,
6327 ArCommand *pAr,
6328 char **pzWhere /* OUT: New WHERE clause */
6330 char *zWhere = 0;
6331 if( *pRc==SQLITE_OK ){
6332 if( pAr->nArg==0 ){
6333 zWhere = sqlite3_mprintf("1");
6334 }else{
6335 int i;
6336 const char *zSep = "";
6337 for(i=0; i<pAr->nArg; i++){
6338 const char *z = pAr->azArg[i];
6339 zWhere = sqlite3_mprintf(
6340 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
6341 zWhere, zSep, z, strlen30(z)+1, z
6343 if( zWhere==0 ){
6344 *pRc = SQLITE_NOMEM;
6345 break;
6347 zSep = " OR ";
6351 *pzWhere = zWhere;
6355 ** Implementation of .ar "lisT" command.
6357 static int arListCommand(ArCommand *pAr){
6358 const char *zSql = "SELECT %s FROM %s WHERE %s";
6359 const char *azCols[] = {
6360 "name",
6361 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6364 char *zWhere = 0;
6365 sqlite3_stmt *pSql = 0;
6366 int rc;
6368 rc = arCheckEntries(pAr);
6369 arWhereClause(&rc, pAr, &zWhere);
6371 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6372 pAr->zSrcTable, zWhere);
6373 if( pAr->bDryRun ){
6374 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6375 }else{
6376 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6377 if( pAr->bVerbose ){
6378 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
6379 sqlite3_column_text(pSql, 0),
6380 sqlite3_column_int(pSql, 1),
6381 sqlite3_column_text(pSql, 2),
6382 sqlite3_column_text(pSql, 3)
6384 }else{
6385 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6389 shellFinalize(&rc, pSql);
6390 sqlite3_free(zWhere);
6391 return rc;
6396 ** Implementation of .ar "eXtract" command.
6398 static int arExtractCommand(ArCommand *pAr){
6399 const char *zSql1 =
6400 "SELECT "
6401 " ($dir || name),"
6402 " writefile(($dir || name), %s, mode, mtime) "
6403 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6404 " AND name NOT GLOB '*..[/\\]*'";
6406 const char *azExtraArg[] = {
6407 "sqlar_uncompress(data, sz)",
6408 "data"
6411 sqlite3_stmt *pSql = 0;
6412 int rc = SQLITE_OK;
6413 char *zDir = 0;
6414 char *zWhere = 0;
6415 int i, j;
6417 /* If arguments are specified, check that they actually exist within
6418 ** the archive before proceeding. And formulate a WHERE clause to
6419 ** match them. */
6420 rc = arCheckEntries(pAr);
6421 arWhereClause(&rc, pAr, &zWhere);
6423 if( rc==SQLITE_OK ){
6424 if( pAr->zDir ){
6425 zDir = sqlite3_mprintf("%s/", pAr->zDir);
6426 }else{
6427 zDir = sqlite3_mprintf("");
6429 if( zDir==0 ) rc = SQLITE_NOMEM;
6432 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6433 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6436 if( rc==SQLITE_OK ){
6437 j = sqlite3_bind_parameter_index(pSql, "$dir");
6438 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6440 /* Run the SELECT statement twice. The first time, writefile() is called
6441 ** for all archive members that should be extracted. The second time,
6442 ** only for the directories. This is because the timestamps for
6443 ** extracted directories must be reset after they are populated (as
6444 ** populating them changes the timestamp). */
6445 for(i=0; i<2; i++){
6446 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6447 sqlite3_bind_int(pSql, j, i);
6448 if( pAr->bDryRun ){
6449 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6450 }else{
6451 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6452 if( i==0 && pAr->bVerbose ){
6453 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6457 shellReset(&rc, pSql);
6459 shellFinalize(&rc, pSql);
6462 sqlite3_free(zDir);
6463 sqlite3_free(zWhere);
6464 return rc;
6468 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
6470 static int arExecSql(ArCommand *pAr, const char *zSql){
6471 int rc;
6472 if( pAr->bDryRun ){
6473 utf8_printf(pAr->p->out, "%s\n", zSql);
6474 rc = SQLITE_OK;
6475 }else{
6476 char *zErr = 0;
6477 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6478 if( zErr ){
6479 utf8_printf(stdout, "ERROR: %s\n", zErr);
6480 sqlite3_free(zErr);
6483 return rc;
6488 ** Implementation of .ar "create", "insert", and "update" commands.
6490 ** create -> Create a new SQL archive
6491 ** insert -> Insert or reinsert all files listed
6492 ** update -> Insert files that have changed or that were not
6493 ** previously in the archive
6495 ** Create the "sqlar" table in the database if it does not already exist.
6496 ** Then add each file in the azFile[] array to the archive. Directories
6497 ** are added recursively. If argument bVerbose is non-zero, a message is
6498 ** printed on stdout for each file archived.
6500 ** The create command is the same as update, except that it drops
6501 ** any existing "sqlar" table before beginning. The "insert" command
6502 ** always overwrites every file named on the command-line, where as
6503 ** "update" only overwrites if the size or mtime or mode has changed.
6505 static int arCreateOrUpdateCommand(
6506 ArCommand *pAr, /* Command arguments and options */
6507 int bUpdate, /* true for a --create. */
6508 int bOnlyIfChanged /* Only update if file has changed */
6510 const char *zCreate =
6511 "CREATE TABLE IF NOT EXISTS sqlar(\n"
6512 " name TEXT PRIMARY KEY, -- name of the file\n"
6513 " mode INT, -- access permissions\n"
6514 " mtime INT, -- last modification time\n"
6515 " sz INT, -- original file size\n"
6516 " data BLOB -- compressed content\n"
6517 ")";
6518 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6519 const char *zInsertFmt[2] = {
6520 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6521 " SELECT\n"
6522 " %s,\n"
6523 " mode,\n"
6524 " mtime,\n"
6525 " CASE substr(lsmode(mode),1,1)\n"
6526 " WHEN '-' THEN length(data)\n"
6527 " WHEN 'd' THEN 0\n"
6528 " ELSE -1 END,\n"
6529 " sqlar_compress(data)\n"
6530 " FROM fsdir(%Q,%Q) AS disk\n"
6531 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6533 "REPLACE INTO %s(name,mode,mtime,data)\n"
6534 " SELECT\n"
6535 " %s,\n"
6536 " mode,\n"
6537 " mtime,\n"
6538 " data\n"
6539 " FROM fsdir(%Q,%Q) AS disk\n"
6540 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6542 int i; /* For iterating through azFile[] */
6543 int rc; /* Return code */
6544 const char *zTab = 0; /* SQL table into which to insert */
6545 char *zSql;
6546 char zTemp[50];
6547 char *zExists = 0;
6549 arExecSql(pAr, "PRAGMA page_size=512");
6550 rc = arExecSql(pAr, "SAVEPOINT ar;");
6551 if( rc!=SQLITE_OK ) return rc;
6552 zTemp[0] = 0;
6553 if( pAr->bZip ){
6554 /* Initialize the zipfile virtual table, if necessary */
6555 if( pAr->zFile ){
6556 sqlite3_uint64 r;
6557 sqlite3_randomness(sizeof(r),&r);
6558 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6559 zTab = zTemp;
6560 zSql = sqlite3_mprintf(
6561 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6562 zTab, pAr->zFile
6564 rc = arExecSql(pAr, zSql);
6565 sqlite3_free(zSql);
6566 }else{
6567 zTab = "zip";
6569 }else{
6570 /* Initialize the table for an SQLAR */
6571 zTab = "sqlar";
6572 if( bUpdate==0 ){
6573 rc = arExecSql(pAr, zDrop);
6574 if( rc!=SQLITE_OK ) goto end_ar_transaction;
6576 rc = arExecSql(pAr, zCreate);
6578 if( bOnlyIfChanged ){
6579 zExists = sqlite3_mprintf(
6580 " AND NOT EXISTS("
6581 "SELECT 1 FROM %s AS mem"
6582 " WHERE mem.name=disk.name"
6583 " AND mem.mtime=disk.mtime"
6584 " AND mem.mode=disk.mode)", zTab);
6585 }else{
6586 zExists = sqlite3_mprintf("");
6588 if( zExists==0 ) rc = SQLITE_NOMEM;
6589 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6590 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6591 pAr->bVerbose ? "shell_putsnl(name)" : "name",
6592 pAr->azArg[i], pAr->zDir, zExists);
6593 rc = arExecSql(pAr, zSql2);
6594 sqlite3_free(zSql2);
6596 end_ar_transaction:
6597 if( rc!=SQLITE_OK ){
6598 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6599 }else{
6600 rc = arExecSql(pAr, "RELEASE ar;");
6601 if( pAr->bZip && pAr->zFile ){
6602 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6603 arExecSql(pAr, zSql);
6604 sqlite3_free(zSql);
6607 sqlite3_free(zExists);
6608 return rc;
6612 ** Implementation of ".ar" dot command.
6614 static int arDotCommand(
6615 ShellState *pState, /* Current shell tool state */
6616 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
6617 char **azArg, /* Array of arguments passed to dot command */
6618 int nArg /* Number of entries in azArg[] */
6620 ArCommand cmd;
6621 int rc;
6622 memset(&cmd, 0, sizeof(cmd));
6623 cmd.fromCmdLine = fromCmdLine;
6624 rc = arParseCommand(azArg, nArg, &cmd);
6625 if( rc==SQLITE_OK ){
6626 int eDbType = SHELL_OPEN_UNSPEC;
6627 cmd.p = pState;
6628 cmd.db = pState->db;
6629 if( cmd.zFile ){
6630 eDbType = deduceDatabaseType(cmd.zFile, 1);
6631 }else{
6632 eDbType = pState->openMode;
6634 if( eDbType==SHELL_OPEN_ZIPFILE ){
6635 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6636 if( cmd.zFile==0 ){
6637 cmd.zSrcTable = sqlite3_mprintf("zip");
6638 }else{
6639 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6642 cmd.bZip = 1;
6643 }else if( cmd.zFile ){
6644 int flags;
6645 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6646 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6647 || cmd.eCmd==AR_CMD_UPDATE ){
6648 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6649 }else{
6650 flags = SQLITE_OPEN_READONLY;
6652 cmd.db = 0;
6653 if( cmd.bDryRun ){
6654 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6655 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6657 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6658 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6659 if( rc!=SQLITE_OK ){
6660 utf8_printf(stderr, "cannot open file: %s (%s)\n",
6661 cmd.zFile, sqlite3_errmsg(cmd.db)
6663 goto end_ar_command;
6665 sqlite3_fileio_init(cmd.db, 0, 0);
6666 sqlite3_sqlar_init(cmd.db, 0, 0);
6667 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6668 shellPutsFunc, 0, 0);
6671 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6672 if( cmd.eCmd!=AR_CMD_CREATE
6673 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6675 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6676 rc = SQLITE_ERROR;
6677 goto end_ar_command;
6679 cmd.zSrcTable = sqlite3_mprintf("sqlar");
6682 switch( cmd.eCmd ){
6683 case AR_CMD_CREATE:
6684 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6685 break;
6687 case AR_CMD_EXTRACT:
6688 rc = arExtractCommand(&cmd);
6689 break;
6691 case AR_CMD_LIST:
6692 rc = arListCommand(&cmd);
6693 break;
6695 case AR_CMD_HELP:
6696 arUsage(pState->out);
6697 break;
6699 case AR_CMD_INSERT:
6700 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6701 break;
6703 default:
6704 assert( cmd.eCmd==AR_CMD_UPDATE );
6705 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6706 break;
6709 end_ar_command:
6710 if( cmd.db!=pState->db ){
6711 close_db(cmd.db);
6713 sqlite3_free(cmd.zSrcTable);
6715 return rc;
6717 /* End of the ".archive" or ".ar" command logic
6718 *******************************************************************************/
6719 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6721 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6723 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6724 ** Otherwise, the SQL statement or statements in zSql are executed using
6725 ** database connection db and the error code written to *pRc before
6726 ** this function returns.
6728 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6729 int rc = *pRc;
6730 if( rc==SQLITE_OK ){
6731 char *zErr = 0;
6732 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6733 if( rc!=SQLITE_OK ){
6734 raw_printf(stderr, "SQL error: %s\n", zErr);
6736 sqlite3_free(zErr);
6737 *pRc = rc;
6742 ** Like shellExec(), except that zFmt is a printf() style format string.
6744 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6745 char *z = 0;
6746 if( *pRc==SQLITE_OK ){
6747 va_list ap;
6748 va_start(ap, zFmt);
6749 z = sqlite3_vmprintf(zFmt, ap);
6750 va_end(ap);
6751 if( z==0 ){
6752 *pRc = SQLITE_NOMEM;
6753 }else{
6754 shellExec(db, pRc, z);
6756 sqlite3_free(z);
6761 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6762 ** Otherwise, an attempt is made to allocate, zero and return a pointer
6763 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6764 ** to SQLITE_NOMEM and NULL returned.
6766 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6767 void *pRet = 0;
6768 if( *pRc==SQLITE_OK ){
6769 pRet = sqlite3_malloc64(nByte);
6770 if( pRet==0 ){
6771 *pRc = SQLITE_NOMEM;
6772 }else{
6773 memset(pRet, 0, nByte);
6776 return pRet;
6780 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6781 ** Otherwise, zFmt is treated as a printf() style string. The result of
6782 ** formatting it along with any trailing arguments is written into a
6783 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6784 ** It is the responsibility of the caller to eventually free this buffer
6785 ** using a call to sqlite3_free().
6787 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6788 ** pointer returned.
6790 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6791 char *z = 0;
6792 if( *pRc==SQLITE_OK ){
6793 va_list ap;
6794 va_start(ap, zFmt);
6795 z = sqlite3_vmprintf(zFmt, ap);
6796 va_end(ap);
6797 if( z==0 ){
6798 *pRc = SQLITE_NOMEM;
6801 return z;
6805 ** When running the ".recover" command, each output table, and the special
6806 ** orphaned row table if it is required, is represented by an instance
6807 ** of the following struct.
6809 typedef struct RecoverTable RecoverTable;
6810 struct RecoverTable {
6811 char *zQuoted; /* Quoted version of table name */
6812 int nCol; /* Number of columns in table */
6813 char **azlCol; /* Array of column lists */
6814 int iPk; /* Index of IPK column */
6818 ** Free a RecoverTable object allocated by recoverFindTable() or
6819 ** recoverOrphanTable().
6821 static void recoverFreeTable(RecoverTable *pTab){
6822 if( pTab ){
6823 sqlite3_free(pTab->zQuoted);
6824 if( pTab->azlCol ){
6825 int i;
6826 for(i=0; i<=pTab->nCol; i++){
6827 sqlite3_free(pTab->azlCol[i]);
6829 sqlite3_free(pTab->azlCol);
6831 sqlite3_free(pTab);
6836 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6837 ** Otherwise, it allocates and returns a RecoverTable object based on the
6838 ** final four arguments passed to this function. It is the responsibility
6839 ** of the caller to eventually free the returned object using
6840 ** recoverFreeTable().
6842 static RecoverTable *recoverNewTable(
6843 int *pRc, /* IN/OUT: Error code */
6844 const char *zName, /* Name of table */
6845 const char *zSql, /* CREATE TABLE statement */
6846 int bIntkey,
6847 int nCol
6849 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
6850 int rc = *pRc;
6851 RecoverTable *pTab = 0;
6853 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
6854 if( rc==SQLITE_OK ){
6855 int nSqlCol = 0;
6856 int bSqlIntkey = 0;
6857 sqlite3_stmt *pStmt = 0;
6859 rc = sqlite3_open("", &dbtmp);
6860 if( rc==SQLITE_OK ){
6861 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
6862 shellIdQuote, 0, 0);
6864 if( rc==SQLITE_OK ){
6865 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6867 if( rc==SQLITE_OK ){
6868 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6869 if( rc==SQLITE_ERROR ){
6870 rc = SQLITE_OK;
6871 goto finished;
6874 shellPreparePrintf(dbtmp, &rc, &pStmt,
6875 "SELECT count(*) FROM pragma_table_info(%Q)", zName
6877 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6878 nSqlCol = sqlite3_column_int(pStmt, 0);
6880 shellFinalize(&rc, pStmt);
6882 if( rc!=SQLITE_OK || nSqlCol<nCol ){
6883 goto finished;
6886 shellPreparePrintf(dbtmp, &rc, &pStmt,
6887 "SELECT ("
6888 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6889 ") FROM sqlite_schema WHERE name = %Q", zName
6891 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6892 bSqlIntkey = sqlite3_column_int(pStmt, 0);
6894 shellFinalize(&rc, pStmt);
6896 if( bIntkey==bSqlIntkey ){
6897 int i;
6898 const char *zPk = "_rowid_";
6899 sqlite3_stmt *pPkFinder = 0;
6901 /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6902 ** set zPk to the name of the PK column, and pTab->iPk to the index
6903 ** of the column, where columns are 0-numbered from left to right.
6904 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6905 ** leave zPk as "_rowid_" and pTab->iPk at -2. */
6906 pTab->iPk = -2;
6907 if( bIntkey ){
6908 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
6909 "SELECT cid, name FROM pragma_table_info(%Q) "
6910 " WHERE pk=1 AND type='integer' COLLATE nocase"
6911 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6912 , zName, zName
6914 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6915 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6916 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6920 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
6921 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
6922 pTab->nCol = nSqlCol;
6924 if( bIntkey ){
6925 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
6926 }else{
6927 pTab->azlCol[0] = shellMPrintf(&rc, "");
6929 i = 1;
6930 shellPreparePrintf(dbtmp, &rc, &pStmt,
6931 "SELECT %Q || group_concat(shell_idquote(name), ', ') "
6932 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
6933 "FROM pragma_table_info(%Q)",
6934 bIntkey ? ", " : "", pTab->iPk,
6935 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6936 zName
6938 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6939 const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6940 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6941 i++;
6943 shellFinalize(&rc, pStmt);
6945 shellFinalize(&rc, pPkFinder);
6949 finished:
6950 sqlite3_close(dbtmp);
6951 *pRc = rc;
6952 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
6953 recoverFreeTable(pTab);
6954 pTab = 0;
6956 return pTab;
6960 ** This function is called to search the schema recovered from the
6961 ** sqlite_schema table of the (possibly) corrupt database as part
6962 ** of a ".recover" command. Specifically, for a table with root page
6963 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
6964 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
6965 ** those.
6967 ** If a table is found, a (RecoverTable*) object is returned. Or, if
6968 ** no such table is found, but bIntkey is false and iRoot is the
6969 ** root page of an index in the recovered schema, then (*pbNoop) is
6970 ** set to true and NULL returned. Or, if there is no such table or
6971 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
6972 ** the caller should write data to the orphans table.
6974 static RecoverTable *recoverFindTable(
6975 ShellState *pState, /* Shell state object */
6976 int *pRc, /* IN/OUT: Error code */
6977 int iRoot, /* Root page of table */
6978 int bIntkey, /* True for an intkey table */
6979 int nCol, /* Number of columns in table */
6980 int *pbNoop /* OUT: True if iRoot is root of index */
6982 sqlite3_stmt *pStmt = 0;
6983 RecoverTable *pRet = 0;
6984 int bNoop = 0;
6985 const char *zSql = 0;
6986 const char *zName = 0;
6988 /* Search the recovered schema for an object with root page iRoot. */
6989 shellPreparePrintf(pState->db, pRc, &pStmt,
6990 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6992 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6993 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6994 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6995 bNoop = 1;
6996 break;
6998 if( sqlite3_stricmp(zType, "table")==0 ){
6999 zName = (const char*)sqlite3_column_text(pStmt, 1);
7000 zSql = (const char*)sqlite3_column_text(pStmt, 2);
7001 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7002 break;
7006 shellFinalize(pRc, pStmt);
7007 *pbNoop = bNoop;
7008 return pRet;
7012 ** Return a RecoverTable object representing the orphans table.
7014 static RecoverTable *recoverOrphanTable(
7015 ShellState *pState, /* Shell state object */
7016 int *pRc, /* IN/OUT: Error code */
7017 const char *zLostAndFound, /* Base name for orphans table */
7018 int nCol /* Number of user data columns */
7020 RecoverTable *pTab = 0;
7021 if( nCol>=0 && *pRc==SQLITE_OK ){
7022 int i;
7024 /* This block determines the name of the orphan table. The prefered
7025 ** name is zLostAndFound. But if that clashes with another name
7026 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7027 ** and so on until a non-clashing name is found. */
7028 int iTab = 0;
7029 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7030 sqlite3_stmt *pTest = 0;
7031 shellPrepare(pState->db, pRc,
7032 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7034 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7035 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7036 shellReset(pRc, pTest);
7037 sqlite3_free(zTab);
7038 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7039 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7041 shellFinalize(pRc, pTest);
7043 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7044 if( pTab ){
7045 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7046 pTab->nCol = nCol;
7047 pTab->iPk = -2;
7048 if( nCol>0 ){
7049 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7050 if( pTab->azlCol ){
7051 pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7052 for(i=nCol-1; i>=0; i--){
7053 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7058 if( *pRc!=SQLITE_OK ){
7059 recoverFreeTable(pTab);
7060 pTab = 0;
7061 }else{
7062 raw_printf(pState->out,
7063 "CREATE TABLE %s(rootpgno INTEGER, "
7064 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7066 for(i=0; i<nCol; i++){
7067 raw_printf(pState->out, ", c%d", i);
7069 raw_printf(pState->out, ");\n");
7072 sqlite3_free(zTab);
7074 return pTab;
7078 ** This function is called to recover data from the database. A script
7079 ** to construct a new database containing all recovered data is output
7080 ** on stream pState->out.
7082 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7083 int rc = SQLITE_OK;
7084 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
7085 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
7086 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
7087 const char *zRecoveryDb = ""; /* Name of "recovery" database */
7088 const char *zLostAndFound = "lost_and_found";
7089 int i;
7090 int nOrphan = -1;
7091 RecoverTable *pOrphan = 0;
7093 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
7094 int bRowids = 1; /* 0 if --no-rowids */
7095 for(i=1; i<nArg; i++){
7096 char *z = azArg[i];
7097 int n;
7098 if( z[0]=='-' && z[1]=='-' ) z++;
7099 n = strlen30(z);
7100 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7101 bFreelist = 0;
7102 }else
7103 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7104 i++;
7105 zRecoveryDb = azArg[i];
7106 }else
7107 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7108 i++;
7109 zLostAndFound = azArg[i];
7110 }else
7111 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7112 bRowids = 0;
7114 else{
7115 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7116 showHelp(pState->out, azArg[0]);
7117 return 1;
7121 shellExecPrintf(pState->db, &rc,
7122 /* Attach an in-memory database named 'recovery'. Create an indexed
7123 ** cache of the sqlite_dbptr virtual table. */
7124 "PRAGMA writable_schema = on;"
7125 "ATTACH %Q AS recovery;"
7126 "DROP TABLE IF EXISTS recovery.dbptr;"
7127 "DROP TABLE IF EXISTS recovery.freelist;"
7128 "DROP TABLE IF EXISTS recovery.map;"
7129 "DROP TABLE IF EXISTS recovery.schema;"
7130 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7133 if( bFreelist ){
7134 shellExec(pState->db, &rc,
7135 "WITH trunk(pgno) AS ("
7136 " SELECT shell_int32("
7137 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7138 " WHERE x>0"
7139 " UNION"
7140 " SELECT shell_int32("
7141 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7142 " FROM trunk WHERE x>0"
7143 "),"
7144 "freelist(data, n, freepgno) AS ("
7145 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7146 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7147 " UNION ALL"
7148 " SELECT data, n-1, shell_int32(data, 2+n) "
7149 " FROM freelist WHERE n>=0"
7151 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7155 /* If this is an auto-vacuum database, add all pointer-map pages to
7156 ** the freelist table. Do this regardless of whether or not
7157 ** --freelist-corrupt was specified. */
7158 shellExec(pState->db, &rc,
7159 "WITH ptrmap(pgno) AS ("
7160 " SELECT 2 WHERE shell_int32("
7161 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7162 " )"
7163 " UNION ALL "
7164 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7165 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7167 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7170 shellExec(pState->db, &rc,
7171 "CREATE TABLE recovery.dbptr("
7172 " pgno, child, PRIMARY KEY(child, pgno)"
7173 ") WITHOUT ROWID;"
7174 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7175 " SELECT * FROM sqlite_dbptr"
7176 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7178 /* Delete any pointer to page 1. This ensures that page 1 is considered
7179 ** a root page, regardless of how corrupt the db is. */
7180 "DELETE FROM recovery.dbptr WHERE child = 1;"
7182 /* Delete all pointers to any pages that have more than one pointer
7183 ** to them. Such pages will be treated as root pages when recovering
7184 ** data. */
7185 "DELETE FROM recovery.dbptr WHERE child IN ("
7186 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7187 ");"
7189 /* Create the "map" table that will (eventually) contain instructions
7190 ** for dealing with each page in the db that contains one or more
7191 ** records. */
7192 "CREATE TABLE recovery.map("
7193 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7194 ");"
7196 /* Populate table [map]. If there are circular loops of pages in the
7197 ** database, the following adds all pages in such a loop to the map
7198 ** as individual root pages. This could be handled better. */
7199 "WITH pages(i, maxlen) AS ("
7200 " SELECT page_count, ("
7201 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7202 " ) FROM pragma_page_count WHERE page_count>0"
7203 " UNION ALL"
7204 " SELECT i-1, ("
7205 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7206 " ) FROM pages WHERE i>=2"
7208 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7209 " SELECT i, maxlen, NULL, ("
7210 " WITH p(orig, pgno, parent) AS ("
7211 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7212 " UNION "
7213 " SELECT i, p.parent, "
7214 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7215 " )"
7216 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7217 ") "
7218 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7219 "UPDATE recovery.map AS o SET intkey = ("
7220 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7221 ");"
7223 /* Extract data from page 1 and any linked pages into table
7224 ** recovery.schema. With the same schema as an sqlite_schema table. */
7225 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7226 "INSERT INTO recovery.schema SELECT "
7227 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
7228 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
7229 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
7230 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
7231 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
7232 "FROM sqlite_dbdata WHERE pgno IN ("
7233 " SELECT pgno FROM recovery.map WHERE root=1"
7235 "GROUP BY pgno, cell;"
7236 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7239 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7240 ** CREATE TABLE statements that extracted from the existing schema. */
7241 if( rc==SQLITE_OK ){
7242 sqlite3_stmt *pStmt = 0;
7243 /* ".recover" might output content in an order which causes immediate
7244 ** foreign key constraints to be violated. So disable foreign-key
7245 ** constraint enforcement to prevent problems when running the output
7246 ** script. */
7247 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7248 raw_printf(pState->out, "BEGIN;\n");
7249 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7250 shellPrepare(pState->db, &rc,
7251 "SELECT sql FROM recovery.schema "
7252 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7254 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7255 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7256 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7257 &zCreateTable[12]
7260 shellFinalize(&rc, pStmt);
7263 /* Figure out if an orphan table will be required. And if so, how many
7264 ** user columns it should contain */
7265 shellPrepare(pState->db, &rc,
7266 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7267 , &pLoop
7269 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7270 nOrphan = sqlite3_column_int(pLoop, 0);
7272 shellFinalize(&rc, pLoop);
7273 pLoop = 0;
7275 shellPrepare(pState->db, &rc,
7276 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7279 shellPrepare(pState->db, &rc,
7280 "SELECT max(field), group_concat(shell_escape_crnl(quote"
7281 "(case when (? AND field<0) then NULL else value end)"
7282 "), ', ')"
7283 ", min(field) "
7284 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7285 "GROUP BY cell", &pCells
7288 /* Loop through each root page. */
7289 shellPrepare(pState->db, &rc,
7290 "SELECT root, intkey, max(maxlen) FROM recovery.map"
7291 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7292 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7293 ")", &pLoop
7295 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7296 int iRoot = sqlite3_column_int(pLoop, 0);
7297 int bIntkey = sqlite3_column_int(pLoop, 1);
7298 int nCol = sqlite3_column_int(pLoop, 2);
7299 int bNoop = 0;
7300 RecoverTable *pTab;
7302 assert( bIntkey==0 || bIntkey==1 );
7303 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7304 if( bNoop || rc ) continue;
7305 if( pTab==0 ){
7306 if( pOrphan==0 ){
7307 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7309 pTab = pOrphan;
7310 if( pTab==0 ) break;
7313 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7314 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7316 sqlite3_bind_int(pPages, 1, iRoot);
7317 if( bRowids==0 && pTab->iPk<0 ){
7318 sqlite3_bind_int(pCells, 1, 1);
7319 }else{
7320 sqlite3_bind_int(pCells, 1, 0);
7322 sqlite3_bind_int(pCells, 3, pTab->iPk);
7324 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7325 int iPgno = sqlite3_column_int(pPages, 0);
7326 sqlite3_bind_int(pCells, 2, iPgno);
7327 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7328 int nField = sqlite3_column_int(pCells, 0);
7329 int iMin = sqlite3_column_int(pCells, 2);
7330 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7332 RecoverTable *pTab2 = pTab;
7333 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7334 if( pOrphan==0 ){
7335 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7337 pTab2 = pOrphan;
7338 if( pTab2==0 ) break;
7341 nField = nField+1;
7342 if( pTab2==pOrphan ){
7343 raw_printf(pState->out,
7344 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7345 pTab2->zQuoted, iRoot, iPgno, nField,
7346 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7348 }else{
7349 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7350 pTab2->zQuoted, pTab2->azlCol[nField], zVal
7354 shellReset(&rc, pCells);
7356 shellReset(&rc, pPages);
7357 if( pTab!=pOrphan ) recoverFreeTable(pTab);
7359 shellFinalize(&rc, pLoop);
7360 shellFinalize(&rc, pPages);
7361 shellFinalize(&rc, pCells);
7362 recoverFreeTable(pOrphan);
7364 /* The rest of the schema */
7365 if( rc==SQLITE_OK ){
7366 sqlite3_stmt *pStmt = 0;
7367 shellPrepare(pState->db, &rc,
7368 "SELECT sql, name FROM recovery.schema "
7369 "WHERE sql NOT LIKE 'create table%'", &pStmt
7371 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7372 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7373 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7374 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7375 char *zPrint = shellMPrintf(&rc,
7376 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7377 zName, zName, zSql
7379 raw_printf(pState->out, "%s;\n", zPrint);
7380 sqlite3_free(zPrint);
7381 }else{
7382 raw_printf(pState->out, "%s;\n", zSql);
7385 shellFinalize(&rc, pStmt);
7388 if( rc==SQLITE_OK ){
7389 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7390 raw_printf(pState->out, "COMMIT;\n");
7392 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7393 return rc;
7395 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7399 ** If an input line begins with "." then invoke this routine to
7400 ** process that line.
7402 ** Return 1 on error, 2 to exit, and 0 otherwise.
7404 static int do_meta_command(char *zLine, ShellState *p){
7405 int h = 1;
7406 int nArg = 0;
7407 int n, c;
7408 int rc = 0;
7409 char *azArg[52];
7411 #ifndef SQLITE_OMIT_VIRTUALTABLE
7412 if( p->expert.pExpert ){
7413 expertFinish(p, 1, 0);
7415 #endif
7417 /* Parse the input line into tokens.
7419 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7420 while( IsSpace(zLine[h]) ){ h++; }
7421 if( zLine[h]==0 ) break;
7422 if( zLine[h]=='\'' || zLine[h]=='"' ){
7423 int delim = zLine[h++];
7424 azArg[nArg++] = &zLine[h];
7425 while( zLine[h] && zLine[h]!=delim ){
7426 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7427 h++;
7429 if( zLine[h]==delim ){
7430 zLine[h++] = 0;
7432 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7433 }else{
7434 azArg[nArg++] = &zLine[h];
7435 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7436 if( zLine[h] ) zLine[h++] = 0;
7437 resolve_backslashes(azArg[nArg-1]);
7440 azArg[nArg] = 0;
7442 /* Process the input line.
7444 if( nArg==0 ) return 0; /* no tokens, no error */
7445 n = strlen30(azArg[0]);
7446 c = azArg[0][0];
7447 clearTempFile(p);
7449 #ifndef SQLITE_OMIT_AUTHORIZATION
7450 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7451 if( nArg!=2 ){
7452 raw_printf(stderr, "Usage: .auth ON|OFF\n");
7453 rc = 1;
7454 goto meta_command_exit;
7456 open_db(p, 0);
7457 if( booleanValue(azArg[1]) ){
7458 sqlite3_set_authorizer(p->db, shellAuth, p);
7459 }else{
7460 sqlite3_set_authorizer(p->db, 0, 0);
7462 }else
7463 #endif
7465 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7466 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7467 open_db(p, 0);
7468 rc = arDotCommand(p, 0, azArg, nArg);
7469 }else
7470 #endif
7472 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7473 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7475 const char *zDestFile = 0;
7476 const char *zDb = 0;
7477 sqlite3 *pDest;
7478 sqlite3_backup *pBackup;
7479 int j;
7480 int bAsync = 0;
7481 const char *zVfs = 0;
7482 for(j=1; j<nArg; j++){
7483 const char *z = azArg[j];
7484 if( z[0]=='-' ){
7485 if( z[1]=='-' ) z++;
7486 if( strcmp(z, "-append")==0 ){
7487 zVfs = "apndvfs";
7488 }else
7489 if( strcmp(z, "-async")==0 ){
7490 bAsync = 1;
7491 }else
7493 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7494 return 1;
7496 }else if( zDestFile==0 ){
7497 zDestFile = azArg[j];
7498 }else if( zDb==0 ){
7499 zDb = zDestFile;
7500 zDestFile = azArg[j];
7501 }else{
7502 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7503 return 1;
7506 if( zDestFile==0 ){
7507 raw_printf(stderr, "missing FILENAME argument on .backup\n");
7508 return 1;
7510 if( zDb==0 ) zDb = "main";
7511 rc = sqlite3_open_v2(zDestFile, &pDest,
7512 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7513 if( rc!=SQLITE_OK ){
7514 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7515 close_db(pDest);
7516 return 1;
7518 if( bAsync ){
7519 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7520 0, 0, 0);
7522 open_db(p, 0);
7523 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7524 if( pBackup==0 ){
7525 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7526 close_db(pDest);
7527 return 1;
7529 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7530 sqlite3_backup_finish(pBackup);
7531 if( rc==SQLITE_DONE ){
7532 rc = 0;
7533 }else{
7534 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7535 rc = 1;
7537 close_db(pDest);
7538 }else
7540 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7541 if( nArg==2 ){
7542 bail_on_error = booleanValue(azArg[1]);
7543 }else{
7544 raw_printf(stderr, "Usage: .bail on|off\n");
7545 rc = 1;
7547 }else
7549 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7550 if( nArg==2 ){
7551 if( booleanValue(azArg[1]) ){
7552 setBinaryMode(p->out, 1);
7553 }else{
7554 setTextMode(p->out, 1);
7556 }else{
7557 raw_printf(stderr, "Usage: .binary on|off\n");
7558 rc = 1;
7560 }else
7562 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7563 if( nArg==2 ){
7564 #if defined(_WIN32) || defined(WIN32)
7565 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7566 rc = !SetCurrentDirectoryW(z);
7567 sqlite3_free(z);
7568 #else
7569 rc = chdir(azArg[1]);
7570 #endif
7571 if( rc ){
7572 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7573 rc = 1;
7575 }else{
7576 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7577 rc = 1;
7579 }else
7581 /* The undocumented ".breakpoint" command causes a call to the no-op
7582 ** routine named test_breakpoint().
7584 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7585 test_breakpoint();
7586 }else
7588 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7589 if( nArg==2 ){
7590 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7591 }else{
7592 raw_printf(stderr, "Usage: .changes on|off\n");
7593 rc = 1;
7595 }else
7597 /* Cancel output redirection, if it is currently set (by .testcase)
7598 ** Then read the content of the testcase-out.txt file and compare against
7599 ** azArg[1]. If there are differences, report an error and exit.
7601 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7602 char *zRes = 0;
7603 output_reset(p);
7604 if( nArg!=2 ){
7605 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7606 rc = 2;
7607 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7608 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7609 rc = 2;
7610 }else if( testcase_glob(azArg[1],zRes)==0 ){
7611 utf8_printf(stderr,
7612 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
7613 p->zTestcase, azArg[1], zRes);
7614 rc = 1;
7615 }else{
7616 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7617 p->nCheck++;
7619 sqlite3_free(zRes);
7620 }else
7622 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7623 if( nArg==2 ){
7624 tryToClone(p, azArg[1]);
7625 }else{
7626 raw_printf(stderr, "Usage: .clone FILENAME\n");
7627 rc = 1;
7629 }else
7631 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7632 char **azName = 0;
7633 int nName = 0;
7634 sqlite3_stmt *pStmt;
7635 int i;
7636 open_db(p, 0);
7637 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7638 if( rc ){
7639 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7640 rc = 1;
7641 }else{
7642 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7643 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7644 const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7645 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7646 if( azName==0 ){ shell_out_of_memory(); /* Does not return */ }
7647 azName[nName*2] = strdup(zSchema);
7648 azName[nName*2+1] = strdup(zFile);
7649 nName++;
7652 sqlite3_finalize(pStmt);
7653 for(i=0; i<nName; i++){
7654 int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7655 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7656 const char *z = azName[i*2+1];
7657 utf8_printf(p->out, "%s: %s %s%s\n",
7658 azName[i*2],
7659 z && z[0] ? z : "\"\"",
7660 bRdonly ? "r/o" : "r/w",
7661 eTxn==SQLITE_TXN_NONE ? "" :
7662 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7663 free(azName[i*2]);
7664 free(azName[i*2+1]);
7666 sqlite3_free(azName);
7667 }else
7669 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7670 static const struct DbConfigChoices {
7671 const char *zName;
7672 int op;
7673 } aDbConfig[] = {
7674 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
7675 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
7676 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
7677 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
7678 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
7679 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
7680 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
7681 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7682 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
7683 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
7684 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7685 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
7686 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
7687 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
7688 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
7689 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
7691 int ii, v;
7692 open_db(p, 0);
7693 for(ii=0; ii<ArraySize(aDbConfig); ii++){
7694 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7695 if( nArg>=3 ){
7696 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7698 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7699 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7700 if( nArg>1 ) break;
7702 if( nArg>1 && ii==ArraySize(aDbConfig) ){
7703 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7704 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7706 }else
7708 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7709 rc = shell_dbinfo_command(p, nArg, azArg);
7710 }else
7712 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7713 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7714 open_db(p, 0);
7715 rc = recoverDatabaseCmd(p, nArg, azArg);
7716 }else
7717 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7719 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7720 char *zLike = 0;
7721 char *zSql;
7722 int i;
7723 int savedShowHeader = p->showHeader;
7724 int savedShellFlags = p->shellFlgs;
7725 ShellClearFlag(p,
7726 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7727 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7728 for(i=1; i<nArg; i++){
7729 if( azArg[i][0]=='-' ){
7730 const char *z = azArg[i]+1;
7731 if( z[0]=='-' ) z++;
7732 if( strcmp(z,"preserve-rowids")==0 ){
7733 #ifdef SQLITE_OMIT_VIRTUALTABLE
7734 raw_printf(stderr, "The --preserve-rowids option is not compatible"
7735 " with SQLITE_OMIT_VIRTUALTABLE\n");
7736 rc = 1;
7737 sqlite3_free(zLike);
7738 goto meta_command_exit;
7739 #else
7740 ShellSetFlag(p, SHFLG_PreserveRowid);
7741 #endif
7742 }else
7743 if( strcmp(z,"newlines")==0 ){
7744 ShellSetFlag(p, SHFLG_Newlines);
7745 }else
7746 if( strcmp(z,"data-only")==0 ){
7747 ShellSetFlag(p, SHFLG_DumpDataOnly);
7748 }else
7749 if( strcmp(z,"nosys")==0 ){
7750 ShellSetFlag(p, SHFLG_DumpNoSys);
7751 }else
7753 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7754 rc = 1;
7755 sqlite3_free(zLike);
7756 goto meta_command_exit;
7758 }else{
7759 /* azArg[i] contains a LIKE pattern. This ".dump" request should
7760 ** only dump data for tables for which either the table name matches
7761 ** the LIKE pattern, or the table appears to be a shadow table of
7762 ** a virtual table for which the name matches the LIKE pattern.
7764 char *zExpr = sqlite3_mprintf(
7765 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
7766 " SELECT 1 FROM sqlite_schema WHERE "
7767 " name LIKE %Q ESCAPE '\\' AND"
7768 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
7769 " substr(o.name, 1, length(name)+1) == (name||'_')"
7770 ")", azArg[i], azArg[i]
7773 if( zLike ){
7774 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
7775 }else{
7776 zLike = zExpr;
7781 open_db(p, 0);
7783 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7784 /* When playing back a "dump", the content might appear in an order
7785 ** which causes immediate foreign key constraints to be violated.
7786 ** So disable foreign-key constraint enforcement to prevent problems. */
7787 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7788 raw_printf(p->out, "BEGIN TRANSACTION;\n");
7790 p->writableSchema = 0;
7791 p->showHeader = 0;
7792 /* Set writable_schema=ON since doing so forces SQLite to initialize
7793 ** as much of the schema as it can even if the sqlite_schema table is
7794 ** corrupt. */
7795 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7796 p->nErr = 0;
7797 if( zLike==0 ) zLike = sqlite3_mprintf("true");
7798 zSql = sqlite3_mprintf(
7799 "SELECT name, type, sql FROM sqlite_schema AS o "
7800 "WHERE (%s) AND type=='table'"
7801 " AND sql NOT NULL"
7802 " ORDER BY tbl_name='sqlite_sequence', rowid",
7803 zLike
7805 run_schema_dump_query(p,zSql);
7806 sqlite3_free(zSql);
7807 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7808 zSql = sqlite3_mprintf(
7809 "SELECT sql FROM sqlite_schema AS o "
7810 "WHERE (%s) AND sql NOT NULL"
7811 " AND type IN ('index','trigger','view')",
7812 zLike
7814 run_table_dump_query(p, zSql);
7815 sqlite3_free(zSql);
7817 sqlite3_free(zLike);
7818 if( p->writableSchema ){
7819 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7820 p->writableSchema = 0;
7822 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7823 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
7824 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7825 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
7827 p->showHeader = savedShowHeader;
7828 p->shellFlgs = savedShellFlags;
7829 }else
7831 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7832 if( nArg==2 ){
7833 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7834 }else{
7835 raw_printf(stderr, "Usage: .echo on|off\n");
7836 rc = 1;
7838 }else
7840 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7841 if( nArg==2 ){
7842 p->autoEQPtest = 0;
7843 if( p->autoEQPtrace ){
7844 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7845 p->autoEQPtrace = 0;
7847 if( strcmp(azArg[1],"full")==0 ){
7848 p->autoEQP = AUTOEQP_full;
7849 }else if( strcmp(azArg[1],"trigger")==0 ){
7850 p->autoEQP = AUTOEQP_trigger;
7851 #ifdef SQLITE_DEBUG
7852 }else if( strcmp(azArg[1],"test")==0 ){
7853 p->autoEQP = AUTOEQP_on;
7854 p->autoEQPtest = 1;
7855 }else if( strcmp(azArg[1],"trace")==0 ){
7856 p->autoEQP = AUTOEQP_full;
7857 p->autoEQPtrace = 1;
7858 open_db(p, 0);
7859 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
7860 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7861 #endif
7862 }else{
7863 p->autoEQP = (u8)booleanValue(azArg[1]);
7865 }else{
7866 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
7867 rc = 1;
7869 }else
7871 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7872 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7873 rc = 2;
7874 }else
7876 /* The ".explain" command is automatic now. It is largely pointless. It
7877 ** retained purely for backwards compatibility */
7878 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7879 int val = 1;
7880 if( nArg>=2 ){
7881 if( strcmp(azArg[1],"auto")==0 ){
7882 val = 99;
7883 }else{
7884 val = booleanValue(azArg[1]);
7887 if( val==1 && p->mode!=MODE_Explain ){
7888 p->normalMode = p->mode;
7889 p->mode = MODE_Explain;
7890 p->autoExplain = 0;
7891 }else if( val==0 ){
7892 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7893 p->autoExplain = 0;
7894 }else if( val==99 ){
7895 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7896 p->autoExplain = 1;
7898 }else
7900 #ifndef SQLITE_OMIT_VIRTUALTABLE
7901 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7902 open_db(p, 0);
7903 expertDotCommand(p, azArg, nArg);
7904 }else
7905 #endif
7907 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
7908 static const struct {
7909 const char *zCtrlName; /* Name of a test-control option */
7910 int ctrlCode; /* Integer code for that option */
7911 const char *zUsage; /* Usage notes */
7912 } aCtrl[] = {
7913 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
7914 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
7915 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
7916 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
7917 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
7918 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
7919 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
7920 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
7921 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
7922 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
7923 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
7925 int filectrl = -1;
7926 int iCtrl = -1;
7927 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
7928 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
7929 int n2, i;
7930 const char *zCmd = 0;
7931 const char *zSchema = 0;
7933 open_db(p, 0);
7934 zCmd = nArg>=2 ? azArg[1] : "help";
7936 if( zCmd[0]=='-'
7937 && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
7938 && nArg>=4
7940 zSchema = azArg[2];
7941 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
7942 nArg -= 2;
7943 zCmd = azArg[1];
7946 /* The argument can optionally begin with "-" or "--" */
7947 if( zCmd[0]=='-' && zCmd[1] ){
7948 zCmd++;
7949 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7952 /* --help lists all file-controls */
7953 if( strcmp(zCmd,"help")==0 ){
7954 utf8_printf(p->out, "Available file-controls:\n");
7955 for(i=0; i<ArraySize(aCtrl); i++){
7956 utf8_printf(p->out, " .filectrl %s %s\n",
7957 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7959 rc = 1;
7960 goto meta_command_exit;
7963 /* convert filectrl text option to value. allow any unique prefix
7964 ** of the option name, or a numerical value. */
7965 n2 = strlen30(zCmd);
7966 for(i=0; i<ArraySize(aCtrl); i++){
7967 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7968 if( filectrl<0 ){
7969 filectrl = aCtrl[i].ctrlCode;
7970 iCtrl = i;
7971 }else{
7972 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
7973 "Use \".filectrl --help\" for help\n", zCmd);
7974 rc = 1;
7975 goto meta_command_exit;
7979 if( filectrl<0 ){
7980 utf8_printf(stderr,"Error: unknown file-control: %s\n"
7981 "Use \".filectrl --help\" for help\n", zCmd);
7982 }else{
7983 switch(filectrl){
7984 case SQLITE_FCNTL_SIZE_LIMIT: {
7985 if( nArg!=2 && nArg!=3 ) break;
7986 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
7987 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
7988 isOk = 1;
7989 break;
7991 case SQLITE_FCNTL_LOCK_TIMEOUT:
7992 case SQLITE_FCNTL_CHUNK_SIZE: {
7993 int x;
7994 if( nArg!=3 ) break;
7995 x = (int)integerValue(azArg[2]);
7996 sqlite3_file_control(p->db, zSchema, filectrl, &x);
7997 isOk = 2;
7998 break;
8000 case SQLITE_FCNTL_PERSIST_WAL:
8001 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8002 int x;
8003 if( nArg!=2 && nArg!=3 ) break;
8004 x = nArg==3 ? booleanValue(azArg[2]) : -1;
8005 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8006 iRes = x;
8007 isOk = 1;
8008 break;
8010 case SQLITE_FCNTL_DATA_VERSION:
8011 case SQLITE_FCNTL_HAS_MOVED: {
8012 int x;
8013 if( nArg!=2 ) break;
8014 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8015 iRes = x;
8016 isOk = 1;
8017 break;
8019 case SQLITE_FCNTL_TEMPFILENAME: {
8020 char *z = 0;
8021 if( nArg!=2 ) break;
8022 sqlite3_file_control(p->db, zSchema, filectrl, &z);
8023 if( z ){
8024 utf8_printf(p->out, "%s\n", z);
8025 sqlite3_free(z);
8027 isOk = 2;
8028 break;
8030 case SQLITE_FCNTL_RESERVE_BYTES: {
8031 int x;
8032 if( nArg>=3 ){
8033 x = atoi(azArg[2]);
8034 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8036 x = -1;
8037 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8038 utf8_printf(p->out,"%d\n", x);
8039 isOk = 2;
8040 break;
8044 if( isOk==0 && iCtrl>=0 ){
8045 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8046 rc = 1;
8047 }else if( isOk==1 ){
8048 char zBuf[100];
8049 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8050 raw_printf(p->out, "%s\n", zBuf);
8052 }else
8054 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8055 ShellState data;
8056 int doStats = 0;
8057 memcpy(&data, p, sizeof(data));
8058 data.showHeader = 0;
8059 data.cMode = data.mode = MODE_Semi;
8060 if( nArg==2 && optionMatch(azArg[1], "indent") ){
8061 data.cMode = data.mode = MODE_Pretty;
8062 nArg = 1;
8064 if( nArg!=1 ){
8065 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8066 rc = 1;
8067 goto meta_command_exit;
8069 open_db(p, 0);
8070 rc = sqlite3_exec(p->db,
8071 "SELECT sql FROM"
8072 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8073 " FROM sqlite_schema UNION ALL"
8074 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8075 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8076 "ORDER BY rowid",
8077 callback, &data, 0
8079 if( rc==SQLITE_OK ){
8080 sqlite3_stmt *pStmt;
8081 rc = sqlite3_prepare_v2(p->db,
8082 "SELECT rowid FROM sqlite_schema"
8083 " WHERE name GLOB 'sqlite_stat[134]'",
8084 -1, &pStmt, 0);
8085 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8086 sqlite3_finalize(pStmt);
8088 if( doStats==0 ){
8089 raw_printf(p->out, "/* No STAT tables available */\n");
8090 }else{
8091 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8092 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
8093 callback, &data, 0);
8094 data.cMode = data.mode = MODE_Insert;
8095 data.zDestTable = "sqlite_stat1";
8096 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8097 data.zDestTable = "sqlite_stat4";
8098 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8099 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8101 }else
8103 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8104 if( nArg==2 ){
8105 p->showHeader = booleanValue(azArg[1]);
8106 p->shellFlgs |= SHFLG_HeaderSet;
8107 }else{
8108 raw_printf(stderr, "Usage: .headers on|off\n");
8109 rc = 1;
8111 }else
8113 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8114 if( nArg>=2 ){
8115 n = showHelp(p->out, azArg[1]);
8116 if( n==0 ){
8117 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8119 }else{
8120 showHelp(p->out, 0);
8122 }else
8124 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8125 char *zTable = 0; /* Insert data into this table */
8126 char *zFile = 0; /* Name of file to extra content from */
8127 sqlite3_stmt *pStmt = NULL; /* A statement */
8128 int nCol; /* Number of columns in the table */
8129 int nByte; /* Number of bytes in an SQL string */
8130 int i, j; /* Loop counters */
8131 int needCommit; /* True to COMMIT or ROLLBACK at end */
8132 int nSep; /* Number of bytes in p->colSeparator[] */
8133 char *zSql; /* An SQL statement */
8134 ImportCtx sCtx; /* Reader context */
8135 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8136 int eVerbose = 0; /* Larger for more console output */
8137 int nSkip = 0; /* Initial lines to skip */
8138 int useOutputMode = 1; /* Use output mode to determine separators */
8140 memset(&sCtx, 0, sizeof(sCtx));
8141 if( p->mode==MODE_Ascii ){
8142 xRead = ascii_read_one_field;
8143 }else{
8144 xRead = csv_read_one_field;
8146 for(i=1; i<nArg; i++){
8147 char *z = azArg[i];
8148 if( z[0]=='-' && z[1]=='-' ) z++;
8149 if( z[0]!='-' ){
8150 if( zFile==0 ){
8151 zFile = z;
8152 }else if( zTable==0 ){
8153 zTable = z;
8154 }else{
8155 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
8156 showHelp(p->out, "import");
8157 rc = 1;
8158 goto meta_command_exit;
8160 }else if( strcmp(z,"-v")==0 ){
8161 eVerbose++;
8162 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8163 nSkip = integerValue(azArg[++i]);
8164 }else if( strcmp(z,"-ascii")==0 ){
8165 sCtx.cColSep = SEP_Unit[0];
8166 sCtx.cRowSep = SEP_Record[0];
8167 xRead = ascii_read_one_field;
8168 useOutputMode = 0;
8169 }else if( strcmp(z,"-csv")==0 ){
8170 sCtx.cColSep = ',';
8171 sCtx.cRowSep = '\n';
8172 xRead = csv_read_one_field;
8173 useOutputMode = 0;
8174 }else{
8175 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
8176 showHelp(p->out, "import");
8177 rc = 1;
8178 goto meta_command_exit;
8181 if( zTable==0 ){
8182 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8183 zFile==0 ? "FILE" : "TABLE");
8184 showHelp(p->out, "import");
8185 rc = 1;
8186 goto meta_command_exit;
8188 seenInterrupt = 0;
8189 open_db(p, 0);
8190 if( useOutputMode ){
8191 /* If neither the --csv or --ascii options are specified, then set
8192 ** the column and row separator characters from the output mode. */
8193 nSep = strlen30(p->colSeparator);
8194 if( nSep==0 ){
8195 raw_printf(stderr,
8196 "Error: non-null column separator required for import\n");
8197 rc = 1;
8198 goto meta_command_exit;
8200 if( nSep>1 ){
8201 raw_printf(stderr,
8202 "Error: multi-character column separators not allowed"
8203 " for import\n");
8204 rc = 1;
8205 goto meta_command_exit;
8207 nSep = strlen30(p->rowSeparator);
8208 if( nSep==0 ){
8209 raw_printf(stderr,
8210 "Error: non-null row separator required for import\n");
8211 rc = 1;
8212 goto meta_command_exit;
8214 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8215 /* When importing CSV (only), if the row separator is set to the
8216 ** default output row separator, change it to the default input
8217 ** row separator. This avoids having to maintain different input
8218 ** and output row separators. */
8219 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8220 nSep = strlen30(p->rowSeparator);
8222 if( nSep>1 ){
8223 raw_printf(stderr, "Error: multi-character row separators not allowed"
8224 " for import\n");
8225 rc = 1;
8226 goto meta_command_exit;
8228 sCtx.cColSep = p->colSeparator[0];
8229 sCtx.cRowSep = p->rowSeparator[0];
8231 sCtx.zFile = zFile;
8232 sCtx.nLine = 1;
8233 if( sCtx.zFile[0]=='|' ){
8234 #ifdef SQLITE_OMIT_POPEN
8235 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8236 rc = 1;
8237 goto meta_command_exit;
8238 #else
8239 sCtx.in = popen(sCtx.zFile+1, "r");
8240 sCtx.zFile = "<pipe>";
8241 sCtx.xCloser = pclose;
8242 #endif
8243 }else{
8244 sCtx.in = fopen(sCtx.zFile, "rb");
8245 sCtx.xCloser = fclose;
8247 if( sCtx.in==0 ){
8248 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8249 rc = 1;
8250 goto meta_command_exit;
8252 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8253 char zSep[2];
8254 zSep[1] = 0;
8255 zSep[0] = sCtx.cColSep;
8256 utf8_printf(p->out, "Column separator ");
8257 output_c_string(p->out, zSep);
8258 utf8_printf(p->out, ", row separator ");
8259 zSep[0] = sCtx.cRowSep;
8260 output_c_string(p->out, zSep);
8261 utf8_printf(p->out, "\n");
8263 while( (nSkip--)>0 ){
8264 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8266 zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
8267 if( zSql==0 ){
8268 import_cleanup(&sCtx);
8269 shell_out_of_memory();
8271 nByte = strlen30(zSql);
8272 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8273 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
8274 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8275 char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
8276 char cSep = '(';
8277 while( xRead(&sCtx) ){
8278 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
8279 cSep = ',';
8280 if( sCtx.cTerm!=sCtx.cColSep ) break;
8282 if( cSep=='(' ){
8283 sqlite3_free(zCreate);
8284 import_cleanup(&sCtx);
8285 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8286 rc = 1;
8287 goto meta_command_exit;
8289 zCreate = sqlite3_mprintf("%z\n)", zCreate);
8290 if( eVerbose>=1 ){
8291 utf8_printf(p->out, "%s\n", zCreate);
8293 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8294 sqlite3_free(zCreate);
8295 if( rc ){
8296 utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
8297 sqlite3_errmsg(p->db));
8298 import_cleanup(&sCtx);
8299 rc = 1;
8300 goto meta_command_exit;
8302 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8304 sqlite3_free(zSql);
8305 if( rc ){
8306 if (pStmt) sqlite3_finalize(pStmt);
8307 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8308 import_cleanup(&sCtx);
8309 rc = 1;
8310 goto meta_command_exit;
8312 nCol = sqlite3_column_count(pStmt);
8313 sqlite3_finalize(pStmt);
8314 pStmt = 0;
8315 if( nCol==0 ) return 0; /* no columns, no error */
8316 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8317 if( zSql==0 ){
8318 import_cleanup(&sCtx);
8319 shell_out_of_memory();
8321 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
8322 j = strlen30(zSql);
8323 for(i=1; i<nCol; i++){
8324 zSql[j++] = ',';
8325 zSql[j++] = '?';
8327 zSql[j++] = ')';
8328 zSql[j] = 0;
8329 if( eVerbose>=2 ){
8330 utf8_printf(p->out, "Insert using: %s\n", zSql);
8332 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8333 sqlite3_free(zSql);
8334 if( rc ){
8335 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8336 if (pStmt) sqlite3_finalize(pStmt);
8337 import_cleanup(&sCtx);
8338 rc = 1;
8339 goto meta_command_exit;
8341 needCommit = sqlite3_get_autocommit(p->db);
8342 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8344 int startLine = sCtx.nLine;
8345 for(i=0; i<nCol; i++){
8346 char *z = xRead(&sCtx);
8348 ** Did we reach end-of-file before finding any columns?
8349 ** If so, stop instead of NULL filling the remaining columns.
8351 if( z==0 && i==0 ) break;
8353 ** Did we reach end-of-file OR end-of-line before finding any
8354 ** columns in ASCII mode? If so, stop instead of NULL filling
8355 ** the remaining columns.
8357 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8358 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8359 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8360 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8361 "filling the rest with NULL\n",
8362 sCtx.zFile, startLine, nCol, i+1);
8363 i += 2;
8364 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8367 if( sCtx.cTerm==sCtx.cColSep ){
8369 xRead(&sCtx);
8370 i++;
8371 }while( sCtx.cTerm==sCtx.cColSep );
8372 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8373 "extras ignored\n",
8374 sCtx.zFile, startLine, nCol, i);
8376 if( i>=nCol ){
8377 sqlite3_step(pStmt);
8378 rc = sqlite3_reset(pStmt);
8379 if( rc!=SQLITE_OK ){
8380 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8381 startLine, sqlite3_errmsg(p->db));
8382 sCtx.nErr++;
8383 }else{
8384 sCtx.nRow++;
8387 }while( sCtx.cTerm!=EOF );
8389 import_cleanup(&sCtx);
8390 sqlite3_finalize(pStmt);
8391 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8392 if( eVerbose>0 ){
8393 utf8_printf(p->out,
8394 "Added %d rows with %d errors using %d lines of input\n",
8395 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8397 }else
8399 #ifndef SQLITE_UNTESTABLE
8400 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8401 char *zSql;
8402 char *zCollist = 0;
8403 sqlite3_stmt *pStmt;
8404 int tnum = 0;
8405 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
8406 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8407 int i;
8408 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8409 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8410 " .imposter off\n");
8411 /* Also allowed, but not documented:
8413 ** .imposter TABLE IMPOSTER
8415 ** where TABLE is a WITHOUT ROWID table. In that case, the
8416 ** imposter is another WITHOUT ROWID table with the columns in
8417 ** storage order. */
8418 rc = 1;
8419 goto meta_command_exit;
8421 open_db(p, 0);
8422 if( nArg==2 ){
8423 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8424 goto meta_command_exit;
8426 zSql = sqlite3_mprintf(
8427 "SELECT rootpage, 0 FROM sqlite_schema"
8428 " WHERE name='%q' AND type='index'"
8429 "UNION ALL "
8430 "SELECT rootpage, 1 FROM sqlite_schema"
8431 " WHERE name='%q' AND type='table'"
8432 " AND sql LIKE '%%without%%rowid%%'",
8433 azArg[1], azArg[1]
8435 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8436 sqlite3_free(zSql);
8437 if( sqlite3_step(pStmt)==SQLITE_ROW ){
8438 tnum = sqlite3_column_int(pStmt, 0);
8439 isWO = sqlite3_column_int(pStmt, 1);
8441 sqlite3_finalize(pStmt);
8442 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8443 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8444 sqlite3_free(zSql);
8445 i = 0;
8446 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8447 char zLabel[20];
8448 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8449 i++;
8450 if( zCol==0 ){
8451 if( sqlite3_column_int(pStmt,1)==-1 ){
8452 zCol = "_ROWID_";
8453 }else{
8454 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8455 zCol = zLabel;
8458 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8459 lenPK = (int)strlen(zCollist);
8461 if( zCollist==0 ){
8462 zCollist = sqlite3_mprintf("\"%w\"", zCol);
8463 }else{
8464 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8467 sqlite3_finalize(pStmt);
8468 if( i==0 || tnum==0 ){
8469 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8470 rc = 1;
8471 sqlite3_free(zCollist);
8472 goto meta_command_exit;
8474 if( lenPK==0 ) lenPK = 100000;
8475 zSql = sqlite3_mprintf(
8476 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8477 azArg[2], zCollist, lenPK, zCollist);
8478 sqlite3_free(zCollist);
8479 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8480 if( rc==SQLITE_OK ){
8481 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8482 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8483 if( rc ){
8484 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8485 }else{
8486 utf8_printf(stdout, "%s;\n", zSql);
8487 raw_printf(stdout,
8488 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8489 azArg[1], isWO ? "table" : "index"
8492 }else{
8493 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8494 rc = 1;
8496 sqlite3_free(zSql);
8497 }else
8498 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8500 #ifdef SQLITE_ENABLE_IOTRACE
8501 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8502 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8503 if( iotrace && iotrace!=stdout ) fclose(iotrace);
8504 iotrace = 0;
8505 if( nArg<2 ){
8506 sqlite3IoTrace = 0;
8507 }else if( strcmp(azArg[1], "-")==0 ){
8508 sqlite3IoTrace = iotracePrintf;
8509 iotrace = stdout;
8510 }else{
8511 iotrace = fopen(azArg[1], "w");
8512 if( iotrace==0 ){
8513 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8514 sqlite3IoTrace = 0;
8515 rc = 1;
8516 }else{
8517 sqlite3IoTrace = iotracePrintf;
8520 }else
8521 #endif
8523 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8524 static const struct {
8525 const char *zLimitName; /* Name of a limit */
8526 int limitCode; /* Integer code for that limit */
8527 } aLimit[] = {
8528 { "length", SQLITE_LIMIT_LENGTH },
8529 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
8530 { "column", SQLITE_LIMIT_COLUMN },
8531 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
8532 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
8533 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
8534 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
8535 { "attached", SQLITE_LIMIT_ATTACHED },
8536 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
8537 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
8538 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
8539 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
8541 int i, n2;
8542 open_db(p, 0);
8543 if( nArg==1 ){
8544 for(i=0; i<ArraySize(aLimit); i++){
8545 printf("%20s %d\n", aLimit[i].zLimitName,
8546 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8548 }else if( nArg>3 ){
8549 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8550 rc = 1;
8551 goto meta_command_exit;
8552 }else{
8553 int iLimit = -1;
8554 n2 = strlen30(azArg[1]);
8555 for(i=0; i<ArraySize(aLimit); i++){
8556 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8557 if( iLimit<0 ){
8558 iLimit = i;
8559 }else{
8560 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8561 rc = 1;
8562 goto meta_command_exit;
8566 if( iLimit<0 ){
8567 utf8_printf(stderr, "unknown limit: \"%s\"\n"
8568 "enter \".limits\" with no arguments for a list.\n",
8569 azArg[1]);
8570 rc = 1;
8571 goto meta_command_exit;
8573 if( nArg==3 ){
8574 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8575 (int)integerValue(azArg[2]));
8577 printf("%20s %d\n", aLimit[iLimit].zLimitName,
8578 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8580 }else
8582 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8583 open_db(p, 0);
8584 lintDotCommand(p, azArg, nArg);
8585 }else
8587 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8588 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8589 const char *zFile, *zProc;
8590 char *zErrMsg = 0;
8591 if( nArg<2 ){
8592 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8593 rc = 1;
8594 goto meta_command_exit;
8596 zFile = azArg[1];
8597 zProc = nArg>=3 ? azArg[2] : 0;
8598 open_db(p, 0);
8599 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8600 if( rc!=SQLITE_OK ){
8601 utf8_printf(stderr, "Error: %s\n", zErrMsg);
8602 sqlite3_free(zErrMsg);
8603 rc = 1;
8605 }else
8606 #endif
8608 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8609 if( nArg!=2 ){
8610 raw_printf(stderr, "Usage: .log FILENAME\n");
8611 rc = 1;
8612 }else{
8613 const char *zFile = azArg[1];
8614 output_file_close(p->pLog);
8615 p->pLog = output_file_open(zFile, 0);
8617 }else
8619 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8620 const char *zMode = nArg>=2 ? azArg[1] : "";
8621 int n2 = strlen30(zMode);
8622 int c2 = zMode[0];
8623 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8624 p->mode = MODE_Line;
8625 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8626 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8627 p->mode = MODE_Column;
8628 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8629 p->showHeader = 1;
8631 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8632 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8633 p->mode = MODE_List;
8634 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8635 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8636 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8637 p->mode = MODE_Html;
8638 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8639 p->mode = MODE_Tcl;
8640 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8641 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8642 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8643 p->mode = MODE_Csv;
8644 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8645 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8646 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8647 p->mode = MODE_List;
8648 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8649 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8650 p->mode = MODE_Insert;
8651 set_table_name(p, nArg>=3 ? azArg[2] : "table");
8652 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8653 p->mode = MODE_Quote;
8654 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8655 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8656 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8657 p->mode = MODE_Ascii;
8658 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8659 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8660 }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
8661 p->mode = MODE_Markdown;
8662 }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
8663 p->mode = MODE_Table;
8664 }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
8665 p->mode = MODE_Box;
8666 }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
8667 p->mode = MODE_Json;
8668 }else if( nArg==1 ){
8669 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8670 }else{
8671 raw_printf(stderr, "Error: mode should be one of: "
8672 "ascii box column csv html insert json line list markdown "
8673 "quote table tabs tcl\n");
8674 rc = 1;
8676 p->cMode = p->mode;
8677 }else
8679 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8680 if( nArg==2 ){
8681 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8682 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8683 }else{
8684 raw_printf(stderr, "Usage: .nullvalue STRING\n");
8685 rc = 1;
8687 }else
8689 #ifdef SQLITE_DEBUG
8690 if( c=='o' && strcmp(azArg[0],"oom")==0 ){
8691 int i;
8692 for(i=1; i<nArg; i++){
8693 const char *z = azArg[i];
8694 if( z[0]=='-' && z[1]=='-' ) z++;
8695 if( strcmp(z,"-repeat")==0 ){
8696 if( i==nArg-1 ){
8697 raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
8698 rc = 1;
8699 }else{
8700 oomRepeat = (int)integerValue(azArg[++i]);
8702 }else if( IsDigit(z[0]) ){
8703 oomCounter = (int)integerValue(azArg[i]);
8704 }else{
8705 raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
8706 raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
8707 rc = 1;
8710 if( rc==0 ){
8711 raw_printf(p->out, "oomCounter = %d\n", oomCounter);
8712 raw_printf(p->out, "oomRepeat = %d\n", oomRepeat);
8714 }else
8715 #endif /* SQLITE_DEBUG */
8717 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8718 char *zNewFilename = 0; /* Name of the database file to open */
8719 int iName = 1; /* Index in azArg[] of the filename */
8720 int newFlag = 0; /* True to delete file before opening */
8721 /* Close the existing database */
8722 session_close_all(p);
8723 close_db(p->db);
8724 p->db = 0;
8725 p->zDbFilename = 0;
8726 sqlite3_free(p->zFreeOnClose);
8727 p->zFreeOnClose = 0;
8728 p->openMode = SHELL_OPEN_UNSPEC;
8729 p->openFlags = 0;
8730 p->szMax = 0;
8731 /* Check for command-line arguments */
8732 for(iName=1; iName<nArg; iName++){
8733 const char *z = azArg[iName];
8734 if( optionMatch(z,"new") ){
8735 newFlag = 1;
8736 #ifdef SQLITE_HAVE_ZLIB
8737 }else if( optionMatch(z, "zip") ){
8738 p->openMode = SHELL_OPEN_ZIPFILE;
8739 #endif
8740 }else if( optionMatch(z, "append") ){
8741 p->openMode = SHELL_OPEN_APPENDVFS;
8742 }else if( optionMatch(z, "readonly") ){
8743 p->openMode = SHELL_OPEN_READONLY;
8744 }else if( optionMatch(z, "nofollow") ){
8745 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
8746 #ifndef SQLITE_OMIT_DESERIALIZE
8747 }else if( optionMatch(z, "deserialize") ){
8748 p->openMode = SHELL_OPEN_DESERIALIZE;
8749 }else if( optionMatch(z, "hexdb") ){
8750 p->openMode = SHELL_OPEN_HEXDB;
8751 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
8752 p->szMax = integerValue(azArg[++iName]);
8753 #endif /* SQLITE_OMIT_DESERIALIZE */
8754 }else if( z[0]=='-' ){
8755 utf8_printf(stderr, "unknown option: %s\n", z);
8756 rc = 1;
8757 goto meta_command_exit;
8758 }else if( zNewFilename ){
8759 utf8_printf(stderr, "extra argument: \"%s\"\n", z);
8760 rc = 1;
8761 goto meta_command_exit;
8762 }else{
8763 zNewFilename = sqlite3_mprintf("%s", z);
8766 /* If a filename is specified, try to open it first */
8767 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
8768 if( newFlag ) shellDeleteFile(zNewFilename);
8769 p->zDbFilename = zNewFilename;
8770 open_db(p, OPEN_DB_KEEPALIVE);
8771 if( p->db==0 ){
8772 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
8773 sqlite3_free(zNewFilename);
8774 }else{
8775 p->zFreeOnClose = zNewFilename;
8778 if( p->db==0 ){
8779 /* As a fall-back open a TEMP database */
8780 p->zDbFilename = 0;
8781 open_db(p, 0);
8783 }else
8785 if( (c=='o'
8786 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
8787 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
8789 char *zFile = 0;
8790 int bTxtMode = 0;
8791 int i;
8792 int eMode = 0;
8793 int bBOM = 0;
8794 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
8796 if( c=='e' ){
8797 eMode = 'x';
8798 bOnce = 2;
8799 }else if( strncmp(azArg[0],"once",n)==0 ){
8800 bOnce = 1;
8802 for(i=1; i<nArg; i++){
8803 char *z = azArg[i];
8804 if( z[0]=='-' ){
8805 if( z[1]=='-' ) z++;
8806 if( strcmp(z,"-bom")==0 ){
8807 bBOM = 1;
8808 }else if( c!='e' && strcmp(z,"-x")==0 ){
8809 eMode = 'x'; /* spreadsheet */
8810 }else if( c!='e' && strcmp(z,"-e")==0 ){
8811 eMode = 'e'; /* text editor */
8812 }else{
8813 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
8814 azArg[i]);
8815 showHelp(p->out, azArg[0]);
8816 rc = 1;
8817 goto meta_command_exit;
8819 }else if( zFile==0 && eMode!='e' && eMode!='x' ){
8820 zFile = sqlite3_mprintf("%s", z);
8821 if( zFile[0]=='|' ){
8822 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
8823 break;
8825 }else{
8826 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
8827 azArg[i]);
8828 showHelp(p->out, azArg[0]);
8829 rc = 1;
8830 sqlite3_free(zFile);
8831 goto meta_command_exit;
8834 if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
8835 if( bOnce ){
8836 p->outCount = 2;
8837 }else{
8838 p->outCount = 0;
8840 output_reset(p);
8841 #ifndef SQLITE_NOHAVE_SYSTEM
8842 if( eMode=='e' || eMode=='x' ){
8843 p->doXdgOpen = 1;
8844 outputModePush(p);
8845 if( eMode=='x' ){
8846 /* spreadsheet mode. Output as CSV. */
8847 newTempFile(p, "csv");
8848 ShellClearFlag(p, SHFLG_Echo);
8849 p->mode = MODE_Csv;
8850 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8851 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8852 }else{
8853 /* text editor mode */
8854 newTempFile(p, "txt");
8855 bTxtMode = 1;
8857 sqlite3_free(zFile);
8858 zFile = sqlite3_mprintf("%s", p->zTempFile);
8860 #endif /* SQLITE_NOHAVE_SYSTEM */
8861 if( zFile[0]=='|' ){
8862 #ifdef SQLITE_OMIT_POPEN
8863 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8864 rc = 1;
8865 p->out = stdout;
8866 #else
8867 p->out = popen(zFile + 1, "w");
8868 if( p->out==0 ){
8869 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
8870 p->out = stdout;
8871 rc = 1;
8872 }else{
8873 if( bBOM ) fprintf(p->out,"\357\273\277");
8874 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8876 #endif
8877 }else{
8878 p->out = output_file_open(zFile, bTxtMode);
8879 if( p->out==0 ){
8880 if( strcmp(zFile,"off")!=0 ){
8881 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
8883 p->out = stdout;
8884 rc = 1;
8885 } else {
8886 if( bBOM ) fprintf(p->out,"\357\273\277");
8887 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8890 sqlite3_free(zFile);
8891 }else
8893 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
8894 open_db(p,0);
8895 if( nArg<=1 ) goto parameter_syntax_error;
8897 /* .parameter clear
8898 ** Clear all bind parameters by dropping the TEMP table that holds them.
8900 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
8901 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
8902 0, 0, 0);
8903 }else
8905 /* .parameter list
8906 ** List all bind parameters.
8908 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
8909 sqlite3_stmt *pStmt = 0;
8910 int rx;
8911 int len = 0;
8912 rx = sqlite3_prepare_v2(p->db,
8913 "SELECT max(length(key)) "
8914 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8915 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8916 len = sqlite3_column_int(pStmt, 0);
8917 if( len>40 ) len = 40;
8919 sqlite3_finalize(pStmt);
8920 pStmt = 0;
8921 if( len ){
8922 rx = sqlite3_prepare_v2(p->db,
8923 "SELECT key, quote(value) "
8924 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8925 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8926 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
8927 sqlite3_column_text(pStmt,1));
8929 sqlite3_finalize(pStmt);
8931 }else
8933 /* .parameter init
8934 ** Make sure the TEMP table used to hold bind parameters exists.
8935 ** Create it if necessary.
8937 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
8938 bind_table_init(p);
8939 }else
8941 /* .parameter set NAME VALUE
8942 ** Set or reset a bind parameter. NAME should be the full parameter
8943 ** name exactly as it appears in the query. (ex: $abc, @def). The
8944 ** VALUE can be in either SQL literal notation, or if not it will be
8945 ** understood to be a text string.
8947 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
8948 int rx;
8949 char *zSql;
8950 sqlite3_stmt *pStmt;
8951 const char *zKey = azArg[2];
8952 const char *zValue = azArg[3];
8953 bind_table_init(p);
8954 zSql = sqlite3_mprintf(
8955 "REPLACE INTO temp.sqlite_parameters(key,value)"
8956 "VALUES(%Q,%s);", zKey, zValue);
8957 if( zSql==0 ) shell_out_of_memory();
8958 pStmt = 0;
8959 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8960 sqlite3_free(zSql);
8961 if( rx!=SQLITE_OK ){
8962 sqlite3_finalize(pStmt);
8963 pStmt = 0;
8964 zSql = sqlite3_mprintf(
8965 "REPLACE INTO temp.sqlite_parameters(key,value)"
8966 "VALUES(%Q,%Q);", zKey, zValue);
8967 if( zSql==0 ) shell_out_of_memory();
8968 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8969 sqlite3_free(zSql);
8970 if( rx!=SQLITE_OK ){
8971 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
8972 sqlite3_finalize(pStmt);
8973 pStmt = 0;
8974 rc = 1;
8977 sqlite3_step(pStmt);
8978 sqlite3_finalize(pStmt);
8979 }else
8981 /* .parameter unset NAME
8982 ** Remove the NAME binding from the parameter binding table, if it
8983 ** exists.
8985 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
8986 char *zSql = sqlite3_mprintf(
8987 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
8988 if( zSql==0 ) shell_out_of_memory();
8989 sqlite3_exec(p->db, zSql, 0, 0, 0);
8990 sqlite3_free(zSql);
8991 }else
8992 /* If no command name matches, show a syntax error */
8993 parameter_syntax_error:
8994 showHelp(p->out, "parameter");
8995 }else
8997 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
8998 int i;
8999 for(i=1; i<nArg; i++){
9000 if( i>1 ) raw_printf(p->out, " ");
9001 utf8_printf(p->out, "%s", azArg[i]);
9003 raw_printf(p->out, "\n");
9004 }else
9006 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9007 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9008 int i;
9009 int nn = 0;
9010 p->flgProgress = 0;
9011 p->mxProgress = 0;
9012 p->nProgress = 0;
9013 for(i=1; i<nArg; i++){
9014 const char *z = azArg[i];
9015 if( z[0]=='-' ){
9016 z++;
9017 if( z[0]=='-' ) z++;
9018 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9019 p->flgProgress |= SHELL_PROGRESS_QUIET;
9020 continue;
9022 if( strcmp(z,"reset")==0 ){
9023 p->flgProgress |= SHELL_PROGRESS_RESET;
9024 continue;
9026 if( strcmp(z,"once")==0 ){
9027 p->flgProgress |= SHELL_PROGRESS_ONCE;
9028 continue;
9030 if( strcmp(z,"limit")==0 ){
9031 if( i+1>=nArg ){
9032 utf8_printf(stderr, "Error: missing argument on --limit\n");
9033 rc = 1;
9034 goto meta_command_exit;
9035 }else{
9036 p->mxProgress = (int)integerValue(azArg[++i]);
9038 continue;
9040 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9041 rc = 1;
9042 goto meta_command_exit;
9043 }else{
9044 nn = (int)integerValue(z);
9047 open_db(p, 0);
9048 sqlite3_progress_handler(p->db, nn, progress_handler, p);
9049 }else
9050 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9052 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9053 if( nArg >= 2) {
9054 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9056 if( nArg >= 3) {
9057 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9059 }else
9061 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9062 rc = 2;
9063 }else
9065 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9066 FILE *inSaved = p->in;
9067 int savedLineno = p->lineno;
9068 if( nArg!=2 ){
9069 raw_printf(stderr, "Usage: .read FILE\n");
9070 rc = 1;
9071 goto meta_command_exit;
9073 if( azArg[1][0]=='|' ){
9074 #ifdef SQLITE_OMIT_POPEN
9075 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9076 rc = 1;
9077 p->out = stdout;
9078 #else
9079 p->in = popen(azArg[1]+1, "r");
9080 if( p->in==0 ){
9081 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9082 rc = 1;
9083 }else{
9084 rc = process_input(p);
9085 pclose(p->in);
9087 #endif
9088 }else if( notNormalFile(azArg[1]) || (p->in = fopen(azArg[1], "rb"))==0 ){
9089 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9090 rc = 1;
9091 }else{
9092 rc = process_input(p);
9093 fclose(p->in);
9095 p->in = inSaved;
9096 p->lineno = savedLineno;
9097 }else
9099 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9100 const char *zSrcFile;
9101 const char *zDb;
9102 sqlite3 *pSrc;
9103 sqlite3_backup *pBackup;
9104 int nTimeout = 0;
9106 if( nArg==2 ){
9107 zSrcFile = azArg[1];
9108 zDb = "main";
9109 }else if( nArg==3 ){
9110 zSrcFile = azArg[2];
9111 zDb = azArg[1];
9112 }else{
9113 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9114 rc = 1;
9115 goto meta_command_exit;
9117 rc = sqlite3_open(zSrcFile, &pSrc);
9118 if( rc!=SQLITE_OK ){
9119 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9120 close_db(pSrc);
9121 return 1;
9123 open_db(p, 0);
9124 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9125 if( pBackup==0 ){
9126 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9127 close_db(pSrc);
9128 return 1;
9130 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9131 || rc==SQLITE_BUSY ){
9132 if( rc==SQLITE_BUSY ){
9133 if( nTimeout++ >= 3 ) break;
9134 sqlite3_sleep(100);
9137 sqlite3_backup_finish(pBackup);
9138 if( rc==SQLITE_DONE ){
9139 rc = 0;
9140 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9141 raw_printf(stderr, "Error: source database is busy\n");
9142 rc = 1;
9143 }else{
9144 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9145 rc = 1;
9147 close_db(pSrc);
9148 }else
9150 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9151 if( nArg==2 ){
9152 p->scanstatsOn = (u8)booleanValue(azArg[1]);
9153 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9154 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9155 #endif
9156 }else{
9157 raw_printf(stderr, "Usage: .scanstats on|off\n");
9158 rc = 1;
9160 }else
9162 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9163 ShellText sSelect;
9164 ShellState data;
9165 char *zErrMsg = 0;
9166 const char *zDiv = "(";
9167 const char *zName = 0;
9168 int iSchema = 0;
9169 int bDebug = 0;
9170 int bNoSystemTabs = 0;
9171 int ii;
9173 open_db(p, 0);
9174 memcpy(&data, p, sizeof(data));
9175 data.showHeader = 0;
9176 data.cMode = data.mode = MODE_Semi;
9177 initText(&sSelect);
9178 for(ii=1; ii<nArg; ii++){
9179 if( optionMatch(azArg[ii],"indent") ){
9180 data.cMode = data.mode = MODE_Pretty;
9181 }else if( optionMatch(azArg[ii],"debug") ){
9182 bDebug = 1;
9183 }else if( optionMatch(azArg[ii],"nosys") ){
9184 bNoSystemTabs = 1;
9185 }else if( azArg[ii][0]=='-' ){
9186 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9187 rc = 1;
9188 goto meta_command_exit;
9189 }else if( zName==0 ){
9190 zName = azArg[ii];
9191 }else{
9192 raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9193 rc = 1;
9194 goto meta_command_exit;
9197 if( zName!=0 ){
9198 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9199 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9200 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9201 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9202 if( isSchema ){
9203 char *new_argv[2], *new_colv[2];
9204 new_argv[0] = sqlite3_mprintf(
9205 "CREATE TABLE %s (\n"
9206 " type text,\n"
9207 " name text,\n"
9208 " tbl_name text,\n"
9209 " rootpage integer,\n"
9210 " sql text\n"
9211 ")", zName);
9212 new_argv[1] = 0;
9213 new_colv[0] = "sql";
9214 new_colv[1] = 0;
9215 callback(&data, 1, new_argv, new_colv);
9216 sqlite3_free(new_argv[0]);
9219 if( zDiv ){
9220 sqlite3_stmt *pStmt = 0;
9221 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9222 -1, &pStmt, 0);
9223 if( rc ){
9224 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9225 sqlite3_finalize(pStmt);
9226 rc = 1;
9227 goto meta_command_exit;
9229 appendText(&sSelect, "SELECT sql FROM", 0);
9230 iSchema = 0;
9231 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9232 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9233 char zScNum[30];
9234 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9235 appendText(&sSelect, zDiv, 0);
9236 zDiv = " UNION ALL ";
9237 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9238 if( sqlite3_stricmp(zDb, "main")!=0 ){
9239 appendText(&sSelect, zDb, '\'');
9240 }else{
9241 appendText(&sSelect, "NULL", 0);
9243 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9244 appendText(&sSelect, zScNum, 0);
9245 appendText(&sSelect, " AS snum, ", 0);
9246 appendText(&sSelect, zDb, '\'');
9247 appendText(&sSelect, " AS sname FROM ", 0);
9248 appendText(&sSelect, zDb, quoteChar(zDb));
9249 appendText(&sSelect, ".sqlite_schema", 0);
9251 sqlite3_finalize(pStmt);
9252 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9253 if( zName ){
9254 appendText(&sSelect,
9255 " UNION ALL SELECT shell_module_schema(name),"
9256 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9259 #endif
9260 appendText(&sSelect, ") WHERE ", 0);
9261 if( zName ){
9262 char *zQarg = sqlite3_mprintf("%Q", zName);
9263 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9264 strchr(zName, '[') != 0;
9265 if( strchr(zName, '.') ){
9266 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9267 }else{
9268 appendText(&sSelect, "lower(tbl_name)", 0);
9270 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9271 appendText(&sSelect, zQarg, 0);
9272 if( !bGlob ){
9273 appendText(&sSelect, " ESCAPE '\\' ", 0);
9275 appendText(&sSelect, " AND ", 0);
9276 sqlite3_free(zQarg);
9278 if( bNoSystemTabs ){
9279 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9281 appendText(&sSelect, "sql IS NOT NULL"
9282 " ORDER BY snum, rowid", 0);
9283 if( bDebug ){
9284 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9285 }else{
9286 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9288 freeText(&sSelect);
9290 if( zErrMsg ){
9291 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9292 sqlite3_free(zErrMsg);
9293 rc = 1;
9294 }else if( rc != SQLITE_OK ){
9295 raw_printf(stderr,"Error: querying schema information\n");
9296 rc = 1;
9297 }else{
9298 rc = 0;
9300 }else
9302 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9303 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9304 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9305 }else
9307 #if defined(SQLITE_ENABLE_SESSION)
9308 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9309 OpenSession *pSession = &p->aSession[0];
9310 char **azCmd = &azArg[1];
9311 int iSes = 0;
9312 int nCmd = nArg - 1;
9313 int i;
9314 if( nArg<=1 ) goto session_syntax_error;
9315 open_db(p, 0);
9316 if( nArg>=3 ){
9317 for(iSes=0; iSes<p->nSession; iSes++){
9318 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
9320 if( iSes<p->nSession ){
9321 pSession = &p->aSession[iSes];
9322 azCmd++;
9323 nCmd--;
9324 }else{
9325 pSession = &p->aSession[0];
9326 iSes = 0;
9330 /* .session attach TABLE
9331 ** Invoke the sqlite3session_attach() interface to attach a particular
9332 ** table so that it is never filtered.
9334 if( strcmp(azCmd[0],"attach")==0 ){
9335 if( nCmd!=2 ) goto session_syntax_error;
9336 if( pSession->p==0 ){
9337 session_not_open:
9338 raw_printf(stderr, "ERROR: No sessions are open\n");
9339 }else{
9340 rc = sqlite3session_attach(pSession->p, azCmd[1]);
9341 if( rc ){
9342 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9343 rc = 0;
9346 }else
9348 /* .session changeset FILE
9349 ** .session patchset FILE
9350 ** Write a changeset or patchset into a file. The file is overwritten.
9352 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9353 FILE *out = 0;
9354 if( nCmd!=2 ) goto session_syntax_error;
9355 if( pSession->p==0 ) goto session_not_open;
9356 out = fopen(azCmd[1], "wb");
9357 if( out==0 ){
9358 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9359 azCmd[1]);
9360 }else{
9361 int szChng;
9362 void *pChng;
9363 if( azCmd[0][0]=='c' ){
9364 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9365 }else{
9366 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9368 if( rc ){
9369 printf("Error: error code %d\n", rc);
9370 rc = 0;
9372 if( pChng
9373 && fwrite(pChng, szChng, 1, out)!=1 ){
9374 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9375 szChng);
9377 sqlite3_free(pChng);
9378 fclose(out);
9380 }else
9382 /* .session close
9383 ** Close the identified session
9385 if( strcmp(azCmd[0], "close")==0 ){
9386 if( nCmd!=1 ) goto session_syntax_error;
9387 if( p->nSession ){
9388 session_close(pSession);
9389 p->aSession[iSes] = p->aSession[--p->nSession];
9391 }else
9393 /* .session enable ?BOOLEAN?
9394 ** Query or set the enable flag
9396 if( strcmp(azCmd[0], "enable")==0 ){
9397 int ii;
9398 if( nCmd>2 ) goto session_syntax_error;
9399 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9400 if( p->nSession ){
9401 ii = sqlite3session_enable(pSession->p, ii);
9402 utf8_printf(p->out, "session %s enable flag = %d\n",
9403 pSession->zName, ii);
9405 }else
9407 /* .session filter GLOB ....
9408 ** Set a list of GLOB patterns of table names to be excluded.
9410 if( strcmp(azCmd[0], "filter")==0 ){
9411 int ii, nByte;
9412 if( nCmd<2 ) goto session_syntax_error;
9413 if( p->nSession ){
9414 for(ii=0; ii<pSession->nFilter; ii++){
9415 sqlite3_free(pSession->azFilter[ii]);
9417 sqlite3_free(pSession->azFilter);
9418 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9419 pSession->azFilter = sqlite3_malloc( nByte );
9420 if( pSession->azFilter==0 ){
9421 raw_printf(stderr, "Error: out or memory\n");
9422 exit(1);
9424 for(ii=1; ii<nCmd; ii++){
9425 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9427 pSession->nFilter = ii-1;
9429 }else
9431 /* .session indirect ?BOOLEAN?
9432 ** Query or set the indirect flag
9434 if( strcmp(azCmd[0], "indirect")==0 ){
9435 int ii;
9436 if( nCmd>2 ) goto session_syntax_error;
9437 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9438 if( p->nSession ){
9439 ii = sqlite3session_indirect(pSession->p, ii);
9440 utf8_printf(p->out, "session %s indirect flag = %d\n",
9441 pSession->zName, ii);
9443 }else
9445 /* .session isempty
9446 ** Determine if the session is empty
9448 if( strcmp(azCmd[0], "isempty")==0 ){
9449 int ii;
9450 if( nCmd!=1 ) goto session_syntax_error;
9451 if( p->nSession ){
9452 ii = sqlite3session_isempty(pSession->p);
9453 utf8_printf(p->out, "session %s isempty flag = %d\n",
9454 pSession->zName, ii);
9456 }else
9458 /* .session list
9459 ** List all currently open sessions
9461 if( strcmp(azCmd[0],"list")==0 ){
9462 for(i=0; i<p->nSession; i++){
9463 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
9465 }else
9467 /* .session open DB NAME
9468 ** Open a new session called NAME on the attached database DB.
9469 ** DB is normally "main".
9471 if( strcmp(azCmd[0],"open")==0 ){
9472 char *zName;
9473 if( nCmd!=3 ) goto session_syntax_error;
9474 zName = azCmd[2];
9475 if( zName[0]==0 ) goto session_syntax_error;
9476 for(i=0; i<p->nSession; i++){
9477 if( strcmp(p->aSession[i].zName,zName)==0 ){
9478 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9479 goto meta_command_exit;
9482 if( p->nSession>=ArraySize(p->aSession) ){
9483 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
9484 goto meta_command_exit;
9486 pSession = &p->aSession[p->nSession];
9487 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9488 if( rc ){
9489 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9490 rc = 0;
9491 goto meta_command_exit;
9493 pSession->nFilter = 0;
9494 sqlite3session_table_filter(pSession->p, session_filter, pSession);
9495 p->nSession++;
9496 pSession->zName = sqlite3_mprintf("%s", zName);
9497 }else
9498 /* If no command name matches, show a syntax error */
9499 session_syntax_error:
9500 showHelp(p->out, "session");
9501 }else
9502 #endif
9504 #ifdef SQLITE_DEBUG
9505 /* Undocumented commands for internal testing. Subject to change
9506 ** without notice. */
9507 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9508 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9509 int i, v;
9510 for(i=1; i<nArg; i++){
9511 v = booleanValue(azArg[i]);
9512 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9515 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9516 int i; sqlite3_int64 v;
9517 for(i=1; i<nArg; i++){
9518 char zBuf[200];
9519 v = integerValue(azArg[i]);
9520 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9521 utf8_printf(p->out, "%s", zBuf);
9524 }else
9525 #endif
9527 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9528 int bIsInit = 0; /* True to initialize the SELFTEST table */
9529 int bVerbose = 0; /* Verbose output */
9530 int bSelftestExists; /* True if SELFTEST already exists */
9531 int i, k; /* Loop counters */
9532 int nTest = 0; /* Number of tests runs */
9533 int nErr = 0; /* Number of errors seen */
9534 ShellText str; /* Answer for a query */
9535 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9537 open_db(p,0);
9538 for(i=1; i<nArg; i++){
9539 const char *z = azArg[i];
9540 if( z[0]=='-' && z[1]=='-' ) z++;
9541 if( strcmp(z,"-init")==0 ){
9542 bIsInit = 1;
9543 }else
9544 if( strcmp(z,"-v")==0 ){
9545 bVerbose++;
9546 }else
9548 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9549 azArg[i], azArg[0]);
9550 raw_printf(stderr, "Should be one of: --init -v\n");
9551 rc = 1;
9552 goto meta_command_exit;
9555 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9556 != SQLITE_OK ){
9557 bSelftestExists = 0;
9558 }else{
9559 bSelftestExists = 1;
9561 if( bIsInit ){
9562 createSelftestTable(p);
9563 bSelftestExists = 1;
9565 initText(&str);
9566 appendText(&str, "x", 0);
9567 for(k=bSelftestExists; k>=0; k--){
9568 if( k==1 ){
9569 rc = sqlite3_prepare_v2(p->db,
9570 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9571 -1, &pStmt, 0);
9572 }else{
9573 rc = sqlite3_prepare_v2(p->db,
9574 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9575 " (1,'run','PRAGMA integrity_check','ok')",
9576 -1, &pStmt, 0);
9578 if( rc ){
9579 raw_printf(stderr, "Error querying the selftest table\n");
9580 rc = 1;
9581 sqlite3_finalize(pStmt);
9582 goto meta_command_exit;
9584 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9585 int tno = sqlite3_column_int(pStmt, 0);
9586 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9587 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9588 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9590 k = 0;
9591 if( bVerbose>0 ){
9592 char *zQuote = sqlite3_mprintf("%q", zSql);
9593 printf("%d: %s %s\n", tno, zOp, zSql);
9594 sqlite3_free(zQuote);
9596 if( strcmp(zOp,"memo")==0 ){
9597 utf8_printf(p->out, "%s\n", zSql);
9598 }else
9599 if( strcmp(zOp,"run")==0 ){
9600 char *zErrMsg = 0;
9601 str.n = 0;
9602 str.z[0] = 0;
9603 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9604 nTest++;
9605 if( bVerbose ){
9606 utf8_printf(p->out, "Result: %s\n", str.z);
9608 if( rc || zErrMsg ){
9609 nErr++;
9610 rc = 1;
9611 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9612 sqlite3_free(zErrMsg);
9613 }else if( strcmp(zAns,str.z)!=0 ){
9614 nErr++;
9615 rc = 1;
9616 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9617 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
9619 }else
9621 utf8_printf(stderr,
9622 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9623 rc = 1;
9624 break;
9626 } /* End loop over rows of content from SELFTEST */
9627 sqlite3_finalize(pStmt);
9628 } /* End loop over k */
9629 freeText(&str);
9630 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9631 }else
9633 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9634 if( nArg<2 || nArg>3 ){
9635 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9636 rc = 1;
9638 if( nArg>=2 ){
9639 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9640 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9642 if( nArg>=3 ){
9643 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9644 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9646 }else
9648 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9649 const char *zLike = 0; /* Which table to checksum. 0 means everything */
9650 int i; /* Loop counter */
9651 int bSchema = 0; /* Also hash the schema */
9652 int bSeparate = 0; /* Hash each table separately */
9653 int iSize = 224; /* Hash algorithm to use */
9654 int bDebug = 0; /* Only show the query that would have run */
9655 sqlite3_stmt *pStmt; /* For querying tables names */
9656 char *zSql; /* SQL to be run */
9657 char *zSep; /* Separator */
9658 ShellText sSql; /* Complete SQL for the query to run the hash */
9659 ShellText sQuery; /* Set of queries used to read all content */
9660 open_db(p, 0);
9661 for(i=1; i<nArg; i++){
9662 const char *z = azArg[i];
9663 if( z[0]=='-' ){
9664 z++;
9665 if( z[0]=='-' ) z++;
9666 if( strcmp(z,"schema")==0 ){
9667 bSchema = 1;
9668 }else
9669 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9670 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9672 iSize = atoi(&z[5]);
9673 }else
9674 if( strcmp(z,"debug")==0 ){
9675 bDebug = 1;
9676 }else
9678 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9679 azArg[i], azArg[0]);
9680 showHelp(p->out, azArg[0]);
9681 rc = 1;
9682 goto meta_command_exit;
9684 }else if( zLike ){
9685 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9686 rc = 1;
9687 goto meta_command_exit;
9688 }else{
9689 zLike = z;
9690 bSeparate = 1;
9691 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9694 if( bSchema ){
9695 zSql = "SELECT lower(name) FROM sqlite_schema"
9696 " WHERE type='table' AND coalesce(rootpage,0)>1"
9697 " UNION ALL SELECT 'sqlite_schema'"
9698 " ORDER BY 1 collate nocase";
9699 }else{
9700 zSql = "SELECT lower(name) FROM sqlite_schema"
9701 " WHERE type='table' AND coalesce(rootpage,0)>1"
9702 " AND name NOT LIKE 'sqlite_%'"
9703 " ORDER BY 1 collate nocase";
9705 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9706 initText(&sQuery);
9707 initText(&sSql);
9708 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
9709 zSep = "VALUES(";
9710 while( SQLITE_ROW==sqlite3_step(pStmt) ){
9711 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
9712 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
9713 if( strncmp(zTab, "sqlite_",7)!=0 ){
9714 appendText(&sQuery,"SELECT * FROM ", 0);
9715 appendText(&sQuery,zTab,'"');
9716 appendText(&sQuery," NOT INDEXED;", 0);
9717 }else if( strcmp(zTab, "sqlite_schema")==0 ){
9718 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
9719 " ORDER BY name;", 0);
9720 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
9721 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
9722 " ORDER BY name;", 0);
9723 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
9724 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
9725 " ORDER BY tbl,idx;", 0);
9726 }else if( strcmp(zTab, "sqlite_stat4")==0 ){
9727 appendText(&sQuery, "SELECT * FROM ", 0);
9728 appendText(&sQuery, zTab, 0);
9729 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
9731 appendText(&sSql, zSep, 0);
9732 appendText(&sSql, sQuery.z, '\'');
9733 sQuery.n = 0;
9734 appendText(&sSql, ",", 0);
9735 appendText(&sSql, zTab, '\'');
9736 zSep = "),(";
9738 sqlite3_finalize(pStmt);
9739 if( bSeparate ){
9740 zSql = sqlite3_mprintf(
9741 "%s))"
9742 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
9743 " FROM [sha3sum$query]",
9744 sSql.z, iSize);
9745 }else{
9746 zSql = sqlite3_mprintf(
9747 "%s))"
9748 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
9749 " FROM [sha3sum$query]",
9750 sSql.z, iSize);
9752 freeText(&sQuery);
9753 freeText(&sSql);
9754 if( bDebug ){
9755 utf8_printf(p->out, "%s\n", zSql);
9756 }else{
9757 shell_exec(p, zSql, 0);
9759 sqlite3_free(zSql);
9760 }else
9762 #ifndef SQLITE_NOHAVE_SYSTEM
9763 if( c=='s'
9764 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
9766 char *zCmd;
9767 int i, x;
9768 if( nArg<2 ){
9769 raw_printf(stderr, "Usage: .system COMMAND\n");
9770 rc = 1;
9771 goto meta_command_exit;
9773 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
9774 for(i=2; i<nArg; i++){
9775 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
9776 zCmd, azArg[i]);
9778 x = system(zCmd);
9779 sqlite3_free(zCmd);
9780 if( x ) raw_printf(stderr, "System command returns %d\n", x);
9781 }else
9782 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
9784 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
9785 static const char *azBool[] = { "off", "on", "trigger", "full"};
9786 const char *zOut;
9787 int i;
9788 if( nArg!=1 ){
9789 raw_printf(stderr, "Usage: .show\n");
9790 rc = 1;
9791 goto meta_command_exit;
9793 utf8_printf(p->out, "%12.12s: %s\n","echo",
9794 azBool[ShellHasFlag(p, SHFLG_Echo)]);
9795 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
9796 utf8_printf(p->out, "%12.12s: %s\n","explain",
9797 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
9798 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
9799 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
9800 utf8_printf(p->out, "%12.12s: ", "nullvalue");
9801 output_c_string(p->out, p->nullValue);
9802 raw_printf(p->out, "\n");
9803 utf8_printf(p->out,"%12.12s: %s\n","output",
9804 strlen30(p->outfile) ? p->outfile : "stdout");
9805 utf8_printf(p->out,"%12.12s: ", "colseparator");
9806 output_c_string(p->out, p->colSeparator);
9807 raw_printf(p->out, "\n");
9808 utf8_printf(p->out,"%12.12s: ", "rowseparator");
9809 output_c_string(p->out, p->rowSeparator);
9810 raw_printf(p->out, "\n");
9811 switch( p->statsOn ){
9812 case 0: zOut = "off"; break;
9813 default: zOut = "on"; break;
9814 case 2: zOut = "stmt"; break;
9815 case 3: zOut = "vmstep"; break;
9817 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
9818 utf8_printf(p->out, "%12.12s: ", "width");
9819 for (i=0;i<p->nWidth;i++) {
9820 raw_printf(p->out, "%d ", p->colWidth[i]);
9822 raw_printf(p->out, "\n");
9823 utf8_printf(p->out, "%12.12s: %s\n", "filename",
9824 p->zDbFilename ? p->zDbFilename : "");
9825 }else
9827 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
9828 if( nArg==2 ){
9829 if( strcmp(azArg[1],"stmt")==0 ){
9830 p->statsOn = 2;
9831 }else if( strcmp(azArg[1],"vmstep")==0 ){
9832 p->statsOn = 3;
9833 }else{
9834 p->statsOn = (u8)booleanValue(azArg[1]);
9836 }else if( nArg==1 ){
9837 display_stats(p->db, p, 0);
9838 }else{
9839 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
9840 rc = 1;
9842 }else
9844 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
9845 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
9846 || strncmp(azArg[0], "indexes", n)==0) )
9848 sqlite3_stmt *pStmt;
9849 char **azResult;
9850 int nRow, nAlloc;
9851 int ii;
9852 ShellText s;
9853 initText(&s);
9854 open_db(p, 0);
9855 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
9856 if( rc ){
9857 sqlite3_finalize(pStmt);
9858 return shellDatabaseError(p->db);
9861 if( nArg>2 && c=='i' ){
9862 /* It is an historical accident that the .indexes command shows an error
9863 ** when called with the wrong number of arguments whereas the .tables
9864 ** command does not. */
9865 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
9866 rc = 1;
9867 sqlite3_finalize(pStmt);
9868 goto meta_command_exit;
9870 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
9871 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
9872 if( zDbName==0 ) continue;
9873 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
9874 if( sqlite3_stricmp(zDbName, "main")==0 ){
9875 appendText(&s, "SELECT name FROM ", 0);
9876 }else{
9877 appendText(&s, "SELECT ", 0);
9878 appendText(&s, zDbName, '\'');
9879 appendText(&s, "||'.'||name FROM ", 0);
9881 appendText(&s, zDbName, '"');
9882 appendText(&s, ".sqlite_schema ", 0);
9883 if( c=='t' ){
9884 appendText(&s," WHERE type IN ('table','view')"
9885 " AND name NOT LIKE 'sqlite_%'"
9886 " AND name LIKE ?1", 0);
9887 }else{
9888 appendText(&s," WHERE type='index'"
9889 " AND tbl_name LIKE ?1", 0);
9892 rc = sqlite3_finalize(pStmt);
9893 appendText(&s, " ORDER BY 1", 0);
9894 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
9895 freeText(&s);
9896 if( rc ) return shellDatabaseError(p->db);
9898 /* Run the SQL statement prepared by the above block. Store the results
9899 ** as an array of nul-terminated strings in azResult[]. */
9900 nRow = nAlloc = 0;
9901 azResult = 0;
9902 if( nArg>1 ){
9903 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
9904 }else{
9905 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
9907 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9908 if( nRow>=nAlloc ){
9909 char **azNew;
9910 int n2 = nAlloc*2 + 10;
9911 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
9912 if( azNew==0 ) shell_out_of_memory();
9913 nAlloc = n2;
9914 azResult = azNew;
9916 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
9917 if( 0==azResult[nRow] ) shell_out_of_memory();
9918 nRow++;
9920 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
9921 rc = shellDatabaseError(p->db);
9924 /* Pretty-print the contents of array azResult[] to the output */
9925 if( rc==0 && nRow>0 ){
9926 int len, maxlen = 0;
9927 int i, j;
9928 int nPrintCol, nPrintRow;
9929 for(i=0; i<nRow; i++){
9930 len = strlen30(azResult[i]);
9931 if( len>maxlen ) maxlen = len;
9933 nPrintCol = 80/(maxlen+2);
9934 if( nPrintCol<1 ) nPrintCol = 1;
9935 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
9936 for(i=0; i<nPrintRow; i++){
9937 for(j=i; j<nRow; j+=nPrintRow){
9938 char *zSp = j<nPrintRow ? "" : " ";
9939 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
9940 azResult[j] ? azResult[j]:"");
9942 raw_printf(p->out, "\n");
9946 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
9947 sqlite3_free(azResult);
9948 }else
9950 /* Begin redirecting output to the file "testcase-out.txt" */
9951 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
9952 output_reset(p);
9953 p->out = output_file_open("testcase-out.txt", 0);
9954 if( p->out==0 ){
9955 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
9957 if( nArg>=2 ){
9958 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
9959 }else{
9960 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
9962 }else
9964 #ifndef SQLITE_UNTESTABLE
9965 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
9966 static const struct {
9967 const char *zCtrlName; /* Name of a test-control option */
9968 int ctrlCode; /* Integer code for that option */
9969 const char *zUsage; /* Usage notes */
9970 } aCtrl[] = {
9971 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
9972 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
9973 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
9974 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
9975 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
9976 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" },
9977 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/
9978 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
9979 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
9980 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
9981 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
9982 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
9983 #ifdef YYCOVERAGE
9984 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
9985 #endif
9986 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
9987 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
9988 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
9989 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" },
9990 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, "" },
9991 { "tune", SQLITE_TESTCTRL_TUNE, "ID VALUE" },
9993 int testctrl = -1;
9994 int iCtrl = -1;
9995 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
9996 int isOk = 0;
9997 int i, n2;
9998 const char *zCmd = 0;
10000 open_db(p, 0);
10001 zCmd = nArg>=2 ? azArg[1] : "help";
10003 /* The argument can optionally begin with "-" or "--" */
10004 if( zCmd[0]=='-' && zCmd[1] ){
10005 zCmd++;
10006 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10009 /* --help lists all test-controls */
10010 if( strcmp(zCmd,"help")==0 ){
10011 utf8_printf(p->out, "Available test-controls:\n");
10012 for(i=0; i<ArraySize(aCtrl); i++){
10013 utf8_printf(p->out, " .testctrl %s %s\n",
10014 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10016 rc = 1;
10017 goto meta_command_exit;
10020 /* convert testctrl text option to value. allow any unique prefix
10021 ** of the option name, or a numerical value. */
10022 n2 = strlen30(zCmd);
10023 for(i=0; i<ArraySize(aCtrl); i++){
10024 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10025 if( testctrl<0 ){
10026 testctrl = aCtrl[i].ctrlCode;
10027 iCtrl = i;
10028 }else{
10029 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10030 "Use \".testctrl --help\" for help\n", zCmd);
10031 rc = 1;
10032 goto meta_command_exit;
10036 if( testctrl<0 ){
10037 utf8_printf(stderr,"Error: unknown test-control: %s\n"
10038 "Use \".testctrl --help\" for help\n", zCmd);
10039 }else{
10040 switch(testctrl){
10042 /* sqlite3_test_control(int, db, int) */
10043 case SQLITE_TESTCTRL_OPTIMIZATIONS:
10044 if( nArg==3 ){
10045 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10046 rc2 = sqlite3_test_control(testctrl, p->db, opt);
10047 isOk = 3;
10049 break;
10051 /* sqlite3_test_control(int) */
10052 case SQLITE_TESTCTRL_PRNG_SAVE:
10053 case SQLITE_TESTCTRL_PRNG_RESTORE:
10054 case SQLITE_TESTCTRL_BYTEORDER:
10055 if( nArg==2 ){
10056 rc2 = sqlite3_test_control(testctrl);
10057 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10059 break;
10061 /* sqlite3_test_control(int, uint) */
10062 case SQLITE_TESTCTRL_PENDING_BYTE:
10063 if( nArg==3 ){
10064 unsigned int opt = (unsigned int)integerValue(azArg[2]);
10065 rc2 = sqlite3_test_control(testctrl, opt);
10066 isOk = 3;
10068 break;
10070 /* sqlite3_test_control(int, int, sqlite3*) */
10071 case SQLITE_TESTCTRL_PRNG_SEED:
10072 if( nArg==3 || nArg==4 ){
10073 int ii = (int)integerValue(azArg[2]);
10074 sqlite3 *db;
10075 if( ii==0 && strcmp(azArg[2],"random")==0 ){
10076 sqlite3_randomness(sizeof(ii),&ii);
10077 printf("-- random seed: %d\n", ii);
10079 if( nArg==3 ){
10080 db = 0;
10081 }else{
10082 db = p->db;
10083 /* Make sure the schema has been loaded */
10084 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10086 rc2 = sqlite3_test_control(testctrl, ii, db);
10087 isOk = 3;
10089 break;
10091 /* sqlite3_test_control(int, int) */
10092 case SQLITE_TESTCTRL_ASSERT:
10093 case SQLITE_TESTCTRL_ALWAYS:
10094 if( nArg==3 ){
10095 int opt = booleanValue(azArg[2]);
10096 rc2 = sqlite3_test_control(testctrl, opt);
10097 isOk = 1;
10099 break;
10101 /* sqlite3_test_control(int, int) */
10102 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10103 case SQLITE_TESTCTRL_NEVER_CORRUPT:
10104 if( nArg==3 ){
10105 int opt = booleanValue(azArg[2]);
10106 rc2 = sqlite3_test_control(testctrl, opt);
10107 isOk = 3;
10109 break;
10111 /* sqlite3_test_control(sqlite3*) */
10112 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10113 rc2 = sqlite3_test_control(testctrl, p->db);
10114 isOk = 3;
10115 break;
10117 case SQLITE_TESTCTRL_IMPOSTER:
10118 if( nArg==5 ){
10119 rc2 = sqlite3_test_control(testctrl, p->db,
10120 azArg[2],
10121 integerValue(azArg[3]),
10122 integerValue(azArg[4]));
10123 isOk = 3;
10125 break;
10127 case SQLITE_TESTCTRL_SEEK_COUNT: {
10128 u64 x = 0;
10129 rc2 = sqlite3_test_control(testctrl, p->db, &x);
10130 utf8_printf(p->out, "%llu\n", x);
10131 isOk = 3;
10132 break;
10135 #ifdef YYCOVERAGE
10136 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10137 if( nArg==2 ){
10138 sqlite3_test_control(testctrl, p->out);
10139 isOk = 3;
10141 break;
10143 #endif
10144 #ifdef SQLITE_DEBUG
10145 case SQLITE_TESTCTRL_TUNE: {
10146 if( nArg==4 ){
10147 int id = (int)integerValue(azArg[2]);
10148 int val = (int)integerValue(azArg[3]);
10149 sqlite3_test_control(testctrl, id, &val);
10150 isOk = 3;
10151 }else if( nArg==3 ){
10152 int id = (int)integerValue(azArg[2]);
10153 sqlite3_test_control(testctrl, -id, &rc2);
10154 isOk = 1;
10155 }else if( nArg==2 ){
10156 int id = 1;
10157 while(1){
10158 int val = 0;
10159 rc2 = sqlite3_test_control(testctrl, -id, &val);
10160 if( rc2!=SQLITE_OK ) break;
10161 if( id>1 ) utf8_printf(p->out, " ");
10162 utf8_printf(p->out, "%d: %d", id, val);
10163 id++;
10165 if( id>1 ) utf8_printf(p->out, "\n");
10166 isOk = 3;
10168 break;
10170 #endif
10173 if( isOk==0 && iCtrl>=0 ){
10174 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10175 rc = 1;
10176 }else if( isOk==1 ){
10177 raw_printf(p->out, "%d\n", rc2);
10178 }else if( isOk==2 ){
10179 raw_printf(p->out, "0x%08x\n", rc2);
10181 }else
10182 #endif /* !defined(SQLITE_UNTESTABLE) */
10184 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10185 open_db(p, 0);
10186 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10187 }else
10189 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10190 if( nArg==2 ){
10191 enableTimer = booleanValue(azArg[1]);
10192 if( enableTimer && !HAS_TIMER ){
10193 raw_printf(stderr, "Error: timer not available on this system.\n");
10194 enableTimer = 0;
10196 }else{
10197 raw_printf(stderr, "Usage: .timer on|off\n");
10198 rc = 1;
10200 }else
10202 #ifndef SQLITE_OMIT_TRACE
10203 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10204 int mType = 0;
10205 int jj;
10206 open_db(p, 0);
10207 for(jj=1; jj<nArg; jj++){
10208 const char *z = azArg[jj];
10209 if( z[0]=='-' ){
10210 if( optionMatch(z, "expanded") ){
10211 p->eTraceType = SHELL_TRACE_EXPANDED;
10213 #ifdef SQLITE_ENABLE_NORMALIZE
10214 else if( optionMatch(z, "normalized") ){
10215 p->eTraceType = SHELL_TRACE_NORMALIZED;
10217 #endif
10218 else if( optionMatch(z, "plain") ){
10219 p->eTraceType = SHELL_TRACE_PLAIN;
10221 else if( optionMatch(z, "profile") ){
10222 mType |= SQLITE_TRACE_PROFILE;
10224 else if( optionMatch(z, "row") ){
10225 mType |= SQLITE_TRACE_ROW;
10227 else if( optionMatch(z, "stmt") ){
10228 mType |= SQLITE_TRACE_STMT;
10230 else if( optionMatch(z, "close") ){
10231 mType |= SQLITE_TRACE_CLOSE;
10233 else {
10234 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10235 rc = 1;
10236 goto meta_command_exit;
10238 }else{
10239 output_file_close(p->traceOut);
10240 p->traceOut = output_file_open(azArg[1], 0);
10243 if( p->traceOut==0 ){
10244 sqlite3_trace_v2(p->db, 0, 0, 0);
10245 }else{
10246 if( mType==0 ) mType = SQLITE_TRACE_STMT;
10247 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10249 }else
10250 #endif /* !defined(SQLITE_OMIT_TRACE) */
10252 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10253 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10254 int ii;
10255 int lenOpt;
10256 char *zOpt;
10257 if( nArg<2 ){
10258 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10259 rc = 1;
10260 goto meta_command_exit;
10262 open_db(p, 0);
10263 zOpt = azArg[1];
10264 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10265 lenOpt = (int)strlen(zOpt);
10266 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10267 assert( azArg[nArg]==0 );
10268 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10269 }else{
10270 for(ii=1; ii<nArg; ii++){
10271 sqlite3_create_module(p->db, azArg[ii], 0, 0);
10274 }else
10275 #endif
10277 #if SQLITE_USER_AUTHENTICATION
10278 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10279 if( nArg<2 ){
10280 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10281 rc = 1;
10282 goto meta_command_exit;
10284 open_db(p, 0);
10285 if( strcmp(azArg[1],"login")==0 ){
10286 if( nArg!=4 ){
10287 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10288 rc = 1;
10289 goto meta_command_exit;
10291 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10292 strlen30(azArg[3]));
10293 if( rc ){
10294 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10295 rc = 1;
10297 }else if( strcmp(azArg[1],"add")==0 ){
10298 if( nArg!=5 ){
10299 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10300 rc = 1;
10301 goto meta_command_exit;
10303 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10304 booleanValue(azArg[4]));
10305 if( rc ){
10306 raw_printf(stderr, "User-Add failed: %d\n", rc);
10307 rc = 1;
10309 }else if( strcmp(azArg[1],"edit")==0 ){
10310 if( nArg!=5 ){
10311 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10312 rc = 1;
10313 goto meta_command_exit;
10315 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10316 booleanValue(azArg[4]));
10317 if( rc ){
10318 raw_printf(stderr, "User-Edit failed: %d\n", rc);
10319 rc = 1;
10321 }else if( strcmp(azArg[1],"delete")==0 ){
10322 if( nArg!=3 ){
10323 raw_printf(stderr, "Usage: .user delete USER\n");
10324 rc = 1;
10325 goto meta_command_exit;
10327 rc = sqlite3_user_delete(p->db, azArg[2]);
10328 if( rc ){
10329 raw_printf(stderr, "User-Delete failed: %d\n", rc);
10330 rc = 1;
10332 }else{
10333 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10334 rc = 1;
10335 goto meta_command_exit;
10337 }else
10338 #endif /* SQLITE_USER_AUTHENTICATION */
10340 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10341 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10342 sqlite3_libversion(), sqlite3_sourceid());
10343 /* BEGIN SQLCIPHER */
10344 #ifdef SQLITE_HAS_CODEC
10346 extern char* sqlcipher_version();
10347 char *sqlcipher_ver = sqlcipher_version();
10348 utf8_printf(p->out, "SQLCipher %s\n", sqlcipher_ver);
10349 sqlite3_free(sqlcipher_ver);
10351 #endif
10352 /* END SQLCIPHER */
10353 #if SQLITE_HAVE_ZLIB
10354 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10355 #endif
10356 #define CTIMEOPT_VAL_(opt) #opt
10357 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10358 #if defined(__clang__) && defined(__clang_major__)
10359 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10360 CTIMEOPT_VAL(__clang_minor__) "."
10361 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10362 #elif defined(_MSC_VER)
10363 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10364 #elif defined(__GNUC__) && defined(__VERSION__)
10365 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10366 #endif
10367 }else
10369 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10370 const char *zDbName = nArg==2 ? azArg[1] : "main";
10371 sqlite3_vfs *pVfs = 0;
10372 if( p->db ){
10373 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10374 if( pVfs ){
10375 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
10376 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
10377 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
10378 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10381 }else
10383 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10384 sqlite3_vfs *pVfs;
10385 sqlite3_vfs *pCurrent = 0;
10386 if( p->db ){
10387 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10389 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10390 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
10391 pVfs==pCurrent ? " <--- CURRENT" : "");
10392 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
10393 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
10394 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10395 if( pVfs->pNext ){
10396 raw_printf(p->out, "-----------------------------------\n");
10399 }else
10401 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10402 const char *zDbName = nArg==2 ? azArg[1] : "main";
10403 char *zVfsName = 0;
10404 if( p->db ){
10405 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10406 if( zVfsName ){
10407 utf8_printf(p->out, "%s\n", zVfsName);
10408 sqlite3_free(zVfsName);
10411 }else
10413 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10414 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10415 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10416 }else
10418 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10419 int j;
10420 assert( nArg<=ArraySize(azArg) );
10421 p->nWidth = nArg-1;
10422 p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
10423 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10424 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10425 for(j=1; j<nArg; j++){
10426 p->colWidth[j-1] = (int)integerValue(azArg[j]);
10428 }else
10431 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10432 " \"%s\". Enter \".help\" for help\n", azArg[0]);
10433 rc = 1;
10436 meta_command_exit:
10437 if( p->outCount ){
10438 p->outCount--;
10439 if( p->outCount==0 ) output_reset(p);
10441 return rc;
10445 ** Return TRUE if a semicolon occurs anywhere in the first N characters
10446 ** of string z[].
10448 static int line_contains_semicolon(const char *z, int N){
10449 int i;
10450 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
10451 return 0;
10455 ** Test to see if a line consists entirely of whitespace.
10457 static int _all_whitespace(const char *z){
10458 for(; *z; z++){
10459 if( IsSpace(z[0]) ) continue;
10460 if( *z=='/' && z[1]=='*' ){
10461 z += 2;
10462 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
10463 if( *z==0 ) return 0;
10464 z++;
10465 continue;
10467 if( *z=='-' && z[1]=='-' ){
10468 z += 2;
10469 while( *z && *z!='\n' ){ z++; }
10470 if( *z==0 ) return 1;
10471 continue;
10473 return 0;
10475 return 1;
10479 ** Return TRUE if the line typed in is an SQL command terminator other
10480 ** than a semi-colon. The SQL Server style "go" command is understood
10481 ** as is the Oracle "/".
10483 static int line_is_command_terminator(const char *zLine){
10484 while( IsSpace(zLine[0]) ){ zLine++; };
10485 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
10486 return 1; /* Oracle */
10488 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
10489 && _all_whitespace(&zLine[2]) ){
10490 return 1; /* SQL Server */
10492 return 0;
10496 ** We need a default sqlite3_complete() implementation to use in case
10497 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
10498 ** any arbitrary text is a complete SQL statement. This is not very
10499 ** user-friendly, but it does seem to work.
10501 #ifdef SQLITE_OMIT_COMPLETE
10502 #define sqlite3_complete(x) 1
10503 #endif
10506 ** Return true if zSql is a complete SQL statement. Return false if it
10507 ** ends in the middle of a string literal or C-style comment.
10509 static int line_is_complete(char *zSql, int nSql){
10510 int rc;
10511 if( zSql==0 ) return 1;
10512 zSql[nSql] = ';';
10513 zSql[nSql+1] = 0;
10514 rc = sqlite3_complete(zSql);
10515 zSql[nSql] = 0;
10516 return rc;
10520 ** Run a single line of SQL. Return the number of errors.
10522 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10523 int rc;
10524 char *zErrMsg = 0;
10526 open_db(p, 0);
10527 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10528 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10529 BEGIN_TIMER;
10530 rc = shell_exec(p, zSql, &zErrMsg);
10531 END_TIMER;
10532 if( rc || zErrMsg ){
10533 char zPrefix[100];
10534 if( in!=0 || !stdin_is_interactive ){
10535 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10536 "Error: near line %d:", startline);
10537 }else{
10538 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
10540 if( zErrMsg!=0 ){
10541 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
10542 sqlite3_free(zErrMsg);
10543 zErrMsg = 0;
10544 }else{
10545 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
10547 return 1;
10548 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10549 raw_printf(p->out, "changes: %3d total_changes: %d\n",
10550 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
10552 return 0;
10557 ** Read input from *in and process it. If *in==0 then input
10558 ** is interactive - the user is typing it it. Otherwise, input
10559 ** is coming from a file or device. A prompt is issued and history
10560 ** is saved only if input is interactive. An interrupt signal will
10561 ** cause this routine to exit immediately, unless input is interactive.
10563 ** Return the number of errors.
10565 static int process_input(ShellState *p){
10566 char *zLine = 0; /* A single input line */
10567 char *zSql = 0; /* Accumulated SQL text */
10568 int nLine; /* Length of current line */
10569 int nSql = 0; /* Bytes of zSql[] used */
10570 int nAlloc = 0; /* Allocated zSql[] space */
10571 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
10572 int rc; /* Error code */
10573 int errCnt = 0; /* Number of errors seen */
10574 int startline = 0; /* Line number for start of current input */
10576 p->lineno = 0;
10577 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
10578 fflush(p->out);
10579 zLine = one_input_line(p->in, zLine, nSql>0);
10580 if( zLine==0 ){
10581 /* End of input */
10582 if( p->in==0 && stdin_is_interactive ) printf("\n");
10583 break;
10585 if( seenInterrupt ){
10586 if( p->in!=0 ) break;
10587 seenInterrupt = 0;
10589 p->lineno++;
10590 if( nSql==0 && _all_whitespace(zLine) ){
10591 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10592 continue;
10594 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
10595 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10596 if( zLine[0]=='.' ){
10597 rc = do_meta_command(zLine, p);
10598 if( rc==2 ){ /* exit requested */
10599 break;
10600 }else if( rc ){
10601 errCnt++;
10604 continue;
10606 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
10607 memcpy(zLine,";",2);
10609 nLine = strlen30(zLine);
10610 if( nSql+nLine+2>=nAlloc ){
10611 nAlloc = nSql+nLine+100;
10612 zSql = realloc(zSql, nAlloc);
10613 if( zSql==0 ) shell_out_of_memory();
10615 nSqlPrior = nSql;
10616 if( nSql==0 ){
10617 int i;
10618 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
10619 assert( nAlloc>0 && zSql!=0 );
10620 memcpy(zSql, zLine+i, nLine+1-i);
10621 startline = p->lineno;
10622 nSql = nLine-i;
10623 }else{
10624 zSql[nSql++] = '\n';
10625 memcpy(zSql+nSql, zLine, nLine+1);
10626 nSql += nLine;
10628 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
10629 && sqlite3_complete(zSql) ){
10630 errCnt += runOneSqlLine(p, zSql, p->in, startline);
10631 nSql = 0;
10632 if( p->outCount ){
10633 output_reset(p);
10634 p->outCount = 0;
10635 }else{
10636 clearTempFile(p);
10638 }else if( nSql && _all_whitespace(zSql) ){
10639 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
10640 nSql = 0;
10643 if( nSql && !_all_whitespace(zSql) ){
10644 errCnt += runOneSqlLine(p, zSql, p->in, startline);
10646 free(zSql);
10647 free(zLine);
10648 return errCnt>0;
10652 ** Return a pathname which is the user's home directory. A
10653 ** 0 return indicates an error of some kind.
10655 static char *find_home_dir(int clearFlag){
10656 static char *home_dir = NULL;
10657 if( clearFlag ){
10658 free(home_dir);
10659 home_dir = 0;
10660 return 0;
10662 if( home_dir ) return home_dir;
10664 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
10665 && !defined(__RTP__) && !defined(_WRS_KERNEL)
10667 struct passwd *pwent;
10668 uid_t uid = getuid();
10669 if( (pwent=getpwuid(uid)) != NULL) {
10670 home_dir = pwent->pw_dir;
10673 #endif
10675 #if defined(_WIN32_WCE)
10676 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
10678 home_dir = "/";
10679 #else
10681 #if defined(_WIN32) || defined(WIN32)
10682 if (!home_dir) {
10683 home_dir = getenv("USERPROFILE");
10685 #endif
10687 if (!home_dir) {
10688 home_dir = getenv("HOME");
10691 #if defined(_WIN32) || defined(WIN32)
10692 if (!home_dir) {
10693 char *zDrive, *zPath;
10694 int n;
10695 zDrive = getenv("HOMEDRIVE");
10696 zPath = getenv("HOMEPATH");
10697 if( zDrive && zPath ){
10698 n = strlen30(zDrive) + strlen30(zPath) + 1;
10699 home_dir = malloc( n );
10700 if( home_dir==0 ) return 0;
10701 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
10702 return home_dir;
10704 home_dir = "c:\\";
10706 #endif
10708 #endif /* !_WIN32_WCE */
10710 if( home_dir ){
10711 int n = strlen30(home_dir) + 1;
10712 char *z = malloc( n );
10713 if( z ) memcpy(z, home_dir, n);
10714 home_dir = z;
10717 return home_dir;
10721 ** Read input from the file given by sqliterc_override. Or if that
10722 ** parameter is NULL, take input from ~/.sqliterc
10724 ** Returns the number of errors.
10726 static void process_sqliterc(
10727 ShellState *p, /* Configuration data */
10728 const char *sqliterc_override /* Name of config file. NULL to use default */
10730 char *home_dir = NULL;
10731 const char *sqliterc = sqliterc_override;
10732 char *zBuf = 0;
10733 FILE *inSaved = p->in;
10734 int savedLineno = p->lineno;
10736 if (sqliterc == NULL) {
10737 home_dir = find_home_dir(0);
10738 if( home_dir==0 ){
10739 raw_printf(stderr, "-- warning: cannot find home directory;"
10740 " cannot read ~/.sqliterc\n");
10741 return;
10743 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
10744 sqliterc = zBuf;
10746 p->in = fopen(sqliterc,"rb");
10747 if( p->in ){
10748 if( stdin_is_interactive ){
10749 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
10751 if( process_input(p) && bail_on_error ) exit(1);
10752 fclose(p->in);
10753 }else if( sqliterc_override!=0 ){
10754 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
10755 if( bail_on_error ) exit(1);
10757 p->in = inSaved;
10758 p->lineno = savedLineno;
10759 sqlite3_free(zBuf);
10763 ** Show available command line options
10765 static const char zOptions[] =
10766 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10767 " -A ARGS... run \".archive ARGS\" and exit\n"
10768 #endif
10769 " -append append the database to the end of the file\n"
10770 " -ascii set output mode to 'ascii'\n"
10771 " -bail stop after hitting an error\n"
10772 " -batch force batch I/O\n"
10773 " -box set output mode to 'box'\n"
10774 " -column set output mode to 'column'\n"
10775 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
10776 " -csv set output mode to 'csv'\n"
10777 #if !defined(SQLITE_OMIT_DESERIALIZE)
10778 " -deserialize open the database using sqlite3_deserialize()\n"
10779 #endif
10780 " -echo print commands before execution\n"
10781 " -init FILENAME read/process named file\n"
10782 " -[no]header turn headers on or off\n"
10783 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10784 " -heap SIZE Size of heap for memsys3 or memsys5\n"
10785 #endif
10786 " -help show this message\n"
10787 " -html set output mode to HTML\n"
10788 " -interactive force interactive I/O\n"
10789 " -json set output mode to 'json'\n"
10790 " -line set output mode to 'line'\n"
10791 " -list set output mode to 'list'\n"
10792 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
10793 " -markdown set output mode to 'markdown'\n"
10794 #if !defined(SQLITE_OMIT_DESERIALIZE)
10795 " -maxsize N maximum size for a --deserialize database\n"
10796 #endif
10797 " -memtrace trace all memory allocations and deallocations\n"
10798 " -mmap N default mmap size set to N\n"
10799 #ifdef SQLITE_ENABLE_MULTIPLEX
10800 " -multiplex enable the multiplexor VFS\n"
10801 #endif
10802 " -newline SEP set output row separator. Default: '\\n'\n"
10803 " -nofollow refuse to open symbolic links to database files\n"
10804 " -nullvalue TEXT set text string for NULL values. Default ''\n"
10805 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
10806 " -quote set output mode to 'quote'\n"
10807 " -readonly open the database read-only\n"
10808 " -separator SEP set output column separator. Default: '|'\n"
10809 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
10810 " -sorterref SIZE sorter references threshold size\n"
10811 #endif
10812 " -stats print memory stats before each finalize\n"
10813 " -table set output mode to 'table'\n"
10814 " -tabs set output mode to 'tabs'\n"
10815 " -version show SQLite version\n"
10816 " -vfs NAME use NAME as the default VFS\n"
10817 #ifdef SQLITE_ENABLE_VFSTRACE
10818 " -vfstrace enable tracing of all VFS calls\n"
10819 #endif
10820 #ifdef SQLITE_HAVE_ZLIB
10821 " -zip open the file as a ZIP Archive\n"
10822 #endif
10824 static void usage(int showDetail){
10825 utf8_printf(stderr,
10826 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
10827 "FILENAME is the name of an SQLite database. A new database is created\n"
10828 "if the file does not previously exist.\n", Argv0);
10829 if( showDetail ){
10830 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
10831 }else{
10832 raw_printf(stderr, "Use the -help option for additional information\n");
10834 exit(1);
10838 ** Internal check: Verify that the SQLite is uninitialized. Print a
10839 ** error message if it is initialized.
10841 static void verify_uninitialized(void){
10842 if( sqlite3_config(-1)==SQLITE_MISUSE ){
10843 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
10844 " initialization.\n");
10849 ** Initialize the state information in data
10851 static void main_init(ShellState *data) {
10852 memset(data, 0, sizeof(*data));
10853 data->normalMode = data->cMode = data->mode = MODE_List;
10854 data->autoExplain = 1;
10855 memcpy(data->colSeparator,SEP_Column, 2);
10856 memcpy(data->rowSeparator,SEP_Row, 2);
10857 data->showHeader = 0;
10858 data->shellFlgs = SHFLG_Lookaside;
10859 verify_uninitialized();
10860 sqlite3_config(SQLITE_CONFIG_URI, 1);
10861 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
10862 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
10863 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
10864 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
10868 ** Output text to the console in a font that attracts extra attention.
10870 #ifdef _WIN32
10871 static void printBold(const char *zText){
10872 #if !SQLITE_OS_WINRT
10873 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
10874 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
10875 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
10876 SetConsoleTextAttribute(out,
10877 FOREGROUND_RED|FOREGROUND_INTENSITY
10879 #endif
10880 printf("%s", zText);
10881 #if !SQLITE_OS_WINRT
10882 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
10883 #endif
10885 #else
10886 static void printBold(const char *zText){
10887 printf("\033[1m%s\033[0m", zText);
10889 #endif
10892 ** Get the argument to an --option. Throw an error and die if no argument
10893 ** is available.
10895 static char *cmdline_option_value(int argc, char **argv, int i){
10896 if( i==argc ){
10897 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
10898 argv[0], argv[argc-1]);
10899 exit(1);
10901 return argv[i];
10904 #ifndef SQLITE_SHELL_IS_UTF8
10905 # if (defined(_WIN32) || defined(WIN32)) \
10906 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
10907 # define SQLITE_SHELL_IS_UTF8 (0)
10908 # else
10909 # define SQLITE_SHELL_IS_UTF8 (1)
10910 # endif
10911 #endif
10913 #if SQLITE_SHELL_IS_UTF8
10914 int SQLITE_CDECL main(int argc, char **argv){
10915 #else
10916 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
10917 char **argv;
10918 #endif
10919 char *zErrMsg = 0;
10920 ShellState data;
10921 const char *zInitFile = 0;
10922 int i;
10923 int rc = 0;
10924 int warnInmemoryDb = 0;
10925 int readStdin = 1;
10926 int nCmd = 0;
10927 char **azCmd = 0;
10928 const char *zVfs = 0; /* Value of -vfs command-line option */
10929 #if !SQLITE_SHELL_IS_UTF8
10930 char **argvToFree = 0;
10931 int argcToFree = 0;
10932 #endif
10934 setBinaryMode(stdin, 0);
10935 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
10936 stdin_is_interactive = isatty(0);
10937 stdout_is_console = isatty(1);
10939 #ifdef SQLITE_DEBUG
10940 registerOomSimulator();
10941 #endif
10943 #if !defined(_WIN32_WCE)
10944 if( getenv("SQLITE_DEBUG_BREAK") ){
10945 if( isatty(0) && isatty(2) ){
10946 fprintf(stderr,
10947 "attach debugger to process %d and press any key to continue.\n",
10948 GETPID());
10949 fgetc(stdin);
10950 }else{
10951 #if defined(_WIN32) || defined(WIN32)
10952 #if SQLITE_OS_WINRT
10953 __debugbreak();
10954 #else
10955 DebugBreak();
10956 #endif
10957 #elif defined(SIGTRAP)
10958 raise(SIGTRAP);
10959 #endif
10962 #endif
10964 #if USE_SYSTEM_SQLITE+0!=1
10965 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
10966 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
10967 sqlite3_sourceid(), SQLITE_SOURCE_ID);
10968 exit(1);
10970 #endif
10971 main_init(&data);
10973 /* On Windows, we must translate command-line arguments into UTF-8.
10974 ** The SQLite memory allocator subsystem has to be enabled in order to
10975 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
10976 ** subsequent sqlite3_config() calls will work. So copy all results into
10977 ** memory that does not come from the SQLite memory allocator.
10979 #if !SQLITE_SHELL_IS_UTF8
10980 sqlite3_initialize();
10981 argvToFree = malloc(sizeof(argv[0])*argc*2);
10982 argcToFree = argc;
10983 argv = argvToFree + argc;
10984 if( argv==0 ) shell_out_of_memory();
10985 for(i=0; i<argc; i++){
10986 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
10987 int n;
10988 if( z==0 ) shell_out_of_memory();
10989 n = (int)strlen(z);
10990 argv[i] = malloc( n+1 );
10991 if( argv[i]==0 ) shell_out_of_memory();
10992 memcpy(argv[i], z, n+1);
10993 argvToFree[i] = argv[i];
10994 sqlite3_free(z);
10996 sqlite3_shutdown();
10997 #endif
10999 assert( argc>=1 && argv && argv[0] );
11000 Argv0 = argv[0];
11002 /* Make sure we have a valid signal handler early, before anything
11003 ** else is done.
11005 #ifdef SIGINT
11006 signal(SIGINT, interrupt_handler);
11007 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11008 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11009 #endif
11011 #ifdef SQLITE_SHELL_DBNAME_PROC
11013 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11014 ** of a C-function that will provide the name of the database file. Use
11015 ** this compile-time option to embed this shell program in larger
11016 ** applications. */
11017 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11018 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
11019 warnInmemoryDb = 0;
11021 #endif
11023 /* Do an initial pass through the command-line argument to locate
11024 ** the name of the database file, the name of the initialization file,
11025 ** the size of the alternative malloc heap,
11026 ** and the first command to execute.
11028 verify_uninitialized();
11029 for(i=1; i<argc; i++){
11030 char *z;
11031 z = argv[i];
11032 if( z[0]!='-' ){
11033 if( data.zDbFilename==0 ){
11034 data.zDbFilename = z;
11035 }else{
11036 /* Excesss arguments are interpreted as SQL (or dot-commands) and
11037 ** mean that nothing is read from stdin */
11038 readStdin = 0;
11039 nCmd++;
11040 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11041 if( azCmd==0 ) shell_out_of_memory();
11042 azCmd[nCmd-1] = z;
11045 if( z[1]=='-' ) z++;
11046 if( strcmp(z,"-separator")==0
11047 || strcmp(z,"-nullvalue")==0
11048 || strcmp(z,"-newline")==0
11049 || strcmp(z,"-cmd")==0
11051 (void)cmdline_option_value(argc, argv, ++i);
11052 }else if( strcmp(z,"-init")==0 ){
11053 zInitFile = cmdline_option_value(argc, argv, ++i);
11054 }else if( strcmp(z,"-batch")==0 ){
11055 /* Need to check for batch mode here to so we can avoid printing
11056 ** informational messages (like from process_sqliterc) before
11057 ** we do the actual processing of arguments later in a second pass.
11059 stdin_is_interactive = 0;
11060 }else if( strcmp(z,"-heap")==0 ){
11061 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11062 const char *zSize;
11063 sqlite3_int64 szHeap;
11065 zSize = cmdline_option_value(argc, argv, ++i);
11066 szHeap = integerValue(zSize);
11067 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11068 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11069 #else
11070 (void)cmdline_option_value(argc, argv, ++i);
11071 #endif
11072 }else if( strcmp(z,"-pagecache")==0 ){
11073 sqlite3_int64 n, sz;
11074 sz = integerValue(cmdline_option_value(argc,argv,++i));
11075 if( sz>70000 ) sz = 70000;
11076 if( sz<0 ) sz = 0;
11077 n = integerValue(cmdline_option_value(argc,argv,++i));
11078 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11079 n = 0xffffffffffffLL/sz;
11081 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11082 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11083 data.shellFlgs |= SHFLG_Pagecache;
11084 }else if( strcmp(z,"-lookaside")==0 ){
11085 int n, sz;
11086 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11087 if( sz<0 ) sz = 0;
11088 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11089 if( n<0 ) n = 0;
11090 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11091 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11092 #ifdef SQLITE_ENABLE_VFSTRACE
11093 }else if( strcmp(z,"-vfstrace")==0 ){
11094 extern int vfstrace_register(
11095 const char *zTraceName,
11096 const char *zOldVfsName,
11097 int (*xOut)(const char*,void*),
11098 void *pOutArg,
11099 int makeDefault
11101 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11102 #endif
11103 #ifdef SQLITE_ENABLE_MULTIPLEX
11104 }else if( strcmp(z,"-multiplex")==0 ){
11105 extern int sqlite3_multiple_initialize(const char*,int);
11106 sqlite3_multiplex_initialize(0, 1);
11107 #endif
11108 }else if( strcmp(z,"-mmap")==0 ){
11109 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11110 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11111 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11112 }else if( strcmp(z,"-sorterref")==0 ){
11113 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11114 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11115 #endif
11116 }else if( strcmp(z,"-vfs")==0 ){
11117 zVfs = cmdline_option_value(argc, argv, ++i);
11118 #ifdef SQLITE_HAVE_ZLIB
11119 }else if( strcmp(z,"-zip")==0 ){
11120 data.openMode = SHELL_OPEN_ZIPFILE;
11121 #endif
11122 }else if( strcmp(z,"-append")==0 ){
11123 data.openMode = SHELL_OPEN_APPENDVFS;
11124 #ifndef SQLITE_OMIT_DESERIALIZE
11125 }else if( strcmp(z,"-deserialize")==0 ){
11126 data.openMode = SHELL_OPEN_DESERIALIZE;
11127 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11128 data.szMax = integerValue(argv[++i]);
11129 #endif
11130 }else if( strcmp(z,"-readonly")==0 ){
11131 data.openMode = SHELL_OPEN_READONLY;
11132 }else if( strcmp(z,"-nofollow")==0 ){
11133 data.openFlags = SQLITE_OPEN_NOFOLLOW;
11134 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11135 }else if( strncmp(z, "-A",2)==0 ){
11136 /* All remaining command-line arguments are passed to the ".archive"
11137 ** command, so ignore them */
11138 break;
11139 #endif
11140 }else if( strcmp(z, "-memtrace")==0 ){
11141 sqlite3MemTraceActivate(stderr);
11142 }else if( strcmp(z,"-bail")==0 ){
11143 bail_on_error = 1;
11146 verify_uninitialized();
11149 #ifdef SQLITE_SHELL_INIT_PROC
11151 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11152 ** of a C-function that will perform initialization actions on SQLite that
11153 ** occur just before or after sqlite3_initialize(). Use this compile-time
11154 ** option to embed this shell program in larger applications. */
11155 extern void SQLITE_SHELL_INIT_PROC(void);
11156 SQLITE_SHELL_INIT_PROC();
11158 #else
11159 /* All the sqlite3_config() calls have now been made. So it is safe
11160 ** to call sqlite3_initialize() and process any command line -vfs option. */
11161 sqlite3_initialize();
11162 #endif
11164 if( zVfs ){
11165 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11166 if( pVfs ){
11167 sqlite3_vfs_register(pVfs, 1);
11168 }else{
11169 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11170 exit(1);
11174 if( data.zDbFilename==0 ){
11175 #ifndef SQLITE_OMIT_MEMORYDB
11176 data.zDbFilename = ":memory:";
11177 warnInmemoryDb = argc==1;
11178 #else
11179 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11180 return 1;
11181 #endif
11183 data.out = stdout;
11184 sqlite3_appendvfs_init(0,0,0);
11186 /* Go ahead and open the database file if it already exists. If the
11187 ** file does not exist, delay opening it. This prevents empty database
11188 ** files from being created if a user mistypes the database name argument
11189 ** to the sqlite command-line tool.
11191 if( access(data.zDbFilename, 0)==0 ){
11192 open_db(&data, 0);
11195 /* Process the initialization file if there is one. If no -init option
11196 ** is given on the command line, look for a file named ~/.sqliterc and
11197 ** try to process it.
11199 process_sqliterc(&data,zInitFile);
11201 /* Make a second pass through the command-line argument and set
11202 ** options. This second pass is delayed until after the initialization
11203 ** file is processed so that the command-line arguments will override
11204 ** settings in the initialization file.
11206 for(i=1; i<argc; i++){
11207 char *z = argv[i];
11208 if( z[0]!='-' ) continue;
11209 if( z[1]=='-' ){ z++; }
11210 if( strcmp(z,"-init")==0 ){
11211 i++;
11212 }else if( strcmp(z,"-html")==0 ){
11213 data.mode = MODE_Html;
11214 }else if( strcmp(z,"-list")==0 ){
11215 data.mode = MODE_List;
11216 }else if( strcmp(z,"-quote")==0 ){
11217 data.mode = MODE_Quote;
11218 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11219 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11220 }else if( strcmp(z,"-line")==0 ){
11221 data.mode = MODE_Line;
11222 }else if( strcmp(z,"-column")==0 ){
11223 data.mode = MODE_Column;
11224 }else if( strcmp(z,"-json")==0 ){
11225 data.mode = MODE_Json;
11226 }else if( strcmp(z,"-markdown")==0 ){
11227 data.mode = MODE_Markdown;
11228 }else if( strcmp(z,"-table")==0 ){
11229 data.mode = MODE_Table;
11230 }else if( strcmp(z,"-box")==0 ){
11231 data.mode = MODE_Box;
11232 }else if( strcmp(z,"-csv")==0 ){
11233 data.mode = MODE_Csv;
11234 memcpy(data.colSeparator,",",2);
11235 #ifdef SQLITE_HAVE_ZLIB
11236 }else if( strcmp(z,"-zip")==0 ){
11237 data.openMode = SHELL_OPEN_ZIPFILE;
11238 #endif
11239 }else if( strcmp(z,"-append")==0 ){
11240 data.openMode = SHELL_OPEN_APPENDVFS;
11241 #ifndef SQLITE_OMIT_DESERIALIZE
11242 }else if( strcmp(z,"-deserialize")==0 ){
11243 data.openMode = SHELL_OPEN_DESERIALIZE;
11244 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11245 data.szMax = integerValue(argv[++i]);
11246 #endif
11247 }else if( strcmp(z,"-readonly")==0 ){
11248 data.openMode = SHELL_OPEN_READONLY;
11249 }else if( strcmp(z,"-nofollow")==0 ){
11250 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11251 }else if( strcmp(z,"-ascii")==0 ){
11252 data.mode = MODE_Ascii;
11253 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11254 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11255 }else if( strcmp(z,"-tabs")==0 ){
11256 data.mode = MODE_List;
11257 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11258 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11259 }else if( strcmp(z,"-separator")==0 ){
11260 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11261 "%s",cmdline_option_value(argc,argv,++i));
11262 }else if( strcmp(z,"-newline")==0 ){
11263 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11264 "%s",cmdline_option_value(argc,argv,++i));
11265 }else if( strcmp(z,"-nullvalue")==0 ){
11266 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11267 "%s",cmdline_option_value(argc,argv,++i));
11268 }else if( strcmp(z,"-header")==0 ){
11269 data.showHeader = 1;
11270 }else if( strcmp(z,"-noheader")==0 ){
11271 data.showHeader = 0;
11272 }else if( strcmp(z,"-echo")==0 ){
11273 ShellSetFlag(&data, SHFLG_Echo);
11274 }else if( strcmp(z,"-eqp")==0 ){
11275 data.autoEQP = AUTOEQP_on;
11276 }else if( strcmp(z,"-eqpfull")==0 ){
11277 data.autoEQP = AUTOEQP_full;
11278 }else if( strcmp(z,"-stats")==0 ){
11279 data.statsOn = 1;
11280 }else if( strcmp(z,"-scanstats")==0 ){
11281 data.scanstatsOn = 1;
11282 }else if( strcmp(z,"-backslash")==0 ){
11283 /* Undocumented command-line option: -backslash
11284 ** Causes C-style backslash escapes to be evaluated in SQL statements
11285 ** prior to sending the SQL into SQLite. Useful for injecting
11286 ** crazy bytes in the middle of SQL statements for testing and debugging.
11288 ShellSetFlag(&data, SHFLG_Backslash);
11289 }else if( strcmp(z,"-bail")==0 ){
11290 /* No-op. The bail_on_error flag should already be set. */
11291 }else if( strcmp(z,"-version")==0 ){
11292 /* BEGIN SQLCIPHER */
11293 #ifdef SQLITE_HAS_CODEC
11294 extern char* sqlcipher_version();
11295 char *sqlcipher_ver = sqlcipher_version();
11296 printf("%s %s", sqlite3_libversion(), sqlite3_sourceid());
11297 printf(" (SQLCipher %s)\n", sqlcipher_ver);
11298 sqlite3_free(sqlcipher_ver);
11299 #else
11300 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11301 #endif
11302 /* END SQLCIPHER */
11303 return 0;
11304 }else if( strcmp(z,"-interactive")==0 ){
11305 stdin_is_interactive = 1;
11306 }else if( strcmp(z,"-batch")==0 ){
11307 stdin_is_interactive = 0;
11308 }else if( strcmp(z,"-heap")==0 ){
11309 i++;
11310 }else if( strcmp(z,"-pagecache")==0 ){
11311 i+=2;
11312 }else if( strcmp(z,"-lookaside")==0 ){
11313 i+=2;
11314 }else if( strcmp(z,"-mmap")==0 ){
11315 i++;
11316 }else if( strcmp(z,"-memtrace")==0 ){
11317 i++;
11318 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11319 }else if( strcmp(z,"-sorterref")==0 ){
11320 i++;
11321 #endif
11322 }else if( strcmp(z,"-vfs")==0 ){
11323 i++;
11324 #ifdef SQLITE_ENABLE_VFSTRACE
11325 }else if( strcmp(z,"-vfstrace")==0 ){
11326 i++;
11327 #endif
11328 #ifdef SQLITE_ENABLE_MULTIPLEX
11329 }else if( strcmp(z,"-multiplex")==0 ){
11330 i++;
11331 #endif
11332 }else if( strcmp(z,"-help")==0 ){
11333 usage(1);
11334 }else if( strcmp(z,"-cmd")==0 ){
11335 /* Run commands that follow -cmd first and separately from commands
11336 ** that simply appear on the command-line. This seems goofy. It would
11337 ** be better if all commands ran in the order that they appear. But
11338 ** we retain the goofy behavior for historical compatibility. */
11339 if( i==argc-1 ) break;
11340 z = cmdline_option_value(argc,argv,++i);
11341 if( z[0]=='.' ){
11342 rc = do_meta_command(z, &data);
11343 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11344 }else{
11345 open_db(&data, 0);
11346 rc = shell_exec(&data, z, &zErrMsg);
11347 if( zErrMsg!=0 ){
11348 utf8_printf(stderr,"Error: %s\n", zErrMsg);
11349 if( bail_on_error ) return rc!=0 ? rc : 1;
11350 }else if( rc!=0 ){
11351 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11352 if( bail_on_error ) return rc;
11355 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11356 }else if( strncmp(z, "-A", 2)==0 ){
11357 if( nCmd>0 ){
11358 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11359 " with \"%s\"\n", z);
11360 return 1;
11362 open_db(&data, OPEN_DB_ZIPFILE);
11363 if( z[2] ){
11364 argv[i] = &z[2];
11365 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11366 }else{
11367 arDotCommand(&data, 1, argv+i, argc-i);
11369 readStdin = 0;
11370 break;
11371 #endif
11372 }else{
11373 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11374 raw_printf(stderr,"Use -help for a list of options.\n");
11375 return 1;
11377 data.cMode = data.mode;
11380 if( !readStdin ){
11381 /* Run all arguments that do not begin with '-' as if they were separate
11382 ** command-line inputs, except for the argToSkip argument which contains
11383 ** the database filename.
11385 for(i=0; i<nCmd; i++){
11386 if( azCmd[i][0]=='.' ){
11387 rc = do_meta_command(azCmd[i], &data);
11388 if( rc ){
11389 free(azCmd);
11390 return rc==2 ? 0 : rc;
11392 }else{
11393 open_db(&data, 0);
11394 rc = shell_exec(&data, azCmd[i], &zErrMsg);
11395 if( zErrMsg || rc ){
11396 if( zErrMsg!=0 ){
11397 utf8_printf(stderr,"Error: %s\n", zErrMsg);
11398 }else{
11399 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11401 sqlite3_free(zErrMsg);
11402 free(azCmd);
11403 return rc!=0 ? rc : 1;
11407 }else{
11408 /* Run commands received from standard input
11410 if( stdin_is_interactive ){
11411 char *zHome;
11412 char *zHistory;
11413 int nHistory;
11414 /* BEGIN SQLCIPHER */
11415 #ifdef SQLITE_HAS_CODEC
11416 extern char* sqlcipher_version();
11417 char *sqlcipher_ver = sqlcipher_version();
11418 printf(
11419 "SQLite version %s %.19s" /*extra-version-info*/
11420 " (SQLCipher %s)\n" /*sqlcipher version info*/
11421 "Enter \".help\" for usage hints.\n",
11422 sqlite3_libversion(), sqlite3_sourceid(), sqlcipher_ver
11424 sqlite3_free(sqlcipher_ver);
11425 #else
11426 printf(
11427 "SQLite version %s %.19s\n" /*extra-version-info*/
11428 "Enter \".help\" for usage hints.\n",
11429 sqlite3_libversion(), sqlite3_sourceid()
11431 #endif
11432 /* END SQLCIPHER */
11433 if( warnInmemoryDb ){
11434 printf("Connected to a ");
11435 printBold("transient in-memory database");
11436 printf(".\nUse \".open FILENAME\" to reopen on a "
11437 "persistent database.\n");
11439 zHistory = getenv("SQLITE_HISTORY");
11440 if( zHistory ){
11441 zHistory = strdup(zHistory);
11442 }else if( (zHome = find_home_dir(0))!=0 ){
11443 nHistory = strlen30(zHome) + 20;
11444 if( (zHistory = malloc(nHistory))!=0 ){
11445 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11448 if( zHistory ){ shell_read_history(zHistory); }
11449 #if HAVE_READLINE || HAVE_EDITLINE
11450 rl_attempted_completion_function = readline_completion;
11451 #elif HAVE_LINENOISE
11452 linenoiseSetCompletionCallback(linenoise_completion);
11453 #endif
11454 data.in = 0;
11455 rc = process_input(&data);
11456 if( zHistory ){
11457 shell_stifle_history(2000);
11458 shell_write_history(zHistory);
11459 free(zHistory);
11461 }else{
11462 data.in = stdin;
11463 rc = process_input(&data);
11466 free(azCmd);
11467 set_table_name(&data, 0);
11468 if( data.db ){
11469 session_close_all(&data);
11470 close_db(data.db);
11472 sqlite3_free(data.zFreeOnClose);
11473 find_home_dir(1);
11474 output_reset(&data);
11475 data.doXdgOpen = 0;
11476 clearTempFile(&data);
11477 #if !SQLITE_SHELL_IS_UTF8
11478 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11479 free(argvToFree);
11480 #endif
11481 free(data.colWidth);
11482 /* Clear the global data structure so that valgrind will detect memory
11483 ** leaks */
11484 memset(&data, 0, sizeof(data));
11485 return rc;