Merge sqlite-release(3.39.2) into prerelease-integration
[sqlcipher.git] / src / shell.c.in
blob185ec39856f8839409f2c7f72cebc817c036d8a7
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 ** Optionally #include a user-defined header, whereby compilation options
22 ** may be set prior to where they take effect, but after platform setup.
23 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24 ** file. Note that this macro has a like effect on sqlite3.c compilation.
26 # define SHELL_STRINGIFY_(f) #f
27 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28 #ifdef SQLITE_CUSTOM_INCLUDE
29 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30 #endif
33 ** Determine if we are dealing with WinRT, which provides only a subset of
34 ** the full Win32 API.
36 #if !defined(SQLITE_OS_WINRT)
37 # define SQLITE_OS_WINRT 0
38 #endif
41 ** Warning pragmas copied from msvc.h in the core.
43 #if defined(_MSC_VER)
44 #pragma warning(disable : 4054)
45 #pragma warning(disable : 4055)
46 #pragma warning(disable : 4100)
47 #pragma warning(disable : 4127)
48 #pragma warning(disable : 4130)
49 #pragma warning(disable : 4152)
50 #pragma warning(disable : 4189)
51 #pragma warning(disable : 4206)
52 #pragma warning(disable : 4210)
53 #pragma warning(disable : 4232)
54 #pragma warning(disable : 4244)
55 #pragma warning(disable : 4305)
56 #pragma warning(disable : 4306)
57 #pragma warning(disable : 4702)
58 #pragma warning(disable : 4706)
59 #endif /* defined(_MSC_VER) */
62 ** No support for loadable extensions in VxWorks.
64 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
65 # define SQLITE_OMIT_LOAD_EXTENSION 1
66 #endif
69 ** Enable large-file support for fopen() and friends on unix.
71 #ifndef SQLITE_DISABLE_LFS
72 # define _LARGE_FILE 1
73 # ifndef _FILE_OFFSET_BITS
74 # define _FILE_OFFSET_BITS 64
75 # endif
76 # define _LARGEFILE_SOURCE 1
77 #endif
79 #include <stdlib.h>
80 #include <string.h>
81 #include <stdio.h>
82 #include <assert.h>
83 #include "sqlite3.h"
84 typedef sqlite3_int64 i64;
85 typedef sqlite3_uint64 u64;
86 typedef unsigned char u8;
87 #if SQLITE_USER_AUTHENTICATION
88 # include "sqlite3userauth.h"
89 #endif
90 #include <ctype.h>
91 #include <stdarg.h>
93 #if !defined(_WIN32) && !defined(WIN32)
94 # include <signal.h>
95 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
96 # include <pwd.h>
97 # endif
98 #endif
99 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
100 # include <unistd.h>
101 # include <dirent.h>
102 # define GETPID getpid
103 # if defined(__MINGW32__)
104 # define DIRENT dirent
105 # ifndef S_ISLNK
106 # define S_ISLNK(mode) (0)
107 # endif
108 # endif
109 #else
110 # define GETPID (int)GetCurrentProcessId
111 #endif
112 #include <sys/types.h>
113 #include <sys/stat.h>
115 #if HAVE_READLINE
116 # include <readline/readline.h>
117 # include <readline/history.h>
118 #endif
120 #if HAVE_EDITLINE
121 # include <editline/readline.h>
122 #endif
124 #if HAVE_EDITLINE || HAVE_READLINE
126 # define shell_add_history(X) add_history(X)
127 # define shell_read_history(X) read_history(X)
128 # define shell_write_history(X) write_history(X)
129 # define shell_stifle_history(X) stifle_history(X)
130 # define shell_readline(X) readline(X)
132 #elif HAVE_LINENOISE
134 # include "linenoise.h"
135 # define shell_add_history(X) linenoiseHistoryAdd(X)
136 # define shell_read_history(X) linenoiseHistoryLoad(X)
137 # define shell_write_history(X) linenoiseHistorySave(X)
138 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
139 # define shell_readline(X) linenoise(X)
141 #else
143 # define shell_read_history(X)
144 # define shell_write_history(X)
145 # define shell_stifle_history(X)
147 # define SHELL_USE_LOCAL_GETLINE 1
148 #endif
151 #if defined(_WIN32) || defined(WIN32)
152 # if SQLITE_OS_WINRT
153 # define SQLITE_OMIT_POPEN 1
154 # else
155 # include <io.h>
156 # include <fcntl.h>
157 # define isatty(h) _isatty(h)
158 # ifndef access
159 # define access(f,m) _access((f),(m))
160 # endif
161 # ifndef unlink
162 # define unlink _unlink
163 # endif
164 # ifndef strdup
165 # define strdup _strdup
166 # endif
167 # undef popen
168 # define popen _popen
169 # undef pclose
170 # define pclose _pclose
171 # endif
172 #else
173 /* Make sure isatty() has a prototype. */
174 extern int isatty(int);
176 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
177 /* popen and pclose are not C89 functions and so are
178 ** sometimes omitted from the <stdio.h> header */
179 extern FILE *popen(const char*,const char*);
180 extern int pclose(FILE*);
181 # else
182 # define SQLITE_OMIT_POPEN 1
183 # endif
184 #endif
186 #if defined(_WIN32_WCE)
187 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
188 * thus we always assume that we have a console. That can be
189 * overridden with the -batch command line option.
191 #define isatty(x) 1
192 #endif
194 /* ctype macros that work with signed characters */
195 #define IsSpace(X) isspace((unsigned char)X)
196 #define IsDigit(X) isdigit((unsigned char)X)
197 #define ToLower(X) (char)tolower((unsigned char)X)
199 #if defined(_WIN32) || defined(WIN32)
200 #if SQLITE_OS_WINRT
201 #include <intrin.h>
202 #endif
203 #include <windows.h>
205 /* string conversion routines only needed on Win32 */
206 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
207 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
208 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
209 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
210 #endif
212 /* On Windows, we normally run with output mode of TEXT so that \n characters
213 ** are automatically translated into \r\n. However, this behavior needs
214 ** to be disabled in some cases (ex: when generating CSV output and when
215 ** rendering quoted strings that contain \n characters). The following
216 ** routines take care of that.
218 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
219 static void setBinaryMode(FILE *file, int isOutput){
220 if( isOutput ) fflush(file);
221 _setmode(_fileno(file), _O_BINARY);
223 static void setTextMode(FILE *file, int isOutput){
224 if( isOutput ) fflush(file);
225 _setmode(_fileno(file), _O_TEXT);
227 #else
228 # define setBinaryMode(X,Y)
229 # define setTextMode(X,Y)
230 #endif
233 ** When compiling with emcc (a.k.a. emscripten), we're building a
234 ** WebAssembly (WASM) bundle and need to disable and rewire a few
235 ** things.
237 #ifdef __EMSCRIPTEN__
238 #define SQLITE_SHELL_WASM_MODE
239 #else
240 #undef SQLITE_SHELL_WASM_MODE
241 #endif
243 /* True if the timer is enabled */
244 static int enableTimer = 0;
246 /* Return the current wall-clock time */
247 static sqlite3_int64 timeOfDay(void){
248 static sqlite3_vfs *clockVfs = 0;
249 sqlite3_int64 t;
250 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
251 if( clockVfs==0 ) return 0; /* Never actually happens */
252 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
253 clockVfs->xCurrentTimeInt64(clockVfs, &t);
254 }else{
255 double r;
256 clockVfs->xCurrentTime(clockVfs, &r);
257 t = (sqlite3_int64)(r*86400000.0);
259 return t;
262 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
263 #include <sys/time.h>
264 #include <sys/resource.h>
266 /* VxWorks does not support getrusage() as far as we can determine */
267 #if defined(_WRS_KERNEL) || defined(__RTP__)
268 struct rusage {
269 struct timeval ru_utime; /* user CPU time used */
270 struct timeval ru_stime; /* system CPU time used */
272 #define getrusage(A,B) memset(B,0,sizeof(*B))
273 #endif
275 /* Saved resource information for the beginning of an operation */
276 static struct rusage sBegin; /* CPU time at start */
277 static sqlite3_int64 iBegin; /* Wall-clock time at start */
280 ** Begin timing an operation
282 static void beginTimer(void){
283 if( enableTimer ){
284 getrusage(RUSAGE_SELF, &sBegin);
285 iBegin = timeOfDay();
289 /* Return the difference of two time_structs in seconds */
290 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
291 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
292 (double)(pEnd->tv_sec - pStart->tv_sec);
296 ** Print the timing results.
298 static void endTimer(void){
299 if( enableTimer ){
300 sqlite3_int64 iEnd = timeOfDay();
301 struct rusage sEnd;
302 getrusage(RUSAGE_SELF, &sEnd);
303 printf("Run Time: real %.3f user %f sys %f\n",
304 (iEnd - iBegin)*0.001,
305 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
306 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
310 #define BEGIN_TIMER beginTimer()
311 #define END_TIMER endTimer()
312 #define HAS_TIMER 1
314 #elif (defined(_WIN32) || defined(WIN32))
316 /* Saved resource information for the beginning of an operation */
317 static HANDLE hProcess;
318 static FILETIME ftKernelBegin;
319 static FILETIME ftUserBegin;
320 static sqlite3_int64 ftWallBegin;
321 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
322 LPFILETIME, LPFILETIME);
323 static GETPROCTIMES getProcessTimesAddr = NULL;
326 ** Check to see if we have timer support. Return 1 if necessary
327 ** support found (or found previously).
329 static int hasTimer(void){
330 if( getProcessTimesAddr ){
331 return 1;
332 } else {
333 #if !SQLITE_OS_WINRT
334 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
335 ** versions. See if the version we are running on has it, and if it
336 ** does, save off a pointer to it and the current process handle.
338 hProcess = GetCurrentProcess();
339 if( hProcess ){
340 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
341 if( NULL != hinstLib ){
342 getProcessTimesAddr =
343 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
344 if( NULL != getProcessTimesAddr ){
345 return 1;
347 FreeLibrary(hinstLib);
350 #endif
352 return 0;
356 ** Begin timing an operation
358 static void beginTimer(void){
359 if( enableTimer && getProcessTimesAddr ){
360 FILETIME ftCreation, ftExit;
361 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
362 &ftKernelBegin,&ftUserBegin);
363 ftWallBegin = timeOfDay();
367 /* Return the difference of two FILETIME structs in seconds */
368 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
369 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
370 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
371 return (double) ((i64End - i64Start) / 10000000.0);
375 ** Print the timing results.
377 static void endTimer(void){
378 if( enableTimer && getProcessTimesAddr){
379 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
380 sqlite3_int64 ftWallEnd = timeOfDay();
381 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
382 printf("Run Time: real %.3f user %f sys %f\n",
383 (ftWallEnd - ftWallBegin)*0.001,
384 timeDiff(&ftUserBegin, &ftUserEnd),
385 timeDiff(&ftKernelBegin, &ftKernelEnd));
389 #define BEGIN_TIMER beginTimer()
390 #define END_TIMER endTimer()
391 #define HAS_TIMER hasTimer()
393 #else
394 #define BEGIN_TIMER
395 #define END_TIMER
396 #define HAS_TIMER 0
397 #endif
400 ** Used to prevent warnings about unused parameters
402 #define UNUSED_PARAMETER(x) (void)(x)
405 ** Number of elements in an array
407 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
410 ** If the following flag is set, then command execution stops
411 ** at an error if we are not interactive.
413 static int bail_on_error = 0;
416 ** Threat stdin as an interactive input if the following variable
417 ** is true. Otherwise, assume stdin is connected to a file or pipe.
419 static int stdin_is_interactive = 1;
422 ** On Windows systems we have to know if standard output is a console
423 ** in order to translate UTF-8 into MBCS. The following variable is
424 ** true if translation is required.
426 static int stdout_is_console = 1;
429 ** The following is the open SQLite database. We make a pointer
430 ** to this database a static variable so that it can be accessed
431 ** by the SIGINT handler to interrupt database processing.
433 static sqlite3 *globalDb = 0;
436 ** True if an interrupt (Control-C) has been received.
438 static volatile int seenInterrupt = 0;
441 ** This is the name of our program. It is set in main(), used
442 ** in a number of other places, mostly for error messages.
444 static char *Argv0;
447 ** Prompt strings. Initialized in main. Settable with
448 ** .prompt main continue
450 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
451 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
454 ** Render output like fprintf(). Except, if the output is going to the
455 ** console and if this is running on a Windows machine, translate the
456 ** output from UTF-8 into MBCS.
458 #if defined(_WIN32) || defined(WIN32)
459 void utf8_printf(FILE *out, const char *zFormat, ...){
460 va_list ap;
461 va_start(ap, zFormat);
462 if( stdout_is_console && (out==stdout || out==stderr) ){
463 char *z1 = sqlite3_vmprintf(zFormat, ap);
464 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
465 sqlite3_free(z1);
466 fputs(z2, out);
467 sqlite3_free(z2);
468 }else{
469 vfprintf(out, zFormat, ap);
471 va_end(ap);
473 #elif !defined(utf8_printf)
474 # define utf8_printf fprintf
475 #endif
478 ** Render output like fprintf(). This should not be used on anything that
479 ** includes string formatting (e.g. "%s").
481 #if !defined(raw_printf)
482 # define raw_printf fprintf
483 #endif
485 /* Indicate out-of-memory and exit. */
486 static void shell_out_of_memory(void){
487 raw_printf(stderr,"Error: out of memory\n");
488 exit(1);
491 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
492 ** out-of-memory error.
494 static void shell_check_oom(void *p){
495 if( p==0 ) shell_out_of_memory();
499 ** Write I/O traces to the following stream.
501 #ifdef SQLITE_ENABLE_IOTRACE
502 static FILE *iotrace = 0;
503 #endif
506 ** This routine works like printf in that its first argument is a
507 ** format string and subsequent arguments are values to be substituted
508 ** in place of % fields. The result of formatting this string
509 ** is written to iotrace.
511 #ifdef SQLITE_ENABLE_IOTRACE
512 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
513 va_list ap;
514 char *z;
515 if( iotrace==0 ) return;
516 va_start(ap, zFormat);
517 z = sqlite3_vmprintf(zFormat, ap);
518 va_end(ap);
519 utf8_printf(iotrace, "%s", z);
520 sqlite3_free(z);
522 #endif
525 ** Output string zUtf to stream pOut as w characters. If w is negative,
526 ** then right-justify the text. W is the width in UTF-8 characters, not
527 ** in bytes. This is different from the %*.*s specification in printf
528 ** since with %*.*s the width is measured in bytes, not characters.
530 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
531 int i;
532 int n;
533 int aw = w<0 ? -w : w;
534 for(i=n=0; zUtf[i]; i++){
535 if( (zUtf[i]&0xc0)!=0x80 ){
536 n++;
537 if( n==aw ){
538 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
539 break;
543 if( n>=aw ){
544 utf8_printf(pOut, "%.*s", i, zUtf);
545 }else if( w<0 ){
546 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
547 }else{
548 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
554 ** Determines if a string is a number of not.
556 static int isNumber(const char *z, int *realnum){
557 if( *z=='-' || *z=='+' ) z++;
558 if( !IsDigit(*z) ){
559 return 0;
561 z++;
562 if( realnum ) *realnum = 0;
563 while( IsDigit(*z) ){ z++; }
564 if( *z=='.' ){
565 z++;
566 if( !IsDigit(*z) ) return 0;
567 while( IsDigit(*z) ){ z++; }
568 if( realnum ) *realnum = 1;
570 if( *z=='e' || *z=='E' ){
571 z++;
572 if( *z=='+' || *z=='-' ) z++;
573 if( !IsDigit(*z) ) return 0;
574 while( IsDigit(*z) ){ z++; }
575 if( realnum ) *realnum = 1;
577 return *z==0;
581 ** Compute a string length that is limited to what can be stored in
582 ** lower 30 bits of a 32-bit signed integer.
584 static int strlen30(const char *z){
585 const char *z2 = z;
586 while( *z2 ){ z2++; }
587 return 0x3fffffff & (int)(z2 - z);
591 ** Return the length of a string in characters. Multibyte UTF8 characters
592 ** count as a single character.
594 static int strlenChar(const char *z){
595 int n = 0;
596 while( *z ){
597 if( (0xc0&*(z++))!=0x80 ) n++;
599 return n;
603 ** Return open FILE * if zFile exists, can be opened for read
604 ** and is an ordinary file or a character stream source.
605 ** Otherwise return 0.
607 static FILE * openChrSource(const char *zFile){
608 #ifdef _WIN32
609 struct _stat x = {0};
610 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
611 /* On Windows, open first, then check the stream nature. This order
612 ** is necessary because _stat() and sibs, when checking a named pipe,
613 ** effectively break the pipe as its supplier sees it. */
614 FILE *rv = fopen(zFile, "rb");
615 if( rv==0 ) return 0;
616 if( _fstat(_fileno(rv), &x) != 0
617 || !STAT_CHR_SRC(x.st_mode)){
618 fclose(rv);
619 rv = 0;
621 return rv;
622 #else
623 struct stat x = {0};
624 int rc = stat(zFile, &x);
625 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
626 if( rc!=0 ) return 0;
627 if( STAT_CHR_SRC(x.st_mode) ){
628 return fopen(zFile, "rb");
629 }else{
630 return 0;
632 #endif
633 #undef STAT_CHR_SRC
637 ** This routine reads a line of text from FILE in, stores
638 ** the text in memory obtained from malloc() and returns a pointer
639 ** to the text. NULL is returned at end of file, or if malloc()
640 ** fails.
642 ** If zLine is not NULL then it is a malloced buffer returned from
643 ** a previous call to this routine that may be reused.
645 static char *local_getline(char *zLine, FILE *in){
646 int nLine = zLine==0 ? 0 : 100;
647 int n = 0;
649 while( 1 ){
650 if( n+100>nLine ){
651 nLine = nLine*2 + 100;
652 zLine = realloc(zLine, nLine);
653 shell_check_oom(zLine);
655 if( fgets(&zLine[n], nLine - n, in)==0 ){
656 if( n==0 ){
657 free(zLine);
658 return 0;
660 zLine[n] = 0;
661 break;
663 while( zLine[n] ) n++;
664 if( n>0 && zLine[n-1]=='\n' ){
665 n--;
666 if( n>0 && zLine[n-1]=='\r' ) n--;
667 zLine[n] = 0;
668 break;
671 #if defined(_WIN32) || defined(WIN32)
672 /* For interactive input on Windows systems, translate the
673 ** multi-byte characterset characters into UTF-8. */
674 if( stdin_is_interactive && in==stdin ){
675 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
676 if( zTrans ){
677 int nTrans = strlen30(zTrans)+1;
678 if( nTrans>nLine ){
679 zLine = realloc(zLine, nTrans);
680 shell_check_oom(zLine);
682 memcpy(zLine, zTrans, nTrans);
683 sqlite3_free(zTrans);
686 #endif /* defined(_WIN32) || defined(WIN32) */
687 return zLine;
691 ** Retrieve a single line of input text.
693 ** If in==0 then read from standard input and prompt before each line.
694 ** If isContinuation is true, then a continuation prompt is appropriate.
695 ** If isContinuation is zero, then the main prompt should be used.
697 ** If zPrior is not NULL then it is a buffer from a prior call to this
698 ** routine that can be reused.
700 ** The result is stored in space obtained from malloc() and must either
701 ** be freed by the caller or else passed back into this routine via the
702 ** zPrior argument for reuse.
704 #ifndef SQLITE_SHELL_WASM_MODE
705 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
706 char *zPrompt;
707 char *zResult;
708 if( in!=0 ){
709 zResult = local_getline(zPrior, in);
710 }else{
711 zPrompt = isContinuation ? continuePrompt : mainPrompt;
712 #if SHELL_USE_LOCAL_GETLINE
713 printf("%s", zPrompt);
714 fflush(stdout);
715 zResult = local_getline(zPrior, stdin);
716 #else
717 free(zPrior);
718 zResult = shell_readline(zPrompt);
719 /* BEGIN SQLCIPHER */
720 #ifdef SQLITE_HAS_CODEC
721 /* Simplistic filtering of input lines to prevent PRAGKA key and
722 PRAGMA rekey statements from being stored in readline history.
723 Note that this will only prevent single line statements, but that
724 will be sufficient for common cases. */
725 if(zResult && *zResult && (
726 sqlite3_strlike("%pragma%key%=%", zResult, 0)==0 ||
727 sqlite3_strlike("%attach%database%as%key%", zResult, 0)==0
729 ) return zResult;
730 #endif
731 /* END SQLCIPHER */
732 if( zResult && *zResult ) shell_add_history(zResult);
733 #endif
735 return zResult;
737 #endif /* !SQLITE_SHELL_WASM_MODE */
740 ** Return the value of a hexadecimal digit. Return -1 if the input
741 ** is not a hex digit.
743 static int hexDigitValue(char c){
744 if( c>='0' && c<='9' ) return c - '0';
745 if( c>='a' && c<='f' ) return c - 'a' + 10;
746 if( c>='A' && c<='F' ) return c - 'A' + 10;
747 return -1;
751 ** Interpret zArg as an integer value, possibly with suffixes.
753 static sqlite3_int64 integerValue(const char *zArg){
754 sqlite3_int64 v = 0;
755 static const struct { char *zSuffix; int iMult; } aMult[] = {
756 { "KiB", 1024 },
757 { "MiB", 1024*1024 },
758 { "GiB", 1024*1024*1024 },
759 { "KB", 1000 },
760 { "MB", 1000000 },
761 { "GB", 1000000000 },
762 { "K", 1000 },
763 { "M", 1000000 },
764 { "G", 1000000000 },
766 int i;
767 int isNeg = 0;
768 if( zArg[0]=='-' ){
769 isNeg = 1;
770 zArg++;
771 }else if( zArg[0]=='+' ){
772 zArg++;
774 if( zArg[0]=='0' && zArg[1]=='x' ){
775 int x;
776 zArg += 2;
777 while( (x = hexDigitValue(zArg[0]))>=0 ){
778 v = (v<<4) + x;
779 zArg++;
781 }else{
782 while( IsDigit(zArg[0]) ){
783 v = v*10 + zArg[0] - '0';
784 zArg++;
787 for(i=0; i<ArraySize(aMult); i++){
788 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
789 v *= aMult[i].iMult;
790 break;
793 return isNeg? -v : v;
797 ** A variable length string to which one can append text.
799 typedef struct ShellText ShellText;
800 struct ShellText {
801 char *z;
802 int n;
803 int nAlloc;
807 ** Initialize and destroy a ShellText object
809 static void initText(ShellText *p){
810 memset(p, 0, sizeof(*p));
812 static void freeText(ShellText *p){
813 free(p->z);
814 initText(p);
817 /* zIn is either a pointer to a NULL-terminated string in memory obtained
818 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
819 ** added to zIn, and the result returned in memory obtained from malloc().
820 ** zIn, if it was not NULL, is freed.
822 ** If the third argument, quote, is not '\0', then it is used as a
823 ** quote character for zAppend.
825 static void appendText(ShellText *p, const char *zAppend, char quote){
826 int len;
827 int i;
828 int nAppend = strlen30(zAppend);
830 len = nAppend+p->n+1;
831 if( quote ){
832 len += 2;
833 for(i=0; i<nAppend; i++){
834 if( zAppend[i]==quote ) len++;
838 if( p->z==0 || p->n+len>=p->nAlloc ){
839 p->nAlloc = p->nAlloc*2 + len + 20;
840 p->z = realloc(p->z, p->nAlloc);
841 shell_check_oom(p->z);
844 if( quote ){
845 char *zCsr = p->z+p->n;
846 *zCsr++ = quote;
847 for(i=0; i<nAppend; i++){
848 *zCsr++ = zAppend[i];
849 if( zAppend[i]==quote ) *zCsr++ = quote;
851 *zCsr++ = quote;
852 p->n = (int)(zCsr - p->z);
853 *zCsr = '\0';
854 }else{
855 memcpy(p->z+p->n, zAppend, nAppend);
856 p->n += nAppend;
857 p->z[p->n] = '\0';
862 ** Attempt to determine if identifier zName needs to be quoted, either
863 ** because it contains non-alphanumeric characters, or because it is an
864 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
865 ** that quoting is required.
867 ** Return '"' if quoting is required. Return 0 if no quoting is required.
869 static char quoteChar(const char *zName){
870 int i;
871 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
872 for(i=0; zName[i]; i++){
873 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
875 return sqlite3_keyword_check(zName, i) ? '"' : 0;
879 ** Construct a fake object name and column list to describe the structure
880 ** of the view, virtual table, or table valued function zSchema.zName.
882 static char *shellFakeSchema(
883 sqlite3 *db, /* The database connection containing the vtab */
884 const char *zSchema, /* Schema of the database holding the vtab */
885 const char *zName /* The name of the virtual table */
887 sqlite3_stmt *pStmt = 0;
888 char *zSql;
889 ShellText s;
890 char cQuote;
891 char *zDiv = "(";
892 int nRow = 0;
894 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
895 zSchema ? zSchema : "main", zName);
896 shell_check_oom(zSql);
897 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
898 sqlite3_free(zSql);
899 initText(&s);
900 if( zSchema ){
901 cQuote = quoteChar(zSchema);
902 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
903 appendText(&s, zSchema, cQuote);
904 appendText(&s, ".", 0);
906 cQuote = quoteChar(zName);
907 appendText(&s, zName, cQuote);
908 while( sqlite3_step(pStmt)==SQLITE_ROW ){
909 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
910 nRow++;
911 appendText(&s, zDiv, 0);
912 zDiv = ",";
913 if( zCol==0 ) zCol = "";
914 cQuote = quoteChar(zCol);
915 appendText(&s, zCol, cQuote);
917 appendText(&s, ")", 0);
918 sqlite3_finalize(pStmt);
919 if( nRow==0 ){
920 freeText(&s);
921 s.z = 0;
923 return s.z;
927 ** SQL function: shell_module_schema(X)
929 ** Return a fake schema for the table-valued function or eponymous virtual
930 ** table X.
932 static void shellModuleSchema(
933 sqlite3_context *pCtx,
934 int nVal,
935 sqlite3_value **apVal
937 const char *zName;
938 char *zFake;
939 UNUSED_PARAMETER(nVal);
940 zName = (const char*)sqlite3_value_text(apVal[0]);
941 zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
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<ArraySize(aPrefix); 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/memtrace.c
1037 INCLUDE ../ext/misc/shathree.c
1038 INCLUDE ../ext/misc/uint.c
1039 INCLUDE ../ext/misc/decimal.c
1040 INCLUDE ../ext/misc/ieee754.c
1041 INCLUDE ../ext/misc/series.c
1042 INCLUDE ../ext/misc/regexp.c
1043 #ifndef SQLITE_SHELL_WASM_MODE
1044 INCLUDE ../ext/misc/fileio.c
1045 INCLUDE ../ext/misc/completion.c
1046 INCLUDE ../ext/misc/appendvfs.c
1047 #endif
1048 #ifdef SQLITE_HAVE_ZLIB
1049 INCLUDE ../ext/misc/zipfile.c
1050 INCLUDE ../ext/misc/sqlar.c
1051 #endif
1052 INCLUDE ../ext/expert/sqlite3expert.h
1053 INCLUDE ../ext/expert/sqlite3expert.c
1055 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1056 INCLUDE ../ext/misc/dbdata.c
1057 #endif
1059 #if defined(SQLITE_ENABLE_SESSION)
1061 ** State information for a single open session
1063 typedef struct OpenSession OpenSession;
1064 struct OpenSession {
1065 char *zName; /* Symbolic name for this session */
1066 int nFilter; /* Number of xFilter rejection GLOB patterns */
1067 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1068 sqlite3_session *p; /* The open session */
1070 #endif
1072 typedef struct ExpertInfo ExpertInfo;
1073 struct ExpertInfo {
1074 sqlite3expert *pExpert;
1075 int bVerbose;
1078 /* A single line in the EQP output */
1079 typedef struct EQPGraphRow EQPGraphRow;
1080 struct EQPGraphRow {
1081 int iEqpId; /* ID for this row */
1082 int iParentId; /* ID of the parent row */
1083 EQPGraphRow *pNext; /* Next row in sequence */
1084 char zText[1]; /* Text to display for this row */
1087 /* All EQP output is collected into an instance of the following */
1088 typedef struct EQPGraph EQPGraph;
1089 struct EQPGraph {
1090 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1091 EQPGraphRow *pLast; /* Last element of the pRow list */
1092 char zPrefix[100]; /* Graph prefix */
1095 /* Parameters affecting columnar mode result display (defaulting together) */
1096 typedef struct ColModeOpts {
1097 int iWrap; /* In columnar modes, wrap lines reaching this limit */
1098 u8 bQuote; /* Quote results for .mode box and table */
1099 u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
1100 } ColModeOpts;
1101 #define ColModeOpts_default { 60, 0, 0 }
1102 #define ColModeOpts_default_qbox { 60, 1, 0 }
1105 ** State information about the database connection is contained in an
1106 ** instance of the following structure.
1108 typedef struct ShellState ShellState;
1109 struct ShellState {
1110 sqlite3 *db; /* The database */
1111 u8 autoExplain; /* Automatically turn on .explain mode */
1112 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1113 u8 autoEQPtest; /* autoEQP is in test mode */
1114 u8 autoEQPtrace; /* autoEQP is in trace mode */
1115 u8 scanstatsOn; /* True to display scan stats before each finalize */
1116 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1117 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1118 u8 nEqpLevel; /* Depth of the EQP output graph */
1119 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1120 u8 bSafeMode; /* True to prohibit unsafe operations */
1121 u8 bSafeModePersist; /* The long-term value of bSafeMode */
1122 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
1123 unsigned statsOn; /* True to display memory stats before each finalize */
1124 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
1125 int inputNesting; /* Track nesting level of .read and other redirects */
1126 int outCount; /* Revert to stdout when reaching zero */
1127 int cnt; /* Number of records displayed so far */
1128 int lineno; /* Line number of last line read from in */
1129 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1130 FILE *in; /* Read commands from this stream */
1131 FILE *out; /* Write results here */
1132 FILE *traceOut; /* Output for sqlite3_trace() */
1133 int nErr; /* Number of errors seen */
1134 int mode; /* An output mode setting */
1135 int modePrior; /* Saved mode */
1136 int cMode; /* temporary output mode for the current query */
1137 int normalMode; /* Output mode before ".explain on" */
1138 int writableSchema; /* True if PRAGMA writable_schema=ON */
1139 int showHeader; /* True to show column names in List or Column mode */
1140 int nCheck; /* Number of ".check" commands run */
1141 unsigned nProgress; /* Number of progress callbacks encountered */
1142 unsigned mxProgress; /* Maximum progress callbacks before failing */
1143 unsigned flgProgress; /* Flags for the progress callback */
1144 unsigned shellFlgs; /* Various flags */
1145 unsigned priorShFlgs; /* Saved copy of flags */
1146 sqlite3_int64 szMax; /* --maxsize argument to .open */
1147 char *zDestTable; /* Name of destination table when MODE_Insert */
1148 char *zTempFile; /* Temporary file that might need deleting */
1149 char zTestcase[30]; /* Name of current test case */
1150 char colSeparator[20]; /* Column separator character for several modes */
1151 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1152 char colSepPrior[20]; /* Saved column separator */
1153 char rowSepPrior[20]; /* Saved row separator */
1154 int *colWidth; /* Requested width of each column in columnar modes */
1155 int *actualWidth; /* Actual width of each column */
1156 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1157 char nullValue[20]; /* The text to print when a NULL comes back from
1158 ** the database */
1159 char outfile[FILENAME_MAX]; /* Filename for *out */
1160 sqlite3_stmt *pStmt; /* Current statement if any. */
1161 FILE *pLog; /* Write log output here */
1162 struct AuxDb { /* Storage space for auxiliary database connections */
1163 sqlite3 *db; /* Connection pointer */
1164 const char *zDbFilename; /* Filename used to open the connection */
1165 char *zFreeOnClose; /* Free this memory allocation on close */
1166 #if defined(SQLITE_ENABLE_SESSION)
1167 int nSession; /* Number of active sessions */
1168 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1169 #endif
1170 } aAuxDb[5], /* Array of all database connections */
1171 *pAuxDb; /* Currently active database connection */
1172 int *aiIndent; /* Array of indents used in MODE_Explain */
1173 int nIndent; /* Size of array aiIndent[] */
1174 int iIndent; /* Index of current op in aiIndent[] */
1175 char *zNonce; /* Nonce for temporary safe-mode excapes */
1176 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1177 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1178 #ifdef SQLITE_SHELL_WASM_MODE
1179 struct {
1180 const char * zInput; /* Input string from wasm/JS proxy */
1181 const char * zPos; /* Cursor pos into zInput */
1182 } wasm;
1183 #endif
1186 #ifdef SQLITE_SHELL_WASM_MODE
1187 static ShellState shellState;
1188 #endif
1191 /* Allowed values for ShellState.autoEQP
1193 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1194 #define AUTOEQP_on 1 /* Automatic EQP is on */
1195 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1196 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1198 /* Allowed values for ShellState.openMode
1200 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1201 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1202 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1203 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1204 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1205 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1206 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1208 /* Allowed values for ShellState.eTraceType
1210 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1211 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1212 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1214 /* Bits in the ShellState.flgProgress variable */
1215 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1216 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1217 ** callback limit is reached, and for each
1218 ** top-level SQL statement */
1219 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1222 ** These are the allowed shellFlgs values
1224 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1225 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1226 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1227 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1228 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1229 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1230 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1231 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1232 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1233 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1236 ** Macros for testing and setting shellFlgs
1238 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1239 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1240 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1243 ** These are the allowed modes.
1245 #define MODE_Line 0 /* One column per line. Blank line between records */
1246 #define MODE_Column 1 /* One record per line in neat columns */
1247 #define MODE_List 2 /* One record per line with a separator */
1248 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1249 #define MODE_Html 4 /* Generate an XHTML table */
1250 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1251 #define MODE_Quote 6 /* Quote values as for SQL */
1252 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1253 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1254 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1255 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1256 #define MODE_Pretty 11 /* Pretty-print schemas */
1257 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1258 #define MODE_Json 13 /* Output JSON */
1259 #define MODE_Markdown 14 /* Markdown formatting */
1260 #define MODE_Table 15 /* MySQL-style table formatting */
1261 #define MODE_Box 16 /* Unicode box-drawing characters */
1262 #define MODE_Count 17 /* Output only a count of the rows of output */
1263 #define MODE_Off 18 /* No query output shown */
1265 static const char *modeDescr[] = {
1266 "line",
1267 "column",
1268 "list",
1269 "semi",
1270 "html",
1271 "insert",
1272 "quote",
1273 "tcl",
1274 "csv",
1275 "explain",
1276 "ascii",
1277 "prettyprint",
1278 "eqp",
1279 "json",
1280 "markdown",
1281 "table",
1282 "box",
1283 "count",
1284 "off"
1288 ** These are the column/row/line separators used by the various
1289 ** import/export modes.
1291 #define SEP_Column "|"
1292 #define SEP_Row "\n"
1293 #define SEP_Tab "\t"
1294 #define SEP_Space " "
1295 #define SEP_Comma ","
1296 #define SEP_CrLf "\r\n"
1297 #define SEP_Unit "\x1F"
1298 #define SEP_Record "\x1E"
1301 ** Limit input nesting via .read or any other input redirect.
1302 ** It's not too expensive, so a generous allowance can be made.
1304 #define MAX_INPUT_NESTING 25
1307 ** A callback for the sqlite3_log() interface.
1309 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1310 ShellState *p = (ShellState*)pArg;
1311 if( p->pLog==0 ) return;
1312 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1313 fflush(p->pLog);
1317 ** SQL function: shell_putsnl(X)
1319 ** Write the text X to the screen (or whatever output is being directed)
1320 ** adding a newline at the end, and then return X.
1322 static void shellPutsFunc(
1323 sqlite3_context *pCtx,
1324 int nVal,
1325 sqlite3_value **apVal
1327 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1328 (void)nVal;
1329 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1330 sqlite3_result_value(pCtx, apVal[0]);
1334 ** If in safe mode, print an error message described by the arguments
1335 ** and exit immediately.
1337 static void failIfSafeMode(
1338 ShellState *p,
1339 const char *zErrMsg,
1342 if( p->bSafeMode ){
1343 va_list ap;
1344 char *zMsg;
1345 va_start(ap, zErrMsg);
1346 zMsg = sqlite3_vmprintf(zErrMsg, ap);
1347 va_end(ap);
1348 raw_printf(stderr, "line %d: ", p->lineno);
1349 utf8_printf(stderr, "%s\n", zMsg);
1350 exit(1);
1355 ** SQL function: edit(VALUE)
1356 ** edit(VALUE,EDITOR)
1358 ** These steps:
1360 ** (1) Write VALUE into a temporary file.
1361 ** (2) Run program EDITOR on that temporary file.
1362 ** (3) Read the temporary file back and return its content as the result.
1363 ** (4) Delete the temporary file
1365 ** If the EDITOR argument is omitted, use the value in the VISUAL
1366 ** environment variable. If still there is no EDITOR, through an error.
1368 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1370 #ifndef SQLITE_NOHAVE_SYSTEM
1371 static void editFunc(
1372 sqlite3_context *context,
1373 int argc,
1374 sqlite3_value **argv
1376 const char *zEditor;
1377 char *zTempFile = 0;
1378 sqlite3 *db;
1379 char *zCmd = 0;
1380 int bBin;
1381 int rc;
1382 int hasCRNL = 0;
1383 FILE *f = 0;
1384 sqlite3_int64 sz;
1385 sqlite3_int64 x;
1386 unsigned char *p = 0;
1388 if( argc==2 ){
1389 zEditor = (const char*)sqlite3_value_text(argv[1]);
1390 }else{
1391 zEditor = getenv("VISUAL");
1393 if( zEditor==0 ){
1394 sqlite3_result_error(context, "no editor for edit()", -1);
1395 return;
1397 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1398 sqlite3_result_error(context, "NULL input to edit()", -1);
1399 return;
1401 db = sqlite3_context_db_handle(context);
1402 zTempFile = 0;
1403 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1404 if( zTempFile==0 ){
1405 sqlite3_uint64 r = 0;
1406 sqlite3_randomness(sizeof(r), &r);
1407 zTempFile = sqlite3_mprintf("temp%llx", r);
1408 if( zTempFile==0 ){
1409 sqlite3_result_error_nomem(context);
1410 return;
1413 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1414 /* When writing the file to be edited, do \n to \r\n conversions on systems
1415 ** that want \r\n line endings */
1416 f = fopen(zTempFile, bBin ? "wb" : "w");
1417 if( f==0 ){
1418 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1419 goto edit_func_end;
1421 sz = sqlite3_value_bytes(argv[0]);
1422 if( bBin ){
1423 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1424 }else{
1425 const char *z = (const char*)sqlite3_value_text(argv[0]);
1426 /* Remember whether or not the value originally contained \r\n */
1427 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1428 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1430 fclose(f);
1431 f = 0;
1432 if( x!=sz ){
1433 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1434 goto edit_func_end;
1436 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1437 if( zCmd==0 ){
1438 sqlite3_result_error_nomem(context);
1439 goto edit_func_end;
1441 rc = system(zCmd);
1442 sqlite3_free(zCmd);
1443 if( rc ){
1444 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1445 goto edit_func_end;
1447 f = fopen(zTempFile, "rb");
1448 if( f==0 ){
1449 sqlite3_result_error(context,
1450 "edit() cannot reopen temp file after edit", -1);
1451 goto edit_func_end;
1453 fseek(f, 0, SEEK_END);
1454 sz = ftell(f);
1455 rewind(f);
1456 p = sqlite3_malloc64( sz+1 );
1457 if( p==0 ){
1458 sqlite3_result_error_nomem(context);
1459 goto edit_func_end;
1461 x = fread(p, 1, (size_t)sz, f);
1462 fclose(f);
1463 f = 0;
1464 if( x!=sz ){
1465 sqlite3_result_error(context, "could not read back the whole file", -1);
1466 goto edit_func_end;
1468 if( bBin ){
1469 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1470 }else{
1471 sqlite3_int64 i, j;
1472 if( hasCRNL ){
1473 /* If the original contains \r\n then do no conversions back to \n */
1474 }else{
1475 /* If the file did not originally contain \r\n then convert any new
1476 ** \r\n back into \n */
1477 for(i=j=0; i<sz; i++){
1478 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1479 p[j++] = p[i];
1481 sz = j;
1482 p[sz] = 0;
1484 sqlite3_result_text64(context, (const char*)p, sz,
1485 sqlite3_free, SQLITE_UTF8);
1487 p = 0;
1489 edit_func_end:
1490 if( f ) fclose(f);
1491 unlink(zTempFile);
1492 sqlite3_free(zTempFile);
1493 sqlite3_free(p);
1495 #endif /* SQLITE_NOHAVE_SYSTEM */
1498 ** Save or restore the current output mode
1500 static void outputModePush(ShellState *p){
1501 p->modePrior = p->mode;
1502 p->priorShFlgs = p->shellFlgs;
1503 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1504 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1506 static void outputModePop(ShellState *p){
1507 p->mode = p->modePrior;
1508 p->shellFlgs = p->priorShFlgs;
1509 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1510 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1514 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1516 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1517 int i;
1518 char *zBlob = (char *)pBlob;
1519 raw_printf(out,"X'");
1520 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1521 raw_printf(out,"'");
1525 ** Find a string that is not found anywhere in z[]. Return a pointer
1526 ** to that string.
1528 ** Try to use zA and zB first. If both of those are already found in z[]
1529 ** then make up some string and store it in the buffer zBuf.
1531 static const char *unused_string(
1532 const char *z, /* Result must not appear anywhere in z */
1533 const char *zA, const char *zB, /* Try these first */
1534 char *zBuf /* Space to store a generated string */
1536 unsigned i = 0;
1537 if( strstr(z, zA)==0 ) return zA;
1538 if( strstr(z, zB)==0 ) return zB;
1540 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1541 }while( strstr(z,zBuf)!=0 );
1542 return zBuf;
1546 ** Output the given string as a quoted string using SQL quoting conventions.
1548 ** See also: output_quoted_escaped_string()
1550 static void output_quoted_string(FILE *out, const char *z){
1551 int i;
1552 char c;
1553 setBinaryMode(out, 1);
1554 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1555 if( c==0 ){
1556 utf8_printf(out,"'%s'",z);
1557 }else{
1558 raw_printf(out, "'");
1559 while( *z ){
1560 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1561 if( c=='\'' ) i++;
1562 if( i ){
1563 utf8_printf(out, "%.*s", i, z);
1564 z += i;
1566 if( c=='\'' ){
1567 raw_printf(out, "'");
1568 continue;
1570 if( c==0 ){
1571 break;
1573 z++;
1575 raw_printf(out, "'");
1577 setTextMode(out, 1);
1581 ** Output the given string as a quoted string using SQL quoting conventions.
1582 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1583 ** get corrupted by end-of-line translation facilities in some operating
1584 ** systems.
1586 ** This is like output_quoted_string() but with the addition of the \r\n
1587 ** escape mechanism.
1589 static void output_quoted_escaped_string(FILE *out, const char *z){
1590 int i;
1591 char c;
1592 setBinaryMode(out, 1);
1593 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1594 if( c==0 ){
1595 utf8_printf(out,"'%s'",z);
1596 }else{
1597 const char *zNL = 0;
1598 const char *zCR = 0;
1599 int nNL = 0;
1600 int nCR = 0;
1601 char zBuf1[20], zBuf2[20];
1602 for(i=0; z[i]; i++){
1603 if( z[i]=='\n' ) nNL++;
1604 if( z[i]=='\r' ) nCR++;
1606 if( nNL ){
1607 raw_printf(out, "replace(");
1608 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1610 if( nCR ){
1611 raw_printf(out, "replace(");
1612 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1614 raw_printf(out, "'");
1615 while( *z ){
1616 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1617 if( c=='\'' ) i++;
1618 if( i ){
1619 utf8_printf(out, "%.*s", i, z);
1620 z += i;
1622 if( c=='\'' ){
1623 raw_printf(out, "'");
1624 continue;
1626 if( c==0 ){
1627 break;
1629 z++;
1630 if( c=='\n' ){
1631 raw_printf(out, "%s", zNL);
1632 continue;
1634 raw_printf(out, "%s", zCR);
1636 raw_printf(out, "'");
1637 if( nCR ){
1638 raw_printf(out, ",'%s',char(13))", zCR);
1640 if( nNL ){
1641 raw_printf(out, ",'%s',char(10))", zNL);
1644 setTextMode(out, 1);
1648 ** Output the given string as a quoted according to C or TCL quoting rules.
1650 static void output_c_string(FILE *out, const char *z){
1651 unsigned int c;
1652 fputc('"', out);
1653 while( (c = *(z++))!=0 ){
1654 if( c=='\\' ){
1655 fputc(c, out);
1656 fputc(c, out);
1657 }else if( c=='"' ){
1658 fputc('\\', out);
1659 fputc('"', out);
1660 }else if( c=='\t' ){
1661 fputc('\\', out);
1662 fputc('t', out);
1663 }else if( c=='\n' ){
1664 fputc('\\', out);
1665 fputc('n', out);
1666 }else if( c=='\r' ){
1667 fputc('\\', out);
1668 fputc('r', out);
1669 }else if( !isprint(c&0xff) ){
1670 raw_printf(out, "\\%03o", c&0xff);
1671 }else{
1672 fputc(c, out);
1675 fputc('"', out);
1679 ** Output the given string as a quoted according to JSON quoting rules.
1681 static void output_json_string(FILE *out, const char *z, int n){
1682 unsigned int c;
1683 if( n<0 ) n = (int)strlen(z);
1684 fputc('"', out);
1685 while( n-- ){
1686 c = *(z++);
1687 if( c=='\\' || c=='"' ){
1688 fputc('\\', out);
1689 fputc(c, out);
1690 }else if( c<=0x1f ){
1691 fputc('\\', out);
1692 if( c=='\b' ){
1693 fputc('b', out);
1694 }else if( c=='\f' ){
1695 fputc('f', out);
1696 }else if( c=='\n' ){
1697 fputc('n', out);
1698 }else if( c=='\r' ){
1699 fputc('r', out);
1700 }else if( c=='\t' ){
1701 fputc('t', out);
1702 }else{
1703 raw_printf(out, "u%04x",c);
1705 }else{
1706 fputc(c, out);
1709 fputc('"', out);
1713 ** Output the given string with characters that are special to
1714 ** HTML escaped.
1716 static void output_html_string(FILE *out, const char *z){
1717 int i;
1718 if( z==0 ) z = "";
1719 while( *z ){
1720 for(i=0; z[i]
1721 && z[i]!='<'
1722 && z[i]!='&'
1723 && z[i]!='>'
1724 && z[i]!='\"'
1725 && z[i]!='\'';
1726 i++){}
1727 if( i>0 ){
1728 utf8_printf(out,"%.*s",i,z);
1730 if( z[i]=='<' ){
1731 raw_printf(out,"&lt;");
1732 }else if( z[i]=='&' ){
1733 raw_printf(out,"&amp;");
1734 }else if( z[i]=='>' ){
1735 raw_printf(out,"&gt;");
1736 }else if( z[i]=='\"' ){
1737 raw_printf(out,"&quot;");
1738 }else if( z[i]=='\'' ){
1739 raw_printf(out,"&#39;");
1740 }else{
1741 break;
1743 z += i + 1;
1748 ** If a field contains any character identified by a 1 in the following
1749 ** array, then the string must be quoted for CSV.
1751 static const char needCsvQuote[] = {
1752 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1753 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1754 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1755 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1756 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1757 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1758 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1759 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1760 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1761 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1762 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1763 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1764 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1765 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1766 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1767 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1771 ** Output a single term of CSV. Actually, p->colSeparator is used for
1772 ** the separator, which may or may not be a comma. p->nullValue is
1773 ** the null value. Strings are quoted if necessary. The separator
1774 ** is only issued if bSep is true.
1776 static void output_csv(ShellState *p, const char *z, int bSep){
1777 FILE *out = p->out;
1778 if( z==0 ){
1779 utf8_printf(out,"%s",p->nullValue);
1780 }else{
1781 unsigned i;
1782 for(i=0; z[i]; i++){
1783 if( needCsvQuote[((unsigned char*)z)[i]] ){
1784 i = 0;
1785 break;
1788 if( i==0 || strstr(z, p->colSeparator)!=0 ){
1789 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1790 shell_check_oom(zQuoted);
1791 utf8_printf(out, "%s", zQuoted);
1792 sqlite3_free(zQuoted);
1793 }else{
1794 utf8_printf(out, "%s", z);
1797 if( bSep ){
1798 utf8_printf(p->out, "%s", p->colSeparator);
1803 ** This routine runs when the user presses Ctrl-C
1805 static void interrupt_handler(int NotUsed){
1806 UNUSED_PARAMETER(NotUsed);
1807 seenInterrupt++;
1808 if( seenInterrupt>2 ) exit(1);
1809 if( globalDb ) sqlite3_interrupt(globalDb);
1812 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1814 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1816 static BOOL WINAPI ConsoleCtrlHandler(
1817 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1819 if( dwCtrlType==CTRL_C_EVENT ){
1820 interrupt_handler(0);
1821 return TRUE;
1823 return FALSE;
1825 #endif
1827 #ifndef SQLITE_OMIT_AUTHORIZATION
1829 ** This authorizer runs in safe mode.
1831 static int safeModeAuth(
1832 void *pClientData,
1833 int op,
1834 const char *zA1,
1835 const char *zA2,
1836 const char *zA3,
1837 const char *zA4
1839 ShellState *p = (ShellState*)pClientData;
1840 static const char *azProhibitedFunctions[] = {
1841 "edit",
1842 "fts3_tokenizer",
1843 "load_extension",
1844 "readfile",
1845 "writefile",
1846 "zipfile",
1847 "zipfile_cds",
1849 UNUSED_PARAMETER(zA2);
1850 UNUSED_PARAMETER(zA3);
1851 UNUSED_PARAMETER(zA4);
1852 switch( op ){
1853 case SQLITE_ATTACH: {
1854 #ifndef SQLITE_SHELL_WASM_MODE
1855 /* In WASM builds the filesystem is a virtual sandbox, so
1856 ** there's no harm in using ATTACH. */
1857 failIfSafeMode(p, "cannot run ATTACH in safe mode");
1858 #endif
1859 break;
1861 case SQLITE_FUNCTION: {
1862 int i;
1863 for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1864 if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1865 failIfSafeMode(p, "cannot use the %s() function in safe mode",
1866 azProhibitedFunctions[i]);
1869 break;
1872 return SQLITE_OK;
1876 ** When the ".auth ON" is set, the following authorizer callback is
1877 ** invoked. It always returns SQLITE_OK.
1879 static int shellAuth(
1880 void *pClientData,
1881 int op,
1882 const char *zA1,
1883 const char *zA2,
1884 const char *zA3,
1885 const char *zA4
1887 ShellState *p = (ShellState*)pClientData;
1888 static const char *azAction[] = { 0,
1889 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1890 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1891 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1892 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1893 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1894 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1895 "PRAGMA", "READ", "SELECT",
1896 "TRANSACTION", "UPDATE", "ATTACH",
1897 "DETACH", "ALTER_TABLE", "REINDEX",
1898 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1899 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1901 int i;
1902 const char *az[4];
1903 az[0] = zA1;
1904 az[1] = zA2;
1905 az[2] = zA3;
1906 az[3] = zA4;
1907 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1908 for(i=0; i<4; i++){
1909 raw_printf(p->out, " ");
1910 if( az[i] ){
1911 output_c_string(p->out, az[i]);
1912 }else{
1913 raw_printf(p->out, "NULL");
1916 raw_printf(p->out, "\n");
1917 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1918 return SQLITE_OK;
1920 #endif
1923 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1925 ** This routine converts some CREATE TABLE statements for shadow tables
1926 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1928 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1929 if( z==0 ) return;
1930 if( zTail==0 ) return;
1931 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1932 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1933 }else{
1934 utf8_printf(out, "%s%s", z, zTail);
1937 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1938 char c = z[n];
1939 z[n] = 0;
1940 printSchemaLine(out, z, zTail);
1941 z[n] = c;
1945 ** Return true if string z[] has nothing but whitespace and comments to the
1946 ** end of the first line.
1948 static int wsToEol(const char *z){
1949 int i;
1950 for(i=0; z[i]; i++){
1951 if( z[i]=='\n' ) return 1;
1952 if( IsSpace(z[i]) ) continue;
1953 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1954 return 0;
1956 return 1;
1960 ** Add a new entry to the EXPLAIN QUERY PLAN data
1962 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1963 EQPGraphRow *pNew;
1964 int nText = strlen30(zText);
1965 if( p->autoEQPtest ){
1966 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1968 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1969 shell_check_oom(pNew);
1970 pNew->iEqpId = iEqpId;
1971 pNew->iParentId = p2;
1972 memcpy(pNew->zText, zText, nText+1);
1973 pNew->pNext = 0;
1974 if( p->sGraph.pLast ){
1975 p->sGraph.pLast->pNext = pNew;
1976 }else{
1977 p->sGraph.pRow = pNew;
1979 p->sGraph.pLast = pNew;
1983 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1984 ** in p->sGraph.
1986 static void eqp_reset(ShellState *p){
1987 EQPGraphRow *pRow, *pNext;
1988 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1989 pNext = pRow->pNext;
1990 sqlite3_free(pRow);
1992 memset(&p->sGraph, 0, sizeof(p->sGraph));
1995 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1996 ** pOld, or return the first such line if pOld is NULL
1998 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1999 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2000 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2001 return pRow;
2004 /* Render a single level of the graph that has iEqpId as its parent. Called
2005 ** recursively to render sublevels.
2007 static void eqp_render_level(ShellState *p, int iEqpId){
2008 EQPGraphRow *pRow, *pNext;
2009 int n = strlen30(p->sGraph.zPrefix);
2010 char *z;
2011 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2012 pNext = eqp_next_row(p, iEqpId, pRow);
2013 z = pRow->zText;
2014 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2015 pNext ? "|--" : "`--", z);
2016 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2017 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
2018 eqp_render_level(p, pRow->iEqpId);
2019 p->sGraph.zPrefix[n] = 0;
2025 ** Display and reset the EXPLAIN QUERY PLAN data
2027 static void eqp_render(ShellState *p){
2028 EQPGraphRow *pRow = p->sGraph.pRow;
2029 if( pRow ){
2030 if( pRow->zText[0]=='-' ){
2031 if( pRow->pNext==0 ){
2032 eqp_reset(p);
2033 return;
2035 utf8_printf(p->out, "%s\n", pRow->zText+3);
2036 p->sGraph.pRow = pRow->pNext;
2037 sqlite3_free(pRow);
2038 }else{
2039 utf8_printf(p->out, "QUERY PLAN\n");
2041 p->sGraph.zPrefix[0] = 0;
2042 eqp_render_level(p, 0);
2043 eqp_reset(p);
2047 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2049 ** Progress handler callback.
2051 static int progress_handler(void *pClientData) {
2052 ShellState *p = (ShellState*)pClientData;
2053 p->nProgress++;
2054 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2055 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2056 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2057 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2058 return 1;
2060 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2061 raw_printf(p->out, "Progress %u\n", p->nProgress);
2063 return 0;
2065 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2068 ** Print N dashes
2070 static void print_dashes(FILE *out, int N){
2071 const char zDash[] = "--------------------------------------------------";
2072 const int nDash = sizeof(zDash) - 1;
2073 while( N>nDash ){
2074 fputs(zDash, out);
2075 N -= nDash;
2077 raw_printf(out, "%.*s", N, zDash);
2081 ** Print a markdown or table-style row separator using ascii-art
2083 static void print_row_separator(
2084 ShellState *p,
2085 int nArg,
2086 const char *zSep
2088 int i;
2089 if( nArg>0 ){
2090 fputs(zSep, p->out);
2091 print_dashes(p->out, p->actualWidth[0]+2);
2092 for(i=1; i<nArg; i++){
2093 fputs(zSep, p->out);
2094 print_dashes(p->out, p->actualWidth[i]+2);
2096 fputs(zSep, p->out);
2098 fputs("\n", p->out);
2102 ** This is the callback routine that the shell
2103 ** invokes for each row of a query result.
2105 static int shell_callback(
2106 void *pArg,
2107 int nArg, /* Number of result columns */
2108 char **azArg, /* Text of each result column */
2109 char **azCol, /* Column names */
2110 int *aiType /* Column types. Might be NULL */
2112 int i;
2113 ShellState *p = (ShellState*)pArg;
2115 if( azArg==0 ) return 0;
2116 switch( p->cMode ){
2117 case MODE_Count:
2118 case MODE_Off: {
2119 break;
2121 case MODE_Line: {
2122 int w = 5;
2123 if( azArg==0 ) break;
2124 for(i=0; i<nArg; i++){
2125 int len = strlen30(azCol[i] ? azCol[i] : "");
2126 if( len>w ) w = len;
2128 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2129 for(i=0; i<nArg; i++){
2130 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2131 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2133 break;
2135 case MODE_Explain: {
2136 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2137 if( nArg>ArraySize(aExplainWidth) ){
2138 nArg = ArraySize(aExplainWidth);
2140 if( p->cnt++==0 ){
2141 for(i=0; i<nArg; i++){
2142 int w = aExplainWidth[i];
2143 utf8_width_print(p->out, w, azCol[i]);
2144 fputs(i==nArg-1 ? "\n" : " ", p->out);
2146 for(i=0; i<nArg; i++){
2147 int w = aExplainWidth[i];
2148 print_dashes(p->out, w);
2149 fputs(i==nArg-1 ? "\n" : " ", p->out);
2152 if( azArg==0 ) break;
2153 for(i=0; i<nArg; i++){
2154 int w = aExplainWidth[i];
2155 if( i==nArg-1 ) w = 0;
2156 if( azArg[i] && strlenChar(azArg[i])>w ){
2157 w = strlenChar(azArg[i]);
2159 if( i==1 && p->aiIndent && p->pStmt ){
2160 if( p->iIndent<p->nIndent ){
2161 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2163 p->iIndent++;
2165 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2166 fputs(i==nArg-1 ? "\n" : " ", p->out);
2168 break;
2170 case MODE_Semi: { /* .schema and .fullschema output */
2171 printSchemaLine(p->out, azArg[0], ";\n");
2172 break;
2174 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2175 char *z;
2176 int j;
2177 int nParen = 0;
2178 char cEnd = 0;
2179 char c;
2180 int nLine = 0;
2181 assert( nArg==1 );
2182 if( azArg[0]==0 ) break;
2183 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2184 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2186 utf8_printf(p->out, "%s;\n", azArg[0]);
2187 break;
2189 z = sqlite3_mprintf("%s", azArg[0]);
2190 shell_check_oom(z);
2191 j = 0;
2192 for(i=0; IsSpace(z[i]); i++){}
2193 for(; (c = z[i])!=0; i++){
2194 if( IsSpace(c) ){
2195 if( z[j-1]=='\r' ) z[j-1] = '\n';
2196 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2197 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2198 j--;
2200 z[j++] = c;
2202 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2203 z[j] = 0;
2204 if( strlen30(z)>=79 ){
2205 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2206 if( c==cEnd ){
2207 cEnd = 0;
2208 }else if( c=='"' || c=='\'' || c=='`' ){
2209 cEnd = c;
2210 }else if( c=='[' ){
2211 cEnd = ']';
2212 }else if( c=='-' && z[i+1]=='-' ){
2213 cEnd = '\n';
2214 }else if( c=='(' ){
2215 nParen++;
2216 }else if( c==')' ){
2217 nParen--;
2218 if( nLine>0 && nParen==0 && j>0 ){
2219 printSchemaLineN(p->out, z, j, "\n");
2220 j = 0;
2223 z[j++] = c;
2224 if( nParen==1 && cEnd==0
2225 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2227 if( c=='\n' ) j--;
2228 printSchemaLineN(p->out, z, j, "\n ");
2229 j = 0;
2230 nLine++;
2231 while( IsSpace(z[i+1]) ){ i++; }
2234 z[j] = 0;
2236 printSchemaLine(p->out, z, ";\n");
2237 sqlite3_free(z);
2238 break;
2240 case MODE_List: {
2241 if( p->cnt++==0 && p->showHeader ){
2242 for(i=0; i<nArg; i++){
2243 utf8_printf(p->out,"%s%s",azCol[i],
2244 i==nArg-1 ? p->rowSeparator : p->colSeparator);
2247 if( azArg==0 ) break;
2248 for(i=0; i<nArg; i++){
2249 char *z = azArg[i];
2250 if( z==0 ) z = p->nullValue;
2251 utf8_printf(p->out, "%s", z);
2252 if( i<nArg-1 ){
2253 utf8_printf(p->out, "%s", p->colSeparator);
2254 }else{
2255 utf8_printf(p->out, "%s", p->rowSeparator);
2258 break;
2260 case MODE_Html: {
2261 if( p->cnt++==0 && p->showHeader ){
2262 raw_printf(p->out,"<TR>");
2263 for(i=0; i<nArg; i++){
2264 raw_printf(p->out,"<TH>");
2265 output_html_string(p->out, azCol[i]);
2266 raw_printf(p->out,"</TH>\n");
2268 raw_printf(p->out,"</TR>\n");
2270 if( azArg==0 ) break;
2271 raw_printf(p->out,"<TR>");
2272 for(i=0; i<nArg; i++){
2273 raw_printf(p->out,"<TD>");
2274 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2275 raw_printf(p->out,"</TD>\n");
2277 raw_printf(p->out,"</TR>\n");
2278 break;
2280 case MODE_Tcl: {
2281 if( p->cnt++==0 && p->showHeader ){
2282 for(i=0; i<nArg; i++){
2283 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2284 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2286 utf8_printf(p->out, "%s", p->rowSeparator);
2288 if( azArg==0 ) break;
2289 for(i=0; i<nArg; i++){
2290 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2291 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2293 utf8_printf(p->out, "%s", p->rowSeparator);
2294 break;
2296 case MODE_Csv: {
2297 setBinaryMode(p->out, 1);
2298 if( p->cnt++==0 && p->showHeader ){
2299 for(i=0; i<nArg; i++){
2300 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2302 utf8_printf(p->out, "%s", p->rowSeparator);
2304 if( nArg>0 ){
2305 for(i=0; i<nArg; i++){
2306 output_csv(p, azArg[i], i<nArg-1);
2308 utf8_printf(p->out, "%s", p->rowSeparator);
2310 setTextMode(p->out, 1);
2311 break;
2313 case MODE_Insert: {
2314 if( azArg==0 ) break;
2315 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2316 if( p->showHeader ){
2317 raw_printf(p->out,"(");
2318 for(i=0; i<nArg; i++){
2319 if( i>0 ) raw_printf(p->out, ",");
2320 if( quoteChar(azCol[i]) ){
2321 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2322 shell_check_oom(z);
2323 utf8_printf(p->out, "%s", z);
2324 sqlite3_free(z);
2325 }else{
2326 raw_printf(p->out, "%s", azCol[i]);
2329 raw_printf(p->out,")");
2331 p->cnt++;
2332 for(i=0; i<nArg; i++){
2333 raw_printf(p->out, i>0 ? "," : " VALUES(");
2334 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2335 utf8_printf(p->out,"NULL");
2336 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2337 if( ShellHasFlag(p, SHFLG_Newlines) ){
2338 output_quoted_string(p->out, azArg[i]);
2339 }else{
2340 output_quoted_escaped_string(p->out, azArg[i]);
2342 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2343 utf8_printf(p->out,"%s", azArg[i]);
2344 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2345 char z[50];
2346 double r = sqlite3_column_double(p->pStmt, i);
2347 sqlite3_uint64 ur;
2348 memcpy(&ur,&r,sizeof(r));
2349 if( ur==0x7ff0000000000000LL ){
2350 raw_printf(p->out, "1e999");
2351 }else if( ur==0xfff0000000000000LL ){
2352 raw_printf(p->out, "-1e999");
2353 }else{
2354 sqlite3_int64 ir = (sqlite3_int64)r;
2355 if( r==(double)ir ){
2356 sqlite3_snprintf(50,z,"%lld.0", ir);
2357 }else{
2358 sqlite3_snprintf(50,z,"%!.20g", r);
2360 raw_printf(p->out, "%s", z);
2362 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2363 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2364 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2365 output_hex_blob(p->out, pBlob, nBlob);
2366 }else if( isNumber(azArg[i], 0) ){
2367 utf8_printf(p->out,"%s", azArg[i]);
2368 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2369 output_quoted_string(p->out, azArg[i]);
2370 }else{
2371 output_quoted_escaped_string(p->out, azArg[i]);
2374 raw_printf(p->out,");\n");
2375 break;
2377 case MODE_Json: {
2378 if( azArg==0 ) break;
2379 if( p->cnt==0 ){
2380 fputs("[{", p->out);
2381 }else{
2382 fputs(",\n{", p->out);
2384 p->cnt++;
2385 for(i=0; i<nArg; i++){
2386 output_json_string(p->out, azCol[i], -1);
2387 putc(':', p->out);
2388 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2389 fputs("null",p->out);
2390 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2391 char z[50];
2392 double r = sqlite3_column_double(p->pStmt, i);
2393 sqlite3_uint64 ur;
2394 memcpy(&ur,&r,sizeof(r));
2395 if( ur==0x7ff0000000000000LL ){
2396 raw_printf(p->out, "1e999");
2397 }else if( ur==0xfff0000000000000LL ){
2398 raw_printf(p->out, "-1e999");
2399 }else{
2400 sqlite3_snprintf(50,z,"%!.20g", r);
2401 raw_printf(p->out, "%s", z);
2403 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2404 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2405 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2406 output_json_string(p->out, pBlob, nBlob);
2407 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2408 output_json_string(p->out, azArg[i], -1);
2409 }else{
2410 utf8_printf(p->out,"%s", azArg[i]);
2412 if( i<nArg-1 ){
2413 putc(',', p->out);
2416 putc('}', p->out);
2417 break;
2419 case MODE_Quote: {
2420 if( azArg==0 ) break;
2421 if( p->cnt==0 && p->showHeader ){
2422 for(i=0; i<nArg; i++){
2423 if( i>0 ) fputs(p->colSeparator, p->out);
2424 output_quoted_string(p->out, azCol[i]);
2426 fputs(p->rowSeparator, p->out);
2428 p->cnt++;
2429 for(i=0; i<nArg; i++){
2430 if( i>0 ) fputs(p->colSeparator, p->out);
2431 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2432 utf8_printf(p->out,"NULL");
2433 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2434 output_quoted_string(p->out, azArg[i]);
2435 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2436 utf8_printf(p->out,"%s", azArg[i]);
2437 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2438 char z[50];
2439 double r = sqlite3_column_double(p->pStmt, i);
2440 sqlite3_snprintf(50,z,"%!.20g", r);
2441 raw_printf(p->out, "%s", z);
2442 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2443 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2444 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2445 output_hex_blob(p->out, pBlob, nBlob);
2446 }else if( isNumber(azArg[i], 0) ){
2447 utf8_printf(p->out,"%s", azArg[i]);
2448 }else{
2449 output_quoted_string(p->out, azArg[i]);
2452 fputs(p->rowSeparator, p->out);
2453 break;
2455 case MODE_Ascii: {
2456 if( p->cnt++==0 && p->showHeader ){
2457 for(i=0; i<nArg; i++){
2458 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2459 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2461 utf8_printf(p->out, "%s", p->rowSeparator);
2463 if( azArg==0 ) break;
2464 for(i=0; i<nArg; i++){
2465 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2466 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2468 utf8_printf(p->out, "%s", p->rowSeparator);
2469 break;
2471 case MODE_EQP: {
2472 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2473 break;
2476 return 0;
2480 ** This is the callback routine that the SQLite library
2481 ** invokes for each row of a query result.
2483 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2484 /* since we don't have type info, call the shell_callback with a NULL value */
2485 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2489 ** This is the callback routine from sqlite3_exec() that appends all
2490 ** output onto the end of a ShellText object.
2492 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2493 ShellText *p = (ShellText*)pArg;
2494 int i;
2495 UNUSED_PARAMETER(az);
2496 if( azArg==0 ) return 0;
2497 if( p->n ) appendText(p, "|", 0);
2498 for(i=0; i<nArg; i++){
2499 if( i ) appendText(p, ",", 0);
2500 if( azArg[i] ) appendText(p, azArg[i], 0);
2502 return 0;
2506 ** Generate an appropriate SELFTEST table in the main database.
2508 static void createSelftestTable(ShellState *p){
2509 char *zErrMsg = 0;
2510 sqlite3_exec(p->db,
2511 "SAVEPOINT selftest_init;\n"
2512 "CREATE TABLE IF NOT EXISTS selftest(\n"
2513 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2514 " op TEXT,\n" /* Operator: memo run */
2515 " cmd TEXT,\n" /* Command text */
2516 " ans TEXT\n" /* Desired answer */
2517 ");"
2518 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2519 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2520 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2521 " 'memo','Tests generated by --init');\n"
2522 "INSERT INTO [_shell$self]\n"
2523 " SELECT 'run',\n"
2524 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2525 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2526 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2527 "FROM sqlite_schema ORDER BY 2',224));\n"
2528 "INSERT INTO [_shell$self]\n"
2529 " SELECT 'run',"
2530 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2531 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2532 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2533 " FROM (\n"
2534 " SELECT name FROM sqlite_schema\n"
2535 " WHERE type='table'\n"
2536 " AND name<>'selftest'\n"
2537 " AND coalesce(rootpage,0)>0\n"
2538 " )\n"
2539 " ORDER BY name;\n"
2540 "INSERT INTO [_shell$self]\n"
2541 " VALUES('run','PRAGMA integrity_check','ok');\n"
2542 "INSERT INTO selftest(tno,op,cmd,ans)"
2543 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2544 "DROP TABLE [_shell$self];"
2545 ,0,0,&zErrMsg);
2546 if( zErrMsg ){
2547 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2548 sqlite3_free(zErrMsg);
2550 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2555 ** Set the destination table field of the ShellState structure to
2556 ** the name of the table given. Escape any quote characters in the
2557 ** table name.
2559 static void set_table_name(ShellState *p, const char *zName){
2560 int i, n;
2561 char cQuote;
2562 char *z;
2564 if( p->zDestTable ){
2565 free(p->zDestTable);
2566 p->zDestTable = 0;
2568 if( zName==0 ) return;
2569 cQuote = quoteChar(zName);
2570 n = strlen30(zName);
2571 if( cQuote ) n += n+2;
2572 z = p->zDestTable = malloc( n+1 );
2573 shell_check_oom(z);
2574 n = 0;
2575 if( cQuote ) z[n++] = cQuote;
2576 for(i=0; zName[i]; i++){
2577 z[n++] = zName[i];
2578 if( zName[i]==cQuote ) z[n++] = cQuote;
2580 if( cQuote ) z[n++] = cQuote;
2581 z[n] = 0;
2585 ** Maybe construct two lines of text that point out the position of a
2586 ** syntax error. Return a pointer to the text, in memory obtained from
2587 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2588 ** specific token that we can point to, return an empty string.
2590 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2591 ** and should be released by the caller invoking sqlite3_free().
2593 static char *shell_error_context(const char *zSql, sqlite3 *db){
2594 int iOffset;
2595 size_t len;
2596 char *zCode;
2597 char *zMsg;
2598 int i;
2599 if( db==0
2600 || zSql==0
2601 || (iOffset = sqlite3_error_offset(db))<0
2603 return sqlite3_mprintf("");
2605 while( iOffset>50 ){
2606 iOffset--;
2607 zSql++;
2608 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2610 len = strlen(zSql);
2611 if( len>78 ){
2612 len = 78;
2613 while( (zSql[len]&0xc0)==0x80 ) len--;
2615 zCode = sqlite3_mprintf("%.*s", len, zSql);
2616 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2617 if( iOffset<25 ){
2618 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode, iOffset, "");
2619 }else{
2620 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode, iOffset-14, "");
2622 return zMsg;
2627 ** Execute a query statement that will generate SQL output. Print
2628 ** the result columns, comma-separated, on a line and then add a
2629 ** semicolon terminator to the end of that line.
2631 ** If the number of columns is 1 and that column contains text "--"
2632 ** then write the semicolon on a separate line. That way, if a
2633 ** "--" comment occurs at the end of the statement, the comment
2634 ** won't consume the semicolon terminator.
2636 static int run_table_dump_query(
2637 ShellState *p, /* Query context */
2638 const char *zSelect /* SELECT statement to extract content */
2640 sqlite3_stmt *pSelect;
2641 int rc;
2642 int nResult;
2643 int i;
2644 const char *z;
2645 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2646 if( rc!=SQLITE_OK || !pSelect ){
2647 char *zContext = shell_error_context(zSelect, p->db);
2648 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2649 sqlite3_errmsg(p->db), zContext);
2650 sqlite3_free(zContext);
2651 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2652 return rc;
2654 rc = sqlite3_step(pSelect);
2655 nResult = sqlite3_column_count(pSelect);
2656 while( rc==SQLITE_ROW ){
2657 z = (const char*)sqlite3_column_text(pSelect, 0);
2658 utf8_printf(p->out, "%s", z);
2659 for(i=1; i<nResult; i++){
2660 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2662 if( z==0 ) z = "";
2663 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2664 if( z[0] ){
2665 raw_printf(p->out, "\n;\n");
2666 }else{
2667 raw_printf(p->out, ";\n");
2669 rc = sqlite3_step(pSelect);
2671 rc = sqlite3_finalize(pSelect);
2672 if( rc!=SQLITE_OK ){
2673 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2674 sqlite3_errmsg(p->db));
2675 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2677 return rc;
2681 ** Allocate space and save off string indicating current error.
2683 static char *save_err_msg(
2684 sqlite3 *db, /* Database to query */
2685 const char *zPhase, /* When the error occcurs */
2686 int rc, /* Error code returned from API */
2687 const char *zSql /* SQL string, or NULL */
2689 char *zErr;
2690 char *zContext;
2691 sqlite3_str *pStr = sqlite3_str_new(0);
2692 sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2693 if( rc>1 ){
2694 sqlite3_str_appendf(pStr, " (%d)", rc);
2696 zContext = shell_error_context(zSql, db);
2697 if( zContext ){
2698 sqlite3_str_appendall(pStr, zContext);
2699 sqlite3_free(zContext);
2701 zErr = sqlite3_str_finish(pStr);
2702 shell_check_oom(zErr);
2703 return zErr;
2706 #ifdef __linux__
2708 ** Attempt to display I/O stats on Linux using /proc/PID/io
2710 static void displayLinuxIoStats(FILE *out){
2711 FILE *in;
2712 char z[200];
2713 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2714 in = fopen(z, "rb");
2715 if( in==0 ) return;
2716 while( fgets(z, sizeof(z), in)!=0 ){
2717 static const struct {
2718 const char *zPattern;
2719 const char *zDesc;
2720 } aTrans[] = {
2721 { "rchar: ", "Bytes received by read():" },
2722 { "wchar: ", "Bytes sent to write():" },
2723 { "syscr: ", "Read() system calls:" },
2724 { "syscw: ", "Write() system calls:" },
2725 { "read_bytes: ", "Bytes read from storage:" },
2726 { "write_bytes: ", "Bytes written to storage:" },
2727 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2729 int i;
2730 for(i=0; i<ArraySize(aTrans); i++){
2731 int n = strlen30(aTrans[i].zPattern);
2732 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2733 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2734 break;
2738 fclose(in);
2740 #endif
2743 ** Display a single line of status using 64-bit values.
2745 static void displayStatLine(
2746 ShellState *p, /* The shell context */
2747 char *zLabel, /* Label for this one line */
2748 char *zFormat, /* Format for the result */
2749 int iStatusCtrl, /* Which status to display */
2750 int bReset /* True to reset the stats */
2752 sqlite3_int64 iCur = -1;
2753 sqlite3_int64 iHiwtr = -1;
2754 int i, nPercent;
2755 char zLine[200];
2756 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2757 for(i=0, nPercent=0; zFormat[i]; i++){
2758 if( zFormat[i]=='%' ) nPercent++;
2760 if( nPercent>1 ){
2761 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2762 }else{
2763 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2765 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2769 ** Display memory stats.
2771 static int display_stats(
2772 sqlite3 *db, /* Database to query */
2773 ShellState *pArg, /* Pointer to ShellState */
2774 int bReset /* True to reset the stats */
2776 int iCur;
2777 int iHiwtr;
2778 FILE *out;
2779 if( pArg==0 || pArg->out==0 ) return 0;
2780 out = pArg->out;
2782 if( pArg->pStmt && pArg->statsOn==2 ){
2783 int nCol, i, x;
2784 sqlite3_stmt *pStmt = pArg->pStmt;
2785 char z[100];
2786 nCol = sqlite3_column_count(pStmt);
2787 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2788 for(i=0; i<nCol; i++){
2789 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2790 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2791 #ifndef SQLITE_OMIT_DECLTYPE
2792 sqlite3_snprintf(30, z+x, "declared type:");
2793 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2794 #endif
2795 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2796 sqlite3_snprintf(30, z+x, "database name:");
2797 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2798 sqlite3_snprintf(30, z+x, "table name:");
2799 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2800 sqlite3_snprintf(30, z+x, "origin name:");
2801 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2802 #endif
2806 if( pArg->statsOn==3 ){
2807 if( pArg->pStmt ){
2808 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2809 raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2811 return 0;
2814 displayStatLine(pArg, "Memory Used:",
2815 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2816 displayStatLine(pArg, "Number of Outstanding Allocations:",
2817 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2818 if( pArg->shellFlgs & SHFLG_Pagecache ){
2819 displayStatLine(pArg, "Number of Pcache Pages Used:",
2820 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2822 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2823 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2824 displayStatLine(pArg, "Largest Allocation:",
2825 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2826 displayStatLine(pArg, "Largest Pcache Allocation:",
2827 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2828 #ifdef YYTRACKMAXSTACKDEPTH
2829 displayStatLine(pArg, "Deepest Parser Stack:",
2830 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2831 #endif
2833 if( db ){
2834 if( pArg->shellFlgs & SHFLG_Lookaside ){
2835 iHiwtr = iCur = -1;
2836 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2837 &iCur, &iHiwtr, bReset);
2838 raw_printf(pArg->out,
2839 "Lookaside Slots Used: %d (max %d)\n",
2840 iCur, iHiwtr);
2841 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2842 &iCur, &iHiwtr, bReset);
2843 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2844 iHiwtr);
2845 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2846 &iCur, &iHiwtr, bReset);
2847 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2848 iHiwtr);
2849 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2850 &iCur, &iHiwtr, bReset);
2851 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2852 iHiwtr);
2854 iHiwtr = iCur = -1;
2855 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2856 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2857 iCur);
2858 iHiwtr = iCur = -1;
2859 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2860 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2861 iHiwtr = iCur = -1;
2862 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2863 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2864 iHiwtr = iCur = -1;
2865 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2866 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2867 iHiwtr = iCur = -1;
2868 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2869 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2870 iHiwtr = iCur = -1;
2871 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2872 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2873 iCur);
2874 iHiwtr = iCur = -1;
2875 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2876 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2877 iCur);
2880 if( pArg->pStmt ){
2881 int iHit, iMiss;
2882 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2883 bReset);
2884 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2885 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2886 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2887 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2888 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2889 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2890 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2891 if( iHit || iMiss ){
2892 raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n",
2893 iHit, iHit+iMiss);
2895 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2896 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2897 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2898 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2899 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2900 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2901 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2902 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
2905 #ifdef __linux__
2906 displayLinuxIoStats(pArg->out);
2907 #endif
2909 /* Do not remove this machine readable comment: extra-stats-output-here */
2911 return 0;
2915 ** Display scan stats.
2917 static void display_scanstats(
2918 sqlite3 *db, /* Database to query */
2919 ShellState *pArg /* Pointer to ShellState */
2921 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2922 UNUSED_PARAMETER(db);
2923 UNUSED_PARAMETER(pArg);
2924 #else
2925 int i, k, n, mx;
2926 raw_printf(pArg->out, "-------- scanstats --------\n");
2927 mx = 0;
2928 for(k=0; k<=mx; k++){
2929 double rEstLoop = 1.0;
2930 for(i=n=0; 1; i++){
2931 sqlite3_stmt *p = pArg->pStmt;
2932 sqlite3_int64 nLoop, nVisit;
2933 double rEst;
2934 int iSid;
2935 const char *zExplain;
2936 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2937 break;
2939 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2940 if( iSid>mx ) mx = iSid;
2941 if( iSid!=k ) continue;
2942 if( n==0 ){
2943 rEstLoop = (double)nLoop;
2944 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2946 n++;
2947 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2948 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2949 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2950 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2951 rEstLoop *= rEst;
2952 raw_printf(pArg->out,
2953 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2954 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2958 raw_printf(pArg->out, "---------------------------\n");
2959 #endif
2963 ** Parameter azArray points to a zero-terminated array of strings. zStr
2964 ** points to a single nul-terminated string. Return non-zero if zStr
2965 ** is equal, according to strcmp(), to any of the strings in the array.
2966 ** Otherwise, return zero.
2968 static int str_in_array(const char *zStr, const char **azArray){
2969 int i;
2970 for(i=0; azArray[i]; i++){
2971 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2973 return 0;
2977 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2978 ** and populate the ShellState.aiIndent[] array with the number of
2979 ** spaces each opcode should be indented before it is output.
2981 ** The indenting rules are:
2983 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2984 ** all opcodes that occur between the p2 jump destination and the opcode
2985 ** itself by 2 spaces.
2987 ** * Do the previous for "Return" instructions for when P2 is positive.
2988 ** See tag-20220407a in wherecode.c and vdbe.c.
2990 ** * For each "Goto", if the jump destination is earlier in the program
2991 ** and ends on one of:
2992 ** Yield SeekGt SeekLt RowSetRead Rewind
2993 ** or if the P1 parameter is one instead of zero,
2994 ** then indent all opcodes between the earlier instruction
2995 ** and "Goto" by 2 spaces.
2997 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2998 const char *zSql; /* The text of the SQL statement */
2999 const char *z; /* Used to check if this is an EXPLAIN */
3000 int *abYield = 0; /* True if op is an OP_Yield */
3001 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
3002 int iOp; /* Index of operation in p->aiIndent[] */
3004 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3005 "Return", 0 };
3006 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3007 "Rewind", 0 };
3008 const char *azGoto[] = { "Goto", 0 };
3010 /* Try to figure out if this is really an EXPLAIN statement. If this
3011 ** cannot be verified, return early. */
3012 if( sqlite3_column_count(pSql)!=8 ){
3013 p->cMode = p->mode;
3014 return;
3016 zSql = sqlite3_sql(pSql);
3017 if( zSql==0 ) return;
3018 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3019 if( sqlite3_strnicmp(z, "explain", 7) ){
3020 p->cMode = p->mode;
3021 return;
3024 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3025 int i;
3026 int iAddr = sqlite3_column_int(pSql, 0);
3027 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3029 /* Set p2 to the P2 field of the current opcode. Then, assuming that
3030 ** p2 is an instruction address, set variable p2op to the index of that
3031 ** instruction in the aiIndent[] array. p2 and p2op may be different if
3032 ** the current instruction is part of a sub-program generated by an
3033 ** SQL trigger or foreign key. */
3034 int p2 = sqlite3_column_int(pSql, 3);
3035 int p2op = (p2 + (iOp-iAddr));
3037 /* Grow the p->aiIndent array as required */
3038 if( iOp>=nAlloc ){
3039 if( iOp==0 ){
3040 /* Do further verfication that this is explain output. Abort if
3041 ** it is not */
3042 static const char *explainCols[] = {
3043 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3044 int jj;
3045 for(jj=0; jj<ArraySize(explainCols); jj++){
3046 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3047 p->cMode = p->mode;
3048 sqlite3_reset(pSql);
3049 return;
3053 nAlloc += 100;
3054 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3055 shell_check_oom(p->aiIndent);
3056 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3057 shell_check_oom(abYield);
3059 abYield[iOp] = str_in_array(zOp, azYield);
3060 p->aiIndent[iOp] = 0;
3061 p->nIndent = iOp+1;
3063 if( str_in_array(zOp, azNext) && p2op>0 ){
3064 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3066 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3067 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3069 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3073 p->iIndent = 0;
3074 sqlite3_free(abYield);
3075 sqlite3_reset(pSql);
3079 ** Free the array allocated by explain_data_prepare().
3081 static void explain_data_delete(ShellState *p){
3082 sqlite3_free(p->aiIndent);
3083 p->aiIndent = 0;
3084 p->nIndent = 0;
3085 p->iIndent = 0;
3089 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3091 static unsigned int savedSelectTrace;
3092 static unsigned int savedWhereTrace;
3093 static void disable_debug_trace_modes(void){
3094 unsigned int zero = 0;
3095 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3096 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3097 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3098 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3100 static void restore_debug_trace_modes(void){
3101 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3102 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3105 /* Create the TEMP table used to store parameter bindings */
3106 static void bind_table_init(ShellState *p){
3107 int wrSchema = 0;
3108 int defensiveMode = 0;
3109 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3110 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3111 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3112 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3113 sqlite3_exec(p->db,
3114 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3115 " key TEXT PRIMARY KEY,\n"
3116 " value\n"
3117 ") WITHOUT ROWID;",
3118 0, 0, 0);
3119 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3120 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3124 ** Bind parameters on a prepared statement.
3126 ** Parameter bindings are taken from a TEMP table of the form:
3128 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3129 ** WITHOUT ROWID;
3131 ** No bindings occur if this table does not exist. The name of the table
3132 ** begins with "sqlite_" so that it will not collide with ordinary application
3133 ** tables. The table must be in the TEMP schema.
3135 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3136 int nVar;
3137 int i;
3138 int rc;
3139 sqlite3_stmt *pQ = 0;
3141 nVar = sqlite3_bind_parameter_count(pStmt);
3142 if( nVar==0 ) return; /* Nothing to do */
3143 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3144 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3145 return; /* Parameter table does not exist */
3147 rc = sqlite3_prepare_v2(pArg->db,
3148 "SELECT value FROM temp.sqlite_parameters"
3149 " WHERE key=?1", -1, &pQ, 0);
3150 if( rc || pQ==0 ) return;
3151 for(i=1; i<=nVar; i++){
3152 char zNum[30];
3153 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3154 if( zVar==0 ){
3155 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3156 zVar = zNum;
3158 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3159 if( sqlite3_step(pQ)==SQLITE_ROW ){
3160 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3161 }else{
3162 sqlite3_bind_null(pStmt, i);
3164 sqlite3_reset(pQ);
3166 sqlite3_finalize(pQ);
3170 ** UTF8 box-drawing characters. Imagine box lines like this:
3172 ** 1
3173 ** |
3174 ** 4 --+-- 2
3175 ** |
3176 ** 3
3178 ** Each box characters has between 2 and 4 of the lines leading from
3179 ** the center. The characters are here identified by the numbers of
3180 ** their corresponding lines.
3182 #define BOX_24 "\342\224\200" /* U+2500 --- */
3183 #define BOX_13 "\342\224\202" /* U+2502 | */
3184 #define BOX_23 "\342\224\214" /* U+250c ,- */
3185 #define BOX_34 "\342\224\220" /* U+2510 -, */
3186 #define BOX_12 "\342\224\224" /* U+2514 '- */
3187 #define BOX_14 "\342\224\230" /* U+2518 -' */
3188 #define BOX_123 "\342\224\234" /* U+251c |- */
3189 #define BOX_134 "\342\224\244" /* U+2524 -| */
3190 #define BOX_234 "\342\224\254" /* U+252c -,- */
3191 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3192 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3194 /* Draw horizontal line N characters long using unicode box
3195 ** characters
3197 static void print_box_line(FILE *out, int N){
3198 const char zDash[] =
3199 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3200 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3201 const int nDash = sizeof(zDash) - 1;
3202 N *= 3;
3203 while( N>nDash ){
3204 utf8_printf(out, zDash);
3205 N -= nDash;
3207 utf8_printf(out, "%.*s", N, zDash);
3211 ** Draw a horizontal separator for a MODE_Box table.
3213 static void print_box_row_separator(
3214 ShellState *p,
3215 int nArg,
3216 const char *zSep1,
3217 const char *zSep2,
3218 const char *zSep3
3220 int i;
3221 if( nArg>0 ){
3222 utf8_printf(p->out, "%s", zSep1);
3223 print_box_line(p->out, p->actualWidth[0]+2);
3224 for(i=1; i<nArg; i++){
3225 utf8_printf(p->out, "%s", zSep2);
3226 print_box_line(p->out, p->actualWidth[i]+2);
3228 utf8_printf(p->out, "%s", zSep3);
3230 fputs("\n", p->out);
3234 ** z[] is a line of text that is to be displayed the .mode box or table or
3235 ** similar tabular formats. z[] might contain control characters such
3236 ** as \n, \t, \f, or \r.
3238 ** Compute characters to display on the first line of z[]. Stop at the
3239 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3240 ** from malloc()) of that first line, which caller should free sometime.
3241 ** Write anything to display on the next line into *pzTail. If this is
3242 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3244 static char *translateForDisplayAndDup(
3245 const unsigned char *z, /* Input text to be transformed */
3246 const unsigned char **pzTail, /* OUT: Tail of the input for next line */
3247 int mxWidth, /* Max width. 0 means no limit */
3248 u8 bWordWrap /* If true, avoid breaking mid-word */
3250 int i; /* Input bytes consumed */
3251 int j; /* Output bytes generated */
3252 int k; /* Input bytes to be displayed */
3253 int n; /* Output column number */
3254 unsigned char *zOut; /* Output text */
3256 if( z==0 ){
3257 *pzTail = 0;
3258 return 0;
3260 if( mxWidth<0 ) mxWidth = -mxWidth;
3261 if( mxWidth==0 ) mxWidth = 1000000;
3262 i = j = n = 0;
3263 while( n<mxWidth ){
3264 if( z[i]>=' ' ){
3265 n++;
3266 do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3267 continue;
3269 if( z[i]=='\t' ){
3271 n++;
3272 j++;
3273 }while( (n&7)!=0 && n<mxWidth );
3274 i++;
3275 continue;
3277 break;
3279 if( n>=mxWidth && bWordWrap ){
3280 /* Perhaps try to back up to a better place to break the line */
3281 for(k=i; k>i/2; k--){
3282 if( isspace(z[k-1]) ) break;
3284 if( k<=i/2 ){
3285 for(k=i; k>i/2; k--){
3286 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3289 if( k<=i/2 ){
3290 k = i;
3291 }else{
3292 i = k;
3293 while( z[i]==' ' ) i++;
3295 }else{
3296 k = i;
3298 if( n>=mxWidth && z[i]>=' ' ){
3299 *pzTail = &z[i];
3300 }else if( z[i]=='\r' && z[i+1]=='\n' ){
3301 *pzTail = z[i+2] ? &z[i+2] : 0;
3302 }else if( z[i]==0 || z[i+1]==0 ){
3303 *pzTail = 0;
3304 }else{
3305 *pzTail = &z[i+1];
3307 zOut = malloc( j+1 );
3308 shell_check_oom(zOut);
3309 i = j = n = 0;
3310 while( i<k ){
3311 if( z[i]>=' ' ){
3312 n++;
3313 do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3314 continue;
3316 if( z[i]=='\t' ){
3318 n++;
3319 zOut[j++] = ' ';
3320 }while( (n&7)!=0 && n<mxWidth );
3321 i++;
3322 continue;
3324 break;
3326 zOut[j] = 0;
3327 return (char*)zOut;
3330 /* Extract the value of the i-th current column for pStmt as an SQL literal
3331 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3332 ** the caller.
3334 static char *quoted_column(sqlite3_stmt *pStmt, int i){
3335 switch( sqlite3_column_type(pStmt, i) ){
3336 case SQLITE_NULL: {
3337 return sqlite3_mprintf("NULL");
3339 case SQLITE_INTEGER:
3340 case SQLITE_FLOAT: {
3341 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3343 case SQLITE_TEXT: {
3344 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3346 case SQLITE_BLOB: {
3347 int j;
3348 sqlite3_str *pStr = sqlite3_str_new(0);
3349 const unsigned char *a = sqlite3_column_blob(pStmt,i);
3350 int n = sqlite3_column_bytes(pStmt,i);
3351 sqlite3_str_append(pStr, "x'", 2);
3352 for(j=0; j<n; j++){
3353 sqlite3_str_appendf(pStr, "%02x", a[j]);
3355 sqlite3_str_append(pStr, "'", 1);
3356 return sqlite3_str_finish(pStr);
3359 return 0; /* Not reached */
3363 ** Run a prepared statement and output the result in one of the
3364 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3365 ** or MODE_Box.
3367 ** This is different from ordinary exec_prepared_stmt() in that
3368 ** it has to run the entire query and gather the results into memory
3369 ** first, in order to determine column widths, before providing
3370 ** any output.
3372 static void exec_prepared_stmt_columnar(
3373 ShellState *p, /* Pointer to ShellState */
3374 sqlite3_stmt *pStmt /* Statment to run */
3376 sqlite3_int64 nRow = 0;
3377 int nColumn = 0;
3378 char **azData = 0;
3379 sqlite3_int64 nAlloc = 0;
3380 char *abRowDiv = 0;
3381 const unsigned char *uz;
3382 const char *z;
3383 char **azQuoted = 0;
3384 int rc;
3385 sqlite3_int64 i, nData;
3386 int j, nTotal, w, n;
3387 const char *colSep = 0;
3388 const char *rowSep = 0;
3389 const unsigned char **azNextLine = 0;
3390 int bNextLine = 0;
3391 int bMultiLineRowExists = 0;
3392 int bw = p->cmOpts.bWordWrap;
3393 const char *zEmpty = "";
3394 const char *zShowNull = p->nullValue;
3396 rc = sqlite3_step(pStmt);
3397 if( rc!=SQLITE_ROW ) return;
3398 nColumn = sqlite3_column_count(pStmt);
3399 nAlloc = nColumn*4;
3400 if( nAlloc<=0 ) nAlloc = 1;
3401 azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3402 shell_check_oom(azData);
3403 azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3404 shell_check_oom((void*)azNextLine);
3405 memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3406 if( p->cmOpts.bQuote ){
3407 azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3408 shell_check_oom(azQuoted);
3409 memset(azQuoted, 0, nColumn*sizeof(char*) );
3411 abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3412 shell_check_oom(abRowDiv);
3413 if( nColumn>p->nWidth ){
3414 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3415 shell_check_oom(p->colWidth);
3416 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3417 p->nWidth = nColumn;
3418 p->actualWidth = &p->colWidth[nColumn];
3420 memset(p->actualWidth, 0, nColumn*sizeof(int));
3421 for(i=0; i<nColumn; i++){
3422 w = p->colWidth[i];
3423 if( w<0 ) w = -w;
3424 p->actualWidth[i] = w;
3426 for(i=0; i<nColumn; i++){
3427 const unsigned char *zNotUsed;
3428 int wx = p->colWidth[i];
3429 if( wx==0 ){
3430 wx = p->cmOpts.iWrap;
3432 if( wx<0 ) wx = -wx;
3433 uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3434 azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3437 int useNextLine = bNextLine;
3438 bNextLine = 0;
3439 if( (nRow+2)*nColumn >= nAlloc ){
3440 nAlloc *= 2;
3441 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3442 shell_check_oom(azData);
3443 abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3444 shell_check_oom(abRowDiv);
3446 abRowDiv[nRow] = 1;
3447 nRow++;
3448 for(i=0; i<nColumn; i++){
3449 int wx = p->colWidth[i];
3450 if( wx==0 ){
3451 wx = p->cmOpts.iWrap;
3453 if( wx<0 ) wx = -wx;
3454 if( useNextLine ){
3455 uz = azNextLine[i];
3456 if( uz==0 ) uz = (u8*)zEmpty;
3457 }else if( p->cmOpts.bQuote ){
3458 sqlite3_free(azQuoted[i]);
3459 azQuoted[i] = quoted_column(pStmt,i);
3460 uz = (const unsigned char*)azQuoted[i];
3461 }else{
3462 uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3463 if( uz==0 ) uz = (u8*)zShowNull;
3465 azData[nRow*nColumn + i]
3466 = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3467 if( azNextLine[i] ){
3468 bNextLine = 1;
3469 abRowDiv[nRow-1] = 0;
3470 bMultiLineRowExists = 1;
3473 }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3474 nTotal = nColumn*(nRow+1);
3475 for(i=0; i<nTotal; i++){
3476 z = azData[i];
3477 if( z==0 ) z = (char*)zEmpty;
3478 n = strlenChar(z);
3479 j = i%nColumn;
3480 if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3482 if( seenInterrupt ) goto columnar_end;
3483 if( nColumn==0 ) goto columnar_end;
3484 switch( p->cMode ){
3485 case MODE_Column: {
3486 colSep = " ";
3487 rowSep = "\n";
3488 if( p->showHeader ){
3489 for(i=0; i<nColumn; i++){
3490 w = p->actualWidth[i];
3491 if( p->colWidth[i]<0 ) w = -w;
3492 utf8_width_print(p->out, w, azData[i]);
3493 fputs(i==nColumn-1?"\n":" ", p->out);
3495 for(i=0; i<nColumn; i++){
3496 print_dashes(p->out, p->actualWidth[i]);
3497 fputs(i==nColumn-1?"\n":" ", p->out);
3500 break;
3502 case MODE_Table: {
3503 colSep = " | ";
3504 rowSep = " |\n";
3505 print_row_separator(p, nColumn, "+");
3506 fputs("| ", p->out);
3507 for(i=0; i<nColumn; i++){
3508 w = p->actualWidth[i];
3509 n = strlenChar(azData[i]);
3510 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3511 fputs(i==nColumn-1?" |\n":" | ", p->out);
3513 print_row_separator(p, nColumn, "+");
3514 break;
3516 case MODE_Markdown: {
3517 colSep = " | ";
3518 rowSep = " |\n";
3519 fputs("| ", p->out);
3520 for(i=0; i<nColumn; i++){
3521 w = p->actualWidth[i];
3522 n = strlenChar(azData[i]);
3523 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3524 fputs(i==nColumn-1?" |\n":" | ", p->out);
3526 print_row_separator(p, nColumn, "|");
3527 break;
3529 case MODE_Box: {
3530 colSep = " " BOX_13 " ";
3531 rowSep = " " BOX_13 "\n";
3532 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3533 utf8_printf(p->out, BOX_13 " ");
3534 for(i=0; i<nColumn; i++){
3535 w = p->actualWidth[i];
3536 n = strlenChar(azData[i]);
3537 utf8_printf(p->out, "%*s%s%*s%s",
3538 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3539 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3541 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3542 break;
3545 for(i=nColumn, j=0; i<nTotal; i++, j++){
3546 if( j==0 && p->cMode!=MODE_Column ){
3547 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3549 z = azData[i];
3550 if( z==0 ) z = p->nullValue;
3551 w = p->actualWidth[j];
3552 if( p->colWidth[j]<0 ) w = -w;
3553 utf8_width_print(p->out, w, z);
3554 if( j==nColumn-1 ){
3555 utf8_printf(p->out, "%s", rowSep);
3556 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3557 if( p->cMode==MODE_Table ){
3558 print_row_separator(p, nColumn, "+");
3559 }else if( p->cMode==MODE_Box ){
3560 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3561 }else if( p->cMode==MODE_Column ){
3562 raw_printf(p->out, "\n");
3565 j = -1;
3566 if( seenInterrupt ) goto columnar_end;
3567 }else{
3568 utf8_printf(p->out, "%s", colSep);
3571 if( p->cMode==MODE_Table ){
3572 print_row_separator(p, nColumn, "+");
3573 }else if( p->cMode==MODE_Box ){
3574 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3576 columnar_end:
3577 if( seenInterrupt ){
3578 utf8_printf(p->out, "Interrupt\n");
3580 nData = (nRow+1)*nColumn;
3581 for(i=0; i<nData; i++){
3582 z = azData[i];
3583 if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3585 sqlite3_free(azData);
3586 sqlite3_free((void*)azNextLine);
3587 sqlite3_free(abRowDiv);
3588 if( azQuoted ){
3589 for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3590 sqlite3_free(azQuoted);
3595 ** Run a prepared statement
3597 static void exec_prepared_stmt(
3598 ShellState *pArg, /* Pointer to ShellState */
3599 sqlite3_stmt *pStmt /* Statment to run */
3601 int rc;
3602 sqlite3_uint64 nRow = 0;
3604 if( pArg->cMode==MODE_Column
3605 || pArg->cMode==MODE_Table
3606 || pArg->cMode==MODE_Box
3607 || pArg->cMode==MODE_Markdown
3609 exec_prepared_stmt_columnar(pArg, pStmt);
3610 return;
3613 /* perform the first step. this will tell us if we
3614 ** have a result set or not and how wide it is.
3616 rc = sqlite3_step(pStmt);
3617 /* if we have a result set... */
3618 if( SQLITE_ROW == rc ){
3619 /* allocate space for col name ptr, value ptr, and type */
3620 int nCol = sqlite3_column_count(pStmt);
3621 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3622 if( !pData ){
3623 shell_out_of_memory();
3624 }else{
3625 char **azCols = (char **)pData; /* Names of result columns */
3626 char **azVals = &azCols[nCol]; /* Results */
3627 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3628 int i, x;
3629 assert(sizeof(int) <= sizeof(char *));
3630 /* save off ptrs to column names */
3631 for(i=0; i<nCol; i++){
3632 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3635 nRow++;
3636 /* extract the data and data types */
3637 for(i=0; i<nCol; i++){
3638 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3639 if( x==SQLITE_BLOB
3640 && pArg
3641 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3643 azVals[i] = "";
3644 }else{
3645 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3647 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3648 rc = SQLITE_NOMEM;
3649 break; /* from for */
3651 } /* end for */
3653 /* if data and types extracted successfully... */
3654 if( SQLITE_ROW == rc ){
3655 /* call the supplied callback with the result row data */
3656 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3657 rc = SQLITE_ABORT;
3658 }else{
3659 rc = sqlite3_step(pStmt);
3662 } while( SQLITE_ROW == rc );
3663 sqlite3_free(pData);
3664 if( pArg->cMode==MODE_Json ){
3665 fputs("]\n", pArg->out);
3666 }else if( pArg->cMode==MODE_Count ){
3667 char zBuf[200];
3668 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3669 nRow, nRow!=1 ? "s" : "");
3670 printf("%s", zBuf);
3676 #ifndef SQLITE_OMIT_VIRTUALTABLE
3678 ** This function is called to process SQL if the previous shell command
3679 ** was ".expert". It passes the SQL in the second argument directly to
3680 ** the sqlite3expert object.
3682 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3683 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3684 ** an English language error message. It is the responsibility of the
3685 ** caller to eventually free this buffer using sqlite3_free().
3687 static int expertHandleSQL(
3688 ShellState *pState,
3689 const char *zSql,
3690 char **pzErr
3692 assert( pState->expert.pExpert );
3693 assert( pzErr==0 || *pzErr==0 );
3694 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3698 ** This function is called either to silently clean up the object
3699 ** created by the ".expert" command (if bCancel==1), or to generate a
3700 ** report from it and then clean it up (if bCancel==0).
3702 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3703 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3704 ** an English language error message. It is the responsibility of the
3705 ** caller to eventually free this buffer using sqlite3_free().
3707 static int expertFinish(
3708 ShellState *pState,
3709 int bCancel,
3710 char **pzErr
3712 int rc = SQLITE_OK;
3713 sqlite3expert *p = pState->expert.pExpert;
3714 assert( p );
3715 assert( bCancel || pzErr==0 || *pzErr==0 );
3716 if( bCancel==0 ){
3717 FILE *out = pState->out;
3718 int bVerbose = pState->expert.bVerbose;
3720 rc = sqlite3_expert_analyze(p, pzErr);
3721 if( rc==SQLITE_OK ){
3722 int nQuery = sqlite3_expert_count(p);
3723 int i;
3725 if( bVerbose ){
3726 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3727 raw_printf(out, "-- Candidates -----------------------------\n");
3728 raw_printf(out, "%s\n", zCand);
3730 for(i=0; i<nQuery; i++){
3731 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3732 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3733 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3734 if( zIdx==0 ) zIdx = "(no new indexes)\n";
3735 if( bVerbose ){
3736 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3737 raw_printf(out, "%s\n\n", zSql);
3739 raw_printf(out, "%s\n", zIdx);
3740 raw_printf(out, "%s\n", zEQP);
3744 sqlite3_expert_destroy(p);
3745 pState->expert.pExpert = 0;
3746 return rc;
3750 ** Implementation of ".expert" dot command.
3752 static int expertDotCommand(
3753 ShellState *pState, /* Current shell tool state */
3754 char **azArg, /* Array of arguments passed to dot command */
3755 int nArg /* Number of entries in azArg[] */
3757 int rc = SQLITE_OK;
3758 char *zErr = 0;
3759 int i;
3760 int iSample = 0;
3762 assert( pState->expert.pExpert==0 );
3763 memset(&pState->expert, 0, sizeof(ExpertInfo));
3765 for(i=1; rc==SQLITE_OK && i<nArg; i++){
3766 char *z = azArg[i];
3767 int n;
3768 if( z[0]=='-' && z[1]=='-' ) z++;
3769 n = strlen30(z);
3770 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3771 pState->expert.bVerbose = 1;
3773 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3774 if( i==(nArg-1) ){
3775 raw_printf(stderr, "option requires an argument: %s\n", z);
3776 rc = SQLITE_ERROR;
3777 }else{
3778 iSample = (int)integerValue(azArg[++i]);
3779 if( iSample<0 || iSample>100 ){
3780 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3781 rc = SQLITE_ERROR;
3785 else{
3786 raw_printf(stderr, "unknown option: %s\n", z);
3787 rc = SQLITE_ERROR;
3791 if( rc==SQLITE_OK ){
3792 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3793 if( pState->expert.pExpert==0 ){
3794 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3795 rc = SQLITE_ERROR;
3796 }else{
3797 sqlite3_expert_config(
3798 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3802 sqlite3_free(zErr);
3804 return rc;
3806 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3809 ** Execute a statement or set of statements. Print
3810 ** any result rows/columns depending on the current mode
3811 ** set via the supplied callback.
3813 ** This is very similar to SQLite's built-in sqlite3_exec()
3814 ** function except it takes a slightly different callback
3815 ** and callback data argument.
3817 static int shell_exec(
3818 ShellState *pArg, /* Pointer to ShellState */
3819 const char *zSql, /* SQL to be evaluated */
3820 char **pzErrMsg /* Error msg written here */
3822 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3823 int rc = SQLITE_OK; /* Return Code */
3824 int rc2;
3825 const char *zLeftover; /* Tail of unprocessed SQL */
3826 sqlite3 *db = pArg->db;
3828 if( pzErrMsg ){
3829 *pzErrMsg = NULL;
3832 #ifndef SQLITE_OMIT_VIRTUALTABLE
3833 if( pArg->expert.pExpert ){
3834 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3835 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3837 #endif
3839 while( zSql[0] && (SQLITE_OK == rc) ){
3840 static const char *zStmtSql;
3841 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3842 if( SQLITE_OK != rc ){
3843 if( pzErrMsg ){
3844 *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3846 }else{
3847 if( !pStmt ){
3848 /* this happens for a comment or white-space */
3849 zSql = zLeftover;
3850 while( IsSpace(zSql[0]) ) zSql++;
3851 continue;
3853 zStmtSql = sqlite3_sql(pStmt);
3854 if( zStmtSql==0 ) zStmtSql = "";
3855 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3857 /* save off the prepared statment handle and reset row count */
3858 if( pArg ){
3859 pArg->pStmt = pStmt;
3860 pArg->cnt = 0;
3863 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3864 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3865 sqlite3_stmt *pExplain;
3866 char *zEQP;
3867 int triggerEQP = 0;
3868 disable_debug_trace_modes();
3869 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3870 if( pArg->autoEQP>=AUTOEQP_trigger ){
3871 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3873 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3874 shell_check_oom(zEQP);
3875 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3876 if( rc==SQLITE_OK ){
3877 while( sqlite3_step(pExplain)==SQLITE_ROW ){
3878 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3879 int iEqpId = sqlite3_column_int(pExplain, 0);
3880 int iParentId = sqlite3_column_int(pExplain, 1);
3881 if( zEQPLine==0 ) zEQPLine = "";
3882 if( zEQPLine[0]=='-' ) eqp_render(pArg);
3883 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3885 eqp_render(pArg);
3887 sqlite3_finalize(pExplain);
3888 sqlite3_free(zEQP);
3889 if( pArg->autoEQP>=AUTOEQP_full ){
3890 /* Also do an EXPLAIN for ".eqp full" mode */
3891 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3892 shell_check_oom(zEQP);
3893 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3894 if( rc==SQLITE_OK ){
3895 pArg->cMode = MODE_Explain;
3896 explain_data_prepare(pArg, pExplain);
3897 exec_prepared_stmt(pArg, pExplain);
3898 explain_data_delete(pArg);
3900 sqlite3_finalize(pExplain);
3901 sqlite3_free(zEQP);
3903 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3904 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3905 /* Reprepare pStmt before reactiving trace modes */
3906 sqlite3_finalize(pStmt);
3907 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3908 if( pArg ) pArg->pStmt = pStmt;
3910 restore_debug_trace_modes();
3913 if( pArg ){
3914 pArg->cMode = pArg->mode;
3915 if( pArg->autoExplain ){
3916 if( sqlite3_stmt_isexplain(pStmt)==1 ){
3917 pArg->cMode = MODE_Explain;
3919 if( sqlite3_stmt_isexplain(pStmt)==2 ){
3920 pArg->cMode = MODE_EQP;
3924 /* If the shell is currently in ".explain" mode, gather the extra
3925 ** data required to add indents to the output.*/
3926 if( pArg->cMode==MODE_Explain ){
3927 explain_data_prepare(pArg, pStmt);
3931 bind_prepared_stmt(pArg, pStmt);
3932 exec_prepared_stmt(pArg, pStmt);
3933 explain_data_delete(pArg);
3934 eqp_render(pArg);
3936 /* print usage stats if stats on */
3937 if( pArg && pArg->statsOn ){
3938 display_stats(db, pArg, 0);
3941 /* print loop-counters if required */
3942 if( pArg && pArg->scanstatsOn ){
3943 display_scanstats(db, pArg);
3946 /* Finalize the statement just executed. If this fails, save a
3947 ** copy of the error message. Otherwise, set zSql to point to the
3948 ** next statement to execute. */
3949 rc2 = sqlite3_finalize(pStmt);
3950 if( rc!=SQLITE_NOMEM ) rc = rc2;
3951 if( rc==SQLITE_OK ){
3952 zSql = zLeftover;
3953 while( IsSpace(zSql[0]) ) zSql++;
3954 }else if( pzErrMsg ){
3955 *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3958 /* clear saved stmt handle */
3959 if( pArg ){
3960 pArg->pStmt = NULL;
3963 } /* end while */
3965 return rc;
3969 ** Release memory previously allocated by tableColumnList().
3971 static void freeColumnList(char **azCol){
3972 int i;
3973 for(i=1; azCol[i]; i++){
3974 sqlite3_free(azCol[i]);
3976 /* azCol[0] is a static string */
3977 sqlite3_free(azCol);
3981 ** Return a list of pointers to strings which are the names of all
3982 ** columns in table zTab. The memory to hold the names is dynamically
3983 ** allocated and must be released by the caller using a subsequent call
3984 ** to freeColumnList().
3986 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3987 ** value that needs to be preserved, then azCol[0] is filled in with the
3988 ** name of the rowid column.
3990 ** The first regular column in the table is azCol[1]. The list is terminated
3991 ** by an entry with azCol[i]==0.
3993 static char **tableColumnList(ShellState *p, const char *zTab){
3994 char **azCol = 0;
3995 sqlite3_stmt *pStmt;
3996 char *zSql;
3997 int nCol = 0;
3998 int nAlloc = 0;
3999 int nPK = 0; /* Number of PRIMARY KEY columns seen */
4000 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
4001 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4002 int rc;
4004 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4005 shell_check_oom(zSql);
4006 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4007 sqlite3_free(zSql);
4008 if( rc ) return 0;
4009 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4010 if( nCol>=nAlloc-2 ){
4011 nAlloc = nAlloc*2 + nCol + 10;
4012 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4013 shell_check_oom(azCol);
4015 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4016 shell_check_oom(azCol[nCol]);
4017 if( sqlite3_column_int(pStmt, 5) ){
4018 nPK++;
4019 if( nPK==1
4020 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4021 "INTEGER")==0
4023 isIPK = 1;
4024 }else{
4025 isIPK = 0;
4029 sqlite3_finalize(pStmt);
4030 if( azCol==0 ) return 0;
4031 azCol[0] = 0;
4032 azCol[nCol+1] = 0;
4034 /* The decision of whether or not a rowid really needs to be preserved
4035 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4036 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4037 ** rowids on tables where the rowid is inaccessible because there are other
4038 ** columns in the table named "rowid", "_rowid_", and "oid".
4040 if( preserveRowid && isIPK ){
4041 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4042 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
4043 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4044 ** ROWID aliases. To distinguish these cases, check to see if
4045 ** there is a "pk" entry in "PRAGMA index_list". There will be
4046 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4048 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4049 " WHERE origin='pk'", zTab);
4050 shell_check_oom(zSql);
4051 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4052 sqlite3_free(zSql);
4053 if( rc ){
4054 freeColumnList(azCol);
4055 return 0;
4057 rc = sqlite3_step(pStmt);
4058 sqlite3_finalize(pStmt);
4059 preserveRowid = rc==SQLITE_ROW;
4061 if( preserveRowid ){
4062 /* Only preserve the rowid if we can find a name to use for the
4063 ** rowid */
4064 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4065 int i, j;
4066 for(j=0; j<3; j++){
4067 for(i=1; i<=nCol; i++){
4068 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4070 if( i>nCol ){
4071 /* At this point, we know that azRowid[j] is not the name of any
4072 ** ordinary column in the table. Verify that azRowid[j] is a valid
4073 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4074 ** tables will fail this last check */
4075 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4076 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4077 break;
4081 return azCol;
4085 ** Toggle the reverse_unordered_selects setting.
4087 static void toggleSelectOrder(sqlite3 *db){
4088 sqlite3_stmt *pStmt = 0;
4089 int iSetting = 0;
4090 char zStmt[100];
4091 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4092 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4093 iSetting = sqlite3_column_int(pStmt, 0);
4095 sqlite3_finalize(pStmt);
4096 sqlite3_snprintf(sizeof(zStmt), zStmt,
4097 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4098 sqlite3_exec(db, zStmt, 0, 0, 0);
4102 ** This is a different callback routine used for dumping the database.
4103 ** Each row received by this callback consists of a table name,
4104 ** the table type ("index" or "table") and SQL to create the table.
4105 ** This routine should print text sufficient to recreate the table.
4107 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4108 int rc;
4109 const char *zTable;
4110 const char *zType;
4111 const char *zSql;
4112 ShellState *p = (ShellState *)pArg;
4113 int dataOnly;
4114 int noSys;
4116 UNUSED_PARAMETER(azNotUsed);
4117 if( nArg!=3 || azArg==0 ) return 0;
4118 zTable = azArg[0];
4119 zType = azArg[1];
4120 zSql = azArg[2];
4121 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4122 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4124 if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4125 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4126 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4127 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4128 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4129 return 0;
4130 }else if( dataOnly ){
4131 /* no-op */
4132 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4133 char *zIns;
4134 if( !p->writableSchema ){
4135 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4136 p->writableSchema = 1;
4138 zIns = sqlite3_mprintf(
4139 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4140 "VALUES('table','%q','%q',0,'%q');",
4141 zTable, zTable, zSql);
4142 shell_check_oom(zIns);
4143 utf8_printf(p->out, "%s\n", zIns);
4144 sqlite3_free(zIns);
4145 return 0;
4146 }else{
4147 printSchemaLine(p->out, zSql, ";\n");
4150 if( strcmp(zType, "table")==0 ){
4151 ShellText sSelect;
4152 ShellText sTable;
4153 char **azCol;
4154 int i;
4155 char *savedDestTable;
4156 int savedMode;
4158 azCol = tableColumnList(p, zTable);
4159 if( azCol==0 ){
4160 p->nErr++;
4161 return 0;
4164 /* Always quote the table name, even if it appears to be pure ascii,
4165 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4166 initText(&sTable);
4167 appendText(&sTable, zTable, quoteChar(zTable));
4168 /* If preserving the rowid, add a column list after the table name.
4169 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4170 ** instead of the usual "INSERT INTO tab VALUES(...)".
4172 if( azCol[0] ){
4173 appendText(&sTable, "(", 0);
4174 appendText(&sTable, azCol[0], 0);
4175 for(i=1; azCol[i]; i++){
4176 appendText(&sTable, ",", 0);
4177 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4179 appendText(&sTable, ")", 0);
4182 /* Build an appropriate SELECT statement */
4183 initText(&sSelect);
4184 appendText(&sSelect, "SELECT ", 0);
4185 if( azCol[0] ){
4186 appendText(&sSelect, azCol[0], 0);
4187 appendText(&sSelect, ",", 0);
4189 for(i=1; azCol[i]; i++){
4190 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4191 if( azCol[i+1] ){
4192 appendText(&sSelect, ",", 0);
4195 freeColumnList(azCol);
4196 appendText(&sSelect, " FROM ", 0);
4197 appendText(&sSelect, zTable, quoteChar(zTable));
4199 savedDestTable = p->zDestTable;
4200 savedMode = p->mode;
4201 p->zDestTable = sTable.z;
4202 p->mode = p->cMode = MODE_Insert;
4203 rc = shell_exec(p, sSelect.z, 0);
4204 if( (rc&0xff)==SQLITE_CORRUPT ){
4205 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4206 toggleSelectOrder(p->db);
4207 shell_exec(p, sSelect.z, 0);
4208 toggleSelectOrder(p->db);
4210 p->zDestTable = savedDestTable;
4211 p->mode = savedMode;
4212 freeText(&sTable);
4213 freeText(&sSelect);
4214 if( rc ) p->nErr++;
4216 return 0;
4220 ** Run zQuery. Use dump_callback() as the callback routine so that
4221 ** the contents of the query are output as SQL statements.
4223 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4224 ** "ORDER BY rowid DESC" to the end.
4226 static int run_schema_dump_query(
4227 ShellState *p,
4228 const char *zQuery
4230 int rc;
4231 char *zErr = 0;
4232 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4233 if( rc==SQLITE_CORRUPT ){
4234 char *zQ2;
4235 int len = strlen30(zQuery);
4236 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4237 if( zErr ){
4238 utf8_printf(p->out, "/****** %s ******/\n", zErr);
4239 sqlite3_free(zErr);
4240 zErr = 0;
4242 zQ2 = malloc( len+100 );
4243 if( zQ2==0 ) return rc;
4244 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4245 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4246 if( rc ){
4247 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4248 }else{
4249 rc = SQLITE_CORRUPT;
4251 sqlite3_free(zErr);
4252 free(zQ2);
4254 return rc;
4258 ** Text of help messages.
4260 ** The help text for each individual command begins with a line that starts
4261 ** with ".". Subsequent lines are supplemental information.
4263 ** There must be two or more spaces between the end of the command and the
4264 ** start of the description of what that command does.
4266 static const char *(azHelp[]) = {
4267 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4268 && !defined(SQLITE_SHELL_WASM_MODE)
4269 ".archive ... Manage SQL archives",
4270 " Each command must have exactly one of the following options:",
4271 " -c, --create Create a new archive",
4272 " -u, --update Add or update files with changed mtime",
4273 " -i, --insert Like -u but always add even if unchanged",
4274 " -r, --remove Remove files from archive",
4275 " -t, --list List contents of archive",
4276 " -x, --extract Extract files from archive",
4277 " Optional arguments:",
4278 " -v, --verbose Print each filename as it is processed",
4279 " -f FILE, --file FILE Use archive FILE (default is current db)",
4280 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4281 " -C DIR, --directory DIR Read/extract files from directory DIR",
4282 " -g, --glob Use glob matching for names in archive",
4283 " -n, --dryrun Show the SQL that would have occurred",
4284 " Examples:",
4285 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4286 " .ar -tf ARCHIVE # List members of ARCHIVE",
4287 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4288 " See also:",
4289 " http://sqlite.org/cli.html#sqlite_archive_support",
4290 #endif
4291 #ifndef SQLITE_OMIT_AUTHORIZATION
4292 ".auth ON|OFF Show authorizer callbacks",
4293 #endif
4294 #ifndef SQLITE_SHELL_WASM_MODE
4295 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4296 " Options:",
4297 " --append Use the appendvfs",
4298 " --async Write to FILE without journal and fsync()",
4299 #endif
4300 ".bail on|off Stop after hitting an error. Default OFF",
4301 ".binary on|off Turn binary output on or off. Default OFF",
4302 #ifndef SQLITE_SHELL_WASM_MODE
4303 ".cd DIRECTORY Change the working directory to DIRECTORY",
4304 #endif
4305 ".changes on|off Show number of rows changed by SQL",
4306 #ifndef SQLITE_SHELL_WASM_MODE
4307 ".check GLOB Fail if output since .testcase does not match",
4308 ".clone NEWDB Clone data into NEWDB from the existing database",
4309 #endif
4310 ".connection [close] [#] Open or close an auxiliary database connection",
4311 ".databases List names and files of attached databases",
4312 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4313 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4314 ".dbinfo ?DB? Show status information about the database",
4315 #endif
4316 ".dump ?OBJECTS? Render database content as SQL",
4317 " Options:",
4318 " --data-only Output only INSERT statements",
4319 " --newlines Allow unescaped newline characters in output",
4320 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4321 " --preserve-rowids Include ROWID values in the output",
4322 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4323 " Additional LIKE patterns can be given in subsequent arguments",
4324 ".echo on|off Turn command echo on or off",
4325 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4326 " Other Modes:",
4327 #ifdef SQLITE_DEBUG
4328 " test Show raw EXPLAIN QUERY PLAN output",
4329 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4330 #endif
4331 " trigger Like \"full\" but also show trigger bytecode",
4332 #ifndef SQLITE_SHELL_WASM_MODE
4333 ".excel Display the output of next command in spreadsheet",
4334 " --bom Put a UTF8 byte-order mark on intermediate file",
4335 #endif
4336 #ifndef SQLITE_SHELL_WASM_MODE
4337 ".exit ?CODE? Exit this program with return-code CODE",
4338 #endif
4339 ".expert EXPERIMENTAL. Suggest indexes for queries",
4340 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4341 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4342 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4343 " --help Show CMD details",
4344 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4345 ".headers on|off Turn display of headers on or off",
4346 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4347 #ifndef SQLITE_SHELL_WASM_MODE
4348 ".import FILE TABLE Import data from FILE into TABLE",
4349 " Options:",
4350 " --ascii Use \\037 and \\036 as column and row separators",
4351 " --csv Use , and \\n as column and row separators",
4352 " --skip N Skip the first N rows of input",
4353 " --schema S Target table to be S.TABLE",
4354 " -v \"Verbose\" - increase auxiliary output",
4355 " Notes:",
4356 " * If TABLE does not exist, it is created. The first row of input",
4357 " determines the column names.",
4358 " * If neither --csv or --ascii are used, the input mode is derived",
4359 " from the \".mode\" output mode",
4360 " * If FILE begins with \"|\" then it is a command that generates the",
4361 " input text.",
4362 #endif
4363 #ifndef SQLITE_OMIT_TEST_CONTROL
4364 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4365 #endif
4366 ".indexes ?TABLE? Show names of indexes",
4367 " If TABLE is specified, only show indexes for",
4368 " tables matching TABLE using the LIKE operator.",
4369 #ifdef SQLITE_ENABLE_IOTRACE
4370 ".iotrace FILE Enable I/O diagnostic logging to FILE",
4371 #endif
4372 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4373 ".lint OPTIONS Report potential schema issues.",
4374 " Options:",
4375 " fkey-indexes Find missing foreign key indexes",
4376 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
4377 ".load FILE ?ENTRY? Load an extension library",
4378 #endif
4379 #ifndef SQLITE_SHELL_WASM_MODE
4380 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
4381 #endif
4382 ".mode MODE ?OPTIONS? Set output mode",
4383 " MODE is one of:",
4384 " ascii Columns/rows delimited by 0x1F and 0x1E",
4385 " box Tables using unicode box-drawing characters",
4386 " csv Comma-separated values",
4387 " column Output in columns. (See .width)",
4388 " html HTML <table> code",
4389 " insert SQL insert statements for TABLE",
4390 " json Results in a JSON array",
4391 " line One value per line",
4392 " list Values delimited by \"|\"",
4393 " markdown Markdown table format",
4394 " qbox Shorthand for \"box --width 60 --quote\"",
4395 " quote Escape answers as for SQL",
4396 " table ASCII-art table",
4397 " tabs Tab-separated values",
4398 " tcl TCL list elements",
4399 " OPTIONS: (for columnar modes or insert mode):",
4400 " --wrap N Wrap output lines to no longer than N characters",
4401 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4402 " --ww Shorthand for \"--wordwrap 1\"",
4403 " --quote Quote output text as SQL literals",
4404 " --noquote Do not quote output text",
4405 " TABLE The name of SQL table used for \"insert\" mode",
4406 #ifndef SQLITE_SHELL_WASM_MODE
4407 ".nonce STRING Suspend safe mode for one command if nonce matches",
4408 #endif
4409 ".nullvalue STRING Use STRING in place of NULL values",
4410 #ifndef SQLITE_SHELL_WASM_MODE
4411 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4412 " If FILE begins with '|' then open as a pipe",
4413 " --bom Put a UTF8 byte-order mark at the beginning",
4414 " -e Send output to the system text editor",
4415 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4416 /* Note that .open is (partially) available in WASM builds but is
4417 ** currently only intended to be used by the fiddle tool, not
4418 ** end users, so is "undocumented." */
4419 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4420 " Options:",
4421 " --append Use appendvfs to append database to the end of FILE",
4422 #endif
4423 #ifndef SQLITE_OMIT_DESERIALIZE
4424 " --deserialize Load into memory using sqlite3_deserialize()",
4425 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4426 " --maxsize N Maximum size for --hexdb or --deserialized database",
4427 #endif
4428 " --new Initialize FILE to an empty database",
4429 " --nofollow Do not follow symbolic links",
4430 " --readonly Open FILE readonly",
4431 " --zip FILE is a ZIP archive",
4432 #ifndef SQLITE_SHELL_WASM_MODE
4433 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4434 " If FILE begins with '|' then open it as a pipe.",
4435 " Options:",
4436 " --bom Prefix output with a UTF8 byte-order mark",
4437 " -e Send output to the system text editor",
4438 " -x Send output as CSV to a spreadsheet",
4439 #endif
4440 ".parameter CMD ... Manage SQL parameter bindings",
4441 " clear Erase all bindings",
4442 " init Initialize the TEMP table that holds bindings",
4443 " list List the current parameter bindings",
4444 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4445 " PARAMETER should start with one of: $ : @ ?",
4446 " unset PARAMETER Remove PARAMETER from the binding table",
4447 ".print STRING... Print literal STRING",
4448 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4449 ".progress N Invoke progress handler after every N opcodes",
4450 " --limit N Interrupt after N progress callbacks",
4451 " --once Do no more than one progress interrupt",
4452 " --quiet|-q No output except at interrupts",
4453 " --reset Reset the count for each input and interrupt",
4454 #endif
4455 ".prompt MAIN CONTINUE Replace the standard prompts",
4456 #ifndef SQLITE_SHELL_WASM_MODE
4457 ".quit Exit this program",
4458 ".read FILE Read input from FILE or command output",
4459 " If FILE begins with \"|\", it is a command that generates the input.",
4460 #endif
4461 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4462 ".recover Recover as much data as possible from corrupt db.",
4463 " --freelist-corrupt Assume the freelist is corrupt",
4464 " --recovery-db NAME Store recovery metadata in database file NAME",
4465 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4466 " --no-rowids Do not attempt to recover rowid values",
4467 " that are not also INTEGER PRIMARY KEYs",
4468 #endif
4469 #ifndef SQLITE_SHELL_WASM_MODE
4470 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4471 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4472 #endif
4473 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
4474 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4475 " Options:",
4476 " --indent Try to pretty-print the schema",
4477 " --nosys Omit objects whose names start with \"sqlite_\"",
4478 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4479 " Options:",
4480 " --init Create a new SELFTEST table",
4481 " -v Verbose output",
4482 ".separator COL ?ROW? Change the column and row separators",
4483 #if defined(SQLITE_ENABLE_SESSION)
4484 ".session ?NAME? CMD ... Create or control sessions",
4485 " Subcommands:",
4486 " attach TABLE Attach TABLE",
4487 " changeset FILE Write a changeset into FILE",
4488 " close Close one session",
4489 " enable ?BOOLEAN? Set or query the enable bit",
4490 " filter GLOB... Reject tables matching GLOBs",
4491 " indirect ?BOOLEAN? Mark or query the indirect status",
4492 " isempty Query whether the session is empty",
4493 " list List currently open session names",
4494 " open DB NAME Open a new session on DB",
4495 " patchset FILE Write a patchset into FILE",
4496 " If ?NAME? is omitted, the first defined session is used.",
4497 #endif
4498 ".sha3sum ... Compute a SHA3 hash of database content",
4499 " Options:",
4500 " --schema Also hash the sqlite_schema table",
4501 " --sha3-224 Use the sha3-224 algorithm",
4502 " --sha3-256 Use the sha3-256 algorithm (default)",
4503 " --sha3-384 Use the sha3-384 algorithm",
4504 " --sha3-512 Use the sha3-512 algorithm",
4505 " Any other argument is a LIKE pattern for tables to hash",
4506 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
4507 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4508 #endif
4509 ".show Show the current values for various settings",
4510 ".stats ?ARG? Show stats or turn stats on or off",
4511 " off Turn off automatic stat display",
4512 " on Turn on automatic stat display",
4513 " stmt Show statement stats",
4514 " vmstep Show the virtual machine step count only",
4515 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
4516 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4517 #endif
4518 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4519 #ifndef SQLITE_SHELL_WASM_MODE
4520 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
4521 #endif
4522 ".testctrl CMD ... Run various sqlite3_test_control() operations",
4523 " Run \".testctrl\" with no arguments for details",
4524 ".timeout MS Try opening locked tables for MS milliseconds",
4525 ".timer on|off Turn SQL timer on or off",
4526 #ifndef SQLITE_OMIT_TRACE
4527 ".trace ?OPTIONS? Output each SQL statement as it is run",
4528 " FILE Send output to FILE",
4529 " stdout Send output to stdout",
4530 " stderr Send output to stderr",
4531 " off Disable tracing",
4532 " --expanded Expand query parameters",
4533 #ifdef SQLITE_ENABLE_NORMALIZE
4534 " --normalized Normal the SQL statements",
4535 #endif
4536 " --plain Show SQL as it is input",
4537 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4538 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4539 " --row Trace each row (SQLITE_TRACE_ROW)",
4540 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4541 #endif /* SQLITE_OMIT_TRACE */
4542 #ifdef SQLITE_DEBUG
4543 ".unmodule NAME ... Unregister virtual table modules",
4544 " --allexcept Unregister everything except those named",
4545 #endif
4546 ".vfsinfo ?AUX? Information about the top-level VFS",
4547 ".vfslist List all available VFSes",
4548 ".vfsname ?AUX? Print the name of the VFS stack",
4549 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4550 " Negative values right-justify",
4554 ** Output help text.
4556 ** zPattern describes the set of commands for which help text is provided.
4557 ** If zPattern is NULL, then show all commands, but only give a one-line
4558 ** description of each.
4560 ** Return the number of matches.
4562 static int showHelp(FILE *out, const char *zPattern){
4563 int i = 0;
4564 int j = 0;
4565 int n = 0;
4566 char *zPat;
4567 if( zPattern==0
4568 || zPattern[0]=='0'
4569 || strcmp(zPattern,"-a")==0
4570 || strcmp(zPattern,"-all")==0
4571 || strcmp(zPattern,"--all")==0
4573 /* Show all commands, but only one line per command */
4574 if( zPattern==0 ) zPattern = "";
4575 for(i=0; i<ArraySize(azHelp); i++){
4576 if( azHelp[i][0]=='.' || zPattern[0] ){
4577 utf8_printf(out, "%s\n", azHelp[i]);
4578 n++;
4581 }else{
4582 /* Look for commands that for which zPattern is an exact prefix */
4583 zPat = sqlite3_mprintf(".%s*", zPattern);
4584 shell_check_oom(zPat);
4585 for(i=0; i<ArraySize(azHelp); i++){
4586 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4587 utf8_printf(out, "%s\n", azHelp[i]);
4588 j = i+1;
4589 n++;
4592 sqlite3_free(zPat);
4593 if( n ){
4594 if( n==1 ){
4595 /* when zPattern is a prefix of exactly one command, then include the
4596 ** details of that command, which should begin at offset j */
4597 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4598 utf8_printf(out, "%s\n", azHelp[j]);
4599 j++;
4602 return n;
4604 /* Look for commands that contain zPattern anywhere. Show the complete
4605 ** text of all commands that match. */
4606 zPat = sqlite3_mprintf("%%%s%%", zPattern);
4607 shell_check_oom(zPat);
4608 for(i=0; i<ArraySize(azHelp); i++){
4609 if( azHelp[i][0]=='.' ) j = i;
4610 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4611 utf8_printf(out, "%s\n", azHelp[j]);
4612 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4613 j++;
4614 utf8_printf(out, "%s\n", azHelp[j]);
4616 i = j;
4617 n++;
4620 sqlite3_free(zPat);
4622 return n;
4625 /* Forward reference */
4626 static int process_input(ShellState *p);
4629 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
4630 ** and return a pointer to the buffer. The caller is responsible for freeing
4631 ** the memory.
4633 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4634 ** read.
4636 ** For convenience, a nul-terminator byte is always appended to the data read
4637 ** from the file before the buffer is returned. This byte is not included in
4638 ** the final value of (*pnByte), if applicable.
4640 ** NULL is returned if any error is encountered. The final value of *pnByte
4641 ** is undefined in this case.
4643 static char *readFile(const char *zName, int *pnByte){
4644 FILE *in = fopen(zName, "rb");
4645 long nIn;
4646 size_t nRead;
4647 char *pBuf;
4648 if( in==0 ) return 0;
4649 fseek(in, 0, SEEK_END);
4650 nIn = ftell(in);
4651 rewind(in);
4652 pBuf = sqlite3_malloc64( nIn+1 );
4653 if( pBuf==0 ){ fclose(in); return 0; }
4654 nRead = fread(pBuf, nIn, 1, in);
4655 fclose(in);
4656 if( nRead!=1 ){
4657 sqlite3_free(pBuf);
4658 return 0;
4660 pBuf[nIn] = 0;
4661 if( pnByte ) *pnByte = nIn;
4662 return pBuf;
4665 #if defined(SQLITE_ENABLE_SESSION)
4667 ** Close a single OpenSession object and release all of its associated
4668 ** resources.
4670 static void session_close(OpenSession *pSession){
4671 int i;
4672 sqlite3session_delete(pSession->p);
4673 sqlite3_free(pSession->zName);
4674 for(i=0; i<pSession->nFilter; i++){
4675 sqlite3_free(pSession->azFilter[i]);
4677 sqlite3_free(pSession->azFilter);
4678 memset(pSession, 0, sizeof(OpenSession));
4680 #endif
4683 ** Close all OpenSession objects and release all associated resources.
4685 #if defined(SQLITE_ENABLE_SESSION)
4686 static void session_close_all(ShellState *p, int i){
4687 int j;
4688 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4689 for(j=0; j<pAuxDb->nSession; j++){
4690 session_close(&pAuxDb->aSession[j]);
4692 pAuxDb->nSession = 0;
4694 #else
4695 # define session_close_all(X,Y)
4696 #endif
4699 ** Implementation of the xFilter function for an open session. Omit
4700 ** any tables named by ".session filter" but let all other table through.
4702 #if defined(SQLITE_ENABLE_SESSION)
4703 static int session_filter(void *pCtx, const char *zTab){
4704 OpenSession *pSession = (OpenSession*)pCtx;
4705 int i;
4706 for(i=0; i<pSession->nFilter; i++){
4707 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4709 return 1;
4711 #endif
4714 ** Try to deduce the type of file for zName based on its content. Return
4715 ** one of the SHELL_OPEN_* constants.
4717 ** If the file does not exist or is empty but its name looks like a ZIP
4718 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4719 ** Otherwise, assume an ordinary database regardless of the filename if
4720 ** the type cannot be determined from content.
4722 int deduceDatabaseType(const char *zName, int dfltZip){
4723 FILE *f = fopen(zName, "rb");
4724 size_t n;
4725 int rc = SHELL_OPEN_UNSPEC;
4726 char zBuf[100];
4727 if( f==0 ){
4728 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4729 return SHELL_OPEN_ZIPFILE;
4730 }else{
4731 return SHELL_OPEN_NORMAL;
4734 n = fread(zBuf, 16, 1, f);
4735 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4736 fclose(f);
4737 return SHELL_OPEN_NORMAL;
4739 fseek(f, -25, SEEK_END);
4740 n = fread(zBuf, 25, 1, f);
4741 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4742 rc = SHELL_OPEN_APPENDVFS;
4743 }else{
4744 fseek(f, -22, SEEK_END);
4745 n = fread(zBuf, 22, 1, f);
4746 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4747 && zBuf[3]==0x06 ){
4748 rc = SHELL_OPEN_ZIPFILE;
4749 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4750 rc = SHELL_OPEN_ZIPFILE;
4753 fclose(f);
4754 return rc;
4757 #ifndef SQLITE_OMIT_DESERIALIZE
4759 ** Reconstruct an in-memory database using the output from the "dbtotxt"
4760 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
4761 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4763 static unsigned char *readHexDb(ShellState *p, int *pnData){
4764 unsigned char *a = 0;
4765 int nLine;
4766 int n = 0;
4767 int pgsz = 0;
4768 int iOffset = 0;
4769 int j, k;
4770 int rc;
4771 FILE *in;
4772 const char *zDbFilename = p->pAuxDb->zDbFilename;
4773 unsigned int x[16];
4774 char zLine[1000];
4775 if( zDbFilename ){
4776 in = fopen(zDbFilename, "r");
4777 if( in==0 ){
4778 utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4779 return 0;
4781 nLine = 0;
4782 }else{
4783 in = p->in;
4784 nLine = p->lineno;
4785 if( in==0 ) in = stdin;
4787 *pnData = 0;
4788 nLine++;
4789 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4790 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4791 if( rc!=2 ) goto readHexDb_error;
4792 if( n<0 ) goto readHexDb_error;
4793 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4794 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
4795 a = sqlite3_malloc( n ? n : 1 );
4796 shell_check_oom(a);
4797 memset(a, 0, n);
4798 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4799 utf8_printf(stderr, "invalid pagesize\n");
4800 goto readHexDb_error;
4802 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4803 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4804 if( rc==2 ){
4805 iOffset = k;
4806 continue;
4808 if( strncmp(zLine, "| end ", 6)==0 ){
4809 break;
4811 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4812 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4813 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4814 if( rc==17 ){
4815 k = iOffset+j;
4816 if( k+16<=n && k>=0 ){
4817 int ii;
4818 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4822 *pnData = n;
4823 if( in!=p->in ){
4824 fclose(in);
4825 }else{
4826 p->lineno = nLine;
4828 return a;
4830 readHexDb_error:
4831 if( in!=p->in ){
4832 fclose(in);
4833 }else{
4834 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4835 nLine++;
4836 if(strncmp(zLine, "| end ", 6)==0 ) break;
4838 p->lineno = nLine;
4840 sqlite3_free(a);
4841 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4842 return 0;
4844 #endif /* SQLITE_OMIT_DESERIALIZE */
4847 ** Scalar function "shell_int32". The first argument to this function
4848 ** must be a blob. The second a non-negative integer. This function
4849 ** reads and returns a 32-bit big-endian integer from byte
4850 ** offset (4*<arg2>) of the blob.
4852 static void shellInt32(
4853 sqlite3_context *context,
4854 int argc,
4855 sqlite3_value **argv
4857 const unsigned char *pBlob;
4858 int nBlob;
4859 int iInt;
4861 UNUSED_PARAMETER(argc);
4862 nBlob = sqlite3_value_bytes(argv[0]);
4863 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4864 iInt = sqlite3_value_int(argv[1]);
4866 if( iInt>=0 && (iInt+1)*4<=nBlob ){
4867 const unsigned char *a = &pBlob[iInt*4];
4868 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4869 + ((sqlite3_int64)a[1]<<16)
4870 + ((sqlite3_int64)a[2]<< 8)
4871 + ((sqlite3_int64)a[3]<< 0);
4872 sqlite3_result_int64(context, iVal);
4877 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4878 ** using "..." with internal double-quote characters doubled.
4880 static void shellIdQuote(
4881 sqlite3_context *context,
4882 int argc,
4883 sqlite3_value **argv
4885 const char *zName = (const char*)sqlite3_value_text(argv[0]);
4886 UNUSED_PARAMETER(argc);
4887 if( zName ){
4888 char *z = sqlite3_mprintf("\"%w\"", zName);
4889 sqlite3_result_text(context, z, -1, sqlite3_free);
4894 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4896 static void shellUSleepFunc(
4897 sqlite3_context *context,
4898 int argcUnused,
4899 sqlite3_value **argv
4901 int sleep = sqlite3_value_int(argv[0]);
4902 (void)argcUnused;
4903 sqlite3_sleep(sleep/1000);
4904 sqlite3_result_int(context, sleep);
4908 ** Scalar function "shell_escape_crnl" used by the .recover command.
4909 ** The argument passed to this function is the output of built-in
4910 ** function quote(). If the first character of the input is "'",
4911 ** indicating that the value passed to quote() was a text value,
4912 ** then this function searches the input for "\n" and "\r" characters
4913 ** and adds a wrapper similar to the following:
4915 ** replace(replace(<input>, '\n', char(10), '\r', char(13));
4917 ** Or, if the first character of the input is not "'", then a copy
4918 ** of the input is returned.
4920 static void shellEscapeCrnl(
4921 sqlite3_context *context,
4922 int argc,
4923 sqlite3_value **argv
4925 const char *zText = (const char*)sqlite3_value_text(argv[0]);
4926 UNUSED_PARAMETER(argc);
4927 if( zText && zText[0]=='\'' ){
4928 int nText = sqlite3_value_bytes(argv[0]);
4929 int i;
4930 char zBuf1[20];
4931 char zBuf2[20];
4932 const char *zNL = 0;
4933 const char *zCR = 0;
4934 int nCR = 0;
4935 int nNL = 0;
4937 for(i=0; zText[i]; i++){
4938 if( zNL==0 && zText[i]=='\n' ){
4939 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4940 nNL = (int)strlen(zNL);
4942 if( zCR==0 && zText[i]=='\r' ){
4943 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4944 nCR = (int)strlen(zCR);
4948 if( zNL || zCR ){
4949 int iOut = 0;
4950 i64 nMax = (nNL > nCR) ? nNL : nCR;
4951 i64 nAlloc = nMax * nText + (nMax+64)*2;
4952 char *zOut = (char*)sqlite3_malloc64(nAlloc);
4953 if( zOut==0 ){
4954 sqlite3_result_error_nomem(context);
4955 return;
4958 if( zNL && zCR ){
4959 memcpy(&zOut[iOut], "replace(replace(", 16);
4960 iOut += 16;
4961 }else{
4962 memcpy(&zOut[iOut], "replace(", 8);
4963 iOut += 8;
4965 for(i=0; zText[i]; i++){
4966 if( zText[i]=='\n' ){
4967 memcpy(&zOut[iOut], zNL, nNL);
4968 iOut += nNL;
4969 }else if( zText[i]=='\r' ){
4970 memcpy(&zOut[iOut], zCR, nCR);
4971 iOut += nCR;
4972 }else{
4973 zOut[iOut] = zText[i];
4974 iOut++;
4978 if( zNL ){
4979 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4980 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4981 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4983 if( zCR ){
4984 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4985 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4986 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4989 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4990 sqlite3_free(zOut);
4991 return;
4995 sqlite3_result_value(context, argv[0]);
4998 /* Flags for open_db().
5000 ** The default behavior of open_db() is to exit(1) if the database fails to
5001 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5002 ** but still returns without calling exit.
5004 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5005 ** ZIP archive if the file does not exist or is empty and its name matches
5006 ** the *.zip pattern.
5008 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5009 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5012 ** Make sure the database is open. If it is not, then open it. If
5013 ** the database fails to open, print an error message and exit.
5015 static void open_db(ShellState *p, int openFlags){
5016 if( p->db==0 ){
5017 const char *zDbFilename = p->pAuxDb->zDbFilename;
5018 if( p->openMode==SHELL_OPEN_UNSPEC ){
5019 if( zDbFilename==0 || zDbFilename[0]==0 ){
5020 p->openMode = SHELL_OPEN_NORMAL;
5021 }else{
5022 p->openMode = (u8)deduceDatabaseType(zDbFilename,
5023 (openFlags & OPEN_DB_ZIPFILE)!=0);
5026 switch( p->openMode ){
5027 case SHELL_OPEN_APPENDVFS: {
5028 sqlite3_open_v2(zDbFilename, &p->db,
5029 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5030 break;
5032 case SHELL_OPEN_HEXDB:
5033 case SHELL_OPEN_DESERIALIZE: {
5034 sqlite3_open(0, &p->db);
5035 break;
5037 case SHELL_OPEN_ZIPFILE: {
5038 sqlite3_open(":memory:", &p->db);
5039 break;
5041 case SHELL_OPEN_READONLY: {
5042 sqlite3_open_v2(zDbFilename, &p->db,
5043 SQLITE_OPEN_READONLY|p->openFlags, 0);
5044 break;
5046 case SHELL_OPEN_UNSPEC:
5047 case SHELL_OPEN_NORMAL: {
5048 sqlite3_open_v2(zDbFilename, &p->db,
5049 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5050 break;
5053 globalDb = p->db;
5054 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5055 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5056 zDbFilename, sqlite3_errmsg(p->db));
5057 if( openFlags & OPEN_DB_KEEPALIVE ){
5058 sqlite3_open(":memory:", &p->db);
5059 return;
5061 exit(1);
5063 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5064 sqlite3_enable_load_extension(p->db, 1);
5065 #endif
5066 sqlite3_shathree_init(p->db, 0, 0);
5067 sqlite3_uint_init(p->db, 0, 0);
5068 sqlite3_decimal_init(p->db, 0, 0);
5069 sqlite3_regexp_init(p->db, 0, 0);
5070 sqlite3_ieee_init(p->db, 0, 0);
5071 sqlite3_series_init(p->db, 0, 0);
5072 #ifndef SQLITE_SHELL_WASM_MODE
5073 sqlite3_fileio_init(p->db, 0, 0);
5074 sqlite3_completion_init(p->db, 0, 0);
5075 #endif
5076 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5077 sqlite3_dbdata_init(p->db, 0, 0);
5078 #endif
5079 #ifdef SQLITE_HAVE_ZLIB
5080 if( !p->bSafeModePersist ){
5081 sqlite3_zipfile_init(p->db, 0, 0);
5082 sqlite3_sqlar_init(p->db, 0, 0);
5084 #endif
5085 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5086 shellAddSchemaName, 0, 0);
5087 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5088 shellModuleSchema, 0, 0);
5089 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5090 shellPutsFunc, 0, 0);
5091 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5092 shellEscapeCrnl, 0, 0);
5093 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5094 shellInt32, 0, 0);
5095 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5096 shellIdQuote, 0, 0);
5097 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5098 shellUSleepFunc, 0, 0);
5099 #ifndef SQLITE_NOHAVE_SYSTEM
5100 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5101 editFunc, 0, 0);
5102 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5103 editFunc, 0, 0);
5104 #endif
5105 if( p->openMode==SHELL_OPEN_ZIPFILE ){
5106 char *zSql = sqlite3_mprintf(
5107 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5108 shell_check_oom(zSql);
5109 sqlite3_exec(p->db, zSql, 0, 0, 0);
5110 sqlite3_free(zSql);
5112 #ifndef SQLITE_OMIT_DESERIALIZE
5113 else
5114 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5115 int rc;
5116 int nData = 0;
5117 unsigned char *aData;
5118 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5119 aData = (unsigned char*)readFile(zDbFilename, &nData);
5120 }else{
5121 aData = readHexDb(p, &nData);
5122 if( aData==0 ){
5123 return;
5126 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5127 SQLITE_DESERIALIZE_RESIZEABLE |
5128 SQLITE_DESERIALIZE_FREEONCLOSE);
5129 if( rc ){
5130 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5132 if( p->szMax>0 ){
5133 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5136 #endif
5138 if( p->bSafeModePersist && p->db!=0 ){
5139 sqlite3_set_authorizer(p->db, safeModeAuth, p);
5144 ** Attempt to close the databaes connection. Report errors.
5146 void close_db(sqlite3 *db){
5147 int rc = sqlite3_close(db);
5148 if( rc ){
5149 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5150 rc, sqlite3_errmsg(db));
5154 #if HAVE_READLINE || HAVE_EDITLINE
5156 ** Readline completion callbacks
5158 static char *readline_completion_generator(const char *text, int state){
5159 static sqlite3_stmt *pStmt = 0;
5160 char *zRet;
5161 if( state==0 ){
5162 char *zSql;
5163 sqlite3_finalize(pStmt);
5164 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5165 " FROM completion(%Q) ORDER BY 1", text);
5166 shell_check_oom(zSql);
5167 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5168 sqlite3_free(zSql);
5170 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5171 const char *z = (const char*)sqlite3_column_text(pStmt,0);
5172 zRet = z ? strdup(z) : 0;
5173 }else{
5174 sqlite3_finalize(pStmt);
5175 pStmt = 0;
5176 zRet = 0;
5178 return zRet;
5180 static char **readline_completion(const char *zText, int iStart, int iEnd){
5181 rl_attempted_completion_over = 1;
5182 return rl_completion_matches(zText, readline_completion_generator);
5185 #elif HAVE_LINENOISE
5187 ** Linenoise completion callback
5189 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5190 int nLine = strlen30(zLine);
5191 int i, iStart;
5192 sqlite3_stmt *pStmt = 0;
5193 char *zSql;
5194 char zBuf[1000];
5196 if( nLine>sizeof(zBuf)-30 ) return;
5197 if( zLine[0]=='.' || zLine[0]=='#') return;
5198 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5199 if( i==nLine-1 ) return;
5200 iStart = i+1;
5201 memcpy(zBuf, zLine, iStart);
5202 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5203 " FROM completion(%Q,%Q) ORDER BY 1",
5204 &zLine[iStart], zLine);
5205 shell_check_oom(zSql);
5206 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5207 sqlite3_free(zSql);
5208 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5209 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5210 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5211 int nCompletion = sqlite3_column_bytes(pStmt, 0);
5212 if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5213 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5214 linenoiseAddCompletion(lc, zBuf);
5217 sqlite3_finalize(pStmt);
5219 #endif
5222 ** Do C-language style dequoting.
5224 ** \a -> alarm
5225 ** \b -> backspace
5226 ** \t -> tab
5227 ** \n -> newline
5228 ** \v -> vertical tab
5229 ** \f -> form feed
5230 ** \r -> carriage return
5231 ** \s -> space
5232 ** \" -> "
5233 ** \' -> '
5234 ** \\ -> backslash
5235 ** \NNN -> ascii character NNN in octal
5237 static void resolve_backslashes(char *z){
5238 int i, j;
5239 char c;
5240 while( *z && *z!='\\' ) z++;
5241 for(i=j=0; (c = z[i])!=0; i++, j++){
5242 if( c=='\\' && z[i+1]!=0 ){
5243 c = z[++i];
5244 if( c=='a' ){
5245 c = '\a';
5246 }else if( c=='b' ){
5247 c = '\b';
5248 }else if( c=='t' ){
5249 c = '\t';
5250 }else if( c=='n' ){
5251 c = '\n';
5252 }else if( c=='v' ){
5253 c = '\v';
5254 }else if( c=='f' ){
5255 c = '\f';
5256 }else if( c=='r' ){
5257 c = '\r';
5258 }else if( c=='"' ){
5259 c = '"';
5260 }else if( c=='\'' ){
5261 c = '\'';
5262 }else if( c=='\\' ){
5263 c = '\\';
5264 }else if( c>='0' && c<='7' ){
5265 c -= '0';
5266 if( z[i+1]>='0' && z[i+1]<='7' ){
5267 i++;
5268 c = (c<<3) + z[i] - '0';
5269 if( z[i+1]>='0' && z[i+1]<='7' ){
5270 i++;
5271 c = (c<<3) + z[i] - '0';
5276 z[j] = c;
5278 if( j<i ) z[j] = 0;
5282 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5283 ** for TRUE and FALSE. Return the integer value if appropriate.
5285 static int booleanValue(const char *zArg){
5286 int i;
5287 if( zArg[0]=='0' && zArg[1]=='x' ){
5288 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5289 }else{
5290 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5292 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5293 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5294 return 1;
5296 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5297 return 0;
5299 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5300 zArg);
5301 return 0;
5305 ** Set or clear a shell flag according to a boolean value.
5307 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5308 if( booleanValue(zArg) ){
5309 ShellSetFlag(p, mFlag);
5310 }else{
5311 ShellClearFlag(p, mFlag);
5316 ** Close an output file, assuming it is not stderr or stdout
5318 static void output_file_close(FILE *f){
5319 if( f && f!=stdout && f!=stderr ) fclose(f);
5323 ** Try to open an output file. The names "stdout" and "stderr" are
5324 ** recognized and do the right thing. NULL is returned if the output
5325 ** filename is "off".
5327 static FILE *output_file_open(const char *zFile, int bTextMode){
5328 FILE *f;
5329 if( strcmp(zFile,"stdout")==0 ){
5330 f = stdout;
5331 }else if( strcmp(zFile, "stderr")==0 ){
5332 f = stderr;
5333 }else if( strcmp(zFile, "off")==0 ){
5334 f = 0;
5335 }else{
5336 f = fopen(zFile, bTextMode ? "w" : "wb");
5337 if( f==0 ){
5338 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5341 return f;
5344 #ifndef SQLITE_OMIT_TRACE
5346 ** A routine for handling output from sqlite3_trace().
5348 static int sql_trace_callback(
5349 unsigned mType, /* The trace type */
5350 void *pArg, /* The ShellState pointer */
5351 void *pP, /* Usually a pointer to sqlite_stmt */
5352 void *pX /* Auxiliary output */
5354 ShellState *p = (ShellState*)pArg;
5355 sqlite3_stmt *pStmt;
5356 const char *zSql;
5357 int nSql;
5358 if( p->traceOut==0 ) return 0;
5359 if( mType==SQLITE_TRACE_CLOSE ){
5360 utf8_printf(p->traceOut, "-- closing database connection\n");
5361 return 0;
5363 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5364 zSql = (const char*)pX;
5365 }else{
5366 pStmt = (sqlite3_stmt*)pP;
5367 switch( p->eTraceType ){
5368 case SHELL_TRACE_EXPANDED: {
5369 zSql = sqlite3_expanded_sql(pStmt);
5370 break;
5372 #ifdef SQLITE_ENABLE_NORMALIZE
5373 case SHELL_TRACE_NORMALIZED: {
5374 zSql = sqlite3_normalized_sql(pStmt);
5375 break;
5377 #endif
5378 default: {
5379 zSql = sqlite3_sql(pStmt);
5380 break;
5384 if( zSql==0 ) return 0;
5385 nSql = strlen30(zSql);
5386 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5387 switch( mType ){
5388 case SQLITE_TRACE_ROW:
5389 case SQLITE_TRACE_STMT: {
5390 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5391 break;
5393 case SQLITE_TRACE_PROFILE: {
5394 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5395 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5396 break;
5399 return 0;
5401 #endif
5404 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5405 ** a useful spot to set a debugger breakpoint.
5407 static void test_breakpoint(void){
5408 static int nCall = 0;
5409 nCall++;
5413 ** An object used to read a CSV and other files for import.
5415 typedef struct ImportCtx ImportCtx;
5416 struct ImportCtx {
5417 const char *zFile; /* Name of the input file */
5418 FILE *in; /* Read the CSV text from this input stream */
5419 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
5420 char *z; /* Accumulated text for a field */
5421 int n; /* Number of bytes in z */
5422 int nAlloc; /* Space allocated for z[] */
5423 int nLine; /* Current line number */
5424 int nRow; /* Number of rows imported */
5425 int nErr; /* Number of errors encountered */
5426 int bNotFirst; /* True if one or more bytes already read */
5427 int cTerm; /* Character that terminated the most recent field */
5428 int cColSep; /* The column separator character. (Usually ",") */
5429 int cRowSep; /* The row separator character. (Usually "\n") */
5432 /* Clean up resourced used by an ImportCtx */
5433 static void import_cleanup(ImportCtx *p){
5434 if( p->in!=0 && p->xCloser!=0 ){
5435 p->xCloser(p->in);
5436 p->in = 0;
5438 sqlite3_free(p->z);
5439 p->z = 0;
5442 /* Append a single byte to z[] */
5443 static void import_append_char(ImportCtx *p, int c){
5444 if( p->n+1>=p->nAlloc ){
5445 p->nAlloc += p->nAlloc + 100;
5446 p->z = sqlite3_realloc64(p->z, p->nAlloc);
5447 shell_check_oom(p->z);
5449 p->z[p->n++] = (char)c;
5452 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5453 ** with the option of having a separator other than ",".
5455 ** + Input comes from p->in.
5456 ** + Store results in p->z of length p->n. Space to hold p->z comes
5457 ** from sqlite3_malloc64().
5458 ** + Use p->cSep as the column separator. The default is ",".
5459 ** + Use p->rSep as the row separator. The default is "\n".
5460 ** + Keep track of the line number in p->nLine.
5461 ** + Store the character that terminates the field in p->cTerm. Store
5462 ** EOF on end-of-file.
5463 ** + Report syntax errors on stderr
5465 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5466 int c;
5467 int cSep = p->cColSep;
5468 int rSep = p->cRowSep;
5469 p->n = 0;
5470 c = fgetc(p->in);
5471 if( c==EOF || seenInterrupt ){
5472 p->cTerm = EOF;
5473 return 0;
5475 if( c=='"' ){
5476 int pc, ppc;
5477 int startLine = p->nLine;
5478 int cQuote = c;
5479 pc = ppc = 0;
5480 while( 1 ){
5481 c = fgetc(p->in);
5482 if( c==rSep ) p->nLine++;
5483 if( c==cQuote ){
5484 if( pc==cQuote ){
5485 pc = 0;
5486 continue;
5489 if( (c==cSep && pc==cQuote)
5490 || (c==rSep && pc==cQuote)
5491 || (c==rSep && pc=='\r' && ppc==cQuote)
5492 || (c==EOF && pc==cQuote)
5494 do{ p->n--; }while( p->z[p->n]!=cQuote );
5495 p->cTerm = c;
5496 break;
5498 if( pc==cQuote && c!='\r' ){
5499 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5500 p->zFile, p->nLine, cQuote);
5502 if( c==EOF ){
5503 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5504 p->zFile, startLine, cQuote);
5505 p->cTerm = c;
5506 break;
5508 import_append_char(p, c);
5509 ppc = pc;
5510 pc = c;
5512 }else{
5513 /* If this is the first field being parsed and it begins with the
5514 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5515 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5516 import_append_char(p, c);
5517 c = fgetc(p->in);
5518 if( (c&0xff)==0xbb ){
5519 import_append_char(p, c);
5520 c = fgetc(p->in);
5521 if( (c&0xff)==0xbf ){
5522 p->bNotFirst = 1;
5523 p->n = 0;
5524 return csv_read_one_field(p);
5528 while( c!=EOF && c!=cSep && c!=rSep ){
5529 import_append_char(p, c);
5530 c = fgetc(p->in);
5532 if( c==rSep ){
5533 p->nLine++;
5534 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5536 p->cTerm = c;
5538 if( p->z ) p->z[p->n] = 0;
5539 p->bNotFirst = 1;
5540 return p->z;
5543 /* Read a single field of ASCII delimited text.
5545 ** + Input comes from p->in.
5546 ** + Store results in p->z of length p->n. Space to hold p->z comes
5547 ** from sqlite3_malloc64().
5548 ** + Use p->cSep as the column separator. The default is "\x1F".
5549 ** + Use p->rSep as the row separator. The default is "\x1E".
5550 ** + Keep track of the row number in p->nLine.
5551 ** + Store the character that terminates the field in p->cTerm. Store
5552 ** EOF on end-of-file.
5553 ** + Report syntax errors on stderr
5555 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5556 int c;
5557 int cSep = p->cColSep;
5558 int rSep = p->cRowSep;
5559 p->n = 0;
5560 c = fgetc(p->in);
5561 if( c==EOF || seenInterrupt ){
5562 p->cTerm = EOF;
5563 return 0;
5565 while( c!=EOF && c!=cSep && c!=rSep ){
5566 import_append_char(p, c);
5567 c = fgetc(p->in);
5569 if( c==rSep ){
5570 p->nLine++;
5572 p->cTerm = c;
5573 if( p->z ) p->z[p->n] = 0;
5574 return p->z;
5578 ** Try to transfer data for table zTable. If an error is seen while
5579 ** moving forward, try to go backwards. The backwards movement won't
5580 ** work for WITHOUT ROWID tables.
5582 static void tryToCloneData(
5583 ShellState *p,
5584 sqlite3 *newDb,
5585 const char *zTable
5587 sqlite3_stmt *pQuery = 0;
5588 sqlite3_stmt *pInsert = 0;
5589 char *zQuery = 0;
5590 char *zInsert = 0;
5591 int rc;
5592 int i, j, n;
5593 int nTable = strlen30(zTable);
5594 int k = 0;
5595 int cnt = 0;
5596 const int spinRate = 10000;
5598 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5599 shell_check_oom(zQuery);
5600 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5601 if( rc ){
5602 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5603 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5604 zQuery);
5605 goto end_data_xfer;
5607 n = sqlite3_column_count(pQuery);
5608 zInsert = sqlite3_malloc64(200 + nTable + n*3);
5609 shell_check_oom(zInsert);
5610 sqlite3_snprintf(200+nTable,zInsert,
5611 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5612 i = strlen30(zInsert);
5613 for(j=1; j<n; j++){
5614 memcpy(zInsert+i, ",?", 2);
5615 i += 2;
5617 memcpy(zInsert+i, ");", 3);
5618 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5619 if( rc ){
5620 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5621 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5622 zQuery);
5623 goto end_data_xfer;
5625 for(k=0; k<2; k++){
5626 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5627 for(i=0; i<n; i++){
5628 switch( sqlite3_column_type(pQuery, i) ){
5629 case SQLITE_NULL: {
5630 sqlite3_bind_null(pInsert, i+1);
5631 break;
5633 case SQLITE_INTEGER: {
5634 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5635 break;
5637 case SQLITE_FLOAT: {
5638 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5639 break;
5641 case SQLITE_TEXT: {
5642 sqlite3_bind_text(pInsert, i+1,
5643 (const char*)sqlite3_column_text(pQuery,i),
5644 -1, SQLITE_STATIC);
5645 break;
5647 case SQLITE_BLOB: {
5648 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5649 sqlite3_column_bytes(pQuery,i),
5650 SQLITE_STATIC);
5651 break;
5654 } /* End for */
5655 rc = sqlite3_step(pInsert);
5656 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5657 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5658 sqlite3_errmsg(newDb));
5660 sqlite3_reset(pInsert);
5661 cnt++;
5662 if( (cnt%spinRate)==0 ){
5663 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5664 fflush(stdout);
5666 } /* End while */
5667 if( rc==SQLITE_DONE ) break;
5668 sqlite3_finalize(pQuery);
5669 sqlite3_free(zQuery);
5670 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5671 zTable);
5672 shell_check_oom(zQuery);
5673 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5674 if( rc ){
5675 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5676 break;
5678 } /* End for(k=0...) */
5680 end_data_xfer:
5681 sqlite3_finalize(pQuery);
5682 sqlite3_finalize(pInsert);
5683 sqlite3_free(zQuery);
5684 sqlite3_free(zInsert);
5689 ** Try to transfer all rows of the schema that match zWhere. For
5690 ** each row, invoke xForEach() on the object defined by that row.
5691 ** If an error is encountered while moving forward through the
5692 ** sqlite_schema table, try again moving backwards.
5694 static void tryToCloneSchema(
5695 ShellState *p,
5696 sqlite3 *newDb,
5697 const char *zWhere,
5698 void (*xForEach)(ShellState*,sqlite3*,const char*)
5700 sqlite3_stmt *pQuery = 0;
5701 char *zQuery = 0;
5702 int rc;
5703 const unsigned char *zName;
5704 const unsigned char *zSql;
5705 char *zErrMsg = 0;
5707 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5708 " WHERE %s", zWhere);
5709 shell_check_oom(zQuery);
5710 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5711 if( rc ){
5712 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5713 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5714 zQuery);
5715 goto end_schema_xfer;
5717 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5718 zName = sqlite3_column_text(pQuery, 0);
5719 zSql = sqlite3_column_text(pQuery, 1);
5720 if( zName==0 || zSql==0 ) continue;
5721 printf("%s... ", zName); fflush(stdout);
5722 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5723 if( zErrMsg ){
5724 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5725 sqlite3_free(zErrMsg);
5726 zErrMsg = 0;
5728 if( xForEach ){
5729 xForEach(p, newDb, (const char*)zName);
5731 printf("done\n");
5733 if( rc!=SQLITE_DONE ){
5734 sqlite3_finalize(pQuery);
5735 sqlite3_free(zQuery);
5736 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5737 " WHERE %s ORDER BY rowid DESC", zWhere);
5738 shell_check_oom(zQuery);
5739 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5740 if( rc ){
5741 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5742 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5743 zQuery);
5744 goto end_schema_xfer;
5746 while( sqlite3_step(pQuery)==SQLITE_ROW ){
5747 zName = sqlite3_column_text(pQuery, 0);
5748 zSql = sqlite3_column_text(pQuery, 1);
5749 if( zName==0 || zSql==0 ) continue;
5750 printf("%s... ", zName); fflush(stdout);
5751 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5752 if( zErrMsg ){
5753 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5754 sqlite3_free(zErrMsg);
5755 zErrMsg = 0;
5757 if( xForEach ){
5758 xForEach(p, newDb, (const char*)zName);
5760 printf("done\n");
5763 end_schema_xfer:
5764 sqlite3_finalize(pQuery);
5765 sqlite3_free(zQuery);
5769 ** Open a new database file named "zNewDb". Try to recover as much information
5770 ** as possible out of the main database (which might be corrupt) and write it
5771 ** into zNewDb.
5773 static void tryToClone(ShellState *p, const char *zNewDb){
5774 int rc;
5775 sqlite3 *newDb = 0;
5776 if( access(zNewDb,0)==0 ){
5777 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5778 return;
5780 rc = sqlite3_open(zNewDb, &newDb);
5781 if( rc ){
5782 utf8_printf(stderr, "Cannot create output database: %s\n",
5783 sqlite3_errmsg(newDb));
5784 }else{
5785 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5786 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5787 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5788 tryToCloneSchema(p, newDb, "type!='table'", 0);
5789 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5790 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5792 close_db(newDb);
5796 ** Change the output file back to stdout.
5798 ** If the p->doXdgOpen flag is set, that means the output was being
5799 ** redirected to a temporary file named by p->zTempFile. In that case,
5800 ** launch start/open/xdg-open on that temporary file.
5802 static void output_reset(ShellState *p){
5803 if( p->outfile[0]=='|' ){
5804 #ifndef SQLITE_OMIT_POPEN
5805 pclose(p->out);
5806 #endif
5807 }else{
5808 output_file_close(p->out);
5809 #ifndef SQLITE_NOHAVE_SYSTEM
5810 if( p->doXdgOpen ){
5811 const char *zXdgOpenCmd =
5812 #if defined(_WIN32)
5813 "start";
5814 #elif defined(__APPLE__)
5815 "open";
5816 #else
5817 "xdg-open";
5818 #endif
5819 char *zCmd;
5820 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5821 if( system(zCmd) ){
5822 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5823 }else{
5824 /* Give the start/open/xdg-open command some time to get
5825 ** going before we continue, and potential delete the
5826 ** p->zTempFile data file out from under it */
5827 sqlite3_sleep(2000);
5829 sqlite3_free(zCmd);
5830 outputModePop(p);
5831 p->doXdgOpen = 0;
5833 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5835 p->outfile[0] = 0;
5836 p->out = stdout;
5840 ** Run an SQL command and return the single integer result.
5842 static int db_int(sqlite3 *db, const char *zSql){
5843 sqlite3_stmt *pStmt;
5844 int res = 0;
5845 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5846 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5847 res = sqlite3_column_int(pStmt,0);
5849 sqlite3_finalize(pStmt);
5850 return res;
5853 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5855 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
5857 static unsigned int get2byteInt(unsigned char *a){
5858 return (a[0]<<8) + a[1];
5860 static unsigned int get4byteInt(unsigned char *a){
5861 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5865 ** Implementation of the ".dbinfo" command.
5867 ** Return 1 on error, 2 to exit, and 0 otherwise.
5869 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5870 static const struct { const char *zName; int ofst; } aField[] = {
5871 { "file change counter:", 24 },
5872 { "database page count:", 28 },
5873 { "freelist page count:", 36 },
5874 { "schema cookie:", 40 },
5875 { "schema format:", 44 },
5876 { "default cache size:", 48 },
5877 { "autovacuum top root:", 52 },
5878 { "incremental vacuum:", 64 },
5879 { "text encoding:", 56 },
5880 { "user version:", 60 },
5881 { "application id:", 68 },
5882 { "software version:", 96 },
5884 static const struct { const char *zName; const char *zSql; } aQuery[] = {
5885 { "number of tables:",
5886 "SELECT count(*) FROM %s WHERE type='table'" },
5887 { "number of indexes:",
5888 "SELECT count(*) FROM %s WHERE type='index'" },
5889 { "number of triggers:",
5890 "SELECT count(*) FROM %s WHERE type='trigger'" },
5891 { "number of views:",
5892 "SELECT count(*) FROM %s WHERE type='view'" },
5893 { "schema size:",
5894 "SELECT total(length(sql)) FROM %s" },
5896 int i, rc;
5897 unsigned iDataVersion;
5898 char *zSchemaTab;
5899 char *zDb = nArg>=2 ? azArg[1] : "main";
5900 sqlite3_stmt *pStmt = 0;
5901 unsigned char aHdr[100];
5902 open_db(p, 0);
5903 if( p->db==0 ) return 1;
5904 rc = sqlite3_prepare_v2(p->db,
5905 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5906 -1, &pStmt, 0);
5907 if( rc ){
5908 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5909 sqlite3_finalize(pStmt);
5910 return 1;
5912 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5913 if( sqlite3_step(pStmt)==SQLITE_ROW
5914 && sqlite3_column_bytes(pStmt,0)>100
5916 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5917 sqlite3_finalize(pStmt);
5918 }else{
5919 raw_printf(stderr, "unable to read database header\n");
5920 sqlite3_finalize(pStmt);
5921 return 1;
5923 i = get2byteInt(aHdr+16);
5924 if( i==1 ) i = 65536;
5925 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5926 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5927 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5928 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5929 for(i=0; i<ArraySize(aField); i++){
5930 int ofst = aField[i].ofst;
5931 unsigned int val = get4byteInt(aHdr + ofst);
5932 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5933 switch( ofst ){
5934 case 56: {
5935 if( val==1 ) raw_printf(p->out, " (utf8)");
5936 if( val==2 ) raw_printf(p->out, " (utf16le)");
5937 if( val==3 ) raw_printf(p->out, " (utf16be)");
5940 raw_printf(p->out, "\n");
5942 if( zDb==0 ){
5943 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5944 }else if( strcmp(zDb,"temp")==0 ){
5945 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5946 }else{
5947 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5949 for(i=0; i<ArraySize(aQuery); i++){
5950 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5951 int val = db_int(p->db, zSql);
5952 sqlite3_free(zSql);
5953 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5955 sqlite3_free(zSchemaTab);
5956 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5957 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5958 return 0;
5960 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5961 && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5964 ** Print the current sqlite3_errmsg() value to stderr and return 1.
5966 static int shellDatabaseError(sqlite3 *db){
5967 const char *zErr = sqlite3_errmsg(db);
5968 utf8_printf(stderr, "Error: %s\n", zErr);
5969 return 1;
5973 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
5974 ** if they match and FALSE (0) if they do not match.
5976 ** Globbing rules:
5978 ** '*' Matches any sequence of zero or more characters.
5980 ** '?' Matches exactly one character.
5982 ** [...] Matches one character from the enclosed list of
5983 ** characters.
5985 ** [^...] Matches one character not in the enclosed list.
5987 ** '#' Matches any sequence of one or more digits with an
5988 ** optional + or - sign in front
5990 ** ' ' Any span of whitespace matches any other span of
5991 ** whitespace.
5993 ** Extra whitespace at the end of z[] is ignored.
5995 static int testcase_glob(const char *zGlob, const char *z){
5996 int c, c2;
5997 int invert;
5998 int seen;
6000 while( (c = (*(zGlob++)))!=0 ){
6001 if( IsSpace(c) ){
6002 if( !IsSpace(*z) ) return 0;
6003 while( IsSpace(*zGlob) ) zGlob++;
6004 while( IsSpace(*z) ) z++;
6005 }else if( c=='*' ){
6006 while( (c=(*(zGlob++))) == '*' || c=='?' ){
6007 if( c=='?' && (*(z++))==0 ) return 0;
6009 if( c==0 ){
6010 return 1;
6011 }else if( c=='[' ){
6012 while( *z && testcase_glob(zGlob-1,z)==0 ){
6013 z++;
6015 return (*z)!=0;
6017 while( (c2 = (*(z++)))!=0 ){
6018 while( c2!=c ){
6019 c2 = *(z++);
6020 if( c2==0 ) return 0;
6022 if( testcase_glob(zGlob,z) ) return 1;
6024 return 0;
6025 }else if( c=='?' ){
6026 if( (*(z++))==0 ) return 0;
6027 }else if( c=='[' ){
6028 int prior_c = 0;
6029 seen = 0;
6030 invert = 0;
6031 c = *(z++);
6032 if( c==0 ) return 0;
6033 c2 = *(zGlob++);
6034 if( c2=='^' ){
6035 invert = 1;
6036 c2 = *(zGlob++);
6038 if( c2==']' ){
6039 if( c==']' ) seen = 1;
6040 c2 = *(zGlob++);
6042 while( c2 && c2!=']' ){
6043 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6044 c2 = *(zGlob++);
6045 if( c>=prior_c && c<=c2 ) seen = 1;
6046 prior_c = 0;
6047 }else{
6048 if( c==c2 ){
6049 seen = 1;
6051 prior_c = c2;
6053 c2 = *(zGlob++);
6055 if( c2==0 || (seen ^ invert)==0 ) return 0;
6056 }else if( c=='#' ){
6057 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6058 if( !IsDigit(z[0]) ) return 0;
6059 z++;
6060 while( IsDigit(z[0]) ){ z++; }
6061 }else{
6062 if( c!=(*(z++)) ) return 0;
6065 while( IsSpace(*z) ){ z++; }
6066 return *z==0;
6071 ** Compare the string as a command-line option with either one or two
6072 ** initial "-" characters.
6074 static int optionMatch(const char *zStr, const char *zOpt){
6075 if( zStr[0]!='-' ) return 0;
6076 zStr++;
6077 if( zStr[0]=='-' ) zStr++;
6078 return strcmp(zStr, zOpt)==0;
6082 ** Delete a file.
6084 int shellDeleteFile(const char *zFilename){
6085 int rc;
6086 #ifdef _WIN32
6087 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6088 rc = _wunlink(z);
6089 sqlite3_free(z);
6090 #else
6091 rc = unlink(zFilename);
6092 #endif
6093 return rc;
6097 ** Try to delete the temporary file (if there is one) and free the
6098 ** memory used to hold the name of the temp file.
6100 static void clearTempFile(ShellState *p){
6101 if( p->zTempFile==0 ) return;
6102 if( p->doXdgOpen ) return;
6103 if( shellDeleteFile(p->zTempFile) ) return;
6104 sqlite3_free(p->zTempFile);
6105 p->zTempFile = 0;
6109 ** Create a new temp file name with the given suffix.
6111 static void newTempFile(ShellState *p, const char *zSuffix){
6112 clearTempFile(p);
6113 sqlite3_free(p->zTempFile);
6114 p->zTempFile = 0;
6115 if( p->db ){
6116 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6118 if( p->zTempFile==0 ){
6119 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6120 ** will not work and we will need to fallback to guessing */
6121 char *zTemp;
6122 sqlite3_uint64 r;
6123 sqlite3_randomness(sizeof(r), &r);
6124 zTemp = getenv("TEMP");
6125 if( zTemp==0 ) zTemp = getenv("TMP");
6126 if( zTemp==0 ){
6127 #ifdef _WIN32
6128 zTemp = "\\tmp";
6129 #else
6130 zTemp = "/tmp";
6131 #endif
6133 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6134 }else{
6135 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6137 shell_check_oom(p->zTempFile);
6142 ** The implementation of SQL scalar function fkey_collate_clause(), used
6143 ** by the ".lint fkey-indexes" command. This scalar function is always
6144 ** called with four arguments - the parent table name, the parent column name,
6145 ** the child table name and the child column name.
6147 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6149 ** If either of the named tables or columns do not exist, this function
6150 ** returns an empty string. An empty string is also returned if both tables
6151 ** and columns exist but have the same default collation sequence. Or,
6152 ** if both exist but the default collation sequences are different, this
6153 ** function returns the string " COLLATE <parent-collation>", where
6154 ** <parent-collation> is the default collation sequence of the parent column.
6156 static void shellFkeyCollateClause(
6157 sqlite3_context *pCtx,
6158 int nVal,
6159 sqlite3_value **apVal
6161 sqlite3 *db = sqlite3_context_db_handle(pCtx);
6162 const char *zParent;
6163 const char *zParentCol;
6164 const char *zParentSeq;
6165 const char *zChild;
6166 const char *zChildCol;
6167 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
6168 int rc;
6170 assert( nVal==4 );
6171 zParent = (const char*)sqlite3_value_text(apVal[0]);
6172 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6173 zChild = (const char*)sqlite3_value_text(apVal[2]);
6174 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6176 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6177 rc = sqlite3_table_column_metadata(
6178 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6180 if( rc==SQLITE_OK ){
6181 rc = sqlite3_table_column_metadata(
6182 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6186 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6187 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6188 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6189 sqlite3_free(z);
6195 ** The implementation of dot-command ".lint fkey-indexes".
6197 static int lintFkeyIndexes(
6198 ShellState *pState, /* Current shell tool state */
6199 char **azArg, /* Array of arguments passed to dot command */
6200 int nArg /* Number of entries in azArg[] */
6202 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
6203 FILE *out = pState->out; /* Stream to write non-error output to */
6204 int bVerbose = 0; /* If -verbose is present */
6205 int bGroupByParent = 0; /* If -groupbyparent is present */
6206 int i; /* To iterate through azArg[] */
6207 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
6208 int rc; /* Return code */
6209 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
6212 ** This SELECT statement returns one row for each foreign key constraint
6213 ** in the schema of the main database. The column values are:
6215 ** 0. The text of an SQL statement similar to:
6217 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6219 ** This SELECT is similar to the one that the foreign keys implementation
6220 ** needs to run internally on child tables. If there is an index that can
6221 ** be used to optimize this query, then it can also be used by the FK
6222 ** implementation to optimize DELETE or UPDATE statements on the parent
6223 ** table.
6225 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6226 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6227 ** contains an index that can be used to optimize the query.
6229 ** 2. Human readable text that describes the child table and columns. e.g.
6231 ** "child_table(child_key1, child_key2)"
6233 ** 3. Human readable text that describes the parent table and columns. e.g.
6235 ** "parent_table(parent_key1, parent_key2)"
6237 ** 4. A full CREATE INDEX statement for an index that could be used to
6238 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6240 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6242 ** 5. The name of the parent table.
6244 ** These six values are used by the C logic below to generate the report.
6246 const char *zSql =
6247 "SELECT "
6248 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6249 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6250 " || fkey_collate_clause("
6251 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6252 ", "
6253 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6254 " || group_concat('*=?', ' AND ') || ')'"
6255 ", "
6256 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6257 ", "
6258 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6259 ", "
6260 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6261 " || ' ON ' || quote(s.name) || '('"
6262 " || group_concat(quote(f.[from]) ||"
6263 " fkey_collate_clause("
6264 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6265 " || ');'"
6266 ", "
6267 " f.[table] "
6268 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6269 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6270 "GROUP BY s.name, f.id "
6271 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6273 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6275 for(i=2; i<nArg; i++){
6276 int n = strlen30(azArg[i]);
6277 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6278 bVerbose = 1;
6280 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6281 bGroupByParent = 1;
6282 zIndent = " ";
6284 else{
6285 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6286 azArg[0], azArg[1]
6288 return SQLITE_ERROR;
6292 /* Register the fkey_collate_clause() SQL function */
6293 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6294 0, shellFkeyCollateClause, 0, 0
6298 if( rc==SQLITE_OK ){
6299 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6301 if( rc==SQLITE_OK ){
6302 sqlite3_bind_int(pSql, 1, bGroupByParent);
6305 if( rc==SQLITE_OK ){
6306 int rc2;
6307 char *zPrev = 0;
6308 while( SQLITE_ROW==sqlite3_step(pSql) ){
6309 int res = -1;
6310 sqlite3_stmt *pExplain = 0;
6311 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6312 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6313 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6314 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6315 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6316 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6318 if( zEQP==0 ) continue;
6319 if( zGlob==0 ) continue;
6320 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6321 if( rc!=SQLITE_OK ) break;
6322 if( SQLITE_ROW==sqlite3_step(pExplain) ){
6323 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6324 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
6325 || 0==sqlite3_strglob(zGlobIPK, zPlan));
6327 rc = sqlite3_finalize(pExplain);
6328 if( rc!=SQLITE_OK ) break;
6330 if( res<0 ){
6331 raw_printf(stderr, "Error: internal error");
6332 break;
6333 }else{
6334 if( bGroupByParent
6335 && (bVerbose || res==0)
6336 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6338 raw_printf(out, "-- Parent table %s\n", zParent);
6339 sqlite3_free(zPrev);
6340 zPrev = sqlite3_mprintf("%s", zParent);
6343 if( res==0 ){
6344 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6345 }else if( bVerbose ){
6346 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6347 zIndent, zFrom, zTarget
6352 sqlite3_free(zPrev);
6354 if( rc!=SQLITE_OK ){
6355 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6358 rc2 = sqlite3_finalize(pSql);
6359 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6360 rc = rc2;
6361 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6363 }else{
6364 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6367 return rc;
6371 ** Implementation of ".lint" dot command.
6373 static int lintDotCommand(
6374 ShellState *pState, /* Current shell tool state */
6375 char **azArg, /* Array of arguments passed to dot command */
6376 int nArg /* Number of entries in azArg[] */
6378 int n;
6379 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6380 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6381 return lintFkeyIndexes(pState, azArg, nArg);
6383 usage:
6384 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6385 raw_printf(stderr, "Where sub-commands are:\n");
6386 raw_printf(stderr, " fkey-indexes\n");
6387 return SQLITE_ERROR;
6390 #if !defined SQLITE_OMIT_VIRTUALTABLE
6391 static void shellPrepare(
6392 sqlite3 *db,
6393 int *pRc,
6394 const char *zSql,
6395 sqlite3_stmt **ppStmt
6397 *ppStmt = 0;
6398 if( *pRc==SQLITE_OK ){
6399 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6400 if( rc!=SQLITE_OK ){
6401 raw_printf(stderr, "sql error: %s (%d)\n",
6402 sqlite3_errmsg(db), sqlite3_errcode(db)
6404 *pRc = rc;
6410 ** Create a prepared statement using printf-style arguments for the SQL.
6412 ** This routine is could be marked "static". But it is not always used,
6413 ** depending on compile-time options. By omitting the "static", we avoid
6414 ** nuisance compiler warnings about "defined but not used".
6416 void shellPreparePrintf(
6417 sqlite3 *db,
6418 int *pRc,
6419 sqlite3_stmt **ppStmt,
6420 const char *zFmt,
6423 *ppStmt = 0;
6424 if( *pRc==SQLITE_OK ){
6425 va_list ap;
6426 char *z;
6427 va_start(ap, zFmt);
6428 z = sqlite3_vmprintf(zFmt, ap);
6429 va_end(ap);
6430 if( z==0 ){
6431 *pRc = SQLITE_NOMEM;
6432 }else{
6433 shellPrepare(db, pRc, z, ppStmt);
6434 sqlite3_free(z);
6439 /* Finalize the prepared statement created using shellPreparePrintf().
6441 ** This routine is could be marked "static". But it is not always used,
6442 ** depending on compile-time options. By omitting the "static", we avoid
6443 ** nuisance compiler warnings about "defined but not used".
6445 void shellFinalize(
6446 int *pRc,
6447 sqlite3_stmt *pStmt
6449 if( pStmt ){
6450 sqlite3 *db = sqlite3_db_handle(pStmt);
6451 int rc = sqlite3_finalize(pStmt);
6452 if( *pRc==SQLITE_OK ){
6453 if( rc!=SQLITE_OK ){
6454 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6456 *pRc = rc;
6461 /* Reset the prepared statement created using shellPreparePrintf().
6463 ** This routine is could be marked "static". But it is not always used,
6464 ** depending on compile-time options. By omitting the "static", we avoid
6465 ** nuisance compiler warnings about "defined but not used".
6467 void shellReset(
6468 int *pRc,
6469 sqlite3_stmt *pStmt
6471 int rc = sqlite3_reset(pStmt);
6472 if( *pRc==SQLITE_OK ){
6473 if( rc!=SQLITE_OK ){
6474 sqlite3 *db = sqlite3_db_handle(pStmt);
6475 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6477 *pRc = rc;
6480 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6482 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6483 /******************************************************************************
6484 ** The ".archive" or ".ar" command.
6487 ** Structure representing a single ".ar" command.
6489 typedef struct ArCommand ArCommand;
6490 struct ArCommand {
6491 u8 eCmd; /* An AR_CMD_* value */
6492 u8 bVerbose; /* True if --verbose */
6493 u8 bZip; /* True if the archive is a ZIP */
6494 u8 bDryRun; /* True if --dry-run */
6495 u8 bAppend; /* True if --append */
6496 u8 bGlob; /* True if --glob */
6497 u8 fromCmdLine; /* Run from -A instead of .archive */
6498 int nArg; /* Number of command arguments */
6499 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6500 const char *zFile; /* --file argument, or NULL */
6501 const char *zDir; /* --directory argument, or NULL */
6502 char **azArg; /* Array of command arguments */
6503 ShellState *p; /* Shell state */
6504 sqlite3 *db; /* Database containing the archive */
6508 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6510 static int arUsage(FILE *f){
6511 showHelp(f,"archive");
6512 return SQLITE_ERROR;
6516 ** Print an error message for the .ar command to stderr and return
6517 ** SQLITE_ERROR.
6519 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6520 va_list ap;
6521 char *z;
6522 va_start(ap, zFmt);
6523 z = sqlite3_vmprintf(zFmt, ap);
6524 va_end(ap);
6525 utf8_printf(stderr, "Error: %s\n", z);
6526 if( pAr->fromCmdLine ){
6527 utf8_printf(stderr, "Use \"-A\" for more help\n");
6528 }else{
6529 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6531 sqlite3_free(z);
6532 return SQLITE_ERROR;
6536 ** Values for ArCommand.eCmd.
6538 #define AR_CMD_CREATE 1
6539 #define AR_CMD_UPDATE 2
6540 #define AR_CMD_INSERT 3
6541 #define AR_CMD_EXTRACT 4
6542 #define AR_CMD_LIST 5
6543 #define AR_CMD_HELP 6
6544 #define AR_CMD_REMOVE 7
6547 ** Other (non-command) switches.
6549 #define AR_SWITCH_VERBOSE 8
6550 #define AR_SWITCH_FILE 9
6551 #define AR_SWITCH_DIRECTORY 10
6552 #define AR_SWITCH_APPEND 11
6553 #define AR_SWITCH_DRYRUN 12
6554 #define AR_SWITCH_GLOB 13
6556 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6557 switch( eSwitch ){
6558 case AR_CMD_CREATE:
6559 case AR_CMD_EXTRACT:
6560 case AR_CMD_LIST:
6561 case AR_CMD_REMOVE:
6562 case AR_CMD_UPDATE:
6563 case AR_CMD_INSERT:
6564 case AR_CMD_HELP:
6565 if( pAr->eCmd ){
6566 return arErrorMsg(pAr, "multiple command options");
6568 pAr->eCmd = eSwitch;
6569 break;
6571 case AR_SWITCH_DRYRUN:
6572 pAr->bDryRun = 1;
6573 break;
6574 case AR_SWITCH_GLOB:
6575 pAr->bGlob = 1;
6576 break;
6577 case AR_SWITCH_VERBOSE:
6578 pAr->bVerbose = 1;
6579 break;
6580 case AR_SWITCH_APPEND:
6581 pAr->bAppend = 1;
6582 /* Fall thru into --file */
6583 case AR_SWITCH_FILE:
6584 pAr->zFile = zArg;
6585 break;
6586 case AR_SWITCH_DIRECTORY:
6587 pAr->zDir = zArg;
6588 break;
6591 return SQLITE_OK;
6595 ** Parse the command line for an ".ar" command. The results are written into
6596 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6597 ** successfully, otherwise an error message is written to stderr and
6598 ** SQLITE_ERROR returned.
6600 static int arParseCommand(
6601 char **azArg, /* Array of arguments passed to dot command */
6602 int nArg, /* Number of entries in azArg[] */
6603 ArCommand *pAr /* Populate this object */
6605 struct ArSwitch {
6606 const char *zLong;
6607 char cShort;
6608 u8 eSwitch;
6609 u8 bArg;
6610 } aSwitch[] = {
6611 { "create", 'c', AR_CMD_CREATE, 0 },
6612 { "extract", 'x', AR_CMD_EXTRACT, 0 },
6613 { "insert", 'i', AR_CMD_INSERT, 0 },
6614 { "list", 't', AR_CMD_LIST, 0 },
6615 { "remove", 'r', AR_CMD_REMOVE, 0 },
6616 { "update", 'u', AR_CMD_UPDATE, 0 },
6617 { "help", 'h', AR_CMD_HELP, 0 },
6618 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
6619 { "file", 'f', AR_SWITCH_FILE, 1 },
6620 { "append", 'a', AR_SWITCH_APPEND, 1 },
6621 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6622 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
6623 { "glob", 'g', AR_SWITCH_GLOB, 0 },
6625 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6626 struct ArSwitch *pEnd = &aSwitch[nSwitch];
6628 if( nArg<=1 ){
6629 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
6630 return arUsage(stderr);
6631 }else{
6632 char *z = azArg[1];
6633 if( z[0]!='-' ){
6634 /* Traditional style [tar] invocation */
6635 int i;
6636 int iArg = 2;
6637 for(i=0; z[i]; i++){
6638 const char *zArg = 0;
6639 struct ArSwitch *pOpt;
6640 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6641 if( z[i]==pOpt->cShort ) break;
6643 if( pOpt==pEnd ){
6644 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6646 if( pOpt->bArg ){
6647 if( iArg>=nArg ){
6648 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6650 zArg = azArg[iArg++];
6652 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6654 pAr->nArg = nArg-iArg;
6655 if( pAr->nArg>0 ){
6656 pAr->azArg = &azArg[iArg];
6658 }else{
6659 /* Non-traditional invocation */
6660 int iArg;
6661 for(iArg=1; iArg<nArg; iArg++){
6662 int n;
6663 z = azArg[iArg];
6664 if( z[0]!='-' ){
6665 /* All remaining command line words are command arguments. */
6666 pAr->azArg = &azArg[iArg];
6667 pAr->nArg = nArg-iArg;
6668 break;
6670 n = strlen30(z);
6672 if( z[1]!='-' ){
6673 int i;
6674 /* One or more short options */
6675 for(i=1; i<n; i++){
6676 const char *zArg = 0;
6677 struct ArSwitch *pOpt;
6678 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6679 if( z[i]==pOpt->cShort ) break;
6681 if( pOpt==pEnd ){
6682 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6684 if( pOpt->bArg ){
6685 if( i<(n-1) ){
6686 zArg = &z[i+1];
6687 i = n;
6688 }else{
6689 if( iArg>=(nArg-1) ){
6690 return arErrorMsg(pAr, "option requires an argument: %c",
6691 z[i]);
6693 zArg = azArg[++iArg];
6696 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6698 }else if( z[2]=='\0' ){
6699 /* A -- option, indicating that all remaining command line words
6700 ** are command arguments. */
6701 pAr->azArg = &azArg[iArg+1];
6702 pAr->nArg = nArg-iArg-1;
6703 break;
6704 }else{
6705 /* A long option */
6706 const char *zArg = 0; /* Argument for option, if any */
6707 struct ArSwitch *pMatch = 0; /* Matching option */
6708 struct ArSwitch *pOpt; /* Iterator */
6709 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6710 const char *zLong = pOpt->zLong;
6711 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6712 if( pMatch ){
6713 return arErrorMsg(pAr, "ambiguous option: %s",z);
6714 }else{
6715 pMatch = pOpt;
6720 if( pMatch==0 ){
6721 return arErrorMsg(pAr, "unrecognized option: %s", z);
6723 if( pMatch->bArg ){
6724 if( iArg>=(nArg-1) ){
6725 return arErrorMsg(pAr, "option requires an argument: %s", z);
6727 zArg = azArg[++iArg];
6729 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6735 return SQLITE_OK;
6739 ** This function assumes that all arguments within the ArCommand.azArg[]
6740 ** array refer to archive members, as for the --extract, --list or --remove
6741 ** commands. It checks that each of them are "present". If any specified
6742 ** file is not present in the archive, an error is printed to stderr and an
6743 ** error code returned. Otherwise, if all specified arguments are present
6744 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
6745 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6746 ** when pAr->bGlob is true.
6748 ** This function strips any trailing '/' characters from each argument.
6749 ** This is consistent with the way the [tar] command seems to work on
6750 ** Linux.
6752 static int arCheckEntries(ArCommand *pAr){
6753 int rc = SQLITE_OK;
6754 if( pAr->nArg ){
6755 int i, j;
6756 sqlite3_stmt *pTest = 0;
6757 const char *zSel = (pAr->bGlob)
6758 ? "SELECT name FROM %s WHERE glob($name,name)"
6759 : "SELECT name FROM %s WHERE name=$name";
6761 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6762 j = sqlite3_bind_parameter_index(pTest, "$name");
6763 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6764 char *z = pAr->azArg[i];
6765 int n = strlen30(z);
6766 int bOk = 0;
6767 while( n>0 && z[n-1]=='/' ) n--;
6768 z[n] = '\0';
6769 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6770 if( SQLITE_ROW==sqlite3_step(pTest) ){
6771 bOk = 1;
6773 shellReset(&rc, pTest);
6774 if( rc==SQLITE_OK && bOk==0 ){
6775 utf8_printf(stderr, "not found in archive: %s\n", z);
6776 rc = SQLITE_ERROR;
6779 shellFinalize(&rc, pTest);
6781 return rc;
6785 ** Format a WHERE clause that can be used against the "sqlar" table to
6786 ** identify all archive members that match the command arguments held
6787 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6788 ** The caller is responsible for eventually calling sqlite3_free() on
6789 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6790 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6792 static void arWhereClause(
6793 int *pRc,
6794 ArCommand *pAr,
6795 char **pzWhere /* OUT: New WHERE clause */
6797 char *zWhere = 0;
6798 const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6799 if( *pRc==SQLITE_OK ){
6800 if( pAr->nArg==0 ){
6801 zWhere = sqlite3_mprintf("1");
6802 }else{
6803 int i;
6804 const char *zSep = "";
6805 for(i=0; i<pAr->nArg; i++){
6806 const char *z = pAr->azArg[i];
6807 zWhere = sqlite3_mprintf(
6808 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6809 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6811 if( zWhere==0 ){
6812 *pRc = SQLITE_NOMEM;
6813 break;
6815 zSep = " OR ";
6819 *pzWhere = zWhere;
6823 ** Implementation of .ar "lisT" command.
6825 static int arListCommand(ArCommand *pAr){
6826 const char *zSql = "SELECT %s FROM %s WHERE %s";
6827 const char *azCols[] = {
6828 "name",
6829 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6832 char *zWhere = 0;
6833 sqlite3_stmt *pSql = 0;
6834 int rc;
6836 rc = arCheckEntries(pAr);
6837 arWhereClause(&rc, pAr, &zWhere);
6839 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6840 pAr->zSrcTable, zWhere);
6841 if( pAr->bDryRun ){
6842 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6843 }else{
6844 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6845 if( pAr->bVerbose ){
6846 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
6847 sqlite3_column_text(pSql, 0),
6848 sqlite3_column_int(pSql, 1),
6849 sqlite3_column_text(pSql, 2),
6850 sqlite3_column_text(pSql, 3)
6852 }else{
6853 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6857 shellFinalize(&rc, pSql);
6858 sqlite3_free(zWhere);
6859 return rc;
6864 ** Implementation of .ar "Remove" command.
6866 static int arRemoveCommand(ArCommand *pAr){
6867 int rc = 0;
6868 char *zSql = 0;
6869 char *zWhere = 0;
6871 if( pAr->nArg ){
6872 /* Verify that args actually exist within the archive before proceeding.
6873 ** And formulate a WHERE clause to match them. */
6874 rc = arCheckEntries(pAr);
6875 arWhereClause(&rc, pAr, &zWhere);
6877 if( rc==SQLITE_OK ){
6878 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6879 pAr->zSrcTable, zWhere);
6880 if( pAr->bDryRun ){
6881 utf8_printf(pAr->p->out, "%s\n", zSql);
6882 }else{
6883 char *zErr = 0;
6884 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6885 if( rc==SQLITE_OK ){
6886 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6887 if( rc!=SQLITE_OK ){
6888 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6889 }else{
6890 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6893 if( zErr ){
6894 utf8_printf(stdout, "ERROR: %s\n", zErr);
6895 sqlite3_free(zErr);
6899 sqlite3_free(zWhere);
6900 sqlite3_free(zSql);
6901 return rc;
6905 ** Implementation of .ar "eXtract" command.
6907 static int arExtractCommand(ArCommand *pAr){
6908 const char *zSql1 =
6909 "SELECT "
6910 " ($dir || name),"
6911 " writefile(($dir || name), %s, mode, mtime) "
6912 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6913 " AND name NOT GLOB '*..[/\\]*'";
6915 const char *azExtraArg[] = {
6916 "sqlar_uncompress(data, sz)",
6917 "data"
6920 sqlite3_stmt *pSql = 0;
6921 int rc = SQLITE_OK;
6922 char *zDir = 0;
6923 char *zWhere = 0;
6924 int i, j;
6926 /* If arguments are specified, check that they actually exist within
6927 ** the archive before proceeding. And formulate a WHERE clause to
6928 ** match them. */
6929 rc = arCheckEntries(pAr);
6930 arWhereClause(&rc, pAr, &zWhere);
6932 if( rc==SQLITE_OK ){
6933 if( pAr->zDir ){
6934 zDir = sqlite3_mprintf("%s/", pAr->zDir);
6935 }else{
6936 zDir = sqlite3_mprintf("");
6938 if( zDir==0 ) rc = SQLITE_NOMEM;
6941 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6942 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6945 if( rc==SQLITE_OK ){
6946 j = sqlite3_bind_parameter_index(pSql, "$dir");
6947 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6949 /* Run the SELECT statement twice. The first time, writefile() is called
6950 ** for all archive members that should be extracted. The second time,
6951 ** only for the directories. This is because the timestamps for
6952 ** extracted directories must be reset after they are populated (as
6953 ** populating them changes the timestamp). */
6954 for(i=0; i<2; i++){
6955 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6956 sqlite3_bind_int(pSql, j, i);
6957 if( pAr->bDryRun ){
6958 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6959 }else{
6960 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6961 if( i==0 && pAr->bVerbose ){
6962 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6966 shellReset(&rc, pSql);
6968 shellFinalize(&rc, pSql);
6971 sqlite3_free(zDir);
6972 sqlite3_free(zWhere);
6973 return rc;
6977 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
6979 static int arExecSql(ArCommand *pAr, const char *zSql){
6980 int rc;
6981 if( pAr->bDryRun ){
6982 utf8_printf(pAr->p->out, "%s\n", zSql);
6983 rc = SQLITE_OK;
6984 }else{
6985 char *zErr = 0;
6986 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6987 if( zErr ){
6988 utf8_printf(stdout, "ERROR: %s\n", zErr);
6989 sqlite3_free(zErr);
6992 return rc;
6997 ** Implementation of .ar "create", "insert", and "update" commands.
6999 ** create -> Create a new SQL archive
7000 ** insert -> Insert or reinsert all files listed
7001 ** update -> Insert files that have changed or that were not
7002 ** previously in the archive
7004 ** Create the "sqlar" table in the database if it does not already exist.
7005 ** Then add each file in the azFile[] array to the archive. Directories
7006 ** are added recursively. If argument bVerbose is non-zero, a message is
7007 ** printed on stdout for each file archived.
7009 ** The create command is the same as update, except that it drops
7010 ** any existing "sqlar" table before beginning. The "insert" command
7011 ** always overwrites every file named on the command-line, where as
7012 ** "update" only overwrites if the size or mtime or mode has changed.
7014 static int arCreateOrUpdateCommand(
7015 ArCommand *pAr, /* Command arguments and options */
7016 int bUpdate, /* true for a --create. */
7017 int bOnlyIfChanged /* Only update if file has changed */
7019 const char *zCreate =
7020 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7021 " name TEXT PRIMARY KEY, -- name of the file\n"
7022 " mode INT, -- access permissions\n"
7023 " mtime INT, -- last modification time\n"
7024 " sz INT, -- original file size\n"
7025 " data BLOB -- compressed content\n"
7026 ")";
7027 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7028 const char *zInsertFmt[2] = {
7029 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7030 " SELECT\n"
7031 " %s,\n"
7032 " mode,\n"
7033 " mtime,\n"
7034 " CASE substr(lsmode(mode),1,1)\n"
7035 " WHEN '-' THEN length(data)\n"
7036 " WHEN 'd' THEN 0\n"
7037 " ELSE -1 END,\n"
7038 " sqlar_compress(data)\n"
7039 " FROM fsdir(%Q,%Q) AS disk\n"
7040 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7042 "REPLACE INTO %s(name,mode,mtime,data)\n"
7043 " SELECT\n"
7044 " %s,\n"
7045 " mode,\n"
7046 " mtime,\n"
7047 " data\n"
7048 " FROM fsdir(%Q,%Q) AS disk\n"
7049 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7051 int i; /* For iterating through azFile[] */
7052 int rc; /* Return code */
7053 const char *zTab = 0; /* SQL table into which to insert */
7054 char *zSql;
7055 char zTemp[50];
7056 char *zExists = 0;
7058 arExecSql(pAr, "PRAGMA page_size=512");
7059 rc = arExecSql(pAr, "SAVEPOINT ar;");
7060 if( rc!=SQLITE_OK ) return rc;
7061 zTemp[0] = 0;
7062 if( pAr->bZip ){
7063 /* Initialize the zipfile virtual table, if necessary */
7064 if( pAr->zFile ){
7065 sqlite3_uint64 r;
7066 sqlite3_randomness(sizeof(r),&r);
7067 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7068 zTab = zTemp;
7069 zSql = sqlite3_mprintf(
7070 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7071 zTab, pAr->zFile
7073 rc = arExecSql(pAr, zSql);
7074 sqlite3_free(zSql);
7075 }else{
7076 zTab = "zip";
7078 }else{
7079 /* Initialize the table for an SQLAR */
7080 zTab = "sqlar";
7081 if( bUpdate==0 ){
7082 rc = arExecSql(pAr, zDrop);
7083 if( rc!=SQLITE_OK ) goto end_ar_transaction;
7085 rc = arExecSql(pAr, zCreate);
7087 if( bOnlyIfChanged ){
7088 zExists = sqlite3_mprintf(
7089 " AND NOT EXISTS("
7090 "SELECT 1 FROM %s AS mem"
7091 " WHERE mem.name=disk.name"
7092 " AND mem.mtime=disk.mtime"
7093 " AND mem.mode=disk.mode)", zTab);
7094 }else{
7095 zExists = sqlite3_mprintf("");
7097 if( zExists==0 ) rc = SQLITE_NOMEM;
7098 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7099 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7100 pAr->bVerbose ? "shell_putsnl(name)" : "name",
7101 pAr->azArg[i], pAr->zDir, zExists);
7102 rc = arExecSql(pAr, zSql2);
7103 sqlite3_free(zSql2);
7105 end_ar_transaction:
7106 if( rc!=SQLITE_OK ){
7107 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7108 }else{
7109 rc = arExecSql(pAr, "RELEASE ar;");
7110 if( pAr->bZip && pAr->zFile ){
7111 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7112 arExecSql(pAr, zSql);
7113 sqlite3_free(zSql);
7116 sqlite3_free(zExists);
7117 return rc;
7121 ** Implementation of ".ar" dot command.
7123 static int arDotCommand(
7124 ShellState *pState, /* Current shell tool state */
7125 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
7126 char **azArg, /* Array of arguments passed to dot command */
7127 int nArg /* Number of entries in azArg[] */
7129 ArCommand cmd;
7130 int rc;
7131 memset(&cmd, 0, sizeof(cmd));
7132 cmd.fromCmdLine = fromCmdLine;
7133 rc = arParseCommand(azArg, nArg, &cmd);
7134 if( rc==SQLITE_OK ){
7135 int eDbType = SHELL_OPEN_UNSPEC;
7136 cmd.p = pState;
7137 cmd.db = pState->db;
7138 if( cmd.zFile ){
7139 eDbType = deduceDatabaseType(cmd.zFile, 1);
7140 }else{
7141 eDbType = pState->openMode;
7143 if( eDbType==SHELL_OPEN_ZIPFILE ){
7144 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7145 if( cmd.zFile==0 ){
7146 cmd.zSrcTable = sqlite3_mprintf("zip");
7147 }else{
7148 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7151 cmd.bZip = 1;
7152 }else if( cmd.zFile ){
7153 int flags;
7154 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7155 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7156 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7157 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7158 }else{
7159 flags = SQLITE_OPEN_READONLY;
7161 cmd.db = 0;
7162 if( cmd.bDryRun ){
7163 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7164 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7166 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7167 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7168 if( rc!=SQLITE_OK ){
7169 utf8_printf(stderr, "cannot open file: %s (%s)\n",
7170 cmd.zFile, sqlite3_errmsg(cmd.db)
7172 goto end_ar_command;
7174 sqlite3_fileio_init(cmd.db, 0, 0);
7175 sqlite3_sqlar_init(cmd.db, 0, 0);
7176 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7177 shellPutsFunc, 0, 0);
7180 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7181 if( cmd.eCmd!=AR_CMD_CREATE
7182 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7184 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7185 rc = SQLITE_ERROR;
7186 goto end_ar_command;
7188 cmd.zSrcTable = sqlite3_mprintf("sqlar");
7191 switch( cmd.eCmd ){
7192 case AR_CMD_CREATE:
7193 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7194 break;
7196 case AR_CMD_EXTRACT:
7197 rc = arExtractCommand(&cmd);
7198 break;
7200 case AR_CMD_LIST:
7201 rc = arListCommand(&cmd);
7202 break;
7204 case AR_CMD_HELP:
7205 arUsage(pState->out);
7206 break;
7208 case AR_CMD_INSERT:
7209 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7210 break;
7212 case AR_CMD_REMOVE:
7213 rc = arRemoveCommand(&cmd);
7214 break;
7216 default:
7217 assert( cmd.eCmd==AR_CMD_UPDATE );
7218 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7219 break;
7222 end_ar_command:
7223 if( cmd.db!=pState->db ){
7224 close_db(cmd.db);
7226 sqlite3_free(cmd.zSrcTable);
7228 return rc;
7230 /* End of the ".archive" or ".ar" command logic
7231 *******************************************************************************/
7232 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7234 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7236 ** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7237 ** Otherwise, the SQL statement or statements in zSql are executed using
7238 ** database connection db and the error code written to *pRc before
7239 ** this function returns.
7241 static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7242 int rc = *pRc;
7243 if( rc==SQLITE_OK ){
7244 char *zErr = 0;
7245 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7246 if( rc!=SQLITE_OK ){
7247 raw_printf(stderr, "SQL error: %s\n", zErr);
7249 sqlite3_free(zErr);
7250 *pRc = rc;
7255 ** Like shellExec(), except that zFmt is a printf() style format string.
7257 static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7258 char *z = 0;
7259 if( *pRc==SQLITE_OK ){
7260 va_list ap;
7261 va_start(ap, zFmt);
7262 z = sqlite3_vmprintf(zFmt, ap);
7263 va_end(ap);
7264 if( z==0 ){
7265 *pRc = SQLITE_NOMEM;
7266 }else{
7267 shellExec(db, pRc, z);
7269 sqlite3_free(z);
7274 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7275 ** Otherwise, an attempt is made to allocate, zero and return a pointer
7276 ** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7277 ** to SQLITE_NOMEM and NULL returned.
7279 static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7280 void *pRet = 0;
7281 if( *pRc==SQLITE_OK ){
7282 pRet = sqlite3_malloc64(nByte);
7283 if( pRet==0 ){
7284 *pRc = SQLITE_NOMEM;
7285 }else{
7286 memset(pRet, 0, nByte);
7289 return pRet;
7293 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7294 ** Otherwise, zFmt is treated as a printf() style string. The result of
7295 ** formatting it along with any trailing arguments is written into a
7296 ** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7297 ** It is the responsibility of the caller to eventually free this buffer
7298 ** using a call to sqlite3_free().
7300 ** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7301 ** pointer returned.
7303 static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7304 char *z = 0;
7305 if( *pRc==SQLITE_OK ){
7306 va_list ap;
7307 va_start(ap, zFmt);
7308 z = sqlite3_vmprintf(zFmt, ap);
7309 va_end(ap);
7310 if( z==0 ){
7311 *pRc = SQLITE_NOMEM;
7314 return z;
7319 ** When running the ".recover" command, each output table, and the special
7320 ** orphaned row table if it is required, is represented by an instance
7321 ** of the following struct.
7323 typedef struct RecoverTable RecoverTable;
7324 struct RecoverTable {
7325 char *zQuoted; /* Quoted version of table name */
7326 int nCol; /* Number of columns in table */
7327 char **azlCol; /* Array of column lists */
7328 int iPk; /* Index of IPK column */
7332 ** Free a RecoverTable object allocated by recoverFindTable() or
7333 ** recoverOrphanTable().
7335 static void recoverFreeTable(RecoverTable *pTab){
7336 if( pTab ){
7337 sqlite3_free(pTab->zQuoted);
7338 if( pTab->azlCol ){
7339 int i;
7340 for(i=0; i<=pTab->nCol; i++){
7341 sqlite3_free(pTab->azlCol[i]);
7343 sqlite3_free(pTab->azlCol);
7345 sqlite3_free(pTab);
7350 ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7351 ** Otherwise, it allocates and returns a RecoverTable object based on the
7352 ** final four arguments passed to this function. It is the responsibility
7353 ** of the caller to eventually free the returned object using
7354 ** recoverFreeTable().
7356 static RecoverTable *recoverNewTable(
7357 int *pRc, /* IN/OUT: Error code */
7358 const char *zName, /* Name of table */
7359 const char *zSql, /* CREATE TABLE statement */
7360 int bIntkey,
7361 int nCol
7363 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
7364 int rc = *pRc;
7365 RecoverTable *pTab = 0;
7367 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7368 if( rc==SQLITE_OK ){
7369 int nSqlCol = 0;
7370 int bSqlIntkey = 0;
7371 sqlite3_stmt *pStmt = 0;
7373 rc = sqlite3_open("", &dbtmp);
7374 if( rc==SQLITE_OK ){
7375 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7376 shellIdQuote, 0, 0);
7378 if( rc==SQLITE_OK ){
7379 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7381 if( rc==SQLITE_OK ){
7382 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7383 if( rc==SQLITE_ERROR ){
7384 rc = SQLITE_OK;
7385 goto finished;
7388 shellPreparePrintf(dbtmp, &rc, &pStmt,
7389 "SELECT count(*) FROM pragma_table_info(%Q)", zName
7391 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7392 nSqlCol = sqlite3_column_int(pStmt, 0);
7394 shellFinalize(&rc, pStmt);
7396 if( rc!=SQLITE_OK || nSqlCol<nCol ){
7397 goto finished;
7400 shellPreparePrintf(dbtmp, &rc, &pStmt,
7401 "SELECT ("
7402 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7403 ") FROM sqlite_schema WHERE name = %Q", zName
7405 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7406 bSqlIntkey = sqlite3_column_int(pStmt, 0);
7408 shellFinalize(&rc, pStmt);
7410 if( bIntkey==bSqlIntkey ){
7411 int i;
7412 const char *zPk = "_rowid_";
7413 sqlite3_stmt *pPkFinder = 0;
7415 /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7416 ** set zPk to the name of the PK column, and pTab->iPk to the index
7417 ** of the column, where columns are 0-numbered from left to right.
7418 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7419 ** leave zPk as "_rowid_" and pTab->iPk at -2. */
7420 pTab->iPk = -2;
7421 if( bIntkey ){
7422 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7423 "SELECT cid, name FROM pragma_table_info(%Q) "
7424 " WHERE pk=1 AND type='integer' COLLATE nocase"
7425 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7426 , zName, zName
7428 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7429 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7430 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7431 if( zPk==0 ){ zPk = "_"; /* Defensive. Should never happen */ }
7435 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7436 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7437 pTab->nCol = nSqlCol;
7439 if( bIntkey ){
7440 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7441 }else{
7442 pTab->azlCol[0] = shellMPrintf(&rc, "");
7444 i = 1;
7445 shellPreparePrintf(dbtmp, &rc, &pStmt,
7446 "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7447 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7448 "FROM pragma_table_info(%Q)",
7449 bIntkey ? ", " : "", pTab->iPk,
7450 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7451 zName
7453 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7454 const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7455 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7456 i++;
7458 shellFinalize(&rc, pStmt);
7460 shellFinalize(&rc, pPkFinder);
7464 finished:
7465 sqlite3_close(dbtmp);
7466 *pRc = rc;
7467 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7468 recoverFreeTable(pTab);
7469 pTab = 0;
7471 return pTab;
7475 ** This function is called to search the schema recovered from the
7476 ** sqlite_schema table of the (possibly) corrupt database as part
7477 ** of a ".recover" command. Specifically, for a table with root page
7478 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7479 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
7480 ** those.
7482 ** If a table is found, a (RecoverTable*) object is returned. Or, if
7483 ** no such table is found, but bIntkey is false and iRoot is the
7484 ** root page of an index in the recovered schema, then (*pbNoop) is
7485 ** set to true and NULL returned. Or, if there is no such table or
7486 ** index, NULL is returned and (*pbNoop) set to 0, indicating that
7487 ** the caller should write data to the orphans table.
7489 static RecoverTable *recoverFindTable(
7490 ShellState *pState, /* Shell state object */
7491 int *pRc, /* IN/OUT: Error code */
7492 int iRoot, /* Root page of table */
7493 int bIntkey, /* True for an intkey table */
7494 int nCol, /* Number of columns in table */
7495 int *pbNoop /* OUT: True if iRoot is root of index */
7497 sqlite3_stmt *pStmt = 0;
7498 RecoverTable *pRet = 0;
7499 int bNoop = 0;
7500 const char *zSql = 0;
7501 const char *zName = 0;
7503 /* Search the recovered schema for an object with root page iRoot. */
7504 shellPreparePrintf(pState->db, pRc, &pStmt,
7505 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7507 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7508 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7509 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7510 bNoop = 1;
7511 break;
7513 if( sqlite3_stricmp(zType, "table")==0 ){
7514 zName = (const char*)sqlite3_column_text(pStmt, 1);
7515 zSql = (const char*)sqlite3_column_text(pStmt, 2);
7516 if( zName!=0 && zSql!=0 ){
7517 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7518 break;
7523 shellFinalize(pRc, pStmt);
7524 *pbNoop = bNoop;
7525 return pRet;
7529 ** Return a RecoverTable object representing the orphans table.
7531 static RecoverTable *recoverOrphanTable(
7532 ShellState *pState, /* Shell state object */
7533 int *pRc, /* IN/OUT: Error code */
7534 const char *zLostAndFound, /* Base name for orphans table */
7535 int nCol /* Number of user data columns */
7537 RecoverTable *pTab = 0;
7538 if( nCol>=0 && *pRc==SQLITE_OK ){
7539 int i;
7541 /* This block determines the name of the orphan table. The prefered
7542 ** name is zLostAndFound. But if that clashes with another name
7543 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7544 ** and so on until a non-clashing name is found. */
7545 int iTab = 0;
7546 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7547 sqlite3_stmt *pTest = 0;
7548 shellPrepare(pState->db, pRc,
7549 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7551 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7552 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7553 shellReset(pRc, pTest);
7554 sqlite3_free(zTab);
7555 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7556 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7558 shellFinalize(pRc, pTest);
7560 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7561 if( pTab ){
7562 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7563 pTab->nCol = nCol;
7564 pTab->iPk = -2;
7565 if( nCol>0 ){
7566 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7567 if( pTab->azlCol ){
7568 pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7569 for(i=nCol-1; i>=0; i--){
7570 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7575 if( *pRc!=SQLITE_OK ){
7576 recoverFreeTable(pTab);
7577 pTab = 0;
7578 }else{
7579 raw_printf(pState->out,
7580 "CREATE TABLE %s(rootpgno INTEGER, "
7581 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7583 for(i=0; i<nCol; i++){
7584 raw_printf(pState->out, ", c%d", i);
7586 raw_printf(pState->out, ");\n");
7589 sqlite3_free(zTab);
7591 return pTab;
7595 ** This function is called to recover data from the database. A script
7596 ** to construct a new database containing all recovered data is output
7597 ** on stream pState->out.
7599 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7600 int rc = SQLITE_OK;
7601 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
7602 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
7603 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
7604 const char *zRecoveryDb = ""; /* Name of "recovery" database */
7605 const char *zLostAndFound = "lost_and_found";
7606 int i;
7607 int nOrphan = -1;
7608 RecoverTable *pOrphan = 0;
7610 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
7611 int bRowids = 1; /* 0 if --no-rowids */
7612 for(i=1; i<nArg; i++){
7613 char *z = azArg[i];
7614 int n;
7615 if( z[0]=='-' && z[1]=='-' ) z++;
7616 n = strlen30(z);
7617 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7618 bFreelist = 0;
7619 }else
7620 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7621 i++;
7622 zRecoveryDb = azArg[i];
7623 }else
7624 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7625 i++;
7626 zLostAndFound = azArg[i];
7627 }else
7628 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7629 bRowids = 0;
7631 else{
7632 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7633 showHelp(pState->out, azArg[0]);
7634 return 1;
7638 shellExecPrintf(pState->db, &rc,
7639 /* Attach an in-memory database named 'recovery'. Create an indexed
7640 ** cache of the sqlite_dbptr virtual table. */
7641 "PRAGMA writable_schema = on;"
7642 "ATTACH %Q AS recovery;"
7643 "DROP TABLE IF EXISTS recovery.dbptr;"
7644 "DROP TABLE IF EXISTS recovery.freelist;"
7645 "DROP TABLE IF EXISTS recovery.map;"
7646 "DROP TABLE IF EXISTS recovery.schema;"
7647 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7650 if( bFreelist ){
7651 shellExec(pState->db, &rc,
7652 "WITH trunk(pgno) AS ("
7653 " SELECT shell_int32("
7654 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7655 " WHERE x>0"
7656 " UNION"
7657 " SELECT shell_int32("
7658 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7659 " FROM trunk WHERE x>0"
7660 "),"
7661 "freelist(data, n, freepgno) AS ("
7662 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7663 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7664 " UNION ALL"
7665 " SELECT data, n-1, shell_int32(data, 2+n) "
7666 " FROM freelist WHERE n>=0"
7668 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7672 /* If this is an auto-vacuum database, add all pointer-map pages to
7673 ** the freelist table. Do this regardless of whether or not
7674 ** --freelist-corrupt was specified. */
7675 shellExec(pState->db, &rc,
7676 "WITH ptrmap(pgno) AS ("
7677 " SELECT 2 WHERE shell_int32("
7678 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7679 " )"
7680 " UNION ALL "
7681 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7682 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7684 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7687 shellExec(pState->db, &rc,
7688 "CREATE TABLE recovery.dbptr("
7689 " pgno, child, PRIMARY KEY(child, pgno)"
7690 ") WITHOUT ROWID;"
7691 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7692 " SELECT * FROM sqlite_dbptr"
7693 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7695 /* Delete any pointer to page 1. This ensures that page 1 is considered
7696 ** a root page, regardless of how corrupt the db is. */
7697 "DELETE FROM recovery.dbptr WHERE child = 1;"
7699 /* Delete all pointers to any pages that have more than one pointer
7700 ** to them. Such pages will be treated as root pages when recovering
7701 ** data. */
7702 "DELETE FROM recovery.dbptr WHERE child IN ("
7703 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7704 ");"
7706 /* Create the "map" table that will (eventually) contain instructions
7707 ** for dealing with each page in the db that contains one or more
7708 ** records. */
7709 "CREATE TABLE recovery.map("
7710 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7711 ");"
7713 /* Populate table [map]. If there are circular loops of pages in the
7714 ** database, the following adds all pages in such a loop to the map
7715 ** as individual root pages. This could be handled better. */
7716 "WITH pages(i, maxlen) AS ("
7717 " SELECT page_count, ("
7718 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7719 " ) FROM pragma_page_count WHERE page_count>0"
7720 " UNION ALL"
7721 " SELECT i-1, ("
7722 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7723 " ) FROM pages WHERE i>=2"
7725 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7726 " SELECT i, maxlen, NULL, ("
7727 " WITH p(orig, pgno, parent) AS ("
7728 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7729 " UNION "
7730 " SELECT i, p.parent, "
7731 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7732 " )"
7733 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7734 ") "
7735 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7736 "UPDATE recovery.map AS o SET intkey = ("
7737 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7738 ");"
7740 /* Extract data from page 1 and any linked pages into table
7741 ** recovery.schema. With the same schema as an sqlite_schema table. */
7742 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7743 "INSERT INTO recovery.schema SELECT "
7744 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
7745 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
7746 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
7747 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
7748 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
7749 "FROM sqlite_dbdata WHERE pgno IN ("
7750 " SELECT pgno FROM recovery.map WHERE root=1"
7752 "GROUP BY pgno, cell;"
7753 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7756 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7757 ** CREATE TABLE statements that extracted from the existing schema. */
7758 if( rc==SQLITE_OK ){
7759 sqlite3_stmt *pStmt = 0;
7760 /* ".recover" might output content in an order which causes immediate
7761 ** foreign key constraints to be violated. So disable foreign-key
7762 ** constraint enforcement to prevent problems when running the output
7763 ** script. */
7764 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7765 raw_printf(pState->out, "BEGIN;\n");
7766 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7767 shellPrepare(pState->db, &rc,
7768 "SELECT sql FROM recovery.schema "
7769 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7771 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7772 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7773 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7774 &zCreateTable[12]
7777 shellFinalize(&rc, pStmt);
7780 /* Figure out if an orphan table will be required. And if so, how many
7781 ** user columns it should contain */
7782 shellPrepare(pState->db, &rc,
7783 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7784 , &pLoop
7786 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7787 nOrphan = sqlite3_column_int(pLoop, 0);
7789 shellFinalize(&rc, pLoop);
7790 pLoop = 0;
7792 shellPrepare(pState->db, &rc,
7793 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7796 shellPrepare(pState->db, &rc,
7797 "SELECT max(field), group_concat(shell_escape_crnl(quote"
7798 "(case when (? AND field<0) then NULL else value end)"
7799 "), ', ')"
7800 ", min(field) "
7801 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7802 "GROUP BY cell", &pCells
7805 /* Loop through each root page. */
7806 shellPrepare(pState->db, &rc,
7807 "SELECT root, intkey, max(maxlen) FROM recovery.map"
7808 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7809 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7810 ")", &pLoop
7812 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7813 int iRoot = sqlite3_column_int(pLoop, 0);
7814 int bIntkey = sqlite3_column_int(pLoop, 1);
7815 int nCol = sqlite3_column_int(pLoop, 2);
7816 int bNoop = 0;
7817 RecoverTable *pTab;
7819 assert( bIntkey==0 || bIntkey==1 );
7820 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7821 if( bNoop || rc ) continue;
7822 if( pTab==0 ){
7823 if( pOrphan==0 ){
7824 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7826 pTab = pOrphan;
7827 if( pTab==0 ) break;
7830 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7831 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7833 sqlite3_bind_int(pPages, 1, iRoot);
7834 if( bRowids==0 && pTab->iPk<0 ){
7835 sqlite3_bind_int(pCells, 1, 1);
7836 }else{
7837 sqlite3_bind_int(pCells, 1, 0);
7839 sqlite3_bind_int(pCells, 3, pTab->iPk);
7841 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7842 int iPgno = sqlite3_column_int(pPages, 0);
7843 sqlite3_bind_int(pCells, 2, iPgno);
7844 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7845 int nField = sqlite3_column_int(pCells, 0);
7846 int iMin = sqlite3_column_int(pCells, 2);
7847 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7849 RecoverTable *pTab2 = pTab;
7850 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7851 if( pOrphan==0 ){
7852 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7854 pTab2 = pOrphan;
7855 if( pTab2==0 ) break;
7858 nField = nField+1;
7859 if( pTab2==pOrphan ){
7860 raw_printf(pState->out,
7861 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7862 pTab2->zQuoted, iRoot, iPgno, nField,
7863 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7865 }else{
7866 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7867 pTab2->zQuoted, pTab2->azlCol[nField], zVal
7871 shellReset(&rc, pCells);
7873 shellReset(&rc, pPages);
7874 if( pTab!=pOrphan ) recoverFreeTable(pTab);
7876 shellFinalize(&rc, pLoop);
7877 shellFinalize(&rc, pPages);
7878 shellFinalize(&rc, pCells);
7879 recoverFreeTable(pOrphan);
7881 /* The rest of the schema */
7882 if( rc==SQLITE_OK ){
7883 sqlite3_stmt *pStmt = 0;
7884 shellPrepare(pState->db, &rc,
7885 "SELECT sql, name FROM recovery.schema "
7886 "WHERE sql NOT LIKE 'create table%'", &pStmt
7888 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7889 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7890 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7891 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7892 char *zPrint = shellMPrintf(&rc,
7893 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7894 zName, zName, zSql
7896 raw_printf(pState->out, "%s;\n", zPrint);
7897 sqlite3_free(zPrint);
7898 }else{
7899 raw_printf(pState->out, "%s;\n", zSql);
7902 shellFinalize(&rc, pStmt);
7905 if( rc==SQLITE_OK ){
7906 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7907 raw_printf(pState->out, "COMMIT;\n");
7909 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7910 return rc;
7912 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7916 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7917 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7918 * close db and set it to 0, and return the columns spec, to later
7919 * be sqlite3_free()'ed by the caller.
7920 * The return is 0 when either:
7921 * (a) The db was not initialized and zCol==0 (There are no columns.)
7922 * (b) zCol!=0 (Column was added, db initialized as needed.)
7923 * The 3rd argument, pRenamed, references an out parameter. If the
7924 * pointer is non-zero, its referent will be set to a summary of renames
7925 * done if renaming was necessary, or set to 0 if none was done. The out
7926 * string (if any) must be sqlite3_free()'ed by the caller.
7928 #ifdef SHELL_DEBUG
7929 #define rc_err_oom_die(rc) \
7930 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7931 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7932 fprintf(stderr,"E:%d\n",rc), assert(0)
7933 #else
7934 static void rc_err_oom_die(int rc){
7935 if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7936 assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7938 #endif
7940 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7941 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7942 #else /* Otherwise, memory is faster/better for the transient DB. */
7943 static const char *zCOL_DB = ":memory:";
7944 #endif
7946 /* Define character (as C string) to separate generated column ordinal
7947 * from protected part of incoming column names. This defaults to "_"
7948 * so that incoming column identifiers that did not need not be quoted
7949 * remain usable without being quoted. It must be one character.
7951 #ifndef SHELL_AUTOCOLUMN_SEP
7952 # define AUTOCOLUMN_SEP "_"
7953 #else
7954 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7955 #endif
7957 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7958 /* Queries and D{D,M}L used here */
7959 static const char * const zTabMake = "\
7960 CREATE TABLE ColNames(\
7961 cpos INTEGER PRIMARY KEY,\
7962 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7963 CREATE VIEW RepeatedNames AS \
7964 SELECT DISTINCT t.name FROM ColNames t \
7965 WHERE t.name COLLATE NOCASE IN (\
7966 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7969 static const char * const zTabFill = "\
7970 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7971 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7973 static const char * const zHasDupes = "\
7974 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7975 <count(name) FROM ColNames\
7977 #ifdef SHELL_COLUMN_RENAME_CLEAN
7978 static const char * const zDedoctor = "\
7979 UPDATE ColNames SET chop=iif(\
7980 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7981 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7982 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7986 #endif
7987 static const char * const zSetReps = "\
7988 UPDATE ColNames AS t SET reps=\
7989 (SELECT count(*) FROM ColNames d \
7990 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7991 COLLATE NOCASE\
7994 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7995 static const char * const zColDigits = "\
7996 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7998 #else
7999 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
8000 static const char * const zColDigits = "\
8001 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
8002 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
8003 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
8005 #endif
8006 static const char * const zRenameRank =
8007 #ifdef SHELL_COLUMN_RENAME_CLEAN
8008 "UPDATE ColNames AS t SET suff="
8009 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
8010 #else /* ...RENAME_MINIMAL_ONE_PASS */
8011 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
8012 " SELECT 0 AS nlz"
8013 " UNION"
8014 " SELECT nlz+1 AS nlz FROM Lzn"
8015 " WHERE EXISTS("
8016 " SELECT 1"
8017 " FROM ColNames t, ColNames o"
8018 " WHERE"
8019 " iif(t.name IN (SELECT * FROM RepeatedNames),"
8020 " printf('%s"AUTOCOLUMN_SEP"%s',"
8021 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8022 " t.name"
8023 " )"
8024 " ="
8025 " iif(o.name IN (SELECT * FROM RepeatedNames),"
8026 " printf('%s"AUTOCOLUMN_SEP"%s',"
8027 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8028 " o.name"
8029 " )"
8030 " COLLATE NOCASE"
8031 " AND o.cpos<>t.cpos"
8032 " GROUP BY t.cpos"
8033 " )"
8034 ") UPDATE Colnames AS t SET"
8035 " chop = 0," /* No chopping, never touch incoming names. */
8036 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
8037 " printf('"AUTOCOLUMN_SEP"%s', substring("
8038 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8039 " ''"
8040 " )"
8041 #endif
8043 static const char * const zCollectVar = "\
8044 SELECT\
8045 '('||x'0a'\
8046 || group_concat(\
8047 cname||' TEXT',\
8048 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8049 ||')' AS ColsSpec \
8050 FROM (\
8051 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8052 FROM ColNames ORDER BY cpos\
8054 static const char * const zRenamesDone =
8055 "SELECT group_concat("
8056 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8057 " ','||x'0a')"
8058 "FROM ColNames WHERE suff<>'' OR chop!=0"
8060 int rc;
8061 sqlite3_stmt *pStmt = 0;
8062 assert(pDb!=0);
8063 if( zColNew ){
8064 /* Add initial or additional column. Init db if necessary. */
8065 if( *pDb==0 ){
8066 if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8067 #ifdef SHELL_COLFIX_DB
8068 if(*zCOL_DB!=':')
8069 sqlite3_exec(*pDb,"drop table if exists ColNames;"
8070 "drop view if exists RepeatedNames;",0,0,0);
8071 #endif
8072 rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8073 rc_err_oom_die(rc);
8075 assert(*pDb!=0);
8076 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8077 rc_err_oom_die(rc);
8078 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8079 rc_err_oom_die(rc);
8080 rc = sqlite3_step(pStmt);
8081 rc_err_oom_die(rc);
8082 sqlite3_finalize(pStmt);
8083 return 0;
8084 }else if( *pDb==0 ){
8085 return 0;
8086 }else{
8087 /* Formulate the columns spec, close the DB, zero *pDb. */
8088 char *zColsSpec = 0;
8089 int hasDupes = db_int(*pDb, zHasDupes);
8090 int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8091 if( hasDupes ){
8092 #ifdef SHELL_COLUMN_RENAME_CLEAN
8093 rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8094 rc_err_oom_die(rc);
8095 #endif
8096 rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8097 rc_err_oom_die(rc);
8098 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8099 rc_err_oom_die(rc);
8100 sqlite3_bind_int(pStmt, 1, nDigits);
8101 rc = sqlite3_step(pStmt);
8102 sqlite3_finalize(pStmt);
8103 assert(rc==SQLITE_DONE);
8105 assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8106 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8107 rc_err_oom_die(rc);
8108 rc = sqlite3_step(pStmt);
8109 if( rc==SQLITE_ROW ){
8110 zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8111 }else{
8112 zColsSpec = 0;
8114 if( pzRenamed!=0 ){
8115 if( !hasDupes ) *pzRenamed = 0;
8116 else{
8117 sqlite3_finalize(pStmt);
8118 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8119 && SQLITE_ROW==sqlite3_step(pStmt) ){
8120 *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8121 }else
8122 *pzRenamed = 0;
8125 sqlite3_finalize(pStmt);
8126 sqlite3_close(*pDb);
8127 *pDb = 0;
8128 return zColsSpec;
8133 ** If an input line begins with "." then invoke this routine to
8134 ** process that line.
8136 ** Return 1 on error, 2 to exit, and 0 otherwise.
8138 static int do_meta_command(char *zLine, ShellState *p){
8139 int h = 1;
8140 int nArg = 0;
8141 int n, c;
8142 int rc = 0;
8143 char *azArg[52];
8145 #ifndef SQLITE_OMIT_VIRTUALTABLE
8146 if( p->expert.pExpert ){
8147 expertFinish(p, 1, 0);
8149 #endif
8151 /* Parse the input line into tokens.
8153 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8154 while( IsSpace(zLine[h]) ){ h++; }
8155 if( zLine[h]==0 ) break;
8156 if( zLine[h]=='\'' || zLine[h]=='"' ){
8157 int delim = zLine[h++];
8158 azArg[nArg++] = &zLine[h];
8159 while( zLine[h] && zLine[h]!=delim ){
8160 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8161 h++;
8163 if( zLine[h]==delim ){
8164 zLine[h++] = 0;
8166 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8167 }else{
8168 azArg[nArg++] = &zLine[h];
8169 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8170 if( zLine[h] ) zLine[h++] = 0;
8171 resolve_backslashes(azArg[nArg-1]);
8174 azArg[nArg] = 0;
8176 /* Process the input line.
8178 if( nArg==0 ) return 0; /* no tokens, no error */
8179 n = strlen30(azArg[0]);
8180 c = azArg[0][0];
8181 clearTempFile(p);
8183 #ifndef SQLITE_OMIT_AUTHORIZATION
8184 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8185 if( nArg!=2 ){
8186 raw_printf(stderr, "Usage: .auth ON|OFF\n");
8187 rc = 1;
8188 goto meta_command_exit;
8190 open_db(p, 0);
8191 if( booleanValue(azArg[1]) ){
8192 sqlite3_set_authorizer(p->db, shellAuth, p);
8193 }else if( p->bSafeModePersist ){
8194 sqlite3_set_authorizer(p->db, safeModeAuth, p);
8195 }else{
8196 sqlite3_set_authorizer(p->db, 0, 0);
8198 }else
8199 #endif
8201 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8202 && !defined(SQLITE_SHELL_WASM_MODE)
8203 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8204 open_db(p, 0);
8205 failIfSafeMode(p, "cannot run .archive in safe mode");
8206 rc = arDotCommand(p, 0, azArg, nArg);
8207 }else
8208 #endif
8210 #ifndef SQLITE_SHELL_WASM_MODE
8211 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8212 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8214 const char *zDestFile = 0;
8215 const char *zDb = 0;
8216 sqlite3 *pDest;
8217 sqlite3_backup *pBackup;
8218 int j;
8219 int bAsync = 0;
8220 const char *zVfs = 0;
8221 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8222 for(j=1; j<nArg; j++){
8223 const char *z = azArg[j];
8224 if( z[0]=='-' ){
8225 if( z[1]=='-' ) z++;
8226 if( strcmp(z, "-append")==0 ){
8227 zVfs = "apndvfs";
8228 }else
8229 if( strcmp(z, "-async")==0 ){
8230 bAsync = 1;
8231 }else
8233 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8234 return 1;
8236 }else if( zDestFile==0 ){
8237 zDestFile = azArg[j];
8238 }else if( zDb==0 ){
8239 zDb = zDestFile;
8240 zDestFile = azArg[j];
8241 }else{
8242 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8243 return 1;
8246 if( zDestFile==0 ){
8247 raw_printf(stderr, "missing FILENAME argument on .backup\n");
8248 return 1;
8250 if( zDb==0 ) zDb = "main";
8251 rc = sqlite3_open_v2(zDestFile, &pDest,
8252 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8253 if( rc!=SQLITE_OK ){
8254 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8255 close_db(pDest);
8256 return 1;
8258 if( bAsync ){
8259 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8260 0, 0, 0);
8262 open_db(p, 0);
8263 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8264 if( pBackup==0 ){
8265 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8266 close_db(pDest);
8267 return 1;
8269 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8270 sqlite3_backup_finish(pBackup);
8271 if( rc==SQLITE_DONE ){
8272 rc = 0;
8273 }else{
8274 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8275 rc = 1;
8277 close_db(pDest);
8278 }else
8279 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8281 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8282 if( nArg==2 ){
8283 bail_on_error = booleanValue(azArg[1]);
8284 }else{
8285 raw_printf(stderr, "Usage: .bail on|off\n");
8286 rc = 1;
8288 }else
8290 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8291 if( nArg==2 ){
8292 if( booleanValue(azArg[1]) ){
8293 setBinaryMode(p->out, 1);
8294 }else{
8295 setTextMode(p->out, 1);
8297 }else{
8298 raw_printf(stderr, "Usage: .binary on|off\n");
8299 rc = 1;
8301 }else
8303 /* The undocumented ".breakpoint" command causes a call to the no-op
8304 ** routine named test_breakpoint().
8306 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8307 test_breakpoint();
8308 }else
8310 #ifndef SQLITE_SHELL_WASM_MODE
8311 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8312 failIfSafeMode(p, "cannot run .cd in safe mode");
8313 if( nArg==2 ){
8314 #if defined(_WIN32) || defined(WIN32)
8315 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8316 rc = !SetCurrentDirectoryW(z);
8317 sqlite3_free(z);
8318 #else
8319 rc = chdir(azArg[1]);
8320 #endif
8321 if( rc ){
8322 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8323 rc = 1;
8325 }else{
8326 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8327 rc = 1;
8329 }else
8330 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8332 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8333 if( nArg==2 ){
8334 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8335 }else{
8336 raw_printf(stderr, "Usage: .changes on|off\n");
8337 rc = 1;
8339 }else
8341 #ifndef SQLITE_SHELL_WASM_MODE
8342 /* Cancel output redirection, if it is currently set (by .testcase)
8343 ** Then read the content of the testcase-out.txt file and compare against
8344 ** azArg[1]. If there are differences, report an error and exit.
8346 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8347 char *zRes = 0;
8348 output_reset(p);
8349 if( nArg!=2 ){
8350 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8351 rc = 2;
8352 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8353 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8354 rc = 2;
8355 }else if( testcase_glob(azArg[1],zRes)==0 ){
8356 utf8_printf(stderr,
8357 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8358 p->zTestcase, azArg[1], zRes);
8359 rc = 1;
8360 }else{
8361 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8362 p->nCheck++;
8364 sqlite3_free(zRes);
8365 }else
8366 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8368 #ifndef SQLITE_SHELL_WASM_MODE
8369 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8370 failIfSafeMode(p, "cannot run .clone in safe mode");
8371 if( nArg==2 ){
8372 tryToClone(p, azArg[1]);
8373 }else{
8374 raw_printf(stderr, "Usage: .clone FILENAME\n");
8375 rc = 1;
8377 }else
8378 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8380 if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8381 if( nArg==1 ){
8382 /* List available connections */
8383 int i;
8384 for(i=0; i<ArraySize(p->aAuxDb); i++){
8385 const char *zFile = p->aAuxDb[i].zDbFilename;
8386 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8387 zFile = "(not open)";
8388 }else if( zFile==0 ){
8389 zFile = "(memory)";
8390 }else if( zFile[0]==0 ){
8391 zFile = "(temporary-file)";
8393 if( p->pAuxDb == &p->aAuxDb[i] ){
8394 utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8395 }else if( p->aAuxDb[i].db!=0 ){
8396 utf8_printf(stdout, " %d: %s\n", i, zFile);
8399 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8400 int i = azArg[1][0] - '0';
8401 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8402 p->pAuxDb->db = p->db;
8403 p->pAuxDb = &p->aAuxDb[i];
8404 globalDb = p->db = p->pAuxDb->db;
8405 p->pAuxDb->db = 0;
8407 }else if( nArg==3 && strcmp(azArg[1], "close")==0
8408 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8409 int i = azArg[2][0] - '0';
8410 if( i<0 || i>=ArraySize(p->aAuxDb) ){
8411 /* No-op */
8412 }else if( p->pAuxDb == &p->aAuxDb[i] ){
8413 raw_printf(stderr, "cannot close the active database connection\n");
8414 rc = 1;
8415 }else if( p->aAuxDb[i].db ){
8416 session_close_all(p, i);
8417 close_db(p->aAuxDb[i].db);
8418 p->aAuxDb[i].db = 0;
8420 }else{
8421 raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8422 rc = 1;
8424 }else
8426 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8427 char **azName = 0;
8428 int nName = 0;
8429 sqlite3_stmt *pStmt;
8430 int i;
8431 open_db(p, 0);
8432 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8433 if( rc ){
8434 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8435 rc = 1;
8436 }else{
8437 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8438 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8439 const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8440 if( zSchema==0 || zFile==0 ) continue;
8441 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8442 shell_check_oom(azName);
8443 azName[nName*2] = strdup(zSchema);
8444 azName[nName*2+1] = strdup(zFile);
8445 nName++;
8448 sqlite3_finalize(pStmt);
8449 for(i=0; i<nName; i++){
8450 int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8451 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8452 const char *z = azName[i*2+1];
8453 utf8_printf(p->out, "%s: %s %s%s\n",
8454 azName[i*2],
8455 z && z[0] ? z : "\"\"",
8456 bRdonly ? "r/o" : "r/w",
8457 eTxn==SQLITE_TXN_NONE ? "" :
8458 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8459 free(azName[i*2]);
8460 free(azName[i*2+1]);
8462 sqlite3_free(azName);
8463 }else
8465 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8466 static const struct DbConfigChoices {
8467 const char *zName;
8468 int op;
8469 } aDbConfig[] = {
8470 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
8471 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
8472 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
8473 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
8474 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
8475 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
8476 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
8477 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8478 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
8479 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
8480 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8481 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
8482 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
8483 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
8484 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
8485 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
8487 int ii, v;
8488 open_db(p, 0);
8489 for(ii=0; ii<ArraySize(aDbConfig); ii++){
8490 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8491 if( nArg>=3 ){
8492 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8494 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8495 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8496 if( nArg>1 ) break;
8498 if( nArg>1 && ii==ArraySize(aDbConfig) ){
8499 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8500 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8502 }else
8504 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8505 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8506 rc = shell_dbinfo_command(p, nArg, azArg);
8507 }else
8509 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8510 open_db(p, 0);
8511 rc = recoverDatabaseCmd(p, nArg, azArg);
8512 }else
8513 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8515 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8516 char *zLike = 0;
8517 char *zSql;
8518 int i;
8519 int savedShowHeader = p->showHeader;
8520 int savedShellFlags = p->shellFlgs;
8521 ShellClearFlag(p,
8522 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8523 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8524 for(i=1; i<nArg; i++){
8525 if( azArg[i][0]=='-' ){
8526 const char *z = azArg[i]+1;
8527 if( z[0]=='-' ) z++;
8528 if( strcmp(z,"preserve-rowids")==0 ){
8529 #ifdef SQLITE_OMIT_VIRTUALTABLE
8530 raw_printf(stderr, "The --preserve-rowids option is not compatible"
8531 " with SQLITE_OMIT_VIRTUALTABLE\n");
8532 rc = 1;
8533 sqlite3_free(zLike);
8534 goto meta_command_exit;
8535 #else
8536 ShellSetFlag(p, SHFLG_PreserveRowid);
8537 #endif
8538 }else
8539 if( strcmp(z,"newlines")==0 ){
8540 ShellSetFlag(p, SHFLG_Newlines);
8541 }else
8542 if( strcmp(z,"data-only")==0 ){
8543 ShellSetFlag(p, SHFLG_DumpDataOnly);
8544 }else
8545 if( strcmp(z,"nosys")==0 ){
8546 ShellSetFlag(p, SHFLG_DumpNoSys);
8547 }else
8549 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8550 rc = 1;
8551 sqlite3_free(zLike);
8552 goto meta_command_exit;
8554 }else{
8555 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8556 ** only dump data for tables for which either the table name matches
8557 ** the LIKE pattern, or the table appears to be a shadow table of
8558 ** a virtual table for which the name matches the LIKE pattern.
8560 char *zExpr = sqlite3_mprintf(
8561 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8562 " SELECT 1 FROM sqlite_schema WHERE "
8563 " name LIKE %Q ESCAPE '\\' AND"
8564 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8565 " substr(o.name, 1, length(name)+1) == (name||'_')"
8566 ")", azArg[i], azArg[i]
8569 if( zLike ){
8570 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8571 }else{
8572 zLike = zExpr;
8577 open_db(p, 0);
8579 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8580 /* When playing back a "dump", the content might appear in an order
8581 ** which causes immediate foreign key constraints to be violated.
8582 ** So disable foreign-key constraint enforcement to prevent problems. */
8583 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8584 raw_printf(p->out, "BEGIN TRANSACTION;\n");
8586 p->writableSchema = 0;
8587 p->showHeader = 0;
8588 /* Set writable_schema=ON since doing so forces SQLite to initialize
8589 ** as much of the schema as it can even if the sqlite_schema table is
8590 ** corrupt. */
8591 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8592 p->nErr = 0;
8593 if( zLike==0 ) zLike = sqlite3_mprintf("true");
8594 zSql = sqlite3_mprintf(
8595 "SELECT name, type, sql FROM sqlite_schema AS o "
8596 "WHERE (%s) AND type=='table'"
8597 " AND sql NOT NULL"
8598 " ORDER BY tbl_name='sqlite_sequence', rowid",
8599 zLike
8601 run_schema_dump_query(p,zSql);
8602 sqlite3_free(zSql);
8603 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8604 zSql = sqlite3_mprintf(
8605 "SELECT sql FROM sqlite_schema AS o "
8606 "WHERE (%s) AND sql NOT NULL"
8607 " AND type IN ('index','trigger','view')",
8608 zLike
8610 run_table_dump_query(p, zSql);
8611 sqlite3_free(zSql);
8613 sqlite3_free(zLike);
8614 if( p->writableSchema ){
8615 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8616 p->writableSchema = 0;
8618 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8619 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8620 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8621 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8623 p->showHeader = savedShowHeader;
8624 p->shellFlgs = savedShellFlags;
8625 }else
8627 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8628 if( nArg==2 ){
8629 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8630 }else{
8631 raw_printf(stderr, "Usage: .echo on|off\n");
8632 rc = 1;
8634 }else
8636 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8637 if( nArg==2 ){
8638 p->autoEQPtest = 0;
8639 if( p->autoEQPtrace ){
8640 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8641 p->autoEQPtrace = 0;
8643 if( strcmp(azArg[1],"full")==0 ){
8644 p->autoEQP = AUTOEQP_full;
8645 }else if( strcmp(azArg[1],"trigger")==0 ){
8646 p->autoEQP = AUTOEQP_trigger;
8647 #ifdef SQLITE_DEBUG
8648 }else if( strcmp(azArg[1],"test")==0 ){
8649 p->autoEQP = AUTOEQP_on;
8650 p->autoEQPtest = 1;
8651 }else if( strcmp(azArg[1],"trace")==0 ){
8652 p->autoEQP = AUTOEQP_full;
8653 p->autoEQPtrace = 1;
8654 open_db(p, 0);
8655 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8656 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8657 #endif
8658 }else{
8659 p->autoEQP = (u8)booleanValue(azArg[1]);
8661 }else{
8662 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8663 rc = 1;
8665 }else
8667 #ifndef SQLITE_SHELL_WASM_MODE
8668 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8669 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8670 rc = 2;
8671 }else
8672 #endif
8674 /* The ".explain" command is automatic now. It is largely pointless. It
8675 ** retained purely for backwards compatibility */
8676 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8677 int val = 1;
8678 if( nArg>=2 ){
8679 if( strcmp(azArg[1],"auto")==0 ){
8680 val = 99;
8681 }else{
8682 val = booleanValue(azArg[1]);
8685 if( val==1 && p->mode!=MODE_Explain ){
8686 p->normalMode = p->mode;
8687 p->mode = MODE_Explain;
8688 p->autoExplain = 0;
8689 }else if( val==0 ){
8690 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8691 p->autoExplain = 0;
8692 }else if( val==99 ){
8693 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8694 p->autoExplain = 1;
8696 }else
8698 #ifndef SQLITE_OMIT_VIRTUALTABLE
8699 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8700 if( p->bSafeMode ){
8701 raw_printf(stderr,
8702 "Cannot run experimental commands such as \"%s\" in safe mode\n",
8703 azArg[0]);
8704 rc = 1;
8705 }else{
8706 open_db(p, 0);
8707 expertDotCommand(p, azArg, nArg);
8709 }else
8710 #endif
8712 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8713 static const struct {
8714 const char *zCtrlName; /* Name of a test-control option */
8715 int ctrlCode; /* Integer code for that option */
8716 const char *zUsage; /* Usage notes */
8717 } aCtrl[] = {
8718 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
8719 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
8720 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
8721 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
8722 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
8723 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8724 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
8725 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
8726 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
8727 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
8728 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8730 int filectrl = -1;
8731 int iCtrl = -1;
8732 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
8733 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
8734 int n2, i;
8735 const char *zCmd = 0;
8736 const char *zSchema = 0;
8738 open_db(p, 0);
8739 zCmd = nArg>=2 ? azArg[1] : "help";
8741 if( zCmd[0]=='-'
8742 && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8743 && nArg>=4
8745 zSchema = azArg[2];
8746 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8747 nArg -= 2;
8748 zCmd = azArg[1];
8751 /* The argument can optionally begin with "-" or "--" */
8752 if( zCmd[0]=='-' && zCmd[1] ){
8753 zCmd++;
8754 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8757 /* --help lists all file-controls */
8758 if( strcmp(zCmd,"help")==0 ){
8759 utf8_printf(p->out, "Available file-controls:\n");
8760 for(i=0; i<ArraySize(aCtrl); i++){
8761 utf8_printf(p->out, " .filectrl %s %s\n",
8762 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8764 rc = 1;
8765 goto meta_command_exit;
8768 /* convert filectrl text option to value. allow any unique prefix
8769 ** of the option name, or a numerical value. */
8770 n2 = strlen30(zCmd);
8771 for(i=0; i<ArraySize(aCtrl); i++){
8772 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8773 if( filectrl<0 ){
8774 filectrl = aCtrl[i].ctrlCode;
8775 iCtrl = i;
8776 }else{
8777 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8778 "Use \".filectrl --help\" for help\n", zCmd);
8779 rc = 1;
8780 goto meta_command_exit;
8784 if( filectrl<0 ){
8785 utf8_printf(stderr,"Error: unknown file-control: %s\n"
8786 "Use \".filectrl --help\" for help\n", zCmd);
8787 }else{
8788 switch(filectrl){
8789 case SQLITE_FCNTL_SIZE_LIMIT: {
8790 if( nArg!=2 && nArg!=3 ) break;
8791 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8792 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8793 isOk = 1;
8794 break;
8796 case SQLITE_FCNTL_LOCK_TIMEOUT:
8797 case SQLITE_FCNTL_CHUNK_SIZE: {
8798 int x;
8799 if( nArg!=3 ) break;
8800 x = (int)integerValue(azArg[2]);
8801 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8802 isOk = 2;
8803 break;
8805 case SQLITE_FCNTL_PERSIST_WAL:
8806 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8807 int x;
8808 if( nArg!=2 && nArg!=3 ) break;
8809 x = nArg==3 ? booleanValue(azArg[2]) : -1;
8810 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8811 iRes = x;
8812 isOk = 1;
8813 break;
8815 case SQLITE_FCNTL_DATA_VERSION:
8816 case SQLITE_FCNTL_HAS_MOVED: {
8817 int x;
8818 if( nArg!=2 ) break;
8819 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8820 iRes = x;
8821 isOk = 1;
8822 break;
8824 case SQLITE_FCNTL_TEMPFILENAME: {
8825 char *z = 0;
8826 if( nArg!=2 ) break;
8827 sqlite3_file_control(p->db, zSchema, filectrl, &z);
8828 if( z ){
8829 utf8_printf(p->out, "%s\n", z);
8830 sqlite3_free(z);
8832 isOk = 2;
8833 break;
8835 case SQLITE_FCNTL_RESERVE_BYTES: {
8836 int x;
8837 if( nArg>=3 ){
8838 x = atoi(azArg[2]);
8839 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8841 x = -1;
8842 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8843 utf8_printf(p->out,"%d\n", x);
8844 isOk = 2;
8845 break;
8849 if( isOk==0 && iCtrl>=0 ){
8850 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8851 rc = 1;
8852 }else if( isOk==1 ){
8853 char zBuf[100];
8854 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8855 raw_printf(p->out, "%s\n", zBuf);
8857 }else
8859 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8860 ShellState data;
8861 int doStats = 0;
8862 memcpy(&data, p, sizeof(data));
8863 data.showHeader = 0;
8864 data.cMode = data.mode = MODE_Semi;
8865 if( nArg==2 && optionMatch(azArg[1], "indent") ){
8866 data.cMode = data.mode = MODE_Pretty;
8867 nArg = 1;
8869 if( nArg!=1 ){
8870 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8871 rc = 1;
8872 goto meta_command_exit;
8874 open_db(p, 0);
8875 rc = sqlite3_exec(p->db,
8876 "SELECT sql FROM"
8877 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8878 " FROM sqlite_schema UNION ALL"
8879 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8880 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8881 "ORDER BY x",
8882 callback, &data, 0
8884 if( rc==SQLITE_OK ){
8885 sqlite3_stmt *pStmt;
8886 rc = sqlite3_prepare_v2(p->db,
8887 "SELECT rowid FROM sqlite_schema"
8888 " WHERE name GLOB 'sqlite_stat[134]'",
8889 -1, &pStmt, 0);
8890 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8891 sqlite3_finalize(pStmt);
8893 if( doStats==0 ){
8894 raw_printf(p->out, "/* No STAT tables available */\n");
8895 }else{
8896 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8897 data.cMode = data.mode = MODE_Insert;
8898 data.zDestTable = "sqlite_stat1";
8899 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8900 data.zDestTable = "sqlite_stat4";
8901 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8902 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8904 }else
8906 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8907 if( nArg==2 ){
8908 p->showHeader = booleanValue(azArg[1]);
8909 p->shellFlgs |= SHFLG_HeaderSet;
8910 }else{
8911 raw_printf(stderr, "Usage: .headers on|off\n");
8912 rc = 1;
8914 }else
8916 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8917 if( nArg>=2 ){
8918 n = showHelp(p->out, azArg[1]);
8919 if( n==0 ){
8920 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8922 }else{
8923 showHelp(p->out, 0);
8925 }else
8927 #ifndef SQLITE_SHELL_WASM_MODE
8928 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8929 char *zTable = 0; /* Insert data into this table */
8930 char *zSchema = 0; /* within this schema (may default to "main") */
8931 char *zFile = 0; /* Name of file to extra content from */
8932 sqlite3_stmt *pStmt = NULL; /* A statement */
8933 int nCol; /* Number of columns in the table */
8934 int nByte; /* Number of bytes in an SQL string */
8935 int i, j; /* Loop counters */
8936 int needCommit; /* True to COMMIT or ROLLBACK at end */
8937 int nSep; /* Number of bytes in p->colSeparator[] */
8938 char *zSql; /* An SQL statement */
8939 char *zFullTabName; /* Table name with schema if applicable */
8940 ImportCtx sCtx; /* Reader context */
8941 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8942 int eVerbose = 0; /* Larger for more console output */
8943 int nSkip = 0; /* Initial lines to skip */
8944 int useOutputMode = 1; /* Use output mode to determine separators */
8945 char *zCreate = 0; /* CREATE TABLE statement text */
8947 failIfSafeMode(p, "cannot run .import in safe mode");
8948 memset(&sCtx, 0, sizeof(sCtx));
8949 if( p->mode==MODE_Ascii ){
8950 xRead = ascii_read_one_field;
8951 }else{
8952 xRead = csv_read_one_field;
8954 rc = 1;
8955 for(i=1; i<nArg; i++){
8956 char *z = azArg[i];
8957 if( z[0]=='-' && z[1]=='-' ) z++;
8958 if( z[0]!='-' ){
8959 if( zFile==0 ){
8960 zFile = z;
8961 }else if( zTable==0 ){
8962 zTable = z;
8963 }else{
8964 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
8965 showHelp(p->out, "import");
8966 goto meta_command_exit;
8968 }else if( strcmp(z,"-v")==0 ){
8969 eVerbose++;
8970 }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8971 zSchema = azArg[++i];
8972 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8973 nSkip = integerValue(azArg[++i]);
8974 }else if( strcmp(z,"-ascii")==0 ){
8975 sCtx.cColSep = SEP_Unit[0];
8976 sCtx.cRowSep = SEP_Record[0];
8977 xRead = ascii_read_one_field;
8978 useOutputMode = 0;
8979 }else if( strcmp(z,"-csv")==0 ){
8980 sCtx.cColSep = ',';
8981 sCtx.cRowSep = '\n';
8982 xRead = csv_read_one_field;
8983 useOutputMode = 0;
8984 }else{
8985 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
8986 showHelp(p->out, "import");
8987 goto meta_command_exit;
8990 if( zTable==0 ){
8991 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8992 zFile==0 ? "FILE" : "TABLE");
8993 showHelp(p->out, "import");
8994 goto meta_command_exit;
8996 seenInterrupt = 0;
8997 open_db(p, 0);
8998 if( useOutputMode ){
8999 /* If neither the --csv or --ascii options are specified, then set
9000 ** the column and row separator characters from the output mode. */
9001 nSep = strlen30(p->colSeparator);
9002 if( nSep==0 ){
9003 raw_printf(stderr,
9004 "Error: non-null column separator required for import\n");
9005 goto meta_command_exit;
9007 if( nSep>1 ){
9008 raw_printf(stderr,
9009 "Error: multi-character column separators not allowed"
9010 " for import\n");
9011 goto meta_command_exit;
9013 nSep = strlen30(p->rowSeparator);
9014 if( nSep==0 ){
9015 raw_printf(stderr,
9016 "Error: non-null row separator required for import\n");
9017 goto meta_command_exit;
9019 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9020 /* When importing CSV (only), if the row separator is set to the
9021 ** default output row separator, change it to the default input
9022 ** row separator. This avoids having to maintain different input
9023 ** and output row separators. */
9024 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9025 nSep = strlen30(p->rowSeparator);
9027 if( nSep>1 ){
9028 raw_printf(stderr, "Error: multi-character row separators not allowed"
9029 " for import\n");
9030 goto meta_command_exit;
9032 sCtx.cColSep = p->colSeparator[0];
9033 sCtx.cRowSep = p->rowSeparator[0];
9035 sCtx.zFile = zFile;
9036 sCtx.nLine = 1;
9037 if( sCtx.zFile[0]=='|' ){
9038 #ifdef SQLITE_OMIT_POPEN
9039 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9040 goto meta_command_exit;
9041 #else
9042 sCtx.in = popen(sCtx.zFile+1, "r");
9043 sCtx.zFile = "<pipe>";
9044 sCtx.xCloser = pclose;
9045 #endif
9046 }else{
9047 sCtx.in = fopen(sCtx.zFile, "rb");
9048 sCtx.xCloser = fclose;
9050 if( sCtx.in==0 ){
9051 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9052 goto meta_command_exit;
9054 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9055 char zSep[2];
9056 zSep[1] = 0;
9057 zSep[0] = sCtx.cColSep;
9058 utf8_printf(p->out, "Column separator ");
9059 output_c_string(p->out, zSep);
9060 utf8_printf(p->out, ", row separator ");
9061 zSep[0] = sCtx.cRowSep;
9062 output_c_string(p->out, zSep);
9063 utf8_printf(p->out, "\n");
9065 sCtx.z = sqlite3_malloc64(120);
9066 if( sCtx.z==0 ){
9067 import_cleanup(&sCtx);
9068 shell_out_of_memory();
9070 /* Below, resources must be freed before exit. */
9071 while( (nSkip--)>0 ){
9072 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9074 if( zSchema!=0 ){
9075 zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9076 }else{
9077 zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9079 zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9080 if( zSql==0 || zFullTabName==0 ){
9081 import_cleanup(&sCtx);
9082 shell_out_of_memory();
9084 nByte = strlen30(zSql);
9085 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9086 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
9087 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9088 sqlite3 *dbCols = 0;
9089 char *zRenames = 0;
9090 char *zColDefs;
9091 zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9092 while( xRead(&sCtx) ){
9093 zAutoColumn(sCtx.z, &dbCols, 0);
9094 if( sCtx.cTerm!=sCtx.cColSep ) break;
9096 zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9097 if( zRenames!=0 ){
9098 utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9099 "Columns renamed during .import %s due to duplicates:\n"
9100 "%s\n", sCtx.zFile, zRenames);
9101 sqlite3_free(zRenames);
9103 assert(dbCols==0);
9104 if( zColDefs==0 ){
9105 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9106 import_fail:
9107 sqlite3_free(zCreate);
9108 sqlite3_free(zSql);
9109 sqlite3_free(zFullTabName);
9110 import_cleanup(&sCtx);
9111 rc = 1;
9112 goto meta_command_exit;
9114 zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9115 if( eVerbose>=1 ){
9116 utf8_printf(p->out, "%s\n", zCreate);
9118 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9119 if( rc ){
9120 utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9121 goto import_fail;
9123 sqlite3_free(zCreate);
9124 zCreate = 0;
9125 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9127 if( rc ){
9128 if (pStmt) sqlite3_finalize(pStmt);
9129 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9130 goto import_fail;
9132 sqlite3_free(zSql);
9133 nCol = sqlite3_column_count(pStmt);
9134 sqlite3_finalize(pStmt);
9135 pStmt = 0;
9136 if( nCol==0 ) return 0; /* no columns, no error */
9137 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9138 if( zSql==0 ){
9139 import_cleanup(&sCtx);
9140 shell_out_of_memory();
9142 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9143 j = strlen30(zSql);
9144 for(i=1; i<nCol; i++){
9145 zSql[j++] = ',';
9146 zSql[j++] = '?';
9148 zSql[j++] = ')';
9149 zSql[j] = 0;
9150 if( eVerbose>=2 ){
9151 utf8_printf(p->out, "Insert using: %s\n", zSql);
9153 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9154 if( rc ){
9155 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9156 if (pStmt) sqlite3_finalize(pStmt);
9157 goto import_fail;
9159 sqlite3_free(zSql);
9160 sqlite3_free(zFullTabName);
9161 needCommit = sqlite3_get_autocommit(p->db);
9162 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9164 int startLine = sCtx.nLine;
9165 for(i=0; i<nCol; i++){
9166 char *z = xRead(&sCtx);
9168 ** Did we reach end-of-file before finding any columns?
9169 ** If so, stop instead of NULL filling the remaining columns.
9171 if( z==0 && i==0 ) break;
9173 ** Did we reach end-of-file OR end-of-line before finding any
9174 ** columns in ASCII mode? If so, stop instead of NULL filling
9175 ** the remaining columns.
9177 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9178 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9179 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9180 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9181 "filling the rest with NULL\n",
9182 sCtx.zFile, startLine, nCol, i+1);
9183 i += 2;
9184 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9187 if( sCtx.cTerm==sCtx.cColSep ){
9189 xRead(&sCtx);
9190 i++;
9191 }while( sCtx.cTerm==sCtx.cColSep );
9192 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9193 "extras ignored\n",
9194 sCtx.zFile, startLine, nCol, i);
9196 if( i>=nCol ){
9197 sqlite3_step(pStmt);
9198 rc = sqlite3_reset(pStmt);
9199 if( rc!=SQLITE_OK ){
9200 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9201 startLine, sqlite3_errmsg(p->db));
9202 sCtx.nErr++;
9203 }else{
9204 sCtx.nRow++;
9207 }while( sCtx.cTerm!=EOF );
9209 import_cleanup(&sCtx);
9210 sqlite3_finalize(pStmt);
9211 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9212 if( eVerbose>0 ){
9213 utf8_printf(p->out,
9214 "Added %d rows with %d errors using %d lines of input\n",
9215 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9217 }else
9218 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9220 #ifndef SQLITE_UNTESTABLE
9221 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9222 char *zSql;
9223 char *zCollist = 0;
9224 sqlite3_stmt *pStmt;
9225 int tnum = 0;
9226 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
9227 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9228 int i;
9229 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9230 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9231 " .imposter off\n");
9232 /* Also allowed, but not documented:
9234 ** .imposter TABLE IMPOSTER
9236 ** where TABLE is a WITHOUT ROWID table. In that case, the
9237 ** imposter is another WITHOUT ROWID table with the columns in
9238 ** storage order. */
9239 rc = 1;
9240 goto meta_command_exit;
9242 open_db(p, 0);
9243 if( nArg==2 ){
9244 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9245 goto meta_command_exit;
9247 zSql = sqlite3_mprintf(
9248 "SELECT rootpage, 0 FROM sqlite_schema"
9249 " WHERE name='%q' AND type='index'"
9250 "UNION ALL "
9251 "SELECT rootpage, 1 FROM sqlite_schema"
9252 " WHERE name='%q' AND type='table'"
9253 " AND sql LIKE '%%without%%rowid%%'",
9254 azArg[1], azArg[1]
9256 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9257 sqlite3_free(zSql);
9258 if( sqlite3_step(pStmt)==SQLITE_ROW ){
9259 tnum = sqlite3_column_int(pStmt, 0);
9260 isWO = sqlite3_column_int(pStmt, 1);
9262 sqlite3_finalize(pStmt);
9263 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9264 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9265 sqlite3_free(zSql);
9266 i = 0;
9267 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9268 char zLabel[20];
9269 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9270 i++;
9271 if( zCol==0 ){
9272 if( sqlite3_column_int(pStmt,1)==-1 ){
9273 zCol = "_ROWID_";
9274 }else{
9275 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9276 zCol = zLabel;
9279 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9280 lenPK = (int)strlen(zCollist);
9282 if( zCollist==0 ){
9283 zCollist = sqlite3_mprintf("\"%w\"", zCol);
9284 }else{
9285 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9288 sqlite3_finalize(pStmt);
9289 if( i==0 || tnum==0 ){
9290 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9291 rc = 1;
9292 sqlite3_free(zCollist);
9293 goto meta_command_exit;
9295 if( lenPK==0 ) lenPK = 100000;
9296 zSql = sqlite3_mprintf(
9297 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9298 azArg[2], zCollist, lenPK, zCollist);
9299 sqlite3_free(zCollist);
9300 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9301 if( rc==SQLITE_OK ){
9302 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9303 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9304 if( rc ){
9305 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9306 }else{
9307 utf8_printf(stdout, "%s;\n", zSql);
9308 raw_printf(stdout,
9309 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9310 azArg[1], isWO ? "table" : "index"
9313 }else{
9314 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9315 rc = 1;
9317 sqlite3_free(zSql);
9318 }else
9319 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9321 #ifdef SQLITE_ENABLE_IOTRACE
9322 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9323 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9324 if( iotrace && iotrace!=stdout ) fclose(iotrace);
9325 iotrace = 0;
9326 if( nArg<2 ){
9327 sqlite3IoTrace = 0;
9328 }else if( strcmp(azArg[1], "-")==0 ){
9329 sqlite3IoTrace = iotracePrintf;
9330 iotrace = stdout;
9331 }else{
9332 iotrace = fopen(azArg[1], "w");
9333 if( iotrace==0 ){
9334 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9335 sqlite3IoTrace = 0;
9336 rc = 1;
9337 }else{
9338 sqlite3IoTrace = iotracePrintf;
9341 }else
9342 #endif
9344 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9345 static const struct {
9346 const char *zLimitName; /* Name of a limit */
9347 int limitCode; /* Integer code for that limit */
9348 } aLimit[] = {
9349 { "length", SQLITE_LIMIT_LENGTH },
9350 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
9351 { "column", SQLITE_LIMIT_COLUMN },
9352 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
9353 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
9354 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
9355 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
9356 { "attached", SQLITE_LIMIT_ATTACHED },
9357 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
9358 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
9359 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
9360 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
9362 int i, n2;
9363 open_db(p, 0);
9364 if( nArg==1 ){
9365 for(i=0; i<ArraySize(aLimit); i++){
9366 printf("%20s %d\n", aLimit[i].zLimitName,
9367 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9369 }else if( nArg>3 ){
9370 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9371 rc = 1;
9372 goto meta_command_exit;
9373 }else{
9374 int iLimit = -1;
9375 n2 = strlen30(azArg[1]);
9376 for(i=0; i<ArraySize(aLimit); i++){
9377 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9378 if( iLimit<0 ){
9379 iLimit = i;
9380 }else{
9381 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9382 rc = 1;
9383 goto meta_command_exit;
9387 if( iLimit<0 ){
9388 utf8_printf(stderr, "unknown limit: \"%s\"\n"
9389 "enter \".limits\" with no arguments for a list.\n",
9390 azArg[1]);
9391 rc = 1;
9392 goto meta_command_exit;
9394 if( nArg==3 ){
9395 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9396 (int)integerValue(azArg[2]));
9398 printf("%20s %d\n", aLimit[iLimit].zLimitName,
9399 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9401 }else
9403 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9404 open_db(p, 0);
9405 lintDotCommand(p, azArg, nArg);
9406 }else
9408 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
9409 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9410 const char *zFile, *zProc;
9411 char *zErrMsg = 0;
9412 failIfSafeMode(p, "cannot run .load in safe mode");
9413 if( nArg<2 ){
9414 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9415 rc = 1;
9416 goto meta_command_exit;
9418 zFile = azArg[1];
9419 zProc = nArg>=3 ? azArg[2] : 0;
9420 open_db(p, 0);
9421 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9422 if( rc!=SQLITE_OK ){
9423 utf8_printf(stderr, "Error: %s\n", zErrMsg);
9424 sqlite3_free(zErrMsg);
9425 rc = 1;
9427 }else
9428 #endif
9430 #ifndef SQLITE_SHELL_WASM_MODE
9431 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9432 failIfSafeMode(p, "cannot run .log in safe mode");
9433 if( nArg!=2 ){
9434 raw_printf(stderr, "Usage: .log FILENAME\n");
9435 rc = 1;
9436 }else{
9437 const char *zFile = azArg[1];
9438 output_file_close(p->pLog);
9439 p->pLog = output_file_open(zFile, 0);
9441 }else
9442 #endif
9444 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9445 const char *zMode = 0;
9446 const char *zTabname = 0;
9447 int i, n2;
9448 ColModeOpts cmOpts = ColModeOpts_default;
9449 for(i=1; i<nArg; i++){
9450 const char *z = azArg[i];
9451 if( optionMatch(z,"wrap") && i+1<nArg ){
9452 cmOpts.iWrap = integerValue(azArg[++i]);
9453 }else if( optionMatch(z,"ww") ){
9454 cmOpts.bWordWrap = 1;
9455 }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9456 cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9457 }else if( optionMatch(z,"quote") ){
9458 cmOpts.bQuote = 1;
9459 }else if( optionMatch(z,"noquote") ){
9460 cmOpts.bQuote = 0;
9461 }else if( zMode==0 ){
9462 zMode = z;
9463 /* Apply defaults for qbox pseudo-mods. If that
9464 * overwrites already-set values, user was informed of this.
9466 if( strcmp(z, "qbox")==0 ){
9467 ColModeOpts cmo = ColModeOpts_default_qbox;
9468 zMode = "box";
9469 cmOpts = cmo;
9471 }else if( zTabname==0 ){
9472 zTabname = z;
9473 }else if( z[0]=='-' ){
9474 utf8_printf(stderr, "unknown option: %s\n", z);
9475 utf8_printf(stderr, "options:\n"
9476 " --noquote\n"
9477 " --quote\n"
9478 " --wordwrap on/off\n"
9479 " --wrap N\n"
9480 " --ww\n");
9481 rc = 1;
9482 goto meta_command_exit;
9483 }else{
9484 utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9485 rc = 1;
9486 goto meta_command_exit;
9489 if( zMode==0 ){
9490 if( p->mode==MODE_Column
9491 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9493 raw_printf
9494 (p->out,
9495 "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9496 modeDescr[p->mode], p->cmOpts.iWrap,
9497 p->cmOpts.bWordWrap ? "on" : "off",
9498 p->cmOpts.bQuote ? "" : "no");
9499 }else{
9500 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9502 zMode = modeDescr[p->mode];
9504 n2 = strlen30(zMode);
9505 if( strncmp(zMode,"lines",n2)==0 ){
9506 p->mode = MODE_Line;
9507 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9508 }else if( strncmp(zMode,"columns",n2)==0 ){
9509 p->mode = MODE_Column;
9510 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9511 p->showHeader = 1;
9513 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9514 p->cmOpts = cmOpts;
9515 }else if( strncmp(zMode,"list",n2)==0 ){
9516 p->mode = MODE_List;
9517 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9518 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9519 }else if( strncmp(zMode,"html",n2)==0 ){
9520 p->mode = MODE_Html;
9521 }else if( strncmp(zMode,"tcl",n2)==0 ){
9522 p->mode = MODE_Tcl;
9523 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9524 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9525 }else if( strncmp(zMode,"csv",n2)==0 ){
9526 p->mode = MODE_Csv;
9527 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9528 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9529 }else if( strncmp(zMode,"tabs",n2)==0 ){
9530 p->mode = MODE_List;
9531 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9532 }else if( strncmp(zMode,"insert",n2)==0 ){
9533 p->mode = MODE_Insert;
9534 set_table_name(p, zTabname ? zTabname : "table");
9535 }else if( strncmp(zMode,"quote",n2)==0 ){
9536 p->mode = MODE_Quote;
9537 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9538 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9539 }else if( strncmp(zMode,"ascii",n2)==0 ){
9540 p->mode = MODE_Ascii;
9541 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9542 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9543 }else if( strncmp(zMode,"markdown",n2)==0 ){
9544 p->mode = MODE_Markdown;
9545 p->cmOpts = cmOpts;
9546 }else if( strncmp(zMode,"table",n2)==0 ){
9547 p->mode = MODE_Table;
9548 p->cmOpts = cmOpts;
9549 }else if( strncmp(zMode,"box",n2)==0 ){
9550 p->mode = MODE_Box;
9551 p->cmOpts = cmOpts;
9552 }else if( strncmp(zMode,"count",n2)==0 ){
9553 p->mode = MODE_Count;
9554 }else if( strncmp(zMode,"off",n2)==0 ){
9555 p->mode = MODE_Off;
9556 }else if( strncmp(zMode,"json",n2)==0 ){
9557 p->mode = MODE_Json;
9558 }else{
9559 raw_printf(stderr, "Error: mode should be one of: "
9560 "ascii box column csv html insert json line list markdown "
9561 "qbox quote table tabs tcl\n");
9562 rc = 1;
9564 p->cMode = p->mode;
9565 }else
9567 #ifndef SQLITE_SHELL_WASM_MODE
9568 if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9569 if( nArg!=2 ){
9570 raw_printf(stderr, "Usage: .nonce NONCE\n");
9571 rc = 1;
9572 }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9573 raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9574 p->lineno, azArg[1]);
9575 exit(1);
9576 }else{
9577 p->bSafeMode = 0;
9578 return 0; /* Return immediately to bypass the safe mode reset
9579 ** at the end of this procedure */
9581 }else
9582 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9584 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9585 if( nArg==2 ){
9586 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9587 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9588 }else{
9589 raw_printf(stderr, "Usage: .nullvalue STRING\n");
9590 rc = 1;
9592 }else
9594 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9595 const char *zFN = 0; /* Pointer to constant filename */
9596 char *zNewFilename = 0; /* Name of the database file to open */
9597 int iName = 1; /* Index in azArg[] of the filename */
9598 int newFlag = 0; /* True to delete file before opening */
9599 int openMode = SHELL_OPEN_UNSPEC;
9601 /* Check for command-line arguments */
9602 for(iName=1; iName<nArg; iName++){
9603 const char *z = azArg[iName];
9604 #ifndef SQLITE_SHELL_WASM_MODE
9605 if( optionMatch(z,"new") ){
9606 newFlag = 1;
9607 #ifdef SQLITE_HAVE_ZLIB
9608 }else if( optionMatch(z, "zip") ){
9609 openMode = SHELL_OPEN_ZIPFILE;
9610 #endif
9611 }else if( optionMatch(z, "append") ){
9612 openMode = SHELL_OPEN_APPENDVFS;
9613 }else if( optionMatch(z, "readonly") ){
9614 openMode = SHELL_OPEN_READONLY;
9615 }else if( optionMatch(z, "nofollow") ){
9616 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9617 #ifndef SQLITE_OMIT_DESERIALIZE
9618 }else if( optionMatch(z, "deserialize") ){
9619 openMode = SHELL_OPEN_DESERIALIZE;
9620 }else if( optionMatch(z, "hexdb") ){
9621 openMode = SHELL_OPEN_HEXDB;
9622 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9623 p->szMax = integerValue(azArg[++iName]);
9624 #endif /* SQLITE_OMIT_DESERIALIZE */
9625 }else
9626 #endif /* !SQLITE_SHELL_WASM_MODE */
9627 if( z[0]=='-' ){
9628 utf8_printf(stderr, "unknown option: %s\n", z);
9629 rc = 1;
9630 goto meta_command_exit;
9631 }else if( zFN ){
9632 utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9633 rc = 1;
9634 goto meta_command_exit;
9635 }else{
9636 zFN = z;
9640 /* Close the existing database */
9641 session_close_all(p, -1);
9642 close_db(p->db);
9643 p->db = 0;
9644 p->pAuxDb->zDbFilename = 0;
9645 sqlite3_free(p->pAuxDb->zFreeOnClose);
9646 p->pAuxDb->zFreeOnClose = 0;
9647 p->openMode = openMode;
9648 p->openFlags = 0;
9649 p->szMax = 0;
9651 /* If a filename is specified, try to open it first */
9652 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9653 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9654 #ifndef SQLITE_SHELL_WASM_MODE
9655 if( p->bSafeMode
9656 && p->openMode!=SHELL_OPEN_HEXDB
9657 && zFN
9658 && strcmp(zFN,":memory:")!=0
9660 failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9662 #else
9663 /* WASM mode has its own sandboxed pseudo-filesystem. */
9664 #endif
9665 if( zFN ){
9666 zNewFilename = sqlite3_mprintf("%s", zFN);
9667 shell_check_oom(zNewFilename);
9668 }else{
9669 zNewFilename = 0;
9671 p->pAuxDb->zDbFilename = zNewFilename;
9672 open_db(p, OPEN_DB_KEEPALIVE);
9673 if( p->db==0 ){
9674 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9675 sqlite3_free(zNewFilename);
9676 }else{
9677 p->pAuxDb->zFreeOnClose = zNewFilename;
9680 if( p->db==0 ){
9681 /* As a fall-back open a TEMP database */
9682 p->pAuxDb->zDbFilename = 0;
9683 open_db(p, 0);
9685 }else
9687 #ifndef SQLITE_SHELL_WASM_MODE
9688 if( (c=='o'
9689 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9690 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9692 char *zFile = 0;
9693 int bTxtMode = 0;
9694 int i;
9695 int eMode = 0;
9696 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
9697 unsigned char zBOM[4]; /* Byte-order mark to using if --bom is present */
9699 zBOM[0] = 0;
9700 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9701 if( c=='e' ){
9702 eMode = 'x';
9703 bOnce = 2;
9704 }else if( strncmp(azArg[0],"once",n)==0 ){
9705 bOnce = 1;
9707 for(i=1; i<nArg; i++){
9708 char *z = azArg[i];
9709 if( z[0]=='-' ){
9710 if( z[1]=='-' ) z++;
9711 if( strcmp(z,"-bom")==0 ){
9712 zBOM[0] = 0xef;
9713 zBOM[1] = 0xbb;
9714 zBOM[2] = 0xbf;
9715 zBOM[3] = 0;
9716 }else if( c!='e' && strcmp(z,"-x")==0 ){
9717 eMode = 'x'; /* spreadsheet */
9718 }else if( c!='e' && strcmp(z,"-e")==0 ){
9719 eMode = 'e'; /* text editor */
9720 }else{
9721 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
9722 azArg[i]);
9723 showHelp(p->out, azArg[0]);
9724 rc = 1;
9725 goto meta_command_exit;
9727 }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9728 zFile = sqlite3_mprintf("%s", z);
9729 if( zFile && zFile[0]=='|' ){
9730 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9731 break;
9733 }else{
9734 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
9735 azArg[i]);
9736 showHelp(p->out, azArg[0]);
9737 rc = 1;
9738 sqlite3_free(zFile);
9739 goto meta_command_exit;
9742 if( zFile==0 ){
9743 zFile = sqlite3_mprintf("stdout");
9745 if( bOnce ){
9746 p->outCount = 2;
9747 }else{
9748 p->outCount = 0;
9750 output_reset(p);
9751 #ifndef SQLITE_NOHAVE_SYSTEM
9752 if( eMode=='e' || eMode=='x' ){
9753 p->doXdgOpen = 1;
9754 outputModePush(p);
9755 if( eMode=='x' ){
9756 /* spreadsheet mode. Output as CSV. */
9757 newTempFile(p, "csv");
9758 ShellClearFlag(p, SHFLG_Echo);
9759 p->mode = MODE_Csv;
9760 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9761 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9762 }else{
9763 /* text editor mode */
9764 newTempFile(p, "txt");
9765 bTxtMode = 1;
9767 sqlite3_free(zFile);
9768 zFile = sqlite3_mprintf("%s", p->zTempFile);
9770 #endif /* SQLITE_NOHAVE_SYSTEM */
9771 shell_check_oom(zFile);
9772 if( zFile[0]=='|' ){
9773 #ifdef SQLITE_OMIT_POPEN
9774 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9775 rc = 1;
9776 p->out = stdout;
9777 #else
9778 p->out = popen(zFile + 1, "w");
9779 if( p->out==0 ){
9780 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9781 p->out = stdout;
9782 rc = 1;
9783 }else{
9784 if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9785 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9787 #endif
9788 }else{
9789 p->out = output_file_open(zFile, bTxtMode);
9790 if( p->out==0 ){
9791 if( strcmp(zFile,"off")!=0 ){
9792 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9794 p->out = stdout;
9795 rc = 1;
9796 } else {
9797 if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9798 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9801 sqlite3_free(zFile);
9802 }else
9803 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9805 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9806 open_db(p,0);
9807 if( nArg<=1 ) goto parameter_syntax_error;
9809 /* .parameter clear
9810 ** Clear all bind parameters by dropping the TEMP table that holds them.
9812 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9813 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9814 0, 0, 0);
9815 }else
9817 /* .parameter list
9818 ** List all bind parameters.
9820 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9821 sqlite3_stmt *pStmt = 0;
9822 int rx;
9823 int len = 0;
9824 rx = sqlite3_prepare_v2(p->db,
9825 "SELECT max(length(key)) "
9826 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9827 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9828 len = sqlite3_column_int(pStmt, 0);
9829 if( len>40 ) len = 40;
9831 sqlite3_finalize(pStmt);
9832 pStmt = 0;
9833 if( len ){
9834 rx = sqlite3_prepare_v2(p->db,
9835 "SELECT key, quote(value) "
9836 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9837 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9838 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9839 sqlite3_column_text(pStmt,1));
9841 sqlite3_finalize(pStmt);
9843 }else
9845 /* .parameter init
9846 ** Make sure the TEMP table used to hold bind parameters exists.
9847 ** Create it if necessary.
9849 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9850 bind_table_init(p);
9851 }else
9853 /* .parameter set NAME VALUE
9854 ** Set or reset a bind parameter. NAME should be the full parameter
9855 ** name exactly as it appears in the query. (ex: $abc, @def). The
9856 ** VALUE can be in either SQL literal notation, or if not it will be
9857 ** understood to be a text string.
9859 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9860 int rx;
9861 char *zSql;
9862 sqlite3_stmt *pStmt;
9863 const char *zKey = azArg[2];
9864 const char *zValue = azArg[3];
9865 bind_table_init(p);
9866 zSql = sqlite3_mprintf(
9867 "REPLACE INTO temp.sqlite_parameters(key,value)"
9868 "VALUES(%Q,%s);", zKey, zValue);
9869 shell_check_oom(zSql);
9870 pStmt = 0;
9871 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9872 sqlite3_free(zSql);
9873 if( rx!=SQLITE_OK ){
9874 sqlite3_finalize(pStmt);
9875 pStmt = 0;
9876 zSql = sqlite3_mprintf(
9877 "REPLACE INTO temp.sqlite_parameters(key,value)"
9878 "VALUES(%Q,%Q);", zKey, zValue);
9879 shell_check_oom(zSql);
9880 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9881 sqlite3_free(zSql);
9882 if( rx!=SQLITE_OK ){
9883 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9884 sqlite3_finalize(pStmt);
9885 pStmt = 0;
9886 rc = 1;
9889 sqlite3_step(pStmt);
9890 sqlite3_finalize(pStmt);
9891 }else
9893 /* .parameter unset NAME
9894 ** Remove the NAME binding from the parameter binding table, if it
9895 ** exists.
9897 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9898 char *zSql = sqlite3_mprintf(
9899 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9900 shell_check_oom(zSql);
9901 sqlite3_exec(p->db, zSql, 0, 0, 0);
9902 sqlite3_free(zSql);
9903 }else
9904 /* If no command name matches, show a syntax error */
9905 parameter_syntax_error:
9906 showHelp(p->out, "parameter");
9907 }else
9909 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9910 int i;
9911 for(i=1; i<nArg; i++){
9912 if( i>1 ) raw_printf(p->out, " ");
9913 utf8_printf(p->out, "%s", azArg[i]);
9915 raw_printf(p->out, "\n");
9916 }else
9918 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9919 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9920 int i;
9921 int nn = 0;
9922 p->flgProgress = 0;
9923 p->mxProgress = 0;
9924 p->nProgress = 0;
9925 for(i=1; i<nArg; i++){
9926 const char *z = azArg[i];
9927 if( z[0]=='-' ){
9928 z++;
9929 if( z[0]=='-' ) z++;
9930 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9931 p->flgProgress |= SHELL_PROGRESS_QUIET;
9932 continue;
9934 if( strcmp(z,"reset")==0 ){
9935 p->flgProgress |= SHELL_PROGRESS_RESET;
9936 continue;
9938 if( strcmp(z,"once")==0 ){
9939 p->flgProgress |= SHELL_PROGRESS_ONCE;
9940 continue;
9942 if( strcmp(z,"limit")==0 ){
9943 if( i+1>=nArg ){
9944 utf8_printf(stderr, "Error: missing argument on --limit\n");
9945 rc = 1;
9946 goto meta_command_exit;
9947 }else{
9948 p->mxProgress = (int)integerValue(azArg[++i]);
9950 continue;
9952 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9953 rc = 1;
9954 goto meta_command_exit;
9955 }else{
9956 nn = (int)integerValue(z);
9959 open_db(p, 0);
9960 sqlite3_progress_handler(p->db, nn, progress_handler, p);
9961 }else
9962 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9964 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9965 if( nArg >= 2) {
9966 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9968 if( nArg >= 3) {
9969 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9971 }else
9973 #ifndef SQLITE_SHELL_WASM_MODE
9974 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9975 rc = 2;
9976 }else
9977 #endif
9979 #ifndef SQLITE_SHELL_WASM_MODE
9980 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9981 FILE *inSaved = p->in;
9982 int savedLineno = p->lineno;
9983 failIfSafeMode(p, "cannot run .read in safe mode");
9984 if( nArg!=2 ){
9985 raw_printf(stderr, "Usage: .read FILE\n");
9986 rc = 1;
9987 goto meta_command_exit;
9989 if( azArg[1][0]=='|' ){
9990 #ifdef SQLITE_OMIT_POPEN
9991 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9992 rc = 1;
9993 p->out = stdout;
9994 #else
9995 p->in = popen(azArg[1]+1, "r");
9996 if( p->in==0 ){
9997 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9998 rc = 1;
9999 }else{
10000 rc = process_input(p);
10001 pclose(p->in);
10003 #endif
10004 }else if( (p->in = openChrSource(azArg[1]))==0 ){
10005 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
10006 rc = 1;
10007 }else{
10008 rc = process_input(p);
10009 fclose(p->in);
10011 p->in = inSaved;
10012 p->lineno = savedLineno;
10013 }else
10014 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10016 #ifndef SQLITE_SHELL_WASM_MODE
10017 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10018 const char *zSrcFile;
10019 const char *zDb;
10020 sqlite3 *pSrc;
10021 sqlite3_backup *pBackup;
10022 int nTimeout = 0;
10024 failIfSafeMode(p, "cannot run .restore in safe mode");
10025 if( nArg==2 ){
10026 zSrcFile = azArg[1];
10027 zDb = "main";
10028 }else if( nArg==3 ){
10029 zSrcFile = azArg[2];
10030 zDb = azArg[1];
10031 }else{
10032 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10033 rc = 1;
10034 goto meta_command_exit;
10036 rc = sqlite3_open(zSrcFile, &pSrc);
10037 if( rc!=SQLITE_OK ){
10038 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10039 close_db(pSrc);
10040 return 1;
10042 open_db(p, 0);
10043 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10044 if( pBackup==0 ){
10045 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10046 close_db(pSrc);
10047 return 1;
10049 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10050 || rc==SQLITE_BUSY ){
10051 if( rc==SQLITE_BUSY ){
10052 if( nTimeout++ >= 3 ) break;
10053 sqlite3_sleep(100);
10056 sqlite3_backup_finish(pBackup);
10057 if( rc==SQLITE_DONE ){
10058 rc = 0;
10059 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10060 raw_printf(stderr, "Error: source database is busy\n");
10061 rc = 1;
10062 }else{
10063 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10064 rc = 1;
10066 close_db(pSrc);
10067 }else
10068 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10070 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10071 if( nArg==2 ){
10072 p->scanstatsOn = (u8)booleanValue(azArg[1]);
10073 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10074 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10075 #endif
10076 }else{
10077 raw_printf(stderr, "Usage: .scanstats on|off\n");
10078 rc = 1;
10080 }else
10082 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10083 ShellText sSelect;
10084 ShellState data;
10085 char *zErrMsg = 0;
10086 const char *zDiv = "(";
10087 const char *zName = 0;
10088 int iSchema = 0;
10089 int bDebug = 0;
10090 int bNoSystemTabs = 0;
10091 int ii;
10093 open_db(p, 0);
10094 memcpy(&data, p, sizeof(data));
10095 data.showHeader = 0;
10096 data.cMode = data.mode = MODE_Semi;
10097 initText(&sSelect);
10098 for(ii=1; ii<nArg; ii++){
10099 if( optionMatch(azArg[ii],"indent") ){
10100 data.cMode = data.mode = MODE_Pretty;
10101 }else if( optionMatch(azArg[ii],"debug") ){
10102 bDebug = 1;
10103 }else if( optionMatch(azArg[ii],"nosys") ){
10104 bNoSystemTabs = 1;
10105 }else if( azArg[ii][0]=='-' ){
10106 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10107 rc = 1;
10108 goto meta_command_exit;
10109 }else if( zName==0 ){
10110 zName = azArg[ii];
10111 }else{
10112 raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10113 rc = 1;
10114 goto meta_command_exit;
10117 if( zName!=0 ){
10118 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10119 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10120 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10121 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10122 if( isSchema ){
10123 char *new_argv[2], *new_colv[2];
10124 new_argv[0] = sqlite3_mprintf(
10125 "CREATE TABLE %s (\n"
10126 " type text,\n"
10127 " name text,\n"
10128 " tbl_name text,\n"
10129 " rootpage integer,\n"
10130 " sql text\n"
10131 ")", zName);
10132 shell_check_oom(new_argv[0]);
10133 new_argv[1] = 0;
10134 new_colv[0] = "sql";
10135 new_colv[1] = 0;
10136 callback(&data, 1, new_argv, new_colv);
10137 sqlite3_free(new_argv[0]);
10140 if( zDiv ){
10141 sqlite3_stmt *pStmt = 0;
10142 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10143 -1, &pStmt, 0);
10144 if( rc ){
10145 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10146 sqlite3_finalize(pStmt);
10147 rc = 1;
10148 goto meta_command_exit;
10150 appendText(&sSelect, "SELECT sql FROM", 0);
10151 iSchema = 0;
10152 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10153 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10154 char zScNum[30];
10155 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10156 appendText(&sSelect, zDiv, 0);
10157 zDiv = " UNION ALL ";
10158 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10159 if( sqlite3_stricmp(zDb, "main")!=0 ){
10160 appendText(&sSelect, zDb, '\'');
10161 }else{
10162 appendText(&sSelect, "NULL", 0);
10164 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10165 appendText(&sSelect, zScNum, 0);
10166 appendText(&sSelect, " AS snum, ", 0);
10167 appendText(&sSelect, zDb, '\'');
10168 appendText(&sSelect, " AS sname FROM ", 0);
10169 appendText(&sSelect, zDb, quoteChar(zDb));
10170 appendText(&sSelect, ".sqlite_schema", 0);
10172 sqlite3_finalize(pStmt);
10173 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10174 if( zName ){
10175 appendText(&sSelect,
10176 " UNION ALL SELECT shell_module_schema(name),"
10177 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10180 #endif
10181 appendText(&sSelect, ") WHERE ", 0);
10182 if( zName ){
10183 char *zQarg = sqlite3_mprintf("%Q", zName);
10184 int bGlob;
10185 shell_check_oom(zQarg);
10186 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10187 strchr(zName, '[') != 0;
10188 if( strchr(zName, '.') ){
10189 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10190 }else{
10191 appendText(&sSelect, "lower(tbl_name)", 0);
10193 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10194 appendText(&sSelect, zQarg, 0);
10195 if( !bGlob ){
10196 appendText(&sSelect, " ESCAPE '\\' ", 0);
10198 appendText(&sSelect, " AND ", 0);
10199 sqlite3_free(zQarg);
10201 if( bNoSystemTabs ){
10202 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10204 appendText(&sSelect, "sql IS NOT NULL"
10205 " ORDER BY snum, rowid", 0);
10206 if( bDebug ){
10207 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10208 }else{
10209 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10211 freeText(&sSelect);
10213 if( zErrMsg ){
10214 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10215 sqlite3_free(zErrMsg);
10216 rc = 1;
10217 }else if( rc != SQLITE_OK ){
10218 raw_printf(stderr,"Error: querying schema information\n");
10219 rc = 1;
10220 }else{
10221 rc = 0;
10223 }else
10225 if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10226 || (c=='t' && n==9 && strncmp(azArg[0], "treetrace", n)==0)
10228 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10229 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10230 }else
10232 #if defined(SQLITE_ENABLE_SESSION)
10233 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10234 struct AuxDb *pAuxDb = p->pAuxDb;
10235 OpenSession *pSession = &pAuxDb->aSession[0];
10236 char **azCmd = &azArg[1];
10237 int iSes = 0;
10238 int nCmd = nArg - 1;
10239 int i;
10240 if( nArg<=1 ) goto session_syntax_error;
10241 open_db(p, 0);
10242 if( nArg>=3 ){
10243 for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10244 if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10246 if( iSes<pAuxDb->nSession ){
10247 pSession = &pAuxDb->aSession[iSes];
10248 azCmd++;
10249 nCmd--;
10250 }else{
10251 pSession = &pAuxDb->aSession[0];
10252 iSes = 0;
10256 /* .session attach TABLE
10257 ** Invoke the sqlite3session_attach() interface to attach a particular
10258 ** table so that it is never filtered.
10260 if( strcmp(azCmd[0],"attach")==0 ){
10261 if( nCmd!=2 ) goto session_syntax_error;
10262 if( pSession->p==0 ){
10263 session_not_open:
10264 raw_printf(stderr, "ERROR: No sessions are open\n");
10265 }else{
10266 rc = sqlite3session_attach(pSession->p, azCmd[1]);
10267 if( rc ){
10268 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10269 rc = 0;
10272 }else
10274 /* .session changeset FILE
10275 ** .session patchset FILE
10276 ** Write a changeset or patchset into a file. The file is overwritten.
10278 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10279 FILE *out = 0;
10280 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10281 if( nCmd!=2 ) goto session_syntax_error;
10282 if( pSession->p==0 ) goto session_not_open;
10283 out = fopen(azCmd[1], "wb");
10284 if( out==0 ){
10285 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10286 azCmd[1]);
10287 }else{
10288 int szChng;
10289 void *pChng;
10290 if( azCmd[0][0]=='c' ){
10291 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10292 }else{
10293 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10295 if( rc ){
10296 printf("Error: error code %d\n", rc);
10297 rc = 0;
10299 if( pChng
10300 && fwrite(pChng, szChng, 1, out)!=1 ){
10301 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10302 szChng);
10304 sqlite3_free(pChng);
10305 fclose(out);
10307 }else
10309 /* .session close
10310 ** Close the identified session
10312 if( strcmp(azCmd[0], "close")==0 ){
10313 if( nCmd!=1 ) goto session_syntax_error;
10314 if( pAuxDb->nSession ){
10315 session_close(pSession);
10316 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10318 }else
10320 /* .session enable ?BOOLEAN?
10321 ** Query or set the enable flag
10323 if( strcmp(azCmd[0], "enable")==0 ){
10324 int ii;
10325 if( nCmd>2 ) goto session_syntax_error;
10326 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10327 if( pAuxDb->nSession ){
10328 ii = sqlite3session_enable(pSession->p, ii);
10329 utf8_printf(p->out, "session %s enable flag = %d\n",
10330 pSession->zName, ii);
10332 }else
10334 /* .session filter GLOB ....
10335 ** Set a list of GLOB patterns of table names to be excluded.
10337 if( strcmp(azCmd[0], "filter")==0 ){
10338 int ii, nByte;
10339 if( nCmd<2 ) goto session_syntax_error;
10340 if( pAuxDb->nSession ){
10341 for(ii=0; ii<pSession->nFilter; ii++){
10342 sqlite3_free(pSession->azFilter[ii]);
10344 sqlite3_free(pSession->azFilter);
10345 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10346 pSession->azFilter = sqlite3_malloc( nByte );
10347 if( pSession->azFilter==0 ){
10348 raw_printf(stderr, "Error: out or memory\n");
10349 exit(1);
10351 for(ii=1; ii<nCmd; ii++){
10352 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10353 shell_check_oom(x);
10355 pSession->nFilter = ii-1;
10357 }else
10359 /* .session indirect ?BOOLEAN?
10360 ** Query or set the indirect flag
10362 if( strcmp(azCmd[0], "indirect")==0 ){
10363 int ii;
10364 if( nCmd>2 ) goto session_syntax_error;
10365 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10366 if( pAuxDb->nSession ){
10367 ii = sqlite3session_indirect(pSession->p, ii);
10368 utf8_printf(p->out, "session %s indirect flag = %d\n",
10369 pSession->zName, ii);
10371 }else
10373 /* .session isempty
10374 ** Determine if the session is empty
10376 if( strcmp(azCmd[0], "isempty")==0 ){
10377 int ii;
10378 if( nCmd!=1 ) goto session_syntax_error;
10379 if( pAuxDb->nSession ){
10380 ii = sqlite3session_isempty(pSession->p);
10381 utf8_printf(p->out, "session %s isempty flag = %d\n",
10382 pSession->zName, ii);
10384 }else
10386 /* .session list
10387 ** List all currently open sessions
10389 if( strcmp(azCmd[0],"list")==0 ){
10390 for(i=0; i<pAuxDb->nSession; i++){
10391 utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10393 }else
10395 /* .session open DB NAME
10396 ** Open a new session called NAME on the attached database DB.
10397 ** DB is normally "main".
10399 if( strcmp(azCmd[0],"open")==0 ){
10400 char *zName;
10401 if( nCmd!=3 ) goto session_syntax_error;
10402 zName = azCmd[2];
10403 if( zName[0]==0 ) goto session_syntax_error;
10404 for(i=0; i<pAuxDb->nSession; i++){
10405 if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10406 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10407 goto meta_command_exit;
10410 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10411 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10412 goto meta_command_exit;
10414 pSession = &pAuxDb->aSession[pAuxDb->nSession];
10415 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10416 if( rc ){
10417 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10418 rc = 0;
10419 goto meta_command_exit;
10421 pSession->nFilter = 0;
10422 sqlite3session_table_filter(pSession->p, session_filter, pSession);
10423 pAuxDb->nSession++;
10424 pSession->zName = sqlite3_mprintf("%s", zName);
10425 shell_check_oom(pSession->zName);
10426 }else
10427 /* If no command name matches, show a syntax error */
10428 session_syntax_error:
10429 showHelp(p->out, "session");
10430 }else
10431 #endif
10433 #ifdef SQLITE_DEBUG
10434 /* Undocumented commands for internal testing. Subject to change
10435 ** without notice. */
10436 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10437 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10438 int i, v;
10439 for(i=1; i<nArg; i++){
10440 v = booleanValue(azArg[i]);
10441 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10444 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10445 int i; sqlite3_int64 v;
10446 for(i=1; i<nArg; i++){
10447 char zBuf[200];
10448 v = integerValue(azArg[i]);
10449 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10450 utf8_printf(p->out, "%s", zBuf);
10453 }else
10454 #endif
10456 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10457 int bIsInit = 0; /* True to initialize the SELFTEST table */
10458 int bVerbose = 0; /* Verbose output */
10459 int bSelftestExists; /* True if SELFTEST already exists */
10460 int i, k; /* Loop counters */
10461 int nTest = 0; /* Number of tests runs */
10462 int nErr = 0; /* Number of errors seen */
10463 ShellText str; /* Answer for a query */
10464 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10466 open_db(p,0);
10467 for(i=1; i<nArg; i++){
10468 const char *z = azArg[i];
10469 if( z[0]=='-' && z[1]=='-' ) z++;
10470 if( strcmp(z,"-init")==0 ){
10471 bIsInit = 1;
10472 }else
10473 if( strcmp(z,"-v")==0 ){
10474 bVerbose++;
10475 }else
10477 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10478 azArg[i], azArg[0]);
10479 raw_printf(stderr, "Should be one of: --init -v\n");
10480 rc = 1;
10481 goto meta_command_exit;
10484 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10485 != SQLITE_OK ){
10486 bSelftestExists = 0;
10487 }else{
10488 bSelftestExists = 1;
10490 if( bIsInit ){
10491 createSelftestTable(p);
10492 bSelftestExists = 1;
10494 initText(&str);
10495 appendText(&str, "x", 0);
10496 for(k=bSelftestExists; k>=0; k--){
10497 if( k==1 ){
10498 rc = sqlite3_prepare_v2(p->db,
10499 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10500 -1, &pStmt, 0);
10501 }else{
10502 rc = sqlite3_prepare_v2(p->db,
10503 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10504 " (1,'run','PRAGMA integrity_check','ok')",
10505 -1, &pStmt, 0);
10507 if( rc ){
10508 raw_printf(stderr, "Error querying the selftest table\n");
10509 rc = 1;
10510 sqlite3_finalize(pStmt);
10511 goto meta_command_exit;
10513 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10514 int tno = sqlite3_column_int(pStmt, 0);
10515 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10516 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10517 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10519 if( zOp==0 ) continue;
10520 if( zSql==0 ) continue;
10521 if( zAns==0 ) continue;
10522 k = 0;
10523 if( bVerbose>0 ){
10524 printf("%d: %s %s\n", tno, zOp, zSql);
10526 if( strcmp(zOp,"memo")==0 ){
10527 utf8_printf(p->out, "%s\n", zSql);
10528 }else
10529 if( strcmp(zOp,"run")==0 ){
10530 char *zErrMsg = 0;
10531 str.n = 0;
10532 str.z[0] = 0;
10533 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10534 nTest++;
10535 if( bVerbose ){
10536 utf8_printf(p->out, "Result: %s\n", str.z);
10538 if( rc || zErrMsg ){
10539 nErr++;
10540 rc = 1;
10541 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10542 sqlite3_free(zErrMsg);
10543 }else if( strcmp(zAns,str.z)!=0 ){
10544 nErr++;
10545 rc = 1;
10546 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10547 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
10549 }else
10551 utf8_printf(stderr,
10552 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10553 rc = 1;
10554 break;
10556 } /* End loop over rows of content from SELFTEST */
10557 sqlite3_finalize(pStmt);
10558 } /* End loop over k */
10559 freeText(&str);
10560 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10561 }else
10563 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10564 if( nArg<2 || nArg>3 ){
10565 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10566 rc = 1;
10568 if( nArg>=2 ){
10569 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10570 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10572 if( nArg>=3 ){
10573 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10574 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10576 }else
10578 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10579 const char *zLike = 0; /* Which table to checksum. 0 means everything */
10580 int i; /* Loop counter */
10581 int bSchema = 0; /* Also hash the schema */
10582 int bSeparate = 0; /* Hash each table separately */
10583 int iSize = 224; /* Hash algorithm to use */
10584 int bDebug = 0; /* Only show the query that would have run */
10585 sqlite3_stmt *pStmt; /* For querying tables names */
10586 char *zSql; /* SQL to be run */
10587 char *zSep; /* Separator */
10588 ShellText sSql; /* Complete SQL for the query to run the hash */
10589 ShellText sQuery; /* Set of queries used to read all content */
10590 open_db(p, 0);
10591 for(i=1; i<nArg; i++){
10592 const char *z = azArg[i];
10593 if( z[0]=='-' ){
10594 z++;
10595 if( z[0]=='-' ) z++;
10596 if( strcmp(z,"schema")==0 ){
10597 bSchema = 1;
10598 }else
10599 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10600 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10602 iSize = atoi(&z[5]);
10603 }else
10604 if( strcmp(z,"debug")==0 ){
10605 bDebug = 1;
10606 }else
10608 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10609 azArg[i], azArg[0]);
10610 showHelp(p->out, azArg[0]);
10611 rc = 1;
10612 goto meta_command_exit;
10614 }else if( zLike ){
10615 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10616 rc = 1;
10617 goto meta_command_exit;
10618 }else{
10619 zLike = z;
10620 bSeparate = 1;
10621 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10624 if( bSchema ){
10625 zSql = "SELECT lower(name) FROM sqlite_schema"
10626 " WHERE type='table' AND coalesce(rootpage,0)>1"
10627 " UNION ALL SELECT 'sqlite_schema'"
10628 " ORDER BY 1 collate nocase";
10629 }else{
10630 zSql = "SELECT lower(name) FROM sqlite_schema"
10631 " WHERE type='table' AND coalesce(rootpage,0)>1"
10632 " AND name NOT LIKE 'sqlite_%'"
10633 " ORDER BY 1 collate nocase";
10635 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10636 initText(&sQuery);
10637 initText(&sSql);
10638 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10639 zSep = "VALUES(";
10640 while( SQLITE_ROW==sqlite3_step(pStmt) ){
10641 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10642 if( zTab==0 ) continue;
10643 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10644 if( strncmp(zTab, "sqlite_",7)!=0 ){
10645 appendText(&sQuery,"SELECT * FROM ", 0);
10646 appendText(&sQuery,zTab,'"');
10647 appendText(&sQuery," NOT INDEXED;", 0);
10648 }else if( strcmp(zTab, "sqlite_schema")==0 ){
10649 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10650 " ORDER BY name;", 0);
10651 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10652 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10653 " ORDER BY name;", 0);
10654 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10655 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10656 " ORDER BY tbl,idx;", 0);
10657 }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10658 appendText(&sQuery, "SELECT * FROM ", 0);
10659 appendText(&sQuery, zTab, 0);
10660 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10662 appendText(&sSql, zSep, 0);
10663 appendText(&sSql, sQuery.z, '\'');
10664 sQuery.n = 0;
10665 appendText(&sSql, ",", 0);
10666 appendText(&sSql, zTab, '\'');
10667 zSep = "),(";
10669 sqlite3_finalize(pStmt);
10670 if( bSeparate ){
10671 zSql = sqlite3_mprintf(
10672 "%s))"
10673 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10674 " FROM [sha3sum$query]",
10675 sSql.z, iSize);
10676 }else{
10677 zSql = sqlite3_mprintf(
10678 "%s))"
10679 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10680 " FROM [sha3sum$query]",
10681 sSql.z, iSize);
10683 shell_check_oom(zSql);
10684 freeText(&sQuery);
10685 freeText(&sSql);
10686 if( bDebug ){
10687 utf8_printf(p->out, "%s\n", zSql);
10688 }else{
10689 shell_exec(p, zSql, 0);
10691 sqlite3_free(zSql);
10692 }else
10694 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
10695 if( c=='s'
10696 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10698 char *zCmd;
10699 int i, x;
10700 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10701 if( nArg<2 ){
10702 raw_printf(stderr, "Usage: .system COMMAND\n");
10703 rc = 1;
10704 goto meta_command_exit;
10706 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10707 for(i=2; i<nArg && zCmd!=0; i++){
10708 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10709 zCmd, azArg[i]);
10711 x = zCmd!=0 ? system(zCmd) : 1;
10712 sqlite3_free(zCmd);
10713 if( x ) raw_printf(stderr, "System command returns %d\n", x);
10714 }else
10715 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE) */
10717 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10718 static const char *azBool[] = { "off", "on", "trigger", "full"};
10719 const char *zOut;
10720 int i;
10721 if( nArg!=1 ){
10722 raw_printf(stderr, "Usage: .show\n");
10723 rc = 1;
10724 goto meta_command_exit;
10726 utf8_printf(p->out, "%12.12s: %s\n","echo",
10727 azBool[ShellHasFlag(p, SHFLG_Echo)]);
10728 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10729 utf8_printf(p->out, "%12.12s: %s\n","explain",
10730 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10731 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10732 if( p->mode==MODE_Column
10733 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10735 utf8_printf
10736 (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10737 modeDescr[p->mode], p->cmOpts.iWrap,
10738 p->cmOpts.bWordWrap ? "on" : "off",
10739 p->cmOpts.bQuote ? "" : "no");
10740 }else{
10741 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10743 utf8_printf(p->out, "%12.12s: ", "nullvalue");
10744 output_c_string(p->out, p->nullValue);
10745 raw_printf(p->out, "\n");
10746 utf8_printf(p->out,"%12.12s: %s\n","output",
10747 strlen30(p->outfile) ? p->outfile : "stdout");
10748 utf8_printf(p->out,"%12.12s: ", "colseparator");
10749 output_c_string(p->out, p->colSeparator);
10750 raw_printf(p->out, "\n");
10751 utf8_printf(p->out,"%12.12s: ", "rowseparator");
10752 output_c_string(p->out, p->rowSeparator);
10753 raw_printf(p->out, "\n");
10754 switch( p->statsOn ){
10755 case 0: zOut = "off"; break;
10756 default: zOut = "on"; break;
10757 case 2: zOut = "stmt"; break;
10758 case 3: zOut = "vmstep"; break;
10760 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10761 utf8_printf(p->out, "%12.12s: ", "width");
10762 for (i=0;i<p->nWidth;i++) {
10763 raw_printf(p->out, "%d ", p->colWidth[i]);
10765 raw_printf(p->out, "\n");
10766 utf8_printf(p->out, "%12.12s: %s\n", "filename",
10767 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10768 }else
10770 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10771 if( nArg==2 ){
10772 if( strcmp(azArg[1],"stmt")==0 ){
10773 p->statsOn = 2;
10774 }else if( strcmp(azArg[1],"vmstep")==0 ){
10775 p->statsOn = 3;
10776 }else{
10777 p->statsOn = (u8)booleanValue(azArg[1]);
10779 }else if( nArg==1 ){
10780 display_stats(p->db, p, 0);
10781 }else{
10782 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10783 rc = 1;
10785 }else
10787 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10788 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10789 || strncmp(azArg[0], "indexes", n)==0) )
10791 sqlite3_stmt *pStmt;
10792 char **azResult;
10793 int nRow, nAlloc;
10794 int ii;
10795 ShellText s;
10796 initText(&s);
10797 open_db(p, 0);
10798 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10799 if( rc ){
10800 sqlite3_finalize(pStmt);
10801 return shellDatabaseError(p->db);
10804 if( nArg>2 && c=='i' ){
10805 /* It is an historical accident that the .indexes command shows an error
10806 ** when called with the wrong number of arguments whereas the .tables
10807 ** command does not. */
10808 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10809 rc = 1;
10810 sqlite3_finalize(pStmt);
10811 goto meta_command_exit;
10813 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10814 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10815 if( zDbName==0 ) continue;
10816 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10817 if( sqlite3_stricmp(zDbName, "main")==0 ){
10818 appendText(&s, "SELECT name FROM ", 0);
10819 }else{
10820 appendText(&s, "SELECT ", 0);
10821 appendText(&s, zDbName, '\'');
10822 appendText(&s, "||'.'||name FROM ", 0);
10824 appendText(&s, zDbName, '"');
10825 appendText(&s, ".sqlite_schema ", 0);
10826 if( c=='t' ){
10827 appendText(&s," WHERE type IN ('table','view')"
10828 " AND name NOT LIKE 'sqlite_%'"
10829 " AND name LIKE ?1", 0);
10830 }else{
10831 appendText(&s," WHERE type='index'"
10832 " AND tbl_name LIKE ?1", 0);
10835 rc = sqlite3_finalize(pStmt);
10836 if( rc==SQLITE_OK ){
10837 appendText(&s, " ORDER BY 1", 0);
10838 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10840 freeText(&s);
10841 if( rc ) return shellDatabaseError(p->db);
10843 /* Run the SQL statement prepared by the above block. Store the results
10844 ** as an array of nul-terminated strings in azResult[]. */
10845 nRow = nAlloc = 0;
10846 azResult = 0;
10847 if( nArg>1 ){
10848 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10849 }else{
10850 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10852 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10853 if( nRow>=nAlloc ){
10854 char **azNew;
10855 int n2 = nAlloc*2 + 10;
10856 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10857 shell_check_oom(azNew);
10858 nAlloc = n2;
10859 azResult = azNew;
10861 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10862 shell_check_oom(azResult[nRow]);
10863 nRow++;
10865 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10866 rc = shellDatabaseError(p->db);
10869 /* Pretty-print the contents of array azResult[] to the output */
10870 if( rc==0 && nRow>0 ){
10871 int len, maxlen = 0;
10872 int i, j;
10873 int nPrintCol, nPrintRow;
10874 for(i=0; i<nRow; i++){
10875 len = strlen30(azResult[i]);
10876 if( len>maxlen ) maxlen = len;
10878 nPrintCol = 80/(maxlen+2);
10879 if( nPrintCol<1 ) nPrintCol = 1;
10880 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10881 for(i=0; i<nPrintRow; i++){
10882 for(j=i; j<nRow; j+=nPrintRow){
10883 char *zSp = j<nPrintRow ? "" : " ";
10884 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10885 azResult[j] ? azResult[j]:"");
10887 raw_printf(p->out, "\n");
10891 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10892 sqlite3_free(azResult);
10893 }else
10895 #ifndef SQLITE_SHELL_WASM_MODE
10896 /* Begin redirecting output to the file "testcase-out.txt" */
10897 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10898 output_reset(p);
10899 p->out = output_file_open("testcase-out.txt", 0);
10900 if( p->out==0 ){
10901 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10903 if( nArg>=2 ){
10904 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10905 }else{
10906 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10908 }else
10909 #endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10911 #ifndef SQLITE_UNTESTABLE
10912 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10913 static const struct {
10914 const char *zCtrlName; /* Name of a test-control option */
10915 int ctrlCode; /* Integer code for that option */
10916 int unSafe; /* Not valid for --safe mode */
10917 const char *zUsage; /* Usage notes */
10918 } aCtrl[] = {
10919 { "always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
10920 { "assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
10921 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10922 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10923 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
10924 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
10925 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10926 { "imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10927 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
10928 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
10929 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
10930 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
10931 #ifdef YYCOVERAGE
10932 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
10933 #endif
10934 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
10935 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
10936 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
10937 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
10938 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
10939 { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
10940 { "tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
10942 int testctrl = -1;
10943 int iCtrl = -1;
10944 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10945 int isOk = 0;
10946 int i, n2;
10947 const char *zCmd = 0;
10949 open_db(p, 0);
10950 zCmd = nArg>=2 ? azArg[1] : "help";
10952 /* The argument can optionally begin with "-" or "--" */
10953 if( zCmd[0]=='-' && zCmd[1] ){
10954 zCmd++;
10955 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10958 /* --help lists all test-controls */
10959 if( strcmp(zCmd,"help")==0 ){
10960 utf8_printf(p->out, "Available test-controls:\n");
10961 for(i=0; i<ArraySize(aCtrl); i++){
10962 utf8_printf(p->out, " .testctrl %s %s\n",
10963 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10965 rc = 1;
10966 goto meta_command_exit;
10969 /* convert testctrl text option to value. allow any unique prefix
10970 ** of the option name, or a numerical value. */
10971 n2 = strlen30(zCmd);
10972 for(i=0; i<ArraySize(aCtrl); i++){
10973 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10974 if( testctrl<0 ){
10975 testctrl = aCtrl[i].ctrlCode;
10976 iCtrl = i;
10977 }else{
10978 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10979 "Use \".testctrl --help\" for help\n", zCmd);
10980 rc = 1;
10981 goto meta_command_exit;
10985 if( testctrl<0 ){
10986 utf8_printf(stderr,"Error: unknown test-control: %s\n"
10987 "Use \".testctrl --help\" for help\n", zCmd);
10988 }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10989 utf8_printf(stderr,
10990 "line %d: \".testctrl %s\" may not be used in safe mode\n",
10991 p->lineno, aCtrl[iCtrl].zCtrlName);
10992 exit(1);
10993 }else{
10994 switch(testctrl){
10996 /* sqlite3_test_control(int, db, int) */
10997 case SQLITE_TESTCTRL_OPTIMIZATIONS:
10998 if( nArg==3 ){
10999 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
11000 rc2 = sqlite3_test_control(testctrl, p->db, opt);
11001 isOk = 3;
11003 break;
11005 /* sqlite3_test_control(int) */
11006 case SQLITE_TESTCTRL_PRNG_SAVE:
11007 case SQLITE_TESTCTRL_PRNG_RESTORE:
11008 case SQLITE_TESTCTRL_BYTEORDER:
11009 if( nArg==2 ){
11010 rc2 = sqlite3_test_control(testctrl);
11011 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
11013 break;
11015 /* sqlite3_test_control(int, uint) */
11016 case SQLITE_TESTCTRL_PENDING_BYTE:
11017 if( nArg==3 ){
11018 unsigned int opt = (unsigned int)integerValue(azArg[2]);
11019 rc2 = sqlite3_test_control(testctrl, opt);
11020 isOk = 3;
11022 break;
11024 /* sqlite3_test_control(int, int, sqlite3*) */
11025 case SQLITE_TESTCTRL_PRNG_SEED:
11026 if( nArg==3 || nArg==4 ){
11027 int ii = (int)integerValue(azArg[2]);
11028 sqlite3 *db;
11029 if( ii==0 && strcmp(azArg[2],"random")==0 ){
11030 sqlite3_randomness(sizeof(ii),&ii);
11031 printf("-- random seed: %d\n", ii);
11033 if( nArg==3 ){
11034 db = 0;
11035 }else{
11036 db = p->db;
11037 /* Make sure the schema has been loaded */
11038 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11040 rc2 = sqlite3_test_control(testctrl, ii, db);
11041 isOk = 3;
11043 break;
11045 /* sqlite3_test_control(int, int) */
11046 case SQLITE_TESTCTRL_ASSERT:
11047 case SQLITE_TESTCTRL_ALWAYS:
11048 if( nArg==3 ){
11049 int opt = booleanValue(azArg[2]);
11050 rc2 = sqlite3_test_control(testctrl, opt);
11051 isOk = 1;
11053 break;
11055 /* sqlite3_test_control(int, int) */
11056 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11057 case SQLITE_TESTCTRL_NEVER_CORRUPT:
11058 if( nArg==3 ){
11059 int opt = booleanValue(azArg[2]);
11060 rc2 = sqlite3_test_control(testctrl, opt);
11061 isOk = 3;
11063 break;
11065 /* sqlite3_test_control(sqlite3*) */
11066 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11067 rc2 = sqlite3_test_control(testctrl, p->db);
11068 isOk = 3;
11069 break;
11071 case SQLITE_TESTCTRL_IMPOSTER:
11072 if( nArg==5 ){
11073 rc2 = sqlite3_test_control(testctrl, p->db,
11074 azArg[2],
11075 integerValue(azArg[3]),
11076 integerValue(azArg[4]));
11077 isOk = 3;
11079 break;
11081 case SQLITE_TESTCTRL_SEEK_COUNT: {
11082 u64 x = 0;
11083 rc2 = sqlite3_test_control(testctrl, p->db, &x);
11084 utf8_printf(p->out, "%llu\n", x);
11085 isOk = 3;
11086 break;
11089 #ifdef YYCOVERAGE
11090 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11091 if( nArg==2 ){
11092 sqlite3_test_control(testctrl, p->out);
11093 isOk = 3;
11095 break;
11097 #endif
11098 #ifdef SQLITE_DEBUG
11099 case SQLITE_TESTCTRL_TUNE: {
11100 if( nArg==4 ){
11101 int id = (int)integerValue(azArg[2]);
11102 int val = (int)integerValue(azArg[3]);
11103 sqlite3_test_control(testctrl, id, &val);
11104 isOk = 3;
11105 }else if( nArg==3 ){
11106 int id = (int)integerValue(azArg[2]);
11107 sqlite3_test_control(testctrl, -id, &rc2);
11108 isOk = 1;
11109 }else if( nArg==2 ){
11110 int id = 1;
11111 while(1){
11112 int val = 0;
11113 rc2 = sqlite3_test_control(testctrl, -id, &val);
11114 if( rc2!=SQLITE_OK ) break;
11115 if( id>1 ) utf8_printf(p->out, " ");
11116 utf8_printf(p->out, "%d: %d", id, val);
11117 id++;
11119 if( id>1 ) utf8_printf(p->out, "\n");
11120 isOk = 3;
11122 break;
11124 #endif
11125 case SQLITE_TESTCTRL_SORTER_MMAP:
11126 if( nArg==3 ){
11127 int opt = (unsigned int)integerValue(azArg[2]);
11128 rc2 = sqlite3_test_control(testctrl, p->db, opt);
11129 isOk = 3;
11131 break;
11134 if( isOk==0 && iCtrl>=0 ){
11135 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11136 rc = 1;
11137 }else if( isOk==1 ){
11138 raw_printf(p->out, "%d\n", rc2);
11139 }else if( isOk==2 ){
11140 raw_printf(p->out, "0x%08x\n", rc2);
11142 }else
11143 #endif /* !defined(SQLITE_UNTESTABLE) */
11145 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11146 open_db(p, 0);
11147 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11148 }else
11150 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11151 if( nArg==2 ){
11152 enableTimer = booleanValue(azArg[1]);
11153 if( enableTimer && !HAS_TIMER ){
11154 raw_printf(stderr, "Error: timer not available on this system.\n");
11155 enableTimer = 0;
11157 }else{
11158 raw_printf(stderr, "Usage: .timer on|off\n");
11159 rc = 1;
11161 }else
11163 #ifndef SQLITE_OMIT_TRACE
11164 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11165 int mType = 0;
11166 int jj;
11167 open_db(p, 0);
11168 for(jj=1; jj<nArg; jj++){
11169 const char *z = azArg[jj];
11170 if( z[0]=='-' ){
11171 if( optionMatch(z, "expanded") ){
11172 p->eTraceType = SHELL_TRACE_EXPANDED;
11174 #ifdef SQLITE_ENABLE_NORMALIZE
11175 else if( optionMatch(z, "normalized") ){
11176 p->eTraceType = SHELL_TRACE_NORMALIZED;
11178 #endif
11179 else if( optionMatch(z, "plain") ){
11180 p->eTraceType = SHELL_TRACE_PLAIN;
11182 else if( optionMatch(z, "profile") ){
11183 mType |= SQLITE_TRACE_PROFILE;
11185 else if( optionMatch(z, "row") ){
11186 mType |= SQLITE_TRACE_ROW;
11188 else if( optionMatch(z, "stmt") ){
11189 mType |= SQLITE_TRACE_STMT;
11191 else if( optionMatch(z, "close") ){
11192 mType |= SQLITE_TRACE_CLOSE;
11194 else {
11195 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11196 rc = 1;
11197 goto meta_command_exit;
11199 }else{
11200 output_file_close(p->traceOut);
11201 p->traceOut = output_file_open(azArg[1], 0);
11204 if( p->traceOut==0 ){
11205 sqlite3_trace_v2(p->db, 0, 0, 0);
11206 }else{
11207 if( mType==0 ) mType = SQLITE_TRACE_STMT;
11208 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11210 }else
11211 #endif /* !defined(SQLITE_OMIT_TRACE) */
11213 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11214 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11215 int ii;
11216 int lenOpt;
11217 char *zOpt;
11218 if( nArg<2 ){
11219 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11220 rc = 1;
11221 goto meta_command_exit;
11223 open_db(p, 0);
11224 zOpt = azArg[1];
11225 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11226 lenOpt = (int)strlen(zOpt);
11227 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11228 assert( azArg[nArg]==0 );
11229 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11230 }else{
11231 for(ii=1; ii<nArg; ii++){
11232 sqlite3_create_module(p->db, azArg[ii], 0, 0);
11235 }else
11236 #endif
11238 #if SQLITE_USER_AUTHENTICATION
11239 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11240 if( nArg<2 ){
11241 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11242 rc = 1;
11243 goto meta_command_exit;
11245 open_db(p, 0);
11246 if( strcmp(azArg[1],"login")==0 ){
11247 if( nArg!=4 ){
11248 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11249 rc = 1;
11250 goto meta_command_exit;
11252 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11253 strlen30(azArg[3]));
11254 if( rc ){
11255 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11256 rc = 1;
11258 }else if( strcmp(azArg[1],"add")==0 ){
11259 if( nArg!=5 ){
11260 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11261 rc = 1;
11262 goto meta_command_exit;
11264 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11265 booleanValue(azArg[4]));
11266 if( rc ){
11267 raw_printf(stderr, "User-Add failed: %d\n", rc);
11268 rc = 1;
11270 }else if( strcmp(azArg[1],"edit")==0 ){
11271 if( nArg!=5 ){
11272 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11273 rc = 1;
11274 goto meta_command_exit;
11276 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11277 booleanValue(azArg[4]));
11278 if( rc ){
11279 raw_printf(stderr, "User-Edit failed: %d\n", rc);
11280 rc = 1;
11282 }else if( strcmp(azArg[1],"delete")==0 ){
11283 if( nArg!=3 ){
11284 raw_printf(stderr, "Usage: .user delete USER\n");
11285 rc = 1;
11286 goto meta_command_exit;
11288 rc = sqlite3_user_delete(p->db, azArg[2]);
11289 if( rc ){
11290 raw_printf(stderr, "User-Delete failed: %d\n", rc);
11291 rc = 1;
11293 }else{
11294 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11295 rc = 1;
11296 goto meta_command_exit;
11298 }else
11299 #endif /* SQLITE_USER_AUTHENTICATION */
11301 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11302 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11303 sqlite3_libversion(), sqlite3_sourceid());
11304 /* BEGIN SQLCIPHER */
11305 #ifdef SQLITE_HAS_CODEC
11307 extern char* sqlcipher_version();
11308 char *sqlcipher_ver = sqlcipher_version();
11309 utf8_printf(p->out, "SQLCipher %s\n", sqlcipher_ver);
11310 sqlite3_free(sqlcipher_ver);
11312 #endif
11313 /* END SQLCIPHER */
11314 #if SQLITE_HAVE_ZLIB
11315 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11316 #endif
11317 #define CTIMEOPT_VAL_(opt) #opt
11318 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11319 #if defined(__clang__) && defined(__clang_major__)
11320 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11321 CTIMEOPT_VAL(__clang_minor__) "."
11322 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11323 #elif defined(_MSC_VER)
11324 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11325 #elif defined(__GNUC__) && defined(__VERSION__)
11326 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11327 #endif
11328 }else
11330 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11331 const char *zDbName = nArg==2 ? azArg[1] : "main";
11332 sqlite3_vfs *pVfs = 0;
11333 if( p->db ){
11334 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11335 if( pVfs ){
11336 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
11337 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
11338 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
11339 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11342 }else
11344 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11345 sqlite3_vfs *pVfs;
11346 sqlite3_vfs *pCurrent = 0;
11347 if( p->db ){
11348 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11350 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11351 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
11352 pVfs==pCurrent ? " <--- CURRENT" : "");
11353 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
11354 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
11355 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11356 if( pVfs->pNext ){
11357 raw_printf(p->out, "-----------------------------------\n");
11360 }else
11362 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11363 const char *zDbName = nArg==2 ? azArg[1] : "main";
11364 char *zVfsName = 0;
11365 if( p->db ){
11366 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11367 if( zVfsName ){
11368 utf8_printf(p->out, "%s\n", zVfsName);
11369 sqlite3_free(zVfsName);
11372 }else
11374 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11375 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11376 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11377 }else
11379 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11380 int j;
11381 assert( nArg<=ArraySize(azArg) );
11382 p->nWidth = nArg-1;
11383 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11384 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11385 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11386 for(j=1; j<nArg; j++){
11387 p->colWidth[j-1] = (int)integerValue(azArg[j]);
11389 }else
11392 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11393 " \"%s\". Enter \".help\" for help\n", azArg[0]);
11394 rc = 1;
11397 meta_command_exit:
11398 if( p->outCount ){
11399 p->outCount--;
11400 if( p->outCount==0 ) output_reset(p);
11402 p->bSafeMode = p->bSafeModePersist;
11403 return rc;
11406 /* Line scan result and intermediate states (supporting scan resumption)
11408 #ifndef CHAR_BIT
11409 # define CHAR_BIT 8
11410 #endif
11411 typedef enum {
11412 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11413 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11414 QSS_Start = 0
11415 } QuickScanState;
11416 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11417 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11418 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11419 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11420 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11423 ** Scan line for classification to guide shell's handling.
11424 ** The scan is resumable for subsequent lines when prior
11425 ** return values are passed as the 2nd argument.
11427 static QuickScanState quickscan(char *zLine, QuickScanState qss){
11428 char cin;
11429 char cWait = (char)qss; /* intentional narrowing loss */
11430 if( cWait==0 ){
11431 PlainScan:
11432 assert( cWait==0 );
11433 while( (cin = *zLine++)!=0 ){
11434 if( IsSpace(cin) )
11435 continue;
11436 switch (cin){
11437 case '-':
11438 if( *zLine!='-' )
11439 break;
11440 while((cin = *++zLine)!=0 )
11441 if( cin=='\n')
11442 goto PlainScan;
11443 return qss;
11444 case ';':
11445 qss |= QSS_EndingSemi;
11446 continue;
11447 case '/':
11448 if( *zLine=='*' ){
11449 ++zLine;
11450 cWait = '*';
11451 qss = QSS_SETV(qss, cWait);
11452 goto TermScan;
11454 break;
11455 case '[':
11456 cin = ']';
11457 /* fall thru */
11458 case '`': case '\'': case '"':
11459 cWait = cin;
11460 qss = QSS_HasDark | cWait;
11461 goto TermScan;
11462 default:
11463 break;
11465 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11467 }else{
11468 TermScan:
11469 while( (cin = *zLine++)!=0 ){
11470 if( cin==cWait ){
11471 switch( cWait ){
11472 case '*':
11473 if( *zLine != '/' )
11474 continue;
11475 ++zLine;
11476 cWait = 0;
11477 qss = QSS_SETV(qss, 0);
11478 goto PlainScan;
11479 case '`': case '\'': case '"':
11480 if(*zLine==cWait){
11481 ++zLine;
11482 continue;
11484 /* fall thru */
11485 case ']':
11486 cWait = 0;
11487 qss = QSS_SETV(qss, 0);
11488 goto PlainScan;
11489 default: assert(0);
11494 return qss;
11498 ** Return TRUE if the line typed in is an SQL command terminator other
11499 ** than a semi-colon. The SQL Server style "go" command is understood
11500 ** as is the Oracle "/".
11502 static int line_is_command_terminator(char *zLine){
11503 while( IsSpace(zLine[0]) ){ zLine++; };
11504 if( zLine[0]=='/' )
11505 zLine += 1; /* Oracle */
11506 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11507 zLine += 2; /* SQL Server */
11508 else
11509 return 0;
11510 return quickscan(zLine, QSS_Start)==QSS_Start;
11514 ** We need a default sqlite3_complete() implementation to use in case
11515 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
11516 ** any arbitrary text is a complete SQL statement. This is not very
11517 ** user-friendly, but it does seem to work.
11519 #ifdef SQLITE_OMIT_COMPLETE
11520 #define sqlite3_complete(x) 1
11521 #endif
11524 ** Return true if zSql is a complete SQL statement. Return false if it
11525 ** ends in the middle of a string literal or C-style comment.
11527 static int line_is_complete(char *zSql, int nSql){
11528 int rc;
11529 if( zSql==0 ) return 1;
11530 zSql[nSql] = ';';
11531 zSql[nSql+1] = 0;
11532 rc = sqlite3_complete(zSql);
11533 zSql[nSql] = 0;
11534 return rc;
11538 ** Run a single line of SQL. Return the number of errors.
11540 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11541 int rc;
11542 char *zErrMsg = 0;
11544 open_db(p, 0);
11545 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11546 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11547 BEGIN_TIMER;
11548 rc = shell_exec(p, zSql, &zErrMsg);
11549 END_TIMER;
11550 if( rc || zErrMsg ){
11551 char zPrefix[100];
11552 const char *zErrorTail;
11553 const char *zErrorType;
11554 if( zErrMsg==0 ){
11555 zErrorType = "Error";
11556 zErrorTail = sqlite3_errmsg(p->db);
11557 }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11558 zErrorType = "Parse error";
11559 zErrorTail = &zErrMsg[12];
11560 }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11561 zErrorType = "Runtime error";
11562 zErrorTail = &zErrMsg[10];
11563 }else{
11564 zErrorType = "Error";
11565 zErrorTail = zErrMsg;
11567 if( in!=0 || !stdin_is_interactive ){
11568 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11569 "%s near line %d:", zErrorType, startline);
11570 }else{
11571 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11573 utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11574 sqlite3_free(zErrMsg);
11575 zErrMsg = 0;
11576 return 1;
11577 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11578 char zLineBuf[2000];
11579 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11580 "changes: %lld total_changes: %lld",
11581 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11582 raw_printf(p->out, "%s\n", zLineBuf);
11584 return 0;
11587 static void echo_group_input(ShellState *p, const char *zDo){
11588 if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11591 #ifdef SQLITE_SHELL_WASM_MODE
11593 ** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11594 ** because we need the global shellState and cannot access it from that function
11595 ** without moving lots of code around (creating a larger/messier diff).
11597 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11598 /* Parse the next line from shellState.wasm.zInput. */
11599 const char *zBegin = shellState.wasm.zPos;
11600 const char *z = zBegin;
11601 char *zLine = 0;
11602 int nZ = 0;
11604 UNUSED_PARAMETER(in);
11605 UNUSED_PARAMETER(isContinuation);
11606 if(!z || !*z){
11607 return 0;
11609 while(*z && isspace(*z)) ++z;
11610 zBegin = z;
11611 for(; *z && '\n'!=*z; ++nZ, ++z){}
11612 if(nZ>0 && '\r'==zBegin[nZ-1]){
11613 --nZ;
11615 shellState.wasm.zPos = z;
11616 zLine = realloc(zPrior, nZ+1);
11617 shell_check_oom(zLine);
11618 memcpy(zLine, zBegin, (size_t)nZ);
11619 zLine[nZ] = 0;
11620 return zLine;
11622 #endif /* SQLITE_SHELL_WASM_MODE */
11625 ** Read input from *in and process it. If *in==0 then input
11626 ** is interactive - the user is typing it it. Otherwise, input
11627 ** is coming from a file or device. A prompt is issued and history
11628 ** is saved only if input is interactive. An interrupt signal will
11629 ** cause this routine to exit immediately, unless input is interactive.
11631 ** Return the number of errors.
11633 static int process_input(ShellState *p){
11634 char *zLine = 0; /* A single input line */
11635 char *zSql = 0; /* Accumulated SQL text */
11636 int nLine; /* Length of current line */
11637 int nSql = 0; /* Bytes of zSql[] used */
11638 int nAlloc = 0; /* Allocated zSql[] space */
11639 int rc; /* Error code */
11640 int errCnt = 0; /* Number of errors seen */
11641 int startline = 0; /* Line number for start of current input */
11642 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11644 if( p->inputNesting==MAX_INPUT_NESTING ){
11645 /* This will be more informative in a later version. */
11646 utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11647 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11648 return 1;
11650 ++p->inputNesting;
11651 p->lineno = 0;
11652 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11653 fflush(p->out);
11654 zLine = one_input_line(p->in, zLine, nSql>0);
11655 if( zLine==0 ){
11656 /* End of input */
11657 if( p->in==0 && stdin_is_interactive ) printf("\n");
11658 break;
11660 if( seenInterrupt ){
11661 if( p->in!=0 ) break;
11662 seenInterrupt = 0;
11664 p->lineno++;
11665 if( QSS_INPLAIN(qss)
11666 && line_is_command_terminator(zLine)
11667 && line_is_complete(zSql, nSql) ){
11668 memcpy(zLine,";",2);
11670 qss = quickscan(zLine, qss);
11671 if( QSS_PLAINWHITE(qss) && nSql==0 ){
11672 /* Just swallow single-line whitespace */
11673 echo_group_input(p, zLine);
11674 qss = QSS_Start;
11675 continue;
11677 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11678 echo_group_input(p, zLine);
11679 if( zLine[0]=='.' ){
11680 rc = do_meta_command(zLine, p);
11681 if( rc==2 ){ /* exit requested */
11682 break;
11683 }else if( rc ){
11684 errCnt++;
11687 qss = QSS_Start;
11688 continue;
11690 /* No single-line dispositions remain; accumulate line(s). */
11691 nLine = strlen30(zLine);
11692 if( nSql+nLine+2>=nAlloc ){
11693 /* Grow buffer by half-again increments when big. */
11694 nAlloc = nSql+(nSql>>1)+nLine+100;
11695 zSql = realloc(zSql, nAlloc);
11696 shell_check_oom(zSql);
11698 if( nSql==0 ){
11699 int i;
11700 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11701 assert( nAlloc>0 && zSql!=0 );
11702 memcpy(zSql, zLine+i, nLine+1-i);
11703 startline = p->lineno;
11704 nSql = nLine-i;
11705 }else{
11706 zSql[nSql++] = '\n';
11707 memcpy(zSql+nSql, zLine, nLine+1);
11708 nSql += nLine;
11710 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11711 echo_group_input(p, zSql);
11712 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11713 nSql = 0;
11714 if( p->outCount ){
11715 output_reset(p);
11716 p->outCount = 0;
11717 }else{
11718 clearTempFile(p);
11720 p->bSafeMode = p->bSafeModePersist;
11721 qss = QSS_Start;
11722 }else if( nSql && QSS_PLAINWHITE(qss) ){
11723 echo_group_input(p, zSql);
11724 nSql = 0;
11725 qss = QSS_Start;
11728 if( nSql ){
11729 /* This may be incomplete. Let the SQL parser deal with that. */
11730 echo_group_input(p, zSql);
11731 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11733 free(zSql);
11734 free(zLine);
11735 --p->inputNesting;
11736 return errCnt>0;
11740 ** Return a pathname which is the user's home directory. A
11741 ** 0 return indicates an error of some kind.
11743 static char *find_home_dir(int clearFlag){
11744 static char *home_dir = NULL;
11745 if( clearFlag ){
11746 free(home_dir);
11747 home_dir = 0;
11748 return 0;
11750 if( home_dir ) return home_dir;
11752 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11753 && !defined(__RTP__) && !defined(_WRS_KERNEL)
11755 struct passwd *pwent;
11756 uid_t uid = getuid();
11757 if( (pwent=getpwuid(uid)) != NULL) {
11758 home_dir = pwent->pw_dir;
11761 #endif
11763 #if defined(_WIN32_WCE)
11764 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11766 home_dir = "/";
11767 #else
11769 #if defined(_WIN32) || defined(WIN32)
11770 if (!home_dir) {
11771 home_dir = getenv("USERPROFILE");
11773 #endif
11775 if (!home_dir) {
11776 home_dir = getenv("HOME");
11779 #if defined(_WIN32) || defined(WIN32)
11780 if (!home_dir) {
11781 char *zDrive, *zPath;
11782 int n;
11783 zDrive = getenv("HOMEDRIVE");
11784 zPath = getenv("HOMEPATH");
11785 if( zDrive && zPath ){
11786 n = strlen30(zDrive) + strlen30(zPath) + 1;
11787 home_dir = malloc( n );
11788 if( home_dir==0 ) return 0;
11789 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11790 return home_dir;
11792 home_dir = "c:\\";
11794 #endif
11796 #endif /* !_WIN32_WCE */
11798 if( home_dir ){
11799 int n = strlen30(home_dir) + 1;
11800 char *z = malloc( n );
11801 if( z ) memcpy(z, home_dir, n);
11802 home_dir = z;
11805 return home_dir;
11809 ** Read input from the file given by sqliterc_override. Or if that
11810 ** parameter is NULL, take input from ~/.sqliterc
11812 ** Returns the number of errors.
11814 static void process_sqliterc(
11815 ShellState *p, /* Configuration data */
11816 const char *sqliterc_override /* Name of config file. NULL to use default */
11818 char *home_dir = NULL;
11819 const char *sqliterc = sqliterc_override;
11820 char *zBuf = 0;
11821 FILE *inSaved = p->in;
11822 int savedLineno = p->lineno;
11824 if (sqliterc == NULL) {
11825 home_dir = find_home_dir(0);
11826 if( home_dir==0 ){
11827 raw_printf(stderr, "-- warning: cannot find home directory;"
11828 " cannot read ~/.sqliterc\n");
11829 return;
11831 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11832 shell_check_oom(zBuf);
11833 sqliterc = zBuf;
11835 p->in = fopen(sqliterc,"rb");
11836 if( p->in ){
11837 if( stdin_is_interactive ){
11838 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11840 if( process_input(p) && bail_on_error ) exit(1);
11841 fclose(p->in);
11842 }else if( sqliterc_override!=0 ){
11843 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11844 if( bail_on_error ) exit(1);
11846 p->in = inSaved;
11847 p->lineno = savedLineno;
11848 sqlite3_free(zBuf);
11852 ** Show available command line options
11854 static const char zOptions[] =
11855 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11856 " -A ARGS... run \".archive ARGS\" and exit\n"
11857 #endif
11858 " -append append the database to the end of the file\n"
11859 " -ascii set output mode to 'ascii'\n"
11860 " -bail stop after hitting an error\n"
11861 " -batch force batch I/O\n"
11862 " -box set output mode to 'box'\n"
11863 " -column set output mode to 'column'\n"
11864 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11865 " -csv set output mode to 'csv'\n"
11866 #if !defined(SQLITE_OMIT_DESERIALIZE)
11867 " -deserialize open the database using sqlite3_deserialize()\n"
11868 #endif
11869 " -echo print inputs before execution\n"
11870 " -init FILENAME read/process named file\n"
11871 " -[no]header turn headers on or off\n"
11872 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11873 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11874 #endif
11875 " -help show this message\n"
11876 " -html set output mode to HTML\n"
11877 " -interactive force interactive I/O\n"
11878 " -json set output mode to 'json'\n"
11879 " -line set output mode to 'line'\n"
11880 " -list set output mode to 'list'\n"
11881 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11882 " -markdown set output mode to 'markdown'\n"
11883 #if !defined(SQLITE_OMIT_DESERIALIZE)
11884 " -maxsize N maximum size for a --deserialize database\n"
11885 #endif
11886 " -memtrace trace all memory allocations and deallocations\n"
11887 " -mmap N default mmap size set to N\n"
11888 #ifdef SQLITE_ENABLE_MULTIPLEX
11889 " -multiplex enable the multiplexor VFS\n"
11890 #endif
11891 " -newline SEP set output row separator. Default: '\\n'\n"
11892 " -nofollow refuse to open symbolic links to database files\n"
11893 " -nonce STRING set the safe-mode escape nonce\n"
11894 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11895 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11896 " -quote set output mode to 'quote'\n"
11897 " -readonly open the database read-only\n"
11898 " -safe enable safe-mode\n"
11899 " -separator SEP set output column separator. Default: '|'\n"
11900 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11901 " -sorterref SIZE sorter references threshold size\n"
11902 #endif
11903 " -stats print memory stats before each finalize\n"
11904 " -table set output mode to 'table'\n"
11905 " -tabs set output mode to 'tabs'\n"
11906 " -version show SQLite version\n"
11907 " -vfs NAME use NAME as the default VFS\n"
11908 #ifdef SQLITE_ENABLE_VFSTRACE
11909 " -vfstrace enable tracing of all VFS calls\n"
11910 #endif
11911 #ifdef SQLITE_HAVE_ZLIB
11912 " -zip open the file as a ZIP Archive\n"
11913 #endif
11915 static void usage(int showDetail){
11916 utf8_printf(stderr,
11917 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11918 "FILENAME is the name of an SQLite database. A new database is created\n"
11919 "if the file does not previously exist.\n", Argv0);
11920 if( showDetail ){
11921 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11922 }else{
11923 raw_printf(stderr, "Use the -help option for additional information\n");
11925 exit(1);
11929 ** Internal check: Verify that the SQLite is uninitialized. Print a
11930 ** error message if it is initialized.
11932 static void verify_uninitialized(void){
11933 if( sqlite3_config(-1)==SQLITE_MISUSE ){
11934 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11935 " initialization.\n");
11940 ** Initialize the state information in data
11942 static void main_init(ShellState *data) {
11943 memset(data, 0, sizeof(*data));
11944 data->normalMode = data->cMode = data->mode = MODE_List;
11945 data->autoExplain = 1;
11946 data->pAuxDb = &data->aAuxDb[0];
11947 memcpy(data->colSeparator,SEP_Column, 2);
11948 memcpy(data->rowSeparator,SEP_Row, 2);
11949 data->showHeader = 0;
11950 data->shellFlgs = SHFLG_Lookaside;
11951 verify_uninitialized();
11952 sqlite3_config(SQLITE_CONFIG_URI, 1);
11953 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11954 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11955 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11956 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
11960 ** Output text to the console in a font that attracts extra attention.
11962 #ifdef _WIN32
11963 static void printBold(const char *zText){
11964 #if !SQLITE_OS_WINRT
11965 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11966 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11967 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11968 SetConsoleTextAttribute(out,
11969 FOREGROUND_RED|FOREGROUND_INTENSITY
11971 #endif
11972 printf("%s", zText);
11973 #if !SQLITE_OS_WINRT
11974 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11975 #endif
11977 #else
11978 static void printBold(const char *zText){
11979 printf("\033[1m%s\033[0m", zText);
11981 #endif
11984 ** Get the argument to an --option. Throw an error and die if no argument
11985 ** is available.
11987 static char *cmdline_option_value(int argc, char **argv, int i){
11988 if( i==argc ){
11989 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11990 argv[0], argv[argc-1]);
11991 exit(1);
11993 return argv[i];
11996 #ifndef SQLITE_SHELL_IS_UTF8
11997 # if (defined(_WIN32) || defined(WIN32)) \
11998 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11999 # define SQLITE_SHELL_IS_UTF8 (0)
12000 # else
12001 # define SQLITE_SHELL_IS_UTF8 (1)
12002 # endif
12003 #endif
12005 #ifdef SQLITE_SHELL_WASM_MODE
12006 # define main fiddle_main
12007 #endif
12009 #if SQLITE_SHELL_IS_UTF8
12010 int SQLITE_CDECL main(int argc, char **argv){
12011 #else
12012 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12013 char **argv;
12014 #endif
12015 #ifdef SQLITE_DEBUG
12016 sqlite3_int64 mem_main_enter = sqlite3_memory_used();
12017 #endif
12018 char *zErrMsg = 0;
12019 #ifdef SQLITE_SHELL_WASM_MODE
12020 # define data shellState
12021 #else
12022 ShellState data;
12023 #endif
12024 const char *zInitFile = 0;
12025 int i;
12026 int rc = 0;
12027 int warnInmemoryDb = 0;
12028 int readStdin = 1;
12029 int nCmd = 0;
12030 char **azCmd = 0;
12031 const char *zVfs = 0; /* Value of -vfs command-line option */
12032 #if !SQLITE_SHELL_IS_UTF8
12033 char **argvToFree = 0;
12034 int argcToFree = 0;
12035 #endif
12037 setBinaryMode(stdin, 0);
12038 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12039 #ifdef SQLITE_SHELL_WASM_MODE
12040 stdin_is_interactive = 0;
12041 stdout_is_console = 1;
12042 #else
12043 stdin_is_interactive = isatty(0);
12044 stdout_is_console = isatty(1);
12045 #endif
12047 #if !defined(_WIN32_WCE)
12048 if( getenv("SQLITE_DEBUG_BREAK") ){
12049 if( isatty(0) && isatty(2) ){
12050 fprintf(stderr,
12051 "attach debugger to process %d and press any key to continue.\n",
12052 GETPID());
12053 fgetc(stdin);
12054 }else{
12055 #if defined(_WIN32) || defined(WIN32)
12056 #if SQLITE_OS_WINRT
12057 __debugbreak();
12058 #else
12059 DebugBreak();
12060 #endif
12061 #elif defined(SIGTRAP)
12062 raise(SIGTRAP);
12063 #endif
12066 #endif
12068 #if USE_SYSTEM_SQLITE+0!=1
12069 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12070 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12071 sqlite3_sourceid(), SQLITE_SOURCE_ID);
12072 exit(1);
12074 #endif
12075 main_init(&data);
12077 /* On Windows, we must translate command-line arguments into UTF-8.
12078 ** The SQLite memory allocator subsystem has to be enabled in order to
12079 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12080 ** subsequent sqlite3_config() calls will work. So copy all results into
12081 ** memory that does not come from the SQLite memory allocator.
12083 #if !SQLITE_SHELL_IS_UTF8
12084 sqlite3_initialize();
12085 argvToFree = malloc(sizeof(argv[0])*argc*2);
12086 shell_check_oom(argvToFree);
12087 argcToFree = argc;
12088 argv = argvToFree + argc;
12089 for(i=0; i<argc; i++){
12090 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12091 int n;
12092 shell_check_oom(z);
12093 n = (int)strlen(z);
12094 argv[i] = malloc( n+1 );
12095 shell_check_oom(argv[i]);
12096 memcpy(argv[i], z, n+1);
12097 argvToFree[i] = argv[i];
12098 sqlite3_free(z);
12100 sqlite3_shutdown();
12101 #endif
12103 assert( argc>=1 && argv && argv[0] );
12104 Argv0 = argv[0];
12106 /* Make sure we have a valid signal handler early, before anything
12107 ** else is done.
12109 #ifdef SIGINT
12110 signal(SIGINT, interrupt_handler);
12111 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12112 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12113 #endif
12115 #ifdef SQLITE_SHELL_DBNAME_PROC
12117 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12118 ** of a C-function that will provide the name of the database file. Use
12119 ** this compile-time option to embed this shell program in larger
12120 ** applications. */
12121 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12122 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12123 warnInmemoryDb = 0;
12125 #endif
12127 /* Do an initial pass through the command-line argument to locate
12128 ** the name of the database file, the name of the initialization file,
12129 ** the size of the alternative malloc heap,
12130 ** and the first command to execute.
12132 verify_uninitialized();
12133 for(i=1; i<argc; i++){
12134 char *z;
12135 z = argv[i];
12136 if( z[0]!='-' ){
12137 if( data.aAuxDb->zDbFilename==0 ){
12138 data.aAuxDb->zDbFilename = z;
12139 }else{
12140 /* Excesss arguments are interpreted as SQL (or dot-commands) and
12141 ** mean that nothing is read from stdin */
12142 readStdin = 0;
12143 nCmd++;
12144 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12145 shell_check_oom(azCmd);
12146 azCmd[nCmd-1] = z;
12149 if( z[1]=='-' ) z++;
12150 if( strcmp(z,"-separator")==0
12151 || strcmp(z,"-nullvalue")==0
12152 || strcmp(z,"-newline")==0
12153 || strcmp(z,"-cmd")==0
12155 (void)cmdline_option_value(argc, argv, ++i);
12156 }else if( strcmp(z,"-init")==0 ){
12157 zInitFile = cmdline_option_value(argc, argv, ++i);
12158 }else if( strcmp(z,"-batch")==0 ){
12159 /* Need to check for batch mode here to so we can avoid printing
12160 ** informational messages (like from process_sqliterc) before
12161 ** we do the actual processing of arguments later in a second pass.
12163 stdin_is_interactive = 0;
12164 }else if( strcmp(z,"-heap")==0 ){
12165 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12166 const char *zSize;
12167 sqlite3_int64 szHeap;
12169 zSize = cmdline_option_value(argc, argv, ++i);
12170 szHeap = integerValue(zSize);
12171 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12172 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12173 #else
12174 (void)cmdline_option_value(argc, argv, ++i);
12175 #endif
12176 }else if( strcmp(z,"-pagecache")==0 ){
12177 sqlite3_int64 n, sz;
12178 sz = integerValue(cmdline_option_value(argc,argv,++i));
12179 if( sz>70000 ) sz = 70000;
12180 if( sz<0 ) sz = 0;
12181 n = integerValue(cmdline_option_value(argc,argv,++i));
12182 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12183 n = 0xffffffffffffLL/sz;
12185 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12186 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12187 data.shellFlgs |= SHFLG_Pagecache;
12188 }else if( strcmp(z,"-lookaside")==0 ){
12189 int n, sz;
12190 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12191 if( sz<0 ) sz = 0;
12192 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12193 if( n<0 ) n = 0;
12194 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12195 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12196 }else if( strcmp(z,"-threadsafe")==0 ){
12197 int n;
12198 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12199 switch( n ){
12200 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
12201 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
12202 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
12204 #ifdef SQLITE_ENABLE_VFSTRACE
12205 }else if( strcmp(z,"-vfstrace")==0 ){
12206 extern int vfstrace_register(
12207 const char *zTraceName,
12208 const char *zOldVfsName,
12209 int (*xOut)(const char*,void*),
12210 void *pOutArg,
12211 int makeDefault
12213 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12214 #endif
12215 #ifdef SQLITE_ENABLE_MULTIPLEX
12216 }else if( strcmp(z,"-multiplex")==0 ){
12217 extern int sqlite3_multiple_initialize(const char*,int);
12218 sqlite3_multiplex_initialize(0, 1);
12219 #endif
12220 }else if( strcmp(z,"-mmap")==0 ){
12221 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12222 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12223 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12224 }else if( strcmp(z,"-sorterref")==0 ){
12225 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12226 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12227 #endif
12228 }else if( strcmp(z,"-vfs")==0 ){
12229 zVfs = cmdline_option_value(argc, argv, ++i);
12230 #ifdef SQLITE_HAVE_ZLIB
12231 }else if( strcmp(z,"-zip")==0 ){
12232 data.openMode = SHELL_OPEN_ZIPFILE;
12233 #endif
12234 }else if( strcmp(z,"-append")==0 ){
12235 data.openMode = SHELL_OPEN_APPENDVFS;
12236 #ifndef SQLITE_OMIT_DESERIALIZE
12237 }else if( strcmp(z,"-deserialize")==0 ){
12238 data.openMode = SHELL_OPEN_DESERIALIZE;
12239 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12240 data.szMax = integerValue(argv[++i]);
12241 #endif
12242 }else if( strcmp(z,"-readonly")==0 ){
12243 data.openMode = SHELL_OPEN_READONLY;
12244 }else if( strcmp(z,"-nofollow")==0 ){
12245 data.openFlags = SQLITE_OPEN_NOFOLLOW;
12246 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12247 }else if( strncmp(z, "-A",2)==0 ){
12248 /* All remaining command-line arguments are passed to the ".archive"
12249 ** command, so ignore them */
12250 break;
12251 #endif
12252 }else if( strcmp(z, "-memtrace")==0 ){
12253 sqlite3MemTraceActivate(stderr);
12254 }else if( strcmp(z,"-bail")==0 ){
12255 bail_on_error = 1;
12256 }else if( strcmp(z,"-nonce")==0 ){
12257 free(data.zNonce);
12258 data.zNonce = strdup(argv[++i]);
12259 }else if( strcmp(z,"-safe")==0 ){
12260 /* no-op - catch this on the second pass */
12263 verify_uninitialized();
12266 #ifdef SQLITE_SHELL_INIT_PROC
12268 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12269 ** of a C-function that will perform initialization actions on SQLite that
12270 ** occur just before or after sqlite3_initialize(). Use this compile-time
12271 ** option to embed this shell program in larger applications. */
12272 extern void SQLITE_SHELL_INIT_PROC(void);
12273 SQLITE_SHELL_INIT_PROC();
12275 #else
12276 /* All the sqlite3_config() calls have now been made. So it is safe
12277 ** to call sqlite3_initialize() and process any command line -vfs option. */
12278 sqlite3_initialize();
12279 #endif
12281 if( zVfs ){
12282 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12283 if( pVfs ){
12284 sqlite3_vfs_register(pVfs, 1);
12285 }else{
12286 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12287 exit(1);
12291 if( data.pAuxDb->zDbFilename==0 ){
12292 #ifndef SQLITE_OMIT_MEMORYDB
12293 data.pAuxDb->zDbFilename = ":memory:";
12294 warnInmemoryDb = argc==1;
12295 #else
12296 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12297 return 1;
12298 #endif
12300 data.out = stdout;
12301 #ifndef SQLITE_SHELL_WASM_MODE
12302 sqlite3_appendvfs_init(0,0,0);
12303 #endif
12305 /* Go ahead and open the database file if it already exists. If the
12306 ** file does not exist, delay opening it. This prevents empty database
12307 ** files from being created if a user mistypes the database name argument
12308 ** to the sqlite command-line tool.
12310 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12311 open_db(&data, 0);
12314 /* Process the initialization file if there is one. If no -init option
12315 ** is given on the command line, look for a file named ~/.sqliterc and
12316 ** try to process it.
12318 process_sqliterc(&data,zInitFile);
12320 /* Make a second pass through the command-line argument and set
12321 ** options. This second pass is delayed until after the initialization
12322 ** file is processed so that the command-line arguments will override
12323 ** settings in the initialization file.
12325 for(i=1; i<argc; i++){
12326 char *z = argv[i];
12327 if( z[0]!='-' ) continue;
12328 if( z[1]=='-' ){ z++; }
12329 if( strcmp(z,"-init")==0 ){
12330 i++;
12331 }else if( strcmp(z,"-html")==0 ){
12332 data.mode = MODE_Html;
12333 }else if( strcmp(z,"-list")==0 ){
12334 data.mode = MODE_List;
12335 }else if( strcmp(z,"-quote")==0 ){
12336 data.mode = MODE_Quote;
12337 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12338 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12339 }else if( strcmp(z,"-line")==0 ){
12340 data.mode = MODE_Line;
12341 }else if( strcmp(z,"-column")==0 ){
12342 data.mode = MODE_Column;
12343 }else if( strcmp(z,"-json")==0 ){
12344 data.mode = MODE_Json;
12345 }else if( strcmp(z,"-markdown")==0 ){
12346 data.mode = MODE_Markdown;
12347 }else if( strcmp(z,"-table")==0 ){
12348 data.mode = MODE_Table;
12349 }else if( strcmp(z,"-box")==0 ){
12350 data.mode = MODE_Box;
12351 }else if( strcmp(z,"-csv")==0 ){
12352 data.mode = MODE_Csv;
12353 memcpy(data.colSeparator,",",2);
12354 #ifdef SQLITE_HAVE_ZLIB
12355 }else if( strcmp(z,"-zip")==0 ){
12356 data.openMode = SHELL_OPEN_ZIPFILE;
12357 #endif
12358 }else if( strcmp(z,"-append")==0 ){
12359 data.openMode = SHELL_OPEN_APPENDVFS;
12360 #ifndef SQLITE_OMIT_DESERIALIZE
12361 }else if( strcmp(z,"-deserialize")==0 ){
12362 data.openMode = SHELL_OPEN_DESERIALIZE;
12363 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12364 data.szMax = integerValue(argv[++i]);
12365 #endif
12366 }else if( strcmp(z,"-readonly")==0 ){
12367 data.openMode = SHELL_OPEN_READONLY;
12368 }else if( strcmp(z,"-nofollow")==0 ){
12369 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12370 }else if( strcmp(z,"-ascii")==0 ){
12371 data.mode = MODE_Ascii;
12372 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12373 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12374 }else if( strcmp(z,"-tabs")==0 ){
12375 data.mode = MODE_List;
12376 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12377 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12378 }else if( strcmp(z,"-separator")==0 ){
12379 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12380 "%s",cmdline_option_value(argc,argv,++i));
12381 }else if( strcmp(z,"-newline")==0 ){
12382 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12383 "%s",cmdline_option_value(argc,argv,++i));
12384 }else if( strcmp(z,"-nullvalue")==0 ){
12385 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12386 "%s",cmdline_option_value(argc,argv,++i));
12387 }else if( strcmp(z,"-header")==0 ){
12388 data.showHeader = 1;
12389 ShellSetFlag(&data, SHFLG_HeaderSet);
12390 }else if( strcmp(z,"-noheader")==0 ){
12391 data.showHeader = 0;
12392 ShellSetFlag(&data, SHFLG_HeaderSet);
12393 }else if( strcmp(z,"-echo")==0 ){
12394 ShellSetFlag(&data, SHFLG_Echo);
12395 }else if( strcmp(z,"-eqp")==0 ){
12396 data.autoEQP = AUTOEQP_on;
12397 }else if( strcmp(z,"-eqpfull")==0 ){
12398 data.autoEQP = AUTOEQP_full;
12399 }else if( strcmp(z,"-stats")==0 ){
12400 data.statsOn = 1;
12401 }else if( strcmp(z,"-scanstats")==0 ){
12402 data.scanstatsOn = 1;
12403 }else if( strcmp(z,"-backslash")==0 ){
12404 /* Undocumented command-line option: -backslash
12405 ** Causes C-style backslash escapes to be evaluated in SQL statements
12406 ** prior to sending the SQL into SQLite. Useful for injecting
12407 ** crazy bytes in the middle of SQL statements for testing and debugging.
12409 ShellSetFlag(&data, SHFLG_Backslash);
12410 }else if( strcmp(z,"-bail")==0 ){
12411 /* No-op. The bail_on_error flag should already be set. */
12412 }else if( strcmp(z,"-version")==0 ){
12413 /* BEGIN SQLCIPHER */
12414 #ifdef SQLITE_HAS_CODEC
12415 extern char* sqlcipher_version();
12416 char *sqlcipher_ver = sqlcipher_version();
12417 printf("%s %s", sqlite3_libversion(), sqlite3_sourceid());
12418 printf(" (SQLCipher %s)\n", sqlcipher_ver);
12419 sqlite3_free(sqlcipher_ver);
12420 #else
12421 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12422 #endif
12423 /* END SQLCIPHER */
12424 return 0;
12425 }else if( strcmp(z,"-interactive")==0 ){
12426 stdin_is_interactive = 1;
12427 }else if( strcmp(z,"-batch")==0 ){
12428 stdin_is_interactive = 0;
12429 }else if( strcmp(z,"-heap")==0 ){
12430 i++;
12431 }else if( strcmp(z,"-pagecache")==0 ){
12432 i+=2;
12433 }else if( strcmp(z,"-lookaside")==0 ){
12434 i+=2;
12435 }else if( strcmp(z,"-threadsafe")==0 ){
12436 i+=2;
12437 }else if( strcmp(z,"-nonce")==0 ){
12438 i += 2;
12439 }else if( strcmp(z,"-mmap")==0 ){
12440 i++;
12441 }else if( strcmp(z,"-memtrace")==0 ){
12442 i++;
12443 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12444 }else if( strcmp(z,"-sorterref")==0 ){
12445 i++;
12446 #endif
12447 }else if( strcmp(z,"-vfs")==0 ){
12448 i++;
12449 #ifdef SQLITE_ENABLE_VFSTRACE
12450 }else if( strcmp(z,"-vfstrace")==0 ){
12451 i++;
12452 #endif
12453 #ifdef SQLITE_ENABLE_MULTIPLEX
12454 }else if( strcmp(z,"-multiplex")==0 ){
12455 i++;
12456 #endif
12457 }else if( strcmp(z,"-help")==0 ){
12458 usage(1);
12459 }else if( strcmp(z,"-cmd")==0 ){
12460 /* Run commands that follow -cmd first and separately from commands
12461 ** that simply appear on the command-line. This seems goofy. It would
12462 ** be better if all commands ran in the order that they appear. But
12463 ** we retain the goofy behavior for historical compatibility. */
12464 if( i==argc-1 ) break;
12465 z = cmdline_option_value(argc,argv,++i);
12466 if( z[0]=='.' ){
12467 rc = do_meta_command(z, &data);
12468 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12469 }else{
12470 open_db(&data, 0);
12471 rc = shell_exec(&data, z, &zErrMsg);
12472 if( zErrMsg!=0 ){
12473 utf8_printf(stderr,"Error: %s\n", zErrMsg);
12474 if( bail_on_error ) return rc!=0 ? rc : 1;
12475 }else if( rc!=0 ){
12476 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12477 if( bail_on_error ) return rc;
12480 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12481 }else if( strncmp(z, "-A", 2)==0 ){
12482 if( nCmd>0 ){
12483 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12484 " with \"%s\"\n", z);
12485 return 1;
12487 open_db(&data, OPEN_DB_ZIPFILE);
12488 if( z[2] ){
12489 argv[i] = &z[2];
12490 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12491 }else{
12492 arDotCommand(&data, 1, argv+i, argc-i);
12494 readStdin = 0;
12495 break;
12496 #endif
12497 }else if( strcmp(z,"-safe")==0 ){
12498 data.bSafeMode = data.bSafeModePersist = 1;
12499 }else{
12500 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12501 raw_printf(stderr,"Use -help for a list of options.\n");
12502 return 1;
12504 data.cMode = data.mode;
12507 if( !readStdin ){
12508 /* Run all arguments that do not begin with '-' as if they were separate
12509 ** command-line inputs, except for the argToSkip argument which contains
12510 ** the database filename.
12512 for(i=0; i<nCmd; i++){
12513 if( azCmd[i][0]=='.' ){
12514 rc = do_meta_command(azCmd[i], &data);
12515 if( rc ){
12516 free(azCmd);
12517 return rc==2 ? 0 : rc;
12519 }else{
12520 open_db(&data, 0);
12521 rc = shell_exec(&data, azCmd[i], &zErrMsg);
12522 if( zErrMsg || rc ){
12523 if( zErrMsg!=0 ){
12524 utf8_printf(stderr,"Error: %s\n", zErrMsg);
12525 }else{
12526 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12528 sqlite3_free(zErrMsg);
12529 free(azCmd);
12530 return rc!=0 ? rc : 1;
12534 }else{
12535 /* Run commands received from standard input
12537 if( stdin_is_interactive ){
12538 char *zHome;
12539 char *zHistory;
12540 int nHistory;
12541 /* BEGIN SQLCIPHER */
12542 #ifdef SQLITE_HAS_CODEC
12543 extern char* sqlcipher_version();
12544 char *sqlcipher_ver = sqlcipher_version();
12545 printf(
12546 "SQLite version %s %.19s" /*extra-version-info*/
12547 " (SQLCipher %s)\n" /*sqlcipher version info*/
12548 "Enter \".help\" for usage hints.\n",
12549 sqlite3_libversion(), sqlite3_sourceid(), sqlcipher_ver
12551 sqlite3_free(sqlcipher_ver);
12552 #else
12553 printf(
12554 "SQLite version %s %.19s\n" /*extra-version-info*/
12555 "Enter \".help\" for usage hints.\n",
12556 sqlite3_libversion(), sqlite3_sourceid()
12558 #endif
12559 /* END SQLCIPHER */
12560 if( warnInmemoryDb ){
12561 printf("Connected to a ");
12562 printBold("transient in-memory database");
12563 printf(".\nUse \".open FILENAME\" to reopen on a "
12564 "persistent database.\n");
12566 zHistory = getenv("SQLITE_HISTORY");
12567 if( zHistory ){
12568 zHistory = strdup(zHistory);
12569 }else if( (zHome = find_home_dir(0))!=0 ){
12570 nHistory = strlen30(zHome) + 20;
12571 if( (zHistory = malloc(nHistory))!=0 ){
12572 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12575 if( zHistory ){ shell_read_history(zHistory); }
12576 #if HAVE_READLINE || HAVE_EDITLINE
12577 rl_attempted_completion_function = readline_completion;
12578 #elif HAVE_LINENOISE
12579 linenoiseSetCompletionCallback(linenoise_completion);
12580 #endif
12581 data.in = 0;
12582 rc = process_input(&data);
12583 if( zHistory ){
12584 shell_stifle_history(2000);
12585 shell_write_history(zHistory);
12586 free(zHistory);
12588 }else{
12589 data.in = stdin;
12590 rc = process_input(&data);
12593 #ifndef SQLITE_SHELL_WASM_MODE
12594 /* In WASM mode we have to leave the db state in place so that
12595 ** client code can "push" SQL into it after this call returns. */
12596 free(azCmd);
12597 set_table_name(&data, 0);
12598 if( data.db ){
12599 session_close_all(&data, -1);
12600 close_db(data.db);
12602 for(i=0; i<ArraySize(data.aAuxDb); i++){
12603 sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12604 if( data.aAuxDb[i].db ){
12605 session_close_all(&data, i);
12606 close_db(data.aAuxDb[i].db);
12609 find_home_dir(1);
12610 output_reset(&data);
12611 data.doXdgOpen = 0;
12612 clearTempFile(&data);
12613 #if !SQLITE_SHELL_IS_UTF8
12614 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12615 free(argvToFree);
12616 #endif
12617 free(data.colWidth);
12618 free(data.zNonce);
12619 /* Clear the global data structure so that valgrind will detect memory
12620 ** leaks */
12621 memset(&data, 0, sizeof(data));
12622 #ifdef SQLITE_DEBUG
12623 if( sqlite3_memory_used()>mem_main_enter ){
12624 utf8_printf(stderr, "Memory leaked: %u bytes\n",
12625 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12627 #endif
12628 #endif /* !SQLITE_SHELL_WASM_MODE */
12629 return rc;
12633 #ifdef SQLITE_SHELL_WASM_MODE
12634 /* Only for emcc experimentation purposes. */
12635 int fiddle_experiment(int a,int b){
12636 return a + b;
12639 /* Only for emcc experimentation purposes.
12641 Define this function in JS using:
12643 emcc ... --js-library somefile.js
12645 containing:
12647 mergeInto(LibraryManager.library, {
12648 my_foo: function(){
12649 console.debug("my_foo()",arguments);
12653 /*extern void my_foo(sqlite3 *);*/
12654 /* Only for emcc experimentation purposes. */
12655 sqlite3 * fiddle_the_db(){
12656 printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12657 /*my_foo(globalDb);*/
12658 return globalDb;
12660 /* Only for emcc experimentation purposes. */
12661 sqlite3 * fiddle_db_arg(sqlite3 *arg){
12662 printf("fiddle_db_arg(%p)\n", (const void*)arg);
12663 return arg;
12667 ** Intended to be called via a SharedWorker() while a separate
12668 ** SharedWorker() (which manages the wasm module) is performing work
12669 ** which should be interrupted. Unfortunately, SharedWorker is not
12670 ** portable enough to make real use of.
12672 void fiddle_interrupt(void){
12673 if(globalDb) sqlite3_interrupt(globalDb);
12677 ** Returns the filename of the given db name, assuming "main" if
12678 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12680 const char * fiddle_db_filename(const char * zDbName){
12681 return globalDb
12682 ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12683 : NULL;
12687 ** Closes, unlinks, and reopens the db using its current filename (or
12688 ** the default if the db is currently closed). It is assumed, for
12689 ** purposes of the fiddle build, that the file is in a transient
12690 ** virtual filesystem within the browser.
12692 void fiddle_reset_db(void){
12693 char *zFilename = 0;
12694 if(0==globalDb){
12695 shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12696 }else{
12697 zFilename =
12698 sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12699 shell_check_oom(zFilename);
12700 close_db(globalDb);
12701 shellDeleteFile(zFilename);
12702 shellState.db = 0;
12703 shellState.pAuxDb->zDbFilename = zFilename;
12705 open_db(&shellState, 0);
12706 sqlite3_free(zFilename);
12710 ** Trivial exportable function for emscripten. Needs to be exported using:
12712 ** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12714 ** (Note the underscore before the function name.) It processes zSql
12715 ** as if it were input to the sqlite3 shell and redirects all output
12716 ** to the wasm binding.
12718 void fiddle_exec(const char * zSql){
12719 static int once = 0;
12720 int rc = 0;
12721 if(!once){
12722 /* Simulate an argv array for main() */
12723 static char * argv[] = {"fiddle",
12724 "-bail",
12725 "-safe"};
12726 rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12727 once = rc ? -1 : 1;
12728 memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12729 printf(
12730 "SQLite version %s %.19s\n" /*extra-version-info*/,
12731 sqlite3_libversion(), sqlite3_sourceid()
12733 puts("WASM shell");
12734 puts("Enter \".help\" for usage hints.");
12735 if(once>0){
12736 fiddle_reset_db();
12738 if(shellState.db){
12739 printf("Connected to %s.\n", fiddle_db_filename(NULL));
12740 }else{
12741 fprintf(stderr,"ERROR initializing db!\n");
12742 return;
12745 if(once<0){
12746 puts("DB init failed. Not executing SQL.");
12747 }else if(zSql && *zSql){
12748 shellState.wasm.zInput = zSql;
12749 shellState.wasm.zPos = zSql;
12750 process_input(&shellState);
12751 memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12754 #endif /* SQLITE_SHELL_WASM_MODE */