update version and change log for 4.4.2
[sqlcipher.git] / src / shell.c.in
blobfd089c404ca20451e89c8cd64e197b84feec1724
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->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
230 clockVfs->xCurrentTimeInt64(clockVfs, &t);
231 }else{
232 double r;
233 clockVfs->xCurrentTime(clockVfs, &r);
234 t = (sqlite3_int64)(r*86400000.0);
236 return t;
239 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
240 #include <sys/time.h>
241 #include <sys/resource.h>
243 /* VxWorks does not support getrusage() as far as we can determine */
244 #if defined(_WRS_KERNEL) || defined(__RTP__)
245 struct rusage {
246 struct timeval ru_utime; /* user CPU time used */
247 struct timeval ru_stime; /* system CPU time used */
249 #define getrusage(A,B) memset(B,0,sizeof(*B))
250 #endif
252 /* Saved resource information for the beginning of an operation */
253 static struct rusage sBegin; /* CPU time at start */
254 static sqlite3_int64 iBegin; /* Wall-clock time at start */
257 ** Begin timing an operation
259 static void beginTimer(void){
260 if( enableTimer ){
261 getrusage(RUSAGE_SELF, &sBegin);
262 iBegin = timeOfDay();
266 /* Return the difference of two time_structs in seconds */
267 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
268 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
269 (double)(pEnd->tv_sec - pStart->tv_sec);
273 ** Print the timing results.
275 static void endTimer(void){
276 if( enableTimer ){
277 sqlite3_int64 iEnd = timeOfDay();
278 struct rusage sEnd;
279 getrusage(RUSAGE_SELF, &sEnd);
280 printf("Run Time: real %.3f user %f sys %f\n",
281 (iEnd - iBegin)*0.001,
282 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
283 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
287 #define BEGIN_TIMER beginTimer()
288 #define END_TIMER endTimer()
289 #define HAS_TIMER 1
291 #elif (defined(_WIN32) || defined(WIN32))
293 /* Saved resource information for the beginning of an operation */
294 static HANDLE hProcess;
295 static FILETIME ftKernelBegin;
296 static FILETIME ftUserBegin;
297 static sqlite3_int64 ftWallBegin;
298 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
299 LPFILETIME, LPFILETIME);
300 static GETPROCTIMES getProcessTimesAddr = NULL;
303 ** Check to see if we have timer support. Return 1 if necessary
304 ** support found (or found previously).
306 static int hasTimer(void){
307 if( getProcessTimesAddr ){
308 return 1;
309 } else {
310 #if !SQLITE_OS_WINRT
311 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
312 ** versions. See if the version we are running on has it, and if it
313 ** does, save off a pointer to it and the current process handle.
315 hProcess = GetCurrentProcess();
316 if( hProcess ){
317 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
318 if( NULL != hinstLib ){
319 getProcessTimesAddr =
320 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
321 if( NULL != getProcessTimesAddr ){
322 return 1;
324 FreeLibrary(hinstLib);
327 #endif
329 return 0;
333 ** Begin timing an operation
335 static void beginTimer(void){
336 if( enableTimer && getProcessTimesAddr ){
337 FILETIME ftCreation, ftExit;
338 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
339 &ftKernelBegin,&ftUserBegin);
340 ftWallBegin = timeOfDay();
344 /* Return the difference of two FILETIME structs in seconds */
345 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
346 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
347 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
348 return (double) ((i64End - i64Start) / 10000000.0);
352 ** Print the timing results.
354 static void endTimer(void){
355 if( enableTimer && getProcessTimesAddr){
356 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
357 sqlite3_int64 ftWallEnd = timeOfDay();
358 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
359 printf("Run Time: real %.3f user %f sys %f\n",
360 (ftWallEnd - ftWallBegin)*0.001,
361 timeDiff(&ftUserBegin, &ftUserEnd),
362 timeDiff(&ftKernelBegin, &ftKernelEnd));
366 #define BEGIN_TIMER beginTimer()
367 #define END_TIMER endTimer()
368 #define HAS_TIMER hasTimer()
370 #else
371 #define BEGIN_TIMER
372 #define END_TIMER
373 #define HAS_TIMER 0
374 #endif
377 ** Used to prevent warnings about unused parameters
379 #define UNUSED_PARAMETER(x) (void)(x)
382 ** Number of elements in an array
384 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
387 ** If the following flag is set, then command execution stops
388 ** at an error if we are not interactive.
390 static int bail_on_error = 0;
393 ** Threat stdin as an interactive input if the following variable
394 ** is true. Otherwise, assume stdin is connected to a file or pipe.
396 static int stdin_is_interactive = 1;
399 ** On Windows systems we have to know if standard output is a console
400 ** in order to translate UTF-8 into MBCS. The following variable is
401 ** true if translation is required.
403 static int stdout_is_console = 1;
406 ** The following is the open SQLite database. We make a pointer
407 ** to this database a static variable so that it can be accessed
408 ** by the SIGINT handler to interrupt database processing.
410 static sqlite3 *globalDb = 0;
413 ** True if an interrupt (Control-C) has been received.
415 static volatile int seenInterrupt = 0;
417 #ifdef SQLITE_DEBUG
419 ** Out-of-memory simulator variables
421 static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
422 static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
423 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
424 #endif /* SQLITE_DEBUG */
427 ** This is the name of our program. It is set in main(), used
428 ** in a number of other places, mostly for error messages.
430 static char *Argv0;
433 ** Prompt strings. Initialized in main. Settable with
434 ** .prompt main continue
436 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
437 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
440 ** Render output like fprintf(). Except, if the output is going to the
441 ** console and if this is running on a Windows machine, translate the
442 ** output from UTF-8 into MBCS.
444 #if defined(_WIN32) || defined(WIN32)
445 void utf8_printf(FILE *out, const char *zFormat, ...){
446 va_list ap;
447 va_start(ap, zFormat);
448 if( stdout_is_console && (out==stdout || out==stderr) ){
449 char *z1 = sqlite3_vmprintf(zFormat, ap);
450 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
451 sqlite3_free(z1);
452 fputs(z2, out);
453 sqlite3_free(z2);
454 }else{
455 vfprintf(out, zFormat, ap);
457 va_end(ap);
459 #elif !defined(utf8_printf)
460 # define utf8_printf fprintf
461 #endif
464 ** Render output like fprintf(). This should not be used on anything that
465 ** includes string formatting (e.g. "%s").
467 #if !defined(raw_printf)
468 # define raw_printf fprintf
469 #endif
471 /* Indicate out-of-memory and exit. */
472 static void shell_out_of_memory(void){
473 raw_printf(stderr,"Error: out of memory\n");
474 exit(1);
477 #ifdef SQLITE_DEBUG
478 /* This routine is called when a simulated OOM occurs. It is broken
479 ** out as a separate routine to make it easy to set a breakpoint on
480 ** the OOM
482 void shellOomFault(void){
483 if( oomRepeat>0 ){
484 oomRepeat--;
485 }else{
486 oomCounter--;
489 #endif /* SQLITE_DEBUG */
491 #ifdef SQLITE_DEBUG
492 /* This routine is a replacement malloc() that is used to simulate
493 ** Out-Of-Memory (OOM) errors for testing purposes.
495 static void *oomMalloc(int nByte){
496 if( oomCounter ){
497 if( oomCounter==1 ){
498 shellOomFault();
499 return 0;
500 }else{
501 oomCounter--;
504 return defaultMalloc(nByte);
506 #endif /* SQLITE_DEBUG */
508 #ifdef SQLITE_DEBUG
509 /* Register the OOM simulator. This must occur before any memory
510 ** allocations */
511 static void registerOomSimulator(void){
512 sqlite3_mem_methods mem;
513 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
514 defaultMalloc = mem.xMalloc;
515 mem.xMalloc = oomMalloc;
516 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
518 #endif
521 ** Write I/O traces to the following stream.
523 #ifdef SQLITE_ENABLE_IOTRACE
524 static FILE *iotrace = 0;
525 #endif
528 ** This routine works like printf in that its first argument is a
529 ** format string and subsequent arguments are values to be substituted
530 ** in place of % fields. The result of formatting this string
531 ** is written to iotrace.
533 #ifdef SQLITE_ENABLE_IOTRACE
534 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
535 va_list ap;
536 char *z;
537 if( iotrace==0 ) return;
538 va_start(ap, zFormat);
539 z = sqlite3_vmprintf(zFormat, ap);
540 va_end(ap);
541 utf8_printf(iotrace, "%s", z);
542 sqlite3_free(z);
544 #endif
547 ** Output string zUtf to stream pOut as w characters. If w is negative,
548 ** then right-justify the text. W is the width in UTF-8 characters, not
549 ** in bytes. This is different from the %*.*s specification in printf
550 ** since with %*.*s the width is measured in bytes, not characters.
552 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
553 int i;
554 int n;
555 int aw = w<0 ? -w : w;
556 char zBuf[1000];
557 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
558 for(i=n=0; zUtf[i]; i++){
559 if( (zUtf[i]&0xc0)!=0x80 ){
560 n++;
561 if( n==aw ){
562 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
563 break;
567 if( n>=aw ){
568 utf8_printf(pOut, "%.*s", i, zUtf);
569 }else if( w<0 ){
570 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
571 }else{
572 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
578 ** Determines if a string is a number of not.
580 static int isNumber(const char *z, int *realnum){
581 if( *z=='-' || *z=='+' ) z++;
582 if( !IsDigit(*z) ){
583 return 0;
585 z++;
586 if( realnum ) *realnum = 0;
587 while( IsDigit(*z) ){ z++; }
588 if( *z=='.' ){
589 z++;
590 if( !IsDigit(*z) ) return 0;
591 while( IsDigit(*z) ){ z++; }
592 if( realnum ) *realnum = 1;
594 if( *z=='e' || *z=='E' ){
595 z++;
596 if( *z=='+' || *z=='-' ) z++;
597 if( !IsDigit(*z) ) return 0;
598 while( IsDigit(*z) ){ z++; }
599 if( realnum ) *realnum = 1;
601 return *z==0;
605 ** Compute a string length that is limited to what can be stored in
606 ** lower 30 bits of a 32-bit signed integer.
608 static int strlen30(const char *z){
609 const char *z2 = z;
610 while( *z2 ){ z2++; }
611 return 0x3fffffff & (int)(z2 - z);
615 ** Return the length of a string in characters. Multibyte UTF8 characters
616 ** count as a single character.
618 static int strlenChar(const char *z){
619 int n = 0;
620 while( *z ){
621 if( (0xc0&*(z++))!=0x80 ) n++;
623 return n;
627 ** Return true if zFile does not exist or if it is not an ordinary file.
629 #ifdef _WIN32
630 # define notNormalFile(X) 0
631 #else
632 static int notNormalFile(const char *zFile){
633 struct stat x;
634 int rc;
635 memset(&x, 0, sizeof(x));
636 rc = stat(zFile, &x);
637 return rc || !S_ISREG(x.st_mode);
639 #endif
642 ** This routine reads a line of text from FILE in, stores
643 ** the text in memory obtained from malloc() and returns a pointer
644 ** to the text. NULL is returned at end of file, or if malloc()
645 ** fails.
647 ** If zLine is not NULL then it is a malloced buffer returned from
648 ** a previous call to this routine that may be reused.
650 static char *local_getline(char *zLine, FILE *in){
651 int nLine = zLine==0 ? 0 : 100;
652 int n = 0;
654 while( 1 ){
655 if( n+100>nLine ){
656 nLine = nLine*2 + 100;
657 zLine = realloc(zLine, nLine);
658 if( zLine==0 ) shell_out_of_memory();
660 if( fgets(&zLine[n], nLine - n, in)==0 ){
661 if( n==0 ){
662 free(zLine);
663 return 0;
665 zLine[n] = 0;
666 break;
668 while( zLine[n] ) n++;
669 if( n>0 && zLine[n-1]=='\n' ){
670 n--;
671 if( n>0 && zLine[n-1]=='\r' ) n--;
672 zLine[n] = 0;
673 break;
676 #if defined(_WIN32) || defined(WIN32)
677 /* For interactive input on Windows systems, translate the
678 ** multi-byte characterset characters into UTF-8. */
679 if( stdin_is_interactive && in==stdin ){
680 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
681 if( zTrans ){
682 int nTrans = strlen30(zTrans)+1;
683 if( nTrans>nLine ){
684 zLine = realloc(zLine, nTrans);
685 if( zLine==0 ) shell_out_of_memory();
687 memcpy(zLine, zTrans, nTrans);
688 sqlite3_free(zTrans);
691 #endif /* defined(_WIN32) || defined(WIN32) */
692 return zLine;
696 ** Retrieve a single line of input text.
698 ** If in==0 then read from standard input and prompt before each line.
699 ** If isContinuation is true, then a continuation prompt is appropriate.
700 ** If isContinuation is zero, then the main prompt should be used.
702 ** If zPrior is not NULL then it is a buffer from a prior call to this
703 ** routine that can be reused.
705 ** The result is stored in space obtained from malloc() and must either
706 ** be freed by the caller or else passed back into this routine via the
707 ** zPrior argument for reuse.
709 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
710 char *zPrompt;
711 char *zResult;
712 if( in!=0 ){
713 zResult = local_getline(zPrior, in);
714 }else{
715 zPrompt = isContinuation ? continuePrompt : mainPrompt;
716 #if SHELL_USE_LOCAL_GETLINE
717 printf("%s", zPrompt);
718 fflush(stdout);
719 zResult = local_getline(zPrior, stdin);
720 #else
721 free(zPrior);
722 zResult = shell_readline(zPrompt);
723 /* BEGIN SQLCIPHER */
724 #ifdef SQLITE_HAS_CODEC
725 /* Simplistic filtering of input lines to prevent PRAGKA key and
726 PRAGMA rekey statements from being stored in readline history.
727 Note that this will only prevent single line statements, but that
728 will be sufficient for common cases. */
729 if(zResult && *zResult && (
730 sqlite3_strlike("%pragma%key%=%", zResult, 0)==0 ||
731 sqlite3_strlike("%attach%database%as%key%", zResult, 0)==0
733 ) return zResult;
734 #endif
735 /* END SQLCIPHER */
736 if( zResult && *zResult ) shell_add_history(zResult);
737 #endif
739 return zResult;
744 ** Return the value of a hexadecimal digit. Return -1 if the input
745 ** is not a hex digit.
747 static int hexDigitValue(char c){
748 if( c>='0' && c<='9' ) return c - '0';
749 if( c>='a' && c<='f' ) return c - 'a' + 10;
750 if( c>='A' && c<='F' ) return c - 'A' + 10;
751 return -1;
755 ** Interpret zArg as an integer value, possibly with suffixes.
757 static sqlite3_int64 integerValue(const char *zArg){
758 sqlite3_int64 v = 0;
759 static const struct { char *zSuffix; int iMult; } aMult[] = {
760 { "KiB", 1024 },
761 { "MiB", 1024*1024 },
762 { "GiB", 1024*1024*1024 },
763 { "KB", 1000 },
764 { "MB", 1000000 },
765 { "GB", 1000000000 },
766 { "K", 1000 },
767 { "M", 1000000 },
768 { "G", 1000000000 },
770 int i;
771 int isNeg = 0;
772 if( zArg[0]=='-' ){
773 isNeg = 1;
774 zArg++;
775 }else if( zArg[0]=='+' ){
776 zArg++;
778 if( zArg[0]=='0' && zArg[1]=='x' ){
779 int x;
780 zArg += 2;
781 while( (x = hexDigitValue(zArg[0]))>=0 ){
782 v = (v<<4) + x;
783 zArg++;
785 }else{
786 while( IsDigit(zArg[0]) ){
787 v = v*10 + zArg[0] - '0';
788 zArg++;
791 for(i=0; i<ArraySize(aMult); i++){
792 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
793 v *= aMult[i].iMult;
794 break;
797 return isNeg? -v : v;
801 ** A variable length string to which one can append text.
803 typedef struct ShellText ShellText;
804 struct ShellText {
805 char *z;
806 int n;
807 int nAlloc;
811 ** Initialize and destroy a ShellText object
813 static void initText(ShellText *p){
814 memset(p, 0, sizeof(*p));
816 static void freeText(ShellText *p){
817 free(p->z);
818 initText(p);
821 /* zIn is either a pointer to a NULL-terminated string in memory obtained
822 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
823 ** added to zIn, and the result returned in memory obtained from malloc().
824 ** zIn, if it was not NULL, is freed.
826 ** If the third argument, quote, is not '\0', then it is used as a
827 ** quote character for zAppend.
829 static void appendText(ShellText *p, char const *zAppend, char quote){
830 int len;
831 int i;
832 int nAppend = strlen30(zAppend);
834 len = nAppend+p->n+1;
835 if( quote ){
836 len += 2;
837 for(i=0; i<nAppend; i++){
838 if( zAppend[i]==quote ) len++;
842 if( p->n+len>=p->nAlloc ){
843 p->nAlloc = p->nAlloc*2 + len + 20;
844 p->z = realloc(p->z, p->nAlloc);
845 if( p->z==0 ) shell_out_of_memory();
848 if( quote ){
849 char *zCsr = p->z+p->n;
850 *zCsr++ = quote;
851 for(i=0; i<nAppend; i++){
852 *zCsr++ = zAppend[i];
853 if( zAppend[i]==quote ) *zCsr++ = quote;
855 *zCsr++ = quote;
856 p->n = (int)(zCsr - p->z);
857 *zCsr = '\0';
858 }else{
859 memcpy(p->z+p->n, zAppend, nAppend);
860 p->n += nAppend;
861 p->z[p->n] = '\0';
866 ** Attempt to determine if identifier zName needs to be quoted, either
867 ** because it contains non-alphanumeric characters, or because it is an
868 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
869 ** that quoting is required.
871 ** Return '"' if quoting is required. Return 0 if no quoting is required.
873 static char quoteChar(const char *zName){
874 int i;
875 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
876 for(i=0; zName[i]; i++){
877 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
879 return sqlite3_keyword_check(zName, i) ? '"' : 0;
883 ** Construct a fake object name and column list to describe the structure
884 ** of the view, virtual table, or table valued function zSchema.zName.
886 static char *shellFakeSchema(
887 sqlite3 *db, /* The database connection containing the vtab */
888 const char *zSchema, /* Schema of the database holding the vtab */
889 const char *zName /* The name of the virtual table */
891 sqlite3_stmt *pStmt = 0;
892 char *zSql;
893 ShellText s;
894 char cQuote;
895 char *zDiv = "(";
896 int nRow = 0;
898 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
899 zSchema ? zSchema : "main", zName);
900 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
901 sqlite3_free(zSql);
902 initText(&s);
903 if( zSchema ){
904 cQuote = quoteChar(zSchema);
905 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
906 appendText(&s, zSchema, cQuote);
907 appendText(&s, ".", 0);
909 cQuote = quoteChar(zName);
910 appendText(&s, zName, cQuote);
911 while( sqlite3_step(pStmt)==SQLITE_ROW ){
912 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
913 nRow++;
914 appendText(&s, zDiv, 0);
915 zDiv = ",";
916 cQuote = quoteChar(zCol);
917 appendText(&s, zCol, cQuote);
919 appendText(&s, ")", 0);
920 sqlite3_finalize(pStmt);
921 if( nRow==0 ){
922 freeText(&s);
923 s.z = 0;
925 return s.z;
929 ** SQL function: shell_module_schema(X)
931 ** Return a fake schema for the table-valued function or eponymous virtual
932 ** table X.
934 static void shellModuleSchema(
935 sqlite3_context *pCtx,
936 int nVal,
937 sqlite3_value **apVal
939 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
940 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
941 UNUSED_PARAMETER(nVal);
942 if( zFake ){
943 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
944 -1, sqlite3_free);
945 free(zFake);
950 ** SQL function: shell_add_schema(S,X)
952 ** Add the schema name X to the CREATE statement in S and return the result.
953 ** Examples:
955 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
957 ** Also works on
959 ** CREATE INDEX
960 ** CREATE UNIQUE INDEX
961 ** CREATE VIEW
962 ** CREATE TRIGGER
963 ** CREATE VIRTUAL TABLE
965 ** This UDF is used by the .schema command to insert the schema name of
966 ** attached databases into the middle of the sqlite_schema.sql field.
968 static void shellAddSchemaName(
969 sqlite3_context *pCtx,
970 int nVal,
971 sqlite3_value **apVal
973 static const char *aPrefix[] = {
974 "TABLE",
975 "INDEX",
976 "UNIQUE INDEX",
977 "VIEW",
978 "TRIGGER",
979 "VIRTUAL TABLE"
981 int i = 0;
982 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
983 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
984 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
985 sqlite3 *db = sqlite3_context_db_handle(pCtx);
986 UNUSED_PARAMETER(nVal);
987 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
988 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
989 int n = strlen30(aPrefix[i]);
990 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
991 char *z = 0;
992 char *zFake = 0;
993 if( zSchema ){
994 char cQuote = quoteChar(zSchema);
995 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
996 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
997 }else{
998 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1001 if( zName
1002 && aPrefix[i][0]=='V'
1003 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1005 if( z==0 ){
1006 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1007 }else{
1008 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1010 free(zFake);
1012 if( z ){
1013 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1014 return;
1019 sqlite3_result_value(pCtx, apVal[0]);
1023 ** The source code for several run-time loadable extensions is inserted
1024 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1025 ** code, we need to override some macros to make the included program code
1026 ** work here in the middle of this regular program.
1028 #define SQLITE_EXTENSION_INIT1
1029 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1031 #if defined(_WIN32) && defined(_MSC_VER)
1032 INCLUDE test_windirent.h
1033 INCLUDE test_windirent.c
1034 #define dirent DIRENT
1035 #endif
1036 INCLUDE ../ext/misc/shathree.c
1037 INCLUDE ../ext/misc/fileio.c
1038 INCLUDE ../ext/misc/completion.c
1039 INCLUDE ../ext/misc/appendvfs.c
1040 INCLUDE ../ext/misc/memtrace.c
1041 INCLUDE ../ext/misc/uint.c
1042 INCLUDE ../ext/misc/decimal.c
1043 INCLUDE ../ext/misc/ieee754.c
1044 #ifdef SQLITE_HAVE_ZLIB
1045 INCLUDE ../ext/misc/zipfile.c
1046 INCLUDE ../ext/misc/sqlar.c
1047 #endif
1048 INCLUDE ../ext/expert/sqlite3expert.h
1049 INCLUDE ../ext/expert/sqlite3expert.c
1051 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1052 INCLUDE ../ext/misc/dbdata.c
1053 #endif
1055 #if defined(SQLITE_ENABLE_SESSION)
1057 ** State information for a single open session
1059 typedef struct OpenSession OpenSession;
1060 struct OpenSession {
1061 char *zName; /* Symbolic name for this session */
1062 int nFilter; /* Number of xFilter rejection GLOB patterns */
1063 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1064 sqlite3_session *p; /* The open session */
1066 #endif
1068 typedef struct ExpertInfo ExpertInfo;
1069 struct ExpertInfo {
1070 sqlite3expert *pExpert;
1071 int bVerbose;
1074 /* A single line in the EQP output */
1075 typedef struct EQPGraphRow EQPGraphRow;
1076 struct EQPGraphRow {
1077 int iEqpId; /* ID for this row */
1078 int iParentId; /* ID of the parent row */
1079 EQPGraphRow *pNext; /* Next row in sequence */
1080 char zText[1]; /* Text to display for this row */
1083 /* All EQP output is collected into an instance of the following */
1084 typedef struct EQPGraph EQPGraph;
1085 struct EQPGraph {
1086 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1087 EQPGraphRow *pLast; /* Last element of the pRow list */
1088 char zPrefix[100]; /* Graph prefix */
1092 ** State information about the database connection is contained in an
1093 ** instance of the following structure.
1095 typedef struct ShellState ShellState;
1096 struct ShellState {
1097 sqlite3 *db; /* The database */
1098 u8 autoExplain; /* Automatically turn on .explain mode */
1099 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1100 u8 autoEQPtest; /* autoEQP is in test mode */
1101 u8 autoEQPtrace; /* autoEQP is in trace mode */
1102 u8 statsOn; /* True to display memory stats before each finalize */
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 mEqpLines; /* Mask of veritical lines in the EQP output graph */
1109 int outCount; /* Revert to stdout when reaching zero */
1110 int cnt; /* Number of records displayed so far */
1111 int lineno; /* Line number of last line read from in */
1112 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1113 FILE *in; /* Read commands from this stream */
1114 FILE *out; /* Write results here */
1115 FILE *traceOut; /* Output for sqlite3_trace() */
1116 int nErr; /* Number of errors seen */
1117 int mode; /* An output mode setting */
1118 int modePrior; /* Saved mode */
1119 int cMode; /* temporary output mode for the current query */
1120 int normalMode; /* Output mode before ".explain on" */
1121 int writableSchema; /* True if PRAGMA writable_schema=ON */
1122 int showHeader; /* True to show column names in List or Column mode */
1123 int nCheck; /* Number of ".check" commands run */
1124 unsigned nProgress; /* Number of progress callbacks encountered */
1125 unsigned mxProgress; /* Maximum progress callbacks before failing */
1126 unsigned flgProgress; /* Flags for the progress callback */
1127 unsigned shellFlgs; /* Various flags */
1128 unsigned priorShFlgs; /* Saved copy of flags */
1129 sqlite3_int64 szMax; /* --maxsize argument to .open */
1130 char *zDestTable; /* Name of destination table when MODE_Insert */
1131 char *zTempFile; /* Temporary file that might need deleting */
1132 char zTestcase[30]; /* Name of current test case */
1133 char colSeparator[20]; /* Column separator character for several modes */
1134 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1135 char colSepPrior[20]; /* Saved column separator */
1136 char rowSepPrior[20]; /* Saved row separator */
1137 int *colWidth; /* Requested width of each column in columnar modes */
1138 int *actualWidth; /* Actual width of each column */
1139 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1140 char nullValue[20]; /* The text to print when a NULL comes back from
1141 ** the database */
1142 char outfile[FILENAME_MAX]; /* Filename for *out */
1143 const char *zDbFilename; /* name of the database file */
1144 char *zFreeOnClose; /* Filename to free when closing */
1145 const char *zVfs; /* Name of VFS to use */
1146 sqlite3_stmt *pStmt; /* Current statement if any. */
1147 FILE *pLog; /* Write log output here */
1148 int *aiIndent; /* Array of indents used in MODE_Explain */
1149 int nIndent; /* Size of array aiIndent[] */
1150 int iIndent; /* Index of current op in aiIndent[] */
1151 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1152 #if defined(SQLITE_ENABLE_SESSION)
1153 int nSession; /* Number of active sessions */
1154 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1155 #endif
1156 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1160 /* Allowed values for ShellState.autoEQP
1162 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1163 #define AUTOEQP_on 1 /* Automatic EQP is on */
1164 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1165 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1167 /* Allowed values for ShellState.openMode
1169 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1170 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1171 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1172 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1173 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1174 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1175 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1177 /* Allowed values for ShellState.eTraceType
1179 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1180 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1181 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1183 /* Bits in the ShellState.flgProgress variable */
1184 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1185 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1186 ** callback limit is reached, and for each
1187 ** top-level SQL statement */
1188 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1191 ** These are the allowed shellFlgs values
1193 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1194 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1195 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1196 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1197 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1198 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1199 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1200 #define SHFLG_HeaderSet 0x00000080 /* .header has been used */
1203 ** Macros for testing and setting shellFlgs
1205 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1206 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1207 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1210 ** These are the allowed modes.
1212 #define MODE_Line 0 /* One column per line. Blank line between records */
1213 #define MODE_Column 1 /* One record per line in neat columns */
1214 #define MODE_List 2 /* One record per line with a separator */
1215 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1216 #define MODE_Html 4 /* Generate an XHTML table */
1217 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1218 #define MODE_Quote 6 /* Quote values as for SQL */
1219 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1220 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1221 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1222 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1223 #define MODE_Pretty 11 /* Pretty-print schemas */
1224 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1225 #define MODE_Json 13 /* Output JSON */
1226 #define MODE_Markdown 14 /* Markdown formatting */
1227 #define MODE_Table 15 /* MySQL-style table formatting */
1228 #define MODE_Box 16 /* Unicode box-drawing characters */
1230 static const char *modeDescr[] = {
1231 "line",
1232 "column",
1233 "list",
1234 "semi",
1235 "html",
1236 "insert",
1237 "quote",
1238 "tcl",
1239 "csv",
1240 "explain",
1241 "ascii",
1242 "prettyprint",
1243 "eqp",
1244 "json",
1245 "markdown",
1246 "table",
1247 "box"
1251 ** These are the column/row/line separators used by the various
1252 ** import/export modes.
1254 #define SEP_Column "|"
1255 #define SEP_Row "\n"
1256 #define SEP_Tab "\t"
1257 #define SEP_Space " "
1258 #define SEP_Comma ","
1259 #define SEP_CrLf "\r\n"
1260 #define SEP_Unit "\x1F"
1261 #define SEP_Record "\x1E"
1264 ** A callback for the sqlite3_log() interface.
1266 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1267 ShellState *p = (ShellState*)pArg;
1268 if( p->pLog==0 ) return;
1269 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1270 fflush(p->pLog);
1274 ** SQL function: shell_putsnl(X)
1276 ** Write the text X to the screen (or whatever output is being directed)
1277 ** adding a newline at the end, and then return X.
1279 static void shellPutsFunc(
1280 sqlite3_context *pCtx,
1281 int nVal,
1282 sqlite3_value **apVal
1284 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1285 (void)nVal;
1286 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1287 sqlite3_result_value(pCtx, apVal[0]);
1291 ** SQL function: edit(VALUE)
1292 ** edit(VALUE,EDITOR)
1294 ** These steps:
1296 ** (1) Write VALUE into a temporary file.
1297 ** (2) Run program EDITOR on that temporary file.
1298 ** (3) Read the temporary file back and return its content as the result.
1299 ** (4) Delete the temporary file
1301 ** If the EDITOR argument is omitted, use the value in the VISUAL
1302 ** environment variable. If still there is no EDITOR, through an error.
1304 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1306 #ifndef SQLITE_NOHAVE_SYSTEM
1307 static void editFunc(
1308 sqlite3_context *context,
1309 int argc,
1310 sqlite3_value **argv
1312 const char *zEditor;
1313 char *zTempFile = 0;
1314 sqlite3 *db;
1315 char *zCmd = 0;
1316 int bBin;
1317 int rc;
1318 int hasCRNL = 0;
1319 FILE *f = 0;
1320 sqlite3_int64 sz;
1321 sqlite3_int64 x;
1322 unsigned char *p = 0;
1324 if( argc==2 ){
1325 zEditor = (const char*)sqlite3_value_text(argv[1]);
1326 }else{
1327 zEditor = getenv("VISUAL");
1329 if( zEditor==0 ){
1330 sqlite3_result_error(context, "no editor for edit()", -1);
1331 return;
1333 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1334 sqlite3_result_error(context, "NULL input to edit()", -1);
1335 return;
1337 db = sqlite3_context_db_handle(context);
1338 zTempFile = 0;
1339 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1340 if( zTempFile==0 ){
1341 sqlite3_uint64 r = 0;
1342 sqlite3_randomness(sizeof(r), &r);
1343 zTempFile = sqlite3_mprintf("temp%llx", r);
1344 if( zTempFile==0 ){
1345 sqlite3_result_error_nomem(context);
1346 return;
1349 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1350 /* When writing the file to be edited, do \n to \r\n conversions on systems
1351 ** that want \r\n line endings */
1352 f = fopen(zTempFile, bBin ? "wb" : "w");
1353 if( f==0 ){
1354 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1355 goto edit_func_end;
1357 sz = sqlite3_value_bytes(argv[0]);
1358 if( bBin ){
1359 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1360 }else{
1361 const char *z = (const char*)sqlite3_value_text(argv[0]);
1362 /* Remember whether or not the value originally contained \r\n */
1363 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1364 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1366 fclose(f);
1367 f = 0;
1368 if( x!=sz ){
1369 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1370 goto edit_func_end;
1372 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1373 if( zCmd==0 ){
1374 sqlite3_result_error_nomem(context);
1375 goto edit_func_end;
1377 rc = system(zCmd);
1378 sqlite3_free(zCmd);
1379 if( rc ){
1380 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1381 goto edit_func_end;
1383 f = fopen(zTempFile, "rb");
1384 if( f==0 ){
1385 sqlite3_result_error(context,
1386 "edit() cannot reopen temp file after edit", -1);
1387 goto edit_func_end;
1389 fseek(f, 0, SEEK_END);
1390 sz = ftell(f);
1391 rewind(f);
1392 p = sqlite3_malloc64( sz+1 );
1393 if( p==0 ){
1394 sqlite3_result_error_nomem(context);
1395 goto edit_func_end;
1397 x = fread(p, 1, (size_t)sz, f);
1398 fclose(f);
1399 f = 0;
1400 if( x!=sz ){
1401 sqlite3_result_error(context, "could not read back the whole file", -1);
1402 goto edit_func_end;
1404 if( bBin ){
1405 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1406 }else{
1407 sqlite3_int64 i, j;
1408 if( hasCRNL ){
1409 /* If the original contains \r\n then do no conversions back to \n */
1410 j = sz;
1411 }else{
1412 /* If the file did not originally contain \r\n then convert any new
1413 ** \r\n back into \n */
1414 for(i=j=0; i<sz; i++){
1415 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1416 p[j++] = p[i];
1418 sz = j;
1419 p[sz] = 0;
1421 sqlite3_result_text64(context, (const char*)p, sz,
1422 sqlite3_free, SQLITE_UTF8);
1424 p = 0;
1426 edit_func_end:
1427 if( f ) fclose(f);
1428 unlink(zTempFile);
1429 sqlite3_free(zTempFile);
1430 sqlite3_free(p);
1432 #endif /* SQLITE_NOHAVE_SYSTEM */
1435 ** Save or restore the current output mode
1437 static void outputModePush(ShellState *p){
1438 p->modePrior = p->mode;
1439 p->priorShFlgs = p->shellFlgs;
1440 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1441 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1443 static void outputModePop(ShellState *p){
1444 p->mode = p->modePrior;
1445 p->shellFlgs = p->priorShFlgs;
1446 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1447 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1451 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1453 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1454 int i;
1455 char *zBlob = (char *)pBlob;
1456 raw_printf(out,"X'");
1457 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1458 raw_printf(out,"'");
1462 ** Find a string that is not found anywhere in z[]. Return a pointer
1463 ** to that string.
1465 ** Try to use zA and zB first. If both of those are already found in z[]
1466 ** then make up some string and store it in the buffer zBuf.
1468 static const char *unused_string(
1469 const char *z, /* Result must not appear anywhere in z */
1470 const char *zA, const char *zB, /* Try these first */
1471 char *zBuf /* Space to store a generated string */
1473 unsigned i = 0;
1474 if( strstr(z, zA)==0 ) return zA;
1475 if( strstr(z, zB)==0 ) return zB;
1477 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1478 }while( strstr(z,zBuf)!=0 );
1479 return zBuf;
1483 ** Output the given string as a quoted string using SQL quoting conventions.
1485 ** See also: output_quoted_escaped_string()
1487 static void output_quoted_string(FILE *out, const char *z){
1488 int i;
1489 char c;
1490 setBinaryMode(out, 1);
1491 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1492 if( c==0 ){
1493 utf8_printf(out,"'%s'",z);
1494 }else{
1495 raw_printf(out, "'");
1496 while( *z ){
1497 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1498 if( c=='\'' ) i++;
1499 if( i ){
1500 utf8_printf(out, "%.*s", i, z);
1501 z += i;
1503 if( c=='\'' ){
1504 raw_printf(out, "'");
1505 continue;
1507 if( c==0 ){
1508 break;
1510 z++;
1512 raw_printf(out, "'");
1514 setTextMode(out, 1);
1518 ** Output the given string as a quoted string using SQL quoting conventions.
1519 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1520 ** get corrupted by end-of-line translation facilities in some operating
1521 ** systems.
1523 ** This is like output_quoted_string() but with the addition of the \r\n
1524 ** escape mechanism.
1526 static void output_quoted_escaped_string(FILE *out, const char *z){
1527 int i;
1528 char c;
1529 setBinaryMode(out, 1);
1530 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1531 if( c==0 ){
1532 utf8_printf(out,"'%s'",z);
1533 }else{
1534 const char *zNL = 0;
1535 const char *zCR = 0;
1536 int nNL = 0;
1537 int nCR = 0;
1538 char zBuf1[20], zBuf2[20];
1539 for(i=0; z[i]; i++){
1540 if( z[i]=='\n' ) nNL++;
1541 if( z[i]=='\r' ) nCR++;
1543 if( nNL ){
1544 raw_printf(out, "replace(");
1545 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1547 if( nCR ){
1548 raw_printf(out, "replace(");
1549 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1551 raw_printf(out, "'");
1552 while( *z ){
1553 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1554 if( c=='\'' ) i++;
1555 if( i ){
1556 utf8_printf(out, "%.*s", i, z);
1557 z += i;
1559 if( c=='\'' ){
1560 raw_printf(out, "'");
1561 continue;
1563 if( c==0 ){
1564 break;
1566 z++;
1567 if( c=='\n' ){
1568 raw_printf(out, "%s", zNL);
1569 continue;
1571 raw_printf(out, "%s", zCR);
1573 raw_printf(out, "'");
1574 if( nCR ){
1575 raw_printf(out, ",'%s',char(13))", zCR);
1577 if( nNL ){
1578 raw_printf(out, ",'%s',char(10))", zNL);
1581 setTextMode(out, 1);
1585 ** Output the given string as a quoted according to C or TCL quoting rules.
1587 static void output_c_string(FILE *out, const char *z){
1588 unsigned int c;
1589 fputc('"', out);
1590 while( (c = *(z++))!=0 ){
1591 if( c=='\\' ){
1592 fputc(c, out);
1593 fputc(c, out);
1594 }else if( c=='"' ){
1595 fputc('\\', out);
1596 fputc('"', out);
1597 }else if( c=='\t' ){
1598 fputc('\\', out);
1599 fputc('t', out);
1600 }else if( c=='\n' ){
1601 fputc('\\', out);
1602 fputc('n', out);
1603 }else if( c=='\r' ){
1604 fputc('\\', out);
1605 fputc('r', out);
1606 }else if( !isprint(c&0xff) ){
1607 raw_printf(out, "\\%03o", c&0xff);
1608 }else{
1609 fputc(c, out);
1612 fputc('"', out);
1616 ** Output the given string as a quoted according to JSON quoting rules.
1618 static void output_json_string(FILE *out, const char *z, int n){
1619 unsigned int c;
1620 if( n<0 ) n = (int)strlen(z);
1621 fputc('"', out);
1622 while( n-- ){
1623 c = *(z++);
1624 if( c=='\\' || c=='"' ){
1625 fputc('\\', out);
1626 fputc(c, out);
1627 }else if( c<=0x1f ){
1628 fputc('\\', out);
1629 if( c=='\b' ){
1630 fputc('b', out);
1631 }else if( c=='\f' ){
1632 fputc('f', out);
1633 }else if( c=='\n' ){
1634 fputc('n', out);
1635 }else if( c=='\r' ){
1636 fputc('r', out);
1637 }else if( c=='\t' ){
1638 fputc('t', out);
1639 }else{
1640 raw_printf(out, "u%04x",c);
1642 }else{
1643 fputc(c, out);
1646 fputc('"', out);
1650 ** Output the given string with characters that are special to
1651 ** HTML escaped.
1653 static void output_html_string(FILE *out, const char *z){
1654 int i;
1655 if( z==0 ) z = "";
1656 while( *z ){
1657 for(i=0; z[i]
1658 && z[i]!='<'
1659 && z[i]!='&'
1660 && z[i]!='>'
1661 && z[i]!='\"'
1662 && z[i]!='\'';
1663 i++){}
1664 if( i>0 ){
1665 utf8_printf(out,"%.*s",i,z);
1667 if( z[i]=='<' ){
1668 raw_printf(out,"&lt;");
1669 }else if( z[i]=='&' ){
1670 raw_printf(out,"&amp;");
1671 }else if( z[i]=='>' ){
1672 raw_printf(out,"&gt;");
1673 }else if( z[i]=='\"' ){
1674 raw_printf(out,"&quot;");
1675 }else if( z[i]=='\'' ){
1676 raw_printf(out,"&#39;");
1677 }else{
1678 break;
1680 z += i + 1;
1685 ** If a field contains any character identified by a 1 in the following
1686 ** array, then the string must be quoted for CSV.
1688 static const char needCsvQuote[] = {
1689 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1690 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1691 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1692 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1693 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1694 0, 0, 0, 0, 0, 0, 0, 0, 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, 1,
1697 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1698 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1699 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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,
1708 ** Output a single term of CSV. Actually, p->colSeparator is used for
1709 ** the separator, which may or may not be a comma. p->nullValue is
1710 ** the null value. Strings are quoted if necessary. The separator
1711 ** is only issued if bSep is true.
1713 static void output_csv(ShellState *p, const char *z, int bSep){
1714 FILE *out = p->out;
1715 if( z==0 ){
1716 utf8_printf(out,"%s",p->nullValue);
1717 }else{
1718 int i;
1719 int nSep = strlen30(p->colSeparator);
1720 for(i=0; z[i]; i++){
1721 if( needCsvQuote[((unsigned char*)z)[i]]
1722 || (z[i]==p->colSeparator[0] &&
1723 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1724 i = 0;
1725 break;
1728 if( i==0 ){
1729 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1730 utf8_printf(out, "%s", zQuoted);
1731 sqlite3_free(zQuoted);
1732 }else{
1733 utf8_printf(out, "%s", z);
1736 if( bSep ){
1737 utf8_printf(p->out, "%s", p->colSeparator);
1742 ** This routine runs when the user presses Ctrl-C
1744 static void interrupt_handler(int NotUsed){
1745 UNUSED_PARAMETER(NotUsed);
1746 seenInterrupt++;
1747 if( seenInterrupt>2 ) exit(1);
1748 if( globalDb ) sqlite3_interrupt(globalDb);
1751 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1753 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1755 static BOOL WINAPI ConsoleCtrlHandler(
1756 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1758 if( dwCtrlType==CTRL_C_EVENT ){
1759 interrupt_handler(0);
1760 return TRUE;
1762 return FALSE;
1764 #endif
1766 #ifndef SQLITE_OMIT_AUTHORIZATION
1768 ** When the ".auth ON" is set, the following authorizer callback is
1769 ** invoked. It always returns SQLITE_OK.
1771 static int shellAuth(
1772 void *pClientData,
1773 int op,
1774 const char *zA1,
1775 const char *zA2,
1776 const char *zA3,
1777 const char *zA4
1779 ShellState *p = (ShellState*)pClientData;
1780 static const char *azAction[] = { 0,
1781 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1782 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1783 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1784 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1785 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1786 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1787 "PRAGMA", "READ", "SELECT",
1788 "TRANSACTION", "UPDATE", "ATTACH",
1789 "DETACH", "ALTER_TABLE", "REINDEX",
1790 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1791 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1793 int i;
1794 const char *az[4];
1795 az[0] = zA1;
1796 az[1] = zA2;
1797 az[2] = zA3;
1798 az[3] = zA4;
1799 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1800 for(i=0; i<4; i++){
1801 raw_printf(p->out, " ");
1802 if( az[i] ){
1803 output_c_string(p->out, az[i]);
1804 }else{
1805 raw_printf(p->out, "NULL");
1808 raw_printf(p->out, "\n");
1809 return SQLITE_OK;
1811 #endif
1814 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1816 ** This routine converts some CREATE TABLE statements for shadow tables
1817 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1819 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1820 if( z==0 ) return;
1821 if( zTail==0 ) return;
1822 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1823 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1824 }else{
1825 utf8_printf(out, "%s%s", z, zTail);
1828 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1829 char c = z[n];
1830 z[n] = 0;
1831 printSchemaLine(out, z, zTail);
1832 z[n] = c;
1836 ** Return true if string z[] has nothing but whitespace and comments to the
1837 ** end of the first line.
1839 static int wsToEol(const char *z){
1840 int i;
1841 for(i=0; z[i]; i++){
1842 if( z[i]=='\n' ) return 1;
1843 if( IsSpace(z[i]) ) continue;
1844 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1845 return 0;
1847 return 1;
1851 ** Add a new entry to the EXPLAIN QUERY PLAN data
1853 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1854 EQPGraphRow *pNew;
1855 int nText = strlen30(zText);
1856 if( p->autoEQPtest ){
1857 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1859 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1860 if( pNew==0 ) shell_out_of_memory();
1861 pNew->iEqpId = iEqpId;
1862 pNew->iParentId = p2;
1863 memcpy(pNew->zText, zText, nText+1);
1864 pNew->pNext = 0;
1865 if( p->sGraph.pLast ){
1866 p->sGraph.pLast->pNext = pNew;
1867 }else{
1868 p->sGraph.pRow = pNew;
1870 p->sGraph.pLast = pNew;
1874 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1875 ** in p->sGraph.
1877 static void eqp_reset(ShellState *p){
1878 EQPGraphRow *pRow, *pNext;
1879 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1880 pNext = pRow->pNext;
1881 sqlite3_free(pRow);
1883 memset(&p->sGraph, 0, sizeof(p->sGraph));
1886 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1887 ** pOld, or return the first such line if pOld is NULL
1889 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1890 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1891 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1892 return pRow;
1895 /* Render a single level of the graph that has iEqpId as its parent. Called
1896 ** recursively to render sublevels.
1898 static void eqp_render_level(ShellState *p, int iEqpId){
1899 EQPGraphRow *pRow, *pNext;
1900 int n = strlen30(p->sGraph.zPrefix);
1901 char *z;
1902 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1903 pNext = eqp_next_row(p, iEqpId, pRow);
1904 z = pRow->zText;
1905 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1906 pNext ? "|--" : "`--", z);
1907 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1908 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
1909 eqp_render_level(p, pRow->iEqpId);
1910 p->sGraph.zPrefix[n] = 0;
1916 ** Display and reset the EXPLAIN QUERY PLAN data
1918 static void eqp_render(ShellState *p){
1919 EQPGraphRow *pRow = p->sGraph.pRow;
1920 if( pRow ){
1921 if( pRow->zText[0]=='-' ){
1922 if( pRow->pNext==0 ){
1923 eqp_reset(p);
1924 return;
1926 utf8_printf(p->out, "%s\n", pRow->zText+3);
1927 p->sGraph.pRow = pRow->pNext;
1928 sqlite3_free(pRow);
1929 }else{
1930 utf8_printf(p->out, "QUERY PLAN\n");
1932 p->sGraph.zPrefix[0] = 0;
1933 eqp_render_level(p, 0);
1934 eqp_reset(p);
1938 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1940 ** Progress handler callback.
1942 static int progress_handler(void *pClientData) {
1943 ShellState *p = (ShellState*)pClientData;
1944 p->nProgress++;
1945 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1946 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
1947 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1948 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
1949 return 1;
1951 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
1952 raw_printf(p->out, "Progress %u\n", p->nProgress);
1954 return 0;
1956 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
1959 ** Print N dashes
1961 static void print_dashes(FILE *out, int N){
1962 const char zDash[] = "--------------------------------------------------";
1963 const int nDash = sizeof(zDash) - 1;
1964 while( N>nDash ){
1965 fputs(zDash, out);
1966 N -= nDash;
1968 raw_printf(out, "%.*s", N, zDash);
1972 ** Print a markdown or table-style row separator using ascii-art
1974 static void print_row_separator(
1975 ShellState *p,
1976 int nArg,
1977 const char *zSep
1979 int i;
1980 if( nArg>0 ){
1981 fputs(zSep, p->out);
1982 print_dashes(p->out, p->actualWidth[0]+2);
1983 for(i=1; i<nArg; i++){
1984 fputs(zSep, p->out);
1985 print_dashes(p->out, p->actualWidth[i]+2);
1987 fputs(zSep, p->out);
1989 fputs("\n", p->out);
1993 ** This is the callback routine that the shell
1994 ** invokes for each row of a query result.
1996 static int shell_callback(
1997 void *pArg,
1998 int nArg, /* Number of result columns */
1999 char **azArg, /* Text of each result column */
2000 char **azCol, /* Column names */
2001 int *aiType /* Column types. Might be NULL */
2003 int i;
2004 ShellState *p = (ShellState*)pArg;
2006 if( azArg==0 ) return 0;
2007 switch( p->cMode ){
2008 case MODE_Line: {
2009 int w = 5;
2010 if( azArg==0 ) break;
2011 for(i=0; i<nArg; i++){
2012 int len = strlen30(azCol[i] ? azCol[i] : "");
2013 if( len>w ) w = len;
2015 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2016 for(i=0; i<nArg; i++){
2017 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2018 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2020 break;
2022 case MODE_Explain: {
2023 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2024 if( nArg>ArraySize(aExplainWidth) ){
2025 nArg = ArraySize(aExplainWidth);
2027 if( p->cnt++==0 ){
2028 for(i=0; i<nArg; i++){
2029 int w = aExplainWidth[i];
2030 utf8_width_print(p->out, w, azCol[i]);
2031 fputs(i==nArg-1 ? "\n" : " ", p->out);
2033 for(i=0; i<nArg; i++){
2034 int w = aExplainWidth[i];
2035 print_dashes(p->out, w);
2036 fputs(i==nArg-1 ? "\n" : " ", p->out);
2039 if( azArg==0 ) break;
2040 for(i=0; i<nArg; i++){
2041 int w = aExplainWidth[i];
2042 if( azArg[i] && strlenChar(azArg[i])>w ){
2043 w = strlenChar(azArg[i]);
2045 if( i==1 && p->aiIndent && p->pStmt ){
2046 if( p->iIndent<p->nIndent ){
2047 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2049 p->iIndent++;
2051 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2052 fputs(i==nArg-1 ? "\n" : " ", p->out);
2054 break;
2056 case MODE_Semi: { /* .schema and .fullschema output */
2057 printSchemaLine(p->out, azArg[0], ";\n");
2058 break;
2060 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2061 char *z;
2062 int j;
2063 int nParen = 0;
2064 char cEnd = 0;
2065 char c;
2066 int nLine = 0;
2067 assert( nArg==1 );
2068 if( azArg[0]==0 ) break;
2069 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2070 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2072 utf8_printf(p->out, "%s;\n", azArg[0]);
2073 break;
2075 z = sqlite3_mprintf("%s", azArg[0]);
2076 j = 0;
2077 for(i=0; IsSpace(z[i]); i++){}
2078 for(; (c = z[i])!=0; i++){
2079 if( IsSpace(c) ){
2080 if( z[j-1]=='\r' ) z[j-1] = '\n';
2081 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2082 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2083 j--;
2085 z[j++] = c;
2087 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2088 z[j] = 0;
2089 if( strlen30(z)>=79 ){
2090 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2091 if( c==cEnd ){
2092 cEnd = 0;
2093 }else if( c=='"' || c=='\'' || c=='`' ){
2094 cEnd = c;
2095 }else if( c=='[' ){
2096 cEnd = ']';
2097 }else if( c=='-' && z[i+1]=='-' ){
2098 cEnd = '\n';
2099 }else if( c=='(' ){
2100 nParen++;
2101 }else if( c==')' ){
2102 nParen--;
2103 if( nLine>0 && nParen==0 && j>0 ){
2104 printSchemaLineN(p->out, z, j, "\n");
2105 j = 0;
2108 z[j++] = c;
2109 if( nParen==1 && cEnd==0
2110 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2112 if( c=='\n' ) j--;
2113 printSchemaLineN(p->out, z, j, "\n ");
2114 j = 0;
2115 nLine++;
2116 while( IsSpace(z[i+1]) ){ i++; }
2119 z[j] = 0;
2121 printSchemaLine(p->out, z, ";\n");
2122 sqlite3_free(z);
2123 break;
2125 case MODE_List: {
2126 if( p->cnt++==0 && p->showHeader ){
2127 for(i=0; i<nArg; i++){
2128 utf8_printf(p->out,"%s%s",azCol[i],
2129 i==nArg-1 ? p->rowSeparator : p->colSeparator);
2132 if( azArg==0 ) break;
2133 for(i=0; i<nArg; i++){
2134 char *z = azArg[i];
2135 if( z==0 ) z = p->nullValue;
2136 utf8_printf(p->out, "%s", z);
2137 if( i<nArg-1 ){
2138 utf8_printf(p->out, "%s", p->colSeparator);
2139 }else{
2140 utf8_printf(p->out, "%s", p->rowSeparator);
2143 break;
2145 case MODE_Html: {
2146 if( p->cnt++==0 && p->showHeader ){
2147 raw_printf(p->out,"<TR>");
2148 for(i=0; i<nArg; i++){
2149 raw_printf(p->out,"<TH>");
2150 output_html_string(p->out, azCol[i]);
2151 raw_printf(p->out,"</TH>\n");
2153 raw_printf(p->out,"</TR>\n");
2155 if( azArg==0 ) break;
2156 raw_printf(p->out,"<TR>");
2157 for(i=0; i<nArg; i++){
2158 raw_printf(p->out,"<TD>");
2159 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2160 raw_printf(p->out,"</TD>\n");
2162 raw_printf(p->out,"</TR>\n");
2163 break;
2165 case MODE_Tcl: {
2166 if( p->cnt++==0 && p->showHeader ){
2167 for(i=0; i<nArg; i++){
2168 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2169 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2171 utf8_printf(p->out, "%s", p->rowSeparator);
2173 if( azArg==0 ) break;
2174 for(i=0; i<nArg; i++){
2175 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2176 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2178 utf8_printf(p->out, "%s", p->rowSeparator);
2179 break;
2181 case MODE_Csv: {
2182 setBinaryMode(p->out, 1);
2183 if( p->cnt++==0 && p->showHeader ){
2184 for(i=0; i<nArg; i++){
2185 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2187 utf8_printf(p->out, "%s", p->rowSeparator);
2189 if( nArg>0 ){
2190 for(i=0; i<nArg; i++){
2191 output_csv(p, azArg[i], i<nArg-1);
2193 utf8_printf(p->out, "%s", p->rowSeparator);
2195 setTextMode(p->out, 1);
2196 break;
2198 case MODE_Insert: {
2199 if( azArg==0 ) break;
2200 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2201 if( p->showHeader ){
2202 raw_printf(p->out,"(");
2203 for(i=0; i<nArg; i++){
2204 if( i>0 ) raw_printf(p->out, ",");
2205 if( quoteChar(azCol[i]) ){
2206 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2207 utf8_printf(p->out, "%s", z);
2208 sqlite3_free(z);
2209 }else{
2210 raw_printf(p->out, "%s", azCol[i]);
2213 raw_printf(p->out,")");
2215 p->cnt++;
2216 for(i=0; i<nArg; i++){
2217 raw_printf(p->out, i>0 ? "," : " VALUES(");
2218 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2219 utf8_printf(p->out,"NULL");
2220 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2221 if( ShellHasFlag(p, SHFLG_Newlines) ){
2222 output_quoted_string(p->out, azArg[i]);
2223 }else{
2224 output_quoted_escaped_string(p->out, azArg[i]);
2226 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2227 utf8_printf(p->out,"%s", azArg[i]);
2228 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2229 char z[50];
2230 double r = sqlite3_column_double(p->pStmt, i);
2231 sqlite3_uint64 ur;
2232 memcpy(&ur,&r,sizeof(r));
2233 if( ur==0x7ff0000000000000LL ){
2234 raw_printf(p->out, "1e999");
2235 }else if( ur==0xfff0000000000000LL ){
2236 raw_printf(p->out, "-1e999");
2237 }else{
2238 sqlite3_snprintf(50,z,"%!.20g", r);
2239 raw_printf(p->out, "%s", z);
2241 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2242 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2243 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2244 output_hex_blob(p->out, pBlob, nBlob);
2245 }else if( isNumber(azArg[i], 0) ){
2246 utf8_printf(p->out,"%s", azArg[i]);
2247 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2248 output_quoted_string(p->out, azArg[i]);
2249 }else{
2250 output_quoted_escaped_string(p->out, azArg[i]);
2253 raw_printf(p->out,");\n");
2254 break;
2256 case MODE_Json: {
2257 if( azArg==0 ) break;
2258 if( p->cnt==0 ){
2259 fputs("[{", p->out);
2260 }else{
2261 fputs(",\n{", p->out);
2263 p->cnt++;
2264 for(i=0; i<nArg; i++){
2265 output_json_string(p->out, azCol[i], -1);
2266 putc(':', p->out);
2267 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2268 fputs("null",p->out);
2269 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2270 char z[50];
2271 double r = sqlite3_column_double(p->pStmt, i);
2272 sqlite3_uint64 ur;
2273 memcpy(&ur,&r,sizeof(r));
2274 if( ur==0x7ff0000000000000LL ){
2275 raw_printf(p->out, "1e999");
2276 }else if( ur==0xfff0000000000000LL ){
2277 raw_printf(p->out, "-1e999");
2278 }else{
2279 sqlite3_snprintf(50,z,"%!.20g", r);
2280 raw_printf(p->out, "%s", z);
2282 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2283 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2284 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2285 output_json_string(p->out, pBlob, nBlob);
2286 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2287 output_json_string(p->out, azArg[i], -1);
2288 }else{
2289 utf8_printf(p->out,"%s", azArg[i]);
2291 if( i<nArg-1 ){
2292 putc(',', p->out);
2295 putc('}', p->out);
2296 break;
2298 case MODE_Quote: {
2299 if( azArg==0 ) break;
2300 if( p->cnt==0 && p->showHeader ){
2301 for(i=0; i<nArg; i++){
2302 if( i>0 ) fputs(p->colSeparator, p->out);
2303 output_quoted_string(p->out, azCol[i]);
2305 fputs(p->rowSeparator, p->out);
2307 p->cnt++;
2308 for(i=0; i<nArg; i++){
2309 if( i>0 ) fputs(p->colSeparator, p->out);
2310 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2311 utf8_printf(p->out,"NULL");
2312 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2313 output_quoted_string(p->out, azArg[i]);
2314 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2315 utf8_printf(p->out,"%s", azArg[i]);
2316 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2317 char z[50];
2318 double r = sqlite3_column_double(p->pStmt, i);
2319 sqlite3_snprintf(50,z,"%!.20g", r);
2320 raw_printf(p->out, "%s", z);
2321 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2322 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2323 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2324 output_hex_blob(p->out, pBlob, nBlob);
2325 }else if( isNumber(azArg[i], 0) ){
2326 utf8_printf(p->out,"%s", azArg[i]);
2327 }else{
2328 output_quoted_string(p->out, azArg[i]);
2331 fputs(p->rowSeparator, p->out);
2332 break;
2334 case MODE_Ascii: {
2335 if( p->cnt++==0 && p->showHeader ){
2336 for(i=0; i<nArg; i++){
2337 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2338 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2340 utf8_printf(p->out, "%s", p->rowSeparator);
2342 if( azArg==0 ) break;
2343 for(i=0; i<nArg; i++){
2344 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2345 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2347 utf8_printf(p->out, "%s", p->rowSeparator);
2348 break;
2350 case MODE_EQP: {
2351 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2352 break;
2355 return 0;
2359 ** This is the callback routine that the SQLite library
2360 ** invokes for each row of a query result.
2362 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2363 /* since we don't have type info, call the shell_callback with a NULL value */
2364 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2368 ** This is the callback routine from sqlite3_exec() that appends all
2369 ** output onto the end of a ShellText object.
2371 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2372 ShellText *p = (ShellText*)pArg;
2373 int i;
2374 UNUSED_PARAMETER(az);
2375 if( azArg==0 ) return 0;
2376 if( p->n ) appendText(p, "|", 0);
2377 for(i=0; i<nArg; i++){
2378 if( i ) appendText(p, ",", 0);
2379 if( azArg[i] ) appendText(p, azArg[i], 0);
2381 return 0;
2385 ** Generate an appropriate SELFTEST table in the main database.
2387 static void createSelftestTable(ShellState *p){
2388 char *zErrMsg = 0;
2389 sqlite3_exec(p->db,
2390 "SAVEPOINT selftest_init;\n"
2391 "CREATE TABLE IF NOT EXISTS selftest(\n"
2392 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2393 " op TEXT,\n" /* Operator: memo run */
2394 " cmd TEXT,\n" /* Command text */
2395 " ans TEXT\n" /* Desired answer */
2396 ");"
2397 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2398 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2399 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2400 " 'memo','Tests generated by --init');\n"
2401 "INSERT INTO [_shell$self]\n"
2402 " SELECT 'run',\n"
2403 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2404 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2405 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2406 "FROM sqlite_schema ORDER BY 2',224));\n"
2407 "INSERT INTO [_shell$self]\n"
2408 " SELECT 'run',"
2409 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2410 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2411 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2412 " FROM (\n"
2413 " SELECT name FROM sqlite_schema\n"
2414 " WHERE type='table'\n"
2415 " AND name<>'selftest'\n"
2416 " AND coalesce(rootpage,0)>0\n"
2417 " )\n"
2418 " ORDER BY name;\n"
2419 "INSERT INTO [_shell$self]\n"
2420 " VALUES('run','PRAGMA integrity_check','ok');\n"
2421 "INSERT INTO selftest(tno,op,cmd,ans)"
2422 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2423 "DROP TABLE [_shell$self];"
2424 ,0,0,&zErrMsg);
2425 if( zErrMsg ){
2426 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2427 sqlite3_free(zErrMsg);
2429 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2434 ** Set the destination table field of the ShellState structure to
2435 ** the name of the table given. Escape any quote characters in the
2436 ** table name.
2438 static void set_table_name(ShellState *p, const char *zName){
2439 int i, n;
2440 char cQuote;
2441 char *z;
2443 if( p->zDestTable ){
2444 free(p->zDestTable);
2445 p->zDestTable = 0;
2447 if( zName==0 ) return;
2448 cQuote = quoteChar(zName);
2449 n = strlen30(zName);
2450 if( cQuote ) n += n+2;
2451 z = p->zDestTable = malloc( n+1 );
2452 if( z==0 ) shell_out_of_memory();
2453 n = 0;
2454 if( cQuote ) z[n++] = cQuote;
2455 for(i=0; zName[i]; i++){
2456 z[n++] = zName[i];
2457 if( zName[i]==cQuote ) z[n++] = cQuote;
2459 if( cQuote ) z[n++] = cQuote;
2460 z[n] = 0;
2465 ** Execute a query statement that will generate SQL output. Print
2466 ** the result columns, comma-separated, on a line and then add a
2467 ** semicolon terminator to the end of that line.
2469 ** If the number of columns is 1 and that column contains text "--"
2470 ** then write the semicolon on a separate line. That way, if a
2471 ** "--" comment occurs at the end of the statement, the comment
2472 ** won't consume the semicolon terminator.
2474 static int run_table_dump_query(
2475 ShellState *p, /* Query context */
2476 const char *zSelect /* SELECT statement to extract content */
2478 sqlite3_stmt *pSelect;
2479 int rc;
2480 int nResult;
2481 int i;
2482 const char *z;
2483 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2484 if( rc!=SQLITE_OK || !pSelect ){
2485 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2486 sqlite3_errmsg(p->db));
2487 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2488 return rc;
2490 rc = sqlite3_step(pSelect);
2491 nResult = sqlite3_column_count(pSelect);
2492 while( rc==SQLITE_ROW ){
2493 z = (const char*)sqlite3_column_text(pSelect, 0);
2494 utf8_printf(p->out, "%s", z);
2495 for(i=1; i<nResult; i++){
2496 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2498 if( z==0 ) z = "";
2499 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2500 if( z[0] ){
2501 raw_printf(p->out, "\n;\n");
2502 }else{
2503 raw_printf(p->out, ";\n");
2505 rc = sqlite3_step(pSelect);
2507 rc = sqlite3_finalize(pSelect);
2508 if( rc!=SQLITE_OK ){
2509 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2510 sqlite3_errmsg(p->db));
2511 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2513 return rc;
2517 ** Allocate space and save off current error string.
2519 static char *save_err_msg(
2520 sqlite3 *db /* Database to query */
2522 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2523 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2524 if( zErrMsg ){
2525 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2527 return zErrMsg;
2530 #ifdef __linux__
2532 ** Attempt to display I/O stats on Linux using /proc/PID/io
2534 static void displayLinuxIoStats(FILE *out){
2535 FILE *in;
2536 char z[200];
2537 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2538 in = fopen(z, "rb");
2539 if( in==0 ) return;
2540 while( fgets(z, sizeof(z), in)!=0 ){
2541 static const struct {
2542 const char *zPattern;
2543 const char *zDesc;
2544 } aTrans[] = {
2545 { "rchar: ", "Bytes received by read():" },
2546 { "wchar: ", "Bytes sent to write():" },
2547 { "syscr: ", "Read() system calls:" },
2548 { "syscw: ", "Write() system calls:" },
2549 { "read_bytes: ", "Bytes read from storage:" },
2550 { "write_bytes: ", "Bytes written to storage:" },
2551 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2553 int i;
2554 for(i=0; i<ArraySize(aTrans); i++){
2555 int n = strlen30(aTrans[i].zPattern);
2556 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2557 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2558 break;
2562 fclose(in);
2564 #endif
2567 ** Display a single line of status using 64-bit values.
2569 static void displayStatLine(
2570 ShellState *p, /* The shell context */
2571 char *zLabel, /* Label for this one line */
2572 char *zFormat, /* Format for the result */
2573 int iStatusCtrl, /* Which status to display */
2574 int bReset /* True to reset the stats */
2576 sqlite3_int64 iCur = -1;
2577 sqlite3_int64 iHiwtr = -1;
2578 int i, nPercent;
2579 char zLine[200];
2580 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2581 for(i=0, nPercent=0; zFormat[i]; i++){
2582 if( zFormat[i]=='%' ) nPercent++;
2584 if( nPercent>1 ){
2585 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2586 }else{
2587 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2589 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2593 ** Display memory stats.
2595 static int display_stats(
2596 sqlite3 *db, /* Database to query */
2597 ShellState *pArg, /* Pointer to ShellState */
2598 int bReset /* True to reset the stats */
2600 int iCur;
2601 int iHiwtr;
2602 FILE *out;
2603 if( pArg==0 || pArg->out==0 ) return 0;
2604 out = pArg->out;
2606 if( pArg->pStmt && (pArg->statsOn & 2) ){
2607 int nCol, i, x;
2608 sqlite3_stmt *pStmt = pArg->pStmt;
2609 char z[100];
2610 nCol = sqlite3_column_count(pStmt);
2611 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2612 for(i=0; i<nCol; i++){
2613 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2614 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2615 #ifndef SQLITE_OMIT_DECLTYPE
2616 sqlite3_snprintf(30, z+x, "declared type:");
2617 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2618 #endif
2619 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2620 sqlite3_snprintf(30, z+x, "database name:");
2621 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2622 sqlite3_snprintf(30, z+x, "table name:");
2623 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2624 sqlite3_snprintf(30, z+x, "origin name:");
2625 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2626 #endif
2630 displayStatLine(pArg, "Memory Used:",
2631 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2632 displayStatLine(pArg, "Number of Outstanding Allocations:",
2633 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2634 if( pArg->shellFlgs & SHFLG_Pagecache ){
2635 displayStatLine(pArg, "Number of Pcache Pages Used:",
2636 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2638 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2639 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2640 displayStatLine(pArg, "Largest Allocation:",
2641 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2642 displayStatLine(pArg, "Largest Pcache Allocation:",
2643 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2644 #ifdef YYTRACKMAXSTACKDEPTH
2645 displayStatLine(pArg, "Deepest Parser Stack:",
2646 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2647 #endif
2649 if( db ){
2650 if( pArg->shellFlgs & SHFLG_Lookaside ){
2651 iHiwtr = iCur = -1;
2652 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2653 &iCur, &iHiwtr, bReset);
2654 raw_printf(pArg->out,
2655 "Lookaside Slots Used: %d (max %d)\n",
2656 iCur, iHiwtr);
2657 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2658 &iCur, &iHiwtr, bReset);
2659 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2660 iHiwtr);
2661 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2662 &iCur, &iHiwtr, bReset);
2663 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2664 iHiwtr);
2665 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2666 &iCur, &iHiwtr, bReset);
2667 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2668 iHiwtr);
2670 iHiwtr = iCur = -1;
2671 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2672 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2673 iCur);
2674 iHiwtr = iCur = -1;
2675 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2676 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2677 iHiwtr = iCur = -1;
2678 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2679 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2680 iHiwtr = iCur = -1;
2681 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2682 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2683 iHiwtr = iCur = -1;
2684 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2685 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2686 iHiwtr = iCur = -1;
2687 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2688 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2689 iCur);
2690 iHiwtr = iCur = -1;
2691 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2692 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2693 iCur);
2696 if( pArg->pStmt ){
2697 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2698 bReset);
2699 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2700 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2701 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2702 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2703 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2704 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2705 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2706 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2707 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2708 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2709 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2710 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2711 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
2714 #ifdef __linux__
2715 displayLinuxIoStats(pArg->out);
2716 #endif
2718 /* Do not remove this machine readable comment: extra-stats-output-here */
2720 return 0;
2724 ** Display scan stats.
2726 static void display_scanstats(
2727 sqlite3 *db, /* Database to query */
2728 ShellState *pArg /* Pointer to ShellState */
2730 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2731 UNUSED_PARAMETER(db);
2732 UNUSED_PARAMETER(pArg);
2733 #else
2734 int i, k, n, mx;
2735 raw_printf(pArg->out, "-------- scanstats --------\n");
2736 mx = 0;
2737 for(k=0; k<=mx; k++){
2738 double rEstLoop = 1.0;
2739 for(i=n=0; 1; i++){
2740 sqlite3_stmt *p = pArg->pStmt;
2741 sqlite3_int64 nLoop, nVisit;
2742 double rEst;
2743 int iSid;
2744 const char *zExplain;
2745 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2746 break;
2748 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2749 if( iSid>mx ) mx = iSid;
2750 if( iSid!=k ) continue;
2751 if( n==0 ){
2752 rEstLoop = (double)nLoop;
2753 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2755 n++;
2756 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2757 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2758 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2759 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2760 rEstLoop *= rEst;
2761 raw_printf(pArg->out,
2762 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2763 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2767 raw_printf(pArg->out, "---------------------------\n");
2768 #endif
2772 ** Parameter azArray points to a zero-terminated array of strings. zStr
2773 ** points to a single nul-terminated string. Return non-zero if zStr
2774 ** is equal, according to strcmp(), to any of the strings in the array.
2775 ** Otherwise, return zero.
2777 static int str_in_array(const char *zStr, const char **azArray){
2778 int i;
2779 for(i=0; azArray[i]; i++){
2780 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2782 return 0;
2786 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2787 ** and populate the ShellState.aiIndent[] array with the number of
2788 ** spaces each opcode should be indented before it is output.
2790 ** The indenting rules are:
2792 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2793 ** all opcodes that occur between the p2 jump destination and the opcode
2794 ** itself by 2 spaces.
2796 ** * For each "Goto", if the jump destination is earlier in the program
2797 ** and ends on one of:
2798 ** Yield SeekGt SeekLt RowSetRead Rewind
2799 ** or if the P1 parameter is one instead of zero,
2800 ** then indent all opcodes between the earlier instruction
2801 ** and "Goto" by 2 spaces.
2803 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2804 const char *zSql; /* The text of the SQL statement */
2805 const char *z; /* Used to check if this is an EXPLAIN */
2806 int *abYield = 0; /* True if op is an OP_Yield */
2807 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2808 int iOp; /* Index of operation in p->aiIndent[] */
2810 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2811 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2812 "Rewind", 0 };
2813 const char *azGoto[] = { "Goto", 0 };
2815 /* Try to figure out if this is really an EXPLAIN statement. If this
2816 ** cannot be verified, return early. */
2817 if( sqlite3_column_count(pSql)!=8 ){
2818 p->cMode = p->mode;
2819 return;
2821 zSql = sqlite3_sql(pSql);
2822 if( zSql==0 ) return;
2823 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2824 if( sqlite3_strnicmp(z, "explain", 7) ){
2825 p->cMode = p->mode;
2826 return;
2829 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2830 int i;
2831 int iAddr = sqlite3_column_int(pSql, 0);
2832 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2834 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2835 ** p2 is an instruction address, set variable p2op to the index of that
2836 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2837 ** the current instruction is part of a sub-program generated by an
2838 ** SQL trigger or foreign key. */
2839 int p2 = sqlite3_column_int(pSql, 3);
2840 int p2op = (p2 + (iOp-iAddr));
2842 /* Grow the p->aiIndent array as required */
2843 if( iOp>=nAlloc ){
2844 if( iOp==0 ){
2845 /* Do further verfication that this is explain output. Abort if
2846 ** it is not */
2847 static const char *explainCols[] = {
2848 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2849 int jj;
2850 for(jj=0; jj<ArraySize(explainCols); jj++){
2851 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2852 p->cMode = p->mode;
2853 sqlite3_reset(pSql);
2854 return;
2858 nAlloc += 100;
2859 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2860 if( p->aiIndent==0 ) shell_out_of_memory();
2861 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2862 if( abYield==0 ) shell_out_of_memory();
2864 abYield[iOp] = str_in_array(zOp, azYield);
2865 p->aiIndent[iOp] = 0;
2866 p->nIndent = iOp+1;
2868 if( str_in_array(zOp, azNext) ){
2869 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2871 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2872 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2874 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2878 p->iIndent = 0;
2879 sqlite3_free(abYield);
2880 sqlite3_reset(pSql);
2884 ** Free the array allocated by explain_data_prepare().
2886 static void explain_data_delete(ShellState *p){
2887 sqlite3_free(p->aiIndent);
2888 p->aiIndent = 0;
2889 p->nIndent = 0;
2890 p->iIndent = 0;
2894 ** Disable and restore .wheretrace and .selecttrace settings.
2896 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2897 extern unsigned int sqlite3_unsupported_selecttrace;
2898 static int savedSelectTrace;
2899 #endif
2900 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2901 extern int sqlite3WhereTrace;
2902 static int savedWhereTrace;
2903 #endif
2904 static void disable_debug_trace_modes(void){
2905 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2906 savedSelectTrace = sqlite3_unsupported_selecttrace;
2907 sqlite3_unsupported_selecttrace = 0;
2908 #endif
2909 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2910 savedWhereTrace = sqlite3WhereTrace;
2911 sqlite3WhereTrace = 0;
2912 #endif
2914 static void restore_debug_trace_modes(void){
2915 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2916 sqlite3_unsupported_selecttrace = savedSelectTrace;
2917 #endif
2918 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2919 sqlite3WhereTrace = savedWhereTrace;
2920 #endif
2923 /* Create the TEMP table used to store parameter bindings */
2924 static void bind_table_init(ShellState *p){
2925 int wrSchema = 0;
2926 int defensiveMode = 0;
2927 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
2928 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
2929 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2930 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
2931 sqlite3_exec(p->db,
2932 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
2933 " key TEXT PRIMARY KEY,\n"
2934 " value ANY\n"
2935 ") WITHOUT ROWID;",
2936 0, 0, 0);
2937 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
2938 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
2942 ** Bind parameters on a prepared statement.
2944 ** Parameter bindings are taken from a TEMP table of the form:
2946 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
2947 ** WITHOUT ROWID;
2949 ** No bindings occur if this table does not exist. The name of the table
2950 ** begins with "sqlite_" so that it will not collide with ordinary application
2951 ** tables. The table must be in the TEMP schema.
2953 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2954 int nVar;
2955 int i;
2956 int rc;
2957 sqlite3_stmt *pQ = 0;
2959 nVar = sqlite3_bind_parameter_count(pStmt);
2960 if( nVar==0 ) return; /* Nothing to do */
2961 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
2962 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2963 return; /* Parameter table does not exist */
2965 rc = sqlite3_prepare_v2(pArg->db,
2966 "SELECT value FROM temp.sqlite_parameters"
2967 " WHERE key=?1", -1, &pQ, 0);
2968 if( rc || pQ==0 ) return;
2969 for(i=1; i<=nVar; i++){
2970 char zNum[30];
2971 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2972 if( zVar==0 ){
2973 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2974 zVar = zNum;
2976 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2977 if( sqlite3_step(pQ)==SQLITE_ROW ){
2978 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2979 }else{
2980 sqlite3_bind_null(pStmt, i);
2982 sqlite3_reset(pQ);
2984 sqlite3_finalize(pQ);
2988 ** UTF8 box-drawing characters. Imagine box lines like this:
2990 ** 1
2991 ** |
2992 ** 4 --+-- 2
2993 ** |
2994 ** 3
2996 ** Each box characters has between 2 and 4 of the lines leading from
2997 ** the center. The characters are here identified by the numbers of
2998 ** their corresponding lines.
3000 #define BOX_24 "\342\224\200" /* U+2500 --- */
3001 #define BOX_13 "\342\224\202" /* U+2502 | */
3002 #define BOX_23 "\342\224\214" /* U+250c ,- */
3003 #define BOX_34 "\342\224\220" /* U+2510 -, */
3004 #define BOX_12 "\342\224\224" /* U+2514 '- */
3005 #define BOX_14 "\342\224\230" /* U+2518 -' */
3006 #define BOX_123 "\342\224\234" /* U+251c |- */
3007 #define BOX_134 "\342\224\244" /* U+2524 -| */
3008 #define BOX_234 "\342\224\254" /* U+252c -,- */
3009 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3010 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3012 /* Draw horizontal line N characters long using unicode box
3013 ** characters
3015 static void print_box_line(FILE *out, int N){
3016 const char zDash[] =
3017 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3018 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3019 const int nDash = sizeof(zDash) - 1;
3020 N *= 3;
3021 while( N>nDash ){
3022 utf8_printf(out, zDash);
3023 N -= nDash;
3025 utf8_printf(out, "%.*s", N, zDash);
3029 ** Draw a horizontal separator for a MODE_Box table.
3031 static void print_box_row_separator(
3032 ShellState *p,
3033 int nArg,
3034 const char *zSep1,
3035 const char *zSep2,
3036 const char *zSep3
3038 int i;
3039 if( nArg>0 ){
3040 utf8_printf(p->out, "%s", zSep1);
3041 print_box_line(p->out, p->actualWidth[0]+2);
3042 for(i=1; i<nArg; i++){
3043 utf8_printf(p->out, "%s", zSep2);
3044 print_box_line(p->out, p->actualWidth[i]+2);
3046 utf8_printf(p->out, "%s", zSep3);
3048 fputs("\n", p->out);
3054 ** Run a prepared statement and output the result in one of the
3055 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3056 ** or MODE_Box.
3058 ** This is different from ordinary exec_prepared_stmt() in that
3059 ** it has to run the entire query and gather the results into memory
3060 ** first, in order to determine column widths, before providing
3061 ** any output.
3063 static void exec_prepared_stmt_columnar(
3064 ShellState *p, /* Pointer to ShellState */
3065 sqlite3_stmt *pStmt /* Statment to run */
3067 sqlite3_int64 nRow = 0;
3068 int nColumn = 0;
3069 char **azData = 0;
3070 sqlite3_int64 nAlloc = 0;
3071 const char *z;
3072 int rc;
3073 sqlite3_int64 i, nData;
3074 int j, nTotal, w, n;
3075 const char *colSep = 0;
3076 const char *rowSep = 0;
3078 rc = sqlite3_step(pStmt);
3079 if( rc!=SQLITE_ROW ) return;
3080 nColumn = sqlite3_column_count(pStmt);
3081 nAlloc = nColumn*4;
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 switch( p->cMode ){
3122 case MODE_Column: {
3123 colSep = " ";
3124 rowSep = "\n";
3125 if( p->showHeader ){
3126 for(i=0; i<nColumn; i++){
3127 w = p->actualWidth[i];
3128 if( p->colWidth[i]<0 ) w = -w;
3129 utf8_width_print(p->out, w, azData[i]);
3130 fputs(i==nColumn-1?"\n":" ", p->out);
3132 for(i=0; i<nColumn; i++){
3133 print_dashes(p->out, p->actualWidth[i]);
3134 fputs(i==nColumn-1?"\n":" ", p->out);
3137 break;
3139 case MODE_Table: {
3140 colSep = " | ";
3141 rowSep = " |\n";
3142 print_row_separator(p, nColumn, "+");
3143 fputs("| ", p->out);
3144 for(i=0; i<nColumn; i++){
3145 w = p->actualWidth[i];
3146 n = strlenChar(azData[i]);
3147 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3148 fputs(i==nColumn-1?" |\n":" | ", p->out);
3150 print_row_separator(p, nColumn, "+");
3151 break;
3153 case MODE_Markdown: {
3154 colSep = " | ";
3155 rowSep = " |\n";
3156 fputs("| ", p->out);
3157 for(i=0; i<nColumn; i++){
3158 w = p->actualWidth[i];
3159 n = strlenChar(azData[i]);
3160 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3161 fputs(i==nColumn-1?" |\n":" | ", p->out);
3163 print_row_separator(p, nColumn, "|");
3164 break;
3166 case MODE_Box: {
3167 colSep = " " BOX_13 " ";
3168 rowSep = " " BOX_13 "\n";
3169 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3170 utf8_printf(p->out, BOX_13 " ");
3171 for(i=0; i<nColumn; i++){
3172 w = p->actualWidth[i];
3173 n = strlenChar(azData[i]);
3174 utf8_printf(p->out, "%*s%s%*s%s",
3175 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3176 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3178 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3179 break;
3182 for(i=nColumn, j=0; i<nTotal; i++, j++){
3183 if( j==0 && p->cMode!=MODE_Column ){
3184 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3186 z = azData[i];
3187 if( z==0 ) z = p->nullValue;
3188 w = p->actualWidth[j];
3189 if( p->colWidth[j]<0 ) w = -w;
3190 utf8_width_print(p->out, w, z);
3191 if( j==nColumn-1 ){
3192 utf8_printf(p->out, "%s", rowSep);
3193 j = -1;
3194 if( seenInterrupt ) goto columnar_end;
3195 }else{
3196 utf8_printf(p->out, "%s", colSep);
3199 if( p->cMode==MODE_Table ){
3200 print_row_separator(p, nColumn, "+");
3201 }else if( p->cMode==MODE_Box ){
3202 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3204 columnar_end:
3205 if( seenInterrupt ){
3206 utf8_printf(p->out, "Interrupt\n");
3208 nData = (nRow+1)*nColumn;
3209 for(i=0; i<nData; i++) free(azData[i]);
3210 sqlite3_free(azData);
3214 ** Run a prepared statement
3216 static void exec_prepared_stmt(
3217 ShellState *pArg, /* Pointer to ShellState */
3218 sqlite3_stmt *pStmt /* Statment to run */
3220 int rc;
3222 if( pArg->cMode==MODE_Column
3223 || pArg->cMode==MODE_Table
3224 || pArg->cMode==MODE_Box
3225 || pArg->cMode==MODE_Markdown
3227 exec_prepared_stmt_columnar(pArg, pStmt);
3228 return;
3231 /* perform the first step. this will tell us if we
3232 ** have a result set or not and how wide it is.
3234 rc = sqlite3_step(pStmt);
3235 /* if we have a result set... */
3236 if( SQLITE_ROW == rc ){
3237 /* allocate space for col name ptr, value ptr, and type */
3238 int nCol = sqlite3_column_count(pStmt);
3239 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3240 if( !pData ){
3241 rc = SQLITE_NOMEM;
3242 }else{
3243 char **azCols = (char **)pData; /* Names of result columns */
3244 char **azVals = &azCols[nCol]; /* Results */
3245 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3246 int i, x;
3247 assert(sizeof(int) <= sizeof(char *));
3248 /* save off ptrs to column names */
3249 for(i=0; i<nCol; i++){
3250 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3253 /* extract the data and data types */
3254 for(i=0; i<nCol; i++){
3255 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3256 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3257 azVals[i] = "";
3258 }else{
3259 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3261 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3262 rc = SQLITE_NOMEM;
3263 break; /* from for */
3265 } /* end for */
3267 /* if data and types extracted successfully... */
3268 if( SQLITE_ROW == rc ){
3269 /* call the supplied callback with the result row data */
3270 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3271 rc = SQLITE_ABORT;
3272 }else{
3273 rc = sqlite3_step(pStmt);
3276 } while( SQLITE_ROW == rc );
3277 sqlite3_free(pData);
3278 if( pArg->cMode==MODE_Json ){
3279 fputs("]\n", pArg->out);
3285 #ifndef SQLITE_OMIT_VIRTUALTABLE
3287 ** This function is called to process SQL if the previous shell command
3288 ** was ".expert". It passes the SQL in the second argument directly to
3289 ** the sqlite3expert object.
3291 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3292 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3293 ** an English language error message. It is the responsibility of the
3294 ** caller to eventually free this buffer using sqlite3_free().
3296 static int expertHandleSQL(
3297 ShellState *pState,
3298 const char *zSql,
3299 char **pzErr
3301 assert( pState->expert.pExpert );
3302 assert( pzErr==0 || *pzErr==0 );
3303 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3307 ** This function is called either to silently clean up the object
3308 ** created by the ".expert" command (if bCancel==1), or to generate a
3309 ** report from it and then clean it up (if bCancel==0).
3311 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3312 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3313 ** an English language error message. It is the responsibility of the
3314 ** caller to eventually free this buffer using sqlite3_free().
3316 static int expertFinish(
3317 ShellState *pState,
3318 int bCancel,
3319 char **pzErr
3321 int rc = SQLITE_OK;
3322 sqlite3expert *p = pState->expert.pExpert;
3323 assert( p );
3324 assert( bCancel || pzErr==0 || *pzErr==0 );
3325 if( bCancel==0 ){
3326 FILE *out = pState->out;
3327 int bVerbose = pState->expert.bVerbose;
3329 rc = sqlite3_expert_analyze(p, pzErr);
3330 if( rc==SQLITE_OK ){
3331 int nQuery = sqlite3_expert_count(p);
3332 int i;
3334 if( bVerbose ){
3335 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3336 raw_printf(out, "-- Candidates -----------------------------\n");
3337 raw_printf(out, "%s\n", zCand);
3339 for(i=0; i<nQuery; i++){
3340 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3341 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3342 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3343 if( zIdx==0 ) zIdx = "(no new indexes)\n";
3344 if( bVerbose ){
3345 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3346 raw_printf(out, "%s\n\n", zSql);
3348 raw_printf(out, "%s\n", zIdx);
3349 raw_printf(out, "%s\n", zEQP);
3353 sqlite3_expert_destroy(p);
3354 pState->expert.pExpert = 0;
3355 return rc;
3359 ** Implementation of ".expert" dot command.
3361 static int expertDotCommand(
3362 ShellState *pState, /* Current shell tool state */
3363 char **azArg, /* Array of arguments passed to dot command */
3364 int nArg /* Number of entries in azArg[] */
3366 int rc = SQLITE_OK;
3367 char *zErr = 0;
3368 int i;
3369 int iSample = 0;
3371 assert( pState->expert.pExpert==0 );
3372 memset(&pState->expert, 0, sizeof(ExpertInfo));
3374 for(i=1; rc==SQLITE_OK && i<nArg; i++){
3375 char *z = azArg[i];
3376 int n;
3377 if( z[0]=='-' && z[1]=='-' ) z++;
3378 n = strlen30(z);
3379 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3380 pState->expert.bVerbose = 1;
3382 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3383 if( i==(nArg-1) ){
3384 raw_printf(stderr, "option requires an argument: %s\n", z);
3385 rc = SQLITE_ERROR;
3386 }else{
3387 iSample = (int)integerValue(azArg[++i]);
3388 if( iSample<0 || iSample>100 ){
3389 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3390 rc = SQLITE_ERROR;
3394 else{
3395 raw_printf(stderr, "unknown option: %s\n", z);
3396 rc = SQLITE_ERROR;
3400 if( rc==SQLITE_OK ){
3401 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3402 if( pState->expert.pExpert==0 ){
3403 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
3404 rc = SQLITE_ERROR;
3405 }else{
3406 sqlite3_expert_config(
3407 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3412 return rc;
3414 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3417 ** Execute a statement or set of statements. Print
3418 ** any result rows/columns depending on the current mode
3419 ** set via the supplied callback.
3421 ** This is very similar to SQLite's built-in sqlite3_exec()
3422 ** function except it takes a slightly different callback
3423 ** and callback data argument.
3425 static int shell_exec(
3426 ShellState *pArg, /* Pointer to ShellState */
3427 const char *zSql, /* SQL to be evaluated */
3428 char **pzErrMsg /* Error msg written here */
3430 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3431 int rc = SQLITE_OK; /* Return Code */
3432 int rc2;
3433 const char *zLeftover; /* Tail of unprocessed SQL */
3434 sqlite3 *db = pArg->db;
3436 if( pzErrMsg ){
3437 *pzErrMsg = NULL;
3440 #ifndef SQLITE_OMIT_VIRTUALTABLE
3441 if( pArg->expert.pExpert ){
3442 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3443 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3445 #endif
3447 while( zSql[0] && (SQLITE_OK == rc) ){
3448 static const char *zStmtSql;
3449 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3450 if( SQLITE_OK != rc ){
3451 if( pzErrMsg ){
3452 *pzErrMsg = save_err_msg(db);
3454 }else{
3455 if( !pStmt ){
3456 /* this happens for a comment or white-space */
3457 zSql = zLeftover;
3458 while( IsSpace(zSql[0]) ) zSql++;
3459 continue;
3461 zStmtSql = sqlite3_sql(pStmt);
3462 if( zStmtSql==0 ) zStmtSql = "";
3463 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3465 /* save off the prepared statment handle and reset row count */
3466 if( pArg ){
3467 pArg->pStmt = pStmt;
3468 pArg->cnt = 0;
3471 /* echo the sql statement if echo on */
3472 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3473 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3476 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3477 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3478 sqlite3_stmt *pExplain;
3479 char *zEQP;
3480 int triggerEQP = 0;
3481 disable_debug_trace_modes();
3482 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3483 if( pArg->autoEQP>=AUTOEQP_trigger ){
3484 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3486 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3487 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3488 if( rc==SQLITE_OK ){
3489 while( sqlite3_step(pExplain)==SQLITE_ROW ){
3490 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3491 int iEqpId = sqlite3_column_int(pExplain, 0);
3492 int iParentId = sqlite3_column_int(pExplain, 1);
3493 if( zEQPLine==0 ) zEQPLine = "";
3494 if( zEQPLine[0]=='-' ) eqp_render(pArg);
3495 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3497 eqp_render(pArg);
3499 sqlite3_finalize(pExplain);
3500 sqlite3_free(zEQP);
3501 if( pArg->autoEQP>=AUTOEQP_full ){
3502 /* Also do an EXPLAIN for ".eqp full" mode */
3503 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3504 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3505 if( rc==SQLITE_OK ){
3506 pArg->cMode = MODE_Explain;
3507 explain_data_prepare(pArg, pExplain);
3508 exec_prepared_stmt(pArg, pExplain);
3509 explain_data_delete(pArg);
3511 sqlite3_finalize(pExplain);
3512 sqlite3_free(zEQP);
3514 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3515 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3516 /* Reprepare pStmt before reactiving trace modes */
3517 sqlite3_finalize(pStmt);
3518 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3519 if( pArg ) pArg->pStmt = pStmt;
3521 restore_debug_trace_modes();
3524 if( pArg ){
3525 pArg->cMode = pArg->mode;
3526 if( pArg->autoExplain ){
3527 if( sqlite3_stmt_isexplain(pStmt)==1 ){
3528 pArg->cMode = MODE_Explain;
3530 if( sqlite3_stmt_isexplain(pStmt)==2 ){
3531 pArg->cMode = MODE_EQP;
3535 /* If the shell is currently in ".explain" mode, gather the extra
3536 ** data required to add indents to the output.*/
3537 if( pArg->cMode==MODE_Explain ){
3538 explain_data_prepare(pArg, pStmt);
3542 bind_prepared_stmt(pArg, pStmt);
3543 exec_prepared_stmt(pArg, pStmt);
3544 explain_data_delete(pArg);
3545 eqp_render(pArg);
3547 /* print usage stats if stats on */
3548 if( pArg && pArg->statsOn ){
3549 display_stats(db, pArg, 0);
3552 /* print loop-counters if required */
3553 if( pArg && pArg->scanstatsOn ){
3554 display_scanstats(db, pArg);
3557 /* Finalize the statement just executed. If this fails, save a
3558 ** copy of the error message. Otherwise, set zSql to point to the
3559 ** next statement to execute. */
3560 rc2 = sqlite3_finalize(pStmt);
3561 if( rc!=SQLITE_NOMEM ) rc = rc2;
3562 if( rc==SQLITE_OK ){
3563 zSql = zLeftover;
3564 while( IsSpace(zSql[0]) ) zSql++;
3565 }else if( pzErrMsg ){
3566 *pzErrMsg = save_err_msg(db);
3569 /* clear saved stmt handle */
3570 if( pArg ){
3571 pArg->pStmt = NULL;
3574 } /* end while */
3576 return rc;
3580 ** Release memory previously allocated by tableColumnList().
3582 static void freeColumnList(char **azCol){
3583 int i;
3584 for(i=1; azCol[i]; i++){
3585 sqlite3_free(azCol[i]);
3587 /* azCol[0] is a static string */
3588 sqlite3_free(azCol);
3592 ** Return a list of pointers to strings which are the names of all
3593 ** columns in table zTab. The memory to hold the names is dynamically
3594 ** allocated and must be released by the caller using a subsequent call
3595 ** to freeColumnList().
3597 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3598 ** value that needs to be preserved, then azCol[0] is filled in with the
3599 ** name of the rowid column.
3601 ** The first regular column in the table is azCol[1]. The list is terminated
3602 ** by an entry with azCol[i]==0.
3604 static char **tableColumnList(ShellState *p, const char *zTab){
3605 char **azCol = 0;
3606 sqlite3_stmt *pStmt;
3607 char *zSql;
3608 int nCol = 0;
3609 int nAlloc = 0;
3610 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3611 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3612 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3613 int rc;
3615 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3616 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3617 sqlite3_free(zSql);
3618 if( rc ) return 0;
3619 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3620 if( nCol>=nAlloc-2 ){
3621 nAlloc = nAlloc*2 + nCol + 10;
3622 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3623 if( azCol==0 ) shell_out_of_memory();
3625 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3626 if( sqlite3_column_int(pStmt, 5) ){
3627 nPK++;
3628 if( nPK==1
3629 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3630 "INTEGER")==0
3632 isIPK = 1;
3633 }else{
3634 isIPK = 0;
3638 sqlite3_finalize(pStmt);
3639 if( azCol==0 ) return 0;
3640 azCol[0] = 0;
3641 azCol[nCol+1] = 0;
3643 /* The decision of whether or not a rowid really needs to be preserved
3644 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3645 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3646 ** rowids on tables where the rowid is inaccessible because there are other
3647 ** columns in the table named "rowid", "_rowid_", and "oid".
3649 if( preserveRowid && isIPK ){
3650 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3651 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3652 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3653 ** ROWID aliases. To distinguish these cases, check to see if
3654 ** there is a "pk" entry in "PRAGMA index_list". There will be
3655 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3657 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3658 " WHERE origin='pk'", zTab);
3659 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3660 sqlite3_free(zSql);
3661 if( rc ){
3662 freeColumnList(azCol);
3663 return 0;
3665 rc = sqlite3_step(pStmt);
3666 sqlite3_finalize(pStmt);
3667 preserveRowid = rc==SQLITE_ROW;
3669 if( preserveRowid ){
3670 /* Only preserve the rowid if we can find a name to use for the
3671 ** rowid */
3672 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3673 int i, j;
3674 for(j=0; j<3; j++){
3675 for(i=1; i<=nCol; i++){
3676 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3678 if( i>nCol ){
3679 /* At this point, we know that azRowid[j] is not the name of any
3680 ** ordinary column in the table. Verify that azRowid[j] is a valid
3681 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3682 ** tables will fail this last check */
3683 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3684 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3685 break;
3689 return azCol;
3693 ** Toggle the reverse_unordered_selects setting.
3695 static void toggleSelectOrder(sqlite3 *db){
3696 sqlite3_stmt *pStmt = 0;
3697 int iSetting = 0;
3698 char zStmt[100];
3699 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3700 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3701 iSetting = sqlite3_column_int(pStmt, 0);
3703 sqlite3_finalize(pStmt);
3704 sqlite3_snprintf(sizeof(zStmt), zStmt,
3705 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3706 sqlite3_exec(db, zStmt, 0, 0, 0);
3710 ** This is a different callback routine used for dumping the database.
3711 ** Each row received by this callback consists of a table name,
3712 ** the table type ("index" or "table") and SQL to create the table.
3713 ** This routine should print text sufficient to recreate the table.
3715 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3716 int rc;
3717 const char *zTable;
3718 const char *zType;
3719 const char *zSql;
3720 ShellState *p = (ShellState *)pArg;
3722 UNUSED_PARAMETER(azNotUsed);
3723 if( nArg!=3 || azArg==0 ) return 0;
3724 zTable = azArg[0];
3725 zType = azArg[1];
3726 zSql = azArg[2];
3728 if( strcmp(zTable, "sqlite_sequence")==0 ){
3729 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3730 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3731 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
3732 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3733 return 0;
3734 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3735 char *zIns;
3736 if( !p->writableSchema ){
3737 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3738 p->writableSchema = 1;
3740 zIns = sqlite3_mprintf(
3741 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
3742 "VALUES('table','%q','%q',0,'%q');",
3743 zTable, zTable, zSql);
3744 utf8_printf(p->out, "%s\n", zIns);
3745 sqlite3_free(zIns);
3746 return 0;
3747 }else{
3748 printSchemaLine(p->out, zSql, ";\n");
3751 if( strcmp(zType, "table")==0 ){
3752 ShellText sSelect;
3753 ShellText sTable;
3754 char **azCol;
3755 int i;
3756 char *savedDestTable;
3757 int savedMode;
3759 azCol = tableColumnList(p, zTable);
3760 if( azCol==0 ){
3761 p->nErr++;
3762 return 0;
3765 /* Always quote the table name, even if it appears to be pure ascii,
3766 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3767 initText(&sTable);
3768 appendText(&sTable, zTable, quoteChar(zTable));
3769 /* If preserving the rowid, add a column list after the table name.
3770 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3771 ** instead of the usual "INSERT INTO tab VALUES(...)".
3773 if( azCol[0] ){
3774 appendText(&sTable, "(", 0);
3775 appendText(&sTable, azCol[0], 0);
3776 for(i=1; azCol[i]; i++){
3777 appendText(&sTable, ",", 0);
3778 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3780 appendText(&sTable, ")", 0);
3783 /* Build an appropriate SELECT statement */
3784 initText(&sSelect);
3785 appendText(&sSelect, "SELECT ", 0);
3786 if( azCol[0] ){
3787 appendText(&sSelect, azCol[0], 0);
3788 appendText(&sSelect, ",", 0);
3790 for(i=1; azCol[i]; i++){
3791 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3792 if( azCol[i+1] ){
3793 appendText(&sSelect, ",", 0);
3796 freeColumnList(azCol);
3797 appendText(&sSelect, " FROM ", 0);
3798 appendText(&sSelect, zTable, quoteChar(zTable));
3800 savedDestTable = p->zDestTable;
3801 savedMode = p->mode;
3802 p->zDestTable = sTable.z;
3803 p->mode = p->cMode = MODE_Insert;
3804 rc = shell_exec(p, sSelect.z, 0);
3805 if( (rc&0xff)==SQLITE_CORRUPT ){
3806 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3807 toggleSelectOrder(p->db);
3808 shell_exec(p, sSelect.z, 0);
3809 toggleSelectOrder(p->db);
3811 p->zDestTable = savedDestTable;
3812 p->mode = savedMode;
3813 freeText(&sTable);
3814 freeText(&sSelect);
3815 if( rc ) p->nErr++;
3817 return 0;
3821 ** Run zQuery. Use dump_callback() as the callback routine so that
3822 ** the contents of the query are output as SQL statements.
3824 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3825 ** "ORDER BY rowid DESC" to the end.
3827 static int run_schema_dump_query(
3828 ShellState *p,
3829 const char *zQuery
3831 int rc;
3832 char *zErr = 0;
3833 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3834 if( rc==SQLITE_CORRUPT ){
3835 char *zQ2;
3836 int len = strlen30(zQuery);
3837 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3838 if( zErr ){
3839 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3840 sqlite3_free(zErr);
3841 zErr = 0;
3843 zQ2 = malloc( len+100 );
3844 if( zQ2==0 ) return rc;
3845 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3846 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3847 if( rc ){
3848 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3849 }else{
3850 rc = SQLITE_CORRUPT;
3852 sqlite3_free(zErr);
3853 free(zQ2);
3855 return rc;
3859 ** Text of help messages.
3861 ** The help text for each individual command begins with a line that starts
3862 ** with ".". Subsequent lines are supplimental information.
3864 ** There must be two or more spaces between the end of the command and the
3865 ** start of the description of what that command does.
3867 static const char *(azHelp[]) = {
3868 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3869 ".archive ... Manage SQL archives",
3870 " Each command must have exactly one of the following options:",
3871 " -c, --create Create a new archive",
3872 " -u, --update Add or update files with changed mtime",
3873 " -i, --insert Like -u but always add even if unchanged",
3874 " -t, --list List contents of archive",
3875 " -x, --extract Extract files from archive",
3876 " Optional arguments:",
3877 " -v, --verbose Print each filename as it is processed",
3878 " -f FILE, --file FILE Use archive FILE (default is current db)",
3879 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
3880 " -C DIR, --directory DIR Read/extract files from directory DIR",
3881 " -n, --dryrun Show the SQL that would have occurred",
3882 " Examples:",
3883 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
3884 " .ar -tf ARCHIVE # List members of ARCHIVE",
3885 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
3886 " See also:",
3887 " http://sqlite.org/cli.html#sqlar_archive_support",
3888 #endif
3889 #ifndef SQLITE_OMIT_AUTHORIZATION
3890 ".auth ON|OFF Show authorizer callbacks",
3891 #endif
3892 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3893 " --append Use the appendvfs",
3894 " --async Write to FILE without journal and fsync()",
3895 ".bail on|off Stop after hitting an error. Default OFF",
3896 ".binary on|off Turn binary output on or off. Default OFF",
3897 ".cd DIRECTORY Change the working directory to DIRECTORY",
3898 ".changes on|off Show number of rows changed by SQL",
3899 ".check GLOB Fail if output since .testcase does not match",
3900 ".clone NEWDB Clone data into NEWDB from the existing database",
3901 ".databases List names and files of attached databases",
3902 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3903 ".dbinfo ?DB? Show status information about the database",
3904 ".dump ?TABLE? Render database content as SQL",
3905 " Options:",
3906 " --preserve-rowids Include ROWID values in the output",
3907 " --newlines Allow unescaped newline characters in output",
3908 " TABLE is a LIKE pattern for the tables to dump",
3909 " Additional LIKE patterns can be given in subsequent arguments",
3910 ".echo on|off Turn command echo on or off",
3911 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3912 " Other Modes:",
3913 #ifdef SQLITE_DEBUG
3914 " test Show raw EXPLAIN QUERY PLAN output",
3915 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
3916 #endif
3917 " trigger Like \"full\" but also show trigger bytecode",
3918 ".excel Display the output of next command in spreadsheet",
3919 " --bom Put a UTF8 byte-order mark on intermediate file",
3920 ".exit ?CODE? Exit this program with return-code CODE",
3921 ".expert EXPERIMENTAL. Suggest indexes for queries",
3922 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
3923 ".filectrl CMD ... Run various sqlite3_file_control() operations",
3924 " --schema SCHEMA Use SCHEMA instead of \"main\"",
3925 " --help Show CMD details",
3926 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3927 ".headers on|off Turn display of headers on or off",
3928 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3929 ".import FILE TABLE Import data from FILE into TABLE",
3930 " Options:",
3931 " --ascii Use \\037 and \\036 as column and row separators",
3932 " --csv Use , and \\n as column and row separators",
3933 " --skip N Skip the first N rows of input",
3934 " -v \"Verbose\" - increase auxiliary output",
3935 " Notes:",
3936 " * If TABLE does not exist, it is created. The first row of input",
3937 " determines the column names.",
3938 " * If neither --csv or --ascii are used, the input mode is derived",
3939 " from the \".mode\" output mode",
3940 " * If FILE begins with \"|\" then it is a command that generates the",
3941 " input text.",
3942 #ifndef SQLITE_OMIT_TEST_CONTROL
3943 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
3944 #endif
3945 ".indexes ?TABLE? Show names of indexes",
3946 " If TABLE is specified, only show indexes for",
3947 " tables matching TABLE using the LIKE operator.",
3948 #ifdef SQLITE_ENABLE_IOTRACE
3949 ".iotrace FILE Enable I/O diagnostic logging to FILE",
3950 #endif
3951 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3952 ".lint OPTIONS Report potential schema issues.",
3953 " Options:",
3954 " fkey-indexes Find missing foreign key indexes",
3955 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3956 ".load FILE ?ENTRY? Load an extension library",
3957 #endif
3958 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3959 ".mode MODE ?TABLE? Set output mode",
3960 " MODE is one of:",
3961 " ascii Columns/rows delimited by 0x1F and 0x1E",
3962 " box Tables using unicode box-drawing characters",
3963 " csv Comma-separated values",
3964 " column Output in columns. (See .width)",
3965 " html HTML <table> code",
3966 " insert SQL insert statements for TABLE",
3967 " json Results in a JSON array",
3968 " line One value per line",
3969 " list Values delimited by \"|\"",
3970 " markdown Markdown table format",
3971 " quote Escape answers as for SQL",
3972 " table ASCII-art table",
3973 " tabs Tab-separated values",
3974 " tcl TCL list elements",
3975 ".nullvalue STRING Use STRING in place of NULL values",
3976 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
3977 " If FILE begins with '|' then open as a pipe",
3978 " --bom Put a UTF8 byte-order mark at the beginning",
3979 " -e Send output to the system text editor",
3980 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
3981 #ifdef SQLITE_DEBUG
3982 ".oom ?--repeat M? ?N? Simulate an OOM error on the N-th allocation",
3983 #endif
3984 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3985 " Options:",
3986 " --append Use appendvfs to append database to the end of FILE",
3987 #ifdef SQLITE_ENABLE_DESERIALIZE
3988 " --deserialize Load into memory useing sqlite3_deserialize()",
3989 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
3990 " --maxsize N Maximum size for --hexdb or --deserialized database",
3991 #endif
3992 " --new Initialize FILE to an empty database",
3993 " --nofollow Do not follow symbolic links",
3994 " --readonly Open FILE readonly",
3995 " --zip FILE is a ZIP archive",
3996 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3997 " If FILE begins with '|' then open it as a pipe.",
3998 " Options:",
3999 " --bom Prefix output with a UTF8 byte-order mark",
4000 " -e Send output to the system text editor",
4001 " -x Send output as CSV to a spreadsheet",
4002 ".parameter CMD ... Manage SQL parameter bindings",
4003 " clear Erase all bindings",
4004 " init Initialize the TEMP table that holds bindings",
4005 " list List the current parameter bindings",
4006 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4007 " PARAMETER should start with one of: $ : @ ?",
4008 " unset PARAMETER Remove PARAMETER from the binding table",
4009 ".print STRING... Print literal STRING",
4010 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4011 ".progress N Invoke progress handler after every N opcodes",
4012 " --limit N Interrupt after N progress callbacks",
4013 " --once Do no more than one progress interrupt",
4014 " --quiet|-q No output except at interrupts",
4015 " --reset Reset the count for each input and interrupt",
4016 #endif
4017 ".prompt MAIN CONTINUE Replace the standard prompts",
4018 ".quit Exit this program",
4019 ".read FILE Read input from FILE",
4020 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4021 ".recover Recover as much data as possible from corrupt db.",
4022 " --freelist-corrupt Assume the freelist is corrupt",
4023 " --recovery-db NAME Store recovery metadata in database file NAME",
4024 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4025 " --no-rowids Do not attempt to recover rowid values",
4026 " that are not also INTEGER PRIMARY KEYs",
4027 #endif
4028 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4029 ".save FILE Write in-memory database into FILE",
4030 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
4031 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4032 " Options:",
4033 " --indent Try to pretty-print the schema",
4034 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4035 " Options:",
4036 " --init Create a new SELFTEST table",
4037 " -v Verbose output",
4038 ".separator COL ?ROW? Change the column and row separators",
4039 #if defined(SQLITE_ENABLE_SESSION)
4040 ".session ?NAME? CMD ... Create or control sessions",
4041 " Subcommands:",
4042 " attach TABLE Attach TABLE",
4043 " changeset FILE Write a changeset into FILE",
4044 " close Close one session",
4045 " enable ?BOOLEAN? Set or query the enable bit",
4046 " filter GLOB... Reject tables matching GLOBs",
4047 " indirect ?BOOLEAN? Mark or query the indirect status",
4048 " isempty Query whether the session is empty",
4049 " list List currently open session names",
4050 " open DB NAME Open a new session on DB",
4051 " patchset FILE Write a patchset into FILE",
4052 " If ?NAME? is omitted, the first defined session is used.",
4053 #endif
4054 ".sha3sum ... Compute a SHA3 hash of database content",
4055 " Options:",
4056 " --schema Also hash the sqlite_schema table",
4057 " --sha3-224 Use the sha3-224 algorithm",
4058 " --sha3-256 Use the sha3-256 algorithm (default)",
4059 " --sha3-384 Use the sha3-384 algorithm",
4060 " --sha3-512 Use the sha3-512 algorithm",
4061 " Any other argument is a LIKE pattern for tables to hash",
4062 #ifndef SQLITE_NOHAVE_SYSTEM
4063 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4064 #endif
4065 ".show Show the current values for various settings",
4066 ".stats ?on|off? Show stats or turn stats on or off",
4067 #ifndef SQLITE_NOHAVE_SYSTEM
4068 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4069 #endif
4070 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4071 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
4072 ".testctrl CMD ... Run various sqlite3_test_control() operations",
4073 " Run \".testctrl\" with no arguments for details",
4074 ".timeout MS Try opening locked tables for MS milliseconds",
4075 ".timer on|off Turn SQL timer on or off",
4076 #ifndef SQLITE_OMIT_TRACE
4077 ".trace ?OPTIONS? Output each SQL statement as it is run",
4078 " FILE Send output to FILE",
4079 " stdout Send output to stdout",
4080 " stderr Send output to stderr",
4081 " off Disable tracing",
4082 " --expanded Expand query parameters",
4083 #ifdef SQLITE_ENABLE_NORMALIZE
4084 " --normalized Normal the SQL statements",
4085 #endif
4086 " --plain Show SQL as it is input",
4087 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4088 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4089 " --row Trace each row (SQLITE_TRACE_ROW)",
4090 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4091 #endif /* SQLITE_OMIT_TRACE */
4092 #ifdef SQLITE_DEBUG
4093 ".unmodule NAME ... Unregister virtual table modules",
4094 " --allexcept Unregister everything except those named",
4095 #endif
4096 ".vfsinfo ?AUX? Information about the top-level VFS",
4097 ".vfslist List all available VFSes",
4098 ".vfsname ?AUX? Print the name of the VFS stack",
4099 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4100 " Negative values right-justify",
4104 ** Output help text.
4106 ** zPattern describes the set of commands for which help text is provided.
4107 ** If zPattern is NULL, then show all commands, but only give a one-line
4108 ** description of each.
4110 ** Return the number of matches.
4112 static int showHelp(FILE *out, const char *zPattern){
4113 int i = 0;
4114 int j = 0;
4115 int n = 0;
4116 char *zPat;
4117 if( zPattern==0
4118 || zPattern[0]=='0'
4119 || strcmp(zPattern,"-a")==0
4120 || strcmp(zPattern,"-all")==0
4121 || strcmp(zPattern,"--all")==0
4123 /* Show all commands, but only one line per command */
4124 if( zPattern==0 ) zPattern = "";
4125 for(i=0; i<ArraySize(azHelp); i++){
4126 if( azHelp[i][0]=='.' || zPattern[0] ){
4127 utf8_printf(out, "%s\n", azHelp[i]);
4128 n++;
4131 }else{
4132 /* Look for commands that for which zPattern is an exact prefix */
4133 zPat = sqlite3_mprintf(".%s*", zPattern);
4134 for(i=0; i<ArraySize(azHelp); i++){
4135 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4136 utf8_printf(out, "%s\n", azHelp[i]);
4137 j = i+1;
4138 n++;
4141 sqlite3_free(zPat);
4142 if( n ){
4143 if( n==1 ){
4144 /* when zPattern is a prefix of exactly one command, then include the
4145 ** details of that command, which should begin at offset j */
4146 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4147 utf8_printf(out, "%s\n", azHelp[j]);
4148 j++;
4151 return n;
4153 /* Look for commands that contain zPattern anywhere. Show the complete
4154 ** text of all commands that match. */
4155 zPat = sqlite3_mprintf("%%%s%%", zPattern);
4156 for(i=0; i<ArraySize(azHelp); i++){
4157 if( azHelp[i][0]=='.' ) j = i;
4158 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4159 utf8_printf(out, "%s\n", azHelp[j]);
4160 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4161 j++;
4162 utf8_printf(out, "%s\n", azHelp[j]);
4164 i = j;
4165 n++;
4168 sqlite3_free(zPat);
4170 return n;
4173 /* Forward reference */
4174 static int process_input(ShellState *p);
4177 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
4178 ** and return a pointer to the buffer. The caller is responsible for freeing
4179 ** the memory.
4181 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4182 ** read.
4184 ** For convenience, a nul-terminator byte is always appended to the data read
4185 ** from the file before the buffer is returned. This byte is not included in
4186 ** the final value of (*pnByte), if applicable.
4188 ** NULL is returned if any error is encountered. The final value of *pnByte
4189 ** is undefined in this case.
4191 static char *readFile(const char *zName, int *pnByte){
4192 FILE *in = fopen(zName, "rb");
4193 long nIn;
4194 size_t nRead;
4195 char *pBuf;
4196 if( in==0 ) return 0;
4197 fseek(in, 0, SEEK_END);
4198 nIn = ftell(in);
4199 rewind(in);
4200 pBuf = sqlite3_malloc64( nIn+1 );
4201 if( pBuf==0 ){ fclose(in); return 0; }
4202 nRead = fread(pBuf, nIn, 1, in);
4203 fclose(in);
4204 if( nRead!=1 ){
4205 sqlite3_free(pBuf);
4206 return 0;
4208 pBuf[nIn] = 0;
4209 if( pnByte ) *pnByte = nIn;
4210 return pBuf;
4213 #if defined(SQLITE_ENABLE_SESSION)
4215 ** Close a single OpenSession object and release all of its associated
4216 ** resources.
4218 static void session_close(OpenSession *pSession){
4219 int i;
4220 sqlite3session_delete(pSession->p);
4221 sqlite3_free(pSession->zName);
4222 for(i=0; i<pSession->nFilter; i++){
4223 sqlite3_free(pSession->azFilter[i]);
4225 sqlite3_free(pSession->azFilter);
4226 memset(pSession, 0, sizeof(OpenSession));
4228 #endif
4231 ** Close all OpenSession objects and release all associated resources.
4233 #if defined(SQLITE_ENABLE_SESSION)
4234 static void session_close_all(ShellState *p){
4235 int i;
4236 for(i=0; i<p->nSession; i++){
4237 session_close(&p->aSession[i]);
4239 p->nSession = 0;
4241 #else
4242 # define session_close_all(X)
4243 #endif
4246 ** Implementation of the xFilter function for an open session. Omit
4247 ** any tables named by ".session filter" but let all other table through.
4249 #if defined(SQLITE_ENABLE_SESSION)
4250 static int session_filter(void *pCtx, const char *zTab){
4251 OpenSession *pSession = (OpenSession*)pCtx;
4252 int i;
4253 for(i=0; i<pSession->nFilter; i++){
4254 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4256 return 1;
4258 #endif
4261 ** Try to deduce the type of file for zName based on its content. Return
4262 ** one of the SHELL_OPEN_* constants.
4264 ** If the file does not exist or is empty but its name looks like a ZIP
4265 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4266 ** Otherwise, assume an ordinary database regardless of the filename if
4267 ** the type cannot be determined from content.
4269 int deduceDatabaseType(const char *zName, int dfltZip){
4270 FILE *f = fopen(zName, "rb");
4271 size_t n;
4272 int rc = SHELL_OPEN_UNSPEC;
4273 char zBuf[100];
4274 if( f==0 ){
4275 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4276 return SHELL_OPEN_ZIPFILE;
4277 }else{
4278 return SHELL_OPEN_NORMAL;
4281 n = fread(zBuf, 16, 1, f);
4282 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4283 fclose(f);
4284 return SHELL_OPEN_NORMAL;
4286 fseek(f, -25, SEEK_END);
4287 n = fread(zBuf, 25, 1, f);
4288 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4289 rc = SHELL_OPEN_APPENDVFS;
4290 }else{
4291 fseek(f, -22, SEEK_END);
4292 n = fread(zBuf, 22, 1, f);
4293 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4294 && zBuf[3]==0x06 ){
4295 rc = SHELL_OPEN_ZIPFILE;
4296 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4297 rc = SHELL_OPEN_ZIPFILE;
4300 fclose(f);
4301 return rc;
4304 #ifdef SQLITE_ENABLE_DESERIALIZE
4306 ** Reconstruct an in-memory database using the output from the "dbtotxt"
4307 ** program. Read content from the file in p->zDbFilename. If p->zDbFilename
4308 ** is 0, then read from standard input.
4310 static unsigned char *readHexDb(ShellState *p, int *pnData){
4311 unsigned char *a = 0;
4312 int nLine;
4313 int n = 0;
4314 int pgsz = 0;
4315 int iOffset = 0;
4316 int j, k;
4317 int rc;
4318 FILE *in;
4319 unsigned int x[16];
4320 char zLine[1000];
4321 if( p->zDbFilename ){
4322 in = fopen(p->zDbFilename, "r");
4323 if( in==0 ){
4324 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
4325 return 0;
4327 nLine = 0;
4328 }else{
4329 in = p->in;
4330 nLine = p->lineno;
4331 if( in==0 ) in = stdin;
4333 *pnData = 0;
4334 nLine++;
4335 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4336 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4337 if( rc!=2 ) goto readHexDb_error;
4338 if( n<0 ) goto readHexDb_error;
4339 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4340 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
4341 a = sqlite3_malloc( n ? n : 1 );
4342 if( a==0 ){
4343 utf8_printf(stderr, "Out of memory!\n");
4344 goto readHexDb_error;
4346 memset(a, 0, n);
4347 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4348 utf8_printf(stderr, "invalid pagesize\n");
4349 goto readHexDb_error;
4351 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4352 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4353 if( rc==2 ){
4354 iOffset = k;
4355 continue;
4357 if( strncmp(zLine, "| end ", 6)==0 ){
4358 break;
4360 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4361 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4362 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4363 if( rc==17 ){
4364 k = iOffset+j;
4365 if( k+16<=n ){
4366 int ii;
4367 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4371 *pnData = n;
4372 if( in!=p->in ){
4373 fclose(in);
4374 }else{
4375 p->lineno = nLine;
4377 return a;
4379 readHexDb_error:
4380 if( in!=p->in ){
4381 fclose(in);
4382 }else{
4383 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4384 nLine++;
4385 if(strncmp(zLine, "| end ", 6)==0 ) break;
4387 p->lineno = nLine;
4389 sqlite3_free(a);
4390 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4391 return 0;
4393 #endif /* SQLITE_ENABLE_DESERIALIZE */
4396 ** Scalar function "shell_int32". The first argument to this function
4397 ** must be a blob. The second a non-negative integer. This function
4398 ** reads and returns a 32-bit big-endian integer from byte
4399 ** offset (4*<arg2>) of the blob.
4401 static void shellInt32(
4402 sqlite3_context *context,
4403 int argc,
4404 sqlite3_value **argv
4406 const unsigned char *pBlob;
4407 int nBlob;
4408 int iInt;
4410 UNUSED_PARAMETER(argc);
4411 nBlob = sqlite3_value_bytes(argv[0]);
4412 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4413 iInt = sqlite3_value_int(argv[1]);
4415 if( iInt>=0 && (iInt+1)*4<=nBlob ){
4416 const unsigned char *a = &pBlob[iInt*4];
4417 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4418 + ((sqlite3_int64)a[1]<<16)
4419 + ((sqlite3_int64)a[2]<< 8)
4420 + ((sqlite3_int64)a[3]<< 0);
4421 sqlite3_result_int64(context, iVal);
4426 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4427 ** using "..." with internal double-quote characters doubled.
4429 static void shellIdQuote(
4430 sqlite3_context *context,
4431 int argc,
4432 sqlite3_value **argv
4434 const char *zName = (const char*)sqlite3_value_text(argv[0]);
4435 UNUSED_PARAMETER(argc);
4436 if( zName ){
4437 char *z = sqlite3_mprintf("\"%w\"", zName);
4438 sqlite3_result_text(context, z, -1, sqlite3_free);
4443 ** Scalar function "shell_escape_crnl" used by the .recover command.
4444 ** The argument passed to this function is the output of built-in
4445 ** function quote(). If the first character of the input is "'",
4446 ** indicating that the value passed to quote() was a text value,
4447 ** then this function searches the input for "\n" and "\r" characters
4448 ** and adds a wrapper similar to the following:
4450 ** replace(replace(<input>, '\n', char(10), '\r', char(13));
4452 ** Or, if the first character of the input is not "'", then a copy
4453 ** of the input is returned.
4455 static void shellEscapeCrnl(
4456 sqlite3_context *context,
4457 int argc,
4458 sqlite3_value **argv
4460 const char *zText = (const char*)sqlite3_value_text(argv[0]);
4461 UNUSED_PARAMETER(argc);
4462 if( zText[0]=='\'' ){
4463 int nText = sqlite3_value_bytes(argv[0]);
4464 int i;
4465 char zBuf1[20];
4466 char zBuf2[20];
4467 const char *zNL = 0;
4468 const char *zCR = 0;
4469 int nCR = 0;
4470 int nNL = 0;
4472 for(i=0; zText[i]; i++){
4473 if( zNL==0 && zText[i]=='\n' ){
4474 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4475 nNL = (int)strlen(zNL);
4477 if( zCR==0 && zText[i]=='\r' ){
4478 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4479 nCR = (int)strlen(zCR);
4483 if( zNL || zCR ){
4484 int iOut = 0;
4485 i64 nMax = (nNL > nCR) ? nNL : nCR;
4486 i64 nAlloc = nMax * nText + (nMax+64)*2;
4487 char *zOut = (char*)sqlite3_malloc64(nAlloc);
4488 if( zOut==0 ){
4489 sqlite3_result_error_nomem(context);
4490 return;
4493 if( zNL && zCR ){
4494 memcpy(&zOut[iOut], "replace(replace(", 16);
4495 iOut += 16;
4496 }else{
4497 memcpy(&zOut[iOut], "replace(", 8);
4498 iOut += 8;
4500 for(i=0; zText[i]; i++){
4501 if( zText[i]=='\n' ){
4502 memcpy(&zOut[iOut], zNL, nNL);
4503 iOut += nNL;
4504 }else if( zText[i]=='\r' ){
4505 memcpy(&zOut[iOut], zCR, nCR);
4506 iOut += nCR;
4507 }else{
4508 zOut[iOut] = zText[i];
4509 iOut++;
4513 if( zNL ){
4514 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4515 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4516 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4518 if( zCR ){
4519 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4520 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4521 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4524 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4525 sqlite3_free(zOut);
4526 return;
4530 sqlite3_result_value(context, argv[0]);
4533 /* Flags for open_db().
4535 ** The default behavior of open_db() is to exit(1) if the database fails to
4536 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4537 ** but still returns without calling exit.
4539 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4540 ** ZIP archive if the file does not exist or is empty and its name matches
4541 ** the *.zip pattern.
4543 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
4544 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
4547 ** Make sure the database is open. If it is not, then open it. If
4548 ** the database fails to open, print an error message and exit.
4550 static void open_db(ShellState *p, int openFlags){
4551 if( p->db==0 ){
4552 if( p->openMode==SHELL_OPEN_UNSPEC ){
4553 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4554 p->openMode = SHELL_OPEN_NORMAL;
4555 }else{
4556 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4557 (openFlags & OPEN_DB_ZIPFILE)!=0);
4560 switch( p->openMode ){
4561 case SHELL_OPEN_APPENDVFS: {
4562 sqlite3_open_v2(p->zDbFilename, &p->db,
4563 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4564 break;
4566 case SHELL_OPEN_HEXDB:
4567 case SHELL_OPEN_DESERIALIZE: {
4568 sqlite3_open(0, &p->db);
4569 break;
4571 case SHELL_OPEN_ZIPFILE: {
4572 sqlite3_open(":memory:", &p->db);
4573 break;
4575 case SHELL_OPEN_READONLY: {
4576 sqlite3_open_v2(p->zDbFilename, &p->db,
4577 SQLITE_OPEN_READONLY|p->openFlags, 0);
4578 break;
4580 case SHELL_OPEN_UNSPEC:
4581 case SHELL_OPEN_NORMAL: {
4582 sqlite3_open_v2(p->zDbFilename, &p->db,
4583 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4584 break;
4587 globalDb = p->db;
4588 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4589 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4590 p->zDbFilename, sqlite3_errmsg(p->db));
4591 if( openFlags & OPEN_DB_KEEPALIVE ){
4592 sqlite3_open(":memory:", &p->db);
4593 return;
4595 exit(1);
4597 #ifndef SQLITE_OMIT_LOAD_EXTENSION
4598 sqlite3_enable_load_extension(p->db, 1);
4599 #endif
4600 sqlite3_fileio_init(p->db, 0, 0);
4601 sqlite3_shathree_init(p->db, 0, 0);
4602 sqlite3_completion_init(p->db, 0, 0);
4603 sqlite3_uint_init(p->db, 0, 0);
4604 sqlite3_decimal_init(p->db, 0, 0);
4605 sqlite3_ieee_init(p->db, 0, 0);
4606 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4607 sqlite3_dbdata_init(p->db, 0, 0);
4608 #endif
4609 #ifdef SQLITE_HAVE_ZLIB
4610 sqlite3_zipfile_init(p->db, 0, 0);
4611 sqlite3_sqlar_init(p->db, 0, 0);
4612 #endif
4613 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4614 shellAddSchemaName, 0, 0);
4615 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4616 shellModuleSchema, 0, 0);
4617 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4618 shellPutsFunc, 0, 0);
4619 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4620 shellEscapeCrnl, 0, 0);
4621 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4622 shellInt32, 0, 0);
4623 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4624 shellIdQuote, 0, 0);
4625 #ifndef SQLITE_NOHAVE_SYSTEM
4626 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4627 editFunc, 0, 0);
4628 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4629 editFunc, 0, 0);
4630 #endif
4631 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4632 char *zSql = sqlite3_mprintf(
4633 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4634 sqlite3_exec(p->db, zSql, 0, 0, 0);
4635 sqlite3_free(zSql);
4637 #ifdef SQLITE_ENABLE_DESERIALIZE
4638 else
4639 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4640 int rc;
4641 int nData = 0;
4642 unsigned char *aData;
4643 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4644 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4645 }else{
4646 aData = readHexDb(p, &nData);
4647 if( aData==0 ){
4648 return;
4651 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4652 SQLITE_DESERIALIZE_RESIZEABLE |
4653 SQLITE_DESERIALIZE_FREEONCLOSE);
4654 if( rc ){
4655 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4657 if( p->szMax>0 ){
4658 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4661 #endif
4666 ** Attempt to close the databaes connection. Report errors.
4668 void close_db(sqlite3 *db){
4669 int rc = sqlite3_close(db);
4670 if( rc ){
4671 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4672 rc, sqlite3_errmsg(db));
4676 #if HAVE_READLINE || HAVE_EDITLINE
4678 ** Readline completion callbacks
4680 static char *readline_completion_generator(const char *text, int state){
4681 static sqlite3_stmt *pStmt = 0;
4682 char *zRet;
4683 if( state==0 ){
4684 char *zSql;
4685 sqlite3_finalize(pStmt);
4686 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4687 " FROM completion(%Q) ORDER BY 1", text);
4688 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4689 sqlite3_free(zSql);
4691 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4692 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4693 }else{
4694 sqlite3_finalize(pStmt);
4695 pStmt = 0;
4696 zRet = 0;
4698 return zRet;
4700 static char **readline_completion(const char *zText, int iStart, int iEnd){
4701 rl_attempted_completion_over = 1;
4702 return rl_completion_matches(zText, readline_completion_generator);
4705 #elif HAVE_LINENOISE
4707 ** Linenoise completion callback
4709 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4710 int nLine = strlen30(zLine);
4711 int i, iStart;
4712 sqlite3_stmt *pStmt = 0;
4713 char *zSql;
4714 char zBuf[1000];
4716 if( nLine>sizeof(zBuf)-30 ) return;
4717 if( zLine[0]=='.' || zLine[0]=='#') return;
4718 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4719 if( i==nLine-1 ) return;
4720 iStart = i+1;
4721 memcpy(zBuf, zLine, iStart);
4722 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4723 " FROM completion(%Q,%Q) ORDER BY 1",
4724 &zLine[iStart], zLine);
4725 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4726 sqlite3_free(zSql);
4727 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4728 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4729 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4730 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4731 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4732 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4733 linenoiseAddCompletion(lc, zBuf);
4736 sqlite3_finalize(pStmt);
4738 #endif
4741 ** Do C-language style dequoting.
4743 ** \a -> alarm
4744 ** \b -> backspace
4745 ** \t -> tab
4746 ** \n -> newline
4747 ** \v -> vertical tab
4748 ** \f -> form feed
4749 ** \r -> carriage return
4750 ** \s -> space
4751 ** \" -> "
4752 ** \' -> '
4753 ** \\ -> backslash
4754 ** \NNN -> ascii character NNN in octal
4756 static void resolve_backslashes(char *z){
4757 int i, j;
4758 char c;
4759 while( *z && *z!='\\' ) z++;
4760 for(i=j=0; (c = z[i])!=0; i++, j++){
4761 if( c=='\\' && z[i+1]!=0 ){
4762 c = z[++i];
4763 if( c=='a' ){
4764 c = '\a';
4765 }else if( c=='b' ){
4766 c = '\b';
4767 }else if( c=='t' ){
4768 c = '\t';
4769 }else if( c=='n' ){
4770 c = '\n';
4771 }else if( c=='v' ){
4772 c = '\v';
4773 }else if( c=='f' ){
4774 c = '\f';
4775 }else if( c=='r' ){
4776 c = '\r';
4777 }else if( c=='"' ){
4778 c = '"';
4779 }else if( c=='\'' ){
4780 c = '\'';
4781 }else if( c=='\\' ){
4782 c = '\\';
4783 }else if( c>='0' && c<='7' ){
4784 c -= '0';
4785 if( z[i+1]>='0' && z[i+1]<='7' ){
4786 i++;
4787 c = (c<<3) + z[i] - '0';
4788 if( z[i+1]>='0' && z[i+1]<='7' ){
4789 i++;
4790 c = (c<<3) + z[i] - '0';
4795 z[j] = c;
4797 if( j<i ) z[j] = 0;
4801 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4802 ** for TRUE and FALSE. Return the integer value if appropriate.
4804 static int booleanValue(const char *zArg){
4805 int i;
4806 if( zArg[0]=='0' && zArg[1]=='x' ){
4807 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4808 }else{
4809 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4811 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4812 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4813 return 1;
4815 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4816 return 0;
4818 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4819 zArg);
4820 return 0;
4824 ** Set or clear a shell flag according to a boolean value.
4826 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4827 if( booleanValue(zArg) ){
4828 ShellSetFlag(p, mFlag);
4829 }else{
4830 ShellClearFlag(p, mFlag);
4835 ** Close an output file, assuming it is not stderr or stdout
4837 static void output_file_close(FILE *f){
4838 if( f && f!=stdout && f!=stderr ) fclose(f);
4842 ** Try to open an output file. The names "stdout" and "stderr" are
4843 ** recognized and do the right thing. NULL is returned if the output
4844 ** filename is "off".
4846 static FILE *output_file_open(const char *zFile, int bTextMode){
4847 FILE *f;
4848 if( strcmp(zFile,"stdout")==0 ){
4849 f = stdout;
4850 }else if( strcmp(zFile, "stderr")==0 ){
4851 f = stderr;
4852 }else if( strcmp(zFile, "off")==0 ){
4853 f = 0;
4854 }else{
4855 f = fopen(zFile, bTextMode ? "w" : "wb");
4856 if( f==0 ){
4857 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4860 return f;
4863 #ifndef SQLITE_OMIT_TRACE
4865 ** A routine for handling output from sqlite3_trace().
4867 static int sql_trace_callback(
4868 unsigned mType, /* The trace type */
4869 void *pArg, /* The ShellState pointer */
4870 void *pP, /* Usually a pointer to sqlite_stmt */
4871 void *pX /* Auxiliary output */
4873 ShellState *p = (ShellState*)pArg;
4874 sqlite3_stmt *pStmt;
4875 const char *zSql;
4876 int nSql;
4877 if( p->traceOut==0 ) return 0;
4878 if( mType==SQLITE_TRACE_CLOSE ){
4879 utf8_printf(p->traceOut, "-- closing database connection\n");
4880 return 0;
4882 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4883 zSql = (const char*)pX;
4884 }else{
4885 pStmt = (sqlite3_stmt*)pP;
4886 switch( p->eTraceType ){
4887 case SHELL_TRACE_EXPANDED: {
4888 zSql = sqlite3_expanded_sql(pStmt);
4889 break;
4891 #ifdef SQLITE_ENABLE_NORMALIZE
4892 case SHELL_TRACE_NORMALIZED: {
4893 zSql = sqlite3_normalized_sql(pStmt);
4894 break;
4896 #endif
4897 default: {
4898 zSql = sqlite3_sql(pStmt);
4899 break;
4903 if( zSql==0 ) return 0;
4904 nSql = strlen30(zSql);
4905 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4906 switch( mType ){
4907 case SQLITE_TRACE_ROW:
4908 case SQLITE_TRACE_STMT: {
4909 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4910 break;
4912 case SQLITE_TRACE_PROFILE: {
4913 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4914 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4915 break;
4918 return 0;
4920 #endif
4923 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
4924 ** a useful spot to set a debugger breakpoint.
4926 static void test_breakpoint(void){
4927 static int nCall = 0;
4928 nCall++;
4932 ** An object used to read a CSV and other files for import.
4934 typedef struct ImportCtx ImportCtx;
4935 struct ImportCtx {
4936 const char *zFile; /* Name of the input file */
4937 FILE *in; /* Read the CSV text from this input stream */
4938 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
4939 char *z; /* Accumulated text for a field */
4940 int n; /* Number of bytes in z */
4941 int nAlloc; /* Space allocated for z[] */
4942 int nLine; /* Current line number */
4943 int nRow; /* Number of rows imported */
4944 int nErr; /* Number of errors encountered */
4945 int bNotFirst; /* True if one or more bytes already read */
4946 int cTerm; /* Character that terminated the most recent field */
4947 int cColSep; /* The column separator character. (Usually ",") */
4948 int cRowSep; /* The row separator character. (Usually "\n") */
4951 /* Clean up resourced used by an ImportCtx */
4952 static void import_cleanup(ImportCtx *p){
4953 if( p->in!=0 && p->xCloser!=0 ){
4954 p->xCloser(p->in);
4955 p->in = 0;
4957 sqlite3_free(p->z);
4958 p->z = 0;
4961 /* Append a single byte to z[] */
4962 static void import_append_char(ImportCtx *p, int c){
4963 if( p->n+1>=p->nAlloc ){
4964 p->nAlloc += p->nAlloc + 100;
4965 p->z = sqlite3_realloc64(p->z, p->nAlloc);
4966 if( p->z==0 ) shell_out_of_memory();
4968 p->z[p->n++] = (char)c;
4971 /* Read a single field of CSV text. Compatible with rfc4180 and extended
4972 ** with the option of having a separator other than ",".
4974 ** + Input comes from p->in.
4975 ** + Store results in p->z of length p->n. Space to hold p->z comes
4976 ** from sqlite3_malloc64().
4977 ** + Use p->cSep as the column separator. The default is ",".
4978 ** + Use p->rSep as the row separator. The default is "\n".
4979 ** + Keep track of the line number in p->nLine.
4980 ** + Store the character that terminates the field in p->cTerm. Store
4981 ** EOF on end-of-file.
4982 ** + Report syntax errors on stderr
4984 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4985 int c;
4986 int cSep = p->cColSep;
4987 int rSep = p->cRowSep;
4988 p->n = 0;
4989 c = fgetc(p->in);
4990 if( c==EOF || seenInterrupt ){
4991 p->cTerm = EOF;
4992 return 0;
4994 if( c=='"' ){
4995 int pc, ppc;
4996 int startLine = p->nLine;
4997 int cQuote = c;
4998 pc = ppc = 0;
4999 while( 1 ){
5000 c = fgetc(p->in);
5001 if( c==rSep ) p->nLine++;
5002 if( c==cQuote ){
5003 if( pc==cQuote ){
5004 pc = 0;
5005 continue;
5008 if( (c==cSep && pc==cQuote)
5009 || (c==rSep && pc==cQuote)
5010 || (c==rSep && pc=='\r' && ppc==cQuote)
5011 || (c==EOF && pc==cQuote)
5013 do{ p->n--; }while( p->z[p->n]!=cQuote );
5014 p->cTerm = c;
5015 break;
5017 if( pc==cQuote && c!='\r' ){
5018 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5019 p->zFile, p->nLine, cQuote);
5021 if( c==EOF ){
5022 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5023 p->zFile, startLine, cQuote);
5024 p->cTerm = c;
5025 break;
5027 import_append_char(p, c);
5028 ppc = pc;
5029 pc = c;
5031 }else{
5032 /* If this is the first field being parsed and it begins with the
5033 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5034 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5035 import_append_char(p, c);
5036 c = fgetc(p->in);
5037 if( (c&0xff)==0xbb ){
5038 import_append_char(p, c);
5039 c = fgetc(p->in);
5040 if( (c&0xff)==0xbf ){
5041 p->bNotFirst = 1;
5042 p->n = 0;
5043 return csv_read_one_field(p);
5047 while( c!=EOF && c!=cSep && c!=rSep ){
5048 import_append_char(p, c);
5049 c = fgetc(p->in);
5051 if( c==rSep ){
5052 p->nLine++;
5053 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5055 p->cTerm = c;
5057 if( p->z ) p->z[p->n] = 0;
5058 p->bNotFirst = 1;
5059 return p->z;
5062 /* Read a single field of ASCII delimited text.
5064 ** + Input comes from p->in.
5065 ** + Store results in p->z of length p->n. Space to hold p->z comes
5066 ** from sqlite3_malloc64().
5067 ** + Use p->cSep as the column separator. The default is "\x1F".
5068 ** + Use p->rSep as the row separator. The default is "\x1E".
5069 ** + Keep track of the row number in p->nLine.
5070 ** + Store the character that terminates the field in p->cTerm. Store
5071 ** EOF on end-of-file.
5072 ** + Report syntax errors on stderr
5074 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5075 int c;
5076 int cSep = p->cColSep;
5077 int rSep = p->cRowSep;
5078 p->n = 0;
5079 c = fgetc(p->in);
5080 if( c==EOF || seenInterrupt ){
5081 p->cTerm = EOF;
5082 return 0;
5084 while( c!=EOF && c!=cSep && c!=rSep ){
5085 import_append_char(p, c);
5086 c = fgetc(p->in);
5088 if( c==rSep ){
5089 p->nLine++;
5091 p->cTerm = c;
5092 if( p->z ) p->z[p->n] = 0;
5093 return p->z;
5097 ** Try to transfer data for table zTable. If an error is seen while
5098 ** moving forward, try to go backwards. The backwards movement won't
5099 ** work for WITHOUT ROWID tables.
5101 static void tryToCloneData(
5102 ShellState *p,
5103 sqlite3 *newDb,
5104 const char *zTable
5106 sqlite3_stmt *pQuery = 0;
5107 sqlite3_stmt *pInsert = 0;
5108 char *zQuery = 0;
5109 char *zInsert = 0;
5110 int rc;
5111 int i, j, n;
5112 int nTable = strlen30(zTable);
5113 int k = 0;
5114 int cnt = 0;
5115 const int spinRate = 10000;
5117 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5118 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5119 if( rc ){
5120 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5121 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5122 zQuery);
5123 goto end_data_xfer;
5125 n = sqlite3_column_count(pQuery);
5126 zInsert = sqlite3_malloc64(200 + nTable + n*3);
5127 if( zInsert==0 ) shell_out_of_memory();
5128 sqlite3_snprintf(200+nTable,zInsert,
5129 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5130 i = strlen30(zInsert);
5131 for(j=1; j<n; j++){
5132 memcpy(zInsert+i, ",?", 2);
5133 i += 2;
5135 memcpy(zInsert+i, ");", 3);
5136 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5137 if( rc ){
5138 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5139 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5140 zQuery);
5141 goto end_data_xfer;
5143 for(k=0; k<2; k++){
5144 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5145 for(i=0; i<n; i++){
5146 switch( sqlite3_column_type(pQuery, i) ){
5147 case SQLITE_NULL: {
5148 sqlite3_bind_null(pInsert, i+1);
5149 break;
5151 case SQLITE_INTEGER: {
5152 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5153 break;
5155 case SQLITE_FLOAT: {
5156 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5157 break;
5159 case SQLITE_TEXT: {
5160 sqlite3_bind_text(pInsert, i+1,
5161 (const char*)sqlite3_column_text(pQuery,i),
5162 -1, SQLITE_STATIC);
5163 break;
5165 case SQLITE_BLOB: {
5166 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5167 sqlite3_column_bytes(pQuery,i),
5168 SQLITE_STATIC);
5169 break;
5172 } /* End for */
5173 rc = sqlite3_step(pInsert);
5174 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5175 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5176 sqlite3_errmsg(newDb));
5178 sqlite3_reset(pInsert);
5179 cnt++;
5180 if( (cnt%spinRate)==0 ){
5181 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5182 fflush(stdout);
5184 } /* End while */
5185 if( rc==SQLITE_DONE ) break;
5186 sqlite3_finalize(pQuery);
5187 sqlite3_free(zQuery);
5188 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5189 zTable);
5190 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5191 if( rc ){
5192 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5193 break;
5195 } /* End for(k=0...) */
5197 end_data_xfer:
5198 sqlite3_finalize(pQuery);
5199 sqlite3_finalize(pInsert);
5200 sqlite3_free(zQuery);
5201 sqlite3_free(zInsert);
5206 ** Try to transfer all rows of the schema that match zWhere. For
5207 ** each row, invoke xForEach() on the object defined by that row.
5208 ** If an error is encountered while moving forward through the
5209 ** sqlite_schema table, try again moving backwards.
5211 static void tryToCloneSchema(
5212 ShellState *p,
5213 sqlite3 *newDb,
5214 const char *zWhere,
5215 void (*xForEach)(ShellState*,sqlite3*,const char*)
5217 sqlite3_stmt *pQuery = 0;
5218 char *zQuery = 0;
5219 int rc;
5220 const unsigned char *zName;
5221 const unsigned char *zSql;
5222 char *zErrMsg = 0;
5224 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5225 " WHERE %s", zWhere);
5226 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5227 if( rc ){
5228 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5229 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5230 zQuery);
5231 goto end_schema_xfer;
5233 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5234 zName = sqlite3_column_text(pQuery, 0);
5235 zSql = sqlite3_column_text(pQuery, 1);
5236 printf("%s... ", zName); fflush(stdout);
5237 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5238 if( zErrMsg ){
5239 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5240 sqlite3_free(zErrMsg);
5241 zErrMsg = 0;
5243 if( xForEach ){
5244 xForEach(p, newDb, (const char*)zName);
5246 printf("done\n");
5248 if( rc!=SQLITE_DONE ){
5249 sqlite3_finalize(pQuery);
5250 sqlite3_free(zQuery);
5251 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5252 " WHERE %s ORDER BY rowid DESC", zWhere);
5253 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5254 if( rc ){
5255 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5256 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5257 zQuery);
5258 goto end_schema_xfer;
5260 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5261 zName = sqlite3_column_text(pQuery, 0);
5262 zSql = sqlite3_column_text(pQuery, 1);
5263 printf("%s... ", zName); fflush(stdout);
5264 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5265 if( zErrMsg ){
5266 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5267 sqlite3_free(zErrMsg);
5268 zErrMsg = 0;
5270 if( xForEach ){
5271 xForEach(p, newDb, (const char*)zName);
5273 printf("done\n");
5276 end_schema_xfer:
5277 sqlite3_finalize(pQuery);
5278 sqlite3_free(zQuery);
5282 ** Open a new database file named "zNewDb". Try to recover as much information
5283 ** as possible out of the main database (which might be corrupt) and write it
5284 ** into zNewDb.
5286 static void tryToClone(ShellState *p, const char *zNewDb){
5287 int rc;
5288 sqlite3 *newDb = 0;
5289 if( access(zNewDb,0)==0 ){
5290 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5291 return;
5293 rc = sqlite3_open(zNewDb, &newDb);
5294 if( rc ){
5295 utf8_printf(stderr, "Cannot create output database: %s\n",
5296 sqlite3_errmsg(newDb));
5297 }else{
5298 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5299 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5300 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5301 tryToCloneSchema(p, newDb, "type!='table'", 0);
5302 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5303 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5305 close_db(newDb);
5309 ** Change the output file back to stdout.
5311 ** If the p->doXdgOpen flag is set, that means the output was being
5312 ** redirected to a temporary file named by p->zTempFile. In that case,
5313 ** launch start/open/xdg-open on that temporary file.
5315 static void output_reset(ShellState *p){
5316 if( p->outfile[0]=='|' ){
5317 #ifndef SQLITE_OMIT_POPEN
5318 pclose(p->out);
5319 #endif
5320 }else{
5321 output_file_close(p->out);
5322 #ifndef SQLITE_NOHAVE_SYSTEM
5323 if( p->doXdgOpen ){
5324 const char *zXdgOpenCmd =
5325 #if defined(_WIN32)
5326 "start";
5327 #elif defined(__APPLE__)
5328 "open";
5329 #else
5330 "xdg-open";
5331 #endif
5332 char *zCmd;
5333 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5334 if( system(zCmd) ){
5335 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5336 }else{
5337 /* Give the start/open/xdg-open command some time to get
5338 ** going before we continue, and potential delete the
5339 ** p->zTempFile data file out from under it */
5340 sqlite3_sleep(2000);
5342 sqlite3_free(zCmd);
5343 outputModePop(p);
5344 p->doXdgOpen = 0;
5346 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5348 p->outfile[0] = 0;
5349 p->out = stdout;
5353 ** Run an SQL command and return the single integer result.
5355 static int db_int(ShellState *p, const char *zSql){
5356 sqlite3_stmt *pStmt;
5357 int res = 0;
5358 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5359 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5360 res = sqlite3_column_int(pStmt,0);
5362 sqlite3_finalize(pStmt);
5363 return res;
5367 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
5369 static unsigned int get2byteInt(unsigned char *a){
5370 return (a[0]<<8) + a[1];
5372 static unsigned int get4byteInt(unsigned char *a){
5373 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5377 ** Implementation of the ".dbinfo" command.
5379 ** Return 1 on error, 2 to exit, and 0 otherwise.
5381 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5382 static const struct { const char *zName; int ofst; } aField[] = {
5383 { "file change counter:", 24 },
5384 { "database page count:", 28 },
5385 { "freelist page count:", 36 },
5386 { "schema cookie:", 40 },
5387 { "schema format:", 44 },
5388 { "default cache size:", 48 },
5389 { "autovacuum top root:", 52 },
5390 { "incremental vacuum:", 64 },
5391 { "text encoding:", 56 },
5392 { "user version:", 60 },
5393 { "application id:", 68 },
5394 { "software version:", 96 },
5396 static const struct { const char *zName; const char *zSql; } aQuery[] = {
5397 { "number of tables:",
5398 "SELECT count(*) FROM %s WHERE type='table'" },
5399 { "number of indexes:",
5400 "SELECT count(*) FROM %s WHERE type='index'" },
5401 { "number of triggers:",
5402 "SELECT count(*) FROM %s WHERE type='trigger'" },
5403 { "number of views:",
5404 "SELECT count(*) FROM %s WHERE type='view'" },
5405 { "schema size:",
5406 "SELECT total(length(sql)) FROM %s" },
5408 int i, rc;
5409 unsigned iDataVersion;
5410 char *zSchemaTab;
5411 char *zDb = nArg>=2 ? azArg[1] : "main";
5412 sqlite3_stmt *pStmt = 0;
5413 unsigned char aHdr[100];
5414 open_db(p, 0);
5415 if( p->db==0 ) return 1;
5416 rc = sqlite3_prepare_v2(p->db,
5417 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5418 -1, &pStmt, 0);
5419 if( rc ){
5420 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5421 sqlite3_finalize(pStmt);
5422 return 1;
5424 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5425 if( sqlite3_step(pStmt)==SQLITE_ROW
5426 && sqlite3_column_bytes(pStmt,0)>100
5428 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5429 sqlite3_finalize(pStmt);
5430 }else{
5431 raw_printf(stderr, "unable to read database header\n");
5432 sqlite3_finalize(pStmt);
5433 return 1;
5435 i = get2byteInt(aHdr+16);
5436 if( i==1 ) i = 65536;
5437 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5438 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5439 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5440 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5441 for(i=0; i<ArraySize(aField); i++){
5442 int ofst = aField[i].ofst;
5443 unsigned int val = get4byteInt(aHdr + ofst);
5444 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5445 switch( ofst ){
5446 case 56: {
5447 if( val==1 ) raw_printf(p->out, " (utf8)");
5448 if( val==2 ) raw_printf(p->out, " (utf16le)");
5449 if( val==3 ) raw_printf(p->out, " (utf16be)");
5452 raw_printf(p->out, "\n");
5454 if( zDb==0 ){
5455 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5456 }else if( strcmp(zDb,"temp")==0 ){
5457 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5458 }else{
5459 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5461 for(i=0; i<ArraySize(aQuery); i++){
5462 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5463 int val = db_int(p, zSql);
5464 sqlite3_free(zSql);
5465 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5467 sqlite3_free(zSchemaTab);
5468 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5469 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5470 return 0;
5474 ** Print the current sqlite3_errmsg() value to stderr and return 1.
5476 static int shellDatabaseError(sqlite3 *db){
5477 const char *zErr = sqlite3_errmsg(db);
5478 utf8_printf(stderr, "Error: %s\n", zErr);
5479 return 1;
5483 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
5484 ** if they match and FALSE (0) if they do not match.
5486 ** Globbing rules:
5488 ** '*' Matches any sequence of zero or more characters.
5490 ** '?' Matches exactly one character.
5492 ** [...] Matches one character from the enclosed list of
5493 ** characters.
5495 ** [^...] Matches one character not in the enclosed list.
5497 ** '#' Matches any sequence of one or more digits with an
5498 ** optional + or - sign in front
5500 ** ' ' Any span of whitespace matches any other span of
5501 ** whitespace.
5503 ** Extra whitespace at the end of z[] is ignored.
5505 static int testcase_glob(const char *zGlob, const char *z){
5506 int c, c2;
5507 int invert;
5508 int seen;
5510 while( (c = (*(zGlob++)))!=0 ){
5511 if( IsSpace(c) ){
5512 if( !IsSpace(*z) ) return 0;
5513 while( IsSpace(*zGlob) ) zGlob++;
5514 while( IsSpace(*z) ) z++;
5515 }else if( c=='*' ){
5516 while( (c=(*(zGlob++))) == '*' || c=='?' ){
5517 if( c=='?' && (*(z++))==0 ) return 0;
5519 if( c==0 ){
5520 return 1;
5521 }else if( c=='[' ){
5522 while( *z && testcase_glob(zGlob-1,z)==0 ){
5523 z++;
5525 return (*z)!=0;
5527 while( (c2 = (*(z++)))!=0 ){
5528 while( c2!=c ){
5529 c2 = *(z++);
5530 if( c2==0 ) return 0;
5532 if( testcase_glob(zGlob,z) ) return 1;
5534 return 0;
5535 }else if( c=='?' ){
5536 if( (*(z++))==0 ) return 0;
5537 }else if( c=='[' ){
5538 int prior_c = 0;
5539 seen = 0;
5540 invert = 0;
5541 c = *(z++);
5542 if( c==0 ) return 0;
5543 c2 = *(zGlob++);
5544 if( c2=='^' ){
5545 invert = 1;
5546 c2 = *(zGlob++);
5548 if( c2==']' ){
5549 if( c==']' ) seen = 1;
5550 c2 = *(zGlob++);
5552 while( c2 && c2!=']' ){
5553 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5554 c2 = *(zGlob++);
5555 if( c>=prior_c && c<=c2 ) seen = 1;
5556 prior_c = 0;
5557 }else{
5558 if( c==c2 ){
5559 seen = 1;
5561 prior_c = c2;
5563 c2 = *(zGlob++);
5565 if( c2==0 || (seen ^ invert)==0 ) return 0;
5566 }else if( c=='#' ){
5567 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5568 if( !IsDigit(z[0]) ) return 0;
5569 z++;
5570 while( IsDigit(z[0]) ){ z++; }
5571 }else{
5572 if( c!=(*(z++)) ) return 0;
5575 while( IsSpace(*z) ){ z++; }
5576 return *z==0;
5581 ** Compare the string as a command-line option with either one or two
5582 ** initial "-" characters.
5584 static int optionMatch(const char *zStr, const char *zOpt){
5585 if( zStr[0]!='-' ) return 0;
5586 zStr++;
5587 if( zStr[0]=='-' ) zStr++;
5588 return strcmp(zStr, zOpt)==0;
5592 ** Delete a file.
5594 int shellDeleteFile(const char *zFilename){
5595 int rc;
5596 #ifdef _WIN32
5597 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5598 rc = _wunlink(z);
5599 sqlite3_free(z);
5600 #else
5601 rc = unlink(zFilename);
5602 #endif
5603 return rc;
5607 ** Try to delete the temporary file (if there is one) and free the
5608 ** memory used to hold the name of the temp file.
5610 static void clearTempFile(ShellState *p){
5611 if( p->zTempFile==0 ) return;
5612 if( p->doXdgOpen ) return;
5613 if( shellDeleteFile(p->zTempFile) ) return;
5614 sqlite3_free(p->zTempFile);
5615 p->zTempFile = 0;
5619 ** Create a new temp file name with the given suffix.
5621 static void newTempFile(ShellState *p, const char *zSuffix){
5622 clearTempFile(p);
5623 sqlite3_free(p->zTempFile);
5624 p->zTempFile = 0;
5625 if( p->db ){
5626 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5628 if( p->zTempFile==0 ){
5629 /* If p->db is an in-memory database then the TEMPFILENAME file-control
5630 ** will not work and we will need to fallback to guessing */
5631 char *zTemp;
5632 sqlite3_uint64 r;
5633 sqlite3_randomness(sizeof(r), &r);
5634 zTemp = getenv("TEMP");
5635 if( zTemp==0 ) zTemp = getenv("TMP");
5636 if( zTemp==0 ){
5637 #ifdef _WIN32
5638 zTemp = "\\tmp";
5639 #else
5640 zTemp = "/tmp";
5641 #endif
5643 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
5644 }else{
5645 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5647 if( p->zTempFile==0 ){
5648 raw_printf(stderr, "out of memory\n");
5649 exit(1);
5655 ** The implementation of SQL scalar function fkey_collate_clause(), used
5656 ** by the ".lint fkey-indexes" command. This scalar function is always
5657 ** called with four arguments - the parent table name, the parent column name,
5658 ** the child table name and the child column name.
5660 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5662 ** If either of the named tables or columns do not exist, this function
5663 ** returns an empty string. An empty string is also returned if both tables
5664 ** and columns exist but have the same default collation sequence. Or,
5665 ** if both exist but the default collation sequences are different, this
5666 ** function returns the string " COLLATE <parent-collation>", where
5667 ** <parent-collation> is the default collation sequence of the parent column.
5669 static void shellFkeyCollateClause(
5670 sqlite3_context *pCtx,
5671 int nVal,
5672 sqlite3_value **apVal
5674 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5675 const char *zParent;
5676 const char *zParentCol;
5677 const char *zParentSeq;
5678 const char *zChild;
5679 const char *zChildCol;
5680 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5681 int rc;
5683 assert( nVal==4 );
5684 zParent = (const char*)sqlite3_value_text(apVal[0]);
5685 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5686 zChild = (const char*)sqlite3_value_text(apVal[2]);
5687 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5689 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5690 rc = sqlite3_table_column_metadata(
5691 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5693 if( rc==SQLITE_OK ){
5694 rc = sqlite3_table_column_metadata(
5695 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5699 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5700 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5701 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5702 sqlite3_free(z);
5708 ** The implementation of dot-command ".lint fkey-indexes".
5710 static int lintFkeyIndexes(
5711 ShellState *pState, /* Current shell tool state */
5712 char **azArg, /* Array of arguments passed to dot command */
5713 int nArg /* Number of entries in azArg[] */
5715 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5716 FILE *out = pState->out; /* Stream to write non-error output to */
5717 int bVerbose = 0; /* If -verbose is present */
5718 int bGroupByParent = 0; /* If -groupbyparent is present */
5719 int i; /* To iterate through azArg[] */
5720 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5721 int rc; /* Return code */
5722 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5725 ** This SELECT statement returns one row for each foreign key constraint
5726 ** in the schema of the main database. The column values are:
5728 ** 0. The text of an SQL statement similar to:
5730 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5732 ** This SELECT is similar to the one that the foreign keys implementation
5733 ** needs to run internally on child tables. If there is an index that can
5734 ** be used to optimize this query, then it can also be used by the FK
5735 ** implementation to optimize DELETE or UPDATE statements on the parent
5736 ** table.
5738 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5739 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5740 ** contains an index that can be used to optimize the query.
5742 ** 2. Human readable text that describes the child table and columns. e.g.
5744 ** "child_table(child_key1, child_key2)"
5746 ** 3. Human readable text that describes the parent table and columns. e.g.
5748 ** "parent_table(parent_key1, parent_key2)"
5750 ** 4. A full CREATE INDEX statement for an index that could be used to
5751 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5753 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5755 ** 5. The name of the parent table.
5757 ** These six values are used by the C logic below to generate the report.
5759 const char *zSql =
5760 "SELECT "
5761 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5762 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5763 " || fkey_collate_clause("
5764 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5765 ", "
5766 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5767 " || group_concat('*=?', ' AND ') || ')'"
5768 ", "
5769 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5770 ", "
5771 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5772 ", "
5773 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5774 " || ' ON ' || quote(s.name) || '('"
5775 " || group_concat(quote(f.[from]) ||"
5776 " fkey_collate_clause("
5777 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5778 " || ');'"
5779 ", "
5780 " f.[table] "
5781 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
5782 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5783 "GROUP BY s.name, f.id "
5784 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5786 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5788 for(i=2; i<nArg; i++){
5789 int n = strlen30(azArg[i]);
5790 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5791 bVerbose = 1;
5793 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5794 bGroupByParent = 1;
5795 zIndent = " ";
5797 else{
5798 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5799 azArg[0], azArg[1]
5801 return SQLITE_ERROR;
5805 /* Register the fkey_collate_clause() SQL function */
5806 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5807 0, shellFkeyCollateClause, 0, 0
5811 if( rc==SQLITE_OK ){
5812 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5814 if( rc==SQLITE_OK ){
5815 sqlite3_bind_int(pSql, 1, bGroupByParent);
5818 if( rc==SQLITE_OK ){
5819 int rc2;
5820 char *zPrev = 0;
5821 while( SQLITE_ROW==sqlite3_step(pSql) ){
5822 int res = -1;
5823 sqlite3_stmt *pExplain = 0;
5824 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5825 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5826 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5827 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5828 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5829 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5831 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5832 if( rc!=SQLITE_OK ) break;
5833 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5834 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5835 res = (
5836 0==sqlite3_strglob(zGlob, zPlan)
5837 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5840 rc = sqlite3_finalize(pExplain);
5841 if( rc!=SQLITE_OK ) break;
5843 if( res<0 ){
5844 raw_printf(stderr, "Error: internal error");
5845 break;
5846 }else{
5847 if( bGroupByParent
5848 && (bVerbose || res==0)
5849 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5851 raw_printf(out, "-- Parent table %s\n", zParent);
5852 sqlite3_free(zPrev);
5853 zPrev = sqlite3_mprintf("%s", zParent);
5856 if( res==0 ){
5857 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5858 }else if( bVerbose ){
5859 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5860 zIndent, zFrom, zTarget
5865 sqlite3_free(zPrev);
5867 if( rc!=SQLITE_OK ){
5868 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5871 rc2 = sqlite3_finalize(pSql);
5872 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5873 rc = rc2;
5874 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5876 }else{
5877 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5880 return rc;
5884 ** Implementation of ".lint" dot command.
5886 static int lintDotCommand(
5887 ShellState *pState, /* Current shell tool state */
5888 char **azArg, /* Array of arguments passed to dot command */
5889 int nArg /* Number of entries in azArg[] */
5891 int n;
5892 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
5893 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5894 return lintFkeyIndexes(pState, azArg, nArg);
5896 usage:
5897 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5898 raw_printf(stderr, "Where sub-commands are:\n");
5899 raw_printf(stderr, " fkey-indexes\n");
5900 return SQLITE_ERROR;
5903 #if !defined SQLITE_OMIT_VIRTUALTABLE
5904 static void shellPrepare(
5905 sqlite3 *db,
5906 int *pRc,
5907 const char *zSql,
5908 sqlite3_stmt **ppStmt
5910 *ppStmt = 0;
5911 if( *pRc==SQLITE_OK ){
5912 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
5913 if( rc!=SQLITE_OK ){
5914 raw_printf(stderr, "sql error: %s (%d)\n",
5915 sqlite3_errmsg(db), sqlite3_errcode(db)
5917 *pRc = rc;
5923 ** Create a prepared statement using printf-style arguments for the SQL.
5925 ** This routine is could be marked "static". But it is not always used,
5926 ** depending on compile-time options. By omitting the "static", we avoid
5927 ** nuisance compiler warnings about "defined but not used".
5929 void shellPreparePrintf(
5930 sqlite3 *db,
5931 int *pRc,
5932 sqlite3_stmt **ppStmt,
5933 const char *zFmt,
5936 *ppStmt = 0;
5937 if( *pRc==SQLITE_OK ){
5938 va_list ap;
5939 char *z;
5940 va_start(ap, zFmt);
5941 z = sqlite3_vmprintf(zFmt, ap);
5942 va_end(ap);
5943 if( z==0 ){
5944 *pRc = SQLITE_NOMEM;
5945 }else{
5946 shellPrepare(db, pRc, z, ppStmt);
5947 sqlite3_free(z);
5952 /* Finalize the prepared statement created using shellPreparePrintf().
5954 ** This routine is could be marked "static". But it is not always used,
5955 ** depending on compile-time options. By omitting the "static", we avoid
5956 ** nuisance compiler warnings about "defined but not used".
5958 void shellFinalize(
5959 int *pRc,
5960 sqlite3_stmt *pStmt
5962 if( pStmt ){
5963 sqlite3 *db = sqlite3_db_handle(pStmt);
5964 int rc = sqlite3_finalize(pStmt);
5965 if( *pRc==SQLITE_OK ){
5966 if( rc!=SQLITE_OK ){
5967 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5969 *pRc = rc;
5974 /* Reset the prepared statement created using shellPreparePrintf().
5976 ** This routine is could be marked "static". But it is not always used,
5977 ** depending on compile-time options. By omitting the "static", we avoid
5978 ** nuisance compiler warnings about "defined but not used".
5980 void shellReset(
5981 int *pRc,
5982 sqlite3_stmt *pStmt
5984 int rc = sqlite3_reset(pStmt);
5985 if( *pRc==SQLITE_OK ){
5986 if( rc!=SQLITE_OK ){
5987 sqlite3 *db = sqlite3_db_handle(pStmt);
5988 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5990 *pRc = rc;
5993 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
5995 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5996 /******************************************************************************
5997 ** The ".archive" or ".ar" command.
6000 ** Structure representing a single ".ar" command.
6002 typedef struct ArCommand ArCommand;
6003 struct ArCommand {
6004 u8 eCmd; /* An AR_CMD_* value */
6005 u8 bVerbose; /* True if --verbose */
6006 u8 bZip; /* True if the archive is a ZIP */
6007 u8 bDryRun; /* True if --dry-run */
6008 u8 bAppend; /* True if --append */
6009 u8 fromCmdLine; /* Run from -A instead of .archive */
6010 int nArg; /* Number of command arguments */
6011 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6012 const char *zFile; /* --file argument, or NULL */
6013 const char *zDir; /* --directory argument, or NULL */
6014 char **azArg; /* Array of command arguments */
6015 ShellState *p; /* Shell state */
6016 sqlite3 *db; /* Database containing the archive */
6020 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6022 static int arUsage(FILE *f){
6023 showHelp(f,"archive");
6024 return SQLITE_ERROR;
6028 ** Print an error message for the .ar command to stderr and return
6029 ** SQLITE_ERROR.
6031 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6032 va_list ap;
6033 char *z;
6034 va_start(ap, zFmt);
6035 z = sqlite3_vmprintf(zFmt, ap);
6036 va_end(ap);
6037 utf8_printf(stderr, "Error: %s\n", z);
6038 if( pAr->fromCmdLine ){
6039 utf8_printf(stderr, "Use \"-A\" for more help\n");
6040 }else{
6041 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6043 sqlite3_free(z);
6044 return SQLITE_ERROR;
6048 ** Values for ArCommand.eCmd.
6050 #define AR_CMD_CREATE 1
6051 #define AR_CMD_UPDATE 2
6052 #define AR_CMD_INSERT 3
6053 #define AR_CMD_EXTRACT 4
6054 #define AR_CMD_LIST 5
6055 #define AR_CMD_HELP 6
6058 ** Other (non-command) switches.
6060 #define AR_SWITCH_VERBOSE 7
6061 #define AR_SWITCH_FILE 8
6062 #define AR_SWITCH_DIRECTORY 9
6063 #define AR_SWITCH_APPEND 10
6064 #define AR_SWITCH_DRYRUN 11
6066 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6067 switch( eSwitch ){
6068 case AR_CMD_CREATE:
6069 case AR_CMD_EXTRACT:
6070 case AR_CMD_LIST:
6071 case AR_CMD_UPDATE:
6072 case AR_CMD_INSERT:
6073 case AR_CMD_HELP:
6074 if( pAr->eCmd ){
6075 return arErrorMsg(pAr, "multiple command options");
6077 pAr->eCmd = eSwitch;
6078 break;
6080 case AR_SWITCH_DRYRUN:
6081 pAr->bDryRun = 1;
6082 break;
6083 case AR_SWITCH_VERBOSE:
6084 pAr->bVerbose = 1;
6085 break;
6086 case AR_SWITCH_APPEND:
6087 pAr->bAppend = 1;
6088 /* Fall thru into --file */
6089 case AR_SWITCH_FILE:
6090 pAr->zFile = zArg;
6091 break;
6092 case AR_SWITCH_DIRECTORY:
6093 pAr->zDir = zArg;
6094 break;
6097 return SQLITE_OK;
6101 ** Parse the command line for an ".ar" command. The results are written into
6102 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6103 ** successfully, otherwise an error message is written to stderr and
6104 ** SQLITE_ERROR returned.
6106 static int arParseCommand(
6107 char **azArg, /* Array of arguments passed to dot command */
6108 int nArg, /* Number of entries in azArg[] */
6109 ArCommand *pAr /* Populate this object */
6111 struct ArSwitch {
6112 const char *zLong;
6113 char cShort;
6114 u8 eSwitch;
6115 u8 bArg;
6116 } aSwitch[] = {
6117 { "create", 'c', AR_CMD_CREATE, 0 },
6118 { "extract", 'x', AR_CMD_EXTRACT, 0 },
6119 { "insert", 'i', AR_CMD_INSERT, 0 },
6120 { "list", 't', AR_CMD_LIST, 0 },
6121 { "update", 'u', AR_CMD_UPDATE, 0 },
6122 { "help", 'h', AR_CMD_HELP, 0 },
6123 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
6124 { "file", 'f', AR_SWITCH_FILE, 1 },
6125 { "append", 'a', AR_SWITCH_APPEND, 1 },
6126 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6127 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
6129 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6130 struct ArSwitch *pEnd = &aSwitch[nSwitch];
6132 if( nArg<=1 ){
6133 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
6134 return arUsage(stderr);
6135 }else{
6136 char *z = azArg[1];
6137 if( z[0]!='-' ){
6138 /* Traditional style [tar] invocation */
6139 int i;
6140 int iArg = 2;
6141 for(i=0; z[i]; i++){
6142 const char *zArg = 0;
6143 struct ArSwitch *pOpt;
6144 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6145 if( z[i]==pOpt->cShort ) break;
6147 if( pOpt==pEnd ){
6148 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6150 if( pOpt->bArg ){
6151 if( iArg>=nArg ){
6152 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6154 zArg = azArg[iArg++];
6156 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6158 pAr->nArg = nArg-iArg;
6159 if( pAr->nArg>0 ){
6160 pAr->azArg = &azArg[iArg];
6162 }else{
6163 /* Non-traditional invocation */
6164 int iArg;
6165 for(iArg=1; iArg<nArg; iArg++){
6166 int n;
6167 z = azArg[iArg];
6168 if( z[0]!='-' ){
6169 /* All remaining command line words are command arguments. */
6170 pAr->azArg = &azArg[iArg];
6171 pAr->nArg = nArg-iArg;
6172 break;
6174 n = strlen30(z);
6176 if( z[1]!='-' ){
6177 int i;
6178 /* One or more short options */
6179 for(i=1; i<n; i++){
6180 const char *zArg = 0;
6181 struct ArSwitch *pOpt;
6182 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6183 if( z[i]==pOpt->cShort ) break;
6185 if( pOpt==pEnd ){
6186 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6188 if( pOpt->bArg ){
6189 if( i<(n-1) ){
6190 zArg = &z[i+1];
6191 i = n;
6192 }else{
6193 if( iArg>=(nArg-1) ){
6194 return arErrorMsg(pAr, "option requires an argument: %c",
6195 z[i]);
6197 zArg = azArg[++iArg];
6200 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6202 }else if( z[2]=='\0' ){
6203 /* A -- option, indicating that all remaining command line words
6204 ** are command arguments. */
6205 pAr->azArg = &azArg[iArg+1];
6206 pAr->nArg = nArg-iArg-1;
6207 break;
6208 }else{
6209 /* A long option */
6210 const char *zArg = 0; /* Argument for option, if any */
6211 struct ArSwitch *pMatch = 0; /* Matching option */
6212 struct ArSwitch *pOpt; /* Iterator */
6213 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6214 const char *zLong = pOpt->zLong;
6215 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6216 if( pMatch ){
6217 return arErrorMsg(pAr, "ambiguous option: %s",z);
6218 }else{
6219 pMatch = pOpt;
6224 if( pMatch==0 ){
6225 return arErrorMsg(pAr, "unrecognized option: %s", z);
6227 if( pMatch->bArg ){
6228 if( iArg>=(nArg-1) ){
6229 return arErrorMsg(pAr, "option requires an argument: %s", z);
6231 zArg = azArg[++iArg];
6233 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6239 return SQLITE_OK;
6243 ** This function assumes that all arguments within the ArCommand.azArg[]
6244 ** array refer to archive members, as for the --extract or --list commands.
6245 ** It checks that each of them are present. If any specified file is not
6246 ** present in the archive, an error is printed to stderr and an error
6247 ** code returned. Otherwise, if all specified arguments are present in
6248 ** the archive, SQLITE_OK is returned.
6250 ** This function strips any trailing '/' characters from each argument.
6251 ** This is consistent with the way the [tar] command seems to work on
6252 ** Linux.
6254 static int arCheckEntries(ArCommand *pAr){
6255 int rc = SQLITE_OK;
6256 if( pAr->nArg ){
6257 int i, j;
6258 sqlite3_stmt *pTest = 0;
6260 shellPreparePrintf(pAr->db, &rc, &pTest,
6261 "SELECT name FROM %s WHERE name=$name",
6262 pAr->zSrcTable
6264 j = sqlite3_bind_parameter_index(pTest, "$name");
6265 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6266 char *z = pAr->azArg[i];
6267 int n = strlen30(z);
6268 int bOk = 0;
6269 while( n>0 && z[n-1]=='/' ) n--;
6270 z[n] = '\0';
6271 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6272 if( SQLITE_ROW==sqlite3_step(pTest) ){
6273 bOk = 1;
6275 shellReset(&rc, pTest);
6276 if( rc==SQLITE_OK && bOk==0 ){
6277 utf8_printf(stderr, "not found in archive: %s\n", z);
6278 rc = SQLITE_ERROR;
6281 shellFinalize(&rc, pTest);
6283 return rc;
6287 ** Format a WHERE clause that can be used against the "sqlar" table to
6288 ** identify all archive members that match the command arguments held
6289 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6290 ** The caller is responsible for eventually calling sqlite3_free() on
6291 ** any non-NULL (*pzWhere) value.
6293 static void arWhereClause(
6294 int *pRc,
6295 ArCommand *pAr,
6296 char **pzWhere /* OUT: New WHERE clause */
6298 char *zWhere = 0;
6299 if( *pRc==SQLITE_OK ){
6300 if( pAr->nArg==0 ){
6301 zWhere = sqlite3_mprintf("1");
6302 }else{
6303 int i;
6304 const char *zSep = "";
6305 for(i=0; i<pAr->nArg; i++){
6306 const char *z = pAr->azArg[i];
6307 zWhere = sqlite3_mprintf(
6308 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
6309 zWhere, zSep, z, strlen30(z)+1, z
6311 if( zWhere==0 ){
6312 *pRc = SQLITE_NOMEM;
6313 break;
6315 zSep = " OR ";
6319 *pzWhere = zWhere;
6323 ** Implementation of .ar "lisT" command.
6325 static int arListCommand(ArCommand *pAr){
6326 const char *zSql = "SELECT %s FROM %s WHERE %s";
6327 const char *azCols[] = {
6328 "name",
6329 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6332 char *zWhere = 0;
6333 sqlite3_stmt *pSql = 0;
6334 int rc;
6336 rc = arCheckEntries(pAr);
6337 arWhereClause(&rc, pAr, &zWhere);
6339 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6340 pAr->zSrcTable, zWhere);
6341 if( pAr->bDryRun ){
6342 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6343 }else{
6344 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6345 if( pAr->bVerbose ){
6346 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
6347 sqlite3_column_text(pSql, 0),
6348 sqlite3_column_int(pSql, 1),
6349 sqlite3_column_text(pSql, 2),
6350 sqlite3_column_text(pSql, 3)
6352 }else{
6353 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6357 shellFinalize(&rc, pSql);
6358 sqlite3_free(zWhere);
6359 return rc;
6364 ** Implementation of .ar "eXtract" command.
6366 static int arExtractCommand(ArCommand *pAr){
6367 const char *zSql1 =
6368 "SELECT "
6369 " ($dir || name),"
6370 " writefile(($dir || name), %s, mode, mtime) "
6371 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6372 " AND name NOT GLOB '*..[/\\]*'";
6374 const char *azExtraArg[] = {
6375 "sqlar_uncompress(data, sz)",
6376 "data"
6379 sqlite3_stmt *pSql = 0;
6380 int rc = SQLITE_OK;
6381 char *zDir = 0;
6382 char *zWhere = 0;
6383 int i, j;
6385 /* If arguments are specified, check that they actually exist within
6386 ** the archive before proceeding. And formulate a WHERE clause to
6387 ** match them. */
6388 rc = arCheckEntries(pAr);
6389 arWhereClause(&rc, pAr, &zWhere);
6391 if( rc==SQLITE_OK ){
6392 if( pAr->zDir ){
6393 zDir = sqlite3_mprintf("%s/", pAr->zDir);
6394 }else{
6395 zDir = sqlite3_mprintf("");
6397 if( zDir==0 ) rc = SQLITE_NOMEM;
6400 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6401 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6404 if( rc==SQLITE_OK ){
6405 j = sqlite3_bind_parameter_index(pSql, "$dir");
6406 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6408 /* Run the SELECT statement twice. The first time, writefile() is called
6409 ** for all archive members that should be extracted. The second time,
6410 ** only for the directories. This is because the timestamps for
6411 ** extracted directories must be reset after they are populated (as
6412 ** populating them changes the timestamp). */
6413 for(i=0; i<2; i++){
6414 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6415 sqlite3_bind_int(pSql, j, i);
6416 if( pAr->bDryRun ){
6417 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6418 }else{
6419 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6420 if( i==0 && pAr->bVerbose ){
6421 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6425 shellReset(&rc, pSql);
6427 shellFinalize(&rc, pSql);
6430 sqlite3_free(zDir);
6431 sqlite3_free(zWhere);
6432 return rc;
6436 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
6438 static int arExecSql(ArCommand *pAr, const char *zSql){
6439 int rc;
6440 if( pAr->bDryRun ){
6441 utf8_printf(pAr->p->out, "%s\n", zSql);
6442 rc = SQLITE_OK;
6443 }else{
6444 char *zErr = 0;
6445 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6446 if( zErr ){
6447 utf8_printf(stdout, "ERROR: %s\n", zErr);
6448 sqlite3_free(zErr);
6451 return rc;
6456 ** Implementation of .ar "create", "insert", and "update" commands.
6458 ** create -> Create a new SQL archive
6459 ** insert -> Insert or reinsert all files listed
6460 ** update -> Insert files that have changed or that were not
6461 ** previously in the archive
6463 ** Create the "sqlar" table in the database if it does not already exist.
6464 ** Then add each file in the azFile[] array to the archive. Directories
6465 ** are added recursively. If argument bVerbose is non-zero, a message is
6466 ** printed on stdout for each file archived.
6468 ** The create command is the same as update, except that it drops
6469 ** any existing "sqlar" table before beginning. The "insert" command
6470 ** always overwrites every file named on the command-line, where as
6471 ** "update" only overwrites if the size or mtime or mode has changed.
6473 static int arCreateOrUpdateCommand(
6474 ArCommand *pAr, /* Command arguments and options */
6475 int bUpdate, /* true for a --create. */
6476 int bOnlyIfChanged /* Only update if file has changed */
6478 const char *zCreate =
6479 "CREATE TABLE IF NOT EXISTS sqlar(\n"
6480 " name TEXT PRIMARY KEY, -- name of the file\n"
6481 " mode INT, -- access permissions\n"
6482 " mtime INT, -- last modification time\n"
6483 " sz INT, -- original file size\n"
6484 " data BLOB -- compressed content\n"
6485 ")";
6486 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6487 const char *zInsertFmt[2] = {
6488 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6489 " SELECT\n"
6490 " %s,\n"
6491 " mode,\n"
6492 " mtime,\n"
6493 " CASE substr(lsmode(mode),1,1)\n"
6494 " WHEN '-' THEN length(data)\n"
6495 " WHEN 'd' THEN 0\n"
6496 " ELSE -1 END,\n"
6497 " sqlar_compress(data)\n"
6498 " FROM fsdir(%Q,%Q) AS disk\n"
6499 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6501 "REPLACE INTO %s(name,mode,mtime,data)\n"
6502 " SELECT\n"
6503 " %s,\n"
6504 " mode,\n"
6505 " mtime,\n"
6506 " data\n"
6507 " FROM fsdir(%Q,%Q) AS disk\n"
6508 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6510 int i; /* For iterating through azFile[] */
6511 int rc; /* Return code */
6512 const char *zTab = 0; /* SQL table into which to insert */
6513 char *zSql;
6514 char zTemp[50];
6515 char *zExists = 0;
6517 arExecSql(pAr, "PRAGMA page_size=512");
6518 rc = arExecSql(pAr, "SAVEPOINT ar;");
6519 if( rc!=SQLITE_OK ) return rc;
6520 zTemp[0] = 0;
6521 if( pAr->bZip ){
6522 /* Initialize the zipfile virtual table, if necessary */
6523 if( pAr->zFile ){
6524 sqlite3_uint64 r;
6525 sqlite3_randomness(sizeof(r),&r);
6526 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6527 zTab = zTemp;
6528 zSql = sqlite3_mprintf(
6529 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6530 zTab, pAr->zFile
6532 rc = arExecSql(pAr, zSql);
6533 sqlite3_free(zSql);
6534 }else{
6535 zTab = "zip";
6537 }else{
6538 /* Initialize the table for an SQLAR */
6539 zTab = "sqlar";
6540 if( bUpdate==0 ){
6541 rc = arExecSql(pAr, zDrop);
6542 if( rc!=SQLITE_OK ) goto end_ar_transaction;
6544 rc = arExecSql(pAr, zCreate);
6546 if( bOnlyIfChanged ){
6547 zExists = sqlite3_mprintf(
6548 " AND NOT EXISTS("
6549 "SELECT 1 FROM %s AS mem"
6550 " WHERE mem.name=disk.name"
6551 " AND mem.mtime=disk.mtime"
6552 " AND mem.mode=disk.mode)", zTab);
6553 }else{
6554 zExists = sqlite3_mprintf("");
6556 if( zExists==0 ) rc = SQLITE_NOMEM;
6557 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6558 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6559 pAr->bVerbose ? "shell_putsnl(name)" : "name",
6560 pAr->azArg[i], pAr->zDir, zExists);
6561 rc = arExecSql(pAr, zSql2);
6562 sqlite3_free(zSql2);
6564 end_ar_transaction:
6565 if( rc!=SQLITE_OK ){
6566 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6567 }else{
6568 rc = arExecSql(pAr, "RELEASE ar;");
6569 if( pAr->bZip && pAr->zFile ){
6570 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6571 arExecSql(pAr, zSql);
6572 sqlite3_free(zSql);
6575 sqlite3_free(zExists);
6576 return rc;
6580 ** Implementation of ".ar" dot command.
6582 static int arDotCommand(
6583 ShellState *pState, /* Current shell tool state */
6584 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
6585 char **azArg, /* Array of arguments passed to dot command */
6586 int nArg /* Number of entries in azArg[] */
6588 ArCommand cmd;
6589 int rc;
6590 memset(&cmd, 0, sizeof(cmd));
6591 cmd.fromCmdLine = fromCmdLine;
6592 rc = arParseCommand(azArg, nArg, &cmd);
6593 if( rc==SQLITE_OK ){
6594 int eDbType = SHELL_OPEN_UNSPEC;
6595 cmd.p = pState;
6596 cmd.db = pState->db;
6597 if( cmd.zFile ){
6598 eDbType = deduceDatabaseType(cmd.zFile, 1);
6599 }else{
6600 eDbType = pState->openMode;
6602 if( eDbType==SHELL_OPEN_ZIPFILE ){
6603 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6604 if( cmd.zFile==0 ){
6605 cmd.zSrcTable = sqlite3_mprintf("zip");
6606 }else{
6607 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6610 cmd.bZip = 1;
6611 }else if( cmd.zFile ){
6612 int flags;
6613 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6614 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6615 || cmd.eCmd==AR_CMD_UPDATE ){
6616 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6617 }else{
6618 flags = SQLITE_OPEN_READONLY;
6620 cmd.db = 0;
6621 if( cmd.bDryRun ){
6622 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6623 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6625 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6626 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6627 if( rc!=SQLITE_OK ){
6628 utf8_printf(stderr, "cannot open file: %s (%s)\n",
6629 cmd.zFile, sqlite3_errmsg(cmd.db)
6631 goto end_ar_command;
6633 sqlite3_fileio_init(cmd.db, 0, 0);
6634 sqlite3_sqlar_init(cmd.db, 0, 0);
6635 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6636 shellPutsFunc, 0, 0);
6639 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6640 if( cmd.eCmd!=AR_CMD_CREATE
6641 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6643 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6644 rc = SQLITE_ERROR;
6645 goto end_ar_command;
6647 cmd.zSrcTable = sqlite3_mprintf("sqlar");
6650 switch( cmd.eCmd ){
6651 case AR_CMD_CREATE:
6652 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6653 break;
6655 case AR_CMD_EXTRACT:
6656 rc = arExtractCommand(&cmd);
6657 break;
6659 case AR_CMD_LIST:
6660 rc = arListCommand(&cmd);
6661 break;
6663 case AR_CMD_HELP:
6664 arUsage(pState->out);
6665 break;
6667 case AR_CMD_INSERT:
6668 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6669 break;
6671 default:
6672 assert( cmd.eCmd==AR_CMD_UPDATE );
6673 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6674 break;
6677 end_ar_command:
6678 if( cmd.db!=pState->db ){
6679 close_db(cmd.db);
6681 sqlite3_free(cmd.zSrcTable);
6683 return rc;
6685 /* End of the ".archive" or ".ar" command logic
6686 *******************************************************************************/
6687 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6689 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6691 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6692 ** Otherwise, the SQL statement or statements in zSql are executed using
6693 ** database connection db and the error code written to *pRc before
6694 ** this function returns.
6696 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6697 int rc = *pRc;
6698 if( rc==SQLITE_OK ){
6699 char *zErr = 0;
6700 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6701 if( rc!=SQLITE_OK ){
6702 raw_printf(stderr, "SQL error: %s\n", zErr);
6704 *pRc = rc;
6709 ** Like shellExec(), except that zFmt is a printf() style format string.
6711 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6712 char *z = 0;
6713 if( *pRc==SQLITE_OK ){
6714 va_list ap;
6715 va_start(ap, zFmt);
6716 z = sqlite3_vmprintf(zFmt, ap);
6717 va_end(ap);
6718 if( z==0 ){
6719 *pRc = SQLITE_NOMEM;
6720 }else{
6721 shellExec(db, pRc, z);
6723 sqlite3_free(z);
6728 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6729 ** Otherwise, an attempt is made to allocate, zero and return a pointer
6730 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6731 ** to SQLITE_NOMEM and NULL returned.
6733 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6734 void *pRet = 0;
6735 if( *pRc==SQLITE_OK ){
6736 pRet = sqlite3_malloc64(nByte);
6737 if( pRet==0 ){
6738 *pRc = SQLITE_NOMEM;
6739 }else{
6740 memset(pRet, 0, nByte);
6743 return pRet;
6747 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6748 ** Otherwise, zFmt is treated as a printf() style string. The result of
6749 ** formatting it along with any trailing arguments is written into a
6750 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6751 ** It is the responsibility of the caller to eventually free this buffer
6752 ** using a call to sqlite3_free().
6754 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6755 ** pointer returned.
6757 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6758 char *z = 0;
6759 if( *pRc==SQLITE_OK ){
6760 va_list ap;
6761 va_start(ap, zFmt);
6762 z = sqlite3_vmprintf(zFmt, ap);
6763 va_end(ap);
6764 if( z==0 ){
6765 *pRc = SQLITE_NOMEM;
6768 return z;
6772 ** When running the ".recover" command, each output table, and the special
6773 ** orphaned row table if it is required, is represented by an instance
6774 ** of the following struct.
6776 typedef struct RecoverTable RecoverTable;
6777 struct RecoverTable {
6778 char *zQuoted; /* Quoted version of table name */
6779 int nCol; /* Number of columns in table */
6780 char **azlCol; /* Array of column lists */
6781 int iPk; /* Index of IPK column */
6785 ** Free a RecoverTable object allocated by recoverFindTable() or
6786 ** recoverOrphanTable().
6788 static void recoverFreeTable(RecoverTable *pTab){
6789 if( pTab ){
6790 sqlite3_free(pTab->zQuoted);
6791 if( pTab->azlCol ){
6792 int i;
6793 for(i=0; i<=pTab->nCol; i++){
6794 sqlite3_free(pTab->azlCol[i]);
6796 sqlite3_free(pTab->azlCol);
6798 sqlite3_free(pTab);
6803 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6804 ** Otherwise, it allocates and returns a RecoverTable object based on the
6805 ** final four arguments passed to this function. It is the responsibility
6806 ** of the caller to eventually free the returned object using
6807 ** recoverFreeTable().
6809 static RecoverTable *recoverNewTable(
6810 int *pRc, /* IN/OUT: Error code */
6811 const char *zName, /* Name of table */
6812 const char *zSql, /* CREATE TABLE statement */
6813 int bIntkey,
6814 int nCol
6816 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
6817 int rc = *pRc;
6818 RecoverTable *pTab = 0;
6820 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
6821 if( rc==SQLITE_OK ){
6822 int nSqlCol = 0;
6823 int bSqlIntkey = 0;
6824 sqlite3_stmt *pStmt = 0;
6826 rc = sqlite3_open("", &dbtmp);
6827 if( rc==SQLITE_OK ){
6828 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
6829 shellIdQuote, 0, 0);
6831 if( rc==SQLITE_OK ){
6832 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6834 if( rc==SQLITE_OK ){
6835 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6836 if( rc==SQLITE_ERROR ){
6837 rc = SQLITE_OK;
6838 goto finished;
6841 shellPreparePrintf(dbtmp, &rc, &pStmt,
6842 "SELECT count(*) FROM pragma_table_info(%Q)", zName
6844 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6845 nSqlCol = sqlite3_column_int(pStmt, 0);
6847 shellFinalize(&rc, pStmt);
6849 if( rc!=SQLITE_OK || nSqlCol<nCol ){
6850 goto finished;
6853 shellPreparePrintf(dbtmp, &rc, &pStmt,
6854 "SELECT ("
6855 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6856 ") FROM sqlite_schema WHERE name = %Q", zName
6858 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6859 bSqlIntkey = sqlite3_column_int(pStmt, 0);
6861 shellFinalize(&rc, pStmt);
6863 if( bIntkey==bSqlIntkey ){
6864 int i;
6865 const char *zPk = "_rowid_";
6866 sqlite3_stmt *pPkFinder = 0;
6868 /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6869 ** set zPk to the name of the PK column, and pTab->iPk to the index
6870 ** of the column, where columns are 0-numbered from left to right.
6871 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6872 ** leave zPk as "_rowid_" and pTab->iPk at -2. */
6873 pTab->iPk = -2;
6874 if( bIntkey ){
6875 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
6876 "SELECT cid, name FROM pragma_table_info(%Q) "
6877 " WHERE pk=1 AND type='integer' COLLATE nocase"
6878 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6879 , zName, zName
6881 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6882 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6883 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6887 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
6888 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
6889 pTab->nCol = nSqlCol;
6891 if( bIntkey ){
6892 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
6893 }else{
6894 pTab->azlCol[0] = shellMPrintf(&rc, "");
6896 i = 1;
6897 shellPreparePrintf(dbtmp, &rc, &pStmt,
6898 "SELECT %Q || group_concat(shell_idquote(name), ', ') "
6899 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
6900 "FROM pragma_table_info(%Q)",
6901 bIntkey ? ", " : "", pTab->iPk,
6902 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6903 zName
6905 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6906 const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6907 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6908 i++;
6910 shellFinalize(&rc, pStmt);
6912 shellFinalize(&rc, pPkFinder);
6916 finished:
6917 sqlite3_close(dbtmp);
6918 *pRc = rc;
6919 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
6920 recoverFreeTable(pTab);
6921 pTab = 0;
6923 return pTab;
6927 ** This function is called to search the schema recovered from the
6928 ** sqlite_schema table of the (possibly) corrupt database as part
6929 ** of a ".recover" command. Specifically, for a table with root page
6930 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
6931 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
6932 ** those.
6934 ** If a table is found, a (RecoverTable*) object is returned. Or, if
6935 ** no such table is found, but bIntkey is false and iRoot is the
6936 ** root page of an index in the recovered schema, then (*pbNoop) is
6937 ** set to true and NULL returned. Or, if there is no such table or
6938 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
6939 ** the caller should write data to the orphans table.
6941 static RecoverTable *recoverFindTable(
6942 ShellState *pState, /* Shell state object */
6943 int *pRc, /* IN/OUT: Error code */
6944 int iRoot, /* Root page of table */
6945 int bIntkey, /* True for an intkey table */
6946 int nCol, /* Number of columns in table */
6947 int *pbNoop /* OUT: True if iRoot is root of index */
6949 sqlite3_stmt *pStmt = 0;
6950 RecoverTable *pRet = 0;
6951 int bNoop = 0;
6952 const char *zSql = 0;
6953 const char *zName = 0;
6955 /* Search the recovered schema for an object with root page iRoot. */
6956 shellPreparePrintf(pState->db, pRc, &pStmt,
6957 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6959 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6960 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6961 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6962 bNoop = 1;
6963 break;
6965 if( sqlite3_stricmp(zType, "table")==0 ){
6966 zName = (const char*)sqlite3_column_text(pStmt, 1);
6967 zSql = (const char*)sqlite3_column_text(pStmt, 2);
6968 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
6969 break;
6973 shellFinalize(pRc, pStmt);
6974 *pbNoop = bNoop;
6975 return pRet;
6979 ** Return a RecoverTable object representing the orphans table.
6981 static RecoverTable *recoverOrphanTable(
6982 ShellState *pState, /* Shell state object */
6983 int *pRc, /* IN/OUT: Error code */
6984 const char *zLostAndFound, /* Base name for orphans table */
6985 int nCol /* Number of user data columns */
6987 RecoverTable *pTab = 0;
6988 if( nCol>=0 && *pRc==SQLITE_OK ){
6989 int i;
6991 /* This block determines the name of the orphan table. The prefered
6992 ** name is zLostAndFound. But if that clashes with another name
6993 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
6994 ** and so on until a non-clashing name is found. */
6995 int iTab = 0;
6996 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
6997 sqlite3_stmt *pTest = 0;
6998 shellPrepare(pState->db, pRc,
6999 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7001 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7002 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7003 shellReset(pRc, pTest);
7004 sqlite3_free(zTab);
7005 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7006 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7008 shellFinalize(pRc, pTest);
7010 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7011 if( pTab ){
7012 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7013 pTab->nCol = nCol;
7014 pTab->iPk = -2;
7015 if( nCol>0 ){
7016 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7017 if( pTab->azlCol ){
7018 pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7019 for(i=nCol-1; i>=0; i--){
7020 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7025 if( *pRc!=SQLITE_OK ){
7026 recoverFreeTable(pTab);
7027 pTab = 0;
7028 }else{
7029 raw_printf(pState->out,
7030 "CREATE TABLE %s(rootpgno INTEGER, "
7031 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7033 for(i=0; i<nCol; i++){
7034 raw_printf(pState->out, ", c%d", i);
7036 raw_printf(pState->out, ");\n");
7039 sqlite3_free(zTab);
7041 return pTab;
7045 ** This function is called to recover data from the database. A script
7046 ** to construct a new database containing all recovered data is output
7047 ** on stream pState->out.
7049 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7050 int rc = SQLITE_OK;
7051 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
7052 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
7053 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
7054 const char *zRecoveryDb = ""; /* Name of "recovery" database */
7055 const char *zLostAndFound = "lost_and_found";
7056 int i;
7057 int nOrphan = -1;
7058 RecoverTable *pOrphan = 0;
7060 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
7061 int bRowids = 1; /* 0 if --no-rowids */
7062 for(i=1; i<nArg; i++){
7063 char *z = azArg[i];
7064 int n;
7065 if( z[0]=='-' && z[1]=='-' ) z++;
7066 n = strlen30(z);
7067 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7068 bFreelist = 0;
7069 }else
7070 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7071 i++;
7072 zRecoveryDb = azArg[i];
7073 }else
7074 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7075 i++;
7076 zLostAndFound = azArg[i];
7077 }else
7078 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7079 bRowids = 0;
7081 else{
7082 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7083 showHelp(pState->out, azArg[0]);
7084 return 1;
7088 shellExecPrintf(pState->db, &rc,
7089 /* Attach an in-memory database named 'recovery'. Create an indexed
7090 ** cache of the sqlite_dbptr virtual table. */
7091 "PRAGMA writable_schema = on;"
7092 "ATTACH %Q AS recovery;"
7093 "DROP TABLE IF EXISTS recovery.dbptr;"
7094 "DROP TABLE IF EXISTS recovery.freelist;"
7095 "DROP TABLE IF EXISTS recovery.map;"
7096 "DROP TABLE IF EXISTS recovery.schema;"
7097 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7100 if( bFreelist ){
7101 shellExec(pState->db, &rc,
7102 "WITH trunk(pgno) AS ("
7103 " SELECT shell_int32("
7104 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7105 " WHERE x>0"
7106 " UNION"
7107 " SELECT shell_int32("
7108 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7109 " FROM trunk WHERE x>0"
7110 "),"
7111 "freelist(data, n, freepgno) AS ("
7112 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7113 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7114 " UNION ALL"
7115 " SELECT data, n-1, shell_int32(data, 2+n) "
7116 " FROM freelist WHERE n>=0"
7118 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7122 /* If this is an auto-vacuum database, add all pointer-map pages to
7123 ** the freelist table. Do this regardless of whether or not
7124 ** --freelist-corrupt was specified. */
7125 shellExec(pState->db, &rc,
7126 "WITH ptrmap(pgno) AS ("
7127 " SELECT 2 WHERE shell_int32("
7128 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7129 " )"
7130 " UNION ALL "
7131 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7132 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7134 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7137 shellExec(pState->db, &rc,
7138 "CREATE TABLE recovery.dbptr("
7139 " pgno, child, PRIMARY KEY(child, pgno)"
7140 ") WITHOUT ROWID;"
7141 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7142 " SELECT * FROM sqlite_dbptr"
7143 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7145 /* Delete any pointer to page 1. This ensures that page 1 is considered
7146 ** a root page, regardless of how corrupt the db is. */
7147 "DELETE FROM recovery.dbptr WHERE child = 1;"
7149 /* Delete all pointers to any pages that have more than one pointer
7150 ** to them. Such pages will be treated as root pages when recovering
7151 ** data. */
7152 "DELETE FROM recovery.dbptr WHERE child IN ("
7153 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7154 ");"
7156 /* Create the "map" table that will (eventually) contain instructions
7157 ** for dealing with each page in the db that contains one or more
7158 ** records. */
7159 "CREATE TABLE recovery.map("
7160 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7161 ");"
7163 /* Populate table [map]. If there are circular loops of pages in the
7164 ** database, the following adds all pages in such a loop to the map
7165 ** as individual root pages. This could be handled better. */
7166 "WITH pages(i, maxlen) AS ("
7167 " SELECT page_count, ("
7168 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7169 " ) FROM pragma_page_count WHERE page_count>0"
7170 " UNION ALL"
7171 " SELECT i-1, ("
7172 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7173 " ) FROM pages WHERE i>=2"
7175 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7176 " SELECT i, maxlen, NULL, ("
7177 " WITH p(orig, pgno, parent) AS ("
7178 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7179 " UNION "
7180 " SELECT i, p.parent, "
7181 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7182 " )"
7183 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7184 ") "
7185 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7186 "UPDATE recovery.map AS o SET intkey = ("
7187 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7188 ");"
7190 /* Extract data from page 1 and any linked pages into table
7191 ** recovery.schema. With the same schema as an sqlite_schema table. */
7192 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7193 "INSERT INTO recovery.schema SELECT "
7194 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
7195 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
7196 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
7197 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
7198 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
7199 "FROM sqlite_dbdata WHERE pgno IN ("
7200 " SELECT pgno FROM recovery.map WHERE root=1"
7202 "GROUP BY pgno, cell;"
7203 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7206 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7207 ** CREATE TABLE statements that extracted from the existing schema. */
7208 if( rc==SQLITE_OK ){
7209 sqlite3_stmt *pStmt = 0;
7210 /* ".recover" might output content in an order which causes immediate
7211 ** foreign key constraints to be violated. So disable foreign-key
7212 ** constraint enforcement to prevent problems when running the output
7213 ** script. */
7214 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7215 raw_printf(pState->out, "BEGIN;\n");
7216 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7217 shellPrepare(pState->db, &rc,
7218 "SELECT sql FROM recovery.schema "
7219 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7221 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7222 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7223 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7224 &zCreateTable[12]
7227 shellFinalize(&rc, pStmt);
7230 /* Figure out if an orphan table will be required. And if so, how many
7231 ** user columns it should contain */
7232 shellPrepare(pState->db, &rc,
7233 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7234 , &pLoop
7236 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7237 nOrphan = sqlite3_column_int(pLoop, 0);
7239 shellFinalize(&rc, pLoop);
7240 pLoop = 0;
7242 shellPrepare(pState->db, &rc,
7243 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7246 shellPrepare(pState->db, &rc,
7247 "SELECT max(field), group_concat(shell_escape_crnl(quote"
7248 "(case when (? AND field<0) then NULL else value end)"
7249 "), ', ')"
7250 ", min(field) "
7251 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7252 "GROUP BY cell", &pCells
7255 /* Loop through each root page. */
7256 shellPrepare(pState->db, &rc,
7257 "SELECT root, intkey, max(maxlen) FROM recovery.map"
7258 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7259 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7260 ")", &pLoop
7262 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7263 int iRoot = sqlite3_column_int(pLoop, 0);
7264 int bIntkey = sqlite3_column_int(pLoop, 1);
7265 int nCol = sqlite3_column_int(pLoop, 2);
7266 int bNoop = 0;
7267 RecoverTable *pTab;
7269 assert( bIntkey==0 || bIntkey==1 );
7270 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7271 if( bNoop || rc ) continue;
7272 if( pTab==0 ){
7273 if( pOrphan==0 ){
7274 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7276 pTab = pOrphan;
7277 if( pTab==0 ) break;
7280 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7281 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7283 sqlite3_bind_int(pPages, 1, iRoot);
7284 if( bRowids==0 && pTab->iPk<0 ){
7285 sqlite3_bind_int(pCells, 1, 1);
7286 }else{
7287 sqlite3_bind_int(pCells, 1, 0);
7289 sqlite3_bind_int(pCells, 3, pTab->iPk);
7291 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7292 int iPgno = sqlite3_column_int(pPages, 0);
7293 sqlite3_bind_int(pCells, 2, iPgno);
7294 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7295 int nField = sqlite3_column_int(pCells, 0);
7296 int iMin = sqlite3_column_int(pCells, 2);
7297 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7299 RecoverTable *pTab2 = pTab;
7300 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7301 if( pOrphan==0 ){
7302 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7304 pTab2 = pOrphan;
7305 if( pTab2==0 ) break;
7308 nField = nField+1;
7309 if( pTab2==pOrphan ){
7310 raw_printf(pState->out,
7311 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7312 pTab2->zQuoted, iRoot, iPgno, nField,
7313 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7315 }else{
7316 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7317 pTab2->zQuoted, pTab2->azlCol[nField], zVal
7321 shellReset(&rc, pCells);
7323 shellReset(&rc, pPages);
7324 if( pTab!=pOrphan ) recoverFreeTable(pTab);
7326 shellFinalize(&rc, pLoop);
7327 shellFinalize(&rc, pPages);
7328 shellFinalize(&rc, pCells);
7329 recoverFreeTable(pOrphan);
7331 /* The rest of the schema */
7332 if( rc==SQLITE_OK ){
7333 sqlite3_stmt *pStmt = 0;
7334 shellPrepare(pState->db, &rc,
7335 "SELECT sql, name FROM recovery.schema "
7336 "WHERE sql NOT LIKE 'create table%'", &pStmt
7338 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7339 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7340 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7341 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7342 char *zPrint = shellMPrintf(&rc,
7343 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7344 zName, zName, zSql
7346 raw_printf(pState->out, "%s;\n", zPrint);
7347 sqlite3_free(zPrint);
7348 }else{
7349 raw_printf(pState->out, "%s;\n", zSql);
7352 shellFinalize(&rc, pStmt);
7355 if( rc==SQLITE_OK ){
7356 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7357 raw_printf(pState->out, "COMMIT;\n");
7359 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7360 return rc;
7362 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7366 ** If an input line begins with "." then invoke this routine to
7367 ** process that line.
7369 ** Return 1 on error, 2 to exit, and 0 otherwise.
7371 static int do_meta_command(char *zLine, ShellState *p){
7372 int h = 1;
7373 int nArg = 0;
7374 int n, c;
7375 int rc = 0;
7376 char *azArg[52];
7378 #ifndef SQLITE_OMIT_VIRTUALTABLE
7379 if( p->expert.pExpert ){
7380 expertFinish(p, 1, 0);
7382 #endif
7384 /* Parse the input line into tokens.
7386 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7387 while( IsSpace(zLine[h]) ){ h++; }
7388 if( zLine[h]==0 ) break;
7389 if( zLine[h]=='\'' || zLine[h]=='"' ){
7390 int delim = zLine[h++];
7391 azArg[nArg++] = &zLine[h];
7392 while( zLine[h] && zLine[h]!=delim ){
7393 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7394 h++;
7396 if( zLine[h]==delim ){
7397 zLine[h++] = 0;
7399 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7400 }else{
7401 azArg[nArg++] = &zLine[h];
7402 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7403 if( zLine[h] ) zLine[h++] = 0;
7404 resolve_backslashes(azArg[nArg-1]);
7407 azArg[nArg] = 0;
7409 /* Process the input line.
7411 if( nArg==0 ) return 0; /* no tokens, no error */
7412 n = strlen30(azArg[0]);
7413 c = azArg[0][0];
7414 clearTempFile(p);
7416 #ifndef SQLITE_OMIT_AUTHORIZATION
7417 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7418 if( nArg!=2 ){
7419 raw_printf(stderr, "Usage: .auth ON|OFF\n");
7420 rc = 1;
7421 goto meta_command_exit;
7423 open_db(p, 0);
7424 if( booleanValue(azArg[1]) ){
7425 sqlite3_set_authorizer(p->db, shellAuth, p);
7426 }else{
7427 sqlite3_set_authorizer(p->db, 0, 0);
7429 }else
7430 #endif
7432 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7433 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7434 open_db(p, 0);
7435 rc = arDotCommand(p, 0, azArg, nArg);
7436 }else
7437 #endif
7439 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7440 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7442 const char *zDestFile = 0;
7443 const char *zDb = 0;
7444 sqlite3 *pDest;
7445 sqlite3_backup *pBackup;
7446 int j;
7447 int bAsync = 0;
7448 const char *zVfs = 0;
7449 for(j=1; j<nArg; j++){
7450 const char *z = azArg[j];
7451 if( z[0]=='-' ){
7452 if( z[1]=='-' ) z++;
7453 if( strcmp(z, "-append")==0 ){
7454 zVfs = "apndvfs";
7455 }else
7456 if( strcmp(z, "-async")==0 ){
7457 bAsync = 1;
7458 }else
7460 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7461 return 1;
7463 }else if( zDestFile==0 ){
7464 zDestFile = azArg[j];
7465 }else if( zDb==0 ){
7466 zDb = zDestFile;
7467 zDestFile = azArg[j];
7468 }else{
7469 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7470 return 1;
7473 if( zDestFile==0 ){
7474 raw_printf(stderr, "missing FILENAME argument on .backup\n");
7475 return 1;
7477 if( zDb==0 ) zDb = "main";
7478 rc = sqlite3_open_v2(zDestFile, &pDest,
7479 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7480 if( rc!=SQLITE_OK ){
7481 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7482 close_db(pDest);
7483 return 1;
7485 if( bAsync ){
7486 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7487 0, 0, 0);
7489 open_db(p, 0);
7490 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7491 if( pBackup==0 ){
7492 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7493 close_db(pDest);
7494 return 1;
7496 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7497 sqlite3_backup_finish(pBackup);
7498 if( rc==SQLITE_DONE ){
7499 rc = 0;
7500 }else{
7501 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7502 rc = 1;
7504 close_db(pDest);
7505 }else
7507 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7508 if( nArg==2 ){
7509 bail_on_error = booleanValue(azArg[1]);
7510 }else{
7511 raw_printf(stderr, "Usage: .bail on|off\n");
7512 rc = 1;
7514 }else
7516 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7517 if( nArg==2 ){
7518 if( booleanValue(azArg[1]) ){
7519 setBinaryMode(p->out, 1);
7520 }else{
7521 setTextMode(p->out, 1);
7523 }else{
7524 raw_printf(stderr, "Usage: .binary on|off\n");
7525 rc = 1;
7527 }else
7529 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7530 if( nArg==2 ){
7531 #if defined(_WIN32) || defined(WIN32)
7532 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7533 rc = !SetCurrentDirectoryW(z);
7534 sqlite3_free(z);
7535 #else
7536 rc = chdir(azArg[1]);
7537 #endif
7538 if( rc ){
7539 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7540 rc = 1;
7542 }else{
7543 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7544 rc = 1;
7546 }else
7548 /* The undocumented ".breakpoint" command causes a call to the no-op
7549 ** routine named test_breakpoint().
7551 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7552 test_breakpoint();
7553 }else
7555 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7556 if( nArg==2 ){
7557 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7558 }else{
7559 raw_printf(stderr, "Usage: .changes on|off\n");
7560 rc = 1;
7562 }else
7564 /* Cancel output redirection, if it is currently set (by .testcase)
7565 ** Then read the content of the testcase-out.txt file and compare against
7566 ** azArg[1]. If there are differences, report an error and exit.
7568 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7569 char *zRes = 0;
7570 output_reset(p);
7571 if( nArg!=2 ){
7572 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7573 rc = 2;
7574 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7575 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7576 rc = 2;
7577 }else if( testcase_glob(azArg[1],zRes)==0 ){
7578 utf8_printf(stderr,
7579 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
7580 p->zTestcase, azArg[1], zRes);
7581 rc = 1;
7582 }else{
7583 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7584 p->nCheck++;
7586 sqlite3_free(zRes);
7587 }else
7589 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7590 if( nArg==2 ){
7591 tryToClone(p, azArg[1]);
7592 }else{
7593 raw_printf(stderr, "Usage: .clone FILENAME\n");
7594 rc = 1;
7596 }else
7598 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7599 ShellState data;
7600 char *zErrMsg = 0;
7601 open_db(p, 0);
7602 memcpy(&data, p, sizeof(data));
7603 data.showHeader = 0;
7604 data.cMode = data.mode = MODE_List;
7605 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
7606 data.cnt = 0;
7607 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
7608 callback, &data, &zErrMsg);
7609 if( zErrMsg ){
7610 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7611 sqlite3_free(zErrMsg);
7612 rc = 1;
7614 }else
7616 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7617 static const struct DbConfigChoices {
7618 const char *zName;
7619 int op;
7620 } aDbConfig[] = {
7621 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
7622 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
7623 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
7624 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
7625 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
7626 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
7627 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
7628 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7629 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
7630 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
7631 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7632 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
7633 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
7634 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
7635 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
7636 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
7638 int ii, v;
7639 open_db(p, 0);
7640 for(ii=0; ii<ArraySize(aDbConfig); ii++){
7641 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7642 if( nArg>=3 ){
7643 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7645 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7646 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7647 if( nArg>1 ) break;
7649 if( nArg>1 && ii==ArraySize(aDbConfig) ){
7650 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7651 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7653 }else
7655 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7656 rc = shell_dbinfo_command(p, nArg, azArg);
7657 }else
7659 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7660 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7661 open_db(p, 0);
7662 rc = recoverDatabaseCmd(p, nArg, azArg);
7663 }else
7664 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7666 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7667 char *zLike = 0;
7668 char *zSql;
7669 int i;
7670 int savedShowHeader = p->showHeader;
7671 int savedShellFlags = p->shellFlgs;
7672 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
7673 for(i=1; i<nArg; i++){
7674 if( azArg[i][0]=='-' ){
7675 const char *z = azArg[i]+1;
7676 if( z[0]=='-' ) z++;
7677 if( strcmp(z,"preserve-rowids")==0 ){
7678 #ifdef SQLITE_OMIT_VIRTUALTABLE
7679 raw_printf(stderr, "The --preserve-rowids option is not compatible"
7680 " with SQLITE_OMIT_VIRTUALTABLE\n");
7681 rc = 1;
7682 sqlite3_free(zLike);
7683 goto meta_command_exit;
7684 #else
7685 ShellSetFlag(p, SHFLG_PreserveRowid);
7686 #endif
7687 }else
7688 if( strcmp(z,"newlines")==0 ){
7689 ShellSetFlag(p, SHFLG_Newlines);
7690 }else
7692 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7693 rc = 1;
7694 sqlite3_free(zLike);
7695 goto meta_command_exit;
7697 }else if( zLike ){
7698 zLike = sqlite3_mprintf("%z OR name LIKE %Q ESCAPE '\\'",
7699 zLike, azArg[i]);
7700 }else{
7701 zLike = sqlite3_mprintf("name LIKE %Q ESCAPE '\\'", azArg[i]);
7705 open_db(p, 0);
7707 /* When playing back a "dump", the content might appear in an order
7708 ** which causes immediate foreign key constraints to be violated.
7709 ** So disable foreign-key constraint enforcement to prevent problems. */
7710 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7711 raw_printf(p->out, "BEGIN TRANSACTION;\n");
7712 p->writableSchema = 0;
7713 p->showHeader = 0;
7714 /* Set writable_schema=ON since doing so forces SQLite to initialize
7715 ** as much of the schema as it can even if the sqlite_schema table is
7716 ** corrupt. */
7717 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7718 p->nErr = 0;
7719 if( zLike==0 ) zLike = sqlite3_mprintf("true");
7720 zSql = sqlite3_mprintf(
7721 "SELECT name, type, sql FROM sqlite_schema "
7722 "WHERE (%s) AND type=='table'"
7723 " AND sql NOT NULL"
7724 " ORDER BY tbl_name='sqlite_sequence', rowid",
7725 zLike
7727 run_schema_dump_query(p,zSql);
7728 sqlite3_free(zSql);
7729 zSql = sqlite3_mprintf(
7730 "SELECT sql FROM sqlite_schema "
7731 "WHERE (%s) AND sql NOT NULL"
7732 " AND type IN ('index','trigger','view')",
7733 zLike
7735 run_table_dump_query(p, zSql);
7736 sqlite3_free(zSql);
7737 sqlite3_free(zLike);
7738 if( p->writableSchema ){
7739 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7740 p->writableSchema = 0;
7742 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7743 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
7744 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
7745 p->showHeader = savedShowHeader;
7746 p->shellFlgs = savedShellFlags;
7747 }else
7749 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7750 if( nArg==2 ){
7751 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7752 }else{
7753 raw_printf(stderr, "Usage: .echo on|off\n");
7754 rc = 1;
7756 }else
7758 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7759 if( nArg==2 ){
7760 p->autoEQPtest = 0;
7761 if( p->autoEQPtrace ){
7762 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7763 p->autoEQPtrace = 0;
7765 if( strcmp(azArg[1],"full")==0 ){
7766 p->autoEQP = AUTOEQP_full;
7767 }else if( strcmp(azArg[1],"trigger")==0 ){
7768 p->autoEQP = AUTOEQP_trigger;
7769 #ifdef SQLITE_DEBUG
7770 }else if( strcmp(azArg[1],"test")==0 ){
7771 p->autoEQP = AUTOEQP_on;
7772 p->autoEQPtest = 1;
7773 }else if( strcmp(azArg[1],"trace")==0 ){
7774 p->autoEQP = AUTOEQP_full;
7775 p->autoEQPtrace = 1;
7776 open_db(p, 0);
7777 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
7778 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7779 #endif
7780 }else{
7781 p->autoEQP = (u8)booleanValue(azArg[1]);
7783 }else{
7784 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
7785 rc = 1;
7787 }else
7789 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7790 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7791 rc = 2;
7792 }else
7794 /* The ".explain" command is automatic now. It is largely pointless. It
7795 ** retained purely for backwards compatibility */
7796 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7797 int val = 1;
7798 if( nArg>=2 ){
7799 if( strcmp(azArg[1],"auto")==0 ){
7800 val = 99;
7801 }else{
7802 val = booleanValue(azArg[1]);
7805 if( val==1 && p->mode!=MODE_Explain ){
7806 p->normalMode = p->mode;
7807 p->mode = MODE_Explain;
7808 p->autoExplain = 0;
7809 }else if( val==0 ){
7810 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7811 p->autoExplain = 0;
7812 }else if( val==99 ){
7813 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7814 p->autoExplain = 1;
7816 }else
7818 #ifndef SQLITE_OMIT_VIRTUALTABLE
7819 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7820 open_db(p, 0);
7821 expertDotCommand(p, azArg, nArg);
7822 }else
7823 #endif
7825 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
7826 static const struct {
7827 const char *zCtrlName; /* Name of a test-control option */
7828 int ctrlCode; /* Integer code for that option */
7829 const char *zUsage; /* Usage notes */
7830 } aCtrl[] = {
7831 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
7832 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
7833 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
7834 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
7835 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
7836 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
7837 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
7838 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
7839 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
7840 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
7842 int filectrl = -1;
7843 int iCtrl = -1;
7844 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
7845 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
7846 int n2, i;
7847 const char *zCmd = 0;
7848 const char *zSchema = 0;
7850 open_db(p, 0);
7851 zCmd = nArg>=2 ? azArg[1] : "help";
7853 if( zCmd[0]=='-'
7854 && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
7855 && nArg>=4
7857 zSchema = azArg[2];
7858 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
7859 nArg -= 2;
7860 zCmd = azArg[1];
7863 /* The argument can optionally begin with "-" or "--" */
7864 if( zCmd[0]=='-' && zCmd[1] ){
7865 zCmd++;
7866 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7869 /* --help lists all file-controls */
7870 if( strcmp(zCmd,"help")==0 ){
7871 utf8_printf(p->out, "Available file-controls:\n");
7872 for(i=0; i<ArraySize(aCtrl); i++){
7873 utf8_printf(p->out, " .filectrl %s %s\n",
7874 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7876 rc = 1;
7877 goto meta_command_exit;
7880 /* convert filectrl text option to value. allow any unique prefix
7881 ** of the option name, or a numerical value. */
7882 n2 = strlen30(zCmd);
7883 for(i=0; i<ArraySize(aCtrl); i++){
7884 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7885 if( filectrl<0 ){
7886 filectrl = aCtrl[i].ctrlCode;
7887 iCtrl = i;
7888 }else{
7889 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
7890 "Use \".filectrl --help\" for help\n", zCmd);
7891 rc = 1;
7892 goto meta_command_exit;
7896 if( filectrl<0 ){
7897 utf8_printf(stderr,"Error: unknown file-control: %s\n"
7898 "Use \".filectrl --help\" for help\n", zCmd);
7899 }else{
7900 switch(filectrl){
7901 case SQLITE_FCNTL_SIZE_LIMIT: {
7902 if( nArg!=2 && nArg!=3 ) break;
7903 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
7904 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
7905 isOk = 1;
7906 break;
7908 case SQLITE_FCNTL_LOCK_TIMEOUT:
7909 case SQLITE_FCNTL_CHUNK_SIZE: {
7910 int x;
7911 if( nArg!=3 ) break;
7912 x = (int)integerValue(azArg[2]);
7913 sqlite3_file_control(p->db, zSchema, filectrl, &x);
7914 isOk = 2;
7915 break;
7917 case SQLITE_FCNTL_PERSIST_WAL:
7918 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
7919 int x;
7920 if( nArg!=2 && nArg!=3 ) break;
7921 x = nArg==3 ? booleanValue(azArg[2]) : -1;
7922 sqlite3_file_control(p->db, zSchema, filectrl, &x);
7923 iRes = x;
7924 isOk = 1;
7925 break;
7927 case SQLITE_FCNTL_HAS_MOVED: {
7928 int x;
7929 if( nArg!=2 ) break;
7930 sqlite3_file_control(p->db, zSchema, filectrl, &x);
7931 iRes = x;
7932 isOk = 1;
7933 break;
7935 case SQLITE_FCNTL_TEMPFILENAME: {
7936 char *z = 0;
7937 if( nArg!=2 ) break;
7938 sqlite3_file_control(p->db, zSchema, filectrl, &z);
7939 if( z ){
7940 utf8_printf(p->out, "%s\n", z);
7941 sqlite3_free(z);
7943 isOk = 2;
7944 break;
7946 case SQLITE_FCNTL_RESERVE_BYTES: {
7947 int x;
7948 if( nArg>=3 ){
7949 x = atoi(azArg[2]);
7950 sqlite3_file_control(p->db, zSchema, filectrl, &x);
7952 x = -1;
7953 sqlite3_file_control(p->db, zSchema, filectrl, &x);
7954 utf8_printf(p->out,"%d\n", x);
7955 isOk = 2;
7956 break;
7960 if( isOk==0 && iCtrl>=0 ){
7961 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
7962 rc = 1;
7963 }else if( isOk==1 ){
7964 char zBuf[100];
7965 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
7966 raw_printf(p->out, "%s\n", zBuf);
7968 }else
7970 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7971 ShellState data;
7972 char *zErrMsg = 0;
7973 int doStats = 0;
7974 memcpy(&data, p, sizeof(data));
7975 data.showHeader = 0;
7976 data.cMode = data.mode = MODE_Semi;
7977 if( nArg==2 && optionMatch(azArg[1], "indent") ){
7978 data.cMode = data.mode = MODE_Pretty;
7979 nArg = 1;
7981 if( nArg!=1 ){
7982 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7983 rc = 1;
7984 goto meta_command_exit;
7986 open_db(p, 0);
7987 rc = sqlite3_exec(p->db,
7988 "SELECT sql FROM"
7989 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7990 " FROM sqlite_schema UNION ALL"
7991 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
7992 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7993 "ORDER BY rowid",
7994 callback, &data, &zErrMsg
7996 if( rc==SQLITE_OK ){
7997 sqlite3_stmt *pStmt;
7998 rc = sqlite3_prepare_v2(p->db,
7999 "SELECT rowid FROM sqlite_schema"
8000 " WHERE name GLOB 'sqlite_stat[134]'",
8001 -1, &pStmt, 0);
8002 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8003 sqlite3_finalize(pStmt);
8005 if( doStats==0 ){
8006 raw_printf(p->out, "/* No STAT tables available */\n");
8007 }else{
8008 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8009 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
8010 callback, &data, &zErrMsg);
8011 data.cMode = data.mode = MODE_Insert;
8012 data.zDestTable = "sqlite_stat1";
8013 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
8014 data.zDestTable = "sqlite_stat4";
8015 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
8016 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8018 }else
8020 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8021 if( nArg==2 ){
8022 p->showHeader = booleanValue(azArg[1]);
8023 p->shellFlgs |= SHFLG_HeaderSet;
8024 }else{
8025 raw_printf(stderr, "Usage: .headers on|off\n");
8026 rc = 1;
8028 }else
8030 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8031 if( nArg>=2 ){
8032 n = showHelp(p->out, azArg[1]);
8033 if( n==0 ){
8034 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8036 }else{
8037 showHelp(p->out, 0);
8039 }else
8041 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8042 char *zTable = 0; /* Insert data into this table */
8043 char *zFile = 0; /* Name of file to extra content from */
8044 sqlite3_stmt *pStmt = NULL; /* A statement */
8045 int nCol; /* Number of columns in the table */
8046 int nByte; /* Number of bytes in an SQL string */
8047 int i, j; /* Loop counters */
8048 int needCommit; /* True to COMMIT or ROLLBACK at end */
8049 int nSep; /* Number of bytes in p->colSeparator[] */
8050 char *zSql; /* An SQL statement */
8051 ImportCtx sCtx; /* Reader context */
8052 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8053 int eVerbose = 0; /* Larger for more console output */
8054 int nSkip = 0; /* Initial lines to skip */
8055 int useOutputMode = 1; /* Use output mode to determine separators */
8057 memset(&sCtx, 0, sizeof(sCtx));
8058 if( p->mode==MODE_Ascii ){
8059 xRead = ascii_read_one_field;
8060 }else{
8061 xRead = csv_read_one_field;
8063 for(i=1; i<nArg; i++){
8064 char *z = azArg[i];
8065 if( z[0]=='-' && z[1]=='-' ) z++;
8066 if( z[0]!='-' ){
8067 if( zFile==0 ){
8068 zFile = z;
8069 }else if( zTable==0 ){
8070 zTable = z;
8071 }else{
8072 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
8073 showHelp(p->out, "import");
8074 rc = 1;
8075 goto meta_command_exit;
8077 }else if( strcmp(z,"-v")==0 ){
8078 eVerbose++;
8079 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8080 nSkip = integerValue(azArg[++i]);
8081 }else if( strcmp(z,"-ascii")==0 ){
8082 sCtx.cColSep = SEP_Unit[0];
8083 sCtx.cRowSep = SEP_Record[0];
8084 xRead = ascii_read_one_field;
8085 useOutputMode = 0;
8086 }else if( strcmp(z,"-csv")==0 ){
8087 sCtx.cColSep = ',';
8088 sCtx.cRowSep = '\n';
8089 xRead = csv_read_one_field;
8090 useOutputMode = 0;
8091 }else{
8092 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
8093 showHelp(p->out, "import");
8094 rc = 1;
8095 goto meta_command_exit;
8098 if( zTable==0 ){
8099 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8100 zFile==0 ? "FILE" : "TABLE");
8101 showHelp(p->out, "import");
8102 rc = 1;
8103 goto meta_command_exit;
8105 seenInterrupt = 0;
8106 open_db(p, 0);
8107 if( useOutputMode ){
8108 /* If neither the --csv or --ascii options are specified, then set
8109 ** the column and row separator characters from the output mode. */
8110 nSep = strlen30(p->colSeparator);
8111 if( nSep==0 ){
8112 raw_printf(stderr,
8113 "Error: non-null column separator required for import\n");
8114 rc = 1;
8115 goto meta_command_exit;
8117 if( nSep>1 ){
8118 raw_printf(stderr,
8119 "Error: multi-character column separators not allowed"
8120 " for import\n");
8121 rc = 1;
8122 goto meta_command_exit;
8124 nSep = strlen30(p->rowSeparator);
8125 if( nSep==0 ){
8126 raw_printf(stderr,
8127 "Error: non-null row separator required for import\n");
8128 rc = 1;
8129 goto meta_command_exit;
8131 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8132 /* When importing CSV (only), if the row separator is set to the
8133 ** default output row separator, change it to the default input
8134 ** row separator. This avoids having to maintain different input
8135 ** and output row separators. */
8136 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8137 nSep = strlen30(p->rowSeparator);
8139 if( nSep>1 ){
8140 raw_printf(stderr, "Error: multi-character row separators not allowed"
8141 " for import\n");
8142 rc = 1;
8143 goto meta_command_exit;
8145 sCtx.cColSep = p->colSeparator[0];
8146 sCtx.cRowSep = p->rowSeparator[0];
8148 sCtx.zFile = zFile;
8149 sCtx.nLine = 1;
8150 if( sCtx.zFile[0]=='|' ){
8151 #ifdef SQLITE_OMIT_POPEN
8152 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8153 rc = 1;
8154 goto meta_command_exit;
8155 #else
8156 sCtx.in = popen(sCtx.zFile+1, "r");
8157 sCtx.zFile = "<pipe>";
8158 sCtx.xCloser = pclose;
8159 #endif
8160 }else{
8161 sCtx.in = fopen(sCtx.zFile, "rb");
8162 sCtx.xCloser = fclose;
8164 if( sCtx.in==0 ){
8165 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8166 rc = 1;
8167 goto meta_command_exit;
8169 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8170 char zSep[2];
8171 zSep[1] = 0;
8172 zSep[0] = sCtx.cColSep;
8173 utf8_printf(p->out, "Column separator ");
8174 output_c_string(p->out, zSep);
8175 utf8_printf(p->out, ", row separator ");
8176 zSep[0] = sCtx.cRowSep;
8177 output_c_string(p->out, zSep);
8178 utf8_printf(p->out, "\n");
8180 while( (nSkip--)>0 ){
8181 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8183 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
8184 if( zSql==0 ){
8185 import_cleanup(&sCtx);
8186 shell_out_of_memory();
8188 nByte = strlen30(zSql);
8189 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8190 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
8191 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8192 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
8193 char cSep = '(';
8194 while( xRead(&sCtx) ){
8195 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
8196 cSep = ',';
8197 if( sCtx.cTerm!=sCtx.cColSep ) break;
8199 if( cSep=='(' ){
8200 sqlite3_free(zCreate);
8201 import_cleanup(&sCtx);
8202 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8203 rc = 1;
8204 goto meta_command_exit;
8206 zCreate = sqlite3_mprintf("%z\n)", zCreate);
8207 if( eVerbose>=1 ){
8208 utf8_printf(p->out, "%s\n", zCreate);
8210 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8211 sqlite3_free(zCreate);
8212 if( rc ){
8213 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
8214 sqlite3_errmsg(p->db));
8215 import_cleanup(&sCtx);
8216 rc = 1;
8217 goto meta_command_exit;
8219 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8221 sqlite3_free(zSql);
8222 if( rc ){
8223 if (pStmt) sqlite3_finalize(pStmt);
8224 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8225 import_cleanup(&sCtx);
8226 rc = 1;
8227 goto meta_command_exit;
8229 nCol = sqlite3_column_count(pStmt);
8230 sqlite3_finalize(pStmt);
8231 pStmt = 0;
8232 if( nCol==0 ) return 0; /* no columns, no error */
8233 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8234 if( zSql==0 ){
8235 import_cleanup(&sCtx);
8236 shell_out_of_memory();
8238 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
8239 j = strlen30(zSql);
8240 for(i=1; i<nCol; i++){
8241 zSql[j++] = ',';
8242 zSql[j++] = '?';
8244 zSql[j++] = ')';
8245 zSql[j] = 0;
8246 if( eVerbose>=2 ){
8247 utf8_printf(p->out, "Insert using: %s\n", zSql);
8249 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8250 sqlite3_free(zSql);
8251 if( rc ){
8252 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8253 if (pStmt) sqlite3_finalize(pStmt);
8254 import_cleanup(&sCtx);
8255 rc = 1;
8256 goto meta_command_exit;
8258 needCommit = sqlite3_get_autocommit(p->db);
8259 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8261 int startLine = sCtx.nLine;
8262 for(i=0; i<nCol; i++){
8263 char *z = xRead(&sCtx);
8265 ** Did we reach end-of-file before finding any columns?
8266 ** If so, stop instead of NULL filling the remaining columns.
8268 if( z==0 && i==0 ) break;
8270 ** Did we reach end-of-file OR end-of-line before finding any
8271 ** columns in ASCII mode? If so, stop instead of NULL filling
8272 ** the remaining columns.
8274 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8275 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8276 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8277 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8278 "filling the rest with NULL\n",
8279 sCtx.zFile, startLine, nCol, i+1);
8280 i += 2;
8281 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8284 if( sCtx.cTerm==sCtx.cColSep ){
8286 xRead(&sCtx);
8287 i++;
8288 }while( sCtx.cTerm==sCtx.cColSep );
8289 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8290 "extras ignored\n",
8291 sCtx.zFile, startLine, nCol, i);
8293 if( i>=nCol ){
8294 sqlite3_step(pStmt);
8295 rc = sqlite3_reset(pStmt);
8296 if( rc!=SQLITE_OK ){
8297 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8298 startLine, sqlite3_errmsg(p->db));
8299 sCtx.nErr++;
8300 }else{
8301 sCtx.nRow++;
8304 }while( sCtx.cTerm!=EOF );
8306 import_cleanup(&sCtx);
8307 sqlite3_finalize(pStmt);
8308 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8309 if( eVerbose>0 ){
8310 utf8_printf(p->out,
8311 "Added %d rows with %d errors using %d lines of input\n",
8312 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8314 }else
8316 #ifndef SQLITE_UNTESTABLE
8317 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8318 char *zSql;
8319 char *zCollist = 0;
8320 sqlite3_stmt *pStmt;
8321 int tnum = 0;
8322 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
8323 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8324 int i;
8325 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8326 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8327 " .imposter off\n");
8328 /* Also allowed, but not documented:
8330 ** .imposter TABLE IMPOSTER
8332 ** where TABLE is a WITHOUT ROWID table. In that case, the
8333 ** imposter is another WITHOUT ROWID table with the columns in
8334 ** storage order. */
8335 rc = 1;
8336 goto meta_command_exit;
8338 open_db(p, 0);
8339 if( nArg==2 ){
8340 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8341 goto meta_command_exit;
8343 zSql = sqlite3_mprintf(
8344 "SELECT rootpage, 0 FROM sqlite_schema"
8345 " WHERE name='%q' AND type='index'"
8346 "UNION ALL "
8347 "SELECT rootpage, 1 FROM sqlite_schema"
8348 " WHERE name='%q' AND type='table'"
8349 " AND sql LIKE '%%without%%rowid%%'",
8350 azArg[1], azArg[1]
8352 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8353 sqlite3_free(zSql);
8354 if( sqlite3_step(pStmt)==SQLITE_ROW ){
8355 tnum = sqlite3_column_int(pStmt, 0);
8356 isWO = sqlite3_column_int(pStmt, 1);
8358 sqlite3_finalize(pStmt);
8359 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8360 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8361 sqlite3_free(zSql);
8362 i = 0;
8363 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8364 char zLabel[20];
8365 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8366 i++;
8367 if( zCol==0 ){
8368 if( sqlite3_column_int(pStmt,1)==-1 ){
8369 zCol = "_ROWID_";
8370 }else{
8371 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8372 zCol = zLabel;
8375 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8376 lenPK = (int)strlen(zCollist);
8378 if( zCollist==0 ){
8379 zCollist = sqlite3_mprintf("\"%w\"", zCol);
8380 }else{
8381 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8384 sqlite3_finalize(pStmt);
8385 if( i==0 || tnum==0 ){
8386 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8387 rc = 1;
8388 sqlite3_free(zCollist);
8389 goto meta_command_exit;
8391 if( lenPK==0 ) lenPK = 100000;
8392 zSql = sqlite3_mprintf(
8393 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8394 azArg[2], zCollist, lenPK, zCollist);
8395 sqlite3_free(zCollist);
8396 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8397 if( rc==SQLITE_OK ){
8398 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8399 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8400 if( rc ){
8401 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8402 }else{
8403 utf8_printf(stdout, "%s;\n", zSql);
8404 raw_printf(stdout,
8405 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8406 azArg[1], isWO ? "table" : "index"
8409 }else{
8410 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8411 rc = 1;
8413 sqlite3_free(zSql);
8414 }else
8415 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8417 #ifdef SQLITE_ENABLE_IOTRACE
8418 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8419 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8420 if( iotrace && iotrace!=stdout ) fclose(iotrace);
8421 iotrace = 0;
8422 if( nArg<2 ){
8423 sqlite3IoTrace = 0;
8424 }else if( strcmp(azArg[1], "-")==0 ){
8425 sqlite3IoTrace = iotracePrintf;
8426 iotrace = stdout;
8427 }else{
8428 iotrace = fopen(azArg[1], "w");
8429 if( iotrace==0 ){
8430 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8431 sqlite3IoTrace = 0;
8432 rc = 1;
8433 }else{
8434 sqlite3IoTrace = iotracePrintf;
8437 }else
8438 #endif
8440 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8441 static const struct {
8442 const char *zLimitName; /* Name of a limit */
8443 int limitCode; /* Integer code for that limit */
8444 } aLimit[] = {
8445 { "length", SQLITE_LIMIT_LENGTH },
8446 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
8447 { "column", SQLITE_LIMIT_COLUMN },
8448 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
8449 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
8450 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
8451 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
8452 { "attached", SQLITE_LIMIT_ATTACHED },
8453 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
8454 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
8455 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
8456 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
8458 int i, n2;
8459 open_db(p, 0);
8460 if( nArg==1 ){
8461 for(i=0; i<ArraySize(aLimit); i++){
8462 printf("%20s %d\n", aLimit[i].zLimitName,
8463 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8465 }else if( nArg>3 ){
8466 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8467 rc = 1;
8468 goto meta_command_exit;
8469 }else{
8470 int iLimit = -1;
8471 n2 = strlen30(azArg[1]);
8472 for(i=0; i<ArraySize(aLimit); i++){
8473 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8474 if( iLimit<0 ){
8475 iLimit = i;
8476 }else{
8477 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8478 rc = 1;
8479 goto meta_command_exit;
8483 if( iLimit<0 ){
8484 utf8_printf(stderr, "unknown limit: \"%s\"\n"
8485 "enter \".limits\" with no arguments for a list.\n",
8486 azArg[1]);
8487 rc = 1;
8488 goto meta_command_exit;
8490 if( nArg==3 ){
8491 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8492 (int)integerValue(azArg[2]));
8494 printf("%20s %d\n", aLimit[iLimit].zLimitName,
8495 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8497 }else
8499 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8500 open_db(p, 0);
8501 lintDotCommand(p, azArg, nArg);
8502 }else
8504 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8505 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8506 const char *zFile, *zProc;
8507 char *zErrMsg = 0;
8508 if( nArg<2 ){
8509 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8510 rc = 1;
8511 goto meta_command_exit;
8513 zFile = azArg[1];
8514 zProc = nArg>=3 ? azArg[2] : 0;
8515 open_db(p, 0);
8516 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8517 if( rc!=SQLITE_OK ){
8518 utf8_printf(stderr, "Error: %s\n", zErrMsg);
8519 sqlite3_free(zErrMsg);
8520 rc = 1;
8522 }else
8523 #endif
8525 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8526 if( nArg!=2 ){
8527 raw_printf(stderr, "Usage: .log FILENAME\n");
8528 rc = 1;
8529 }else{
8530 const char *zFile = azArg[1];
8531 output_file_close(p->pLog);
8532 p->pLog = output_file_open(zFile, 0);
8534 }else
8536 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8537 const char *zMode = nArg>=2 ? azArg[1] : "";
8538 int n2 = strlen30(zMode);
8539 int c2 = zMode[0];
8540 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8541 p->mode = MODE_Line;
8542 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8543 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8544 p->mode = MODE_Column;
8545 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8546 p->showHeader = 1;
8548 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8549 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8550 p->mode = MODE_List;
8551 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8552 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8553 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8554 p->mode = MODE_Html;
8555 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8556 p->mode = MODE_Tcl;
8557 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8558 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8559 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8560 p->mode = MODE_Csv;
8561 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8562 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8563 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8564 p->mode = MODE_List;
8565 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8566 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8567 p->mode = MODE_Insert;
8568 set_table_name(p, nArg>=3 ? azArg[2] : "table");
8569 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8570 p->mode = MODE_Quote;
8571 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8572 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8573 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8574 p->mode = MODE_Ascii;
8575 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8576 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8577 }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
8578 p->mode = MODE_Markdown;
8579 }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
8580 p->mode = MODE_Table;
8581 }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
8582 p->mode = MODE_Box;
8583 }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
8584 p->mode = MODE_Json;
8585 }else if( nArg==1 ){
8586 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8587 }else{
8588 raw_printf(stderr, "Error: mode should be one of: "
8589 "ascii box column csv html insert json line list markdown "
8590 "quote table tabs tcl\n");
8591 rc = 1;
8593 p->cMode = p->mode;
8594 }else
8596 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8597 if( nArg==2 ){
8598 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8599 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8600 }else{
8601 raw_printf(stderr, "Usage: .nullvalue STRING\n");
8602 rc = 1;
8604 }else
8606 #ifdef SQLITE_DEBUG
8607 if( c=='o' && strcmp(azArg[0],"oom")==0 ){
8608 int i;
8609 for(i=1; i<nArg; i++){
8610 const char *z = azArg[i];
8611 if( z[0]=='-' && z[1]=='-' ) z++;
8612 if( strcmp(z,"-repeat")==0 ){
8613 if( i==nArg-1 ){
8614 raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
8615 rc = 1;
8616 }else{
8617 oomRepeat = (int)integerValue(azArg[++i]);
8619 }else if( IsDigit(z[0]) ){
8620 oomCounter = (int)integerValue(azArg[i]);
8621 }else{
8622 raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
8623 raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
8624 rc = 1;
8627 if( rc==0 ){
8628 raw_printf(p->out, "oomCounter = %d\n", oomCounter);
8629 raw_printf(p->out, "oomRepeat = %d\n", oomRepeat);
8631 }else
8632 #endif /* SQLITE_DEBUG */
8634 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8635 char *zNewFilename; /* Name of the database file to open */
8636 int iName = 1; /* Index in azArg[] of the filename */
8637 int newFlag = 0; /* True to delete file before opening */
8638 /* Close the existing database */
8639 session_close_all(p);
8640 close_db(p->db);
8641 p->db = 0;
8642 p->zDbFilename = 0;
8643 sqlite3_free(p->zFreeOnClose);
8644 p->zFreeOnClose = 0;
8645 p->openMode = SHELL_OPEN_UNSPEC;
8646 p->openFlags = 0;
8647 p->szMax = 0;
8648 /* Check for command-line arguments */
8649 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
8650 const char *z = azArg[iName];
8651 if( optionMatch(z,"new") ){
8652 newFlag = 1;
8653 #ifdef SQLITE_HAVE_ZLIB
8654 }else if( optionMatch(z, "zip") ){
8655 p->openMode = SHELL_OPEN_ZIPFILE;
8656 #endif
8657 }else if( optionMatch(z, "append") ){
8658 p->openMode = SHELL_OPEN_APPENDVFS;
8659 }else if( optionMatch(z, "readonly") ){
8660 p->openMode = SHELL_OPEN_READONLY;
8661 }else if( optionMatch(z, "nofollow") ){
8662 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
8663 #ifdef SQLITE_ENABLE_DESERIALIZE
8664 }else if( optionMatch(z, "deserialize") ){
8665 p->openMode = SHELL_OPEN_DESERIALIZE;
8666 }else if( optionMatch(z, "hexdb") ){
8667 p->openMode = SHELL_OPEN_HEXDB;
8668 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
8669 p->szMax = integerValue(azArg[++iName]);
8670 #endif /* SQLITE_ENABLE_DESERIALIZE */
8671 }else if( z[0]=='-' ){
8672 utf8_printf(stderr, "unknown option: %s\n", z);
8673 rc = 1;
8674 goto meta_command_exit;
8677 /* If a filename is specified, try to open it first */
8678 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
8679 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
8680 if( newFlag ) shellDeleteFile(zNewFilename);
8681 p->zDbFilename = zNewFilename;
8682 open_db(p, OPEN_DB_KEEPALIVE);
8683 if( p->db==0 ){
8684 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
8685 sqlite3_free(zNewFilename);
8686 }else{
8687 p->zFreeOnClose = zNewFilename;
8690 if( p->db==0 ){
8691 /* As a fall-back open a TEMP database */
8692 p->zDbFilename = 0;
8693 open_db(p, 0);
8695 }else
8697 if( (c=='o'
8698 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
8699 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
8701 const char *zFile = 0;
8702 int bTxtMode = 0;
8703 int i;
8704 int eMode = 0;
8705 int bBOM = 0;
8706 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
8708 if( c=='e' ){
8709 eMode = 'x';
8710 bOnce = 2;
8711 }else if( strncmp(azArg[0],"once",n)==0 ){
8712 bOnce = 1;
8714 for(i=1; i<nArg; i++){
8715 char *z = azArg[i];
8716 if( z[0]=='-' ){
8717 if( z[1]=='-' ) z++;
8718 if( strcmp(z,"-bom")==0 ){
8719 bBOM = 1;
8720 }else if( c!='e' && strcmp(z,"-x")==0 ){
8721 eMode = 'x'; /* spreadsheet */
8722 }else if( c!='e' && strcmp(z,"-e")==0 ){
8723 eMode = 'e'; /* text editor */
8724 }else{
8725 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
8726 azArg[i]);
8727 showHelp(p->out, azArg[0]);
8728 rc = 1;
8729 goto meta_command_exit;
8731 }else if( zFile==0 ){
8732 zFile = z;
8733 }else{
8734 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
8735 azArg[i]);
8736 showHelp(p->out, azArg[0]);
8737 rc = 1;
8738 goto meta_command_exit;
8741 if( zFile==0 ) zFile = "stdout";
8742 if( bOnce ){
8743 p->outCount = 2;
8744 }else{
8745 p->outCount = 0;
8747 output_reset(p);
8748 #ifndef SQLITE_NOHAVE_SYSTEM
8749 if( eMode=='e' || eMode=='x' ){
8750 p->doXdgOpen = 1;
8751 outputModePush(p);
8752 if( eMode=='x' ){
8753 /* spreadsheet mode. Output as CSV. */
8754 newTempFile(p, "csv");
8755 ShellClearFlag(p, SHFLG_Echo);
8756 p->mode = MODE_Csv;
8757 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8758 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8759 }else{
8760 /* text editor mode */
8761 newTempFile(p, "txt");
8762 bTxtMode = 1;
8764 zFile = p->zTempFile;
8766 #endif /* SQLITE_NOHAVE_SYSTEM */
8767 if( zFile[0]=='|' ){
8768 #ifdef SQLITE_OMIT_POPEN
8769 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8770 rc = 1;
8771 p->out = stdout;
8772 #else
8773 p->out = popen(zFile + 1, "w");
8774 if( p->out==0 ){
8775 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
8776 p->out = stdout;
8777 rc = 1;
8778 }else{
8779 if( bBOM ) fprintf(p->out,"\357\273\277");
8780 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8782 #endif
8783 }else{
8784 p->out = output_file_open(zFile, bTxtMode);
8785 if( p->out==0 ){
8786 if( strcmp(zFile,"off")!=0 ){
8787 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
8789 p->out = stdout;
8790 rc = 1;
8791 } else {
8792 if( bBOM ) fprintf(p->out,"\357\273\277");
8793 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8796 }else
8798 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
8799 open_db(p,0);
8800 if( nArg<=1 ) goto parameter_syntax_error;
8802 /* .parameter clear
8803 ** Clear all bind parameters by dropping the TEMP table that holds them.
8805 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
8806 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
8807 0, 0, 0);
8808 }else
8810 /* .parameter list
8811 ** List all bind parameters.
8813 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
8814 sqlite3_stmt *pStmt = 0;
8815 int rx;
8816 int len = 0;
8817 rx = sqlite3_prepare_v2(p->db,
8818 "SELECT max(length(key)) "
8819 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8820 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8821 len = sqlite3_column_int(pStmt, 0);
8822 if( len>40 ) len = 40;
8824 sqlite3_finalize(pStmt);
8825 pStmt = 0;
8826 if( len ){
8827 rx = sqlite3_prepare_v2(p->db,
8828 "SELECT key, quote(value) "
8829 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8830 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8831 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
8832 sqlite3_column_text(pStmt,1));
8834 sqlite3_finalize(pStmt);
8836 }else
8838 /* .parameter init
8839 ** Make sure the TEMP table used to hold bind parameters exists.
8840 ** Create it if necessary.
8842 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
8843 bind_table_init(p);
8844 }else
8846 /* .parameter set NAME VALUE
8847 ** Set or reset a bind parameter. NAME should be the full parameter
8848 ** name exactly as it appears in the query. (ex: $abc, @def). The
8849 ** VALUE can be in either SQL literal notation, or if not it will be
8850 ** understood to be a text string.
8852 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
8853 int rx;
8854 char *zSql;
8855 sqlite3_stmt *pStmt;
8856 const char *zKey = azArg[2];
8857 const char *zValue = azArg[3];
8858 bind_table_init(p);
8859 zSql = sqlite3_mprintf(
8860 "REPLACE INTO temp.sqlite_parameters(key,value)"
8861 "VALUES(%Q,%s);", zKey, zValue);
8862 if( zSql==0 ) shell_out_of_memory();
8863 pStmt = 0;
8864 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8865 sqlite3_free(zSql);
8866 if( rx!=SQLITE_OK ){
8867 sqlite3_finalize(pStmt);
8868 pStmt = 0;
8869 zSql = sqlite3_mprintf(
8870 "REPLACE INTO temp.sqlite_parameters(key,value)"
8871 "VALUES(%Q,%Q);", zKey, zValue);
8872 if( zSql==0 ) shell_out_of_memory();
8873 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8874 sqlite3_free(zSql);
8875 if( rx!=SQLITE_OK ){
8876 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
8877 sqlite3_finalize(pStmt);
8878 pStmt = 0;
8879 rc = 1;
8882 sqlite3_step(pStmt);
8883 sqlite3_finalize(pStmt);
8884 }else
8886 /* .parameter unset NAME
8887 ** Remove the NAME binding from the parameter binding table, if it
8888 ** exists.
8890 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
8891 char *zSql = sqlite3_mprintf(
8892 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
8893 if( zSql==0 ) shell_out_of_memory();
8894 sqlite3_exec(p->db, zSql, 0, 0, 0);
8895 sqlite3_free(zSql);
8896 }else
8897 /* If no command name matches, show a syntax error */
8898 parameter_syntax_error:
8899 showHelp(p->out, "parameter");
8900 }else
8902 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
8903 int i;
8904 for(i=1; i<nArg; i++){
8905 if( i>1 ) raw_printf(p->out, " ");
8906 utf8_printf(p->out, "%s", azArg[i]);
8908 raw_printf(p->out, "\n");
8909 }else
8911 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8912 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
8913 int i;
8914 int nn = 0;
8915 p->flgProgress = 0;
8916 p->mxProgress = 0;
8917 p->nProgress = 0;
8918 for(i=1; i<nArg; i++){
8919 const char *z = azArg[i];
8920 if( z[0]=='-' ){
8921 z++;
8922 if( z[0]=='-' ) z++;
8923 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
8924 p->flgProgress |= SHELL_PROGRESS_QUIET;
8925 continue;
8927 if( strcmp(z,"reset")==0 ){
8928 p->flgProgress |= SHELL_PROGRESS_RESET;
8929 continue;
8931 if( strcmp(z,"once")==0 ){
8932 p->flgProgress |= SHELL_PROGRESS_ONCE;
8933 continue;
8935 if( strcmp(z,"limit")==0 ){
8936 if( i+1>=nArg ){
8937 utf8_printf(stderr, "Error: missing argument on --limit\n");
8938 rc = 1;
8939 goto meta_command_exit;
8940 }else{
8941 p->mxProgress = (int)integerValue(azArg[++i]);
8943 continue;
8945 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
8946 rc = 1;
8947 goto meta_command_exit;
8948 }else{
8949 nn = (int)integerValue(z);
8952 open_db(p, 0);
8953 sqlite3_progress_handler(p->db, nn, progress_handler, p);
8954 }else
8955 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
8957 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
8958 if( nArg >= 2) {
8959 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
8961 if( nArg >= 3) {
8962 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
8964 }else
8966 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
8967 rc = 2;
8968 }else
8970 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
8971 FILE *inSaved = p->in;
8972 int savedLineno = p->lineno;
8973 if( nArg!=2 ){
8974 raw_printf(stderr, "Usage: .read FILE\n");
8975 rc = 1;
8976 goto meta_command_exit;
8978 if( notNormalFile(azArg[1])
8979 || (p->in = fopen(azArg[1], "rb"))==0
8981 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
8982 rc = 1;
8983 }else{
8984 rc = process_input(p);
8985 fclose(p->in);
8987 p->in = inSaved;
8988 p->lineno = savedLineno;
8989 }else
8991 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
8992 const char *zSrcFile;
8993 const char *zDb;
8994 sqlite3 *pSrc;
8995 sqlite3_backup *pBackup;
8996 int nTimeout = 0;
8998 if( nArg==2 ){
8999 zSrcFile = azArg[1];
9000 zDb = "main";
9001 }else if( nArg==3 ){
9002 zSrcFile = azArg[2];
9003 zDb = azArg[1];
9004 }else{
9005 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9006 rc = 1;
9007 goto meta_command_exit;
9009 rc = sqlite3_open(zSrcFile, &pSrc);
9010 if( rc!=SQLITE_OK ){
9011 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9012 close_db(pSrc);
9013 return 1;
9015 open_db(p, 0);
9016 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9017 if( pBackup==0 ){
9018 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9019 close_db(pSrc);
9020 return 1;
9022 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9023 || rc==SQLITE_BUSY ){
9024 if( rc==SQLITE_BUSY ){
9025 if( nTimeout++ >= 3 ) break;
9026 sqlite3_sleep(100);
9029 sqlite3_backup_finish(pBackup);
9030 if( rc==SQLITE_DONE ){
9031 rc = 0;
9032 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9033 raw_printf(stderr, "Error: source database is busy\n");
9034 rc = 1;
9035 }else{
9036 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9037 rc = 1;
9039 close_db(pSrc);
9040 }else
9042 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9043 if( nArg==2 ){
9044 p->scanstatsOn = (u8)booleanValue(azArg[1]);
9045 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9046 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9047 #endif
9048 }else{
9049 raw_printf(stderr, "Usage: .scanstats on|off\n");
9050 rc = 1;
9052 }else
9054 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9055 ShellText sSelect;
9056 ShellState data;
9057 char *zErrMsg = 0;
9058 const char *zDiv = "(";
9059 const char *zName = 0;
9060 int iSchema = 0;
9061 int bDebug = 0;
9062 int ii;
9064 open_db(p, 0);
9065 memcpy(&data, p, sizeof(data));
9066 data.showHeader = 0;
9067 data.cMode = data.mode = MODE_Semi;
9068 initText(&sSelect);
9069 for(ii=1; ii<nArg; ii++){
9070 if( optionMatch(azArg[ii],"indent") ){
9071 data.cMode = data.mode = MODE_Pretty;
9072 }else if( optionMatch(azArg[ii],"debug") ){
9073 bDebug = 1;
9074 }else if( zName==0 ){
9075 zName = azArg[ii];
9076 }else{
9077 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
9078 rc = 1;
9079 goto meta_command_exit;
9082 if( zName!=0 ){
9083 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9084 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9085 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9086 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9087 if( isSchema ){
9088 char *new_argv[2], *new_colv[2];
9089 new_argv[0] = sqlite3_mprintf(
9090 "CREATE TABLE %s (\n"
9091 " type text,\n"
9092 " name text,\n"
9093 " tbl_name text,\n"
9094 " rootpage integer,\n"
9095 " sql text\n"
9096 ")", zName);
9097 new_argv[1] = 0;
9098 new_colv[0] = "sql";
9099 new_colv[1] = 0;
9100 callback(&data, 1, new_argv, new_colv);
9101 sqlite3_free(new_argv[0]);
9104 if( zDiv ){
9105 sqlite3_stmt *pStmt = 0;
9106 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9107 -1, &pStmt, 0);
9108 if( rc ){
9109 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9110 sqlite3_finalize(pStmt);
9111 rc = 1;
9112 goto meta_command_exit;
9114 appendText(&sSelect, "SELECT sql FROM", 0);
9115 iSchema = 0;
9116 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9117 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9118 char zScNum[30];
9119 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9120 appendText(&sSelect, zDiv, 0);
9121 zDiv = " UNION ALL ";
9122 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9123 if( sqlite3_stricmp(zDb, "main")!=0 ){
9124 appendText(&sSelect, zDb, '\'');
9125 }else{
9126 appendText(&sSelect, "NULL", 0);
9128 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9129 appendText(&sSelect, zScNum, 0);
9130 appendText(&sSelect, " AS snum, ", 0);
9131 appendText(&sSelect, zDb, '\'');
9132 appendText(&sSelect, " AS sname FROM ", 0);
9133 appendText(&sSelect, zDb, quoteChar(zDb));
9134 appendText(&sSelect, ".sqlite_schema", 0);
9136 sqlite3_finalize(pStmt);
9137 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9138 if( zName ){
9139 appendText(&sSelect,
9140 " UNION ALL SELECT shell_module_schema(name),"
9141 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9144 #endif
9145 appendText(&sSelect, ") WHERE ", 0);
9146 if( zName ){
9147 char *zQarg = sqlite3_mprintf("%Q", zName);
9148 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9149 strchr(zName, '[') != 0;
9150 if( strchr(zName, '.') ){
9151 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9152 }else{
9153 appendText(&sSelect, "lower(tbl_name)", 0);
9155 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9156 appendText(&sSelect, zQarg, 0);
9157 if( !bGlob ){
9158 appendText(&sSelect, " ESCAPE '\\' ", 0);
9160 appendText(&sSelect, " AND ", 0);
9161 sqlite3_free(zQarg);
9163 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
9164 " ORDER BY snum, rowid", 0);
9165 if( bDebug ){
9166 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9167 }else{
9168 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9170 freeText(&sSelect);
9172 if( zErrMsg ){
9173 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9174 sqlite3_free(zErrMsg);
9175 rc = 1;
9176 }else if( rc != SQLITE_OK ){
9177 raw_printf(stderr,"Error: querying schema information\n");
9178 rc = 1;
9179 }else{
9180 rc = 0;
9182 }else
9184 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
9185 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9186 sqlite3_unsupported_selecttrace = nArg>=2 ? (int)integerValue(azArg[1]) : 0xffff;
9187 }else
9188 #endif
9190 #if defined(SQLITE_ENABLE_SESSION)
9191 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9192 OpenSession *pSession = &p->aSession[0];
9193 char **azCmd = &azArg[1];
9194 int iSes = 0;
9195 int nCmd = nArg - 1;
9196 int i;
9197 if( nArg<=1 ) goto session_syntax_error;
9198 open_db(p, 0);
9199 if( nArg>=3 ){
9200 for(iSes=0; iSes<p->nSession; iSes++){
9201 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
9203 if( iSes<p->nSession ){
9204 pSession = &p->aSession[iSes];
9205 azCmd++;
9206 nCmd--;
9207 }else{
9208 pSession = &p->aSession[0];
9209 iSes = 0;
9213 /* .session attach TABLE
9214 ** Invoke the sqlite3session_attach() interface to attach a particular
9215 ** table so that it is never filtered.
9217 if( strcmp(azCmd[0],"attach")==0 ){
9218 if( nCmd!=2 ) goto session_syntax_error;
9219 if( pSession->p==0 ){
9220 session_not_open:
9221 raw_printf(stderr, "ERROR: No sessions are open\n");
9222 }else{
9223 rc = sqlite3session_attach(pSession->p, azCmd[1]);
9224 if( rc ){
9225 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9226 rc = 0;
9229 }else
9231 /* .session changeset FILE
9232 ** .session patchset FILE
9233 ** Write a changeset or patchset into a file. The file is overwritten.
9235 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9236 FILE *out = 0;
9237 if( nCmd!=2 ) goto session_syntax_error;
9238 if( pSession->p==0 ) goto session_not_open;
9239 out = fopen(azCmd[1], "wb");
9240 if( out==0 ){
9241 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9242 azCmd[1]);
9243 }else{
9244 int szChng;
9245 void *pChng;
9246 if( azCmd[0][0]=='c' ){
9247 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9248 }else{
9249 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9251 if( rc ){
9252 printf("Error: error code %d\n", rc);
9253 rc = 0;
9255 if( pChng
9256 && fwrite(pChng, szChng, 1, out)!=1 ){
9257 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9258 szChng);
9260 sqlite3_free(pChng);
9261 fclose(out);
9263 }else
9265 /* .session close
9266 ** Close the identified session
9268 if( strcmp(azCmd[0], "close")==0 ){
9269 if( nCmd!=1 ) goto session_syntax_error;
9270 if( p->nSession ){
9271 session_close(pSession);
9272 p->aSession[iSes] = p->aSession[--p->nSession];
9274 }else
9276 /* .session enable ?BOOLEAN?
9277 ** Query or set the enable flag
9279 if( strcmp(azCmd[0], "enable")==0 ){
9280 int ii;
9281 if( nCmd>2 ) goto session_syntax_error;
9282 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9283 if( p->nSession ){
9284 ii = sqlite3session_enable(pSession->p, ii);
9285 utf8_printf(p->out, "session %s enable flag = %d\n",
9286 pSession->zName, ii);
9288 }else
9290 /* .session filter GLOB ....
9291 ** Set a list of GLOB patterns of table names to be excluded.
9293 if( strcmp(azCmd[0], "filter")==0 ){
9294 int ii, nByte;
9295 if( nCmd<2 ) goto session_syntax_error;
9296 if( p->nSession ){
9297 for(ii=0; ii<pSession->nFilter; ii++){
9298 sqlite3_free(pSession->azFilter[ii]);
9300 sqlite3_free(pSession->azFilter);
9301 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9302 pSession->azFilter = sqlite3_malloc( nByte );
9303 if( pSession->azFilter==0 ){
9304 raw_printf(stderr, "Error: out or memory\n");
9305 exit(1);
9307 for(ii=1; ii<nCmd; ii++){
9308 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9310 pSession->nFilter = ii-1;
9312 }else
9314 /* .session indirect ?BOOLEAN?
9315 ** Query or set the indirect flag
9317 if( strcmp(azCmd[0], "indirect")==0 ){
9318 int ii;
9319 if( nCmd>2 ) goto session_syntax_error;
9320 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9321 if( p->nSession ){
9322 ii = sqlite3session_indirect(pSession->p, ii);
9323 utf8_printf(p->out, "session %s indirect flag = %d\n",
9324 pSession->zName, ii);
9326 }else
9328 /* .session isempty
9329 ** Determine if the session is empty
9331 if( strcmp(azCmd[0], "isempty")==0 ){
9332 int ii;
9333 if( nCmd!=1 ) goto session_syntax_error;
9334 if( p->nSession ){
9335 ii = sqlite3session_isempty(pSession->p);
9336 utf8_printf(p->out, "session %s isempty flag = %d\n",
9337 pSession->zName, ii);
9339 }else
9341 /* .session list
9342 ** List all currently open sessions
9344 if( strcmp(azCmd[0],"list")==0 ){
9345 for(i=0; i<p->nSession; i++){
9346 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
9348 }else
9350 /* .session open DB NAME
9351 ** Open a new session called NAME on the attached database DB.
9352 ** DB is normally "main".
9354 if( strcmp(azCmd[0],"open")==0 ){
9355 char *zName;
9356 if( nCmd!=3 ) goto session_syntax_error;
9357 zName = azCmd[2];
9358 if( zName[0]==0 ) goto session_syntax_error;
9359 for(i=0; i<p->nSession; i++){
9360 if( strcmp(p->aSession[i].zName,zName)==0 ){
9361 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9362 goto meta_command_exit;
9365 if( p->nSession>=ArraySize(p->aSession) ){
9366 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
9367 goto meta_command_exit;
9369 pSession = &p->aSession[p->nSession];
9370 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9371 if( rc ){
9372 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9373 rc = 0;
9374 goto meta_command_exit;
9376 pSession->nFilter = 0;
9377 sqlite3session_table_filter(pSession->p, session_filter, pSession);
9378 p->nSession++;
9379 pSession->zName = sqlite3_mprintf("%s", zName);
9380 }else
9381 /* If no command name matches, show a syntax error */
9382 session_syntax_error:
9383 showHelp(p->out, "session");
9384 }else
9385 #endif
9387 #ifdef SQLITE_DEBUG
9388 /* Undocumented commands for internal testing. Subject to change
9389 ** without notice. */
9390 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9391 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9392 int i, v;
9393 for(i=1; i<nArg; i++){
9394 v = booleanValue(azArg[i]);
9395 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9398 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9399 int i; sqlite3_int64 v;
9400 for(i=1; i<nArg; i++){
9401 char zBuf[200];
9402 v = integerValue(azArg[i]);
9403 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9404 utf8_printf(p->out, "%s", zBuf);
9407 }else
9408 #endif
9410 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9411 int bIsInit = 0; /* True to initialize the SELFTEST table */
9412 int bVerbose = 0; /* Verbose output */
9413 int bSelftestExists; /* True if SELFTEST already exists */
9414 int i, k; /* Loop counters */
9415 int nTest = 0; /* Number of tests runs */
9416 int nErr = 0; /* Number of errors seen */
9417 ShellText str; /* Answer for a query */
9418 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9420 open_db(p,0);
9421 for(i=1; i<nArg; i++){
9422 const char *z = azArg[i];
9423 if( z[0]=='-' && z[1]=='-' ) z++;
9424 if( strcmp(z,"-init")==0 ){
9425 bIsInit = 1;
9426 }else
9427 if( strcmp(z,"-v")==0 ){
9428 bVerbose++;
9429 }else
9431 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9432 azArg[i], azArg[0]);
9433 raw_printf(stderr, "Should be one of: --init -v\n");
9434 rc = 1;
9435 goto meta_command_exit;
9438 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9439 != SQLITE_OK ){
9440 bSelftestExists = 0;
9441 }else{
9442 bSelftestExists = 1;
9444 if( bIsInit ){
9445 createSelftestTable(p);
9446 bSelftestExists = 1;
9448 initText(&str);
9449 appendText(&str, "x", 0);
9450 for(k=bSelftestExists; k>=0; k--){
9451 if( k==1 ){
9452 rc = sqlite3_prepare_v2(p->db,
9453 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9454 -1, &pStmt, 0);
9455 }else{
9456 rc = sqlite3_prepare_v2(p->db,
9457 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9458 " (1,'run','PRAGMA integrity_check','ok')",
9459 -1, &pStmt, 0);
9461 if( rc ){
9462 raw_printf(stderr, "Error querying the selftest table\n");
9463 rc = 1;
9464 sqlite3_finalize(pStmt);
9465 goto meta_command_exit;
9467 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9468 int tno = sqlite3_column_int(pStmt, 0);
9469 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9470 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9471 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9473 k = 0;
9474 if( bVerbose>0 ){
9475 char *zQuote = sqlite3_mprintf("%q", zSql);
9476 printf("%d: %s %s\n", tno, zOp, zSql);
9477 sqlite3_free(zQuote);
9479 if( strcmp(zOp,"memo")==0 ){
9480 utf8_printf(p->out, "%s\n", zSql);
9481 }else
9482 if( strcmp(zOp,"run")==0 ){
9483 char *zErrMsg = 0;
9484 str.n = 0;
9485 str.z[0] = 0;
9486 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9487 nTest++;
9488 if( bVerbose ){
9489 utf8_printf(p->out, "Result: %s\n", str.z);
9491 if( rc || zErrMsg ){
9492 nErr++;
9493 rc = 1;
9494 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9495 sqlite3_free(zErrMsg);
9496 }else if( strcmp(zAns,str.z)!=0 ){
9497 nErr++;
9498 rc = 1;
9499 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9500 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
9502 }else
9504 utf8_printf(stderr,
9505 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9506 rc = 1;
9507 break;
9509 } /* End loop over rows of content from SELFTEST */
9510 sqlite3_finalize(pStmt);
9511 } /* End loop over k */
9512 freeText(&str);
9513 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9514 }else
9516 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9517 if( nArg<2 || nArg>3 ){
9518 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9519 rc = 1;
9521 if( nArg>=2 ){
9522 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9523 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9525 if( nArg>=3 ){
9526 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9527 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9529 }else
9531 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9532 const char *zLike = 0; /* Which table to checksum. 0 means everything */
9533 int i; /* Loop counter */
9534 int bSchema = 0; /* Also hash the schema */
9535 int bSeparate = 0; /* Hash each table separately */
9536 int iSize = 224; /* Hash algorithm to use */
9537 int bDebug = 0; /* Only show the query that would have run */
9538 sqlite3_stmt *pStmt; /* For querying tables names */
9539 char *zSql; /* SQL to be run */
9540 char *zSep; /* Separator */
9541 ShellText sSql; /* Complete SQL for the query to run the hash */
9542 ShellText sQuery; /* Set of queries used to read all content */
9543 open_db(p, 0);
9544 for(i=1; i<nArg; i++){
9545 const char *z = azArg[i];
9546 if( z[0]=='-' ){
9547 z++;
9548 if( z[0]=='-' ) z++;
9549 if( strcmp(z,"schema")==0 ){
9550 bSchema = 1;
9551 }else
9552 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9553 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9555 iSize = atoi(&z[5]);
9556 }else
9557 if( strcmp(z,"debug")==0 ){
9558 bDebug = 1;
9559 }else
9561 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9562 azArg[i], azArg[0]);
9563 showHelp(p->out, azArg[0]);
9564 rc = 1;
9565 goto meta_command_exit;
9567 }else if( zLike ){
9568 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9569 rc = 1;
9570 goto meta_command_exit;
9571 }else{
9572 zLike = z;
9573 bSeparate = 1;
9574 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9577 if( bSchema ){
9578 zSql = "SELECT lower(name) FROM sqlite_schema"
9579 " WHERE type='table' AND coalesce(rootpage,0)>1"
9580 " UNION ALL SELECT 'sqlite_schema'"
9581 " ORDER BY 1 collate nocase";
9582 }else{
9583 zSql = "SELECT lower(name) FROM sqlite_schema"
9584 " WHERE type='table' AND coalesce(rootpage,0)>1"
9585 " AND name NOT LIKE 'sqlite_%'"
9586 " ORDER BY 1 collate nocase";
9588 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9589 initText(&sQuery);
9590 initText(&sSql);
9591 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
9592 zSep = "VALUES(";
9593 while( SQLITE_ROW==sqlite3_step(pStmt) ){
9594 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
9595 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
9596 if( strncmp(zTab, "sqlite_",7)!=0 ){
9597 appendText(&sQuery,"SELECT * FROM ", 0);
9598 appendText(&sQuery,zTab,'"');
9599 appendText(&sQuery," NOT INDEXED;", 0);
9600 }else if( strcmp(zTab, "sqlite_schema")==0 ){
9601 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
9602 " ORDER BY name;", 0);
9603 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
9604 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
9605 " ORDER BY name;", 0);
9606 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
9607 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
9608 " ORDER BY tbl,idx;", 0);
9609 }else if( strcmp(zTab, "sqlite_stat4")==0 ){
9610 appendText(&sQuery, "SELECT * FROM ", 0);
9611 appendText(&sQuery, zTab, 0);
9612 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
9614 appendText(&sSql, zSep, 0);
9615 appendText(&sSql, sQuery.z, '\'');
9616 sQuery.n = 0;
9617 appendText(&sSql, ",", 0);
9618 appendText(&sSql, zTab, '\'');
9619 zSep = "),(";
9621 sqlite3_finalize(pStmt);
9622 if( bSeparate ){
9623 zSql = sqlite3_mprintf(
9624 "%s))"
9625 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
9626 " FROM [sha3sum$query]",
9627 sSql.z, iSize);
9628 }else{
9629 zSql = sqlite3_mprintf(
9630 "%s))"
9631 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
9632 " FROM [sha3sum$query]",
9633 sSql.z, iSize);
9635 freeText(&sQuery);
9636 freeText(&sSql);
9637 if( bDebug ){
9638 utf8_printf(p->out, "%s\n", zSql);
9639 }else{
9640 shell_exec(p, zSql, 0);
9642 sqlite3_free(zSql);
9643 }else
9645 #ifndef SQLITE_NOHAVE_SYSTEM
9646 if( c=='s'
9647 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
9649 char *zCmd;
9650 int i, x;
9651 if( nArg<2 ){
9652 raw_printf(stderr, "Usage: .system COMMAND\n");
9653 rc = 1;
9654 goto meta_command_exit;
9656 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
9657 for(i=2; i<nArg; i++){
9658 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
9659 zCmd, azArg[i]);
9661 x = system(zCmd);
9662 sqlite3_free(zCmd);
9663 if( x ) raw_printf(stderr, "System command returns %d\n", x);
9664 }else
9665 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
9667 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
9668 static const char *azBool[] = { "off", "on", "trigger", "full"};
9669 int i;
9670 if( nArg!=1 ){
9671 raw_printf(stderr, "Usage: .show\n");
9672 rc = 1;
9673 goto meta_command_exit;
9675 utf8_printf(p->out, "%12.12s: %s\n","echo",
9676 azBool[ShellHasFlag(p, SHFLG_Echo)]);
9677 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
9678 utf8_printf(p->out, "%12.12s: %s\n","explain",
9679 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
9680 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
9681 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
9682 utf8_printf(p->out, "%12.12s: ", "nullvalue");
9683 output_c_string(p->out, p->nullValue);
9684 raw_printf(p->out, "\n");
9685 utf8_printf(p->out,"%12.12s: %s\n","output",
9686 strlen30(p->outfile) ? p->outfile : "stdout");
9687 utf8_printf(p->out,"%12.12s: ", "colseparator");
9688 output_c_string(p->out, p->colSeparator);
9689 raw_printf(p->out, "\n");
9690 utf8_printf(p->out,"%12.12s: ", "rowseparator");
9691 output_c_string(p->out, p->rowSeparator);
9692 raw_printf(p->out, "\n");
9693 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
9694 utf8_printf(p->out, "%12.12s: ", "width");
9695 for (i=0;i<p->nWidth;i++) {
9696 raw_printf(p->out, "%d ", p->colWidth[i]);
9698 raw_printf(p->out, "\n");
9699 utf8_printf(p->out, "%12.12s: %s\n", "filename",
9700 p->zDbFilename ? p->zDbFilename : "");
9701 }else
9703 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
9704 if( nArg==2 ){
9705 p->statsOn = (u8)booleanValue(azArg[1]);
9706 }else if( nArg==1 ){
9707 display_stats(p->db, p, 0);
9708 }else{
9709 raw_printf(stderr, "Usage: .stats ?on|off?\n");
9710 rc = 1;
9712 }else
9714 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
9715 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
9716 || strncmp(azArg[0], "indexes", n)==0) )
9718 sqlite3_stmt *pStmt;
9719 char **azResult;
9720 int nRow, nAlloc;
9721 int ii;
9722 ShellText s;
9723 initText(&s);
9724 open_db(p, 0);
9725 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
9726 if( rc ){
9727 sqlite3_finalize(pStmt);
9728 return shellDatabaseError(p->db);
9731 if( nArg>2 && c=='i' ){
9732 /* It is an historical accident that the .indexes command shows an error
9733 ** when called with the wrong number of arguments whereas the .tables
9734 ** command does not. */
9735 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
9736 rc = 1;
9737 sqlite3_finalize(pStmt);
9738 goto meta_command_exit;
9740 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
9741 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
9742 if( zDbName==0 ) continue;
9743 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
9744 if( sqlite3_stricmp(zDbName, "main")==0 ){
9745 appendText(&s, "SELECT name FROM ", 0);
9746 }else{
9747 appendText(&s, "SELECT ", 0);
9748 appendText(&s, zDbName, '\'');
9749 appendText(&s, "||'.'||name FROM ", 0);
9751 appendText(&s, zDbName, '"');
9752 appendText(&s, ".sqlite_schema ", 0);
9753 if( c=='t' ){
9754 appendText(&s," WHERE type IN ('table','view')"
9755 " AND name NOT LIKE 'sqlite_%'"
9756 " AND name LIKE ?1", 0);
9757 }else{
9758 appendText(&s," WHERE type='index'"
9759 " AND tbl_name LIKE ?1", 0);
9762 rc = sqlite3_finalize(pStmt);
9763 appendText(&s, " ORDER BY 1", 0);
9764 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
9765 freeText(&s);
9766 if( rc ) return shellDatabaseError(p->db);
9768 /* Run the SQL statement prepared by the above block. Store the results
9769 ** as an array of nul-terminated strings in azResult[]. */
9770 nRow = nAlloc = 0;
9771 azResult = 0;
9772 if( nArg>1 ){
9773 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
9774 }else{
9775 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
9777 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9778 if( nRow>=nAlloc ){
9779 char **azNew;
9780 int n2 = nAlloc*2 + 10;
9781 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
9782 if( azNew==0 ) shell_out_of_memory();
9783 nAlloc = n2;
9784 azResult = azNew;
9786 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
9787 if( 0==azResult[nRow] ) shell_out_of_memory();
9788 nRow++;
9790 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
9791 rc = shellDatabaseError(p->db);
9794 /* Pretty-print the contents of array azResult[] to the output */
9795 if( rc==0 && nRow>0 ){
9796 int len, maxlen = 0;
9797 int i, j;
9798 int nPrintCol, nPrintRow;
9799 for(i=0; i<nRow; i++){
9800 len = strlen30(azResult[i]);
9801 if( len>maxlen ) maxlen = len;
9803 nPrintCol = 80/(maxlen+2);
9804 if( nPrintCol<1 ) nPrintCol = 1;
9805 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
9806 for(i=0; i<nPrintRow; i++){
9807 for(j=i; j<nRow; j+=nPrintRow){
9808 char *zSp = j<nPrintRow ? "" : " ";
9809 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
9810 azResult[j] ? azResult[j]:"");
9812 raw_printf(p->out, "\n");
9816 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
9817 sqlite3_free(azResult);
9818 }else
9820 /* Begin redirecting output to the file "testcase-out.txt" */
9821 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
9822 output_reset(p);
9823 p->out = output_file_open("testcase-out.txt", 0);
9824 if( p->out==0 ){
9825 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
9827 if( nArg>=2 ){
9828 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
9829 }else{
9830 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
9832 }else
9834 #ifndef SQLITE_UNTESTABLE
9835 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
9836 static const struct {
9837 const char *zCtrlName; /* Name of a test-control option */
9838 int ctrlCode; /* Integer code for that option */
9839 const char *zUsage; /* Usage notes */
9840 } aCtrl[] = {
9841 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
9842 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
9843 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
9844 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
9845 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
9846 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" },
9847 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/
9848 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
9849 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
9850 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
9851 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
9852 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
9853 #ifdef YYCOVERAGE
9854 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
9855 #endif
9856 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
9857 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
9858 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
9859 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" },
9861 int testctrl = -1;
9862 int iCtrl = -1;
9863 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
9864 int isOk = 0;
9865 int i, n2;
9866 const char *zCmd = 0;
9868 open_db(p, 0);
9869 zCmd = nArg>=2 ? azArg[1] : "help";
9871 /* The argument can optionally begin with "-" or "--" */
9872 if( zCmd[0]=='-' && zCmd[1] ){
9873 zCmd++;
9874 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
9877 /* --help lists all test-controls */
9878 if( strcmp(zCmd,"help")==0 ){
9879 utf8_printf(p->out, "Available test-controls:\n");
9880 for(i=0; i<ArraySize(aCtrl); i++){
9881 utf8_printf(p->out, " .testctrl %s %s\n",
9882 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
9884 rc = 1;
9885 goto meta_command_exit;
9888 /* convert testctrl text option to value. allow any unique prefix
9889 ** of the option name, or a numerical value. */
9890 n2 = strlen30(zCmd);
9891 for(i=0; i<ArraySize(aCtrl); i++){
9892 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
9893 if( testctrl<0 ){
9894 testctrl = aCtrl[i].ctrlCode;
9895 iCtrl = i;
9896 }else{
9897 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
9898 "Use \".testctrl --help\" for help\n", zCmd);
9899 rc = 1;
9900 goto meta_command_exit;
9904 if( testctrl<0 ){
9905 utf8_printf(stderr,"Error: unknown test-control: %s\n"
9906 "Use \".testctrl --help\" for help\n", zCmd);
9907 }else{
9908 switch(testctrl){
9910 /* sqlite3_test_control(int, db, int) */
9911 case SQLITE_TESTCTRL_OPTIMIZATIONS:
9912 if( nArg==3 ){
9913 int opt = (int)strtol(azArg[2], 0, 0);
9914 rc2 = sqlite3_test_control(testctrl, p->db, opt);
9915 isOk = 3;
9917 break;
9919 /* sqlite3_test_control(int) */
9920 case SQLITE_TESTCTRL_PRNG_SAVE:
9921 case SQLITE_TESTCTRL_PRNG_RESTORE:
9922 case SQLITE_TESTCTRL_PRNG_RESET:
9923 case SQLITE_TESTCTRL_BYTEORDER:
9924 if( nArg==2 ){
9925 rc2 = sqlite3_test_control(testctrl);
9926 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
9928 break;
9930 /* sqlite3_test_control(int, uint) */
9931 case SQLITE_TESTCTRL_PENDING_BYTE:
9932 if( nArg==3 ){
9933 unsigned int opt = (unsigned int)integerValue(azArg[2]);
9934 rc2 = sqlite3_test_control(testctrl, opt);
9935 isOk = 3;
9937 break;
9939 /* sqlite3_test_control(int, int, sqlite3*) */
9940 case SQLITE_TESTCTRL_PRNG_SEED:
9941 if( nArg==3 || nArg==4 ){
9942 int ii = (int)integerValue(azArg[2]);
9943 sqlite3 *db;
9944 if( ii==0 && strcmp(azArg[2],"random")==0 ){
9945 sqlite3_randomness(sizeof(ii),&ii);
9946 printf("-- random seed: %d\n", ii);
9948 if( nArg==3 ){
9949 db = 0;
9950 }else{
9951 db = p->db;
9952 /* Make sure the schema has been loaded */
9953 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
9955 rc2 = sqlite3_test_control(testctrl, ii, db);
9956 isOk = 3;
9958 break;
9960 /* sqlite3_test_control(int, int) */
9961 case SQLITE_TESTCTRL_ASSERT:
9962 case SQLITE_TESTCTRL_ALWAYS:
9963 if( nArg==3 ){
9964 int opt = booleanValue(azArg[2]);
9965 rc2 = sqlite3_test_control(testctrl, opt);
9966 isOk = 1;
9968 break;
9970 /* sqlite3_test_control(int, int) */
9971 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
9972 case SQLITE_TESTCTRL_NEVER_CORRUPT:
9973 if( nArg==3 ){
9974 int opt = booleanValue(azArg[2]);
9975 rc2 = sqlite3_test_control(testctrl, opt);
9976 isOk = 3;
9978 break;
9980 /* sqlite3_test_control(sqlite3*) */
9981 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
9982 rc2 = sqlite3_test_control(testctrl, p->db);
9983 isOk = 3;
9984 break;
9986 case SQLITE_TESTCTRL_IMPOSTER:
9987 if( nArg==5 ){
9988 rc2 = sqlite3_test_control(testctrl, p->db,
9989 azArg[2],
9990 integerValue(azArg[3]),
9991 integerValue(azArg[4]));
9992 isOk = 3;
9994 break;
9996 #ifdef YYCOVERAGE
9997 case SQLITE_TESTCTRL_PARSER_COVERAGE:
9998 if( nArg==2 ){
9999 sqlite3_test_control(testctrl, p->out);
10000 isOk = 3;
10002 #endif
10005 if( isOk==0 && iCtrl>=0 ){
10006 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10007 rc = 1;
10008 }else if( isOk==1 ){
10009 raw_printf(p->out, "%d\n", rc2);
10010 }else if( isOk==2 ){
10011 raw_printf(p->out, "0x%08x\n", rc2);
10013 }else
10014 #endif /* !defined(SQLITE_UNTESTABLE) */
10016 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10017 open_db(p, 0);
10018 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10019 }else
10021 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10022 if( nArg==2 ){
10023 enableTimer = booleanValue(azArg[1]);
10024 if( enableTimer && !HAS_TIMER ){
10025 raw_printf(stderr, "Error: timer not available on this system.\n");
10026 enableTimer = 0;
10028 }else{
10029 raw_printf(stderr, "Usage: .timer on|off\n");
10030 rc = 1;
10032 }else
10034 #ifndef SQLITE_OMIT_TRACE
10035 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10036 int mType = 0;
10037 int jj;
10038 open_db(p, 0);
10039 for(jj=1; jj<nArg; jj++){
10040 const char *z = azArg[jj];
10041 if( z[0]=='-' ){
10042 if( optionMatch(z, "expanded") ){
10043 p->eTraceType = SHELL_TRACE_EXPANDED;
10045 #ifdef SQLITE_ENABLE_NORMALIZE
10046 else if( optionMatch(z, "normalized") ){
10047 p->eTraceType = SHELL_TRACE_NORMALIZED;
10049 #endif
10050 else if( optionMatch(z, "plain") ){
10051 p->eTraceType = SHELL_TRACE_PLAIN;
10053 else if( optionMatch(z, "profile") ){
10054 mType |= SQLITE_TRACE_PROFILE;
10056 else if( optionMatch(z, "row") ){
10057 mType |= SQLITE_TRACE_ROW;
10059 else if( optionMatch(z, "stmt") ){
10060 mType |= SQLITE_TRACE_STMT;
10062 else if( optionMatch(z, "close") ){
10063 mType |= SQLITE_TRACE_CLOSE;
10065 else {
10066 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10067 rc = 1;
10068 goto meta_command_exit;
10070 }else{
10071 output_file_close(p->traceOut);
10072 p->traceOut = output_file_open(azArg[1], 0);
10075 if( p->traceOut==0 ){
10076 sqlite3_trace_v2(p->db, 0, 0, 0);
10077 }else{
10078 if( mType==0 ) mType = SQLITE_TRACE_STMT;
10079 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10081 }else
10082 #endif /* !defined(SQLITE_OMIT_TRACE) */
10084 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10085 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10086 int ii;
10087 int lenOpt;
10088 char *zOpt;
10089 if( nArg<2 ){
10090 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10091 rc = 1;
10092 goto meta_command_exit;
10094 open_db(p, 0);
10095 zOpt = azArg[1];
10096 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10097 lenOpt = (int)strlen(zOpt);
10098 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10099 assert( azArg[nArg]==0 );
10100 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10101 }else{
10102 for(ii=1; ii<nArg; ii++){
10103 sqlite3_create_module(p->db, azArg[ii], 0, 0);
10106 }else
10107 #endif
10109 #if SQLITE_USER_AUTHENTICATION
10110 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10111 if( nArg<2 ){
10112 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10113 rc = 1;
10114 goto meta_command_exit;
10116 open_db(p, 0);
10117 if( strcmp(azArg[1],"login")==0 ){
10118 if( nArg!=4 ){
10119 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10120 rc = 1;
10121 goto meta_command_exit;
10123 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10124 strlen30(azArg[3]));
10125 if( rc ){
10126 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10127 rc = 1;
10129 }else if( strcmp(azArg[1],"add")==0 ){
10130 if( nArg!=5 ){
10131 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10132 rc = 1;
10133 goto meta_command_exit;
10135 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10136 booleanValue(azArg[4]));
10137 if( rc ){
10138 raw_printf(stderr, "User-Add failed: %d\n", rc);
10139 rc = 1;
10141 }else if( strcmp(azArg[1],"edit")==0 ){
10142 if( nArg!=5 ){
10143 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10144 rc = 1;
10145 goto meta_command_exit;
10147 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10148 booleanValue(azArg[4]));
10149 if( rc ){
10150 raw_printf(stderr, "User-Edit failed: %d\n", rc);
10151 rc = 1;
10153 }else if( strcmp(azArg[1],"delete")==0 ){
10154 if( nArg!=3 ){
10155 raw_printf(stderr, "Usage: .user delete USER\n");
10156 rc = 1;
10157 goto meta_command_exit;
10159 rc = sqlite3_user_delete(p->db, azArg[2]);
10160 if( rc ){
10161 raw_printf(stderr, "User-Delete failed: %d\n", rc);
10162 rc = 1;
10164 }else{
10165 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10166 rc = 1;
10167 goto meta_command_exit;
10169 }else
10170 #endif /* SQLITE_USER_AUTHENTICATION */
10172 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10173 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10174 sqlite3_libversion(), sqlite3_sourceid());
10175 /* BEGIN SQLCIPHER */
10176 #ifdef SQLITE_HAS_CODEC
10178 extern char* sqlcipher_version();
10179 char *sqlcipher_ver = sqlcipher_version();
10180 utf8_printf(p->out, "SQLCipher %s\n", sqlcipher_ver);
10181 sqlite3_free(sqlcipher_ver);
10183 #endif
10184 /* END SQLCIPHER */
10185 #if SQLITE_HAVE_ZLIB
10186 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10187 #endif
10188 #define CTIMEOPT_VAL_(opt) #opt
10189 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10190 #if defined(__clang__) && defined(__clang_major__)
10191 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10192 CTIMEOPT_VAL(__clang_minor__) "."
10193 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10194 #elif defined(_MSC_VER)
10195 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10196 #elif defined(__GNUC__) && defined(__VERSION__)
10197 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10198 #endif
10199 }else
10201 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10202 const char *zDbName = nArg==2 ? azArg[1] : "main";
10203 sqlite3_vfs *pVfs = 0;
10204 if( p->db ){
10205 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10206 if( pVfs ){
10207 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
10208 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
10209 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
10210 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10213 }else
10215 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10216 sqlite3_vfs *pVfs;
10217 sqlite3_vfs *pCurrent = 0;
10218 if( p->db ){
10219 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10221 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10222 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
10223 pVfs==pCurrent ? " <--- CURRENT" : "");
10224 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
10225 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
10226 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10227 if( pVfs->pNext ){
10228 raw_printf(p->out, "-----------------------------------\n");
10231 }else
10233 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10234 const char *zDbName = nArg==2 ? azArg[1] : "main";
10235 char *zVfsName = 0;
10236 if( p->db ){
10237 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10238 if( zVfsName ){
10239 utf8_printf(p->out, "%s\n", zVfsName);
10240 sqlite3_free(zVfsName);
10243 }else
10245 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10246 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10247 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
10248 }else
10249 #endif
10251 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10252 int j;
10253 assert( nArg<=ArraySize(azArg) );
10254 p->nWidth = nArg-1;
10255 p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
10256 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10257 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10258 for(j=1; j<nArg; j++){
10259 p->colWidth[j-1] = (int)integerValue(azArg[j]);
10261 }else
10264 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10265 " \"%s\". Enter \".help\" for help\n", azArg[0]);
10266 rc = 1;
10269 meta_command_exit:
10270 if( p->outCount ){
10271 p->outCount--;
10272 if( p->outCount==0 ) output_reset(p);
10274 return rc;
10278 ** Return TRUE if a semicolon occurs anywhere in the first N characters
10279 ** of string z[].
10281 static int line_contains_semicolon(const char *z, int N){
10282 int i;
10283 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
10284 return 0;
10288 ** Test to see if a line consists entirely of whitespace.
10290 static int _all_whitespace(const char *z){
10291 for(; *z; z++){
10292 if( IsSpace(z[0]) ) continue;
10293 if( *z=='/' && z[1]=='*' ){
10294 z += 2;
10295 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
10296 if( *z==0 ) return 0;
10297 z++;
10298 continue;
10300 if( *z=='-' && z[1]=='-' ){
10301 z += 2;
10302 while( *z && *z!='\n' ){ z++; }
10303 if( *z==0 ) return 1;
10304 continue;
10306 return 0;
10308 return 1;
10312 ** Return TRUE if the line typed in is an SQL command terminator other
10313 ** than a semi-colon. The SQL Server style "go" command is understood
10314 ** as is the Oracle "/".
10316 static int line_is_command_terminator(const char *zLine){
10317 while( IsSpace(zLine[0]) ){ zLine++; };
10318 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
10319 return 1; /* Oracle */
10321 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
10322 && _all_whitespace(&zLine[2]) ){
10323 return 1; /* SQL Server */
10325 return 0;
10329 ** We need a default sqlite3_complete() implementation to use in case
10330 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
10331 ** any arbitrary text is a complete SQL statement. This is not very
10332 ** user-friendly, but it does seem to work.
10334 #ifdef SQLITE_OMIT_COMPLETE
10335 #define sqlite3_complete(x) 1
10336 #endif
10339 ** Return true if zSql is a complete SQL statement. Return false if it
10340 ** ends in the middle of a string literal or C-style comment.
10342 static int line_is_complete(char *zSql, int nSql){
10343 int rc;
10344 if( zSql==0 ) return 1;
10345 zSql[nSql] = ';';
10346 zSql[nSql+1] = 0;
10347 rc = sqlite3_complete(zSql);
10348 zSql[nSql] = 0;
10349 return rc;
10353 ** Run a single line of SQL. Return the number of errors.
10355 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10356 int rc;
10357 char *zErrMsg = 0;
10359 open_db(p, 0);
10360 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10361 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10362 BEGIN_TIMER;
10363 rc = shell_exec(p, zSql, &zErrMsg);
10364 END_TIMER;
10365 if( rc || zErrMsg ){
10366 char zPrefix[100];
10367 if( in!=0 || !stdin_is_interactive ){
10368 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10369 "Error: near line %d:", startline);
10370 }else{
10371 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
10373 if( zErrMsg!=0 ){
10374 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
10375 sqlite3_free(zErrMsg);
10376 zErrMsg = 0;
10377 }else{
10378 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
10380 return 1;
10381 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10382 raw_printf(p->out, "changes: %3d total_changes: %d\n",
10383 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
10385 return 0;
10390 ** Read input from *in and process it. If *in==0 then input
10391 ** is interactive - the user is typing it it. Otherwise, input
10392 ** is coming from a file or device. A prompt is issued and history
10393 ** is saved only if input is interactive. An interrupt signal will
10394 ** cause this routine to exit immediately, unless input is interactive.
10396 ** Return the number of errors.
10398 static int process_input(ShellState *p){
10399 char *zLine = 0; /* A single input line */
10400 char *zSql = 0; /* Accumulated SQL text */
10401 int nLine; /* Length of current line */
10402 int nSql = 0; /* Bytes of zSql[] used */
10403 int nAlloc = 0; /* Allocated zSql[] space */
10404 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
10405 int rc; /* Error code */
10406 int errCnt = 0; /* Number of errors seen */
10407 int startline = 0; /* Line number for start of current input */
10409 p->lineno = 0;
10410 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
10411 fflush(p->out);
10412 zLine = one_input_line(p->in, zLine, nSql>0);
10413 if( zLine==0 ){
10414 /* End of input */
10415 if( p->in==0 && stdin_is_interactive ) printf("\n");
10416 break;
10418 if( seenInterrupt ){
10419 if( p->in!=0 ) break;
10420 seenInterrupt = 0;
10422 p->lineno++;
10423 if( nSql==0 && _all_whitespace(zLine) ){
10424 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10425 continue;
10427 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
10428 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10429 if( zLine[0]=='.' ){
10430 rc = do_meta_command(zLine, p);
10431 if( rc==2 ){ /* exit requested */
10432 break;
10433 }else if( rc ){
10434 errCnt++;
10437 continue;
10439 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
10440 memcpy(zLine,";",2);
10442 nLine = strlen30(zLine);
10443 if( nSql+nLine+2>=nAlloc ){
10444 nAlloc = nSql+nLine+100;
10445 zSql = realloc(zSql, nAlloc);
10446 if( zSql==0 ) shell_out_of_memory();
10448 nSqlPrior = nSql;
10449 if( nSql==0 ){
10450 int i;
10451 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
10452 assert( nAlloc>0 && zSql!=0 );
10453 memcpy(zSql, zLine+i, nLine+1-i);
10454 startline = p->lineno;
10455 nSql = nLine-i;
10456 }else{
10457 zSql[nSql++] = '\n';
10458 memcpy(zSql+nSql, zLine, nLine+1);
10459 nSql += nLine;
10461 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
10462 && sqlite3_complete(zSql) ){
10463 errCnt += runOneSqlLine(p, zSql, p->in, startline);
10464 nSql = 0;
10465 if( p->outCount ){
10466 output_reset(p);
10467 p->outCount = 0;
10468 }else{
10469 clearTempFile(p);
10471 }else if( nSql && _all_whitespace(zSql) ){
10472 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
10473 nSql = 0;
10476 if( nSql && !_all_whitespace(zSql) ){
10477 errCnt += runOneSqlLine(p, zSql, p->in, startline);
10479 free(zSql);
10480 free(zLine);
10481 return errCnt>0;
10485 ** Return a pathname which is the user's home directory. A
10486 ** 0 return indicates an error of some kind.
10488 static char *find_home_dir(int clearFlag){
10489 static char *home_dir = NULL;
10490 if( clearFlag ){
10491 free(home_dir);
10492 home_dir = 0;
10493 return 0;
10495 if( home_dir ) return home_dir;
10497 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
10498 && !defined(__RTP__) && !defined(_WRS_KERNEL)
10500 struct passwd *pwent;
10501 uid_t uid = getuid();
10502 if( (pwent=getpwuid(uid)) != NULL) {
10503 home_dir = pwent->pw_dir;
10506 #endif
10508 #if defined(_WIN32_WCE)
10509 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
10511 home_dir = "/";
10512 #else
10514 #if defined(_WIN32) || defined(WIN32)
10515 if (!home_dir) {
10516 home_dir = getenv("USERPROFILE");
10518 #endif
10520 if (!home_dir) {
10521 home_dir = getenv("HOME");
10524 #if defined(_WIN32) || defined(WIN32)
10525 if (!home_dir) {
10526 char *zDrive, *zPath;
10527 int n;
10528 zDrive = getenv("HOMEDRIVE");
10529 zPath = getenv("HOMEPATH");
10530 if( zDrive && zPath ){
10531 n = strlen30(zDrive) + strlen30(zPath) + 1;
10532 home_dir = malloc( n );
10533 if( home_dir==0 ) return 0;
10534 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
10535 return home_dir;
10537 home_dir = "c:\\";
10539 #endif
10541 #endif /* !_WIN32_WCE */
10543 if( home_dir ){
10544 int n = strlen30(home_dir) + 1;
10545 char *z = malloc( n );
10546 if( z ) memcpy(z, home_dir, n);
10547 home_dir = z;
10550 return home_dir;
10554 ** Read input from the file given by sqliterc_override. Or if that
10555 ** parameter is NULL, take input from ~/.sqliterc
10557 ** Returns the number of errors.
10559 static void process_sqliterc(
10560 ShellState *p, /* Configuration data */
10561 const char *sqliterc_override /* Name of config file. NULL to use default */
10563 char *home_dir = NULL;
10564 const char *sqliterc = sqliterc_override;
10565 char *zBuf = 0;
10566 FILE *inSaved = p->in;
10567 int savedLineno = p->lineno;
10569 if (sqliterc == NULL) {
10570 home_dir = find_home_dir(0);
10571 if( home_dir==0 ){
10572 raw_printf(stderr, "-- warning: cannot find home directory;"
10573 " cannot read ~/.sqliterc\n");
10574 return;
10576 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
10577 sqliterc = zBuf;
10579 p->in = fopen(sqliterc,"rb");
10580 if( p->in ){
10581 if( stdin_is_interactive ){
10582 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
10584 process_input(p);
10585 fclose(p->in);
10587 p->in = inSaved;
10588 p->lineno = savedLineno;
10589 sqlite3_free(zBuf);
10593 ** Show available command line options
10595 static const char zOptions[] =
10596 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10597 " -A ARGS... run \".archive ARGS\" and exit\n"
10598 #endif
10599 " -append append the database to the end of the file\n"
10600 " -ascii set output mode to 'ascii'\n"
10601 " -bail stop after hitting an error\n"
10602 " -batch force batch I/O\n"
10603 " -box set output mode to 'box'\n"
10604 " -column set output mode to 'column'\n"
10605 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
10606 " -csv set output mode to 'csv'\n"
10607 #if defined(SQLITE_ENABLE_DESERIALIZE)
10608 " -deserialize open the database using sqlite3_deserialize()\n"
10609 #endif
10610 " -echo print commands before execution\n"
10611 " -init FILENAME read/process named file\n"
10612 " -[no]header turn headers on or off\n"
10613 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10614 " -heap SIZE Size of heap for memsys3 or memsys5\n"
10615 #endif
10616 " -help show this message\n"
10617 " -html set output mode to HTML\n"
10618 " -interactive force interactive I/O\n"
10619 " -json set output mode to 'json'\n"
10620 " -line set output mode to 'line'\n"
10621 " -list set output mode to 'list'\n"
10622 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
10623 " -markdown set output mode to 'markdown'\n"
10624 #if defined(SQLITE_ENABLE_DESERIALIZE)
10625 " -maxsize N maximum size for a --deserialize database\n"
10626 #endif
10627 " -memtrace trace all memory allocations and deallocations\n"
10628 " -mmap N default mmap size set to N\n"
10629 #ifdef SQLITE_ENABLE_MULTIPLEX
10630 " -multiplex enable the multiplexor VFS\n"
10631 #endif
10632 " -newline SEP set output row separator. Default: '\\n'\n"
10633 " -nofollow refuse to open symbolic links to database files\n"
10634 " -nullvalue TEXT set text string for NULL values. Default ''\n"
10635 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
10636 " -quote set output mode to 'quote'\n"
10637 " -readonly open the database read-only\n"
10638 " -separator SEP set output column separator. Default: '|'\n"
10639 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
10640 " -sorterref SIZE sorter references threshold size\n"
10641 #endif
10642 " -stats print memory stats before each finalize\n"
10643 " -table set output mode to 'table'\n"
10644 " -version show SQLite version\n"
10645 " -vfs NAME use NAME as the default VFS\n"
10646 #ifdef SQLITE_ENABLE_VFSTRACE
10647 " -vfstrace enable tracing of all VFS calls\n"
10648 #endif
10649 #ifdef SQLITE_HAVE_ZLIB
10650 " -zip open the file as a ZIP Archive\n"
10651 #endif
10653 static void usage(int showDetail){
10654 utf8_printf(stderr,
10655 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
10656 "FILENAME is the name of an SQLite database. A new database is created\n"
10657 "if the file does not previously exist.\n", Argv0);
10658 if( showDetail ){
10659 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
10660 }else{
10661 raw_printf(stderr, "Use the -help option for additional information\n");
10663 exit(1);
10667 ** Internal check: Verify that the SQLite is uninitialized. Print a
10668 ** error message if it is initialized.
10670 static void verify_uninitialized(void){
10671 if( sqlite3_config(-1)==SQLITE_MISUSE ){
10672 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
10673 " initialization.\n");
10678 ** Initialize the state information in data
10680 static void main_init(ShellState *data) {
10681 memset(data, 0, sizeof(*data));
10682 data->normalMode = data->cMode = data->mode = MODE_List;
10683 data->autoExplain = 1;
10684 memcpy(data->colSeparator,SEP_Column, 2);
10685 memcpy(data->rowSeparator,SEP_Row, 2);
10686 data->showHeader = 0;
10687 data->shellFlgs = SHFLG_Lookaside;
10688 verify_uninitialized();
10689 sqlite3_config(SQLITE_CONFIG_URI, 1);
10690 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
10691 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
10692 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
10693 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
10697 ** Output text to the console in a font that attracts extra attention.
10699 #ifdef _WIN32
10700 static void printBold(const char *zText){
10701 #if !SQLITE_OS_WINRT
10702 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
10703 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
10704 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
10705 SetConsoleTextAttribute(out,
10706 FOREGROUND_RED|FOREGROUND_INTENSITY
10708 #endif
10709 printf("%s", zText);
10710 #if !SQLITE_OS_WINRT
10711 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
10712 #endif
10714 #else
10715 static void printBold(const char *zText){
10716 printf("\033[1m%s\033[0m", zText);
10718 #endif
10721 ** Get the argument to an --option. Throw an error and die if no argument
10722 ** is available.
10724 static char *cmdline_option_value(int argc, char **argv, int i){
10725 if( i==argc ){
10726 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
10727 argv[0], argv[argc-1]);
10728 exit(1);
10730 return argv[i];
10733 #ifndef SQLITE_SHELL_IS_UTF8
10734 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
10735 # define SQLITE_SHELL_IS_UTF8 (0)
10736 # else
10737 # define SQLITE_SHELL_IS_UTF8 (1)
10738 # endif
10739 #endif
10741 #if SQLITE_SHELL_IS_UTF8
10742 int SQLITE_CDECL main(int argc, char **argv){
10743 #else
10744 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
10745 char **argv;
10746 #endif
10747 char *zErrMsg = 0;
10748 ShellState data;
10749 const char *zInitFile = 0;
10750 int i;
10751 int rc = 0;
10752 int warnInmemoryDb = 0;
10753 int readStdin = 1;
10754 int nCmd = 0;
10755 char **azCmd = 0;
10756 const char *zVfs = 0; /* Value of -vfs command-line option */
10757 #if !SQLITE_SHELL_IS_UTF8
10758 char **argvToFree = 0;
10759 int argcToFree = 0;
10760 #endif
10762 setBinaryMode(stdin, 0);
10763 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
10764 stdin_is_interactive = isatty(0);
10765 stdout_is_console = isatty(1);
10767 #ifdef SQLITE_DEBUG
10768 registerOomSimulator();
10769 #endif
10771 #if !defined(_WIN32_WCE)
10772 if( getenv("SQLITE_DEBUG_BREAK") ){
10773 if( isatty(0) && isatty(2) ){
10774 fprintf(stderr,
10775 "attach debugger to process %d and press any key to continue.\n",
10776 GETPID());
10777 fgetc(stdin);
10778 }else{
10779 #if defined(_WIN32) || defined(WIN32)
10780 #if SQLITE_OS_WINRT
10781 __debugbreak();
10782 #else
10783 DebugBreak();
10784 #endif
10785 #elif defined(SIGTRAP)
10786 raise(SIGTRAP);
10787 #endif
10790 #endif
10792 #if USE_SYSTEM_SQLITE+0!=1
10793 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
10794 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
10795 sqlite3_sourceid(), SQLITE_SOURCE_ID);
10796 exit(1);
10798 #endif
10799 main_init(&data);
10801 /* On Windows, we must translate command-line arguments into UTF-8.
10802 ** The SQLite memory allocator subsystem has to be enabled in order to
10803 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
10804 ** subsequent sqlite3_config() calls will work. So copy all results into
10805 ** memory that does not come from the SQLite memory allocator.
10807 #if !SQLITE_SHELL_IS_UTF8
10808 sqlite3_initialize();
10809 argvToFree = malloc(sizeof(argv[0])*argc*2);
10810 argcToFree = argc;
10811 argv = argvToFree + argc;
10812 if( argv==0 ) shell_out_of_memory();
10813 for(i=0; i<argc; i++){
10814 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
10815 int n;
10816 if( z==0 ) shell_out_of_memory();
10817 n = (int)strlen(z);
10818 argv[i] = malloc( n+1 );
10819 if( argv[i]==0 ) shell_out_of_memory();
10820 memcpy(argv[i], z, n+1);
10821 argvToFree[i] = argv[i];
10822 sqlite3_free(z);
10824 sqlite3_shutdown();
10825 #endif
10827 assert( argc>=1 && argv && argv[0] );
10828 Argv0 = argv[0];
10830 /* Make sure we have a valid signal handler early, before anything
10831 ** else is done.
10833 #ifdef SIGINT
10834 signal(SIGINT, interrupt_handler);
10835 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
10836 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
10837 #endif
10839 #ifdef SQLITE_SHELL_DBNAME_PROC
10841 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
10842 ** of a C-function that will provide the name of the database file. Use
10843 ** this compile-time option to embed this shell program in larger
10844 ** applications. */
10845 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
10846 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
10847 warnInmemoryDb = 0;
10849 #endif
10851 /* Do an initial pass through the command-line argument to locate
10852 ** the name of the database file, the name of the initialization file,
10853 ** the size of the alternative malloc heap,
10854 ** and the first command to execute.
10856 verify_uninitialized();
10857 for(i=1; i<argc; i++){
10858 char *z;
10859 z = argv[i];
10860 if( z[0]!='-' ){
10861 if( data.zDbFilename==0 ){
10862 data.zDbFilename = z;
10863 }else{
10864 /* Excesss arguments are interpreted as SQL (or dot-commands) and
10865 ** mean that nothing is read from stdin */
10866 readStdin = 0;
10867 nCmd++;
10868 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
10869 if( azCmd==0 ) shell_out_of_memory();
10870 azCmd[nCmd-1] = z;
10873 if( z[1]=='-' ) z++;
10874 if( strcmp(z,"-separator")==0
10875 || strcmp(z,"-nullvalue")==0
10876 || strcmp(z,"-newline")==0
10877 || strcmp(z,"-cmd")==0
10879 (void)cmdline_option_value(argc, argv, ++i);
10880 }else if( strcmp(z,"-init")==0 ){
10881 zInitFile = cmdline_option_value(argc, argv, ++i);
10882 }else if( strcmp(z,"-batch")==0 ){
10883 /* Need to check for batch mode here to so we can avoid printing
10884 ** informational messages (like from process_sqliterc) before
10885 ** we do the actual processing of arguments later in a second pass.
10887 stdin_is_interactive = 0;
10888 }else if( strcmp(z,"-heap")==0 ){
10889 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10890 const char *zSize;
10891 sqlite3_int64 szHeap;
10893 zSize = cmdline_option_value(argc, argv, ++i);
10894 szHeap = integerValue(zSize);
10895 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
10896 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
10897 #else
10898 (void)cmdline_option_value(argc, argv, ++i);
10899 #endif
10900 }else if( strcmp(z,"-pagecache")==0 ){
10901 int n, sz;
10902 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10903 if( sz>70000 ) sz = 70000;
10904 if( sz<0 ) sz = 0;
10905 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10906 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
10907 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
10908 data.shellFlgs |= SHFLG_Pagecache;
10909 }else if( strcmp(z,"-lookaside")==0 ){
10910 int n, sz;
10911 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10912 if( sz<0 ) sz = 0;
10913 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10914 if( n<0 ) n = 0;
10915 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
10916 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
10917 #ifdef SQLITE_ENABLE_VFSTRACE
10918 }else if( strcmp(z,"-vfstrace")==0 ){
10919 extern int vfstrace_register(
10920 const char *zTraceName,
10921 const char *zOldVfsName,
10922 int (*xOut)(const char*,void*),
10923 void *pOutArg,
10924 int makeDefault
10926 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
10927 #endif
10928 #ifdef SQLITE_ENABLE_MULTIPLEX
10929 }else if( strcmp(z,"-multiplex")==0 ){
10930 extern int sqlite3_multiple_initialize(const char*,int);
10931 sqlite3_multiplex_initialize(0, 1);
10932 #endif
10933 }else if( strcmp(z,"-mmap")==0 ){
10934 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10935 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
10936 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
10937 }else if( strcmp(z,"-sorterref")==0 ){
10938 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10939 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
10940 #endif
10941 }else if( strcmp(z,"-vfs")==0 ){
10942 zVfs = cmdline_option_value(argc, argv, ++i);
10943 #ifdef SQLITE_HAVE_ZLIB
10944 }else if( strcmp(z,"-zip")==0 ){
10945 data.openMode = SHELL_OPEN_ZIPFILE;
10946 #endif
10947 }else if( strcmp(z,"-append")==0 ){
10948 data.openMode = SHELL_OPEN_APPENDVFS;
10949 #ifdef SQLITE_ENABLE_DESERIALIZE
10950 }else if( strcmp(z,"-deserialize")==0 ){
10951 data.openMode = SHELL_OPEN_DESERIALIZE;
10952 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10953 data.szMax = integerValue(argv[++i]);
10954 #endif
10955 }else if( strcmp(z,"-readonly")==0 ){
10956 data.openMode = SHELL_OPEN_READONLY;
10957 }else if( strcmp(z,"-nofollow")==0 ){
10958 data.openFlags = SQLITE_OPEN_NOFOLLOW;
10959 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
10960 }else if( strncmp(z, "-A",2)==0 ){
10961 /* All remaining command-line arguments are passed to the ".archive"
10962 ** command, so ignore them */
10963 break;
10964 #endif
10965 }else if( strcmp(z, "-memtrace")==0 ){
10966 sqlite3MemTraceActivate(stderr);
10969 verify_uninitialized();
10972 #ifdef SQLITE_SHELL_INIT_PROC
10974 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
10975 ** of a C-function that will perform initialization actions on SQLite that
10976 ** occur just before or after sqlite3_initialize(). Use this compile-time
10977 ** option to embed this shell program in larger applications. */
10978 extern void SQLITE_SHELL_INIT_PROC(void);
10979 SQLITE_SHELL_INIT_PROC();
10981 #else
10982 /* All the sqlite3_config() calls have now been made. So it is safe
10983 ** to call sqlite3_initialize() and process any command line -vfs option. */
10984 sqlite3_initialize();
10985 #endif
10987 if( zVfs ){
10988 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
10989 if( pVfs ){
10990 sqlite3_vfs_register(pVfs, 1);
10991 }else{
10992 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
10993 exit(1);
10997 if( data.zDbFilename==0 ){
10998 #ifndef SQLITE_OMIT_MEMORYDB
10999 data.zDbFilename = ":memory:";
11000 warnInmemoryDb = argc==1;
11001 #else
11002 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11003 return 1;
11004 #endif
11006 data.out = stdout;
11007 sqlite3_appendvfs_init(0,0,0);
11009 /* Go ahead and open the database file if it already exists. If the
11010 ** file does not exist, delay opening it. This prevents empty database
11011 ** files from being created if a user mistypes the database name argument
11012 ** to the sqlite command-line tool.
11014 if( access(data.zDbFilename, 0)==0 ){
11015 open_db(&data, 0);
11018 /* Process the initialization file if there is one. If no -init option
11019 ** is given on the command line, look for a file named ~/.sqliterc and
11020 ** try to process it.
11022 process_sqliterc(&data,zInitFile);
11024 /* Make a second pass through the command-line argument and set
11025 ** options. This second pass is delayed until after the initialization
11026 ** file is processed so that the command-line arguments will override
11027 ** settings in the initialization file.
11029 for(i=1; i<argc; i++){
11030 char *z = argv[i];
11031 if( z[0]!='-' ) continue;
11032 if( z[1]=='-' ){ z++; }
11033 if( strcmp(z,"-init")==0 ){
11034 i++;
11035 }else if( strcmp(z,"-html")==0 ){
11036 data.mode = MODE_Html;
11037 }else if( strcmp(z,"-list")==0 ){
11038 data.mode = MODE_List;
11039 }else if( strcmp(z,"-quote")==0 ){
11040 data.mode = MODE_Quote;
11041 }else if( strcmp(z,"-line")==0 ){
11042 data.mode = MODE_Line;
11043 }else if( strcmp(z,"-column")==0 ){
11044 data.mode = MODE_Column;
11045 }else if( strcmp(z,"-json")==0 ){
11046 data.mode = MODE_Json;
11047 }else if( strcmp(z,"-markdown")==0 ){
11048 data.mode = MODE_Markdown;
11049 }else if( strcmp(z,"-table")==0 ){
11050 data.mode = MODE_Table;
11051 }else if( strcmp(z,"-box")==0 ){
11052 data.mode = MODE_Box;
11053 }else if( strcmp(z,"-csv")==0 ){
11054 data.mode = MODE_Csv;
11055 memcpy(data.colSeparator,",",2);
11056 #ifdef SQLITE_HAVE_ZLIB
11057 }else if( strcmp(z,"-zip")==0 ){
11058 data.openMode = SHELL_OPEN_ZIPFILE;
11059 #endif
11060 }else if( strcmp(z,"-append")==0 ){
11061 data.openMode = SHELL_OPEN_APPENDVFS;
11062 #ifdef SQLITE_ENABLE_DESERIALIZE
11063 }else if( strcmp(z,"-deserialize")==0 ){
11064 data.openMode = SHELL_OPEN_DESERIALIZE;
11065 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11066 data.szMax = integerValue(argv[++i]);
11067 #endif
11068 }else if( strcmp(z,"-readonly")==0 ){
11069 data.openMode = SHELL_OPEN_READONLY;
11070 }else if( strcmp(z,"-nofollow")==0 ){
11071 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11072 }else if( strcmp(z,"-ascii")==0 ){
11073 data.mode = MODE_Ascii;
11074 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11075 SEP_Unit);
11076 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11077 SEP_Record);
11078 }else if( strcmp(z,"-separator")==0 ){
11079 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11080 "%s",cmdline_option_value(argc,argv,++i));
11081 }else if( strcmp(z,"-newline")==0 ){
11082 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11083 "%s",cmdline_option_value(argc,argv,++i));
11084 }else if( strcmp(z,"-nullvalue")==0 ){
11085 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11086 "%s",cmdline_option_value(argc,argv,++i));
11087 }else if( strcmp(z,"-header")==0 ){
11088 data.showHeader = 1;
11089 }else if( strcmp(z,"-noheader")==0 ){
11090 data.showHeader = 0;
11091 }else if( strcmp(z,"-echo")==0 ){
11092 ShellSetFlag(&data, SHFLG_Echo);
11093 }else if( strcmp(z,"-eqp")==0 ){
11094 data.autoEQP = AUTOEQP_on;
11095 }else if( strcmp(z,"-eqpfull")==0 ){
11096 data.autoEQP = AUTOEQP_full;
11097 }else if( strcmp(z,"-stats")==0 ){
11098 data.statsOn = 1;
11099 }else if( strcmp(z,"-scanstats")==0 ){
11100 data.scanstatsOn = 1;
11101 }else if( strcmp(z,"-backslash")==0 ){
11102 /* Undocumented command-line option: -backslash
11103 ** Causes C-style backslash escapes to be evaluated in SQL statements
11104 ** prior to sending the SQL into SQLite. Useful for injecting
11105 ** crazy bytes in the middle of SQL statements for testing and debugging.
11107 ShellSetFlag(&data, SHFLG_Backslash);
11108 }else if( strcmp(z,"-bail")==0 ){
11109 bail_on_error = 1;
11110 }else if( strcmp(z,"-version")==0 ){
11111 /* BEGIN SQLCIPHER */
11112 #ifdef SQLITE_HAS_CODEC
11113 extern char* sqlcipher_version();
11114 char *sqlcipher_ver = sqlcipher_version();
11115 printf("%s %s", sqlite3_libversion(), sqlite3_sourceid());
11116 printf(" (SQLCipher %s)\n", sqlcipher_ver);
11117 sqlite3_free(sqlcipher_ver);
11118 #else
11119 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11120 #endif
11121 /* END SQLCIPHER */
11122 return 0;
11123 }else if( strcmp(z,"-interactive")==0 ){
11124 stdin_is_interactive = 1;
11125 }else if( strcmp(z,"-batch")==0 ){
11126 stdin_is_interactive = 0;
11127 }else if( strcmp(z,"-heap")==0 ){
11128 i++;
11129 }else if( strcmp(z,"-pagecache")==0 ){
11130 i+=2;
11131 }else if( strcmp(z,"-lookaside")==0 ){
11132 i+=2;
11133 }else if( strcmp(z,"-mmap")==0 ){
11134 i++;
11135 }else if( strcmp(z,"-memtrace")==0 ){
11136 i++;
11137 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11138 }else if( strcmp(z,"-sorterref")==0 ){
11139 i++;
11140 #endif
11141 }else if( strcmp(z,"-vfs")==0 ){
11142 i++;
11143 #ifdef SQLITE_ENABLE_VFSTRACE
11144 }else if( strcmp(z,"-vfstrace")==0 ){
11145 i++;
11146 #endif
11147 #ifdef SQLITE_ENABLE_MULTIPLEX
11148 }else if( strcmp(z,"-multiplex")==0 ){
11149 i++;
11150 #endif
11151 }else if( strcmp(z,"-help")==0 ){
11152 usage(1);
11153 }else if( strcmp(z,"-cmd")==0 ){
11154 /* Run commands that follow -cmd first and separately from commands
11155 ** that simply appear on the command-line. This seems goofy. It would
11156 ** be better if all commands ran in the order that they appear. But
11157 ** we retain the goofy behavior for historical compatibility. */
11158 if( i==argc-1 ) break;
11159 z = cmdline_option_value(argc,argv,++i);
11160 if( z[0]=='.' ){
11161 rc = do_meta_command(z, &data);
11162 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11163 }else{
11164 open_db(&data, 0);
11165 rc = shell_exec(&data, z, &zErrMsg);
11166 if( zErrMsg!=0 ){
11167 utf8_printf(stderr,"Error: %s\n", zErrMsg);
11168 if( bail_on_error ) return rc!=0 ? rc : 1;
11169 }else if( rc!=0 ){
11170 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11171 if( bail_on_error ) return rc;
11174 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11175 }else if( strncmp(z, "-A", 2)==0 ){
11176 if( nCmd>0 ){
11177 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11178 " with \"%s\"\n", z);
11179 return 1;
11181 open_db(&data, OPEN_DB_ZIPFILE);
11182 if( z[2] ){
11183 argv[i] = &z[2];
11184 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11185 }else{
11186 arDotCommand(&data, 1, argv+i, argc-i);
11188 readStdin = 0;
11189 break;
11190 #endif
11191 }else{
11192 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11193 raw_printf(stderr,"Use -help for a list of options.\n");
11194 return 1;
11196 data.cMode = data.mode;
11199 if( !readStdin ){
11200 /* Run all arguments that do not begin with '-' as if they were separate
11201 ** command-line inputs, except for the argToSkip argument which contains
11202 ** the database filename.
11204 for(i=0; i<nCmd; i++){
11205 if( azCmd[i][0]=='.' ){
11206 rc = do_meta_command(azCmd[i], &data);
11207 if( rc ) return rc==2 ? 0 : rc;
11208 }else{
11209 open_db(&data, 0);
11210 rc = shell_exec(&data, azCmd[i], &zErrMsg);
11211 if( zErrMsg!=0 ){
11212 utf8_printf(stderr,"Error: %s\n", zErrMsg);
11213 return rc!=0 ? rc : 1;
11214 }else if( rc!=0 ){
11215 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11216 return rc;
11220 free(azCmd);
11221 }else{
11222 /* Run commands received from standard input
11224 if( stdin_is_interactive ){
11225 char *zHome;
11226 char *zHistory;
11227 int nHistory;
11228 /* BEGIN SQLCIPHER */
11229 #ifdef SQLITE_HAS_CODEC
11230 extern char* sqlcipher_version();
11231 char *sqlcipher_ver = sqlcipher_version();
11232 printf(
11233 "SQLite version %s %.19s" /*extra-version-info*/
11234 " (SQLCipher %s)\n" /*sqlcipher version info*/
11235 "Enter \".help\" for usage hints.\n",
11236 sqlite3_libversion(), sqlite3_sourceid(), sqlcipher_ver
11238 sqlite3_free(sqlcipher_ver);
11239 #else
11240 printf(
11241 "SQLite version %s %.19s\n" /*extra-version-info*/
11242 "Enter \".help\" for usage hints.\n",
11243 sqlite3_libversion(), sqlite3_sourceid()
11245 #endif
11246 /* END SQLCIPHER */
11247 if( warnInmemoryDb ){
11248 printf("Connected to a ");
11249 printBold("transient in-memory database");
11250 printf(".\nUse \".open FILENAME\" to reopen on a "
11251 "persistent database.\n");
11253 zHistory = getenv("SQLITE_HISTORY");
11254 if( zHistory ){
11255 zHistory = strdup(zHistory);
11256 }else if( (zHome = find_home_dir(0))!=0 ){
11257 nHistory = strlen30(zHome) + 20;
11258 if( (zHistory = malloc(nHistory))!=0 ){
11259 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11262 if( zHistory ){ shell_read_history(zHistory); }
11263 #if HAVE_READLINE || HAVE_EDITLINE
11264 rl_attempted_completion_function = readline_completion;
11265 #elif HAVE_LINENOISE
11266 linenoiseSetCompletionCallback(linenoise_completion);
11267 #endif
11268 data.in = 0;
11269 rc = process_input(&data);
11270 if( zHistory ){
11271 shell_stifle_history(2000);
11272 shell_write_history(zHistory);
11273 free(zHistory);
11275 }else{
11276 data.in = stdin;
11277 rc = process_input(&data);
11280 set_table_name(&data, 0);
11281 if( data.db ){
11282 session_close_all(&data);
11283 close_db(data.db);
11285 sqlite3_free(data.zFreeOnClose);
11286 find_home_dir(1);
11287 output_reset(&data);
11288 data.doXdgOpen = 0;
11289 clearTempFile(&data);
11290 #if !SQLITE_SHELL_IS_UTF8
11291 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11292 free(argvToFree);
11293 #endif
11294 free(data.colWidth);
11295 /* Clear the global data structure so that valgrind will detect memory
11296 ** leaks */
11297 memset(&data, 0, sizeof(data));
11298 return rc;