Reformulate [34439fe3aeea7cbb] slightly to resolve a false-positive OOM reported...
[sqlite.git] / src / shell.c.in
blob1d7f8df450baae4f1722498b3c9ec2cdae980288
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
19 typedef unsigned int u32;
20 typedef unsigned short int u16;
23 ** Optionally #include a user-defined header, whereby compilation options
24 ** may be set prior to where they take effect, but after platform setup.
25 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
26 ** file. Note that this macro has a like effect on sqlite3.c compilation.
28 # define SHELL_STRINGIFY_(f) #f
29 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
30 #ifdef SQLITE_CUSTOM_INCLUDE
31 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
32 #endif
35 ** Determine if we are dealing with WinRT, which provides only a subset of
36 ** the full Win32 API.
38 #if !defined(SQLITE_OS_WINRT)
39 # define SQLITE_OS_WINRT 0
40 #endif
43 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
44 ** somewhat for use as a WASM module in a web browser. This flag
45 ** should only be used when building the "fiddle" web application, as
46 ** the browser-mode build has much different user input requirements
47 ** and this build mode rewires the user input subsystem to account for
48 ** that.
52 ** Warning pragmas copied from msvc.h in the core.
54 #if defined(_MSC_VER)
55 #pragma warning(disable : 4054)
56 #pragma warning(disable : 4055)
57 #pragma warning(disable : 4100)
58 #pragma warning(disable : 4127)
59 #pragma warning(disable : 4130)
60 #pragma warning(disable : 4152)
61 #pragma warning(disable : 4189)
62 #pragma warning(disable : 4206)
63 #pragma warning(disable : 4210)
64 #pragma warning(disable : 4232)
65 #pragma warning(disable : 4244)
66 #pragma warning(disable : 4305)
67 #pragma warning(disable : 4306)
68 #pragma warning(disable : 4702)
69 #pragma warning(disable : 4706)
70 #endif /* defined(_MSC_VER) */
73 ** No support for loadable extensions in VxWorks.
75 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
76 # define SQLITE_OMIT_LOAD_EXTENSION 1
77 #endif
80 ** Enable large-file support for fopen() and friends on unix.
82 #ifndef SQLITE_DISABLE_LFS
83 # define _LARGE_FILE 1
84 # ifndef _FILE_OFFSET_BITS
85 # define _FILE_OFFSET_BITS 64
86 # endif
87 # define _LARGEFILE_SOURCE 1
88 #endif
90 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
92 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
93 ** to expose strdup().
95 # define _POSIX_SOURCE
96 #endif
98 #include <stdlib.h>
99 #include <string.h>
100 #include <stdio.h>
101 #include <assert.h>
102 #include <math.h>
103 #include "sqlite3.h"
104 typedef sqlite3_int64 i64;
105 typedef sqlite3_uint64 u64;
106 typedef unsigned char u8;
107 #if SQLITE_USER_AUTHENTICATION
108 # include "sqlite3userauth.h"
109 #endif
110 #include <ctype.h>
111 #include <stdarg.h>
113 #if !defined(_WIN32) && !defined(WIN32)
114 # include <signal.h>
115 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
116 # include <pwd.h>
117 # endif
118 #endif
119 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
120 # include <unistd.h>
121 # include <dirent.h>
122 # define GETPID getpid
123 # if defined(__MINGW32__)
124 # define DIRENT dirent
125 # ifndef S_ISLNK
126 # define S_ISLNK(mode) (0)
127 # endif
128 # endif
129 #else
130 # define GETPID (int)GetCurrentProcessId
131 #endif
132 #include <sys/types.h>
133 #include <sys/stat.h>
135 #if HAVE_READLINE
136 # include <readline/readline.h>
137 # include <readline/history.h>
138 #endif
140 #if HAVE_EDITLINE
141 # include <editline/readline.h>
142 #endif
144 #if HAVE_EDITLINE || HAVE_READLINE
146 # define shell_add_history(X) add_history(X)
147 # define shell_read_history(X) read_history(X)
148 # define shell_write_history(X) write_history(X)
149 # define shell_stifle_history(X) stifle_history(X)
150 # define shell_readline(X) readline(X)
152 #elif HAVE_LINENOISE
154 # include "linenoise.h"
155 # define shell_add_history(X) linenoiseHistoryAdd(X)
156 # define shell_read_history(X) linenoiseHistoryLoad(X)
157 # define shell_write_history(X) linenoiseHistorySave(X)
158 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
159 # define shell_readline(X) linenoise(X)
161 #else
163 # define shell_read_history(X)
164 # define shell_write_history(X)
165 # define shell_stifle_history(X)
167 # define SHELL_USE_LOCAL_GETLINE 1
168 #endif
170 #ifndef deliberate_fall_through
171 /* Quiet some compilers about some of our intentional code. */
172 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
173 # define deliberate_fall_through __attribute__((fallthrough));
174 # else
175 # define deliberate_fall_through
176 # endif
177 #endif
179 #if defined(_WIN32) || defined(WIN32)
180 # if SQLITE_OS_WINRT
181 # define SQLITE_OMIT_POPEN 1
182 # else
183 # include <io.h>
184 # include <fcntl.h>
185 # define isatty(h) _isatty(h)
186 # ifndef access
187 # define access(f,m) _access((f),(m))
188 # endif
189 # ifndef unlink
190 # define unlink _unlink
191 # endif
192 # ifndef strdup
193 # define strdup _strdup
194 # endif
195 # undef popen
196 # define popen _popen
197 # undef pclose
198 # define pclose _pclose
199 # endif
200 #else
201 /* Make sure isatty() has a prototype. */
202 extern int isatty(int);
204 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
205 /* popen and pclose are not C89 functions and so are
206 ** sometimes omitted from the <stdio.h> header */
207 extern FILE *popen(const char*,const char*);
208 extern int pclose(FILE*);
209 # else
210 # define SQLITE_OMIT_POPEN 1
211 # endif
212 #endif
214 #if defined(_WIN32_WCE)
215 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
216 * thus we always assume that we have a console. That can be
217 * overridden with the -batch command line option.
219 #define isatty(x) 1
220 #endif
222 /* ctype macros that work with signed characters */
223 #define IsSpace(X) isspace((unsigned char)X)
224 #define IsDigit(X) isdigit((unsigned char)X)
225 #define ToLower(X) (char)tolower((unsigned char)X)
227 #if defined(_WIN32) || defined(WIN32)
228 #if SQLITE_OS_WINRT
229 #include <intrin.h>
230 #endif
231 #undef WIN32_LEAN_AND_MEAN
232 #define WIN32_LEAN_AND_MEAN
233 #include <windows.h>
235 /* string conversion routines only needed on Win32 */
236 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
237 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
238 #endif
240 /* Use console I/O package as a direct INCLUDE. */
241 #define SQLITE_INTERNAL_LINKAGE static
243 #ifdef SQLITE_SHELL_FIDDLE
244 /* Deselect most features from the console I/O package for Fiddle. */
245 # define SQLITE_CIO_NO_REDIRECT
246 # define SQLITE_CIO_NO_CLASSIFY
247 # define SQLITE_CIO_NO_TRANSLATE
248 # define SQLITE_CIO_NO_SETMODE
249 #endif
250 INCLUDE ../ext/consio/console_io.h
251 INCLUDE ../ext/consio/console_io.c
253 #ifndef SQLITE_SHELL_FIDDLE
255 /* From here onward, fgets() is redirected to the console_io library. */
256 # define fgets(b,n,f) fGetsUtf8(b,n,f)
258 * Define macros for emitting output text in various ways:
259 * sputz(s, z) => emit 0-terminated string z to given stream s
260 * sputf(s, f, ...) => emit varargs per format f to given stream s
261 * oputz(z) => emit 0-terminated string z to default stream
262 * oputf(f, ...) => emit varargs per format f to default stream
263 * eputz(z) => emit 0-terminated string z to error stream
264 * eputf(f, ...) => emit varargs per format f to error stream
265 * oputb(b, n) => emit char buffer b[0..n-1] to default stream
267 * Note that the default stream is whatever has been last set via:
268 * setOutputStream(FILE *pf)
269 * This is normally the stream that CLI normal output goes to.
270 * For the stand-alone CLI, it is stdout with no .output redirect.
272 * The ?putz(z) forms are required for the Fiddle builds for string literal
273 * output, in aid of enforcing format string to argument correspondence.
275 # define sputz(s,z) fPutsUtf8(z,s)
276 # define sputf fPrintfUtf8
277 # define oputz(z) oPutsUtf8(z)
278 # define oputf oPrintfUtf8
279 # define eputz(z) ePutsUtf8(z)
280 # define eputf ePrintfUtf8
281 # define oputb(buf,na) oPutbUtf8(buf,na)
283 #else
284 /* For Fiddle, all console handling and emit redirection is omitted. */
285 /* These next 3 macros are for emitting formatted output. When complaints
286 * from the WASM build are issued for non-formatted output, (when a mere
287 * string literal is to be emitted, the ?putz(z) forms should be used.
288 * (This permits compile-time checking of format string / argument mismatch.)
290 # define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
291 # define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
292 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
293 /* These next 3 macros are for emitting simple string literals. */
294 # define oputz(z) fputs(z,stdout)
295 # define eputz(z) fputs(z,stderr)
296 # define sputz(fp,z) fputs(z,fp)
297 # define oputb(buf,na) fwrite(buf,1,na,stdout)
298 #endif
300 /* True if the timer is enabled */
301 static int enableTimer = 0;
303 /* A version of strcmp() that works with NULL values */
304 static int cli_strcmp(const char *a, const char *b){
305 if( a==0 ) a = "";
306 if( b==0 ) b = "";
307 return strcmp(a,b);
309 static int cli_strncmp(const char *a, const char *b, size_t n){
310 if( a==0 ) a = "";
311 if( b==0 ) b = "";
312 return strncmp(a,b,n);
315 /* Return the current wall-clock time */
316 static sqlite3_int64 timeOfDay(void){
317 static sqlite3_vfs *clockVfs = 0;
318 sqlite3_int64 t;
319 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
320 if( clockVfs==0 ) return 0; /* Never actually happens */
321 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
322 clockVfs->xCurrentTimeInt64(clockVfs, &t);
323 }else{
324 double r;
325 clockVfs->xCurrentTime(clockVfs, &r);
326 t = (sqlite3_int64)(r*86400000.0);
328 return t;
331 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
332 #include <sys/time.h>
333 #include <sys/resource.h>
335 /* VxWorks does not support getrusage() as far as we can determine */
336 #if defined(_WRS_KERNEL) || defined(__RTP__)
337 struct rusage {
338 struct timeval ru_utime; /* user CPU time used */
339 struct timeval ru_stime; /* system CPU time used */
341 #define getrusage(A,B) memset(B,0,sizeof(*B))
342 #endif
344 /* Saved resource information for the beginning of an operation */
345 static struct rusage sBegin; /* CPU time at start */
346 static sqlite3_int64 iBegin; /* Wall-clock time at start */
349 ** Begin timing an operation
351 static void beginTimer(void){
352 if( enableTimer ){
353 getrusage(RUSAGE_SELF, &sBegin);
354 iBegin = timeOfDay();
358 /* Return the difference of two time_structs in seconds */
359 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
360 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
361 (double)(pEnd->tv_sec - pStart->tv_sec);
365 ** Print the timing results.
367 static void endTimer(void){
368 if( enableTimer ){
369 sqlite3_int64 iEnd = timeOfDay();
370 struct rusage sEnd;
371 getrusage(RUSAGE_SELF, &sEnd);
372 sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
373 (iEnd - iBegin)*0.001,
374 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
375 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
379 #define BEGIN_TIMER beginTimer()
380 #define END_TIMER endTimer()
381 #define HAS_TIMER 1
383 #elif (defined(_WIN32) || defined(WIN32))
385 /* Saved resource information for the beginning of an operation */
386 static HANDLE hProcess;
387 static FILETIME ftKernelBegin;
388 static FILETIME ftUserBegin;
389 static sqlite3_int64 ftWallBegin;
390 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
391 LPFILETIME, LPFILETIME);
392 static GETPROCTIMES getProcessTimesAddr = NULL;
395 ** Check to see if we have timer support. Return 1 if necessary
396 ** support found (or found previously).
398 static int hasTimer(void){
399 if( getProcessTimesAddr ){
400 return 1;
401 } else {
402 #if !SQLITE_OS_WINRT
403 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
404 ** versions. See if the version we are running on has it, and if it
405 ** does, save off a pointer to it and the current process handle.
407 hProcess = GetCurrentProcess();
408 if( hProcess ){
409 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
410 if( NULL != hinstLib ){
411 getProcessTimesAddr =
412 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
413 if( NULL != getProcessTimesAddr ){
414 return 1;
416 FreeLibrary(hinstLib);
419 #endif
421 return 0;
425 ** Begin timing an operation
427 static void beginTimer(void){
428 if( enableTimer && getProcessTimesAddr ){
429 FILETIME ftCreation, ftExit;
430 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
431 &ftKernelBegin,&ftUserBegin);
432 ftWallBegin = timeOfDay();
436 /* Return the difference of two FILETIME structs in seconds */
437 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
438 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
439 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
440 return (double) ((i64End - i64Start) / 10000000.0);
444 ** Print the timing results.
446 static void endTimer(void){
447 if( enableTimer && getProcessTimesAddr){
448 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
449 sqlite3_int64 ftWallEnd = timeOfDay();
450 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
451 sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
452 (ftWallEnd - ftWallBegin)*0.001,
453 timeDiff(&ftUserBegin, &ftUserEnd),
454 timeDiff(&ftKernelBegin, &ftKernelEnd));
458 #define BEGIN_TIMER beginTimer()
459 #define END_TIMER endTimer()
460 #define HAS_TIMER hasTimer()
462 #else
463 #define BEGIN_TIMER
464 #define END_TIMER
465 #define HAS_TIMER 0
466 #endif
469 ** Used to prevent warnings about unused parameters
471 #define UNUSED_PARAMETER(x) (void)(x)
474 ** Number of elements in an array
476 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
479 ** If the following flag is set, then command execution stops
480 ** at an error if we are not interactive.
482 static int bail_on_error = 0;
485 ** Treat stdin as an interactive input if the following variable
486 ** is true. Otherwise, assume stdin is connected to a file or pipe.
488 static int stdin_is_interactive = 1;
491 ** On Windows systems we need to know if standard output is a console
492 ** in order to show that UTF-16 translation is done in the sign-on
493 ** banner. The following variable is true if it is the console.
495 static int stdout_is_console = 1;
498 ** The following is the open SQLite database. We make a pointer
499 ** to this database a static variable so that it can be accessed
500 ** by the SIGINT handler to interrupt database processing.
502 static sqlite3 *globalDb = 0;
505 ** True if an interrupt (Control-C) has been received.
507 static volatile int seenInterrupt = 0;
510 ** This is the name of our program. It is set in main(), used
511 ** in a number of other places, mostly for error messages.
513 static char *Argv0;
516 ** Prompt strings. Initialized in main. Settable with
517 ** .prompt main continue
519 #define PROMPT_LEN_MAX 20
520 /* First line prompt. default: "sqlite> " */
521 static char mainPrompt[PROMPT_LEN_MAX];
522 /* Continuation prompt. default: " ...> " */
523 static char continuePrompt[PROMPT_LEN_MAX];
525 /* This is variant of the standard-library strncpy() routine with the
526 ** one change that the destination string is always zero-terminated, even
527 ** if there is no zero-terminator in the first n-1 characters of the source
528 ** string.
530 static char *shell_strncpy(char *dest, const char *src, size_t n){
531 size_t i;
532 for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
533 dest[i] = 0;
534 return dest;
538 ** Optionally disable dynamic continuation prompt.
539 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
540 ** or open parentheses level if non-zero, or continuation prompt as set.
541 ** This facility interacts with the scanner and process_input() where the
542 ** below 5 macros are used.
544 #ifdef SQLITE_OMIT_DYNAPROMPT
545 # define CONTINUATION_PROMPT continuePrompt
546 # define CONTINUE_PROMPT_RESET
547 # define CONTINUE_PROMPT_AWAITS(p,s)
548 # define CONTINUE_PROMPT_AWAITC(p,c)
549 # define CONTINUE_PAREN_INCR(p,n)
550 # define CONTINUE_PROMPT_PSTATE 0
551 typedef void *t_NoDynaPrompt;
552 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
553 #else
554 # define CONTINUATION_PROMPT dynamicContinuePrompt()
555 # define CONTINUE_PROMPT_RESET \
556 do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
557 # define CONTINUE_PROMPT_AWAITS(p,s) \
558 if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
559 # define CONTINUE_PROMPT_AWAITC(p,c) \
560 if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
561 # define CONTINUE_PAREN_INCR(p,n) \
562 if(p && stdin_is_interactive) (trackParenLevel(p,n))
563 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
564 typedef struct DynaPrompt *t_DynaPromptRef;
565 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
567 static struct DynaPrompt {
568 char dynamicPrompt[PROMPT_LEN_MAX];
569 char acAwait[2];
570 int inParenLevel;
571 char *zScannerAwaits;
572 } dynPrompt = { {0}, {0}, 0, 0 };
574 /* Record parenthesis nesting level change, or force level to 0. */
575 static void trackParenLevel(struct DynaPrompt *p, int ni){
576 p->inParenLevel += ni;
577 if( ni==0 ) p->inParenLevel = 0;
578 p->zScannerAwaits = 0;
581 /* Record that a lexeme is opened, or closed with args==0. */
582 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
583 if( s!=0 || c==0 ){
584 p->zScannerAwaits = s;
585 p->acAwait[0] = 0;
586 }else{
587 p->acAwait[0] = c;
588 p->zScannerAwaits = p->acAwait;
592 /* Upon demand, derive the continuation prompt to display. */
593 static char *dynamicContinuePrompt(void){
594 if( continuePrompt[0]==0
595 || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
596 return continuePrompt;
597 }else{
598 if( dynPrompt.zScannerAwaits ){
599 size_t ncp = strlen(continuePrompt);
600 size_t ndp = strlen(dynPrompt.zScannerAwaits);
601 if( ndp > ncp-3 ) return continuePrompt;
602 strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
603 while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
604 shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
605 PROMPT_LEN_MAX-4);
606 }else{
607 if( dynPrompt.inParenLevel>9 ){
608 shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
609 }else if( dynPrompt.inParenLevel<0 ){
610 shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
611 }else{
612 shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
613 dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
615 shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
616 PROMPT_LEN_MAX-4);
619 return dynPrompt.dynamicPrompt;
621 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
623 /* Indicate out-of-memory and exit. */
624 static void shell_out_of_memory(void){
625 eputz("Error: out of memory\n");
626 exit(1);
629 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
630 ** out-of-memory error.
632 static void shell_check_oom(const void *p){
633 if( p==0 ) shell_out_of_memory();
637 ** Write I/O traces to the following stream.
639 #ifdef SQLITE_ENABLE_IOTRACE
640 static FILE *iotrace = 0;
641 #endif
644 ** This routine works like printf in that its first argument is a
645 ** format string and subsequent arguments are values to be substituted
646 ** in place of % fields. The result of formatting this string
647 ** is written to iotrace.
649 #ifdef SQLITE_ENABLE_IOTRACE
650 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
651 va_list ap;
652 char *z;
653 if( iotrace==0 ) return;
654 va_start(ap, zFormat);
655 z = sqlite3_vmprintf(zFormat, ap);
656 va_end(ap);
657 sputf(iotrace, "%s", z);
658 sqlite3_free(z);
660 #endif
663 ** Output string zUtf to Out stream as w characters. If w is negative,
664 ** then right-justify the text. W is the width in UTF-8 characters, not
665 ** in bytes. This is different from the %*.*s specification in printf
666 ** since with %*.*s the width is measured in bytes, not characters.
668 static void utf8_width_print(int w, const char *zUtf){
669 int i;
670 int n;
671 int aw = w<0 ? -w : w;
672 if( zUtf==0 ) zUtf = "";
673 for(i=n=0; zUtf[i]; i++){
674 if( (zUtf[i]&0xc0)!=0x80 ){
675 n++;
676 if( n==aw ){
677 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
678 break;
682 if( n>=aw ){
683 oputf("%.*s", i, zUtf);
684 }else if( w<0 ){
685 oputf("%*s%s", aw-n, "", zUtf);
686 }else{
687 oputf("%s%*s", zUtf, aw-n, "");
693 ** Determines if a string is a number of not.
695 static int isNumber(const char *z, int *realnum){
696 if( *z=='-' || *z=='+' ) z++;
697 if( !IsDigit(*z) ){
698 return 0;
700 z++;
701 if( realnum ) *realnum = 0;
702 while( IsDigit(*z) ){ z++; }
703 if( *z=='.' ){
704 z++;
705 if( !IsDigit(*z) ) return 0;
706 while( IsDigit(*z) ){ z++; }
707 if( realnum ) *realnum = 1;
709 if( *z=='e' || *z=='E' ){
710 z++;
711 if( *z=='+' || *z=='-' ) z++;
712 if( !IsDigit(*z) ) return 0;
713 while( IsDigit(*z) ){ z++; }
714 if( realnum ) *realnum = 1;
716 return *z==0;
720 ** Compute a string length that is limited to what can be stored in
721 ** lower 30 bits of a 32-bit signed integer.
723 static int strlen30(const char *z){
724 const char *z2 = z;
725 while( *z2 ){ z2++; }
726 return 0x3fffffff & (int)(z2 - z);
730 ** Return the length of a string in characters. Multibyte UTF8 characters
731 ** count as a single character.
733 static int strlenChar(const char *z){
734 int n = 0;
735 while( *z ){
736 if( (0xc0&*(z++))!=0x80 ) n++;
738 return n;
742 ** Return open FILE * if zFile exists, can be opened for read
743 ** and is an ordinary file or a character stream source.
744 ** Otherwise return 0.
746 static FILE * openChrSource(const char *zFile){
747 #if defined(_WIN32) || defined(WIN32)
748 struct __stat64 x = {0};
749 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
750 /* On Windows, open first, then check the stream nature. This order
751 ** is necessary because _stat() and sibs, when checking a named pipe,
752 ** effectively break the pipe as its supplier sees it. */
753 FILE *rv = fopen(zFile, "rb");
754 if( rv==0 ) return 0;
755 if( _fstat64(_fileno(rv), &x) != 0
756 || !STAT_CHR_SRC(x.st_mode)){
757 fclose(rv);
758 rv = 0;
760 return rv;
761 #else
762 struct stat x = {0};
763 int rc = stat(zFile, &x);
764 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
765 if( rc!=0 ) return 0;
766 if( STAT_CHR_SRC(x.st_mode) ){
767 return fopen(zFile, "rb");
768 }else{
769 return 0;
771 #endif
772 #undef STAT_CHR_SRC
776 ** This routine reads a line of text from FILE in, stores
777 ** the text in memory obtained from malloc() and returns a pointer
778 ** to the text. NULL is returned at end of file, or if malloc()
779 ** fails.
781 ** If zLine is not NULL then it is a malloced buffer returned from
782 ** a previous call to this routine that may be reused.
784 static char *local_getline(char *zLine, FILE *in){
785 int nLine = zLine==0 ? 0 : 100;
786 int n = 0;
788 while( 1 ){
789 if( n+100>nLine ){
790 nLine = nLine*2 + 100;
791 zLine = realloc(zLine, nLine);
792 shell_check_oom(zLine);
794 if( fgets(&zLine[n], nLine - n, in)==0 ){
795 if( n==0 ){
796 free(zLine);
797 return 0;
799 zLine[n] = 0;
800 break;
802 while( zLine[n] ) n++;
803 if( n>0 && zLine[n-1]=='\n' ){
804 n--;
805 if( n>0 && zLine[n-1]=='\r' ) n--;
806 zLine[n] = 0;
807 break;
810 return zLine;
814 ** Retrieve a single line of input text.
816 ** If in==0 then read from standard input and prompt before each line.
817 ** If isContinuation is true, then a continuation prompt is appropriate.
818 ** If isContinuation is zero, then the main prompt should be used.
820 ** If zPrior is not NULL then it is a buffer from a prior call to this
821 ** routine that can be reused.
823 ** The result is stored in space obtained from malloc() and must either
824 ** be freed by the caller or else passed back into this routine via the
825 ** zPrior argument for reuse.
827 #ifndef SQLITE_SHELL_FIDDLE
828 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
829 char *zPrompt;
830 char *zResult;
831 if( in!=0 ){
832 zResult = local_getline(zPrior, in);
833 }else{
834 zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
835 #if SHELL_USE_LOCAL_GETLINE
836 sputz(stdout, zPrompt);
837 fflush(stdout);
839 zResult = local_getline(zPrior, stdin);
840 zPrior = 0;
841 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
842 if( zResult==0 ) sqlite3_sleep(50);
843 }while( zResult==0 && seenInterrupt>0 );
844 #else
845 free(zPrior);
846 zResult = shell_readline(zPrompt);
847 while( zResult==0 ){
848 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
849 sqlite3_sleep(50);
850 if( seenInterrupt==0 ) break;
851 zResult = shell_readline("");
853 if( zResult && *zResult ) shell_add_history(zResult);
854 #endif
856 return zResult;
858 #endif /* !SQLITE_SHELL_FIDDLE */
861 ** Return the value of a hexadecimal digit. Return -1 if the input
862 ** is not a hex digit.
864 static int hexDigitValue(char c){
865 if( c>='0' && c<='9' ) return c - '0';
866 if( c>='a' && c<='f' ) return c - 'a' + 10;
867 if( c>='A' && c<='F' ) return c - 'A' + 10;
868 return -1;
872 ** Interpret zArg as an integer value, possibly with suffixes.
874 static sqlite3_int64 integerValue(const char *zArg){
875 sqlite3_int64 v = 0;
876 static const struct { char *zSuffix; int iMult; } aMult[] = {
877 { "KiB", 1024 },
878 { "MiB", 1024*1024 },
879 { "GiB", 1024*1024*1024 },
880 { "KB", 1000 },
881 { "MB", 1000000 },
882 { "GB", 1000000000 },
883 { "K", 1000 },
884 { "M", 1000000 },
885 { "G", 1000000000 },
887 int i;
888 int isNeg = 0;
889 if( zArg[0]=='-' ){
890 isNeg = 1;
891 zArg++;
892 }else if( zArg[0]=='+' ){
893 zArg++;
895 if( zArg[0]=='0' && zArg[1]=='x' ){
896 int x;
897 zArg += 2;
898 while( (x = hexDigitValue(zArg[0]))>=0 ){
899 v = (v<<4) + x;
900 zArg++;
902 }else{
903 while( IsDigit(zArg[0]) ){
904 v = v*10 + zArg[0] - '0';
905 zArg++;
908 for(i=0; i<ArraySize(aMult); i++){
909 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
910 v *= aMult[i].iMult;
911 break;
914 return isNeg? -v : v;
918 ** A variable length string to which one can append text.
920 typedef struct ShellText ShellText;
921 struct ShellText {
922 char *z;
923 int n;
924 int nAlloc;
928 ** Initialize and destroy a ShellText object
930 static void initText(ShellText *p){
931 memset(p, 0, sizeof(*p));
933 static void freeText(ShellText *p){
934 free(p->z);
935 initText(p);
938 /* zIn is either a pointer to a NULL-terminated string in memory obtained
939 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
940 ** added to zIn, and the result returned in memory obtained from malloc().
941 ** zIn, if it was not NULL, is freed.
943 ** If the third argument, quote, is not '\0', then it is used as a
944 ** quote character for zAppend.
946 static void appendText(ShellText *p, const char *zAppend, char quote){
947 i64 len;
948 i64 i;
949 i64 nAppend = strlen30(zAppend);
951 len = nAppend+p->n+1;
952 if( quote ){
953 len += 2;
954 for(i=0; i<nAppend; i++){
955 if( zAppend[i]==quote ) len++;
959 if( p->z==0 || p->n+len>=p->nAlloc ){
960 p->nAlloc = p->nAlloc*2 + len + 20;
961 p->z = realloc(p->z, p->nAlloc);
962 shell_check_oom(p->z);
965 if( quote ){
966 char *zCsr = p->z+p->n;
967 *zCsr++ = quote;
968 for(i=0; i<nAppend; i++){
969 *zCsr++ = zAppend[i];
970 if( zAppend[i]==quote ) *zCsr++ = quote;
972 *zCsr++ = quote;
973 p->n = (int)(zCsr - p->z);
974 *zCsr = '\0';
975 }else{
976 memcpy(p->z+p->n, zAppend, nAppend);
977 p->n += nAppend;
978 p->z[p->n] = '\0';
983 ** Attempt to determine if identifier zName needs to be quoted, either
984 ** because it contains non-alphanumeric characters, or because it is an
985 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
986 ** that quoting is required.
988 ** Return '"' if quoting is required. Return 0 if no quoting is required.
990 static char quoteChar(const char *zName){
991 int i;
992 if( zName==0 ) return '"';
993 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
994 for(i=0; zName[i]; i++){
995 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
997 return sqlite3_keyword_check(zName, i) ? '"' : 0;
1001 ** Construct a fake object name and column list to describe the structure
1002 ** of the view, virtual table, or table valued function zSchema.zName.
1004 static char *shellFakeSchema(
1005 sqlite3 *db, /* The database connection containing the vtab */
1006 const char *zSchema, /* Schema of the database holding the vtab */
1007 const char *zName /* The name of the virtual table */
1009 sqlite3_stmt *pStmt = 0;
1010 char *zSql;
1011 ShellText s;
1012 char cQuote;
1013 char *zDiv = "(";
1014 int nRow = 0;
1016 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1017 zSchema ? zSchema : "main", zName);
1018 shell_check_oom(zSql);
1019 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1020 sqlite3_free(zSql);
1021 initText(&s);
1022 if( zSchema ){
1023 cQuote = quoteChar(zSchema);
1024 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1025 appendText(&s, zSchema, cQuote);
1026 appendText(&s, ".", 0);
1028 cQuote = quoteChar(zName);
1029 appendText(&s, zName, cQuote);
1030 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1031 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1032 nRow++;
1033 appendText(&s, zDiv, 0);
1034 zDiv = ",";
1035 if( zCol==0 ) zCol = "";
1036 cQuote = quoteChar(zCol);
1037 appendText(&s, zCol, cQuote);
1039 appendText(&s, ")", 0);
1040 sqlite3_finalize(pStmt);
1041 if( nRow==0 ){
1042 freeText(&s);
1043 s.z = 0;
1045 return s.z;
1049 ** SQL function: strtod(X)
1051 ** Use the C-library strtod() function to convert string X into a double.
1052 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1053 ** routines against the C-library.
1055 static void shellStrtod(
1056 sqlite3_context *pCtx,
1057 int nVal,
1058 sqlite3_value **apVal
1060 char *z = (char*)sqlite3_value_text(apVal[0]);
1061 UNUSED_PARAMETER(nVal);
1062 if( z==0 ) return;
1063 sqlite3_result_double(pCtx, strtod(z,0));
1067 ** SQL function: dtostr(X)
1069 ** Use the C-library printf() function to convert real value X into a string.
1070 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1071 ** routines against the C-library.
1073 static void shellDtostr(
1074 sqlite3_context *pCtx,
1075 int nVal,
1076 sqlite3_value **apVal
1078 double r = sqlite3_value_double(apVal[0]);
1079 int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
1080 char z[400];
1081 if( n<1 ) n = 1;
1082 if( n>350 ) n = 350;
1083 sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
1084 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
1089 ** SQL function: shell_module_schema(X)
1091 ** Return a fake schema for the table-valued function or eponymous virtual
1092 ** table X.
1094 static void shellModuleSchema(
1095 sqlite3_context *pCtx,
1096 int nVal,
1097 sqlite3_value **apVal
1099 const char *zName;
1100 char *zFake;
1101 UNUSED_PARAMETER(nVal);
1102 zName = (const char*)sqlite3_value_text(apVal[0]);
1103 zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1104 if( zFake ){
1105 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1106 -1, sqlite3_free);
1107 free(zFake);
1112 ** SQL function: shell_add_schema(S,X)
1114 ** Add the schema name X to the CREATE statement in S and return the result.
1115 ** Examples:
1117 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1119 ** Also works on
1121 ** CREATE INDEX
1122 ** CREATE UNIQUE INDEX
1123 ** CREATE VIEW
1124 ** CREATE TRIGGER
1125 ** CREATE VIRTUAL TABLE
1127 ** This UDF is used by the .schema command to insert the schema name of
1128 ** attached databases into the middle of the sqlite_schema.sql field.
1130 static void shellAddSchemaName(
1131 sqlite3_context *pCtx,
1132 int nVal,
1133 sqlite3_value **apVal
1135 static const char *aPrefix[] = {
1136 "TABLE",
1137 "INDEX",
1138 "UNIQUE INDEX",
1139 "VIEW",
1140 "TRIGGER",
1141 "VIRTUAL TABLE"
1143 int i = 0;
1144 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1145 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1146 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1147 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1148 UNUSED_PARAMETER(nVal);
1149 if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1150 for(i=0; i<ArraySize(aPrefix); i++){
1151 int n = strlen30(aPrefix[i]);
1152 if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1153 char *z = 0;
1154 char *zFake = 0;
1155 if( zSchema ){
1156 char cQuote = quoteChar(zSchema);
1157 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1158 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1159 }else{
1160 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1163 if( zName
1164 && aPrefix[i][0]=='V'
1165 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1167 if( z==0 ){
1168 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1169 }else{
1170 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1172 free(zFake);
1174 if( z ){
1175 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1176 return;
1181 sqlite3_result_value(pCtx, apVal[0]);
1185 ** The source code for several run-time loadable extensions is inserted
1186 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1187 ** code, we need to override some macros to make the included program code
1188 ** work here in the middle of this regular program.
1190 #define SQLITE_EXTENSION_INIT1
1191 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1193 #if defined(_WIN32) && defined(_MSC_VER)
1194 INCLUDE test_windirent.h
1195 INCLUDE test_windirent.c
1196 #define dirent DIRENT
1197 #endif
1198 INCLUDE ../ext/misc/memtrace.c
1199 INCLUDE ../ext/misc/pcachetrace.c
1200 INCLUDE ../ext/misc/shathree.c
1201 INCLUDE ../ext/misc/uint.c
1202 INCLUDE ../ext/misc/decimal.c
1203 #undef sqlite3_base_init
1204 #define sqlite3_base_init sqlite3_base64_init
1205 INCLUDE ../ext/misc/base64.c
1206 #undef sqlite3_base_init
1207 #define sqlite3_base_init sqlite3_base85_init
1208 #define OMIT_BASE85_CHECKER
1209 INCLUDE ../ext/misc/base85.c
1210 INCLUDE ../ext/misc/ieee754.c
1211 INCLUDE ../ext/misc/series.c
1212 INCLUDE ../ext/misc/regexp.c
1213 #ifndef SQLITE_SHELL_FIDDLE
1214 INCLUDE ../ext/misc/fileio.c
1215 INCLUDE ../ext/misc/completion.c
1216 INCLUDE ../ext/misc/appendvfs.c
1217 #endif
1218 #ifdef SQLITE_HAVE_ZLIB
1219 INCLUDE ../ext/misc/zipfile.c
1220 INCLUDE ../ext/misc/sqlar.c
1221 #endif
1222 INCLUDE ../ext/expert/sqlite3expert.h
1223 INCLUDE ../ext/expert/sqlite3expert.c
1225 INCLUDE ../ext/intck/sqlite3intck.h
1226 INCLUDE ../ext/intck/sqlite3intck.c
1228 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1229 #define SQLITE_SHELL_HAVE_RECOVER 1
1230 #else
1231 #define SQLITE_SHELL_HAVE_RECOVER 0
1232 #endif
1233 #if SQLITE_SHELL_HAVE_RECOVER
1234 INCLUDE ../ext/recover/sqlite3recover.h
1235 # ifndef SQLITE_HAVE_SQLITE3R
1236 INCLUDE ../ext/recover/dbdata.c
1237 INCLUDE ../ext/recover/sqlite3recover.c
1238 # endif /* SQLITE_HAVE_SQLITE3R */
1239 #endif
1240 #ifdef SQLITE_SHELL_EXTSRC
1241 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1242 #endif
1244 #if defined(SQLITE_ENABLE_SESSION)
1246 ** State information for a single open session
1248 typedef struct OpenSession OpenSession;
1249 struct OpenSession {
1250 char *zName; /* Symbolic name for this session */
1251 int nFilter; /* Number of xFilter rejection GLOB patterns */
1252 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1253 sqlite3_session *p; /* The open session */
1255 #endif
1257 typedef struct ExpertInfo ExpertInfo;
1258 struct ExpertInfo {
1259 sqlite3expert *pExpert;
1260 int bVerbose;
1263 /* A single line in the EQP output */
1264 typedef struct EQPGraphRow EQPGraphRow;
1265 struct EQPGraphRow {
1266 int iEqpId; /* ID for this row */
1267 int iParentId; /* ID of the parent row */
1268 EQPGraphRow *pNext; /* Next row in sequence */
1269 char zText[1]; /* Text to display for this row */
1272 /* All EQP output is collected into an instance of the following */
1273 typedef struct EQPGraph EQPGraph;
1274 struct EQPGraph {
1275 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1276 EQPGraphRow *pLast; /* Last element of the pRow list */
1277 char zPrefix[100]; /* Graph prefix */
1280 /* Parameters affecting columnar mode result display (defaulting together) */
1281 typedef struct ColModeOpts {
1282 int iWrap; /* In columnar modes, wrap lines reaching this limit */
1283 u8 bQuote; /* Quote results for .mode box and table */
1284 u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
1285 } ColModeOpts;
1286 #define ColModeOpts_default { 60, 0, 0 }
1287 #define ColModeOpts_default_qbox { 60, 1, 0 }
1290 ** State information about the database connection is contained in an
1291 ** instance of the following structure.
1293 typedef struct ShellState ShellState;
1294 struct ShellState {
1295 sqlite3 *db; /* The database */
1296 u8 autoExplain; /* Automatically turn on .explain mode */
1297 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
1298 u8 autoEQPtest; /* autoEQP is in test mode */
1299 u8 autoEQPtrace; /* autoEQP is in trace mode */
1300 u8 scanstatsOn; /* True to display scan stats before each finalize */
1301 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1302 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1303 u8 nEqpLevel; /* Depth of the EQP output graph */
1304 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1305 u8 bSafeMode; /* True to prohibit unsafe operations */
1306 u8 bSafeModePersist; /* The long-term value of bSafeMode */
1307 u8 eRestoreState; /* See comments above doAutoDetectRestore() */
1308 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
1309 unsigned statsOn; /* True to display memory stats before each finalize */
1310 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
1311 int inputNesting; /* Track nesting level of .read and other redirects */
1312 int outCount; /* Revert to stdout when reaching zero */
1313 int cnt; /* Number of records displayed so far */
1314 int lineno; /* Line number of last line read from in */
1315 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1316 FILE *in; /* Read commands from this stream */
1317 FILE *out; /* Write results here */
1318 FILE *traceOut; /* Output for sqlite3_trace() */
1319 int nErr; /* Number of errors seen */
1320 int mode; /* An output mode setting */
1321 int modePrior; /* Saved mode */
1322 int cMode; /* temporary output mode for the current query */
1323 int normalMode; /* Output mode before ".explain on" */
1324 int writableSchema; /* True if PRAGMA writable_schema=ON */
1325 int showHeader; /* True to show column names in List or Column mode */
1326 int nCheck; /* Number of ".check" commands run */
1327 unsigned nProgress; /* Number of progress callbacks encountered */
1328 unsigned mxProgress; /* Maximum progress callbacks before failing */
1329 unsigned flgProgress; /* Flags for the progress callback */
1330 unsigned shellFlgs; /* Various flags */
1331 unsigned priorShFlgs; /* Saved copy of flags */
1332 sqlite3_int64 szMax; /* --maxsize argument to .open */
1333 char *zDestTable; /* Name of destination table when MODE_Insert */
1334 char *zTempFile; /* Temporary file that might need deleting */
1335 char zTestcase[30]; /* Name of current test case */
1336 char colSeparator[20]; /* Column separator character for several modes */
1337 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1338 char colSepPrior[20]; /* Saved column separator */
1339 char rowSepPrior[20]; /* Saved row separator */
1340 int *colWidth; /* Requested width of each column in columnar modes */
1341 int *actualWidth; /* Actual width of each column */
1342 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1343 char nullValue[20]; /* The text to print when a NULL comes back from
1344 ** the database */
1345 char outfile[FILENAME_MAX]; /* Filename for *out */
1346 sqlite3_stmt *pStmt; /* Current statement if any. */
1347 FILE *pLog; /* Write log output here */
1348 struct AuxDb { /* Storage space for auxiliary database connections */
1349 sqlite3 *db; /* Connection pointer */
1350 const char *zDbFilename; /* Filename used to open the connection */
1351 char *zFreeOnClose; /* Free this memory allocation on close */
1352 #if defined(SQLITE_ENABLE_SESSION)
1353 int nSession; /* Number of active sessions */
1354 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1355 #endif
1356 } aAuxDb[5], /* Array of all database connections */
1357 *pAuxDb; /* Currently active database connection */
1358 int *aiIndent; /* Array of indents used in MODE_Explain */
1359 int nIndent; /* Size of array aiIndent[] */
1360 int iIndent; /* Index of current op in aiIndent[] */
1361 char *zNonce; /* Nonce for temporary safe-mode escapes */
1362 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1363 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1364 #ifdef SQLITE_SHELL_FIDDLE
1365 struct {
1366 const char * zInput; /* Input string from wasm/JS proxy */
1367 const char * zPos; /* Cursor pos into zInput */
1368 const char * zDefaultDbName; /* Default name for db file */
1369 } wasm;
1370 #endif
1373 #ifdef SQLITE_SHELL_FIDDLE
1374 static ShellState shellState;
1375 #endif
1378 /* Allowed values for ShellState.autoEQP
1380 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1381 #define AUTOEQP_on 1 /* Automatic EQP is on */
1382 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1383 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1385 /* Allowed values for ShellState.openMode
1387 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1388 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1389 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1390 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1391 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1392 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1393 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1395 /* Allowed values for ShellState.eTraceType
1397 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1398 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1399 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1401 /* Bits in the ShellState.flgProgress variable */
1402 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1403 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
1404 ** callback limit is reached, and for each
1405 ** top-level SQL statement */
1406 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1409 ** These are the allowed shellFlgs values
1411 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1412 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1413 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1414 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1415 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1416 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1417 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1418 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1419 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1420 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1421 #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */
1424 ** Macros for testing and setting shellFlgs
1426 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1427 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1428 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1431 ** These are the allowed modes.
1433 #define MODE_Line 0 /* One column per line. Blank line between records */
1434 #define MODE_Column 1 /* One record per line in neat columns */
1435 #define MODE_List 2 /* One record per line with a separator */
1436 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1437 #define MODE_Html 4 /* Generate an XHTML table */
1438 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1439 #define MODE_Quote 6 /* Quote values as for SQL */
1440 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1441 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1442 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1443 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1444 #define MODE_Pretty 11 /* Pretty-print schemas */
1445 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1446 #define MODE_Json 13 /* Output JSON */
1447 #define MODE_Markdown 14 /* Markdown formatting */
1448 #define MODE_Table 15 /* MySQL-style table formatting */
1449 #define MODE_Box 16 /* Unicode box-drawing characters */
1450 #define MODE_Count 17 /* Output only a count of the rows of output */
1451 #define MODE_Off 18 /* No query output shown */
1452 #define MODE_ScanExp 19 /* Like MODE_Explain, but for ".scanstats vm" */
1454 static const char *modeDescr[] = {
1455 "line",
1456 "column",
1457 "list",
1458 "semi",
1459 "html",
1460 "insert",
1461 "quote",
1462 "tcl",
1463 "csv",
1464 "explain",
1465 "ascii",
1466 "prettyprint",
1467 "eqp",
1468 "json",
1469 "markdown",
1470 "table",
1471 "box",
1472 "count",
1473 "off"
1477 ** These are the column/row/line separators used by the various
1478 ** import/export modes.
1480 #define SEP_Column "|"
1481 #define SEP_Row "\n"
1482 #define SEP_Tab "\t"
1483 #define SEP_Space " "
1484 #define SEP_Comma ","
1485 #define SEP_CrLf "\r\n"
1486 #define SEP_Unit "\x1F"
1487 #define SEP_Record "\x1E"
1490 ** Limit input nesting via .read or any other input redirect.
1491 ** It's not too expensive, so a generous allowance can be made.
1493 #define MAX_INPUT_NESTING 25
1496 ** A callback for the sqlite3_log() interface.
1498 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1499 ShellState *p = (ShellState*)pArg;
1500 if( p->pLog==0 ) return;
1501 sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1502 fflush(p->pLog);
1506 ** SQL function: shell_putsnl(X)
1508 ** Write the text X to the screen (or whatever output is being directed)
1509 ** adding a newline at the end, and then return X.
1511 static void shellPutsFunc(
1512 sqlite3_context *pCtx,
1513 int nVal,
1514 sqlite3_value **apVal
1516 /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
1517 (void)nVal;
1518 oputf("%s\n", sqlite3_value_text(apVal[0]));
1519 sqlite3_result_value(pCtx, apVal[0]);
1523 ** If in safe mode, print an error message described by the arguments
1524 ** and exit immediately.
1526 static void failIfSafeMode(
1527 ShellState *p,
1528 const char *zErrMsg,
1531 if( p->bSafeMode ){
1532 va_list ap;
1533 char *zMsg;
1534 va_start(ap, zErrMsg);
1535 zMsg = sqlite3_vmprintf(zErrMsg, ap);
1536 va_end(ap);
1537 eputf("line %d: %s\n", p->lineno, zMsg);
1538 exit(1);
1543 ** SQL function: edit(VALUE)
1544 ** edit(VALUE,EDITOR)
1546 ** These steps:
1548 ** (1) Write VALUE into a temporary file.
1549 ** (2) Run program EDITOR on that temporary file.
1550 ** (3) Read the temporary file back and return its content as the result.
1551 ** (4) Delete the temporary file
1553 ** If the EDITOR argument is omitted, use the value in the VISUAL
1554 ** environment variable. If still there is no EDITOR, through an error.
1556 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1558 #ifndef SQLITE_NOHAVE_SYSTEM
1559 static void editFunc(
1560 sqlite3_context *context,
1561 int argc,
1562 sqlite3_value **argv
1564 const char *zEditor;
1565 char *zTempFile = 0;
1566 sqlite3 *db;
1567 char *zCmd = 0;
1568 int bBin;
1569 int rc;
1570 int hasCRNL = 0;
1571 FILE *f = 0;
1572 sqlite3_int64 sz;
1573 sqlite3_int64 x;
1574 unsigned char *p = 0;
1576 if( argc==2 ){
1577 zEditor = (const char*)sqlite3_value_text(argv[1]);
1578 }else{
1579 zEditor = getenv("VISUAL");
1581 if( zEditor==0 ){
1582 sqlite3_result_error(context, "no editor for edit()", -1);
1583 return;
1585 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1586 sqlite3_result_error(context, "NULL input to edit()", -1);
1587 return;
1589 db = sqlite3_context_db_handle(context);
1590 zTempFile = 0;
1591 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1592 if( zTempFile==0 ){
1593 sqlite3_uint64 r = 0;
1594 sqlite3_randomness(sizeof(r), &r);
1595 zTempFile = sqlite3_mprintf("temp%llx", r);
1596 if( zTempFile==0 ){
1597 sqlite3_result_error_nomem(context);
1598 return;
1601 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1602 /* When writing the file to be edited, do \n to \r\n conversions on systems
1603 ** that want \r\n line endings */
1604 f = fopen(zTempFile, bBin ? "wb" : "w");
1605 if( f==0 ){
1606 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1607 goto edit_func_end;
1609 sz = sqlite3_value_bytes(argv[0]);
1610 if( bBin ){
1611 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1612 }else{
1613 const char *z = (const char*)sqlite3_value_text(argv[0]);
1614 /* Remember whether or not the value originally contained \r\n */
1615 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1616 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1618 fclose(f);
1619 f = 0;
1620 if( x!=sz ){
1621 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1622 goto edit_func_end;
1624 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1625 if( zCmd==0 ){
1626 sqlite3_result_error_nomem(context);
1627 goto edit_func_end;
1629 rc = system(zCmd);
1630 sqlite3_free(zCmd);
1631 if( rc ){
1632 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1633 goto edit_func_end;
1635 f = fopen(zTempFile, "rb");
1636 if( f==0 ){
1637 sqlite3_result_error(context,
1638 "edit() cannot reopen temp file after edit", -1);
1639 goto edit_func_end;
1641 fseek(f, 0, SEEK_END);
1642 sz = ftell(f);
1643 rewind(f);
1644 p = sqlite3_malloc64( sz+1 );
1645 if( p==0 ){
1646 sqlite3_result_error_nomem(context);
1647 goto edit_func_end;
1649 x = fread(p, 1, (size_t)sz, f);
1650 fclose(f);
1651 f = 0;
1652 if( x!=sz ){
1653 sqlite3_result_error(context, "could not read back the whole file", -1);
1654 goto edit_func_end;
1656 if( bBin ){
1657 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1658 }else{
1659 sqlite3_int64 i, j;
1660 if( hasCRNL ){
1661 /* If the original contains \r\n then do no conversions back to \n */
1662 }else{
1663 /* If the file did not originally contain \r\n then convert any new
1664 ** \r\n back into \n */
1665 p[sz] = 0;
1666 for(i=j=0; i<sz; i++){
1667 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1668 p[j++] = p[i];
1670 sz = j;
1671 p[sz] = 0;
1673 sqlite3_result_text64(context, (const char*)p, sz,
1674 sqlite3_free, SQLITE_UTF8);
1676 p = 0;
1678 edit_func_end:
1679 if( f ) fclose(f);
1680 unlink(zTempFile);
1681 sqlite3_free(zTempFile);
1682 sqlite3_free(p);
1684 #endif /* SQLITE_NOHAVE_SYSTEM */
1687 ** Save or restore the current output mode
1689 static void outputModePush(ShellState *p){
1690 p->modePrior = p->mode;
1691 p->priorShFlgs = p->shellFlgs;
1692 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1693 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1695 static void outputModePop(ShellState *p){
1696 p->mode = p->modePrior;
1697 p->shellFlgs = p->priorShFlgs;
1698 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1699 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1703 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1705 static void output_hex_blob(const void *pBlob, int nBlob){
1706 int i;
1707 unsigned char *aBlob = (unsigned char*)pBlob;
1709 char *zStr = sqlite3_malloc(nBlob*2 + 1);
1710 shell_check_oom(zStr);
1712 for(i=0; i<nBlob; i++){
1713 static const char aHex[] = {
1714 '0', '1', '2', '3', '4', '5', '6', '7',
1715 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1717 zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1718 zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1720 zStr[i*2] = '\0';
1722 oputf("X'%s'", zStr);
1723 sqlite3_free(zStr);
1727 ** Find a string that is not found anywhere in z[]. Return a pointer
1728 ** to that string.
1730 ** Try to use zA and zB first. If both of those are already found in z[]
1731 ** then make up some string and store it in the buffer zBuf.
1733 static const char *unused_string(
1734 const char *z, /* Result must not appear anywhere in z */
1735 const char *zA, const char *zB, /* Try these first */
1736 char *zBuf /* Space to store a generated string */
1738 unsigned i = 0;
1739 if( strstr(z, zA)==0 ) return zA;
1740 if( strstr(z, zB)==0 ) return zB;
1742 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1743 }while( strstr(z,zBuf)!=0 );
1744 return zBuf;
1748 ** Output the given string as a quoted string using SQL quoting conventions.
1750 ** See also: output_quoted_escaped_string()
1752 static void output_quoted_string(const char *z){
1753 int i;
1754 char c;
1755 #ifndef SQLITE_SHELL_FIDDLE
1756 FILE *pfO = setOutputStream(invalidFileStream);
1757 setBinaryMode(pfO, 1);
1758 #endif
1759 if( z==0 ) return;
1760 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1761 if( c==0 ){
1762 oputf("'%s'",z);
1763 }else{
1764 oputz("'");
1765 while( *z ){
1766 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1767 if( c=='\'' ) i++;
1768 if( i ){
1769 oputf("%.*s", i, z);
1770 z += i;
1772 if( c=='\'' ){
1773 oputz("'");
1774 continue;
1776 if( c==0 ){
1777 break;
1779 z++;
1781 oputz("'");
1783 #ifndef SQLITE_SHELL_FIDDLE
1784 setTextMode(pfO, 1);
1785 #else
1786 setTextMode(stdout, 1);
1787 #endif
1791 ** Output the given string as a quoted string using SQL quoting conventions.
1792 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1793 ** get corrupted by end-of-line translation facilities in some operating
1794 ** systems.
1796 ** This is like output_quoted_string() but with the addition of the \r\n
1797 ** escape mechanism.
1799 static void output_quoted_escaped_string(const char *z){
1800 int i;
1801 char c;
1802 #ifndef SQLITE_SHELL_FIDDLE
1803 FILE *pfO = setOutputStream(invalidFileStream);
1804 setBinaryMode(pfO, 1);
1805 #endif
1806 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1807 if( c==0 ){
1808 oputf("'%s'",z);
1809 }else{
1810 const char *zNL = 0;
1811 const char *zCR = 0;
1812 int nNL = 0;
1813 int nCR = 0;
1814 char zBuf1[20], zBuf2[20];
1815 for(i=0; z[i]; i++){
1816 if( z[i]=='\n' ) nNL++;
1817 if( z[i]=='\r' ) nCR++;
1819 if( nNL ){
1820 oputz("replace(");
1821 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1823 if( nCR ){
1824 oputz("replace(");
1825 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1827 oputz("'");
1828 while( *z ){
1829 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1830 if( c=='\'' ) i++;
1831 if( i ){
1832 oputf("%.*s", i, z);
1833 z += i;
1835 if( c=='\'' ){
1836 oputz("'");
1837 continue;
1839 if( c==0 ){
1840 break;
1842 z++;
1843 if( c=='\n' ){
1844 oputz(zNL);
1845 continue;
1847 oputz(zCR);
1849 oputz("'");
1850 if( nCR ){
1851 oputf(",'%s',char(13))", zCR);
1853 if( nNL ){
1854 oputf(",'%s',char(10))", zNL);
1857 #ifndef SQLITE_SHELL_FIDDLE
1858 setTextMode(pfO, 1);
1859 #else
1860 setTextMode(stdout, 1);
1861 #endif
1865 ** Find earliest of chars within s specified in zAny.
1866 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
1868 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
1869 const char *pcFirst = 0;
1870 if( ns == ~(size_t)0 ) ns = strlen(s);
1871 while(*zAny){
1872 const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
1873 if( pc ){
1874 pcFirst = pc;
1875 ns = pcFirst - s;
1877 ++zAny;
1879 return pcFirst;
1882 ** Output the given string as a quoted according to C or TCL quoting rules.
1884 static void output_c_string(const char *z){
1885 char c;
1886 static const char *zq = "\"";
1887 static long ctrlMask = ~0L;
1888 static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
1889 char ace[3] = "\\?";
1890 char cbsSay;
1891 oputz(zq);
1892 while( *z!=0 ){
1893 const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
1894 const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
1895 const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
1896 if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
1897 if( (c = *pcEnd)==0 ) break;
1898 ++pcEnd;
1899 switch( c ){
1900 case '\\': case '"':
1901 cbsSay = (char)c;
1902 break;
1903 case '\t': cbsSay = 't'; break;
1904 case '\n': cbsSay = 'n'; break;
1905 case '\r': cbsSay = 'r'; break;
1906 case '\f': cbsSay = 'f'; break;
1907 default: cbsSay = 0; break;
1909 if( cbsSay ){
1910 ace[1] = cbsSay;
1911 oputz(ace);
1912 }else if( !isprint(c&0xff) ){
1913 oputf("\\%03o", c&0xff);
1914 }else{
1915 ace[1] = (char)c;
1916 oputz(ace+1);
1918 z = pcEnd;
1920 oputz(zq);
1924 ** Output the given string as a quoted according to JSON quoting rules.
1926 static void output_json_string(const char *z, i64 n){
1927 char c;
1928 static const char *zq = "\"";
1929 static long ctrlMask = ~0L;
1930 static const char *zDQBS = "\"\\";
1931 const char *pcLimit;
1932 char ace[3] = "\\?";
1933 char cbsSay;
1935 if( z==0 ) z = "";
1936 pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
1937 oputz(zq);
1938 while( z < pcLimit ){
1939 const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
1940 const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
1941 const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
1942 if( pcEnd > z ){
1943 oputb(z, (int)(pcEnd-z));
1944 z = pcEnd;
1946 if( z >= pcLimit ) break;
1947 c = *(z++);
1948 switch( c ){
1949 case '"': case '\\':
1950 cbsSay = (char)c;
1951 break;
1952 case '\b': cbsSay = 'b'; break;
1953 case '\f': cbsSay = 'f'; break;
1954 case '\n': cbsSay = 'n'; break;
1955 case '\r': cbsSay = 'r'; break;
1956 case '\t': cbsSay = 't'; break;
1957 default: cbsSay = 0; break;
1959 if( cbsSay ){
1960 ace[1] = cbsSay;
1961 oputz(ace);
1962 }else if( c<=0x1f ){
1963 oputf("u%04x", c);
1964 }else{
1965 ace[1] = (char)c;
1966 oputz(ace+1);
1969 oputz(zq);
1973 ** Output the given string with characters that are special to
1974 ** HTML escaped.
1976 static void output_html_string(const char *z){
1977 int i;
1978 if( z==0 ) z = "";
1979 while( *z ){
1980 for(i=0; z[i]
1981 && z[i]!='<'
1982 && z[i]!='&'
1983 && z[i]!='>'
1984 && z[i]!='\"'
1985 && z[i]!='\'';
1986 i++){}
1987 if( i>0 ){
1988 oputf("%.*s",i,z);
1990 if( z[i]=='<' ){
1991 oputz("&lt;");
1992 }else if( z[i]=='&' ){
1993 oputz("&amp;");
1994 }else if( z[i]=='>' ){
1995 oputz("&gt;");
1996 }else if( z[i]=='\"' ){
1997 oputz("&quot;");
1998 }else if( z[i]=='\'' ){
1999 oputz("&#39;");
2000 }else{
2001 break;
2003 z += i + 1;
2008 ** If a field contains any character identified by a 1 in the following
2009 ** array, then the string must be quoted for CSV.
2011 static const char needCsvQuote[] = {
2012 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2013 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2014 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2015 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2016 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2017 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2018 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2019 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2020 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2021 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2022 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2023 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2024 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2025 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2026 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2027 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2031 ** Output a single term of CSV. Actually, p->colSeparator is used for
2032 ** the separator, which may or may not be a comma. p->nullValue is
2033 ** the null value. Strings are quoted if necessary. The separator
2034 ** is only issued if bSep is true.
2036 static void output_csv(ShellState *p, const char *z, int bSep){
2037 if( z==0 ){
2038 oputf("%s",p->nullValue);
2039 }else{
2040 unsigned i;
2041 for(i=0; z[i]; i++){
2042 if( needCsvQuote[((unsigned char*)z)[i]] ){
2043 i = 0;
2044 break;
2047 if( i==0 || strstr(z, p->colSeparator)!=0 ){
2048 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
2049 shell_check_oom(zQuoted);
2050 oputz(zQuoted);
2051 sqlite3_free(zQuoted);
2052 }else{
2053 oputz(z);
2056 if( bSep ){
2057 oputz(p->colSeparator);
2062 ** This routine runs when the user presses Ctrl-C
2064 static void interrupt_handler(int NotUsed){
2065 UNUSED_PARAMETER(NotUsed);
2066 if( ++seenInterrupt>1 ) exit(1);
2067 if( globalDb ) sqlite3_interrupt(globalDb);
2070 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
2072 ** This routine runs for console events (e.g. Ctrl-C) on Win32
2074 static BOOL WINAPI ConsoleCtrlHandler(
2075 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
2077 if( dwCtrlType==CTRL_C_EVENT ){
2078 interrupt_handler(0);
2079 return TRUE;
2081 return FALSE;
2083 #endif
2085 #ifndef SQLITE_OMIT_AUTHORIZATION
2087 ** This authorizer runs in safe mode.
2089 static int safeModeAuth(
2090 void *pClientData,
2091 int op,
2092 const char *zA1,
2093 const char *zA2,
2094 const char *zA3,
2095 const char *zA4
2097 ShellState *p = (ShellState*)pClientData;
2098 static const char *azProhibitedFunctions[] = {
2099 "edit",
2100 "fts3_tokenizer",
2101 "load_extension",
2102 "readfile",
2103 "writefile",
2104 "zipfile",
2105 "zipfile_cds",
2107 UNUSED_PARAMETER(zA1);
2108 UNUSED_PARAMETER(zA3);
2109 UNUSED_PARAMETER(zA4);
2110 switch( op ){
2111 case SQLITE_ATTACH: {
2112 #ifndef SQLITE_SHELL_FIDDLE
2113 /* In WASM builds the filesystem is a virtual sandbox, so
2114 ** there's no harm in using ATTACH. */
2115 failIfSafeMode(p, "cannot run ATTACH in safe mode");
2116 #endif
2117 break;
2119 case SQLITE_FUNCTION: {
2120 int i;
2121 for(i=0; i<ArraySize(azProhibitedFunctions); i++){
2122 if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
2123 failIfSafeMode(p, "cannot use the %s() function in safe mode",
2124 azProhibitedFunctions[i]);
2127 break;
2130 return SQLITE_OK;
2134 ** When the ".auth ON" is set, the following authorizer callback is
2135 ** invoked. It always returns SQLITE_OK.
2137 static int shellAuth(
2138 void *pClientData,
2139 int op,
2140 const char *zA1,
2141 const char *zA2,
2142 const char *zA3,
2143 const char *zA4
2145 ShellState *p = (ShellState*)pClientData;
2146 static const char *azAction[] = { 0,
2147 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2148 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2149 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2150 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2151 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2152 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2153 "PRAGMA", "READ", "SELECT",
2154 "TRANSACTION", "UPDATE", "ATTACH",
2155 "DETACH", "ALTER_TABLE", "REINDEX",
2156 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2157 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2159 int i;
2160 const char *az[4];
2161 az[0] = zA1;
2162 az[1] = zA2;
2163 az[2] = zA3;
2164 az[3] = zA4;
2165 oputf("authorizer: %s", azAction[op]);
2166 for(i=0; i<4; i++){
2167 oputz(" ");
2168 if( az[i] ){
2169 output_c_string(az[i]);
2170 }else{
2171 oputz("NULL");
2174 oputz("\n");
2175 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
2176 return SQLITE_OK;
2178 #endif
2181 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2183 ** This routine converts some CREATE TABLE statements for shadow tables
2184 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2186 ** If the schema statement in z[] contains a start-of-comment and if
2187 ** sqlite3_complete() returns false, try to terminate the comment before
2188 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2190 static void printSchemaLine(const char *z, const char *zTail){
2191 char *zToFree = 0;
2192 if( z==0 ) return;
2193 if( zTail==0 ) return;
2194 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
2195 const char *zOrig = z;
2196 static const char *azTerm[] = { "", "*/", "\n" };
2197 int i;
2198 for(i=0; i<ArraySize(azTerm); i++){
2199 char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
2200 shell_check_oom(zNew);
2201 if( sqlite3_complete(zNew) ){
2202 size_t n = strlen(zNew);
2203 zNew[n-1] = 0;
2204 zToFree = zNew;
2205 z = zNew;
2206 break;
2208 sqlite3_free(zNew);
2211 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
2212 oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
2213 }else{
2214 oputf("%s%s", z, zTail);
2216 sqlite3_free(zToFree);
2218 static void printSchemaLineN(char *z, int n, const char *zTail){
2219 char c = z[n];
2220 z[n] = 0;
2221 printSchemaLine(z, zTail);
2222 z[n] = c;
2226 ** Return true if string z[] has nothing but whitespace and comments to the
2227 ** end of the first line.
2229 static int wsToEol(const char *z){
2230 int i;
2231 for(i=0; z[i]; i++){
2232 if( z[i]=='\n' ) return 1;
2233 if( IsSpace(z[i]) ) continue;
2234 if( z[i]=='-' && z[i+1]=='-' ) return 1;
2235 return 0;
2237 return 1;
2241 ** Add a new entry to the EXPLAIN QUERY PLAN data
2243 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
2244 EQPGraphRow *pNew;
2245 i64 nText;
2246 if( zText==0 ) return;
2247 nText = strlen(zText);
2248 if( p->autoEQPtest ){
2249 oputf("%d,%d,%s\n", iEqpId, p2, zText);
2251 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
2252 shell_check_oom(pNew);
2253 pNew->iEqpId = iEqpId;
2254 pNew->iParentId = p2;
2255 memcpy(pNew->zText, zText, nText+1);
2256 pNew->pNext = 0;
2257 if( p->sGraph.pLast ){
2258 p->sGraph.pLast->pNext = pNew;
2259 }else{
2260 p->sGraph.pRow = pNew;
2262 p->sGraph.pLast = pNew;
2266 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2267 ** in p->sGraph.
2269 static void eqp_reset(ShellState *p){
2270 EQPGraphRow *pRow, *pNext;
2271 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2272 pNext = pRow->pNext;
2273 sqlite3_free(pRow);
2275 memset(&p->sGraph, 0, sizeof(p->sGraph));
2278 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2279 ** pOld, or return the first such line if pOld is NULL
2281 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2282 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2283 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2284 return pRow;
2287 /* Render a single level of the graph that has iEqpId as its parent. Called
2288 ** recursively to render sublevels.
2290 static void eqp_render_level(ShellState *p, int iEqpId){
2291 EQPGraphRow *pRow, *pNext;
2292 i64 n = strlen(p->sGraph.zPrefix);
2293 char *z;
2294 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2295 pNext = eqp_next_row(p, iEqpId, pRow);
2296 z = pRow->zText;
2297 oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
2298 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
2299 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
2300 eqp_render_level(p, pRow->iEqpId);
2301 p->sGraph.zPrefix[n] = 0;
2307 ** Display and reset the EXPLAIN QUERY PLAN data
2309 static void eqp_render(ShellState *p, i64 nCycle){
2310 EQPGraphRow *pRow = p->sGraph.pRow;
2311 if( pRow ){
2312 if( pRow->zText[0]=='-' ){
2313 if( pRow->pNext==0 ){
2314 eqp_reset(p);
2315 return;
2317 oputf("%s\n", pRow->zText+3);
2318 p->sGraph.pRow = pRow->pNext;
2319 sqlite3_free(pRow);
2320 }else if( nCycle>0 ){
2321 oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
2322 }else{
2323 oputz("QUERY PLAN\n");
2325 p->sGraph.zPrefix[0] = 0;
2326 eqp_render_level(p, 0);
2327 eqp_reset(p);
2331 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2333 ** Progress handler callback.
2335 static int progress_handler(void *pClientData) {
2336 ShellState *p = (ShellState*)pClientData;
2337 p->nProgress++;
2338 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2339 oputf("Progress limit reached (%u)\n", p->nProgress);
2340 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2341 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2342 return 1;
2344 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2345 oputf("Progress %u\n", p->nProgress);
2347 return 0;
2349 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2352 ** Print N dashes
2354 static void print_dashes(int N){
2355 const char zDash[] = "--------------------------------------------------";
2356 const int nDash = sizeof(zDash) - 1;
2357 while( N>nDash ){
2358 oputz(zDash);
2359 N -= nDash;
2361 oputf("%.*s", N, zDash);
2365 ** Print a markdown or table-style row separator using ascii-art
2367 static void print_row_separator(
2368 ShellState *p,
2369 int nArg,
2370 const char *zSep
2372 int i;
2373 if( nArg>0 ){
2374 oputz(zSep);
2375 print_dashes(p->actualWidth[0]+2);
2376 for(i=1; i<nArg; i++){
2377 oputz(zSep);
2378 print_dashes(p->actualWidth[i]+2);
2380 oputz(zSep);
2382 oputz("\n");
2386 ** This is the callback routine that the shell
2387 ** invokes for each row of a query result.
2389 static int shell_callback(
2390 void *pArg,
2391 int nArg, /* Number of result columns */
2392 char **azArg, /* Text of each result column */
2393 char **azCol, /* Column names */
2394 int *aiType /* Column types. Might be NULL */
2396 int i;
2397 ShellState *p = (ShellState*)pArg;
2399 if( azArg==0 ) return 0;
2400 switch( p->cMode ){
2401 case MODE_Count:
2402 case MODE_Off: {
2403 break;
2405 case MODE_Line: {
2406 int w = 5;
2407 if( azArg==0 ) break;
2408 for(i=0; i<nArg; i++){
2409 int len = strlen30(azCol[i] ? azCol[i] : "");
2410 if( len>w ) w = len;
2412 if( p->cnt++>0 ) oputz(p->rowSeparator);
2413 for(i=0; i<nArg; i++){
2414 oputf("%*s = %s%s", w, azCol[i],
2415 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2417 break;
2419 case MODE_ScanExp:
2420 case MODE_Explain: {
2421 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2422 static const int aExplainMap[] = {0, 1, 2, 3, 4, 5, 6, 7 };
2423 static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
2424 static const int aScanExpMap[] = {0, 9, 8, 1, 2, 3, 4, 5, 6, 7 };
2426 const int *aWidth = aExplainWidth;
2427 const int *aMap = aExplainMap;
2428 int nWidth = ArraySize(aExplainWidth);
2429 int iIndent = 1;
2431 if( p->cMode==MODE_ScanExp ){
2432 aWidth = aScanExpWidth;
2433 aMap = aScanExpMap;
2434 nWidth = ArraySize(aScanExpWidth);
2435 iIndent = 3;
2437 if( nArg>nWidth ) nArg = nWidth;
2439 /* If this is the first row seen, print out the headers */
2440 if( p->cnt++==0 ){
2441 for(i=0; i<nArg; i++){
2442 utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
2443 oputz(i==nArg-1 ? "\n" : " ");
2445 for(i=0; i<nArg; i++){
2446 print_dashes(aWidth[i]);
2447 oputz(i==nArg-1 ? "\n" : " ");
2451 /* If there is no data, exit early. */
2452 if( azArg==0 ) break;
2454 for(i=0; i<nArg; i++){
2455 const char *zSep = " ";
2456 int w = aWidth[i];
2457 const char *zVal = azArg[ aMap[i] ];
2458 if( i==nArg-1 ) w = 0;
2459 if( zVal && strlenChar(zVal)>w ){
2460 w = strlenChar(zVal);
2461 zSep = " ";
2463 if( i==iIndent && p->aiIndent && p->pStmt ){
2464 if( p->iIndent<p->nIndent ){
2465 oputf("%*.s", p->aiIndent[p->iIndent], "");
2467 p->iIndent++;
2469 utf8_width_print(w, zVal ? zVal : p->nullValue);
2470 oputz(i==nArg-1 ? "\n" : zSep);
2472 break;
2474 case MODE_Semi: { /* .schema and .fullschema output */
2475 printSchemaLine(azArg[0], ";\n");
2476 break;
2478 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2479 char *z;
2480 int j;
2481 int nParen = 0;
2482 char cEnd = 0;
2483 char c;
2484 int nLine = 0;
2485 assert( nArg==1 );
2486 if( azArg[0]==0 ) break;
2487 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2488 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2490 oputf("%s;\n", azArg[0]);
2491 break;
2493 z = sqlite3_mprintf("%s", azArg[0]);
2494 shell_check_oom(z);
2495 j = 0;
2496 for(i=0; IsSpace(z[i]); i++){}
2497 for(; (c = z[i])!=0; i++){
2498 if( IsSpace(c) ){
2499 if( z[j-1]=='\r' ) z[j-1] = '\n';
2500 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2501 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2502 j--;
2504 z[j++] = c;
2506 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2507 z[j] = 0;
2508 if( strlen30(z)>=79 ){
2509 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2510 if( c==cEnd ){
2511 cEnd = 0;
2512 }else if( c=='"' || c=='\'' || c=='`' ){
2513 cEnd = c;
2514 }else if( c=='[' ){
2515 cEnd = ']';
2516 }else if( c=='-' && z[i+1]=='-' ){
2517 cEnd = '\n';
2518 }else if( c=='(' ){
2519 nParen++;
2520 }else if( c==')' ){
2521 nParen--;
2522 if( nLine>0 && nParen==0 && j>0 ){
2523 printSchemaLineN(z, j, "\n");
2524 j = 0;
2527 z[j++] = c;
2528 if( nParen==1 && cEnd==0
2529 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2531 if( c=='\n' ) j--;
2532 printSchemaLineN(z, j, "\n ");
2533 j = 0;
2534 nLine++;
2535 while( IsSpace(z[i+1]) ){ i++; }
2538 z[j] = 0;
2540 printSchemaLine(z, ";\n");
2541 sqlite3_free(z);
2542 break;
2544 case MODE_List: {
2545 if( p->cnt++==0 && p->showHeader ){
2546 for(i=0; i<nArg; i++){
2547 oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
2550 if( azArg==0 ) break;
2551 for(i=0; i<nArg; i++){
2552 char *z = azArg[i];
2553 if( z==0 ) z = p->nullValue;
2554 oputz(z);
2555 oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
2557 break;
2559 case MODE_Html: {
2560 if( p->cnt++==0 && p->showHeader ){
2561 oputz("<TR>");
2562 for(i=0; i<nArg; i++){
2563 oputz("<TH>");
2564 output_html_string(azCol[i]);
2565 oputz("</TH>\n");
2567 oputz("</TR>\n");
2569 if( azArg==0 ) break;
2570 oputz("<TR>");
2571 for(i=0; i<nArg; i++){
2572 oputz("<TD>");
2573 output_html_string(azArg[i] ? azArg[i] : p->nullValue);
2574 oputz("</TD>\n");
2576 oputz("</TR>\n");
2577 break;
2579 case MODE_Tcl: {
2580 if( p->cnt++==0 && p->showHeader ){
2581 for(i=0; i<nArg; i++){
2582 output_c_string(azCol[i] ? azCol[i] : "");
2583 if(i<nArg-1) oputz(p->colSeparator);
2585 oputz(p->rowSeparator);
2587 if( azArg==0 ) break;
2588 for(i=0; i<nArg; i++){
2589 output_c_string(azArg[i] ? azArg[i] : p->nullValue);
2590 if(i<nArg-1) oputz(p->colSeparator);
2592 oputz(p->rowSeparator);
2593 break;
2595 case MODE_Csv: {
2596 setBinaryMode(p->out, 1);
2597 if( p->cnt++==0 && p->showHeader ){
2598 for(i=0; i<nArg; i++){
2599 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2601 oputz(p->rowSeparator);
2603 if( nArg>0 ){
2604 for(i=0; i<nArg; i++){
2605 output_csv(p, azArg[i], i<nArg-1);
2607 oputz(p->rowSeparator);
2609 setTextMode(p->out, 1);
2610 break;
2612 case MODE_Insert: {
2613 if( azArg==0 ) break;
2614 oputf("INSERT INTO %s",p->zDestTable);
2615 if( p->showHeader ){
2616 oputz("(");
2617 for(i=0; i<nArg; i++){
2618 if( i>0 ) oputz(",");
2619 if( quoteChar(azCol[i]) ){
2620 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2621 shell_check_oom(z);
2622 oputz(z);
2623 sqlite3_free(z);
2624 }else{
2625 oputf("%s", azCol[i]);
2628 oputz(")");
2630 p->cnt++;
2631 for(i=0; i<nArg; i++){
2632 oputz(i>0 ? "," : " VALUES(");
2633 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2634 oputz("NULL");
2635 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2636 if( ShellHasFlag(p, SHFLG_Newlines) ){
2637 output_quoted_string(azArg[i]);
2638 }else{
2639 output_quoted_escaped_string(azArg[i]);
2641 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2642 oputz(azArg[i]);
2643 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2644 char z[50];
2645 double r = sqlite3_column_double(p->pStmt, i);
2646 sqlite3_uint64 ur;
2647 memcpy(&ur,&r,sizeof(r));
2648 if( ur==0x7ff0000000000000LL ){
2649 oputz("9.0e+999");
2650 }else if( ur==0xfff0000000000000LL ){
2651 oputz("-9.0e+999");
2652 }else{
2653 sqlite3_int64 ir = (sqlite3_int64)r;
2654 if( r==(double)ir ){
2655 sqlite3_snprintf(50,z,"%lld.0", ir);
2656 }else{
2657 sqlite3_snprintf(50,z,"%!.20g", r);
2659 oputz(z);
2661 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2662 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2663 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2664 output_hex_blob(pBlob, nBlob);
2665 }else if( isNumber(azArg[i], 0) ){
2666 oputz(azArg[i]);
2667 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2668 output_quoted_string(azArg[i]);
2669 }else{
2670 output_quoted_escaped_string(azArg[i]);
2673 oputz(");\n");
2674 break;
2676 case MODE_Json: {
2677 if( azArg==0 ) break;
2678 if( p->cnt==0 ){
2679 fputs("[{", p->out);
2680 }else{
2681 fputs(",\n{", p->out);
2683 p->cnt++;
2684 for(i=0; i<nArg; i++){
2685 output_json_string(azCol[i], -1);
2686 oputz(":");
2687 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2688 oputz("null");
2689 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2690 char z[50];
2691 double r = sqlite3_column_double(p->pStmt, i);
2692 sqlite3_uint64 ur;
2693 memcpy(&ur,&r,sizeof(r));
2694 if( ur==0x7ff0000000000000LL ){
2695 oputz("9.0e+999");
2696 }else if( ur==0xfff0000000000000LL ){
2697 oputz("-9.0e+999");
2698 }else{
2699 sqlite3_snprintf(50,z,"%!.20g", r);
2700 oputz(z);
2702 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2703 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2704 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2705 output_json_string(pBlob, nBlob);
2706 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2707 output_json_string(azArg[i], -1);
2708 }else{
2709 oputz(azArg[i]);
2711 if( i<nArg-1 ){
2712 oputz(",");
2715 oputz("}");
2716 break;
2718 case MODE_Quote: {
2719 if( azArg==0 ) break;
2720 if( p->cnt==0 && p->showHeader ){
2721 for(i=0; i<nArg; i++){
2722 if( i>0 ) fputs(p->colSeparator, p->out);
2723 output_quoted_string(azCol[i]);
2725 fputs(p->rowSeparator, p->out);
2727 p->cnt++;
2728 for(i=0; i<nArg; i++){
2729 if( i>0 ) fputs(p->colSeparator, p->out);
2730 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2731 oputz("NULL");
2732 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2733 output_quoted_string(azArg[i]);
2734 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2735 oputz(azArg[i]);
2736 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2737 char z[50];
2738 double r = sqlite3_column_double(p->pStmt, i);
2739 sqlite3_snprintf(50,z,"%!.20g", r);
2740 oputz(z);
2741 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2742 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2743 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2744 output_hex_blob(pBlob, nBlob);
2745 }else if( isNumber(azArg[i], 0) ){
2746 oputz(azArg[i]);
2747 }else{
2748 output_quoted_string(azArg[i]);
2751 fputs(p->rowSeparator, p->out);
2752 break;
2754 case MODE_Ascii: {
2755 if( p->cnt++==0 && p->showHeader ){
2756 for(i=0; i<nArg; i++){
2757 if( i>0 ) oputz(p->colSeparator);
2758 oputz(azCol[i] ? azCol[i] : "");
2760 oputz(p->rowSeparator);
2762 if( azArg==0 ) break;
2763 for(i=0; i<nArg; i++){
2764 if( i>0 ) oputz(p->colSeparator);
2765 oputz(azArg[i] ? azArg[i] : p->nullValue);
2767 oputz(p->rowSeparator);
2768 break;
2770 case MODE_EQP: {
2771 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2772 break;
2775 return 0;
2779 ** This is the callback routine that the SQLite library
2780 ** invokes for each row of a query result.
2782 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2783 /* since we don't have type info, call the shell_callback with a NULL value */
2784 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2788 ** This is the callback routine from sqlite3_exec() that appends all
2789 ** output onto the end of a ShellText object.
2791 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2792 ShellText *p = (ShellText*)pArg;
2793 int i;
2794 UNUSED_PARAMETER(az);
2795 if( azArg==0 ) return 0;
2796 if( p->n ) appendText(p, "|", 0);
2797 for(i=0; i<nArg; i++){
2798 if( i ) appendText(p, ",", 0);
2799 if( azArg[i] ) appendText(p, azArg[i], 0);
2801 return 0;
2805 ** Generate an appropriate SELFTEST table in the main database.
2807 static void createSelftestTable(ShellState *p){
2808 char *zErrMsg = 0;
2809 sqlite3_exec(p->db,
2810 "SAVEPOINT selftest_init;\n"
2811 "CREATE TABLE IF NOT EXISTS selftest(\n"
2812 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2813 " op TEXT,\n" /* Operator: memo run */
2814 " cmd TEXT,\n" /* Command text */
2815 " ans TEXT\n" /* Desired answer */
2816 ");"
2817 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2818 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2819 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2820 " 'memo','Tests generated by --init');\n"
2821 "INSERT INTO [_shell$self]\n"
2822 " SELECT 'run',\n"
2823 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2824 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2825 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2826 "FROM sqlite_schema ORDER BY 2',224));\n"
2827 "INSERT INTO [_shell$self]\n"
2828 " SELECT 'run',"
2829 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2830 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2831 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2832 " FROM (\n"
2833 " SELECT name FROM sqlite_schema\n"
2834 " WHERE type='table'\n"
2835 " AND name<>'selftest'\n"
2836 " AND coalesce(rootpage,0)>0\n"
2837 " )\n"
2838 " ORDER BY name;\n"
2839 "INSERT INTO [_shell$self]\n"
2840 " VALUES('run','PRAGMA integrity_check','ok');\n"
2841 "INSERT INTO selftest(tno,op,cmd,ans)"
2842 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2843 "DROP TABLE [_shell$self];"
2844 ,0,0,&zErrMsg);
2845 if( zErrMsg ){
2846 eputf("SELFTEST initialization failure: %s\n", zErrMsg);
2847 sqlite3_free(zErrMsg);
2849 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2854 ** Set the destination table field of the ShellState structure to
2855 ** the name of the table given. Escape any quote characters in the
2856 ** table name.
2858 static void set_table_name(ShellState *p, const char *zName){
2859 int i, n;
2860 char cQuote;
2861 char *z;
2863 if( p->zDestTable ){
2864 free(p->zDestTable);
2865 p->zDestTable = 0;
2867 if( zName==0 ) return;
2868 cQuote = quoteChar(zName);
2869 n = strlen30(zName);
2870 if( cQuote ) n += n+2;
2871 z = p->zDestTable = malloc( n+1 );
2872 shell_check_oom(z);
2873 n = 0;
2874 if( cQuote ) z[n++] = cQuote;
2875 for(i=0; zName[i]; i++){
2876 z[n++] = zName[i];
2877 if( zName[i]==cQuote ) z[n++] = cQuote;
2879 if( cQuote ) z[n++] = cQuote;
2880 z[n] = 0;
2884 ** Maybe construct two lines of text that point out the position of a
2885 ** syntax error. Return a pointer to the text, in memory obtained from
2886 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2887 ** specific token that we can point to, return an empty string.
2889 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2890 ** and should be released by the caller invoking sqlite3_free().
2892 static char *shell_error_context(const char *zSql, sqlite3 *db){
2893 int iOffset;
2894 size_t len;
2895 char *zCode;
2896 char *zMsg;
2897 int i;
2898 if( db==0
2899 || zSql==0
2900 || (iOffset = sqlite3_error_offset(db))<0
2901 || iOffset>=(int)strlen(zSql)
2903 return sqlite3_mprintf("");
2905 while( iOffset>50 ){
2906 iOffset--;
2907 zSql++;
2908 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2910 len = strlen(zSql);
2911 if( len>78 ){
2912 len = 78;
2913 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
2915 zCode = sqlite3_mprintf("%.*s", len, zSql);
2916 shell_check_oom(zCode);
2917 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2918 if( iOffset<25 ){
2919 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
2920 }else{
2921 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,"");
2923 return zMsg;
2928 ** Execute a query statement that will generate SQL output. Print
2929 ** the result columns, comma-separated, on a line and then add a
2930 ** semicolon terminator to the end of that line.
2932 ** If the number of columns is 1 and that column contains text "--"
2933 ** then write the semicolon on a separate line. That way, if a
2934 ** "--" comment occurs at the end of the statement, the comment
2935 ** won't consume the semicolon terminator.
2937 static int run_table_dump_query(
2938 ShellState *p, /* Query context */
2939 const char *zSelect /* SELECT statement to extract content */
2941 sqlite3_stmt *pSelect;
2942 int rc;
2943 int nResult;
2944 int i;
2945 const char *z;
2946 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2947 if( rc!=SQLITE_OK || !pSelect ){
2948 char *zContext = shell_error_context(zSelect, p->db);
2949 oputf("/**** ERROR: (%d) %s *****/\n%s",
2950 rc, sqlite3_errmsg(p->db), zContext);
2951 sqlite3_free(zContext);
2952 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2953 return rc;
2955 rc = sqlite3_step(pSelect);
2956 nResult = sqlite3_column_count(pSelect);
2957 while( rc==SQLITE_ROW ){
2958 z = (const char*)sqlite3_column_text(pSelect, 0);
2959 oputf("%s", z);
2960 for(i=1; i<nResult; i++){
2961 oputf(",%s", sqlite3_column_text(pSelect, i));
2963 if( z==0 ) z = "";
2964 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2965 if( z[0] ){
2966 oputz("\n;\n");
2967 }else{
2968 oputz(";\n");
2970 rc = sqlite3_step(pSelect);
2972 rc = sqlite3_finalize(pSelect);
2973 if( rc!=SQLITE_OK ){
2974 oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
2975 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2977 return rc;
2981 ** Allocate space and save off string indicating current error.
2983 static char *save_err_msg(
2984 sqlite3 *db, /* Database to query */
2985 const char *zPhase, /* When the error occurs */
2986 int rc, /* Error code returned from API */
2987 const char *zSql /* SQL string, or NULL */
2989 char *zErr;
2990 char *zContext;
2991 sqlite3_str *pStr = sqlite3_str_new(0);
2992 sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2993 if( rc>1 ){
2994 sqlite3_str_appendf(pStr, " (%d)", rc);
2996 zContext = shell_error_context(zSql, db);
2997 if( zContext ){
2998 sqlite3_str_appendall(pStr, zContext);
2999 sqlite3_free(zContext);
3001 zErr = sqlite3_str_finish(pStr);
3002 shell_check_oom(zErr);
3003 return zErr;
3006 #ifdef __linux__
3008 ** Attempt to display I/O stats on Linux using /proc/PID/io
3010 static void displayLinuxIoStats(void){
3011 FILE *in;
3012 char z[200];
3013 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
3014 in = fopen(z, "rb");
3015 if( in==0 ) return;
3016 while( fgets(z, sizeof(z), in)!=0 ){
3017 static const struct {
3018 const char *zPattern;
3019 const char *zDesc;
3020 } aTrans[] = {
3021 { "rchar: ", "Bytes received by read():" },
3022 { "wchar: ", "Bytes sent to write():" },
3023 { "syscr: ", "Read() system calls:" },
3024 { "syscw: ", "Write() system calls:" },
3025 { "read_bytes: ", "Bytes read from storage:" },
3026 { "write_bytes: ", "Bytes written to storage:" },
3027 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
3029 int i;
3030 for(i=0; i<ArraySize(aTrans); i++){
3031 int n = strlen30(aTrans[i].zPattern);
3032 if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
3033 oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
3034 break;
3038 fclose(in);
3040 #endif
3043 ** Display a single line of status using 64-bit values.
3045 static void displayStatLine(
3046 char *zLabel, /* Label for this one line */
3047 char *zFormat, /* Format for the result */
3048 int iStatusCtrl, /* Which status to display */
3049 int bReset /* True to reset the stats */
3051 sqlite3_int64 iCur = -1;
3052 sqlite3_int64 iHiwtr = -1;
3053 int i, nPercent;
3054 char zLine[200];
3055 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
3056 for(i=0, nPercent=0; zFormat[i]; i++){
3057 if( zFormat[i]=='%' ) nPercent++;
3059 if( nPercent>1 ){
3060 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
3061 }else{
3062 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
3064 oputf("%-36s %s\n", zLabel, zLine);
3068 ** Display memory stats.
3070 static int display_stats(
3071 sqlite3 *db, /* Database to query */
3072 ShellState *pArg, /* Pointer to ShellState */
3073 int bReset /* True to reset the stats */
3075 int iCur;
3076 int iHiwtr;
3077 if( pArg==0 || pArg->out==0 ) return 0;
3079 if( pArg->pStmt && pArg->statsOn==2 ){
3080 int nCol, i, x;
3081 sqlite3_stmt *pStmt = pArg->pStmt;
3082 char z[100];
3083 nCol = sqlite3_column_count(pStmt);
3084 oputf("%-36s %d\n", "Number of output columns:", nCol);
3085 for(i=0; i<nCol; i++){
3086 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
3087 oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
3088 #ifndef SQLITE_OMIT_DECLTYPE
3089 sqlite3_snprintf(30, z+x, "declared type:");
3090 oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
3091 #endif
3092 #ifdef SQLITE_ENABLE_COLUMN_METADATA
3093 sqlite3_snprintf(30, z+x, "database name:");
3094 oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
3095 sqlite3_snprintf(30, z+x, "table name:");
3096 oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
3097 sqlite3_snprintf(30, z+x, "origin name:");
3098 oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
3099 #endif
3103 if( pArg->statsOn==3 ){
3104 if( pArg->pStmt ){
3105 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
3106 oputf("VM-steps: %d\n", iCur);
3108 return 0;
3111 displayStatLine("Memory Used:",
3112 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
3113 displayStatLine("Number of Outstanding Allocations:",
3114 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
3115 if( pArg->shellFlgs & SHFLG_Pagecache ){
3116 displayStatLine("Number of Pcache Pages Used:",
3117 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
3119 displayStatLine("Number of Pcache Overflow Bytes:",
3120 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
3121 displayStatLine("Largest Allocation:",
3122 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
3123 displayStatLine("Largest Pcache Allocation:",
3124 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
3125 #ifdef YYTRACKMAXSTACKDEPTH
3126 displayStatLine("Deepest Parser Stack:",
3127 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
3128 #endif
3130 if( db ){
3131 if( pArg->shellFlgs & SHFLG_Lookaside ){
3132 iHiwtr = iCur = -1;
3133 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
3134 &iCur, &iHiwtr, bReset);
3135 oputf("Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
3136 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
3137 &iCur, &iHiwtr, bReset);
3138 oputf("Successful lookaside attempts: %d\n", iHiwtr);
3139 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
3140 &iCur, &iHiwtr, bReset);
3141 oputf("Lookaside failures due to size: %d\n", iHiwtr);
3142 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
3143 &iCur, &iHiwtr, bReset);
3144 oputf("Lookaside failures due to OOM: %d\n", iHiwtr);
3146 iHiwtr = iCur = -1;
3147 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
3148 oputf("Pager Heap Usage: %d bytes\n", iCur);
3149 iHiwtr = iCur = -1;
3150 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
3151 oputf("Page cache hits: %d\n", iCur);
3152 iHiwtr = iCur = -1;
3153 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
3154 oputf("Page cache misses: %d\n", iCur);
3155 iHiwtr = iCur = -1;
3156 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
3157 oputf("Page cache writes: %d\n", iCur);
3158 iHiwtr = iCur = -1;
3159 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
3160 oputf("Page cache spills: %d\n", iCur);
3161 iHiwtr = iCur = -1;
3162 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
3163 oputf("Schema Heap Usage: %d bytes\n", iCur);
3164 iHiwtr = iCur = -1;
3165 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
3166 oputf("Statement Heap/Lookaside Usage: %d bytes\n", iCur);
3169 if( pArg->pStmt ){
3170 int iHit, iMiss;
3171 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
3172 bReset);
3173 oputf("Fullscan Steps: %d\n", iCur);
3174 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
3175 oputf("Sort Operations: %d\n", iCur);
3176 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
3177 oputf("Autoindex Inserts: %d\n", iCur);
3178 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
3179 bReset);
3180 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
3181 bReset);
3182 if( iHit || iMiss ){
3183 oputf("Bloom filter bypass taken: %d/%d\n", iHit, iHit+iMiss);
3185 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
3186 oputf("Virtual Machine Steps: %d\n", iCur);
3187 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
3188 oputf("Reprepare operations: %d\n", iCur);
3189 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
3190 oputf("Number of times run: %d\n", iCur);
3191 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
3192 oputf("Memory used by prepared stmt: %d\n", iCur);
3195 #ifdef __linux__
3196 displayLinuxIoStats();
3197 #endif
3199 /* Do not remove this machine readable comment: extra-stats-output-here */
3201 return 0;
3205 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3206 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
3207 int iPid = 0;
3208 int ret = 1;
3209 sqlite3_stmt_scanstatus_v2(p, iEntry,
3210 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3212 while( iPid!=0 ){
3213 int ii;
3214 for(ii=0; 1; ii++){
3215 int iId;
3216 int res;
3217 res = sqlite3_stmt_scanstatus_v2(p, ii,
3218 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
3220 if( res ) break;
3221 if( iId==iPid ){
3222 sqlite3_stmt_scanstatus_v2(p, ii,
3223 SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3227 ret++;
3229 return ret;
3231 #endif
3233 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3234 static void display_explain_scanstats(
3235 sqlite3 *db, /* Database to query */
3236 ShellState *pArg /* Pointer to ShellState */
3238 static const int f = SQLITE_SCANSTAT_COMPLEX;
3239 sqlite3_stmt *p = pArg->pStmt;
3240 int ii = 0;
3241 i64 nTotal = 0;
3242 int nWidth = 0;
3243 eqp_reset(pArg);
3245 for(ii=0; 1; ii++){
3246 const char *z = 0;
3247 int n = 0;
3248 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
3249 break;
3251 n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
3252 if( n>nWidth ) nWidth = n;
3254 nWidth += 4;
3256 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
3257 for(ii=0; 1; ii++){
3258 i64 nLoop = 0;
3259 i64 nRow = 0;
3260 i64 nCycle = 0;
3261 int iId = 0;
3262 int iPid = 0;
3263 const char *zo = 0;
3264 const char *zName = 0;
3265 char *zText = 0;
3266 double rEst = 0.0;
3268 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
3269 break;
3271 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
3272 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
3273 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
3274 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
3275 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
3276 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
3277 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
3279 zText = sqlite3_mprintf("%s", zo);
3280 if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
3281 char *z = 0;
3282 if( nCycle>=0 && nTotal>0 ){
3283 z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
3284 nCycle, ((nCycle*100)+nTotal/2) / nTotal
3287 if( nLoop>=0 ){
3288 z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
3290 if( nRow>=0 ){
3291 z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
3294 if( zName && pArg->scanstatsOn>1 ){
3295 double rpl = (double)nRow / (double)nLoop;
3296 z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
3299 zText = sqlite3_mprintf(
3300 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
3304 eqp_append(pArg, iId, iPid, zText);
3305 sqlite3_free(zText);
3308 eqp_render(pArg, nTotal);
3310 #endif
3314 ** Parameter azArray points to a zero-terminated array of strings. zStr
3315 ** points to a single nul-terminated string. Return non-zero if zStr
3316 ** is equal, according to strcmp(), to any of the strings in the array.
3317 ** Otherwise, return zero.
3319 static int str_in_array(const char *zStr, const char **azArray){
3320 int i;
3321 for(i=0; azArray[i]; i++){
3322 if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
3324 return 0;
3328 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3329 ** and populate the ShellState.aiIndent[] array with the number of
3330 ** spaces each opcode should be indented before it is output.
3332 ** The indenting rules are:
3334 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3335 ** all opcodes that occur between the p2 jump destination and the opcode
3336 ** itself by 2 spaces.
3338 ** * Do the previous for "Return" instructions for when P2 is positive.
3339 ** See tag-20220407a in wherecode.c and vdbe.c.
3341 ** * For each "Goto", if the jump destination is earlier in the program
3342 ** and ends on one of:
3343 ** Yield SeekGt SeekLt RowSetRead Rewind
3344 ** or if the P1 parameter is one instead of zero,
3345 ** then indent all opcodes between the earlier instruction
3346 ** and "Goto" by 2 spaces.
3348 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3349 int *abYield = 0; /* True if op is an OP_Yield */
3350 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
3351 int iOp; /* Index of operation in p->aiIndent[] */
3353 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3354 "Return", 0 };
3355 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3356 "Rewind", 0 };
3357 const char *azGoto[] = { "Goto", 0 };
3359 /* The caller guarantees that the leftmost 4 columns of the statement
3360 ** passed to this function are equivalent to the leftmost 4 columns
3361 ** of EXPLAIN statement output. In practice the statement may be
3362 ** an EXPLAIN, or it may be a query on the bytecode() virtual table. */
3363 assert( sqlite3_column_count(pSql)>=4 );
3364 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
3365 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
3366 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
3367 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
3369 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3370 int i;
3371 int iAddr = sqlite3_column_int(pSql, 0);
3372 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3373 int p1 = sqlite3_column_int(pSql, 2);
3374 int p2 = sqlite3_column_int(pSql, 3);
3376 /* Assuming that p2 is an instruction address, set variable p2op to the
3377 ** index of that instruction in the aiIndent[] array. p2 and p2op may be
3378 ** different if the current instruction is part of a sub-program generated
3379 ** by an SQL trigger or foreign key. */
3380 int p2op = (p2 + (iOp-iAddr));
3382 /* Grow the p->aiIndent array as required */
3383 if( iOp>=nAlloc ){
3384 nAlloc += 100;
3385 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3386 shell_check_oom(p->aiIndent);
3387 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3388 shell_check_oom(abYield);
3391 abYield[iOp] = str_in_array(zOp, azYield);
3392 p->aiIndent[iOp] = 0;
3393 p->nIndent = iOp+1;
3394 if( str_in_array(zOp, azNext) && p2op>0 ){
3395 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3397 if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
3398 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3402 p->iIndent = 0;
3403 sqlite3_free(abYield);
3404 sqlite3_reset(pSql);
3408 ** Free the array allocated by explain_data_prepare().
3410 static void explain_data_delete(ShellState *p){
3411 sqlite3_free(p->aiIndent);
3412 p->aiIndent = 0;
3413 p->nIndent = 0;
3414 p->iIndent = 0;
3417 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
3420 ** Display scan stats.
3422 static void display_scanstats(
3423 sqlite3 *db, /* Database to query */
3424 ShellState *pArg /* Pointer to ShellState */
3426 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3427 UNUSED_PARAMETER(db);
3428 UNUSED_PARAMETER(pArg);
3429 #else
3430 if( pArg->scanstatsOn==3 ){
3431 const char *zSql =
3432 " SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
3433 " round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
3434 " FROM bytecode(?)";
3436 int rc = SQLITE_OK;
3437 sqlite3_stmt *pStmt = 0;
3438 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3439 if( rc==SQLITE_OK ){
3440 sqlite3_stmt *pSave = pArg->pStmt;
3441 pArg->pStmt = pStmt;
3442 sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
3444 pArg->cnt = 0;
3445 pArg->cMode = MODE_ScanExp;
3446 explain_data_prepare(pArg, pStmt);
3447 exec_prepared_stmt(pArg, pStmt);
3448 explain_data_delete(pArg);
3450 sqlite3_finalize(pStmt);
3451 pArg->pStmt = pSave;
3453 }else{
3454 display_explain_scanstats(db, pArg);
3456 #endif
3460 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3462 static unsigned int savedSelectTrace;
3463 static unsigned int savedWhereTrace;
3464 static void disable_debug_trace_modes(void){
3465 unsigned int zero = 0;
3466 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3467 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3468 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3469 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3471 static void restore_debug_trace_modes(void){
3472 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3473 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3476 /* Create the TEMP table used to store parameter bindings */
3477 static void bind_table_init(ShellState *p){
3478 int wrSchema = 0;
3479 int defensiveMode = 0;
3480 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3481 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3482 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3483 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3484 sqlite3_exec(p->db,
3485 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3486 " key TEXT PRIMARY KEY,\n"
3487 " value\n"
3488 ") WITHOUT ROWID;",
3489 0, 0, 0);
3490 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3491 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3495 ** Bind parameters on a prepared statement.
3497 ** Parameter bindings are taken from a TEMP table of the form:
3499 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3500 ** WITHOUT ROWID;
3502 ** No bindings occur if this table does not exist. The name of the table
3503 ** begins with "sqlite_" so that it will not collide with ordinary application
3504 ** tables. The table must be in the TEMP schema.
3506 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3507 int nVar;
3508 int i;
3509 int rc;
3510 sqlite3_stmt *pQ = 0;
3512 nVar = sqlite3_bind_parameter_count(pStmt);
3513 if( nVar==0 ) return; /* Nothing to do */
3514 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3515 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3516 rc = SQLITE_NOTFOUND;
3517 pQ = 0;
3518 }else{
3519 rc = sqlite3_prepare_v2(pArg->db,
3520 "SELECT value FROM temp.sqlite_parameters"
3521 " WHERE key=?1", -1, &pQ, 0);
3523 for(i=1; i<=nVar; i++){
3524 char zNum[30];
3525 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3526 if( zVar==0 ){
3527 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3528 zVar = zNum;
3530 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3531 if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
3532 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3533 #ifdef NAN
3534 }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
3535 sqlite3_bind_double(pStmt, i, NAN);
3536 #endif
3537 #ifdef INFINITY
3538 }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
3539 sqlite3_bind_double(pStmt, i, INFINITY);
3540 #endif
3541 }else{
3542 sqlite3_bind_null(pStmt, i);
3544 sqlite3_reset(pQ);
3546 sqlite3_finalize(pQ);
3550 ** UTF8 box-drawing characters. Imagine box lines like this:
3552 ** 1
3553 ** |
3554 ** 4 --+-- 2
3555 ** |
3556 ** 3
3558 ** Each box characters has between 2 and 4 of the lines leading from
3559 ** the center. The characters are here identified by the numbers of
3560 ** their corresponding lines.
3562 #define BOX_24 "\342\224\200" /* U+2500 --- */
3563 #define BOX_13 "\342\224\202" /* U+2502 | */
3564 #define BOX_23 "\342\224\214" /* U+250c ,- */
3565 #define BOX_34 "\342\224\220" /* U+2510 -, */
3566 #define BOX_12 "\342\224\224" /* U+2514 '- */
3567 #define BOX_14 "\342\224\230" /* U+2518 -' */
3568 #define BOX_123 "\342\224\234" /* U+251c |- */
3569 #define BOX_134 "\342\224\244" /* U+2524 -| */
3570 #define BOX_234 "\342\224\254" /* U+252c -,- */
3571 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3572 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3574 /* Draw horizontal line N characters long using unicode box
3575 ** characters
3577 static void print_box_line(int N){
3578 const char zDash[] =
3579 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3580 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3581 const int nDash = sizeof(zDash) - 1;
3582 N *= 3;
3583 while( N>nDash ){
3584 oputz(zDash);
3585 N -= nDash;
3587 oputf("%.*s", N, zDash);
3591 ** Draw a horizontal separator for a MODE_Box table.
3593 static void print_box_row_separator(
3594 ShellState *p,
3595 int nArg,
3596 const char *zSep1,
3597 const char *zSep2,
3598 const char *zSep3
3600 int i;
3601 if( nArg>0 ){
3602 oputz(zSep1);
3603 print_box_line(p->actualWidth[0]+2);
3604 for(i=1; i<nArg; i++){
3605 oputz(zSep2);
3606 print_box_line(p->actualWidth[i]+2);
3608 oputz(zSep3);
3610 oputz("\n");
3614 ** z[] is a line of text that is to be displayed the .mode box or table or
3615 ** similar tabular formats. z[] might contain control characters such
3616 ** as \n, \t, \f, or \r.
3618 ** Compute characters to display on the first line of z[]. Stop at the
3619 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3620 ** from malloc()) of that first line, which caller should free sometime.
3621 ** Write anything to display on the next line into *pzTail. If this is
3622 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3624 static char *translateForDisplayAndDup(
3625 const unsigned char *z, /* Input text to be transformed */
3626 const unsigned char **pzTail, /* OUT: Tail of the input for next line */
3627 int mxWidth, /* Max width. 0 means no limit */
3628 u8 bWordWrap /* If true, avoid breaking mid-word */
3630 int i; /* Input bytes consumed */
3631 int j; /* Output bytes generated */
3632 int k; /* Input bytes to be displayed */
3633 int n; /* Output column number */
3634 unsigned char *zOut; /* Output text */
3636 if( z==0 ){
3637 *pzTail = 0;
3638 return 0;
3640 if( mxWidth<0 ) mxWidth = -mxWidth;
3641 if( mxWidth==0 ) mxWidth = 1000000;
3642 i = j = n = 0;
3643 while( n<mxWidth ){
3644 if( z[i]>=' ' ){
3645 n++;
3646 do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3647 continue;
3649 if( z[i]=='\t' ){
3651 n++;
3652 j++;
3653 }while( (n&7)!=0 && n<mxWidth );
3654 i++;
3655 continue;
3657 break;
3659 if( n>=mxWidth && bWordWrap ){
3660 /* Perhaps try to back up to a better place to break the line */
3661 for(k=i; k>i/2; k--){
3662 if( isspace(z[k-1]) ) break;
3664 if( k<=i/2 ){
3665 for(k=i; k>i/2; k--){
3666 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3669 if( k<=i/2 ){
3670 k = i;
3671 }else{
3672 i = k;
3673 while( z[i]==' ' ) i++;
3675 }else{
3676 k = i;
3678 if( n>=mxWidth && z[i]>=' ' ){
3679 *pzTail = &z[i];
3680 }else if( z[i]=='\r' && z[i+1]=='\n' ){
3681 *pzTail = z[i+2] ? &z[i+2] : 0;
3682 }else if( z[i]==0 || z[i+1]==0 ){
3683 *pzTail = 0;
3684 }else{
3685 *pzTail = &z[i+1];
3687 zOut = malloc( j+1 );
3688 shell_check_oom(zOut);
3689 i = j = n = 0;
3690 while( i<k ){
3691 if( z[i]>=' ' ){
3692 n++;
3693 do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3694 continue;
3696 if( z[i]=='\t' ){
3698 n++;
3699 zOut[j++] = ' ';
3700 }while( (n&7)!=0 && n<mxWidth );
3701 i++;
3702 continue;
3704 break;
3706 zOut[j] = 0;
3707 return (char*)zOut;
3710 /* Extract the value of the i-th current column for pStmt as an SQL literal
3711 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3712 ** the caller.
3714 static char *quoted_column(sqlite3_stmt *pStmt, int i){
3715 switch( sqlite3_column_type(pStmt, i) ){
3716 case SQLITE_NULL: {
3717 return sqlite3_mprintf("NULL");
3719 case SQLITE_INTEGER:
3720 case SQLITE_FLOAT: {
3721 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3723 case SQLITE_TEXT: {
3724 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3726 case SQLITE_BLOB: {
3727 int j;
3728 sqlite3_str *pStr = sqlite3_str_new(0);
3729 const unsigned char *a = sqlite3_column_blob(pStmt,i);
3730 int n = sqlite3_column_bytes(pStmt,i);
3731 sqlite3_str_append(pStr, "x'", 2);
3732 for(j=0; j<n; j++){
3733 sqlite3_str_appendf(pStr, "%02x", a[j]);
3735 sqlite3_str_append(pStr, "'", 1);
3736 return sqlite3_str_finish(pStr);
3739 return 0; /* Not reached */
3743 ** Run a prepared statement and output the result in one of the
3744 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3745 ** or MODE_Box.
3747 ** This is different from ordinary exec_prepared_stmt() in that
3748 ** it has to run the entire query and gather the results into memory
3749 ** first, in order to determine column widths, before providing
3750 ** any output.
3752 static void exec_prepared_stmt_columnar(
3753 ShellState *p, /* Pointer to ShellState */
3754 sqlite3_stmt *pStmt /* Statement to run */
3756 sqlite3_int64 nRow = 0;
3757 int nColumn = 0;
3758 char **azData = 0;
3759 sqlite3_int64 nAlloc = 0;
3760 char *abRowDiv = 0;
3761 const unsigned char *uz;
3762 const char *z;
3763 char **azQuoted = 0;
3764 int rc;
3765 sqlite3_int64 i, nData;
3766 int j, nTotal, w, n;
3767 const char *colSep = 0;
3768 const char *rowSep = 0;
3769 const unsigned char **azNextLine = 0;
3770 int bNextLine = 0;
3771 int bMultiLineRowExists = 0;
3772 int bw = p->cmOpts.bWordWrap;
3773 const char *zEmpty = "";
3774 const char *zShowNull = p->nullValue;
3776 rc = sqlite3_step(pStmt);
3777 if( rc!=SQLITE_ROW ) return;
3778 nColumn = sqlite3_column_count(pStmt);
3779 if( nColumn==0 ) goto columnar_end;
3780 nAlloc = nColumn*4;
3781 if( nAlloc<=0 ) nAlloc = 1;
3782 azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3783 shell_check_oom(azData);
3784 azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3785 shell_check_oom(azNextLine);
3786 memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3787 if( p->cmOpts.bQuote ){
3788 azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3789 shell_check_oom(azQuoted);
3790 memset(azQuoted, 0, nColumn*sizeof(char*) );
3792 abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3793 shell_check_oom(abRowDiv);
3794 if( nColumn>p->nWidth ){
3795 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3796 shell_check_oom(p->colWidth);
3797 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3798 p->nWidth = nColumn;
3799 p->actualWidth = &p->colWidth[nColumn];
3801 memset(p->actualWidth, 0, nColumn*sizeof(int));
3802 for(i=0; i<nColumn; i++){
3803 w = p->colWidth[i];
3804 if( w<0 ) w = -w;
3805 p->actualWidth[i] = w;
3807 for(i=0; i<nColumn; i++){
3808 const unsigned char *zNotUsed;
3809 int wx = p->colWidth[i];
3810 if( wx==0 ){
3811 wx = p->cmOpts.iWrap;
3813 if( wx<0 ) wx = -wx;
3814 uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3815 if( uz==0 ) uz = (u8*)"";
3816 azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3819 int useNextLine = bNextLine;
3820 bNextLine = 0;
3821 if( (nRow+2)*nColumn >= nAlloc ){
3822 nAlloc *= 2;
3823 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3824 shell_check_oom(azData);
3825 abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3826 shell_check_oom(abRowDiv);
3828 abRowDiv[nRow] = 1;
3829 nRow++;
3830 for(i=0; i<nColumn; i++){
3831 int wx = p->colWidth[i];
3832 if( wx==0 ){
3833 wx = p->cmOpts.iWrap;
3835 if( wx<0 ) wx = -wx;
3836 if( useNextLine ){
3837 uz = azNextLine[i];
3838 if( uz==0 ) uz = (u8*)zEmpty;
3839 }else if( p->cmOpts.bQuote ){
3840 sqlite3_free(azQuoted[i]);
3841 azQuoted[i] = quoted_column(pStmt,i);
3842 uz = (const unsigned char*)azQuoted[i];
3843 }else{
3844 uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3845 if( uz==0 ) uz = (u8*)zShowNull;
3847 azData[nRow*nColumn + i]
3848 = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3849 if( azNextLine[i] ){
3850 bNextLine = 1;
3851 abRowDiv[nRow-1] = 0;
3852 bMultiLineRowExists = 1;
3855 }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3856 nTotal = nColumn*(nRow+1);
3857 for(i=0; i<nTotal; i++){
3858 z = azData[i];
3859 if( z==0 ) z = (char*)zEmpty;
3860 n = strlenChar(z);
3861 j = i%nColumn;
3862 if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3864 if( seenInterrupt ) goto columnar_end;
3865 switch( p->cMode ){
3866 case MODE_Column: {
3867 colSep = " ";
3868 rowSep = "\n";
3869 if( p->showHeader ){
3870 for(i=0; i<nColumn; i++){
3871 w = p->actualWidth[i];
3872 if( p->colWidth[i]<0 ) w = -w;
3873 utf8_width_print(w, azData[i]);
3874 fputs(i==nColumn-1?"\n":" ", p->out);
3876 for(i=0; i<nColumn; i++){
3877 print_dashes(p->actualWidth[i]);
3878 fputs(i==nColumn-1?"\n":" ", p->out);
3881 break;
3883 case MODE_Table: {
3884 colSep = " | ";
3885 rowSep = " |\n";
3886 print_row_separator(p, nColumn, "+");
3887 fputs("| ", p->out);
3888 for(i=0; i<nColumn; i++){
3889 w = p->actualWidth[i];
3890 n = strlenChar(azData[i]);
3891 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3892 oputz(i==nColumn-1?" |\n":" | ");
3894 print_row_separator(p, nColumn, "+");
3895 break;
3897 case MODE_Markdown: {
3898 colSep = " | ";
3899 rowSep = " |\n";
3900 fputs("| ", p->out);
3901 for(i=0; i<nColumn; i++){
3902 w = p->actualWidth[i];
3903 n = strlenChar(azData[i]);
3904 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3905 oputz(i==nColumn-1?" |\n":" | ");
3907 print_row_separator(p, nColumn, "|");
3908 break;
3910 case MODE_Box: {
3911 colSep = " " BOX_13 " ";
3912 rowSep = " " BOX_13 "\n";
3913 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3914 oputz(BOX_13 " ");
3915 for(i=0; i<nColumn; i++){
3916 w = p->actualWidth[i];
3917 n = strlenChar(azData[i]);
3918 oputf("%*s%s%*s%s",
3919 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3920 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3922 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3923 break;
3926 for(i=nColumn, j=0; i<nTotal; i++, j++){
3927 if( j==0 && p->cMode!=MODE_Column ){
3928 oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
3930 z = azData[i];
3931 if( z==0 ) z = p->nullValue;
3932 w = p->actualWidth[j];
3933 if( p->colWidth[j]<0 ) w = -w;
3934 utf8_width_print(w, z);
3935 if( j==nColumn-1 ){
3936 oputz(rowSep);
3937 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3938 if( p->cMode==MODE_Table ){
3939 print_row_separator(p, nColumn, "+");
3940 }else if( p->cMode==MODE_Box ){
3941 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3942 }else if( p->cMode==MODE_Column ){
3943 oputz("\n");
3946 j = -1;
3947 if( seenInterrupt ) goto columnar_end;
3948 }else{
3949 oputz(colSep);
3952 if( p->cMode==MODE_Table ){
3953 print_row_separator(p, nColumn, "+");
3954 }else if( p->cMode==MODE_Box ){
3955 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3957 columnar_end:
3958 if( seenInterrupt ){
3959 oputz("Interrupt\n");
3961 nData = (nRow+1)*nColumn;
3962 for(i=0; i<nData; i++){
3963 z = azData[i];
3964 if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3966 sqlite3_free(azData);
3967 sqlite3_free((void*)azNextLine);
3968 sqlite3_free(abRowDiv);
3969 if( azQuoted ){
3970 for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3971 sqlite3_free(azQuoted);
3976 ** Run a prepared statement
3978 static void exec_prepared_stmt(
3979 ShellState *pArg, /* Pointer to ShellState */
3980 sqlite3_stmt *pStmt /* Statement to run */
3982 int rc;
3983 sqlite3_uint64 nRow = 0;
3985 if( pArg->cMode==MODE_Column
3986 || pArg->cMode==MODE_Table
3987 || pArg->cMode==MODE_Box
3988 || pArg->cMode==MODE_Markdown
3990 exec_prepared_stmt_columnar(pArg, pStmt);
3991 return;
3994 /* perform the first step. this will tell us if we
3995 ** have a result set or not and how wide it is.
3997 rc = sqlite3_step(pStmt);
3998 /* if we have a result set... */
3999 if( SQLITE_ROW == rc ){
4000 /* allocate space for col name ptr, value ptr, and type */
4001 int nCol = sqlite3_column_count(pStmt);
4002 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
4003 if( !pData ){
4004 shell_out_of_memory();
4005 }else{
4006 char **azCols = (char **)pData; /* Names of result columns */
4007 char **azVals = &azCols[nCol]; /* Results */
4008 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
4009 int i, x;
4010 assert(sizeof(int) <= sizeof(char *));
4011 /* save off ptrs to column names */
4012 for(i=0; i<nCol; i++){
4013 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
4016 nRow++;
4017 /* extract the data and data types */
4018 for(i=0; i<nCol; i++){
4019 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
4020 if( x==SQLITE_BLOB
4021 && pArg
4022 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
4024 azVals[i] = "";
4025 }else{
4026 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
4028 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
4029 rc = SQLITE_NOMEM;
4030 break; /* from for */
4032 } /* end for */
4034 /* if data and types extracted successfully... */
4035 if( SQLITE_ROW == rc ){
4036 /* call the supplied callback with the result row data */
4037 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
4038 rc = SQLITE_ABORT;
4039 }else{
4040 rc = sqlite3_step(pStmt);
4043 } while( SQLITE_ROW == rc );
4044 sqlite3_free(pData);
4045 if( pArg->cMode==MODE_Json ){
4046 fputs("]\n", pArg->out);
4047 }else if( pArg->cMode==MODE_Count ){
4048 char zBuf[200];
4049 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
4050 nRow, nRow!=1 ? "s" : "");
4051 printf("%s", zBuf);
4057 #ifndef SQLITE_OMIT_VIRTUALTABLE
4059 ** This function is called to process SQL if the previous shell command
4060 ** was ".expert". It passes the SQL in the second argument directly to
4061 ** the sqlite3expert object.
4063 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4064 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4065 ** an English language error message. It is the responsibility of the
4066 ** caller to eventually free this buffer using sqlite3_free().
4068 static int expertHandleSQL(
4069 ShellState *pState,
4070 const char *zSql,
4071 char **pzErr
4073 assert( pState->expert.pExpert );
4074 assert( pzErr==0 || *pzErr==0 );
4075 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
4079 ** This function is called either to silently clean up the object
4080 ** created by the ".expert" command (if bCancel==1), or to generate a
4081 ** report from it and then clean it up (if bCancel==0).
4083 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4084 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4085 ** an English language error message. It is the responsibility of the
4086 ** caller to eventually free this buffer using sqlite3_free().
4088 static int expertFinish(
4089 ShellState *pState,
4090 int bCancel,
4091 char **pzErr
4093 int rc = SQLITE_OK;
4094 sqlite3expert *p = pState->expert.pExpert;
4095 assert( p );
4096 assert( bCancel || pzErr==0 || *pzErr==0 );
4097 if( bCancel==0 ){
4098 int bVerbose = pState->expert.bVerbose;
4100 rc = sqlite3_expert_analyze(p, pzErr);
4101 if( rc==SQLITE_OK ){
4102 int nQuery = sqlite3_expert_count(p);
4103 int i;
4105 if( bVerbose ){
4106 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
4107 oputz("-- Candidates -----------------------------\n");
4108 oputf("%s\n", zCand);
4110 for(i=0; i<nQuery; i++){
4111 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
4112 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
4113 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
4114 if( zIdx==0 ) zIdx = "(no new indexes)\n";
4115 if( bVerbose ){
4116 oputf("-- Query %d --------------------------------\n",i+1);
4117 oputf("%s\n\n", zSql);
4119 oputf("%s\n", zIdx);
4120 oputf("%s\n", zEQP);
4124 sqlite3_expert_destroy(p);
4125 pState->expert.pExpert = 0;
4126 return rc;
4130 ** Implementation of ".expert" dot command.
4132 static int expertDotCommand(
4133 ShellState *pState, /* Current shell tool state */
4134 char **azArg, /* Array of arguments passed to dot command */
4135 int nArg /* Number of entries in azArg[] */
4137 int rc = SQLITE_OK;
4138 char *zErr = 0;
4139 int i;
4140 int iSample = 0;
4142 assert( pState->expert.pExpert==0 );
4143 memset(&pState->expert, 0, sizeof(ExpertInfo));
4145 for(i=1; rc==SQLITE_OK && i<nArg; i++){
4146 char *z = azArg[i];
4147 int n;
4148 if( z[0]=='-' && z[1]=='-' ) z++;
4149 n = strlen30(z);
4150 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
4151 pState->expert.bVerbose = 1;
4153 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
4154 if( i==(nArg-1) ){
4155 eputf("option requires an argument: %s\n", z);
4156 rc = SQLITE_ERROR;
4157 }else{
4158 iSample = (int)integerValue(azArg[++i]);
4159 if( iSample<0 || iSample>100 ){
4160 eputf("value out of range: %s\n", azArg[i]);
4161 rc = SQLITE_ERROR;
4165 else{
4166 eputf("unknown option: %s\n", z);
4167 rc = SQLITE_ERROR;
4171 if( rc==SQLITE_OK ){
4172 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
4173 if( pState->expert.pExpert==0 ){
4174 eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
4175 rc = SQLITE_ERROR;
4176 }else{
4177 sqlite3_expert_config(
4178 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
4182 sqlite3_free(zErr);
4184 return rc;
4186 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4189 ** Execute a statement or set of statements. Print
4190 ** any result rows/columns depending on the current mode
4191 ** set via the supplied callback.
4193 ** This is very similar to SQLite's built-in sqlite3_exec()
4194 ** function except it takes a slightly different callback
4195 ** and callback data argument.
4197 static int shell_exec(
4198 ShellState *pArg, /* Pointer to ShellState */
4199 const char *zSql, /* SQL to be evaluated */
4200 char **pzErrMsg /* Error msg written here */
4202 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
4203 int rc = SQLITE_OK; /* Return Code */
4204 int rc2;
4205 const char *zLeftover; /* Tail of unprocessed SQL */
4206 sqlite3 *db = pArg->db;
4208 if( pzErrMsg ){
4209 *pzErrMsg = NULL;
4212 #ifndef SQLITE_OMIT_VIRTUALTABLE
4213 if( pArg->expert.pExpert ){
4214 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
4215 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
4217 #endif
4219 while( zSql[0] && (SQLITE_OK == rc) ){
4220 static const char *zStmtSql;
4221 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
4222 if( SQLITE_OK != rc ){
4223 if( pzErrMsg ){
4224 *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
4226 }else{
4227 if( !pStmt ){
4228 /* this happens for a comment or white-space */
4229 zSql = zLeftover;
4230 while( IsSpace(zSql[0]) ) zSql++;
4231 continue;
4233 zStmtSql = sqlite3_sql(pStmt);
4234 if( zStmtSql==0 ) zStmtSql = "";
4235 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
4237 /* save off the prepared statement handle and reset row count */
4238 if( pArg ){
4239 pArg->pStmt = pStmt;
4240 pArg->cnt = 0;
4243 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4244 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
4245 sqlite3_stmt *pExplain;
4246 int triggerEQP = 0;
4247 disable_debug_trace_modes();
4248 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
4249 if( pArg->autoEQP>=AUTOEQP_trigger ){
4250 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
4252 pExplain = pStmt;
4253 sqlite3_reset(pExplain);
4254 rc = sqlite3_stmt_explain(pExplain, 2);
4255 if( rc==SQLITE_OK ){
4256 while( sqlite3_step(pExplain)==SQLITE_ROW ){
4257 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
4258 int iEqpId = sqlite3_column_int(pExplain, 0);
4259 int iParentId = sqlite3_column_int(pExplain, 1);
4260 if( zEQPLine==0 ) zEQPLine = "";
4261 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
4262 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
4264 eqp_render(pArg, 0);
4266 if( pArg->autoEQP>=AUTOEQP_full ){
4267 /* Also do an EXPLAIN for ".eqp full" mode */
4268 sqlite3_reset(pExplain);
4269 rc = sqlite3_stmt_explain(pExplain, 1);
4270 if( rc==SQLITE_OK ){
4271 pArg->cMode = MODE_Explain;
4272 assert( sqlite3_stmt_isexplain(pExplain)==1 );
4273 explain_data_prepare(pArg, pExplain);
4274 exec_prepared_stmt(pArg, pExplain);
4275 explain_data_delete(pArg);
4278 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
4279 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
4281 sqlite3_reset(pStmt);
4282 sqlite3_stmt_explain(pStmt, 0);
4283 restore_debug_trace_modes();
4286 if( pArg ){
4287 int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
4288 pArg->cMode = pArg->mode;
4289 if( pArg->autoExplain ){
4290 if( bIsExplain ){
4291 pArg->cMode = MODE_Explain;
4293 if( sqlite3_stmt_isexplain(pStmt)==2 ){
4294 pArg->cMode = MODE_EQP;
4298 /* If the shell is currently in ".explain" mode, gather the extra
4299 ** data required to add indents to the output.*/
4300 if( pArg->cMode==MODE_Explain && bIsExplain ){
4301 explain_data_prepare(pArg, pStmt);
4305 bind_prepared_stmt(pArg, pStmt);
4306 exec_prepared_stmt(pArg, pStmt);
4307 explain_data_delete(pArg);
4308 eqp_render(pArg, 0);
4310 /* print usage stats if stats on */
4311 if( pArg && pArg->statsOn ){
4312 display_stats(db, pArg, 0);
4315 /* print loop-counters if required */
4316 if( pArg && pArg->scanstatsOn ){
4317 display_scanstats(db, pArg);
4320 /* Finalize the statement just executed. If this fails, save a
4321 ** copy of the error message. Otherwise, set zSql to point to the
4322 ** next statement to execute. */
4323 rc2 = sqlite3_finalize(pStmt);
4324 if( rc!=SQLITE_NOMEM ) rc = rc2;
4325 if( rc==SQLITE_OK ){
4326 zSql = zLeftover;
4327 while( IsSpace(zSql[0]) ) zSql++;
4328 }else if( pzErrMsg ){
4329 *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
4332 /* clear saved stmt handle */
4333 if( pArg ){
4334 pArg->pStmt = NULL;
4337 } /* end while */
4339 return rc;
4343 ** Release memory previously allocated by tableColumnList().
4345 static void freeColumnList(char **azCol){
4346 int i;
4347 for(i=1; azCol[i]; i++){
4348 sqlite3_free(azCol[i]);
4350 /* azCol[0] is a static string */
4351 sqlite3_free(azCol);
4355 ** Return a list of pointers to strings which are the names of all
4356 ** columns in table zTab. The memory to hold the names is dynamically
4357 ** allocated and must be released by the caller using a subsequent call
4358 ** to freeColumnList().
4360 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4361 ** value that needs to be preserved, then azCol[0] is filled in with the
4362 ** name of the rowid column.
4364 ** The first regular column in the table is azCol[1]. The list is terminated
4365 ** by an entry with azCol[i]==0.
4367 static char **tableColumnList(ShellState *p, const char *zTab){
4368 char **azCol = 0;
4369 sqlite3_stmt *pStmt;
4370 char *zSql;
4371 int nCol = 0;
4372 int nAlloc = 0;
4373 int nPK = 0; /* Number of PRIMARY KEY columns seen */
4374 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
4375 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4376 int rc;
4378 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4379 shell_check_oom(zSql);
4380 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4381 sqlite3_free(zSql);
4382 if( rc ) return 0;
4383 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4384 if( nCol>=nAlloc-2 ){
4385 nAlloc = nAlloc*2 + nCol + 10;
4386 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4387 shell_check_oom(azCol);
4389 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4390 shell_check_oom(azCol[nCol]);
4391 if( sqlite3_column_int(pStmt, 5) ){
4392 nPK++;
4393 if( nPK==1
4394 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4395 "INTEGER")==0
4397 isIPK = 1;
4398 }else{
4399 isIPK = 0;
4403 sqlite3_finalize(pStmt);
4404 if( azCol==0 ) return 0;
4405 azCol[0] = 0;
4406 azCol[nCol+1] = 0;
4408 /* The decision of whether or not a rowid really needs to be preserved
4409 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4410 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4411 ** rowids on tables where the rowid is inaccessible because there are other
4412 ** columns in the table named "rowid", "_rowid_", and "oid".
4414 if( preserveRowid && isIPK ){
4415 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4416 ** might be an alias for the ROWID. But it might also be a WITHOUT ROWID
4417 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4418 ** ROWID aliases. To distinguish these cases, check to see if
4419 ** there is a "pk" entry in "PRAGMA index_list". There will be
4420 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4422 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4423 " WHERE origin='pk'", zTab);
4424 shell_check_oom(zSql);
4425 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4426 sqlite3_free(zSql);
4427 if( rc ){
4428 freeColumnList(azCol);
4429 return 0;
4431 rc = sqlite3_step(pStmt);
4432 sqlite3_finalize(pStmt);
4433 preserveRowid = rc==SQLITE_ROW;
4435 if( preserveRowid ){
4436 /* Only preserve the rowid if we can find a name to use for the
4437 ** rowid */
4438 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4439 int i, j;
4440 for(j=0; j<3; j++){
4441 for(i=1; i<=nCol; i++){
4442 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4444 if( i>nCol ){
4445 /* At this point, we know that azRowid[j] is not the name of any
4446 ** ordinary column in the table. Verify that azRowid[j] is a valid
4447 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4448 ** tables will fail this last check */
4449 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4450 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4451 break;
4455 return azCol;
4459 ** Toggle the reverse_unordered_selects setting.
4461 static void toggleSelectOrder(sqlite3 *db){
4462 sqlite3_stmt *pStmt = 0;
4463 int iSetting = 0;
4464 char zStmt[100];
4465 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4466 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4467 iSetting = sqlite3_column_int(pStmt, 0);
4469 sqlite3_finalize(pStmt);
4470 sqlite3_snprintf(sizeof(zStmt), zStmt,
4471 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4472 sqlite3_exec(db, zStmt, 0, 0, 0);
4476 ** This is a different callback routine used for dumping the database.
4477 ** Each row received by this callback consists of a table name,
4478 ** the table type ("index" or "table") and SQL to create the table.
4479 ** This routine should print text sufficient to recreate the table.
4481 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4482 int rc;
4483 const char *zTable;
4484 const char *zType;
4485 const char *zSql;
4486 ShellState *p = (ShellState *)pArg;
4487 int dataOnly;
4488 int noSys;
4490 UNUSED_PARAMETER(azNotUsed);
4491 if( nArg!=3 || azArg==0 ) return 0;
4492 zTable = azArg[0];
4493 zType = azArg[1];
4494 zSql = azArg[2];
4495 if( zTable==0 ) return 0;
4496 if( zType==0 ) return 0;
4497 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4498 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4500 if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4501 if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
4502 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4503 if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
4504 }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
4505 return 0;
4506 }else if( dataOnly ){
4507 /* no-op */
4508 }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4509 char *zIns;
4510 if( !p->writableSchema ){
4511 oputz("PRAGMA writable_schema=ON;\n");
4512 p->writableSchema = 1;
4514 zIns = sqlite3_mprintf(
4515 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4516 "VALUES('table','%q','%q',0,'%q');",
4517 zTable, zTable, zSql);
4518 shell_check_oom(zIns);
4519 oputf("%s\n", zIns);
4520 sqlite3_free(zIns);
4521 return 0;
4522 }else{
4523 printSchemaLine(zSql, ";\n");
4526 if( cli_strcmp(zType, "table")==0 ){
4527 ShellText sSelect;
4528 ShellText sTable;
4529 char **azCol;
4530 int i;
4531 char *savedDestTable;
4532 int savedMode;
4534 azCol = tableColumnList(p, zTable);
4535 if( azCol==0 ){
4536 p->nErr++;
4537 return 0;
4540 /* Always quote the table name, even if it appears to be pure ascii,
4541 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4542 initText(&sTable);
4543 appendText(&sTable, zTable, quoteChar(zTable));
4544 /* If preserving the rowid, add a column list after the table name.
4545 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4546 ** instead of the usual "INSERT INTO tab VALUES(...)".
4548 if( azCol[0] ){
4549 appendText(&sTable, "(", 0);
4550 appendText(&sTable, azCol[0], 0);
4551 for(i=1; azCol[i]; i++){
4552 appendText(&sTable, ",", 0);
4553 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4555 appendText(&sTable, ")", 0);
4558 /* Build an appropriate SELECT statement */
4559 initText(&sSelect);
4560 appendText(&sSelect, "SELECT ", 0);
4561 if( azCol[0] ){
4562 appendText(&sSelect, azCol[0], 0);
4563 appendText(&sSelect, ",", 0);
4565 for(i=1; azCol[i]; i++){
4566 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4567 if( azCol[i+1] ){
4568 appendText(&sSelect, ",", 0);
4571 freeColumnList(azCol);
4572 appendText(&sSelect, " FROM ", 0);
4573 appendText(&sSelect, zTable, quoteChar(zTable));
4575 savedDestTable = p->zDestTable;
4576 savedMode = p->mode;
4577 p->zDestTable = sTable.z;
4578 p->mode = p->cMode = MODE_Insert;
4579 rc = shell_exec(p, sSelect.z, 0);
4580 if( (rc&0xff)==SQLITE_CORRUPT ){
4581 oputz("/****** CORRUPTION ERROR *******/\n");
4582 toggleSelectOrder(p->db);
4583 shell_exec(p, sSelect.z, 0);
4584 toggleSelectOrder(p->db);
4586 p->zDestTable = savedDestTable;
4587 p->mode = savedMode;
4588 freeText(&sTable);
4589 freeText(&sSelect);
4590 if( rc ) p->nErr++;
4592 return 0;
4596 ** Run zQuery. Use dump_callback() as the callback routine so that
4597 ** the contents of the query are output as SQL statements.
4599 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4600 ** "ORDER BY rowid DESC" to the end.
4602 static int run_schema_dump_query(
4603 ShellState *p,
4604 const char *zQuery
4606 int rc;
4607 char *zErr = 0;
4608 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4609 if( rc==SQLITE_CORRUPT ){
4610 char *zQ2;
4611 int len = strlen30(zQuery);
4612 oputz("/****** CORRUPTION ERROR *******/\n");
4613 if( zErr ){
4614 oputf("/****** %s ******/\n", zErr);
4615 sqlite3_free(zErr);
4616 zErr = 0;
4618 zQ2 = malloc( len+100 );
4619 if( zQ2==0 ) return rc;
4620 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4621 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4622 if( rc ){
4623 oputf("/****** ERROR: %s ******/\n", zErr);
4624 }else{
4625 rc = SQLITE_CORRUPT;
4627 sqlite3_free(zErr);
4628 free(zQ2);
4630 return rc;
4634 ** Text of help messages.
4636 ** The help text for each individual command begins with a line that starts
4637 ** with ".". Subsequent lines are supplemental information.
4639 ** There must be two or more spaces between the end of the command and the
4640 ** start of the description of what that command does.
4642 static const char *(azHelp[]) = {
4643 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4644 && !defined(SQLITE_SHELL_FIDDLE)
4645 ".archive ... Manage SQL archives",
4646 " Each command must have exactly one of the following options:",
4647 " -c, --create Create a new archive",
4648 " -u, --update Add or update files with changed mtime",
4649 " -i, --insert Like -u but always add even if unchanged",
4650 " -r, --remove Remove files from archive",
4651 " -t, --list List contents of archive",
4652 " -x, --extract Extract files from archive",
4653 " Optional arguments:",
4654 " -v, --verbose Print each filename as it is processed",
4655 " -f FILE, --file FILE Use archive FILE (default is current db)",
4656 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4657 " -C DIR, --directory DIR Read/extract files from directory DIR",
4658 " -g, --glob Use glob matching for names in archive",
4659 " -n, --dryrun Show the SQL that would have occurred",
4660 " Examples:",
4661 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4662 " .ar -tf ARCHIVE # List members of ARCHIVE",
4663 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4664 " See also:",
4665 " http://sqlite.org/cli.html#sqlite_archive_support",
4666 #endif
4667 #ifndef SQLITE_OMIT_AUTHORIZATION
4668 ".auth ON|OFF Show authorizer callbacks",
4669 #endif
4670 #ifndef SQLITE_SHELL_FIDDLE
4671 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4672 " Options:",
4673 " --append Use the appendvfs",
4674 " --async Write to FILE without journal and fsync()",
4675 #endif
4676 ".bail on|off Stop after hitting an error. Default OFF",
4677 #ifndef SQLITE_SHELL_FIDDLE
4678 ".cd DIRECTORY Change the working directory to DIRECTORY",
4679 #endif
4680 ".changes on|off Show number of rows changed by SQL",
4681 #ifndef SQLITE_SHELL_FIDDLE
4682 ".check GLOB Fail if output since .testcase does not match",
4683 ".clone NEWDB Clone data into NEWDB from the existing database",
4684 #endif
4685 ".connection [close] [#] Open or close an auxiliary database connection",
4686 #if defined(_WIN32) || defined(WIN32)
4687 ".crnl on|off Translate \\n to \\r\\n. Default ON",
4688 #endif
4689 ".databases List names and files of attached databases",
4690 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4691 #if SQLITE_SHELL_HAVE_RECOVER
4692 ".dbinfo ?DB? Show status information about the database",
4693 #endif
4694 ".dump ?OBJECTS? Render database content as SQL",
4695 " Options:",
4696 " --data-only Output only INSERT statements",
4697 " --newlines Allow unescaped newline characters in output",
4698 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4699 " --preserve-rowids Include ROWID values in the output",
4700 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4701 " Additional LIKE patterns can be given in subsequent arguments",
4702 ".echo on|off Turn command echo on or off",
4703 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4704 " Other Modes:",
4705 #ifdef SQLITE_DEBUG
4706 " test Show raw EXPLAIN QUERY PLAN output",
4707 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4708 #endif
4709 " trigger Like \"full\" but also show trigger bytecode",
4710 #ifndef SQLITE_SHELL_FIDDLE
4711 ".excel Display the output of next command in spreadsheet",
4712 " --bom Put a UTF8 byte-order mark on intermediate file",
4713 #endif
4714 #ifndef SQLITE_SHELL_FIDDLE
4715 ".exit ?CODE? Exit this program with return-code CODE",
4716 #endif
4717 ".expert EXPERIMENTAL. Suggest indexes for queries",
4718 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4719 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4720 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4721 " --help Show CMD details",
4722 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4723 ".headers on|off Turn display of headers on or off",
4724 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4725 #ifndef SQLITE_SHELL_FIDDLE
4726 ".import FILE TABLE Import data from FILE into TABLE",
4727 " Options:",
4728 " --ascii Use \\037 and \\036 as column and row separators",
4729 " --csv Use , and \\n as column and row separators",
4730 " --skip N Skip the first N rows of input",
4731 " --schema S Target table to be S.TABLE",
4732 " -v \"Verbose\" - increase auxiliary output",
4733 " Notes:",
4734 " * If TABLE does not exist, it is created. The first row of input",
4735 " determines the column names.",
4736 " * If neither --csv or --ascii are used, the input mode is derived",
4737 " from the \".mode\" output mode",
4738 " * If FILE begins with \"|\" then it is a command that generates the",
4739 " input text.",
4740 #endif
4741 #ifndef SQLITE_OMIT_TEST_CONTROL
4742 ",imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4743 #endif
4744 ".indexes ?TABLE? Show names of indexes",
4745 " If TABLE is specified, only show indexes for",
4746 " tables matching TABLE using the LIKE operator.",
4747 ".intck ?STEPS_PER_UNLOCK? Run an incremental integrity check on the db",
4748 #ifdef SQLITE_ENABLE_IOTRACE
4749 ",iotrace FILE Enable I/O diagnostic logging to FILE",
4750 #endif
4751 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4752 ".lint OPTIONS Report potential schema issues.",
4753 " Options:",
4754 " fkey-indexes Find missing foreign key indexes",
4755 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4756 ".load FILE ?ENTRY? Load an extension library",
4757 #endif
4758 #if !defined(SQLITE_SHELL_FIDDLE)
4759 ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout",
4760 #else
4761 ".log on|off Turn logging on or off.",
4762 #endif
4763 ".mode MODE ?OPTIONS? Set output mode",
4764 " MODE is one of:",
4765 " ascii Columns/rows delimited by 0x1F and 0x1E",
4766 " box Tables using unicode box-drawing characters",
4767 " csv Comma-separated values",
4768 " column Output in columns. (See .width)",
4769 " html HTML <table> code",
4770 " insert SQL insert statements for TABLE",
4771 " json Results in a JSON array",
4772 " line One value per line",
4773 " list Values delimited by \"|\"",
4774 " markdown Markdown table format",
4775 " qbox Shorthand for \"box --wrap 60 --quote\"",
4776 " quote Escape answers as for SQL",
4777 " table ASCII-art table",
4778 " tabs Tab-separated values",
4779 " tcl TCL list elements",
4780 " OPTIONS: (for columnar modes or insert mode):",
4781 " --wrap N Wrap output lines to no longer than N characters",
4782 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4783 " --ww Shorthand for \"--wordwrap 1\"",
4784 " --quote Quote output text as SQL literals",
4785 " --noquote Do not quote output text",
4786 " TABLE The name of SQL table used for \"insert\" mode",
4787 #ifndef SQLITE_SHELL_FIDDLE
4788 ".nonce STRING Suspend safe mode for one command if nonce matches",
4789 #endif
4790 ".nullvalue STRING Use STRING in place of NULL values",
4791 #ifndef SQLITE_SHELL_FIDDLE
4792 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4793 " If FILE begins with '|' then open as a pipe",
4794 " --bom Put a UTF8 byte-order mark at the beginning",
4795 " -e Send output to the system text editor",
4796 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4797 /* Note that .open is (partially) available in WASM builds but is
4798 ** currently only intended to be used by the fiddle tool, not
4799 ** end users, so is "undocumented." */
4800 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4801 " Options:",
4802 " --append Use appendvfs to append database to the end of FILE",
4803 #endif
4804 #ifndef SQLITE_OMIT_DESERIALIZE
4805 " --deserialize Load into memory using sqlite3_deserialize()",
4806 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4807 " --maxsize N Maximum size for --hexdb or --deserialized database",
4808 #endif
4809 " --new Initialize FILE to an empty database",
4810 " --nofollow Do not follow symbolic links",
4811 " --readonly Open FILE readonly",
4812 " --zip FILE is a ZIP archive",
4813 #ifndef SQLITE_SHELL_FIDDLE
4814 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4815 " If FILE begins with '|' then open it as a pipe.",
4816 " Options:",
4817 " --bom Prefix output with a UTF8 byte-order mark",
4818 " -e Send output to the system text editor",
4819 " -x Send output as CSV to a spreadsheet",
4820 #endif
4821 ".parameter CMD ... Manage SQL parameter bindings",
4822 " clear Erase all bindings",
4823 " init Initialize the TEMP table that holds bindings",
4824 " list List the current parameter bindings",
4825 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4826 " PARAMETER should start with one of: $ : @ ?",
4827 " unset PARAMETER Remove PARAMETER from the binding table",
4828 ".print STRING... Print literal STRING",
4829 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4830 ".progress N Invoke progress handler after every N opcodes",
4831 " --limit N Interrupt after N progress callbacks",
4832 " --once Do no more than one progress interrupt",
4833 " --quiet|-q No output except at interrupts",
4834 " --reset Reset the count for each input and interrupt",
4835 #endif
4836 ".prompt MAIN CONTINUE Replace the standard prompts",
4837 #ifndef SQLITE_SHELL_FIDDLE
4838 ".quit Stop interpreting input stream, exit if primary.",
4839 ".read FILE Read input from FILE or command output",
4840 " If FILE begins with \"|\", it is a command that generates the input.",
4841 #endif
4842 #if SQLITE_SHELL_HAVE_RECOVER
4843 ".recover Recover as much data as possible from corrupt db.",
4844 " --ignore-freelist Ignore pages that appear to be on db freelist",
4845 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4846 " --no-rowids Do not attempt to recover rowid values",
4847 " that are not also INTEGER PRIMARY KEYs",
4848 #endif
4849 #ifndef SQLITE_SHELL_FIDDLE
4850 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4851 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4852 #endif
4853 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4854 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4855 " Options:",
4856 " --indent Try to pretty-print the schema",
4857 " --nosys Omit objects whose names start with \"sqlite_\"",
4858 ",selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4859 " Options:",
4860 " --init Create a new SELFTEST table",
4861 " -v Verbose output",
4862 ".separator COL ?ROW? Change the column and row separators",
4863 #if defined(SQLITE_ENABLE_SESSION)
4864 ".session ?NAME? CMD ... Create or control sessions",
4865 " Subcommands:",
4866 " attach TABLE Attach TABLE",
4867 " changeset FILE Write a changeset into FILE",
4868 " close Close one session",
4869 " enable ?BOOLEAN? Set or query the enable bit",
4870 " filter GLOB... Reject tables matching GLOBs",
4871 " indirect ?BOOLEAN? Mark or query the indirect status",
4872 " isempty Query whether the session is empty",
4873 " list List currently open session names",
4874 " open DB NAME Open a new session on DB",
4875 " patchset FILE Write a patchset into FILE",
4876 " If ?NAME? is omitted, the first defined session is used.",
4877 #endif
4878 ".sha3sum ... Compute a SHA3 hash of database content",
4879 " Options:",
4880 " --schema Also hash the sqlite_schema table",
4881 " --sha3-224 Use the sha3-224 algorithm",
4882 " --sha3-256 Use the sha3-256 algorithm (default)",
4883 " --sha3-384 Use the sha3-384 algorithm",
4884 " --sha3-512 Use the sha3-512 algorithm",
4885 " Any other argument is a LIKE pattern for tables to hash",
4886 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4887 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4888 #endif
4889 ".show Show the current values for various settings",
4890 ".stats ?ARG? Show stats or turn stats on or off",
4891 " off Turn off automatic stat display",
4892 " on Turn on automatic stat display",
4893 " stmt Show statement stats",
4894 " vmstep Show the virtual machine step count only",
4895 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4896 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4897 #endif
4898 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4899 #ifndef SQLITE_SHELL_FIDDLE
4900 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
4901 #endif
4902 ",testctrl CMD ... Run various sqlite3_test_control() operations",
4903 " Run \".testctrl\" with no arguments for details",
4904 ".timeout MS Try opening locked tables for MS milliseconds",
4905 ".timer on|off Turn SQL timer on or off",
4906 #ifndef SQLITE_OMIT_TRACE
4907 ".trace ?OPTIONS? Output each SQL statement as it is run",
4908 " FILE Send output to FILE",
4909 " stdout Send output to stdout",
4910 " stderr Send output to stderr",
4911 " off Disable tracing",
4912 " --expanded Expand query parameters",
4913 #ifdef SQLITE_ENABLE_NORMALIZE
4914 " --normalized Normal the SQL statements",
4915 #endif
4916 " --plain Show SQL as it is input",
4917 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4918 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4919 " --row Trace each row (SQLITE_TRACE_ROW)",
4920 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4921 #endif /* SQLITE_OMIT_TRACE */
4922 #ifdef SQLITE_DEBUG
4923 ".unmodule NAME ... Unregister virtual table modules",
4924 " --allexcept Unregister everything except those named",
4925 #endif
4926 ".version Show source, library and compiler versions",
4927 ".vfsinfo ?AUX? Information about the top-level VFS",
4928 ".vfslist List all available VFSes",
4929 ".vfsname ?AUX? Print the name of the VFS stack",
4930 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4931 " Negative values right-justify",
4935 ** Output help text.
4937 ** zPattern describes the set of commands for which help text is provided.
4938 ** If zPattern is NULL, then show all commands, but only give a one-line
4939 ** description of each.
4941 ** Return the number of matches.
4943 static int showHelp(FILE *out, const char *zPattern){
4944 int i = 0;
4945 int j = 0;
4946 int n = 0;
4947 char *zPat;
4948 if( zPattern==0
4949 || zPattern[0]=='0'
4950 || cli_strcmp(zPattern,"-a")==0
4951 || cli_strcmp(zPattern,"-all")==0
4952 || cli_strcmp(zPattern,"--all")==0
4954 enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
4955 enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
4956 /* Show all or most commands
4957 ** *zPattern==0 => summary of documented commands only
4958 ** *zPattern=='0' => whole help for undocumented commands
4959 ** Otherwise => whole help for documented commands
4961 enum HelpWanted hw = HW_SummaryOnly;
4962 enum HelpHave hh = HH_More;
4963 if( zPattern!=0 ){
4964 hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
4966 for(i=0; i<ArraySize(azHelp); i++){
4967 switch( azHelp[i][0] ){
4968 case ',':
4969 hh = HH_Summary|HH_Undoc;
4970 break;
4971 case '.':
4972 hh = HH_Summary;
4973 break;
4974 default:
4975 hh &= ~HH_Summary;
4976 break;
4978 if( ((hw^hh)&HH_Undoc)==0 ){
4979 if( (hh&HH_Summary)!=0 ){
4980 sputf(out, ".%s\n", azHelp[i]+1);
4981 ++n;
4982 }else if( (hw&HW_SummaryOnly)==0 ){
4983 sputf(out, "%s\n", azHelp[i]);
4987 }else{
4988 /* Seek documented commands for which zPattern is an exact prefix */
4989 zPat = sqlite3_mprintf(".%s*", zPattern);
4990 shell_check_oom(zPat);
4991 for(i=0; i<ArraySize(azHelp); i++){
4992 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4993 sputf(out, "%s\n", azHelp[i]);
4994 j = i+1;
4995 n++;
4998 sqlite3_free(zPat);
4999 if( n ){
5000 if( n==1 ){
5001 /* when zPattern is a prefix of exactly one command, then include
5002 ** the details of that command, which should begin at offset j */
5003 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
5004 sputf(out, "%s\n", azHelp[j]);
5005 j++;
5008 return n;
5010 /* Look for documented commands that contain zPattern anywhere.
5011 ** Show complete text of all documented commands that match. */
5012 zPat = sqlite3_mprintf("%%%s%%", zPattern);
5013 shell_check_oom(zPat);
5014 for(i=0; i<ArraySize(azHelp); i++){
5015 if( azHelp[i][0]==',' ){
5016 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
5017 continue;
5019 if( azHelp[i][0]=='.' ) j = i;
5020 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
5021 sputf(out, "%s\n", azHelp[j]);
5022 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
5023 j++;
5024 sputf(out, "%s\n", azHelp[j]);
5026 i = j;
5027 n++;
5030 sqlite3_free(zPat);
5032 return n;
5035 /* Forward reference */
5036 static int process_input(ShellState *p);
5039 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
5040 ** and return a pointer to the buffer. The caller is responsible for freeing
5041 ** the memory.
5043 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
5044 ** read.
5046 ** For convenience, a nul-terminator byte is always appended to the data read
5047 ** from the file before the buffer is returned. This byte is not included in
5048 ** the final value of (*pnByte), if applicable.
5050 ** NULL is returned if any error is encountered. The final value of *pnByte
5051 ** is undefined in this case.
5053 static char *readFile(const char *zName, int *pnByte){
5054 FILE *in = fopen(zName, "rb");
5055 long nIn;
5056 size_t nRead;
5057 char *pBuf;
5058 int rc;
5059 if( in==0 ) return 0;
5060 rc = fseek(in, 0, SEEK_END);
5061 if( rc!=0 ){
5062 eputf("Error: '%s' not seekable\n", zName);
5063 fclose(in);
5064 return 0;
5066 nIn = ftell(in);
5067 rewind(in);
5068 pBuf = sqlite3_malloc64( nIn+1 );
5069 if( pBuf==0 ){
5070 eputz("Error: out of memory\n");
5071 fclose(in);
5072 return 0;
5074 nRead = fread(pBuf, nIn, 1, in);
5075 fclose(in);
5076 if( nRead!=1 ){
5077 sqlite3_free(pBuf);
5078 eputf("Error: cannot read '%s'\n", zName);
5079 return 0;
5081 pBuf[nIn] = 0;
5082 if( pnByte ) *pnByte = nIn;
5083 return pBuf;
5086 #if defined(SQLITE_ENABLE_SESSION)
5088 ** Close a single OpenSession object and release all of its associated
5089 ** resources.
5091 static void session_close(OpenSession *pSession){
5092 int i;
5093 sqlite3session_delete(pSession->p);
5094 sqlite3_free(pSession->zName);
5095 for(i=0; i<pSession->nFilter; i++){
5096 sqlite3_free(pSession->azFilter[i]);
5098 sqlite3_free(pSession->azFilter);
5099 memset(pSession, 0, sizeof(OpenSession));
5101 #endif
5104 ** Close all OpenSession objects and release all associated resources.
5106 #if defined(SQLITE_ENABLE_SESSION)
5107 static void session_close_all(ShellState *p, int i){
5108 int j;
5109 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
5110 for(j=0; j<pAuxDb->nSession; j++){
5111 session_close(&pAuxDb->aSession[j]);
5113 pAuxDb->nSession = 0;
5115 #else
5116 # define session_close_all(X,Y)
5117 #endif
5120 ** Implementation of the xFilter function for an open session. Omit
5121 ** any tables named by ".session filter" but let all other table through.
5123 #if defined(SQLITE_ENABLE_SESSION)
5124 static int session_filter(void *pCtx, const char *zTab){
5125 OpenSession *pSession = (OpenSession*)pCtx;
5126 int i;
5127 for(i=0; i<pSession->nFilter; i++){
5128 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
5130 return 1;
5132 #endif
5135 ** Try to deduce the type of file for zName based on its content. Return
5136 ** one of the SHELL_OPEN_* constants.
5138 ** If the file does not exist or is empty but its name looks like a ZIP
5139 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
5140 ** Otherwise, assume an ordinary database regardless of the filename if
5141 ** the type cannot be determined from content.
5143 int deduceDatabaseType(const char *zName, int dfltZip){
5144 FILE *f = fopen(zName, "rb");
5145 size_t n;
5146 int rc = SHELL_OPEN_UNSPEC;
5147 char zBuf[100];
5148 if( f==0 ){
5149 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5150 return SHELL_OPEN_ZIPFILE;
5151 }else{
5152 return SHELL_OPEN_NORMAL;
5155 n = fread(zBuf, 16, 1, f);
5156 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
5157 fclose(f);
5158 return SHELL_OPEN_NORMAL;
5160 fseek(f, -25, SEEK_END);
5161 n = fread(zBuf, 25, 1, f);
5162 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
5163 rc = SHELL_OPEN_APPENDVFS;
5164 }else{
5165 fseek(f, -22, SEEK_END);
5166 n = fread(zBuf, 22, 1, f);
5167 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
5168 && zBuf[3]==0x06 ){
5169 rc = SHELL_OPEN_ZIPFILE;
5170 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5171 rc = SHELL_OPEN_ZIPFILE;
5174 fclose(f);
5175 return rc;
5178 #ifndef SQLITE_OMIT_DESERIALIZE
5180 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5181 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5182 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5184 static unsigned char *readHexDb(ShellState *p, int *pnData){
5185 unsigned char *a = 0;
5186 int nLine;
5187 int n = 0;
5188 int pgsz = 0;
5189 int iOffset = 0;
5190 int j, k;
5191 int rc;
5192 FILE *in;
5193 const char *zDbFilename = p->pAuxDb->zDbFilename;
5194 unsigned int x[16];
5195 char zLine[1000];
5196 if( zDbFilename ){
5197 in = fopen(zDbFilename, "r");
5198 if( in==0 ){
5199 eputf("cannot open \"%s\" for reading\n", zDbFilename);
5200 return 0;
5202 nLine = 0;
5203 }else{
5204 in = p->in;
5205 nLine = p->lineno;
5206 if( in==0 ) in = stdin;
5208 *pnData = 0;
5209 nLine++;
5210 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
5211 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
5212 if( rc!=2 ) goto readHexDb_error;
5213 if( n<0 ) goto readHexDb_error;
5214 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
5215 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
5216 a = sqlite3_malloc( n ? n : 1 );
5217 shell_check_oom(a);
5218 memset(a, 0, n);
5219 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
5220 eputz("invalid pagesize\n");
5221 goto readHexDb_error;
5223 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
5224 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
5225 if( rc==2 ){
5226 iOffset = k;
5227 continue;
5229 if( cli_strncmp(zLine, "| end ", 6)==0 ){
5230 break;
5232 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5233 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
5234 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
5235 if( rc==17 ){
5236 k = iOffset+j;
5237 if( k+16<=n && k>=0 ){
5238 int ii;
5239 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
5243 *pnData = n;
5244 if( in!=p->in ){
5245 fclose(in);
5246 }else{
5247 p->lineno = nLine;
5249 return a;
5251 readHexDb_error:
5252 if( in!=p->in ){
5253 fclose(in);
5254 }else{
5255 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
5256 nLine++;
5257 if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
5259 p->lineno = nLine;
5261 sqlite3_free(a);
5262 eputf("Error on line %d of --hexdb input\n", nLine);
5263 return 0;
5265 #endif /* SQLITE_OMIT_DESERIALIZE */
5268 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5270 static void shellUSleepFunc(
5271 sqlite3_context *context,
5272 int argcUnused,
5273 sqlite3_value **argv
5275 int sleep = sqlite3_value_int(argv[0]);
5276 (void)argcUnused;
5277 sqlite3_sleep(sleep/1000);
5278 sqlite3_result_int(context, sleep);
5281 /* Flags for open_db().
5283 ** The default behavior of open_db() is to exit(1) if the database fails to
5284 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5285 ** but still returns without calling exit.
5287 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5288 ** ZIP archive if the file does not exist or is empty and its name matches
5289 ** the *.zip pattern.
5291 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5292 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5295 ** Make sure the database is open. If it is not, then open it. If
5296 ** the database fails to open, print an error message and exit.
5298 static void open_db(ShellState *p, int openFlags){
5299 if( p->db==0 ){
5300 const char *zDbFilename = p->pAuxDb->zDbFilename;
5301 if( p->openMode==SHELL_OPEN_UNSPEC ){
5302 if( zDbFilename==0 || zDbFilename[0]==0 ){
5303 p->openMode = SHELL_OPEN_NORMAL;
5304 }else{
5305 p->openMode = (u8)deduceDatabaseType(zDbFilename,
5306 (openFlags & OPEN_DB_ZIPFILE)!=0);
5309 switch( p->openMode ){
5310 case SHELL_OPEN_APPENDVFS: {
5311 sqlite3_open_v2(zDbFilename, &p->db,
5312 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5313 break;
5315 case SHELL_OPEN_HEXDB:
5316 case SHELL_OPEN_DESERIALIZE: {
5317 sqlite3_open(0, &p->db);
5318 break;
5320 case SHELL_OPEN_ZIPFILE: {
5321 sqlite3_open(":memory:", &p->db);
5322 break;
5324 case SHELL_OPEN_READONLY: {
5325 sqlite3_open_v2(zDbFilename, &p->db,
5326 SQLITE_OPEN_READONLY|p->openFlags, 0);
5327 break;
5329 case SHELL_OPEN_UNSPEC:
5330 case SHELL_OPEN_NORMAL: {
5331 sqlite3_open_v2(zDbFilename, &p->db,
5332 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5333 break;
5336 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5337 eputf("Error: unable to open database \"%s\": %s\n",
5338 zDbFilename, sqlite3_errmsg(p->db));
5339 if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
5340 exit(1);
5342 sqlite3_close(p->db);
5343 sqlite3_open(":memory:", &p->db);
5344 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5345 eputz("Also: unable to open substitute in-memory database.\n");
5346 exit(1);
5347 }else{
5348 eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
5349 zDbFilename);
5352 globalDb = p->db;
5353 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
5355 /* Reflect the use or absence of --unsafe-testing invocation. */
5357 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
5358 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
5359 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
5362 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5363 sqlite3_enable_load_extension(p->db, 1);
5364 #endif
5365 sqlite3_shathree_init(p->db, 0, 0);
5366 sqlite3_uint_init(p->db, 0, 0);
5367 sqlite3_decimal_init(p->db, 0, 0);
5368 sqlite3_base64_init(p->db, 0, 0);
5369 sqlite3_base85_init(p->db, 0, 0);
5370 sqlite3_regexp_init(p->db, 0, 0);
5371 sqlite3_ieee_init(p->db, 0, 0);
5372 sqlite3_series_init(p->db, 0, 0);
5373 #ifndef SQLITE_SHELL_FIDDLE
5374 sqlite3_fileio_init(p->db, 0, 0);
5375 sqlite3_completion_init(p->db, 0, 0);
5376 #endif
5377 #ifdef SQLITE_HAVE_ZLIB
5378 if( !p->bSafeModePersist ){
5379 sqlite3_zipfile_init(p->db, 0, 0);
5380 sqlite3_sqlar_init(p->db, 0, 0);
5382 #endif
5383 #ifdef SQLITE_SHELL_EXTFUNCS
5384 /* Create a preprocessing mechanism for extensions to make
5385 * their own provisions for being built into the shell.
5386 * This is a short-span macro. See further below for usage.
5388 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5389 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5390 /* Let custom-included extensions get their ..._init() called.
5391 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5392 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5393 * initialization routine to be called.
5396 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
5397 /* Let custom-included extensions expose their functionality.
5398 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5399 * the SQL functions, virtual tables, collating sequences or
5400 * VFS's implemented by the extension to be registered.
5402 if( irc==SQLITE_OK
5403 || irc==SQLITE_OK_LOAD_PERMANENTLY ){
5404 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
5406 #undef SHELL_SUB_MACRO
5407 #undef SHELL_SUBMACRO
5409 #endif
5411 sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
5412 shellStrtod, 0, 0);
5413 sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
5414 shellDtostr, 0, 0);
5415 sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
5416 shellDtostr, 0, 0);
5417 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5418 shellAddSchemaName, 0, 0);
5419 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5420 shellModuleSchema, 0, 0);
5421 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5422 shellPutsFunc, 0, 0);
5423 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5424 shellUSleepFunc, 0, 0);
5425 #ifndef SQLITE_NOHAVE_SYSTEM
5426 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5427 editFunc, 0, 0);
5428 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5429 editFunc, 0, 0);
5430 #endif
5432 if( p->openMode==SHELL_OPEN_ZIPFILE ){
5433 char *zSql = sqlite3_mprintf(
5434 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5435 shell_check_oom(zSql);
5436 sqlite3_exec(p->db, zSql, 0, 0, 0);
5437 sqlite3_free(zSql);
5439 #ifndef SQLITE_OMIT_DESERIALIZE
5440 else
5441 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5442 int rc;
5443 int nData = 0;
5444 unsigned char *aData;
5445 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5446 aData = (unsigned char*)readFile(zDbFilename, &nData);
5447 }else{
5448 aData = readHexDb(p, &nData);
5450 if( aData==0 ){
5451 return;
5453 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5454 SQLITE_DESERIALIZE_RESIZEABLE |
5455 SQLITE_DESERIALIZE_FREEONCLOSE);
5456 if( rc ){
5457 eputf("Error: sqlite3_deserialize() returns %d\n", rc);
5459 if( p->szMax>0 ){
5460 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5463 #endif
5465 if( p->db!=0 ){
5466 if( p->bSafeModePersist ){
5467 sqlite3_set_authorizer(p->db, safeModeAuth, p);
5469 sqlite3_db_config(
5470 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
5476 ** Attempt to close the database connection. Report errors.
5478 void close_db(sqlite3 *db){
5479 int rc = sqlite3_close(db);
5480 if( rc ){
5481 eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
5485 #if HAVE_READLINE || HAVE_EDITLINE
5487 ** Readline completion callbacks
5489 static char *readline_completion_generator(const char *text, int state){
5490 static sqlite3_stmt *pStmt = 0;
5491 char *zRet;
5492 if( state==0 ){
5493 char *zSql;
5494 sqlite3_finalize(pStmt);
5495 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5496 " FROM completion(%Q) ORDER BY 1", text);
5497 shell_check_oom(zSql);
5498 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5499 sqlite3_free(zSql);
5501 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5502 const char *z = (const char*)sqlite3_column_text(pStmt,0);
5503 zRet = z ? strdup(z) : 0;
5504 }else{
5505 sqlite3_finalize(pStmt);
5506 pStmt = 0;
5507 zRet = 0;
5509 return zRet;
5511 static char **readline_completion(const char *zText, int iStart, int iEnd){
5512 (void)iStart;
5513 (void)iEnd;
5514 rl_attempted_completion_over = 1;
5515 return rl_completion_matches(zText, readline_completion_generator);
5518 #elif HAVE_LINENOISE
5520 ** Linenoise completion callback
5522 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5523 i64 nLine = strlen(zLine);
5524 i64 i, iStart;
5525 sqlite3_stmt *pStmt = 0;
5526 char *zSql;
5527 char zBuf[1000];
5529 if( nLine>(i64)sizeof(zBuf)-30 ) return;
5530 if( zLine[0]=='.' || zLine[0]=='#') return;
5531 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5532 if( i==nLine-1 ) return;
5533 iStart = i+1;
5534 memcpy(zBuf, zLine, iStart);
5535 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5536 " FROM completion(%Q,%Q) ORDER BY 1",
5537 &zLine[iStart], zLine);
5538 shell_check_oom(zSql);
5539 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5540 sqlite3_free(zSql);
5541 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5542 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5543 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5544 int nCompletion = sqlite3_column_bytes(pStmt, 0);
5545 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
5546 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5547 linenoiseAddCompletion(lc, zBuf);
5550 sqlite3_finalize(pStmt);
5552 #endif
5555 ** Do C-language style dequoting.
5557 ** \a -> alarm
5558 ** \b -> backspace
5559 ** \t -> tab
5560 ** \n -> newline
5561 ** \v -> vertical tab
5562 ** \f -> form feed
5563 ** \r -> carriage return
5564 ** \s -> space
5565 ** \" -> "
5566 ** \' -> '
5567 ** \\ -> backslash
5568 ** \NNN -> ascii character NNN in octal
5569 ** \xHH -> ascii character HH in hexadecimal
5571 static void resolve_backslashes(char *z){
5572 int i, j;
5573 char c;
5574 while( *z && *z!='\\' ) z++;
5575 for(i=j=0; (c = z[i])!=0; i++, j++){
5576 if( c=='\\' && z[i+1]!=0 ){
5577 c = z[++i];
5578 if( c=='a' ){
5579 c = '\a';
5580 }else if( c=='b' ){
5581 c = '\b';
5582 }else if( c=='t' ){
5583 c = '\t';
5584 }else if( c=='n' ){
5585 c = '\n';
5586 }else if( c=='v' ){
5587 c = '\v';
5588 }else if( c=='f' ){
5589 c = '\f';
5590 }else if( c=='r' ){
5591 c = '\r';
5592 }else if( c=='"' ){
5593 c = '"';
5594 }else if( c=='\'' ){
5595 c = '\'';
5596 }else if( c=='\\' ){
5597 c = '\\';
5598 }else if( c=='x' ){
5599 int nhd = 0, hdv;
5600 u8 hv = 0;
5601 while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
5602 hv = (u8)((hv<<4)|hdv);
5603 ++nhd;
5605 i += nhd;
5606 c = (u8)hv;
5607 }else if( c>='0' && c<='7' ){
5608 c -= '0';
5609 if( z[i+1]>='0' && z[i+1]<='7' ){
5610 i++;
5611 c = (c<<3) + z[i] - '0';
5612 if( z[i+1]>='0' && z[i+1]<='7' ){
5613 i++;
5614 c = (c<<3) + z[i] - '0';
5619 z[j] = c;
5621 if( j<i ) z[j] = 0;
5625 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5626 ** for TRUE and FALSE. Return the integer value if appropriate.
5628 static int booleanValue(const char *zArg){
5629 int i;
5630 if( zArg[0]=='0' && zArg[1]=='x' ){
5631 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5632 }else{
5633 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5635 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5636 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5637 return 1;
5639 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5640 return 0;
5642 eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
5643 return 0;
5647 ** Set or clear a shell flag according to a boolean value.
5649 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5650 if( booleanValue(zArg) ){
5651 ShellSetFlag(p, mFlag);
5652 }else{
5653 ShellClearFlag(p, mFlag);
5658 ** Close an output file, assuming it is not stderr or stdout
5660 static void output_file_close(FILE *f){
5661 if( f && f!=stdout && f!=stderr ) fclose(f);
5665 ** Try to open an output file. The names "stdout" and "stderr" are
5666 ** recognized and do the right thing. NULL is returned if the output
5667 ** filename is "off".
5669 static FILE *output_file_open(const char *zFile, int bTextMode){
5670 FILE *f;
5671 if( cli_strcmp(zFile,"stdout")==0 ){
5672 f = stdout;
5673 }else if( cli_strcmp(zFile, "stderr")==0 ){
5674 f = stderr;
5675 }else if( cli_strcmp(zFile, "off")==0 ){
5676 f = 0;
5677 }else{
5678 f = fopen(zFile, bTextMode ? "w" : "wb");
5679 if( f==0 ){
5680 eputf("Error: cannot open \"%s\"\n", zFile);
5683 return f;
5686 #ifndef SQLITE_OMIT_TRACE
5688 ** A routine for handling output from sqlite3_trace().
5690 static int sql_trace_callback(
5691 unsigned mType, /* The trace type */
5692 void *pArg, /* The ShellState pointer */
5693 void *pP, /* Usually a pointer to sqlite_stmt */
5694 void *pX /* Auxiliary output */
5696 ShellState *p = (ShellState*)pArg;
5697 sqlite3_stmt *pStmt;
5698 const char *zSql;
5699 i64 nSql;
5700 if( p->traceOut==0 ) return 0;
5701 if( mType==SQLITE_TRACE_CLOSE ){
5702 sputz(p->traceOut, "-- closing database connection\n");
5703 return 0;
5705 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
5706 zSql = (const char*)pX;
5707 }else{
5708 pStmt = (sqlite3_stmt*)pP;
5709 switch( p->eTraceType ){
5710 case SHELL_TRACE_EXPANDED: {
5711 zSql = sqlite3_expanded_sql(pStmt);
5712 break;
5714 #ifdef SQLITE_ENABLE_NORMALIZE
5715 case SHELL_TRACE_NORMALIZED: {
5716 zSql = sqlite3_normalized_sql(pStmt);
5717 break;
5719 #endif
5720 default: {
5721 zSql = sqlite3_sql(pStmt);
5722 break;
5726 if( zSql==0 ) return 0;
5727 nSql = strlen(zSql);
5728 if( nSql>1000000000 ) nSql = 1000000000;
5729 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5730 switch( mType ){
5731 case SQLITE_TRACE_ROW:
5732 case SQLITE_TRACE_STMT: {
5733 sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5734 break;
5736 case SQLITE_TRACE_PROFILE: {
5737 sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
5738 sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5739 break;
5742 return 0;
5744 #endif
5747 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5748 ** a useful spot to set a debugger breakpoint.
5750 ** This routine does not do anything practical. The code are there simply
5751 ** to prevent the compiler from optimizing this routine out.
5753 static void test_breakpoint(void){
5754 static unsigned int nCall = 0;
5755 if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
5759 ** An object used to read a CSV and other files for import.
5761 typedef struct ImportCtx ImportCtx;
5762 struct ImportCtx {
5763 const char *zFile; /* Name of the input file */
5764 FILE *in; /* Read the CSV text from this input stream */
5765 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
5766 char *z; /* Accumulated text for a field */
5767 int n; /* Number of bytes in z */
5768 int nAlloc; /* Space allocated for z[] */
5769 int nLine; /* Current line number */
5770 int nRow; /* Number of rows imported */
5771 int nErr; /* Number of errors encountered */
5772 int bNotFirst; /* True if one or more bytes already read */
5773 int cTerm; /* Character that terminated the most recent field */
5774 int cColSep; /* The column separator character. (Usually ",") */
5775 int cRowSep; /* The row separator character. (Usually "\n") */
5778 /* Clean up resourced used by an ImportCtx */
5779 static void import_cleanup(ImportCtx *p){
5780 if( p->in!=0 && p->xCloser!=0 ){
5781 p->xCloser(p->in);
5782 p->in = 0;
5784 sqlite3_free(p->z);
5785 p->z = 0;
5788 /* Append a single byte to z[] */
5789 static void import_append_char(ImportCtx *p, int c){
5790 if( p->n+1>=p->nAlloc ){
5791 p->nAlloc += p->nAlloc + 100;
5792 p->z = sqlite3_realloc64(p->z, p->nAlloc);
5793 shell_check_oom(p->z);
5795 p->z[p->n++] = (char)c;
5798 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5799 ** with the option of having a separator other than ",".
5801 ** + Input comes from p->in.
5802 ** + Store results in p->z of length p->n. Space to hold p->z comes
5803 ** from sqlite3_malloc64().
5804 ** + Use p->cSep as the column separator. The default is ",".
5805 ** + Use p->rSep as the row separator. The default is "\n".
5806 ** + Keep track of the line number in p->nLine.
5807 ** + Store the character that terminates the field in p->cTerm. Store
5808 ** EOF on end-of-file.
5809 ** + Report syntax errors on stderr
5811 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5812 int c;
5813 int cSep = (u8)p->cColSep;
5814 int rSep = (u8)p->cRowSep;
5815 p->n = 0;
5816 c = fgetc(p->in);
5817 if( c==EOF || seenInterrupt ){
5818 p->cTerm = EOF;
5819 return 0;
5821 if( c=='"' ){
5822 int pc, ppc;
5823 int startLine = p->nLine;
5824 int cQuote = c;
5825 pc = ppc = 0;
5826 while( 1 ){
5827 c = fgetc(p->in);
5828 if( c==rSep ) p->nLine++;
5829 if( c==cQuote ){
5830 if( pc==cQuote ){
5831 pc = 0;
5832 continue;
5835 if( (c==cSep && pc==cQuote)
5836 || (c==rSep && pc==cQuote)
5837 || (c==rSep && pc=='\r' && ppc==cQuote)
5838 || (c==EOF && pc==cQuote)
5840 do{ p->n--; }while( p->z[p->n]!=cQuote );
5841 p->cTerm = c;
5842 break;
5844 if( pc==cQuote && c!='\r' ){
5845 eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
5847 if( c==EOF ){
5848 eputf("%s:%d: unterminated %c-quoted field\n",
5849 p->zFile, startLine, cQuote);
5850 p->cTerm = c;
5851 break;
5853 import_append_char(p, c);
5854 ppc = pc;
5855 pc = c;
5857 }else{
5858 /* If this is the first field being parsed and it begins with the
5859 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5860 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5861 import_append_char(p, c);
5862 c = fgetc(p->in);
5863 if( (c&0xff)==0xbb ){
5864 import_append_char(p, c);
5865 c = fgetc(p->in);
5866 if( (c&0xff)==0xbf ){
5867 p->bNotFirst = 1;
5868 p->n = 0;
5869 return csv_read_one_field(p);
5873 while( c!=EOF && c!=cSep && c!=rSep ){
5874 import_append_char(p, c);
5875 c = fgetc(p->in);
5877 if( c==rSep ){
5878 p->nLine++;
5879 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5881 p->cTerm = c;
5883 if( p->z ) p->z[p->n] = 0;
5884 p->bNotFirst = 1;
5885 return p->z;
5888 /* Read a single field of ASCII delimited text.
5890 ** + Input comes from p->in.
5891 ** + Store results in p->z of length p->n. Space to hold p->z comes
5892 ** from sqlite3_malloc64().
5893 ** + Use p->cSep as the column separator. The default is "\x1F".
5894 ** + Use p->rSep as the row separator. The default is "\x1E".
5895 ** + Keep track of the row number in p->nLine.
5896 ** + Store the character that terminates the field in p->cTerm. Store
5897 ** EOF on end-of-file.
5898 ** + Report syntax errors on stderr
5900 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5901 int c;
5902 int cSep = (u8)p->cColSep;
5903 int rSep = (u8)p->cRowSep;
5904 p->n = 0;
5905 c = fgetc(p->in);
5906 if( c==EOF || seenInterrupt ){
5907 p->cTerm = EOF;
5908 return 0;
5910 while( c!=EOF && c!=cSep && c!=rSep ){
5911 import_append_char(p, c);
5912 c = fgetc(p->in);
5914 if( c==rSep ){
5915 p->nLine++;
5917 p->cTerm = c;
5918 if( p->z ) p->z[p->n] = 0;
5919 return p->z;
5923 ** Try to transfer data for table zTable. If an error is seen while
5924 ** moving forward, try to go backwards. The backwards movement won't
5925 ** work for WITHOUT ROWID tables.
5927 static void tryToCloneData(
5928 ShellState *p,
5929 sqlite3 *newDb,
5930 const char *zTable
5932 sqlite3_stmt *pQuery = 0;
5933 sqlite3_stmt *pInsert = 0;
5934 char *zQuery = 0;
5935 char *zInsert = 0;
5936 int rc;
5937 int i, j, n;
5938 int nTable = strlen30(zTable);
5939 int k = 0;
5940 int cnt = 0;
5941 const int spinRate = 10000;
5943 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5944 shell_check_oom(zQuery);
5945 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5946 if( rc ){
5947 eputf("Error %d: %s on [%s]\n",
5948 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
5949 goto end_data_xfer;
5951 n = sqlite3_column_count(pQuery);
5952 zInsert = sqlite3_malloc64(200 + nTable + n*3);
5953 shell_check_oom(zInsert);
5954 sqlite3_snprintf(200+nTable,zInsert,
5955 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5956 i = strlen30(zInsert);
5957 for(j=1; j<n; j++){
5958 memcpy(zInsert+i, ",?", 2);
5959 i += 2;
5961 memcpy(zInsert+i, ");", 3);
5962 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5963 if( rc ){
5964 eputf("Error %d: %s on [%s]\n",
5965 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
5966 goto end_data_xfer;
5968 for(k=0; k<2; k++){
5969 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5970 for(i=0; i<n; i++){
5971 switch( sqlite3_column_type(pQuery, i) ){
5972 case SQLITE_NULL: {
5973 sqlite3_bind_null(pInsert, i+1);
5974 break;
5976 case SQLITE_INTEGER: {
5977 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5978 break;
5980 case SQLITE_FLOAT: {
5981 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5982 break;
5984 case SQLITE_TEXT: {
5985 sqlite3_bind_text(pInsert, i+1,
5986 (const char*)sqlite3_column_text(pQuery,i),
5987 -1, SQLITE_STATIC);
5988 break;
5990 case SQLITE_BLOB: {
5991 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5992 sqlite3_column_bytes(pQuery,i),
5993 SQLITE_STATIC);
5994 break;
5997 } /* End for */
5998 rc = sqlite3_step(pInsert);
5999 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
6000 eputf("Error %d: %s\n",
6001 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
6003 sqlite3_reset(pInsert);
6004 cnt++;
6005 if( (cnt%spinRate)==0 ){
6006 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
6007 fflush(stdout);
6009 } /* End while */
6010 if( rc==SQLITE_DONE ) break;
6011 sqlite3_finalize(pQuery);
6012 sqlite3_free(zQuery);
6013 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
6014 zTable);
6015 shell_check_oom(zQuery);
6016 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6017 if( rc ){
6018 eputf("Warning: cannot step \"%s\" backwards", zTable);
6019 break;
6021 } /* End for(k=0...) */
6023 end_data_xfer:
6024 sqlite3_finalize(pQuery);
6025 sqlite3_finalize(pInsert);
6026 sqlite3_free(zQuery);
6027 sqlite3_free(zInsert);
6032 ** Try to transfer all rows of the schema that match zWhere. For
6033 ** each row, invoke xForEach() on the object defined by that row.
6034 ** If an error is encountered while moving forward through the
6035 ** sqlite_schema table, try again moving backwards.
6037 static void tryToCloneSchema(
6038 ShellState *p,
6039 sqlite3 *newDb,
6040 const char *zWhere,
6041 void (*xForEach)(ShellState*,sqlite3*,const char*)
6043 sqlite3_stmt *pQuery = 0;
6044 char *zQuery = 0;
6045 int rc;
6046 const unsigned char *zName;
6047 const unsigned char *zSql;
6048 char *zErrMsg = 0;
6050 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6051 " WHERE %s ORDER BY rowid ASC", zWhere);
6052 shell_check_oom(zQuery);
6053 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6054 if( rc ){
6055 eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
6056 sqlite3_errmsg(p->db), zQuery);
6057 goto end_schema_xfer;
6059 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
6060 zName = sqlite3_column_text(pQuery, 0);
6061 zSql = sqlite3_column_text(pQuery, 1);
6062 if( zName==0 || zSql==0 ) continue;
6063 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
6064 sputf(stdout, "%s... ", zName); fflush(stdout);
6065 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6066 if( zErrMsg ){
6067 eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6068 sqlite3_free(zErrMsg);
6069 zErrMsg = 0;
6072 if( xForEach ){
6073 xForEach(p, newDb, (const char*)zName);
6075 sputz(stdout, "done\n");
6077 if( rc!=SQLITE_DONE ){
6078 sqlite3_finalize(pQuery);
6079 sqlite3_free(zQuery);
6080 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6081 " WHERE %s ORDER BY rowid DESC", zWhere);
6082 shell_check_oom(zQuery);
6083 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6084 if( rc ){
6085 eputf("Error: (%d) %s on [%s]\n",
6086 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
6087 goto end_schema_xfer;
6089 while( sqlite3_step(pQuery)==SQLITE_ROW ){
6090 zName = sqlite3_column_text(pQuery, 0);
6091 zSql = sqlite3_column_text(pQuery, 1);
6092 if( zName==0 || zSql==0 ) continue;
6093 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
6094 sputf(stdout, "%s... ", zName); fflush(stdout);
6095 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6096 if( zErrMsg ){
6097 eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6098 sqlite3_free(zErrMsg);
6099 zErrMsg = 0;
6101 if( xForEach ){
6102 xForEach(p, newDb, (const char*)zName);
6104 sputz(stdout, "done\n");
6107 end_schema_xfer:
6108 sqlite3_finalize(pQuery);
6109 sqlite3_free(zQuery);
6113 ** Open a new database file named "zNewDb". Try to recover as much information
6114 ** as possible out of the main database (which might be corrupt) and write it
6115 ** into zNewDb.
6117 static void tryToClone(ShellState *p, const char *zNewDb){
6118 int rc;
6119 sqlite3 *newDb = 0;
6120 if( access(zNewDb,0)==0 ){
6121 eputf("File \"%s\" already exists.\n", zNewDb);
6122 return;
6124 rc = sqlite3_open(zNewDb, &newDb);
6125 if( rc ){
6126 eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
6127 }else{
6128 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
6129 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
6130 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
6131 tryToCloneSchema(p, newDb, "type!='table'", 0);
6132 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
6133 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6135 close_db(newDb);
6138 #ifndef SQLITE_SHELL_FIDDLE
6140 ** Change the output stream (file or pipe or console) to something else.
6142 static void output_redir(ShellState *p, FILE *pfNew){
6143 if( p->out != stdout ) eputz("Output already redirected.\n");
6144 else{
6145 p->out = pfNew;
6146 setOutputStream(pfNew);
6151 ** Change the output file back to stdout.
6153 ** If the p->doXdgOpen flag is set, that means the output was being
6154 ** redirected to a temporary file named by p->zTempFile. In that case,
6155 ** launch start/open/xdg-open on that temporary file.
6157 static void output_reset(ShellState *p){
6158 if( p->outfile[0]=='|' ){
6159 #ifndef SQLITE_OMIT_POPEN
6160 pclose(p->out);
6161 #endif
6162 }else{
6163 output_file_close(p->out);
6164 #ifndef SQLITE_NOHAVE_SYSTEM
6165 if( p->doXdgOpen ){
6166 const char *zXdgOpenCmd =
6167 #if defined(_WIN32)
6168 "start";
6169 #elif defined(__APPLE__)
6170 "open";
6171 #else
6172 "xdg-open";
6173 #endif
6174 char *zCmd;
6175 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
6176 if( system(zCmd) ){
6177 eputf("Failed: [%s]\n", zCmd);
6178 }else{
6179 /* Give the start/open/xdg-open command some time to get
6180 ** going before we continue, and potential delete the
6181 ** p->zTempFile data file out from under it */
6182 sqlite3_sleep(2000);
6184 sqlite3_free(zCmd);
6185 outputModePop(p);
6186 p->doXdgOpen = 0;
6188 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6190 p->outfile[0] = 0;
6191 p->out = stdout;
6192 setOutputStream(stdout);
6194 #else
6195 # define output_redir(SS,pfO)
6196 # define output_reset(SS)
6197 #endif
6200 ** Run an SQL command and return the single integer result.
6202 static int db_int(sqlite3 *db, const char *zSql){
6203 sqlite3_stmt *pStmt;
6204 int res = 0;
6205 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
6206 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
6207 res = sqlite3_column_int(pStmt,0);
6209 sqlite3_finalize(pStmt);
6210 return res;
6213 #if SQLITE_SHELL_HAVE_RECOVER
6215 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6217 static unsigned int get2byteInt(unsigned char *a){
6218 return (a[0]<<8) + a[1];
6220 static unsigned int get4byteInt(unsigned char *a){
6221 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
6225 ** Implementation of the ".dbinfo" command.
6227 ** Return 1 on error, 2 to exit, and 0 otherwise.
6229 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
6230 static const struct { const char *zName; int ofst; } aField[] = {
6231 { "file change counter:", 24 },
6232 { "database page count:", 28 },
6233 { "freelist page count:", 36 },
6234 { "schema cookie:", 40 },
6235 { "schema format:", 44 },
6236 { "default cache size:", 48 },
6237 { "autovacuum top root:", 52 },
6238 { "incremental vacuum:", 64 },
6239 { "text encoding:", 56 },
6240 { "user version:", 60 },
6241 { "application id:", 68 },
6242 { "software version:", 96 },
6244 static const struct { const char *zName; const char *zSql; } aQuery[] = {
6245 { "number of tables:",
6246 "SELECT count(*) FROM %s WHERE type='table'" },
6247 { "number of indexes:",
6248 "SELECT count(*) FROM %s WHERE type='index'" },
6249 { "number of triggers:",
6250 "SELECT count(*) FROM %s WHERE type='trigger'" },
6251 { "number of views:",
6252 "SELECT count(*) FROM %s WHERE type='view'" },
6253 { "schema size:",
6254 "SELECT total(length(sql)) FROM %s" },
6256 int i, rc;
6257 unsigned iDataVersion;
6258 char *zSchemaTab;
6259 char *zDb = nArg>=2 ? azArg[1] : "main";
6260 sqlite3_stmt *pStmt = 0;
6261 unsigned char aHdr[100];
6262 open_db(p, 0);
6263 if( p->db==0 ) return 1;
6264 rc = sqlite3_prepare_v2(p->db,
6265 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6266 -1, &pStmt, 0);
6267 if( rc ){
6268 eputf("error: %s\n", sqlite3_errmsg(p->db));
6269 sqlite3_finalize(pStmt);
6270 return 1;
6272 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
6273 if( sqlite3_step(pStmt)==SQLITE_ROW
6274 && sqlite3_column_bytes(pStmt,0)>100
6276 const u8 *pb = sqlite3_column_blob(pStmt,0);
6277 shell_check_oom(pb);
6278 memcpy(aHdr, pb, 100);
6279 sqlite3_finalize(pStmt);
6280 }else{
6281 eputz("unable to read database header\n");
6282 sqlite3_finalize(pStmt);
6283 return 1;
6285 i = get2byteInt(aHdr+16);
6286 if( i==1 ) i = 65536;
6287 oputf("%-20s %d\n", "database page size:", i);
6288 oputf("%-20s %d\n", "write format:", aHdr[18]);
6289 oputf("%-20s %d\n", "read format:", aHdr[19]);
6290 oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
6291 for(i=0; i<ArraySize(aField); i++){
6292 int ofst = aField[i].ofst;
6293 unsigned int val = get4byteInt(aHdr + ofst);
6294 oputf("%-20s %u", aField[i].zName, val);
6295 switch( ofst ){
6296 case 56: {
6297 if( val==1 ) oputz(" (utf8)");
6298 if( val==2 ) oputz(" (utf16le)");
6299 if( val==3 ) oputz(" (utf16be)");
6302 oputz("\n");
6304 if( zDb==0 ){
6305 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
6306 }else if( cli_strcmp(zDb,"temp")==0 ){
6307 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
6308 }else{
6309 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
6311 for(i=0; i<ArraySize(aQuery); i++){
6312 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
6313 int val = db_int(p->db, zSql);
6314 sqlite3_free(zSql);
6315 oputf("%-20s %d\n", aQuery[i].zName, val);
6317 sqlite3_free(zSchemaTab);
6318 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
6319 oputf("%-20s %u\n", "data version", iDataVersion);
6320 return 0;
6322 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6325 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6327 static int shellDatabaseError(sqlite3 *db){
6328 const char *zErr = sqlite3_errmsg(db);
6329 eputf("Error: %s\n", zErr);
6330 return 1;
6334 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6335 ** if they match and FALSE (0) if they do not match.
6337 ** Globbing rules:
6339 ** '*' Matches any sequence of zero or more characters.
6341 ** '?' Matches exactly one character.
6343 ** [...] Matches one character from the enclosed list of
6344 ** characters.
6346 ** [^...] Matches one character not in the enclosed list.
6348 ** '#' Matches any sequence of one or more digits with an
6349 ** optional + or - sign in front
6351 ** ' ' Any span of whitespace matches any other span of
6352 ** whitespace.
6354 ** Extra whitespace at the end of z[] is ignored.
6356 static int testcase_glob(const char *zGlob, const char *z){
6357 int c, c2;
6358 int invert;
6359 int seen;
6361 while( (c = (*(zGlob++)))!=0 ){
6362 if( IsSpace(c) ){
6363 if( !IsSpace(*z) ) return 0;
6364 while( IsSpace(*zGlob) ) zGlob++;
6365 while( IsSpace(*z) ) z++;
6366 }else if( c=='*' ){
6367 while( (c=(*(zGlob++))) == '*' || c=='?' ){
6368 if( c=='?' && (*(z++))==0 ) return 0;
6370 if( c==0 ){
6371 return 1;
6372 }else if( c=='[' ){
6373 while( *z && testcase_glob(zGlob-1,z)==0 ){
6374 z++;
6376 return (*z)!=0;
6378 while( (c2 = (*(z++)))!=0 ){
6379 while( c2!=c ){
6380 c2 = *(z++);
6381 if( c2==0 ) return 0;
6383 if( testcase_glob(zGlob,z) ) return 1;
6385 return 0;
6386 }else if( c=='?' ){
6387 if( (*(z++))==0 ) return 0;
6388 }else if( c=='[' ){
6389 int prior_c = 0;
6390 seen = 0;
6391 invert = 0;
6392 c = *(z++);
6393 if( c==0 ) return 0;
6394 c2 = *(zGlob++);
6395 if( c2=='^' ){
6396 invert = 1;
6397 c2 = *(zGlob++);
6399 if( c2==']' ){
6400 if( c==']' ) seen = 1;
6401 c2 = *(zGlob++);
6403 while( c2 && c2!=']' ){
6404 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6405 c2 = *(zGlob++);
6406 if( c>=prior_c && c<=c2 ) seen = 1;
6407 prior_c = 0;
6408 }else{
6409 if( c==c2 ){
6410 seen = 1;
6412 prior_c = c2;
6414 c2 = *(zGlob++);
6416 if( c2==0 || (seen ^ invert)==0 ) return 0;
6417 }else if( c=='#' ){
6418 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6419 if( !IsDigit(z[0]) ) return 0;
6420 z++;
6421 while( IsDigit(z[0]) ){ z++; }
6422 }else{
6423 if( c!=(*(z++)) ) return 0;
6426 while( IsSpace(*z) ){ z++; }
6427 return *z==0;
6432 ** Compare the string as a command-line option with either one or two
6433 ** initial "-" characters.
6435 static int optionMatch(const char *zStr, const char *zOpt){
6436 if( zStr[0]!='-' ) return 0;
6437 zStr++;
6438 if( zStr[0]=='-' ) zStr++;
6439 return cli_strcmp(zStr, zOpt)==0;
6443 ** Delete a file.
6445 int shellDeleteFile(const char *zFilename){
6446 int rc;
6447 #ifdef _WIN32
6448 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6449 rc = _wunlink(z);
6450 sqlite3_free(z);
6451 #else
6452 rc = unlink(zFilename);
6453 #endif
6454 return rc;
6458 ** Try to delete the temporary file (if there is one) and free the
6459 ** memory used to hold the name of the temp file.
6461 static void clearTempFile(ShellState *p){
6462 if( p->zTempFile==0 ) return;
6463 if( p->doXdgOpen ) return;
6464 if( shellDeleteFile(p->zTempFile) ) return;
6465 sqlite3_free(p->zTempFile);
6466 p->zTempFile = 0;
6470 ** Create a new temp file name with the given suffix.
6472 static void newTempFile(ShellState *p, const char *zSuffix){
6473 clearTempFile(p);
6474 sqlite3_free(p->zTempFile);
6475 p->zTempFile = 0;
6476 if( p->db ){
6477 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6479 if( p->zTempFile==0 ){
6480 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6481 ** will not work and we will need to fallback to guessing */
6482 char *zTemp;
6483 sqlite3_uint64 r;
6484 sqlite3_randomness(sizeof(r), &r);
6485 zTemp = getenv("TEMP");
6486 if( zTemp==0 ) zTemp = getenv("TMP");
6487 if( zTemp==0 ){
6488 #ifdef _WIN32
6489 zTemp = "\\tmp";
6490 #else
6491 zTemp = "/tmp";
6492 #endif
6494 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6495 }else{
6496 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6498 shell_check_oom(p->zTempFile);
6503 ** The implementation of SQL scalar function fkey_collate_clause(), used
6504 ** by the ".lint fkey-indexes" command. This scalar function is always
6505 ** called with four arguments - the parent table name, the parent column name,
6506 ** the child table name and the child column name.
6508 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6510 ** If either of the named tables or columns do not exist, this function
6511 ** returns an empty string. An empty string is also returned if both tables
6512 ** and columns exist but have the same default collation sequence. Or,
6513 ** if both exist but the default collation sequences are different, this
6514 ** function returns the string " COLLATE <parent-collation>", where
6515 ** <parent-collation> is the default collation sequence of the parent column.
6517 static void shellFkeyCollateClause(
6518 sqlite3_context *pCtx,
6519 int nVal,
6520 sqlite3_value **apVal
6522 sqlite3 *db = sqlite3_context_db_handle(pCtx);
6523 const char *zParent;
6524 const char *zParentCol;
6525 const char *zParentSeq;
6526 const char *zChild;
6527 const char *zChildCol;
6528 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
6529 int rc;
6531 assert( nVal==4 );
6532 zParent = (const char*)sqlite3_value_text(apVal[0]);
6533 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6534 zChild = (const char*)sqlite3_value_text(apVal[2]);
6535 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6537 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6538 rc = sqlite3_table_column_metadata(
6539 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6541 if( rc==SQLITE_OK ){
6542 rc = sqlite3_table_column_metadata(
6543 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6547 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6548 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6549 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6550 sqlite3_free(z);
6556 ** The implementation of dot-command ".lint fkey-indexes".
6558 static int lintFkeyIndexes(
6559 ShellState *pState, /* Current shell tool state */
6560 char **azArg, /* Array of arguments passed to dot command */
6561 int nArg /* Number of entries in azArg[] */
6563 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
6564 int bVerbose = 0; /* If -verbose is present */
6565 int bGroupByParent = 0; /* If -groupbyparent is present */
6566 int i; /* To iterate through azArg[] */
6567 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
6568 int rc; /* Return code */
6569 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
6572 ** This SELECT statement returns one row for each foreign key constraint
6573 ** in the schema of the main database. The column values are:
6575 ** 0. The text of an SQL statement similar to:
6577 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6579 ** This SELECT is similar to the one that the foreign keys implementation
6580 ** needs to run internally on child tables. If there is an index that can
6581 ** be used to optimize this query, then it can also be used by the FK
6582 ** implementation to optimize DELETE or UPDATE statements on the parent
6583 ** table.
6585 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6586 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6587 ** contains an index that can be used to optimize the query.
6589 ** 2. Human readable text that describes the child table and columns. e.g.
6591 ** "child_table(child_key1, child_key2)"
6593 ** 3. Human readable text that describes the parent table and columns. e.g.
6595 ** "parent_table(parent_key1, parent_key2)"
6597 ** 4. A full CREATE INDEX statement for an index that could be used to
6598 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6600 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6602 ** 5. The name of the parent table.
6604 ** These six values are used by the C logic below to generate the report.
6606 const char *zSql =
6607 "SELECT "
6608 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6609 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6610 " || fkey_collate_clause("
6611 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6612 ", "
6613 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6614 " || group_concat('*=?', ' AND ') || ')'"
6615 ", "
6616 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6617 ", "
6618 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6619 ", "
6620 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6621 " || ' ON ' || quote(s.name) || '('"
6622 " || group_concat(quote(f.[from]) ||"
6623 " fkey_collate_clause("
6624 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6625 " || ');'"
6626 ", "
6627 " f.[table] "
6628 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6629 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6630 "GROUP BY s.name, f.id "
6631 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6633 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6635 for(i=2; i<nArg; i++){
6636 int n = strlen30(azArg[i]);
6637 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6638 bVerbose = 1;
6640 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6641 bGroupByParent = 1;
6642 zIndent = " ";
6644 else{
6645 eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
6646 return SQLITE_ERROR;
6650 /* Register the fkey_collate_clause() SQL function */
6651 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6652 0, shellFkeyCollateClause, 0, 0
6656 if( rc==SQLITE_OK ){
6657 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6659 if( rc==SQLITE_OK ){
6660 sqlite3_bind_int(pSql, 1, bGroupByParent);
6663 if( rc==SQLITE_OK ){
6664 int rc2;
6665 char *zPrev = 0;
6666 while( SQLITE_ROW==sqlite3_step(pSql) ){
6667 int res = -1;
6668 sqlite3_stmt *pExplain = 0;
6669 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6670 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6671 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6672 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6673 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6674 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6676 if( zEQP==0 ) continue;
6677 if( zGlob==0 ) continue;
6678 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6679 if( rc!=SQLITE_OK ) break;
6680 if( SQLITE_ROW==sqlite3_step(pExplain) ){
6681 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6682 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
6683 || 0==sqlite3_strglob(zGlobIPK, zPlan));
6685 rc = sqlite3_finalize(pExplain);
6686 if( rc!=SQLITE_OK ) break;
6688 if( res<0 ){
6689 eputz("Error: internal error");
6690 break;
6691 }else{
6692 if( bGroupByParent
6693 && (bVerbose || res==0)
6694 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6696 oputf("-- Parent table %s\n", zParent);
6697 sqlite3_free(zPrev);
6698 zPrev = sqlite3_mprintf("%s", zParent);
6701 if( res==0 ){
6702 oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
6703 }else if( bVerbose ){
6704 oputf("%s/* no extra indexes required for %s -> %s */\n",
6705 zIndent, zFrom, zTarget
6710 sqlite3_free(zPrev);
6712 if( rc!=SQLITE_OK ){
6713 eputf("%s\n", sqlite3_errmsg(db));
6716 rc2 = sqlite3_finalize(pSql);
6717 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6718 rc = rc2;
6719 eputf("%s\n", sqlite3_errmsg(db));
6721 }else{
6722 eputf("%s\n", sqlite3_errmsg(db));
6725 return rc;
6729 ** Implementation of ".lint" dot command.
6731 static int lintDotCommand(
6732 ShellState *pState, /* Current shell tool state */
6733 char **azArg, /* Array of arguments passed to dot command */
6734 int nArg /* Number of entries in azArg[] */
6736 int n;
6737 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6738 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6739 return lintFkeyIndexes(pState, azArg, nArg);
6741 usage:
6742 eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
6743 eputz("Where sub-commands are:\n");
6744 eputz(" fkey-indexes\n");
6745 return SQLITE_ERROR;
6748 static void shellPrepare(
6749 sqlite3 *db,
6750 int *pRc,
6751 const char *zSql,
6752 sqlite3_stmt **ppStmt
6754 *ppStmt = 0;
6755 if( *pRc==SQLITE_OK ){
6756 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6757 if( rc!=SQLITE_OK ){
6758 eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
6759 *pRc = rc;
6765 ** Create a prepared statement using printf-style arguments for the SQL.
6767 static void shellPreparePrintf(
6768 sqlite3 *db,
6769 int *pRc,
6770 sqlite3_stmt **ppStmt,
6771 const char *zFmt,
6774 *ppStmt = 0;
6775 if( *pRc==SQLITE_OK ){
6776 va_list ap;
6777 char *z;
6778 va_start(ap, zFmt);
6779 z = sqlite3_vmprintf(zFmt, ap);
6780 va_end(ap);
6781 if( z==0 ){
6782 *pRc = SQLITE_NOMEM;
6783 }else{
6784 shellPrepare(db, pRc, z, ppStmt);
6785 sqlite3_free(z);
6791 ** Finalize the prepared statement created using shellPreparePrintf().
6793 static void shellFinalize(
6794 int *pRc,
6795 sqlite3_stmt *pStmt
6797 if( pStmt ){
6798 sqlite3 *db = sqlite3_db_handle(pStmt);
6799 int rc = sqlite3_finalize(pStmt);
6800 if( *pRc==SQLITE_OK ){
6801 if( rc!=SQLITE_OK ){
6802 eputf("SQL error: %s\n", sqlite3_errmsg(db));
6804 *pRc = rc;
6809 #if !defined SQLITE_OMIT_VIRTUALTABLE
6810 /* Reset the prepared statement created using shellPreparePrintf().
6812 ** This routine is could be marked "static". But it is not always used,
6813 ** depending on compile-time options. By omitting the "static", we avoid
6814 ** nuisance compiler warnings about "defined but not used".
6816 void shellReset(
6817 int *pRc,
6818 sqlite3_stmt *pStmt
6820 int rc = sqlite3_reset(pStmt);
6821 if( *pRc==SQLITE_OK ){
6822 if( rc!=SQLITE_OK ){
6823 sqlite3 *db = sqlite3_db_handle(pStmt);
6824 eputf("SQL error: %s\n", sqlite3_errmsg(db));
6826 *pRc = rc;
6829 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6831 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6832 /******************************************************************************
6833 ** The ".archive" or ".ar" command.
6836 ** Structure representing a single ".ar" command.
6838 typedef struct ArCommand ArCommand;
6839 struct ArCommand {
6840 u8 eCmd; /* An AR_CMD_* value */
6841 u8 bVerbose; /* True if --verbose */
6842 u8 bZip; /* True if the archive is a ZIP */
6843 u8 bDryRun; /* True if --dry-run */
6844 u8 bAppend; /* True if --append */
6845 u8 bGlob; /* True if --glob */
6846 u8 fromCmdLine; /* Run from -A instead of .archive */
6847 int nArg; /* Number of command arguments */
6848 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6849 const char *zFile; /* --file argument, or NULL */
6850 const char *zDir; /* --directory argument, or NULL */
6851 char **azArg; /* Array of command arguments */
6852 ShellState *p; /* Shell state */
6853 sqlite3 *db; /* Database containing the archive */
6857 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6859 static int arUsage(FILE *f){
6860 showHelp(f,"archive");
6861 return SQLITE_ERROR;
6865 ** Print an error message for the .ar command to stderr and return
6866 ** SQLITE_ERROR.
6868 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6869 va_list ap;
6870 char *z;
6871 va_start(ap, zFmt);
6872 z = sqlite3_vmprintf(zFmt, ap);
6873 va_end(ap);
6874 eputf("Error: %s\n", z);
6875 if( pAr->fromCmdLine ){
6876 eputz("Use \"-A\" for more help\n");
6877 }else{
6878 eputz("Use \".archive --help\" for more help\n");
6880 sqlite3_free(z);
6881 return SQLITE_ERROR;
6885 ** Values for ArCommand.eCmd.
6887 #define AR_CMD_CREATE 1
6888 #define AR_CMD_UPDATE 2
6889 #define AR_CMD_INSERT 3
6890 #define AR_CMD_EXTRACT 4
6891 #define AR_CMD_LIST 5
6892 #define AR_CMD_HELP 6
6893 #define AR_CMD_REMOVE 7
6896 ** Other (non-command) switches.
6898 #define AR_SWITCH_VERBOSE 8
6899 #define AR_SWITCH_FILE 9
6900 #define AR_SWITCH_DIRECTORY 10
6901 #define AR_SWITCH_APPEND 11
6902 #define AR_SWITCH_DRYRUN 12
6903 #define AR_SWITCH_GLOB 13
6905 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6906 switch( eSwitch ){
6907 case AR_CMD_CREATE:
6908 case AR_CMD_EXTRACT:
6909 case AR_CMD_LIST:
6910 case AR_CMD_REMOVE:
6911 case AR_CMD_UPDATE:
6912 case AR_CMD_INSERT:
6913 case AR_CMD_HELP:
6914 if( pAr->eCmd ){
6915 return arErrorMsg(pAr, "multiple command options");
6917 pAr->eCmd = eSwitch;
6918 break;
6920 case AR_SWITCH_DRYRUN:
6921 pAr->bDryRun = 1;
6922 break;
6923 case AR_SWITCH_GLOB:
6924 pAr->bGlob = 1;
6925 break;
6926 case AR_SWITCH_VERBOSE:
6927 pAr->bVerbose = 1;
6928 break;
6929 case AR_SWITCH_APPEND:
6930 pAr->bAppend = 1;
6931 deliberate_fall_through;
6932 case AR_SWITCH_FILE:
6933 pAr->zFile = zArg;
6934 break;
6935 case AR_SWITCH_DIRECTORY:
6936 pAr->zDir = zArg;
6937 break;
6940 return SQLITE_OK;
6944 ** Parse the command line for an ".ar" command. The results are written into
6945 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6946 ** successfully, otherwise an error message is written to stderr and
6947 ** SQLITE_ERROR returned.
6949 static int arParseCommand(
6950 char **azArg, /* Array of arguments passed to dot command */
6951 int nArg, /* Number of entries in azArg[] */
6952 ArCommand *pAr /* Populate this object */
6954 struct ArSwitch {
6955 const char *zLong;
6956 char cShort;
6957 u8 eSwitch;
6958 u8 bArg;
6959 } aSwitch[] = {
6960 { "create", 'c', AR_CMD_CREATE, 0 },
6961 { "extract", 'x', AR_CMD_EXTRACT, 0 },
6962 { "insert", 'i', AR_CMD_INSERT, 0 },
6963 { "list", 't', AR_CMD_LIST, 0 },
6964 { "remove", 'r', AR_CMD_REMOVE, 0 },
6965 { "update", 'u', AR_CMD_UPDATE, 0 },
6966 { "help", 'h', AR_CMD_HELP, 0 },
6967 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
6968 { "file", 'f', AR_SWITCH_FILE, 1 },
6969 { "append", 'a', AR_SWITCH_APPEND, 1 },
6970 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6971 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
6972 { "glob", 'g', AR_SWITCH_GLOB, 0 },
6974 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6975 struct ArSwitch *pEnd = &aSwitch[nSwitch];
6977 if( nArg<=1 ){
6978 eputz("Wrong number of arguments. Usage:\n");
6979 return arUsage(stderr);
6980 }else{
6981 char *z = azArg[1];
6982 if( z[0]!='-' ){
6983 /* Traditional style [tar] invocation */
6984 int i;
6985 int iArg = 2;
6986 for(i=0; z[i]; i++){
6987 const char *zArg = 0;
6988 struct ArSwitch *pOpt;
6989 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6990 if( z[i]==pOpt->cShort ) break;
6992 if( pOpt==pEnd ){
6993 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6995 if( pOpt->bArg ){
6996 if( iArg>=nArg ){
6997 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6999 zArg = azArg[iArg++];
7001 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7003 pAr->nArg = nArg-iArg;
7004 if( pAr->nArg>0 ){
7005 pAr->azArg = &azArg[iArg];
7007 }else{
7008 /* Non-traditional invocation */
7009 int iArg;
7010 for(iArg=1; iArg<nArg; iArg++){
7011 int n;
7012 z = azArg[iArg];
7013 if( z[0]!='-' ){
7014 /* All remaining command line words are command arguments. */
7015 pAr->azArg = &azArg[iArg];
7016 pAr->nArg = nArg-iArg;
7017 break;
7019 n = strlen30(z);
7021 if( z[1]!='-' ){
7022 int i;
7023 /* One or more short options */
7024 for(i=1; i<n; i++){
7025 const char *zArg = 0;
7026 struct ArSwitch *pOpt;
7027 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7028 if( z[i]==pOpt->cShort ) break;
7030 if( pOpt==pEnd ){
7031 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
7033 if( pOpt->bArg ){
7034 if( i<(n-1) ){
7035 zArg = &z[i+1];
7036 i = n;
7037 }else{
7038 if( iArg>=(nArg-1) ){
7039 return arErrorMsg(pAr, "option requires an argument: %c",
7040 z[i]);
7042 zArg = azArg[++iArg];
7045 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7047 }else if( z[2]=='\0' ){
7048 /* A -- option, indicating that all remaining command line words
7049 ** are command arguments. */
7050 pAr->azArg = &azArg[iArg+1];
7051 pAr->nArg = nArg-iArg-1;
7052 break;
7053 }else{
7054 /* A long option */
7055 const char *zArg = 0; /* Argument for option, if any */
7056 struct ArSwitch *pMatch = 0; /* Matching option */
7057 struct ArSwitch *pOpt; /* Iterator */
7058 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7059 const char *zLong = pOpt->zLong;
7060 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
7061 if( pMatch ){
7062 return arErrorMsg(pAr, "ambiguous option: %s",z);
7063 }else{
7064 pMatch = pOpt;
7069 if( pMatch==0 ){
7070 return arErrorMsg(pAr, "unrecognized option: %s", z);
7072 if( pMatch->bArg ){
7073 if( iArg>=(nArg-1) ){
7074 return arErrorMsg(pAr, "option requires an argument: %s", z);
7076 zArg = azArg[++iArg];
7078 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
7083 if( pAr->eCmd==0 ){
7084 eputz("Required argument missing. Usage:\n");
7085 return arUsage(stderr);
7087 return SQLITE_OK;
7091 ** This function assumes that all arguments within the ArCommand.azArg[]
7092 ** array refer to archive members, as for the --extract, --list or --remove
7093 ** commands. It checks that each of them are "present". If any specified
7094 ** file is not present in the archive, an error is printed to stderr and an
7095 ** error code returned. Otherwise, if all specified arguments are present
7096 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7097 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7098 ** when pAr->bGlob is true.
7100 ** This function strips any trailing '/' characters from each argument.
7101 ** This is consistent with the way the [tar] command seems to work on
7102 ** Linux.
7104 static int arCheckEntries(ArCommand *pAr){
7105 int rc = SQLITE_OK;
7106 if( pAr->nArg ){
7107 int i, j;
7108 sqlite3_stmt *pTest = 0;
7109 const char *zSel = (pAr->bGlob)
7110 ? "SELECT name FROM %s WHERE glob($name,name)"
7111 : "SELECT name FROM %s WHERE name=$name";
7113 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
7114 j = sqlite3_bind_parameter_index(pTest, "$name");
7115 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7116 char *z = pAr->azArg[i];
7117 int n = strlen30(z);
7118 int bOk = 0;
7119 while( n>0 && z[n-1]=='/' ) n--;
7120 z[n] = '\0';
7121 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
7122 if( SQLITE_ROW==sqlite3_step(pTest) ){
7123 bOk = 1;
7125 shellReset(&rc, pTest);
7126 if( rc==SQLITE_OK && bOk==0 ){
7127 eputf("not found in archive: %s\n", z);
7128 rc = SQLITE_ERROR;
7131 shellFinalize(&rc, pTest);
7133 return rc;
7137 ** Format a WHERE clause that can be used against the "sqlar" table to
7138 ** identify all archive members that match the command arguments held
7139 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7140 ** The caller is responsible for eventually calling sqlite3_free() on
7141 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7142 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7144 static void arWhereClause(
7145 int *pRc,
7146 ArCommand *pAr,
7147 char **pzWhere /* OUT: New WHERE clause */
7149 char *zWhere = 0;
7150 const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
7151 if( *pRc==SQLITE_OK ){
7152 if( pAr->nArg==0 ){
7153 zWhere = sqlite3_mprintf("1");
7154 }else{
7155 int i;
7156 const char *zSep = "";
7157 for(i=0; i<pAr->nArg; i++){
7158 const char *z = pAr->azArg[i];
7159 zWhere = sqlite3_mprintf(
7160 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7161 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
7163 if( zWhere==0 ){
7164 *pRc = SQLITE_NOMEM;
7165 break;
7167 zSep = " OR ";
7171 *pzWhere = zWhere;
7175 ** Implementation of .ar "lisT" command.
7177 static int arListCommand(ArCommand *pAr){
7178 const char *zSql = "SELECT %s FROM %s WHERE %s";
7179 const char *azCols[] = {
7180 "name",
7181 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7184 char *zWhere = 0;
7185 sqlite3_stmt *pSql = 0;
7186 int rc;
7188 rc = arCheckEntries(pAr);
7189 arWhereClause(&rc, pAr, &zWhere);
7191 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
7192 pAr->zSrcTable, zWhere);
7193 if( pAr->bDryRun ){
7194 oputf("%s\n", sqlite3_sql(pSql));
7195 }else{
7196 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7197 if( pAr->bVerbose ){
7198 oputf("%s % 10d %s %s\n",
7199 sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
7200 sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
7201 }else{
7202 oputf("%s\n", sqlite3_column_text(pSql, 0));
7206 shellFinalize(&rc, pSql);
7207 sqlite3_free(zWhere);
7208 return rc;
7212 ** Implementation of .ar "Remove" command.
7214 static int arRemoveCommand(ArCommand *pAr){
7215 int rc = 0;
7216 char *zSql = 0;
7217 char *zWhere = 0;
7219 if( pAr->nArg ){
7220 /* Verify that args actually exist within the archive before proceeding.
7221 ** And formulate a WHERE clause to match them. */
7222 rc = arCheckEntries(pAr);
7223 arWhereClause(&rc, pAr, &zWhere);
7225 if( rc==SQLITE_OK ){
7226 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7227 pAr->zSrcTable, zWhere);
7228 if( pAr->bDryRun ){
7229 oputf("%s\n", zSql);
7230 }else{
7231 char *zErr = 0;
7232 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
7233 if( rc==SQLITE_OK ){
7234 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7235 if( rc!=SQLITE_OK ){
7236 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7237 }else{
7238 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
7241 if( zErr ){
7242 sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
7243 sqlite3_free(zErr);
7247 sqlite3_free(zWhere);
7248 sqlite3_free(zSql);
7249 return rc;
7253 ** Implementation of .ar "eXtract" command.
7255 static int arExtractCommand(ArCommand *pAr){
7256 const char *zSql1 =
7257 "SELECT "
7258 " ($dir || name),"
7259 " writefile(($dir || name), %s, mode, mtime) "
7260 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7261 " AND name NOT GLOB '*..[/\\]*'";
7263 const char *azExtraArg[] = {
7264 "sqlar_uncompress(data, sz)",
7265 "data"
7268 sqlite3_stmt *pSql = 0;
7269 int rc = SQLITE_OK;
7270 char *zDir = 0;
7271 char *zWhere = 0;
7272 int i, j;
7274 /* If arguments are specified, check that they actually exist within
7275 ** the archive before proceeding. And formulate a WHERE clause to
7276 ** match them. */
7277 rc = arCheckEntries(pAr);
7278 arWhereClause(&rc, pAr, &zWhere);
7280 if( rc==SQLITE_OK ){
7281 if( pAr->zDir ){
7282 zDir = sqlite3_mprintf("%s/", pAr->zDir);
7283 }else{
7284 zDir = sqlite3_mprintf("");
7286 if( zDir==0 ) rc = SQLITE_NOMEM;
7289 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
7290 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
7293 if( rc==SQLITE_OK ){
7294 j = sqlite3_bind_parameter_index(pSql, "$dir");
7295 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
7297 /* Run the SELECT statement twice. The first time, writefile() is called
7298 ** for all archive members that should be extracted. The second time,
7299 ** only for the directories. This is because the timestamps for
7300 ** extracted directories must be reset after they are populated (as
7301 ** populating them changes the timestamp). */
7302 for(i=0; i<2; i++){
7303 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
7304 sqlite3_bind_int(pSql, j, i);
7305 if( pAr->bDryRun ){
7306 oputf("%s\n", sqlite3_sql(pSql));
7307 }else{
7308 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7309 if( i==0 && pAr->bVerbose ){
7310 oputf("%s\n", sqlite3_column_text(pSql, 0));
7314 shellReset(&rc, pSql);
7316 shellFinalize(&rc, pSql);
7319 sqlite3_free(zDir);
7320 sqlite3_free(zWhere);
7321 return rc;
7325 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7327 static int arExecSql(ArCommand *pAr, const char *zSql){
7328 int rc;
7329 if( pAr->bDryRun ){
7330 oputf("%s\n", zSql);
7331 rc = SQLITE_OK;
7332 }else{
7333 char *zErr = 0;
7334 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7335 if( zErr ){
7336 sputf(stdout, "ERROR: %s\n", zErr);
7337 sqlite3_free(zErr);
7340 return rc;
7345 ** Implementation of .ar "create", "insert", and "update" commands.
7347 ** create -> Create a new SQL archive
7348 ** insert -> Insert or reinsert all files listed
7349 ** update -> Insert files that have changed or that were not
7350 ** previously in the archive
7352 ** Create the "sqlar" table in the database if it does not already exist.
7353 ** Then add each file in the azFile[] array to the archive. Directories
7354 ** are added recursively. If argument bVerbose is non-zero, a message is
7355 ** printed on stdout for each file archived.
7357 ** The create command is the same as update, except that it drops
7358 ** any existing "sqlar" table before beginning. The "insert" command
7359 ** always overwrites every file named on the command-line, where as
7360 ** "update" only overwrites if the size or mtime or mode has changed.
7362 static int arCreateOrUpdateCommand(
7363 ArCommand *pAr, /* Command arguments and options */
7364 int bUpdate, /* true for a --create. */
7365 int bOnlyIfChanged /* Only update if file has changed */
7367 const char *zCreate =
7368 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7369 " name TEXT PRIMARY KEY, -- name of the file\n"
7370 " mode INT, -- access permissions\n"
7371 " mtime INT, -- last modification time\n"
7372 " sz INT, -- original file size\n"
7373 " data BLOB -- compressed content\n"
7374 ")";
7375 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7376 const char *zInsertFmt[2] = {
7377 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7378 " SELECT\n"
7379 " %s,\n"
7380 " mode,\n"
7381 " mtime,\n"
7382 " CASE substr(lsmode(mode),1,1)\n"
7383 " WHEN '-' THEN length(data)\n"
7384 " WHEN 'd' THEN 0\n"
7385 " ELSE -1 END,\n"
7386 " sqlar_compress(data)\n"
7387 " FROM fsdir(%Q,%Q) AS disk\n"
7388 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7390 "REPLACE INTO %s(name,mode,mtime,data)\n"
7391 " SELECT\n"
7392 " %s,\n"
7393 " mode,\n"
7394 " mtime,\n"
7395 " data\n"
7396 " FROM fsdir(%Q,%Q) AS disk\n"
7397 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7399 int i; /* For iterating through azFile[] */
7400 int rc; /* Return code */
7401 const char *zTab = 0; /* SQL table into which to insert */
7402 char *zSql;
7403 char zTemp[50];
7404 char *zExists = 0;
7406 arExecSql(pAr, "PRAGMA page_size=512");
7407 rc = arExecSql(pAr, "SAVEPOINT ar;");
7408 if( rc!=SQLITE_OK ) return rc;
7409 zTemp[0] = 0;
7410 if( pAr->bZip ){
7411 /* Initialize the zipfile virtual table, if necessary */
7412 if( pAr->zFile ){
7413 sqlite3_uint64 r;
7414 sqlite3_randomness(sizeof(r),&r);
7415 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7416 zTab = zTemp;
7417 zSql = sqlite3_mprintf(
7418 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7419 zTab, pAr->zFile
7421 rc = arExecSql(pAr, zSql);
7422 sqlite3_free(zSql);
7423 }else{
7424 zTab = "zip";
7426 }else{
7427 /* Initialize the table for an SQLAR */
7428 zTab = "sqlar";
7429 if( bUpdate==0 ){
7430 rc = arExecSql(pAr, zDrop);
7431 if( rc!=SQLITE_OK ) goto end_ar_transaction;
7433 rc = arExecSql(pAr, zCreate);
7435 if( bOnlyIfChanged ){
7436 zExists = sqlite3_mprintf(
7437 " AND NOT EXISTS("
7438 "SELECT 1 FROM %s AS mem"
7439 " WHERE mem.name=disk.name"
7440 " AND mem.mtime=disk.mtime"
7441 " AND mem.mode=disk.mode)", zTab);
7442 }else{
7443 zExists = sqlite3_mprintf("");
7445 if( zExists==0 ) rc = SQLITE_NOMEM;
7446 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7447 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7448 pAr->bVerbose ? "shell_putsnl(name)" : "name",
7449 pAr->azArg[i], pAr->zDir, zExists);
7450 rc = arExecSql(pAr, zSql2);
7451 sqlite3_free(zSql2);
7453 end_ar_transaction:
7454 if( rc!=SQLITE_OK ){
7455 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7456 }else{
7457 rc = arExecSql(pAr, "RELEASE ar;");
7458 if( pAr->bZip && pAr->zFile ){
7459 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7460 arExecSql(pAr, zSql);
7461 sqlite3_free(zSql);
7464 sqlite3_free(zExists);
7465 return rc;
7469 ** Implementation of ".ar" dot command.
7471 static int arDotCommand(
7472 ShellState *pState, /* Current shell tool state */
7473 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
7474 char **azArg, /* Array of arguments passed to dot command */
7475 int nArg /* Number of entries in azArg[] */
7477 ArCommand cmd;
7478 int rc;
7479 memset(&cmd, 0, sizeof(cmd));
7480 cmd.fromCmdLine = fromCmdLine;
7481 rc = arParseCommand(azArg, nArg, &cmd);
7482 if( rc==SQLITE_OK ){
7483 int eDbType = SHELL_OPEN_UNSPEC;
7484 cmd.p = pState;
7485 cmd.db = pState->db;
7486 if( cmd.zFile ){
7487 eDbType = deduceDatabaseType(cmd.zFile, 1);
7488 }else{
7489 eDbType = pState->openMode;
7491 if( eDbType==SHELL_OPEN_ZIPFILE ){
7492 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7493 if( cmd.zFile==0 ){
7494 cmd.zSrcTable = sqlite3_mprintf("zip");
7495 }else{
7496 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7499 cmd.bZip = 1;
7500 }else if( cmd.zFile ){
7501 int flags;
7502 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7503 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7504 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7505 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7506 }else{
7507 flags = SQLITE_OPEN_READONLY;
7509 cmd.db = 0;
7510 if( cmd.bDryRun ){
7511 oputf("-- open database '%s'%s\n", cmd.zFile,
7512 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7514 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7515 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7516 if( rc!=SQLITE_OK ){
7517 eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
7518 goto end_ar_command;
7520 sqlite3_fileio_init(cmd.db, 0, 0);
7521 sqlite3_sqlar_init(cmd.db, 0, 0);
7522 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7523 shellPutsFunc, 0, 0);
7526 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7527 if( cmd.eCmd!=AR_CMD_CREATE
7528 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7530 eputz("database does not contain an 'sqlar' table\n");
7531 rc = SQLITE_ERROR;
7532 goto end_ar_command;
7534 cmd.zSrcTable = sqlite3_mprintf("sqlar");
7537 switch( cmd.eCmd ){
7538 case AR_CMD_CREATE:
7539 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7540 break;
7542 case AR_CMD_EXTRACT:
7543 rc = arExtractCommand(&cmd);
7544 break;
7546 case AR_CMD_LIST:
7547 rc = arListCommand(&cmd);
7548 break;
7550 case AR_CMD_HELP:
7551 arUsage(pState->out);
7552 break;
7554 case AR_CMD_INSERT:
7555 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7556 break;
7558 case AR_CMD_REMOVE:
7559 rc = arRemoveCommand(&cmd);
7560 break;
7562 default:
7563 assert( cmd.eCmd==AR_CMD_UPDATE );
7564 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7565 break;
7568 end_ar_command:
7569 if( cmd.db!=pState->db ){
7570 close_db(cmd.db);
7572 sqlite3_free(cmd.zSrcTable);
7574 return rc;
7576 /* End of the ".archive" or ".ar" command logic
7577 *******************************************************************************/
7578 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7580 #if SQLITE_SHELL_HAVE_RECOVER
7583 ** This function is used as a callback by the recover extension. Simply
7584 ** print the supplied SQL statement to stdout.
7586 static int recoverSqlCb(void *pCtx, const char *zSql){
7587 ShellState *pState = (ShellState*)pCtx;
7588 sputf(pState->out, "%s;\n", zSql);
7589 return SQLITE_OK;
7593 ** This function is called to recover data from the database. A script
7594 ** to construct a new database containing all recovered data is output
7595 ** on stream pState->out.
7597 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7598 int rc = SQLITE_OK;
7599 const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
7600 const char *zLAF = "lost_and_found";
7601 int bFreelist = 1; /* 0 if --ignore-freelist is specified */
7602 int bRowids = 1; /* 0 if --no-rowids */
7603 sqlite3_recover *p = 0;
7604 int i = 0;
7606 for(i=1; i<nArg; i++){
7607 char *z = azArg[i];
7608 int n;
7609 if( z[0]=='-' && z[1]=='-' ) z++;
7610 n = strlen30(z);
7611 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
7612 bFreelist = 0;
7613 }else
7614 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7615 /* This option determines the name of the ATTACH-ed database used
7616 ** internally by the recovery extension. The default is "" which
7617 ** means to use a temporary database that is automatically deleted
7618 ** when closed. This option is undocumented and might disappear at
7619 ** any moment. */
7620 i++;
7621 zRecoveryDb = azArg[i];
7622 }else
7623 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7624 i++;
7625 zLAF = azArg[i];
7626 }else
7627 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7628 bRowids = 0;
7630 else{
7631 eputf("unexpected option: %s\n", azArg[i]);
7632 showHelp(pState->out, azArg[0]);
7633 return 1;
7637 p = sqlite3_recover_init_sql(
7638 pState->db, "main", recoverSqlCb, (void*)pState
7641 sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */
7642 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7643 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7644 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7646 sqlite3_recover_run(p);
7647 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7648 const char *zErr = sqlite3_recover_errmsg(p);
7649 int errCode = sqlite3_recover_errcode(p);
7650 eputf("sql error: %s (%d)\n", zErr, errCode);
7652 rc = sqlite3_recover_finish(p);
7653 return rc;
7655 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7658 ** Implementation of ".intck STEPS_PER_UNLOCK" command.
7660 static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){
7661 sqlite3_intck *p = 0;
7662 int rc = SQLITE_OK;
7664 rc = sqlite3_intck_open(pState->db, "main", &p);
7665 if( rc==SQLITE_OK ){
7666 i64 nStep = 0;
7667 i64 nError = 0;
7668 const char *zErr = 0;
7669 while( SQLITE_OK==sqlite3_intck_step(p) ){
7670 const char *zMsg = sqlite3_intck_message(p);
7671 if( zMsg ){
7672 oputf("%s\n", zMsg);
7673 nError++;
7675 nStep++;
7676 if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){
7677 sqlite3_intck_unlock(p);
7680 rc = sqlite3_intck_error(p, &zErr);
7681 if( zErr ){
7682 eputf("%s\n", zErr);
7684 sqlite3_intck_close(p);
7686 oputf("%lld steps, %lld errors\n", nStep, nError);
7689 return rc;
7693 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7694 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7695 * close db and set it to 0, and return the columns spec, to later
7696 * be sqlite3_free()'ed by the caller.
7697 * The return is 0 when either:
7698 * (a) The db was not initialized and zCol==0 (There are no columns.)
7699 * (b) zCol!=0 (Column was added, db initialized as needed.)
7700 * The 3rd argument, pRenamed, references an out parameter. If the
7701 * pointer is non-zero, its referent will be set to a summary of renames
7702 * done if renaming was necessary, or set to 0 if none was done. The out
7703 * string (if any) must be sqlite3_free()'ed by the caller.
7705 #ifdef SHELL_DEBUG
7706 #define rc_err_oom_die(rc) \
7707 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7708 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7709 eputf("E:%d\n",rc), assert(0)
7710 #else
7711 static void rc_err_oom_die(int rc){
7712 if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7713 assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7715 #endif
7717 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7718 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7719 #else /* Otherwise, memory is faster/better for the transient DB. */
7720 static const char *zCOL_DB = ":memory:";
7721 #endif
7723 /* Define character (as C string) to separate generated column ordinal
7724 * from protected part of incoming column names. This defaults to "_"
7725 * so that incoming column identifiers that did not need not be quoted
7726 * remain usable without being quoted. It must be one character.
7728 #ifndef SHELL_AUTOCOLUMN_SEP
7729 # define AUTOCOLUMN_SEP "_"
7730 #else
7731 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7732 #endif
7734 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7735 /* Queries and D{D,M}L used here */
7736 static const char * const zTabMake = "\
7737 CREATE TABLE ColNames(\
7738 cpos INTEGER PRIMARY KEY,\
7739 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7740 CREATE VIEW RepeatedNames AS \
7741 SELECT DISTINCT t.name FROM ColNames t \
7742 WHERE t.name COLLATE NOCASE IN (\
7743 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7746 static const char * const zTabFill = "\
7747 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7748 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7750 static const char * const zHasDupes = "\
7751 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7752 <count(name) FROM ColNames\
7754 #ifdef SHELL_COLUMN_RENAME_CLEAN
7755 static const char * const zDedoctor = "\
7756 UPDATE ColNames SET chop=iif(\
7757 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7758 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7759 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7763 #endif
7764 static const char * const zSetReps = "\
7765 UPDATE ColNames AS t SET reps=\
7766 (SELECT count(*) FROM ColNames d \
7767 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7768 COLLATE NOCASE\
7771 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7772 static const char * const zColDigits = "\
7773 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7775 #else
7776 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7777 static const char * const zColDigits = "\
7778 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7779 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7780 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7782 #endif
7783 static const char * const zRenameRank =
7784 #ifdef SHELL_COLUMN_RENAME_CLEAN
7785 "UPDATE ColNames AS t SET suff="
7786 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7787 #else /* ...RENAME_MINIMAL_ONE_PASS */
7788 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7789 " SELECT 0 AS nlz"
7790 " UNION"
7791 " SELECT nlz+1 AS nlz FROM Lzn"
7792 " WHERE EXISTS("
7793 " SELECT 1"
7794 " FROM ColNames t, ColNames o"
7795 " WHERE"
7796 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7797 " printf('%s"AUTOCOLUMN_SEP"%s',"
7798 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7799 " t.name"
7800 " )"
7801 " ="
7802 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7803 " printf('%s"AUTOCOLUMN_SEP"%s',"
7804 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7805 " o.name"
7806 " )"
7807 " COLLATE NOCASE"
7808 " AND o.cpos<>t.cpos"
7809 " GROUP BY t.cpos"
7810 " )"
7811 ") UPDATE Colnames AS t SET"
7812 " chop = 0," /* No chopping, never touch incoming names. */
7813 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7814 " printf('"AUTOCOLUMN_SEP"%s', substring("
7815 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7816 " ''"
7817 " )"
7818 #endif
7820 static const char * const zCollectVar = "\
7821 SELECT\
7822 '('||x'0a'\
7823 || group_concat(\
7824 cname||' TEXT',\
7825 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7826 ||')' AS ColsSpec \
7827 FROM (\
7828 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7829 FROM ColNames ORDER BY cpos\
7831 static const char * const zRenamesDone =
7832 "SELECT group_concat("
7833 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7834 " ','||x'0a')"
7835 "FROM ColNames WHERE suff<>'' OR chop!=0"
7837 int rc;
7838 sqlite3_stmt *pStmt = 0;
7839 assert(pDb!=0);
7840 if( zColNew ){
7841 /* Add initial or additional column. Init db if necessary. */
7842 if( *pDb==0 ){
7843 if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7844 #ifdef SHELL_COLFIX_DB
7845 if(*zCOL_DB!=':')
7846 sqlite3_exec(*pDb,"drop table if exists ColNames;"
7847 "drop view if exists RepeatedNames;",0,0,0);
7848 #endif
7849 #undef SHELL_COLFIX_DB
7850 rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7851 rc_err_oom_die(rc);
7853 assert(*pDb!=0);
7854 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7855 rc_err_oom_die(rc);
7856 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7857 rc_err_oom_die(rc);
7858 rc = sqlite3_step(pStmt);
7859 rc_err_oom_die(rc);
7860 sqlite3_finalize(pStmt);
7861 return 0;
7862 }else if( *pDb==0 ){
7863 return 0;
7864 }else{
7865 /* Formulate the columns spec, close the DB, zero *pDb. */
7866 char *zColsSpec = 0;
7867 int hasDupes = db_int(*pDb, zHasDupes);
7868 int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7869 if( hasDupes ){
7870 #ifdef SHELL_COLUMN_RENAME_CLEAN
7871 rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7872 rc_err_oom_die(rc);
7873 #endif
7874 rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7875 rc_err_oom_die(rc);
7876 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7877 rc_err_oom_die(rc);
7878 sqlite3_bind_int(pStmt, 1, nDigits);
7879 rc = sqlite3_step(pStmt);
7880 sqlite3_finalize(pStmt);
7881 if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
7883 assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7884 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7885 rc_err_oom_die(rc);
7886 rc = sqlite3_step(pStmt);
7887 if( rc==SQLITE_ROW ){
7888 zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7889 }else{
7890 zColsSpec = 0;
7892 if( pzRenamed!=0 ){
7893 if( !hasDupes ) *pzRenamed = 0;
7894 else{
7895 sqlite3_finalize(pStmt);
7896 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7897 && SQLITE_ROW==sqlite3_step(pStmt) ){
7898 *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7899 }else
7900 *pzRenamed = 0;
7903 sqlite3_finalize(pStmt);
7904 sqlite3_close(*pDb);
7905 *pDb = 0;
7906 return zColsSpec;
7911 ** Check if the sqlite_schema table contains one or more virtual tables. If
7912 ** parameter zLike is not NULL, then it is an SQL expression that the
7913 ** sqlite_schema row must also match. If one or more such rows are found,
7914 ** print the following warning to the output:
7916 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
7918 static int outputDumpWarning(ShellState *p, const char *zLike){
7919 int rc = SQLITE_OK;
7920 sqlite3_stmt *pStmt = 0;
7921 shellPreparePrintf(p->db, &rc, &pStmt,
7922 "SELECT 1 FROM sqlite_schema o WHERE "
7923 "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
7925 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7926 oputz("/* WARNING: "
7927 "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
7930 shellFinalize(&rc, pStmt);
7931 return rc;
7935 ** Fault-Simulator state and logic.
7937 static struct {
7938 int iId; /* ID that triggers a simulated fault. -1 means "any" */
7939 int iErr; /* The error code to return on a fault */
7940 int iCnt; /* Trigger the fault only if iCnt is already zero */
7941 int iInterval; /* Reset iCnt to this value after each fault */
7942 int eVerbose; /* When to print output */
7943 } faultsim_state = {-1, 0, 0, 0, 0};
7946 ** This is the fault-sim callback
7948 static int faultsim_callback(int iArg){
7949 if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
7950 return SQLITE_OK;
7952 if( faultsim_state.iCnt>0 ){
7953 faultsim_state.iCnt--;
7954 if( faultsim_state.eVerbose>=2 ){
7955 oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
7957 return SQLITE_OK;
7959 if( faultsim_state.eVerbose>=1 ){
7960 oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
7962 faultsim_state.iCnt = faultsim_state.iInterval;
7963 return faultsim_state.iErr;
7967 ** If an input line begins with "." then invoke this routine to
7968 ** process that line.
7970 ** Return 1 on error, 2 to exit, and 0 otherwise.
7972 static int do_meta_command(char *zLine, ShellState *p){
7973 int h = 1;
7974 int nArg = 0;
7975 int n, c;
7976 int rc = 0;
7977 char *azArg[52];
7979 #ifndef SQLITE_OMIT_VIRTUALTABLE
7980 if( p->expert.pExpert ){
7981 expertFinish(p, 1, 0);
7983 #endif
7985 /* Parse the input line into tokens.
7987 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7988 while( IsSpace(zLine[h]) ){ h++; }
7989 if( zLine[h]==0 ) break;
7990 if( zLine[h]=='\'' || zLine[h]=='"' ){
7991 int delim = zLine[h++];
7992 azArg[nArg++] = &zLine[h];
7993 while( zLine[h] && zLine[h]!=delim ){
7994 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7995 h++;
7997 if( zLine[h]==delim ){
7998 zLine[h++] = 0;
8000 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8001 }else{
8002 azArg[nArg++] = &zLine[h];
8003 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8004 if( zLine[h] ) zLine[h++] = 0;
8007 azArg[nArg] = 0;
8009 /* Process the input line.
8011 if( nArg==0 ) return 0; /* no tokens, no error */
8012 n = strlen30(azArg[0]);
8013 c = azArg[0][0];
8014 clearTempFile(p);
8016 #ifndef SQLITE_OMIT_AUTHORIZATION
8017 if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
8018 if( nArg!=2 ){
8019 eputz("Usage: .auth ON|OFF\n");
8020 rc = 1;
8021 goto meta_command_exit;
8023 open_db(p, 0);
8024 if( booleanValue(azArg[1]) ){
8025 sqlite3_set_authorizer(p->db, shellAuth, p);
8026 }else if( p->bSafeModePersist ){
8027 sqlite3_set_authorizer(p->db, safeModeAuth, p);
8028 }else{
8029 sqlite3_set_authorizer(p->db, 0, 0);
8031 }else
8032 #endif
8034 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8035 && !defined(SQLITE_SHELL_FIDDLE)
8036 if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
8037 open_db(p, 0);
8038 failIfSafeMode(p, "cannot run .archive in safe mode");
8039 rc = arDotCommand(p, 0, azArg, nArg);
8040 }else
8041 #endif
8043 #ifndef SQLITE_SHELL_FIDDLE
8044 if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
8045 || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
8047 const char *zDestFile = 0;
8048 const char *zDb = 0;
8049 sqlite3 *pDest;
8050 sqlite3_backup *pBackup;
8051 int j;
8052 int bAsync = 0;
8053 const char *zVfs = 0;
8054 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8055 for(j=1; j<nArg; j++){
8056 const char *z = azArg[j];
8057 if( z[0]=='-' ){
8058 if( z[1]=='-' ) z++;
8059 if( cli_strcmp(z, "-append")==0 ){
8060 zVfs = "apndvfs";
8061 }else
8062 if( cli_strcmp(z, "-async")==0 ){
8063 bAsync = 1;
8064 }else
8066 eputf("unknown option: %s\n", azArg[j]);
8067 return 1;
8069 }else if( zDestFile==0 ){
8070 zDestFile = azArg[j];
8071 }else if( zDb==0 ){
8072 zDb = zDestFile;
8073 zDestFile = azArg[j];
8074 }else{
8075 eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8076 return 1;
8079 if( zDestFile==0 ){
8080 eputz("missing FILENAME argument on .backup\n");
8081 return 1;
8083 if( zDb==0 ) zDb = "main";
8084 rc = sqlite3_open_v2(zDestFile, &pDest,
8085 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8086 if( rc!=SQLITE_OK ){
8087 eputf("Error: cannot open \"%s\"\n", zDestFile);
8088 close_db(pDest);
8089 return 1;
8091 if( bAsync ){
8092 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8093 0, 0, 0);
8095 open_db(p, 0);
8096 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8097 if( pBackup==0 ){
8098 eputf("Error: %s\n", sqlite3_errmsg(pDest));
8099 close_db(pDest);
8100 return 1;
8102 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8103 sqlite3_backup_finish(pBackup);
8104 if( rc==SQLITE_DONE ){
8105 rc = 0;
8106 }else{
8107 eputf("Error: %s\n", sqlite3_errmsg(pDest));
8108 rc = 1;
8110 close_db(pDest);
8111 }else
8112 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8114 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
8115 if( nArg==2 ){
8116 bail_on_error = booleanValue(azArg[1]);
8117 }else{
8118 eputz("Usage: .bail on|off\n");
8119 rc = 1;
8121 }else
8123 /* Undocumented. Legacy only. See "crnl" below */
8124 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
8125 if( nArg==2 ){
8126 if( booleanValue(azArg[1]) ){
8127 setBinaryMode(p->out, 1);
8128 }else{
8129 setTextMode(p->out, 1);
8131 }else{
8132 eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
8133 "Usage: .binary on|off\n");
8134 rc = 1;
8136 }else
8138 /* The undocumented ".breakpoint" command causes a call to the no-op
8139 ** routine named test_breakpoint().
8141 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
8142 test_breakpoint();
8143 }else
8145 #ifndef SQLITE_SHELL_FIDDLE
8146 if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
8147 failIfSafeMode(p, "cannot run .cd in safe mode");
8148 if( nArg==2 ){
8149 #if defined(_WIN32) || defined(WIN32)
8150 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8151 rc = !SetCurrentDirectoryW(z);
8152 sqlite3_free(z);
8153 #else
8154 rc = chdir(azArg[1]);
8155 #endif
8156 if( rc ){
8157 eputf("Cannot change to directory \"%s\"\n", azArg[1]);
8158 rc = 1;
8160 }else{
8161 eputz("Usage: .cd DIRECTORY\n");
8162 rc = 1;
8164 }else
8165 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8167 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
8168 if( nArg==2 ){
8169 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8170 }else{
8171 eputz("Usage: .changes on|off\n");
8172 rc = 1;
8174 }else
8176 #ifndef SQLITE_SHELL_FIDDLE
8177 /* Cancel output redirection, if it is currently set (by .testcase)
8178 ** Then read the content of the testcase-out.txt file and compare against
8179 ** azArg[1]. If there are differences, report an error and exit.
8181 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
8182 char *zRes = 0;
8183 output_reset(p);
8184 if( nArg!=2 ){
8185 eputz("Usage: .check GLOB-PATTERN\n");
8186 rc = 2;
8187 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8188 rc = 2;
8189 }else if( testcase_glob(azArg[1],zRes)==0 ){
8190 eputf("testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8191 p->zTestcase, azArg[1], zRes);
8192 rc = 1;
8193 }else{
8194 oputf("testcase-%s ok\n", p->zTestcase);
8195 p->nCheck++;
8197 sqlite3_free(zRes);
8198 }else
8199 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8201 #ifndef SQLITE_SHELL_FIDDLE
8202 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
8203 failIfSafeMode(p, "cannot run .clone in safe mode");
8204 if( nArg==2 ){
8205 tryToClone(p, azArg[1]);
8206 }else{
8207 eputz("Usage: .clone FILENAME\n");
8208 rc = 1;
8210 }else
8211 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8213 if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
8214 if( nArg==1 ){
8215 /* List available connections */
8216 int i;
8217 for(i=0; i<ArraySize(p->aAuxDb); i++){
8218 const char *zFile = p->aAuxDb[i].zDbFilename;
8219 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8220 zFile = "(not open)";
8221 }else if( zFile==0 ){
8222 zFile = "(memory)";
8223 }else if( zFile[0]==0 ){
8224 zFile = "(temporary-file)";
8226 if( p->pAuxDb == &p->aAuxDb[i] ){
8227 sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
8228 }else if( p->aAuxDb[i].db!=0 ){
8229 sputf(stdout, " %d: %s\n", i, zFile);
8232 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8233 int i = azArg[1][0] - '0';
8234 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8235 p->pAuxDb->db = p->db;
8236 p->pAuxDb = &p->aAuxDb[i];
8237 globalDb = p->db = p->pAuxDb->db;
8238 p->pAuxDb->db = 0;
8240 }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
8241 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8242 int i = azArg[2][0] - '0';
8243 if( i<0 || i>=ArraySize(p->aAuxDb) ){
8244 /* No-op */
8245 }else if( p->pAuxDb == &p->aAuxDb[i] ){
8246 eputz("cannot close the active database connection\n");
8247 rc = 1;
8248 }else if( p->aAuxDb[i].db ){
8249 session_close_all(p, i);
8250 close_db(p->aAuxDb[i].db);
8251 p->aAuxDb[i].db = 0;
8253 }else{
8254 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
8255 rc = 1;
8257 }else
8259 if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
8260 if( nArg==2 ){
8261 if( booleanValue(azArg[1]) ){
8262 setTextMode(p->out, 1);
8263 }else{
8264 setBinaryMode(p->out, 1);
8266 }else{
8267 #if !defined(_WIN32) && !defined(WIN32)
8268 eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
8269 #endif
8270 eputz("Usage: .crnl on|off\n");
8271 rc = 1;
8273 }else
8275 if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
8276 char **azName = 0;
8277 int nName = 0;
8278 sqlite3_stmt *pStmt;
8279 int i;
8280 open_db(p, 0);
8281 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8282 if( rc ){
8283 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8284 rc = 1;
8285 }else{
8286 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8287 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8288 const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8289 if( zSchema==0 || zFile==0 ) continue;
8290 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8291 shell_check_oom(azName);
8292 azName[nName*2] = strdup(zSchema);
8293 azName[nName*2+1] = strdup(zFile);
8294 nName++;
8297 sqlite3_finalize(pStmt);
8298 for(i=0; i<nName; i++){
8299 int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8300 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8301 const char *z = azName[i*2+1];
8302 oputf("%s: %s %s%s\n",
8303 azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
8304 eTxn==SQLITE_TXN_NONE ? "" :
8305 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8306 free(azName[i*2]);
8307 free(azName[i*2+1]);
8309 sqlite3_free(azName);
8310 }else
8312 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
8313 static const struct DbConfigChoices {
8314 const char *zName;
8315 int op;
8316 } aDbConfig[] = {
8317 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
8318 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
8319 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
8320 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
8321 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
8322 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
8323 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
8324 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8325 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
8326 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
8327 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8328 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
8329 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
8330 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
8331 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
8332 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
8333 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
8334 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
8336 int ii, v;
8337 open_db(p, 0);
8338 for(ii=0; ii<ArraySize(aDbConfig); ii++){
8339 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8340 if( nArg>=3 ){
8341 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8343 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8344 oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8345 if( nArg>1 ) break;
8347 if( nArg>1 && ii==ArraySize(aDbConfig) ){
8348 eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
8349 eputz("Enter \".dbconfig\" with no arguments for a list\n");
8351 }else
8353 #if SQLITE_SHELL_HAVE_RECOVER
8354 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
8355 rc = shell_dbinfo_command(p, nArg, azArg);
8356 }else
8358 if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
8359 open_db(p, 0);
8360 rc = recoverDatabaseCmd(p, nArg, azArg);
8361 }else
8362 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8364 if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
8365 char *zLike = 0;
8366 char *zSql;
8367 int i;
8368 int savedShowHeader = p->showHeader;
8369 int savedShellFlags = p->shellFlgs;
8370 ShellClearFlag(p,
8371 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8372 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8373 for(i=1; i<nArg; i++){
8374 if( azArg[i][0]=='-' ){
8375 const char *z = azArg[i]+1;
8376 if( z[0]=='-' ) z++;
8377 if( cli_strcmp(z,"preserve-rowids")==0 ){
8378 #ifdef SQLITE_OMIT_VIRTUALTABLE
8379 eputz("The --preserve-rowids option is not compatible"
8380 " with SQLITE_OMIT_VIRTUALTABLE\n");
8381 rc = 1;
8382 sqlite3_free(zLike);
8383 goto meta_command_exit;
8384 #else
8385 ShellSetFlag(p, SHFLG_PreserveRowid);
8386 #endif
8387 }else
8388 if( cli_strcmp(z,"newlines")==0 ){
8389 ShellSetFlag(p, SHFLG_Newlines);
8390 }else
8391 if( cli_strcmp(z,"data-only")==0 ){
8392 ShellSetFlag(p, SHFLG_DumpDataOnly);
8393 }else
8394 if( cli_strcmp(z,"nosys")==0 ){
8395 ShellSetFlag(p, SHFLG_DumpNoSys);
8396 }else
8398 eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8399 rc = 1;
8400 sqlite3_free(zLike);
8401 goto meta_command_exit;
8403 }else{
8404 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8405 ** only dump data for tables for which either the table name matches
8406 ** the LIKE pattern, or the table appears to be a shadow table of
8407 ** a virtual table for which the name matches the LIKE pattern.
8409 char *zExpr = sqlite3_mprintf(
8410 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8411 " SELECT 1 FROM sqlite_schema WHERE "
8412 " name LIKE %Q ESCAPE '\\' AND"
8413 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8414 " substr(o.name, 1, length(name)+1) == (name||'_')"
8415 ")", azArg[i], azArg[i]
8418 if( zLike ){
8419 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8420 }else{
8421 zLike = zExpr;
8426 open_db(p, 0);
8428 outputDumpWarning(p, zLike);
8429 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8430 /* When playing back a "dump", the content might appear in an order
8431 ** which causes immediate foreign key constraints to be violated.
8432 ** So disable foreign-key constraint enforcement to prevent problems. */
8433 oputz("PRAGMA foreign_keys=OFF;\n");
8434 oputz("BEGIN TRANSACTION;\n");
8436 p->writableSchema = 0;
8437 p->showHeader = 0;
8438 /* Set writable_schema=ON since doing so forces SQLite to initialize
8439 ** as much of the schema as it can even if the sqlite_schema table is
8440 ** corrupt. */
8441 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8442 p->nErr = 0;
8443 if( zLike==0 ) zLike = sqlite3_mprintf("true");
8444 zSql = sqlite3_mprintf(
8445 "SELECT name, type, sql FROM sqlite_schema AS o "
8446 "WHERE (%s) AND type=='table'"
8447 " AND sql NOT NULL"
8448 " ORDER BY tbl_name='sqlite_sequence', rowid",
8449 zLike
8451 run_schema_dump_query(p,zSql);
8452 sqlite3_free(zSql);
8453 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8454 zSql = sqlite3_mprintf(
8455 "SELECT sql FROM sqlite_schema AS o "
8456 "WHERE (%s) AND sql NOT NULL"
8457 " AND type IN ('index','trigger','view') "
8458 "ORDER BY type COLLATE NOCASE DESC",
8459 zLike
8461 run_table_dump_query(p, zSql);
8462 sqlite3_free(zSql);
8464 sqlite3_free(zLike);
8465 if( p->writableSchema ){
8466 oputz("PRAGMA writable_schema=OFF;\n");
8467 p->writableSchema = 0;
8469 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8470 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8471 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8472 oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8474 p->showHeader = savedShowHeader;
8475 p->shellFlgs = savedShellFlags;
8476 }else
8478 if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
8479 if( nArg==2 ){
8480 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8481 }else{
8482 eputz("Usage: .echo on|off\n");
8483 rc = 1;
8485 }else
8487 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
8488 if( nArg==2 ){
8489 p->autoEQPtest = 0;
8490 if( p->autoEQPtrace ){
8491 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8492 p->autoEQPtrace = 0;
8494 if( cli_strcmp(azArg[1],"full")==0 ){
8495 p->autoEQP = AUTOEQP_full;
8496 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
8497 p->autoEQP = AUTOEQP_trigger;
8498 #ifdef SQLITE_DEBUG
8499 }else if( cli_strcmp(azArg[1],"test")==0 ){
8500 p->autoEQP = AUTOEQP_on;
8501 p->autoEQPtest = 1;
8502 }else if( cli_strcmp(azArg[1],"trace")==0 ){
8503 p->autoEQP = AUTOEQP_full;
8504 p->autoEQPtrace = 1;
8505 open_db(p, 0);
8506 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8507 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8508 #endif
8509 }else{
8510 p->autoEQP = (u8)booleanValue(azArg[1]);
8512 }else{
8513 eputz("Usage: .eqp off|on|trace|trigger|full\n");
8514 rc = 1;
8516 }else
8518 #ifndef SQLITE_SHELL_FIDDLE
8519 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
8520 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8521 rc = 2;
8522 }else
8523 #endif
8525 /* The ".explain" command is automatic now. It is largely pointless. It
8526 ** retained purely for backwards compatibility */
8527 if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
8528 int val = 1;
8529 if( nArg>=2 ){
8530 if( cli_strcmp(azArg[1],"auto")==0 ){
8531 val = 99;
8532 }else{
8533 val = booleanValue(azArg[1]);
8536 if( val==1 && p->mode!=MODE_Explain ){
8537 p->normalMode = p->mode;
8538 p->mode = MODE_Explain;
8539 p->autoExplain = 0;
8540 }else if( val==0 ){
8541 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8542 p->autoExplain = 0;
8543 }else if( val==99 ){
8544 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8545 p->autoExplain = 1;
8547 }else
8549 #ifndef SQLITE_OMIT_VIRTUALTABLE
8550 if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
8551 if( p->bSafeMode ){
8552 eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
8553 azArg[0]);
8554 rc = 1;
8555 }else{
8556 open_db(p, 0);
8557 expertDotCommand(p, azArg, nArg);
8559 }else
8560 #endif
8562 if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
8563 static const struct {
8564 const char *zCtrlName; /* Name of a test-control option */
8565 int ctrlCode; /* Integer code for that option */
8566 const char *zUsage; /* Usage notes */
8567 } aCtrl[] = {
8568 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
8569 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
8570 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
8571 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
8572 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
8573 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8574 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
8575 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
8576 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
8577 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
8578 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8580 int filectrl = -1;
8581 int iCtrl = -1;
8582 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
8583 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
8584 int n2, i;
8585 const char *zCmd = 0;
8586 const char *zSchema = 0;
8588 open_db(p, 0);
8589 zCmd = nArg>=2 ? azArg[1] : "help";
8591 if( zCmd[0]=='-'
8592 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
8593 && nArg>=4
8595 zSchema = azArg[2];
8596 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8597 nArg -= 2;
8598 zCmd = azArg[1];
8601 /* The argument can optionally begin with "-" or "--" */
8602 if( zCmd[0]=='-' && zCmd[1] ){
8603 zCmd++;
8604 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8607 /* --help lists all file-controls */
8608 if( cli_strcmp(zCmd,"help")==0 ){
8609 oputz("Available file-controls:\n");
8610 for(i=0; i<ArraySize(aCtrl); i++){
8611 oputf(" .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8613 rc = 1;
8614 goto meta_command_exit;
8617 /* convert filectrl text option to value. allow any unique prefix
8618 ** of the option name, or a numerical value. */
8619 n2 = strlen30(zCmd);
8620 for(i=0; i<ArraySize(aCtrl); i++){
8621 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8622 if( filectrl<0 ){
8623 filectrl = aCtrl[i].ctrlCode;
8624 iCtrl = i;
8625 }else{
8626 eputf("Error: ambiguous file-control: \"%s\"\n"
8627 "Use \".filectrl --help\" for help\n", zCmd);
8628 rc = 1;
8629 goto meta_command_exit;
8633 if( filectrl<0 ){
8634 eputf("Error: unknown file-control: %s\n"
8635 "Use \".filectrl --help\" for help\n", zCmd);
8636 }else{
8637 switch(filectrl){
8638 case SQLITE_FCNTL_SIZE_LIMIT: {
8639 if( nArg!=2 && nArg!=3 ) break;
8640 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8641 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8642 isOk = 1;
8643 break;
8645 case SQLITE_FCNTL_LOCK_TIMEOUT:
8646 case SQLITE_FCNTL_CHUNK_SIZE: {
8647 int x;
8648 if( nArg!=3 ) break;
8649 x = (int)integerValue(azArg[2]);
8650 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8651 isOk = 2;
8652 break;
8654 case SQLITE_FCNTL_PERSIST_WAL:
8655 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8656 int x;
8657 if( nArg!=2 && nArg!=3 ) break;
8658 x = nArg==3 ? booleanValue(azArg[2]) : -1;
8659 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8660 iRes = x;
8661 isOk = 1;
8662 break;
8664 case SQLITE_FCNTL_DATA_VERSION:
8665 case SQLITE_FCNTL_HAS_MOVED: {
8666 int x;
8667 if( nArg!=2 ) break;
8668 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8669 iRes = x;
8670 isOk = 1;
8671 break;
8673 case SQLITE_FCNTL_TEMPFILENAME: {
8674 char *z = 0;
8675 if( nArg!=2 ) break;
8676 sqlite3_file_control(p->db, zSchema, filectrl, &z);
8677 if( z ){
8678 oputf("%s\n", z);
8679 sqlite3_free(z);
8681 isOk = 2;
8682 break;
8684 case SQLITE_FCNTL_RESERVE_BYTES: {
8685 int x;
8686 if( nArg>=3 ){
8687 x = atoi(azArg[2]);
8688 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8690 x = -1;
8691 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8692 oputf("%d\n", x);
8693 isOk = 2;
8694 break;
8698 if( isOk==0 && iCtrl>=0 ){
8699 oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8700 rc = 1;
8701 }else if( isOk==1 ){
8702 char zBuf[100];
8703 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8704 oputf("%s\n", zBuf);
8706 }else
8708 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
8709 ShellState data;
8710 int doStats = 0;
8711 memcpy(&data, p, sizeof(data));
8712 data.showHeader = 0;
8713 data.cMode = data.mode = MODE_Semi;
8714 if( nArg==2 && optionMatch(azArg[1], "indent") ){
8715 data.cMode = data.mode = MODE_Pretty;
8716 nArg = 1;
8718 if( nArg!=1 ){
8719 eputz("Usage: .fullschema ?--indent?\n");
8720 rc = 1;
8721 goto meta_command_exit;
8723 open_db(p, 0);
8724 rc = sqlite3_exec(p->db,
8725 "SELECT sql FROM"
8726 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8727 " FROM sqlite_schema UNION ALL"
8728 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8729 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8730 "ORDER BY x",
8731 callback, &data, 0
8733 if( rc==SQLITE_OK ){
8734 sqlite3_stmt *pStmt;
8735 rc = sqlite3_prepare_v2(p->db,
8736 "SELECT rowid FROM sqlite_schema"
8737 " WHERE name GLOB 'sqlite_stat[134]'",
8738 -1, &pStmt, 0);
8739 if( rc==SQLITE_OK ){
8740 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8741 sqlite3_finalize(pStmt);
8744 if( doStats==0 ){
8745 oputz("/* No STAT tables available */\n");
8746 }else{
8747 oputz("ANALYZE sqlite_schema;\n");
8748 data.cMode = data.mode = MODE_Insert;
8749 data.zDestTable = "sqlite_stat1";
8750 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8751 data.zDestTable = "sqlite_stat4";
8752 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8753 oputz("ANALYZE sqlite_schema;\n");
8755 }else
8757 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
8758 if( nArg==2 ){
8759 p->showHeader = booleanValue(azArg[1]);
8760 p->shellFlgs |= SHFLG_HeaderSet;
8761 }else{
8762 eputz("Usage: .headers on|off\n");
8763 rc = 1;
8765 }else
8767 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
8768 if( nArg>=2 ){
8769 n = showHelp(p->out, azArg[1]);
8770 if( n==0 ){
8771 oputf("Nothing matches '%s'\n", azArg[1]);
8773 }else{
8774 showHelp(p->out, 0);
8776 }else
8778 #ifndef SQLITE_SHELL_FIDDLE
8779 if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
8780 char *zTable = 0; /* Insert data into this table */
8781 char *zSchema = 0; /* within this schema (may default to "main") */
8782 char *zFile = 0; /* Name of file to extra content from */
8783 sqlite3_stmt *pStmt = NULL; /* A statement */
8784 int nCol; /* Number of columns in the table */
8785 int nByte; /* Number of bytes in an SQL string */
8786 int i, j; /* Loop counters */
8787 int needCommit; /* True to COMMIT or ROLLBACK at end */
8788 int nSep; /* Number of bytes in p->colSeparator[] */
8789 char *zSql; /* An SQL statement */
8790 char *zFullTabName; /* Table name with schema if applicable */
8791 ImportCtx sCtx; /* Reader context */
8792 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8793 int eVerbose = 0; /* Larger for more console output */
8794 int nSkip = 0; /* Initial lines to skip */
8795 int useOutputMode = 1; /* Use output mode to determine separators */
8796 char *zCreate = 0; /* CREATE TABLE statement text */
8798 failIfSafeMode(p, "cannot run .import in safe mode");
8799 memset(&sCtx, 0, sizeof(sCtx));
8800 if( p->mode==MODE_Ascii ){
8801 xRead = ascii_read_one_field;
8802 }else{
8803 xRead = csv_read_one_field;
8805 rc = 1;
8806 for(i=1; i<nArg; i++){
8807 char *z = azArg[i];
8808 if( z[0]=='-' && z[1]=='-' ) z++;
8809 if( z[0]!='-' ){
8810 if( zFile==0 ){
8811 zFile = z;
8812 }else if( zTable==0 ){
8813 zTable = z;
8814 }else{
8815 oputf("ERROR: extra argument: \"%s\". Usage:\n", z);
8816 showHelp(p->out, "import");
8817 goto meta_command_exit;
8819 }else if( cli_strcmp(z,"-v")==0 ){
8820 eVerbose++;
8821 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
8822 zSchema = azArg[++i];
8823 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
8824 nSkip = integerValue(azArg[++i]);
8825 }else if( cli_strcmp(z,"-ascii")==0 ){
8826 sCtx.cColSep = SEP_Unit[0];
8827 sCtx.cRowSep = SEP_Record[0];
8828 xRead = ascii_read_one_field;
8829 useOutputMode = 0;
8830 }else if( cli_strcmp(z,"-csv")==0 ){
8831 sCtx.cColSep = ',';
8832 sCtx.cRowSep = '\n';
8833 xRead = csv_read_one_field;
8834 useOutputMode = 0;
8835 }else{
8836 oputf("ERROR: unknown option: \"%s\". Usage:\n", z);
8837 showHelp(p->out, "import");
8838 goto meta_command_exit;
8841 if( zTable==0 ){
8842 oputf("ERROR: missing %s argument. Usage:\n",
8843 zFile==0 ? "FILE" : "TABLE");
8844 showHelp(p->out, "import");
8845 goto meta_command_exit;
8847 seenInterrupt = 0;
8848 open_db(p, 0);
8849 if( useOutputMode ){
8850 /* If neither the --csv or --ascii options are specified, then set
8851 ** the column and row separator characters from the output mode. */
8852 nSep = strlen30(p->colSeparator);
8853 if( nSep==0 ){
8854 eputz("Error: non-null column separator required for import\n");
8855 goto meta_command_exit;
8857 if( nSep>1 ){
8858 eputz("Error: multi-character column separators not allowed"
8859 " for import\n");
8860 goto meta_command_exit;
8862 nSep = strlen30(p->rowSeparator);
8863 if( nSep==0 ){
8864 eputz("Error: non-null row separator required for import\n");
8865 goto meta_command_exit;
8867 if( nSep==2 && p->mode==MODE_Csv
8868 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
8870 /* When importing CSV (only), if the row separator is set to the
8871 ** default output row separator, change it to the default input
8872 ** row separator. This avoids having to maintain different input
8873 ** and output row separators. */
8874 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8875 nSep = strlen30(p->rowSeparator);
8877 if( nSep>1 ){
8878 eputz("Error: multi-character row separators not allowed"
8879 " for import\n");
8880 goto meta_command_exit;
8882 sCtx.cColSep = (u8)p->colSeparator[0];
8883 sCtx.cRowSep = (u8)p->rowSeparator[0];
8885 sCtx.zFile = zFile;
8886 sCtx.nLine = 1;
8887 if( sCtx.zFile[0]=='|' ){
8888 #ifdef SQLITE_OMIT_POPEN
8889 eputz("Error: pipes are not supported in this OS\n");
8890 goto meta_command_exit;
8891 #else
8892 sCtx.in = popen(sCtx.zFile+1, "r");
8893 sCtx.zFile = "<pipe>";
8894 sCtx.xCloser = pclose;
8895 #endif
8896 }else{
8897 sCtx.in = fopen(sCtx.zFile, "rb");
8898 sCtx.xCloser = fclose;
8900 if( sCtx.in==0 ){
8901 eputf("Error: cannot open \"%s\"\n", zFile);
8902 goto meta_command_exit;
8904 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8905 char zSep[2];
8906 zSep[1] = 0;
8907 zSep[0] = sCtx.cColSep;
8908 oputz("Column separator ");
8909 output_c_string(zSep);
8910 oputz(", row separator ");
8911 zSep[0] = sCtx.cRowSep;
8912 output_c_string(zSep);
8913 oputz("\n");
8915 sCtx.z = sqlite3_malloc64(120);
8916 if( sCtx.z==0 ){
8917 import_cleanup(&sCtx);
8918 shell_out_of_memory();
8920 /* Below, resources must be freed before exit. */
8921 while( (nSkip--)>0 ){
8922 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8924 if( zSchema!=0 ){
8925 zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8926 }else{
8927 zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8929 zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8930 if( zSql==0 || zFullTabName==0 ){
8931 import_cleanup(&sCtx);
8932 shell_out_of_memory();
8934 nByte = strlen30(zSql);
8935 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8936 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
8937 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8938 sqlite3 *dbCols = 0;
8939 char *zRenames = 0;
8940 char *zColDefs;
8941 zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
8942 while( xRead(&sCtx) ){
8943 zAutoColumn(sCtx.z, &dbCols, 0);
8944 if( sCtx.cTerm!=sCtx.cColSep ) break;
8946 zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8947 if( zRenames!=0 ){
8948 sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8949 "Columns renamed during .import %s due to duplicates:\n"
8950 "%s\n", sCtx.zFile, zRenames);
8951 sqlite3_free(zRenames);
8953 assert(dbCols==0);
8954 if( zColDefs==0 ){
8955 eputf("%s: empty file\n", sCtx.zFile);
8956 import_fail:
8957 sqlite3_free(zCreate);
8958 sqlite3_free(zSql);
8959 sqlite3_free(zFullTabName);
8960 import_cleanup(&sCtx);
8961 rc = 1;
8962 goto meta_command_exit;
8964 zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8965 if( eVerbose>=1 ){
8966 oputf("%s\n", zCreate);
8968 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8969 if( rc ){
8970 eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8971 goto import_fail;
8973 sqlite3_free(zCreate);
8974 zCreate = 0;
8975 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8977 if( rc ){
8978 if (pStmt) sqlite3_finalize(pStmt);
8979 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8980 goto import_fail;
8982 sqlite3_free(zSql);
8983 nCol = sqlite3_column_count(pStmt);
8984 sqlite3_finalize(pStmt);
8985 pStmt = 0;
8986 if( nCol==0 ) return 0; /* no columns, no error */
8987 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8988 if( zSql==0 ){
8989 import_cleanup(&sCtx);
8990 shell_out_of_memory();
8992 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
8993 j = strlen30(zSql);
8994 for(i=1; i<nCol; i++){
8995 zSql[j++] = ',';
8996 zSql[j++] = '?';
8998 zSql[j++] = ')';
8999 zSql[j] = 0;
9000 if( eVerbose>=2 ){
9001 oputf("Insert using: %s\n", zSql);
9003 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9004 if( rc ){
9005 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9006 if (pStmt) sqlite3_finalize(pStmt);
9007 goto import_fail;
9009 sqlite3_free(zSql);
9010 sqlite3_free(zFullTabName);
9011 needCommit = sqlite3_get_autocommit(p->db);
9012 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9014 int startLine = sCtx.nLine;
9015 for(i=0; i<nCol; i++){
9016 char *z = xRead(&sCtx);
9018 ** Did we reach end-of-file before finding any columns?
9019 ** If so, stop instead of NULL filling the remaining columns.
9021 if( z==0 && i==0 ) break;
9023 ** Did we reach end-of-file OR end-of-line before finding any
9024 ** columns in ASCII mode? If so, stop instead of NULL filling
9025 ** the remaining columns.
9027 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9029 ** For CSV mode, per RFC 4180, accept EOF in lieu of final
9030 ** record terminator but only for last field of multi-field row.
9031 ** (If there are too few fields, it's not valid CSV anyway.)
9033 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
9034 z = "";
9036 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9037 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9038 eputf("%s:%d: expected %d columns but found %d"
9039 " - filling the rest with NULL\n",
9040 sCtx.zFile, startLine, nCol, i+1);
9041 i += 2;
9042 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9045 if( sCtx.cTerm==sCtx.cColSep ){
9047 xRead(&sCtx);
9048 i++;
9049 }while( sCtx.cTerm==sCtx.cColSep );
9050 eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
9051 sCtx.zFile, startLine, nCol, i);
9053 if( i>=nCol ){
9054 sqlite3_step(pStmt);
9055 rc = sqlite3_reset(pStmt);
9056 if( rc!=SQLITE_OK ){
9057 eputf("%s:%d: INSERT failed: %s\n",
9058 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
9059 sCtx.nErr++;
9060 }else{
9061 sCtx.nRow++;
9064 }while( sCtx.cTerm!=EOF );
9066 import_cleanup(&sCtx);
9067 sqlite3_finalize(pStmt);
9068 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9069 if( eVerbose>0 ){
9070 oputf("Added %d rows with %d errors using %d lines of input\n",
9071 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9073 }else
9074 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9076 #ifndef SQLITE_UNTESTABLE
9077 if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
9078 char *zSql;
9079 char *zCollist = 0;
9080 sqlite3_stmt *pStmt;
9081 int tnum = 0;
9082 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
9083 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9084 int i;
9085 if( !ShellHasFlag(p,SHFLG_TestingMode) ){
9086 eputf(".%s unavailable without --unsafe-testing\n",
9087 "imposter");
9088 rc = 1;
9089 goto meta_command_exit;
9091 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9092 eputz("Usage: .imposter INDEX IMPOSTER\n"
9093 " .imposter off\n");
9094 /* Also allowed, but not documented:
9096 ** .imposter TABLE IMPOSTER
9098 ** where TABLE is a WITHOUT ROWID table. In that case, the
9099 ** imposter is another WITHOUT ROWID table with the columns in
9100 ** storage order. */
9101 rc = 1;
9102 goto meta_command_exit;
9104 open_db(p, 0);
9105 if( nArg==2 ){
9106 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9107 goto meta_command_exit;
9109 zSql = sqlite3_mprintf(
9110 "SELECT rootpage, 0 FROM sqlite_schema"
9111 " WHERE name='%q' AND type='index'"
9112 "UNION ALL "
9113 "SELECT rootpage, 1 FROM sqlite_schema"
9114 " WHERE name='%q' AND type='table'"
9115 " AND sql LIKE '%%without%%rowid%%'",
9116 azArg[1], azArg[1]
9118 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9119 sqlite3_free(zSql);
9120 if( sqlite3_step(pStmt)==SQLITE_ROW ){
9121 tnum = sqlite3_column_int(pStmt, 0);
9122 isWO = sqlite3_column_int(pStmt, 1);
9124 sqlite3_finalize(pStmt);
9125 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9126 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9127 sqlite3_free(zSql);
9128 i = 0;
9129 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9130 char zLabel[20];
9131 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9132 i++;
9133 if( zCol==0 ){
9134 if( sqlite3_column_int(pStmt,1)==-1 ){
9135 zCol = "_ROWID_";
9136 }else{
9137 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9138 zCol = zLabel;
9141 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9142 lenPK = (int)strlen(zCollist);
9144 if( zCollist==0 ){
9145 zCollist = sqlite3_mprintf("\"%w\"", zCol);
9146 }else{
9147 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9150 sqlite3_finalize(pStmt);
9151 if( i==0 || tnum==0 ){
9152 eputf("no such index: \"%s\"\n", azArg[1]);
9153 rc = 1;
9154 sqlite3_free(zCollist);
9155 goto meta_command_exit;
9157 if( lenPK==0 ) lenPK = 100000;
9158 zSql = sqlite3_mprintf(
9159 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9160 azArg[2], zCollist, lenPK, zCollist);
9161 sqlite3_free(zCollist);
9162 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9163 if( rc==SQLITE_OK ){
9164 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9165 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9166 if( rc ){
9167 eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9168 }else{
9169 sputf(stdout, "%s;\n", zSql);
9170 sputf(stdout, "WARNING: writing to an imposter table will corrupt"
9171 " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
9173 }else{
9174 eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9175 rc = 1;
9177 sqlite3_free(zSql);
9178 }else
9179 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9181 if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
9182 i64 iArg = 0;
9183 if( nArg==2 ){
9184 iArg = integerValue(azArg[1]);
9185 if( iArg==0 ) iArg = -1;
9187 if( (nArg!=1 && nArg!=2) || iArg<0 ){
9188 eputf("%s","Usage: .intck STEPS_PER_UNLOCK\n");
9189 rc = 1;
9190 goto meta_command_exit;
9192 open_db(p, 0);
9193 rc = intckDatabaseCmd(p, iArg);
9194 }else
9196 #ifdef SQLITE_ENABLE_IOTRACE
9197 if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
9198 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9199 if( iotrace && iotrace!=stdout ) fclose(iotrace);
9200 iotrace = 0;
9201 if( nArg<2 ){
9202 sqlite3IoTrace = 0;
9203 }else if( cli_strcmp(azArg[1], "-")==0 ){
9204 sqlite3IoTrace = iotracePrintf;
9205 iotrace = stdout;
9206 }else{
9207 iotrace = fopen(azArg[1], "w");
9208 if( iotrace==0 ){
9209 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9210 sqlite3IoTrace = 0;
9211 rc = 1;
9212 }else{
9213 sqlite3IoTrace = iotracePrintf;
9216 }else
9217 #endif
9219 if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
9220 static const struct {
9221 const char *zLimitName; /* Name of a limit */
9222 int limitCode; /* Integer code for that limit */
9223 } aLimit[] = {
9224 { "length", SQLITE_LIMIT_LENGTH },
9225 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
9226 { "column", SQLITE_LIMIT_COLUMN },
9227 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
9228 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
9229 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
9230 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
9231 { "attached", SQLITE_LIMIT_ATTACHED },
9232 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
9233 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
9234 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
9235 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
9237 int i, n2;
9238 open_db(p, 0);
9239 if( nArg==1 ){
9240 for(i=0; i<ArraySize(aLimit); i++){
9241 sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
9242 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9244 }else if( nArg>3 ){
9245 eputz("Usage: .limit NAME ?NEW-VALUE?\n");
9246 rc = 1;
9247 goto meta_command_exit;
9248 }else{
9249 int iLimit = -1;
9250 n2 = strlen30(azArg[1]);
9251 for(i=0; i<ArraySize(aLimit); i++){
9252 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9253 if( iLimit<0 ){
9254 iLimit = i;
9255 }else{
9256 eputf("ambiguous limit: \"%s\"\n", azArg[1]);
9257 rc = 1;
9258 goto meta_command_exit;
9262 if( iLimit<0 ){
9263 eputf("unknown limit: \"%s\"\n"
9264 "enter \".limits\" with no arguments for a list.\n",
9265 azArg[1]);
9266 rc = 1;
9267 goto meta_command_exit;
9269 if( nArg==3 ){
9270 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9271 (int)integerValue(azArg[2]));
9273 sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
9274 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9276 }else
9278 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
9279 open_db(p, 0);
9280 lintDotCommand(p, azArg, nArg);
9281 }else
9283 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9284 if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
9285 const char *zFile, *zProc;
9286 char *zErrMsg = 0;
9287 failIfSafeMode(p, "cannot run .load in safe mode");
9288 if( nArg<2 || azArg[1][0]==0 ){
9289 /* Must have a non-empty FILE. (Will not load self.) */
9290 eputz("Usage: .load FILE ?ENTRYPOINT?\n");
9291 rc = 1;
9292 goto meta_command_exit;
9294 zFile = azArg[1];
9295 zProc = nArg>=3 ? azArg[2] : 0;
9296 open_db(p, 0);
9297 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9298 if( rc!=SQLITE_OK ){
9299 eputf("Error: %s\n", zErrMsg);
9300 sqlite3_free(zErrMsg);
9301 rc = 1;
9303 }else
9304 #endif
9306 if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
9307 if( nArg!=2 ){
9308 eputz("Usage: .log FILENAME\n");
9309 rc = 1;
9310 }else{
9311 const char *zFile = azArg[1];
9312 if( p->bSafeMode
9313 && cli_strcmp(zFile,"on")!=0
9314 && cli_strcmp(zFile,"off")!=0
9316 sputz(stdout, "cannot set .log to anything other"
9317 " than \"on\" or \"off\"\n");
9318 zFile = "off";
9320 output_file_close(p->pLog);
9321 if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
9322 p->pLog = output_file_open(zFile, 0);
9324 }else
9326 if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
9327 const char *zMode = 0;
9328 const char *zTabname = 0;
9329 int i, n2;
9330 ColModeOpts cmOpts = ColModeOpts_default;
9331 for(i=1; i<nArg; i++){
9332 const char *z = azArg[i];
9333 if( optionMatch(z,"wrap") && i+1<nArg ){
9334 cmOpts.iWrap = integerValue(azArg[++i]);
9335 }else if( optionMatch(z,"ww") ){
9336 cmOpts.bWordWrap = 1;
9337 }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9338 cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9339 }else if( optionMatch(z,"quote") ){
9340 cmOpts.bQuote = 1;
9341 }else if( optionMatch(z,"noquote") ){
9342 cmOpts.bQuote = 0;
9343 }else if( zMode==0 ){
9344 zMode = z;
9345 /* Apply defaults for qbox pseudo-mode. If that
9346 * overwrites already-set values, user was informed of this.
9348 if( cli_strcmp(z, "qbox")==0 ){
9349 ColModeOpts cmo = ColModeOpts_default_qbox;
9350 zMode = "box";
9351 cmOpts = cmo;
9353 }else if( zTabname==0 ){
9354 zTabname = z;
9355 }else if( z[0]=='-' ){
9356 eputf("unknown option: %s\n", z);
9357 eputz("options:\n"
9358 " --noquote\n"
9359 " --quote\n"
9360 " --wordwrap on/off\n"
9361 " --wrap N\n"
9362 " --ww\n");
9363 rc = 1;
9364 goto meta_command_exit;
9365 }else{
9366 eputf("extra argument: \"%s\"\n", z);
9367 rc = 1;
9368 goto meta_command_exit;
9371 if( zMode==0 ){
9372 if( p->mode==MODE_Column
9373 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9375 oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9376 modeDescr[p->mode], p->cmOpts.iWrap,
9377 p->cmOpts.bWordWrap ? "on" : "off",
9378 p->cmOpts.bQuote ? "" : "no");
9379 }else{
9380 oputf("current output mode: %s\n", modeDescr[p->mode]);
9382 zMode = modeDescr[p->mode];
9384 n2 = strlen30(zMode);
9385 if( cli_strncmp(zMode,"lines",n2)==0 ){
9386 p->mode = MODE_Line;
9387 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9388 }else if( cli_strncmp(zMode,"columns",n2)==0 ){
9389 p->mode = MODE_Column;
9390 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9391 p->showHeader = 1;
9393 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9394 p->cmOpts = cmOpts;
9395 }else if( cli_strncmp(zMode,"list",n2)==0 ){
9396 p->mode = MODE_List;
9397 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9398 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9399 }else if( cli_strncmp(zMode,"html",n2)==0 ){
9400 p->mode = MODE_Html;
9401 }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
9402 p->mode = MODE_Tcl;
9403 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9404 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9405 }else if( cli_strncmp(zMode,"csv",n2)==0 ){
9406 p->mode = MODE_Csv;
9407 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9408 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9409 }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
9410 p->mode = MODE_List;
9411 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9412 }else if( cli_strncmp(zMode,"insert",n2)==0 ){
9413 p->mode = MODE_Insert;
9414 set_table_name(p, zTabname ? zTabname : "table");
9415 }else if( cli_strncmp(zMode,"quote",n2)==0 ){
9416 p->mode = MODE_Quote;
9417 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9418 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9419 }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
9420 p->mode = MODE_Ascii;
9421 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9422 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9423 }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
9424 p->mode = MODE_Markdown;
9425 p->cmOpts = cmOpts;
9426 }else if( cli_strncmp(zMode,"table",n2)==0 ){
9427 p->mode = MODE_Table;
9428 p->cmOpts = cmOpts;
9429 }else if( cli_strncmp(zMode,"box",n2)==0 ){
9430 p->mode = MODE_Box;
9431 p->cmOpts = cmOpts;
9432 }else if( cli_strncmp(zMode,"count",n2)==0 ){
9433 p->mode = MODE_Count;
9434 }else if( cli_strncmp(zMode,"off",n2)==0 ){
9435 p->mode = MODE_Off;
9436 }else if( cli_strncmp(zMode,"json",n2)==0 ){
9437 p->mode = MODE_Json;
9438 }else{
9439 eputz("Error: mode should be one of: "
9440 "ascii box column csv html insert json line list markdown "
9441 "qbox quote table tabs tcl\n");
9442 rc = 1;
9444 p->cMode = p->mode;
9445 }else
9447 #ifndef SQLITE_SHELL_FIDDLE
9448 if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
9449 if( nArg!=2 ){
9450 eputz("Usage: .nonce NONCE\n");
9451 rc = 1;
9452 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
9453 eputf("line %d: incorrect nonce: \"%s\"\n",
9454 p->lineno, azArg[1]);
9455 exit(1);
9456 }else{
9457 p->bSafeMode = 0;
9458 return 0; /* Return immediately to bypass the safe mode reset
9459 ** at the end of this procedure */
9461 }else
9462 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9464 if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
9465 if( nArg==2 ){
9466 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9467 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9468 }else{
9469 eputz("Usage: .nullvalue STRING\n");
9470 rc = 1;
9472 }else
9474 if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
9475 const char *zFN = 0; /* Pointer to constant filename */
9476 char *zNewFilename = 0; /* Name of the database file to open */
9477 int iName = 1; /* Index in azArg[] of the filename */
9478 int newFlag = 0; /* True to delete file before opening */
9479 int openMode = SHELL_OPEN_UNSPEC;
9481 /* Check for command-line arguments */
9482 for(iName=1; iName<nArg; iName++){
9483 const char *z = azArg[iName];
9484 #ifndef SQLITE_SHELL_FIDDLE
9485 if( optionMatch(z,"new") ){
9486 newFlag = 1;
9487 #ifdef SQLITE_HAVE_ZLIB
9488 }else if( optionMatch(z, "zip") ){
9489 openMode = SHELL_OPEN_ZIPFILE;
9490 #endif
9491 }else if( optionMatch(z, "append") ){
9492 openMode = SHELL_OPEN_APPENDVFS;
9493 }else if( optionMatch(z, "readonly") ){
9494 openMode = SHELL_OPEN_READONLY;
9495 }else if( optionMatch(z, "nofollow") ){
9496 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9497 #ifndef SQLITE_OMIT_DESERIALIZE
9498 }else if( optionMatch(z, "deserialize") ){
9499 openMode = SHELL_OPEN_DESERIALIZE;
9500 }else if( optionMatch(z, "hexdb") ){
9501 openMode = SHELL_OPEN_HEXDB;
9502 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9503 p->szMax = integerValue(azArg[++iName]);
9504 #endif /* SQLITE_OMIT_DESERIALIZE */
9505 }else
9506 #endif /* !SQLITE_SHELL_FIDDLE */
9507 if( z[0]=='-' ){
9508 eputf("unknown option: %s\n", z);
9509 rc = 1;
9510 goto meta_command_exit;
9511 }else if( zFN ){
9512 eputf("extra argument: \"%s\"\n", z);
9513 rc = 1;
9514 goto meta_command_exit;
9515 }else{
9516 zFN = z;
9520 /* Close the existing database */
9521 session_close_all(p, -1);
9522 close_db(p->db);
9523 p->db = 0;
9524 p->pAuxDb->zDbFilename = 0;
9525 sqlite3_free(p->pAuxDb->zFreeOnClose);
9526 p->pAuxDb->zFreeOnClose = 0;
9527 p->openMode = openMode;
9528 p->openFlags = 0;
9529 p->szMax = 0;
9531 /* If a filename is specified, try to open it first */
9532 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9533 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9534 #ifndef SQLITE_SHELL_FIDDLE
9535 if( p->bSafeMode
9536 && p->openMode!=SHELL_OPEN_HEXDB
9537 && zFN
9538 && cli_strcmp(zFN,":memory:")!=0
9540 failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9542 #else
9543 /* WASM mode has its own sandboxed pseudo-filesystem. */
9544 #endif
9545 if( zFN ){
9546 zNewFilename = sqlite3_mprintf("%s", zFN);
9547 shell_check_oom(zNewFilename);
9548 }else{
9549 zNewFilename = 0;
9551 p->pAuxDb->zDbFilename = zNewFilename;
9552 open_db(p, OPEN_DB_KEEPALIVE);
9553 if( p->db==0 ){
9554 eputf("Error: cannot open '%s'\n", zNewFilename);
9555 sqlite3_free(zNewFilename);
9556 }else{
9557 p->pAuxDb->zFreeOnClose = zNewFilename;
9560 if( p->db==0 ){
9561 /* As a fall-back open a TEMP database */
9562 p->pAuxDb->zDbFilename = 0;
9563 open_db(p, 0);
9565 }else
9567 #ifndef SQLITE_SHELL_FIDDLE
9568 if( (c=='o'
9569 && (cli_strncmp(azArg[0], "output", n)==0
9570 || cli_strncmp(azArg[0], "once", n)==0))
9571 || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
9573 char *zFile = 0;
9574 int bTxtMode = 0;
9575 int i;
9576 int eMode = 0;
9577 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
9578 static const char *zBomUtf8 = "\xef\xbb\xbf";
9579 const char *zBom = 0;
9581 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9582 if( c=='e' ){
9583 eMode = 'x';
9584 bOnce = 2;
9585 }else if( cli_strncmp(azArg[0],"once",n)==0 ){
9586 bOnce = 1;
9588 for(i=1; i<nArg; i++){
9589 char *z = azArg[i];
9590 if( z[0]=='-' ){
9591 if( z[1]=='-' ) z++;
9592 if( cli_strcmp(z,"-bom")==0 ){
9593 zBom = zBomUtf8;
9594 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
9595 eMode = 'x'; /* spreadsheet */
9596 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
9597 eMode = 'e'; /* text editor */
9598 }else{
9599 oputf("ERROR: unknown option: \"%s\". Usage:\n", azArg[i]);
9600 showHelp(p->out, azArg[0]);
9601 rc = 1;
9602 goto meta_command_exit;
9604 }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9605 zFile = sqlite3_mprintf("%s", z);
9606 if( zFile && zFile[0]=='|' ){
9607 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9608 break;
9610 }else{
9611 oputf("ERROR: extra parameter: \"%s\". Usage:\n", azArg[i]);
9612 showHelp(p->out, azArg[0]);
9613 rc = 1;
9614 sqlite3_free(zFile);
9615 goto meta_command_exit;
9618 if( zFile==0 ){
9619 zFile = sqlite3_mprintf("stdout");
9621 if( bOnce ){
9622 p->outCount = 2;
9623 }else{
9624 p->outCount = 0;
9626 output_reset(p);
9627 #ifndef SQLITE_NOHAVE_SYSTEM
9628 if( eMode=='e' || eMode=='x' ){
9629 p->doXdgOpen = 1;
9630 outputModePush(p);
9631 if( eMode=='x' ){
9632 /* spreadsheet mode. Output as CSV. */
9633 newTempFile(p, "csv");
9634 ShellClearFlag(p, SHFLG_Echo);
9635 p->mode = MODE_Csv;
9636 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9637 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9638 }else{
9639 /* text editor mode */
9640 newTempFile(p, "txt");
9641 bTxtMode = 1;
9643 sqlite3_free(zFile);
9644 zFile = sqlite3_mprintf("%s", p->zTempFile);
9646 #endif /* SQLITE_NOHAVE_SYSTEM */
9647 shell_check_oom(zFile);
9648 if( zFile[0]=='|' ){
9649 #ifdef SQLITE_OMIT_POPEN
9650 eputz("Error: pipes are not supported in this OS\n");
9651 rc = 1;
9652 output_redir(p, stdout);
9653 #else
9654 FILE *pfPipe = popen(zFile + 1, "w");
9655 if( pfPipe==0 ){
9656 eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
9657 rc = 1;
9658 }else{
9659 output_redir(p, pfPipe);
9660 if( zBom ) oputz(zBom);
9661 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9663 #endif
9664 }else{
9665 FILE *pfFile = output_file_open(zFile, bTxtMode);
9666 if( pfFile==0 ){
9667 if( cli_strcmp(zFile,"off")!=0 ){
9668 eputf("Error: cannot write to \"%s\"\n", zFile);
9670 rc = 1;
9671 } else {
9672 output_redir(p, pfFile);
9673 if( zBom ) oputz(zBom);
9674 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9677 sqlite3_free(zFile);
9678 }else
9679 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9681 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
9682 open_db(p,0);
9683 if( nArg<=1 ) goto parameter_syntax_error;
9685 /* .parameter clear
9686 ** Clear all bind parameters by dropping the TEMP table that holds them.
9688 if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
9689 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9690 0, 0, 0);
9691 }else
9693 /* .parameter list
9694 ** List all bind parameters.
9696 if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
9697 sqlite3_stmt *pStmt = 0;
9698 int rx;
9699 int len = 0;
9700 rx = sqlite3_prepare_v2(p->db,
9701 "SELECT max(length(key)) "
9702 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9703 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9704 len = sqlite3_column_int(pStmt, 0);
9705 if( len>40 ) len = 40;
9707 sqlite3_finalize(pStmt);
9708 pStmt = 0;
9709 if( len ){
9710 rx = sqlite3_prepare_v2(p->db,
9711 "SELECT key, quote(value) "
9712 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9713 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9714 oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9715 sqlite3_column_text(pStmt,1));
9717 sqlite3_finalize(pStmt);
9719 }else
9721 /* .parameter init
9722 ** Make sure the TEMP table used to hold bind parameters exists.
9723 ** Create it if necessary.
9725 if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
9726 bind_table_init(p);
9727 }else
9729 /* .parameter set NAME VALUE
9730 ** Set or reset a bind parameter. NAME should be the full parameter
9731 ** name exactly as it appears in the query. (ex: $abc, @def). The
9732 ** VALUE can be in either SQL literal notation, or if not it will be
9733 ** understood to be a text string.
9735 if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
9736 int rx;
9737 char *zSql;
9738 sqlite3_stmt *pStmt;
9739 const char *zKey = azArg[2];
9740 const char *zValue = azArg[3];
9741 bind_table_init(p);
9742 zSql = sqlite3_mprintf(
9743 "REPLACE INTO temp.sqlite_parameters(key,value)"
9744 "VALUES(%Q,%s);", zKey, zValue);
9745 shell_check_oom(zSql);
9746 pStmt = 0;
9747 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9748 sqlite3_free(zSql);
9749 if( rx!=SQLITE_OK ){
9750 sqlite3_finalize(pStmt);
9751 pStmt = 0;
9752 zSql = sqlite3_mprintf(
9753 "REPLACE INTO temp.sqlite_parameters(key,value)"
9754 "VALUES(%Q,%Q);", zKey, zValue);
9755 shell_check_oom(zSql);
9756 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9757 sqlite3_free(zSql);
9758 if( rx!=SQLITE_OK ){
9759 oputf("Error: %s\n", sqlite3_errmsg(p->db));
9760 sqlite3_finalize(pStmt);
9761 pStmt = 0;
9762 rc = 1;
9765 sqlite3_step(pStmt);
9766 sqlite3_finalize(pStmt);
9767 }else
9769 /* .parameter unset NAME
9770 ** Remove the NAME binding from the parameter binding table, if it
9771 ** exists.
9773 if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
9774 char *zSql = sqlite3_mprintf(
9775 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9776 shell_check_oom(zSql);
9777 sqlite3_exec(p->db, zSql, 0, 0, 0);
9778 sqlite3_free(zSql);
9779 }else
9780 /* If no command name matches, show a syntax error */
9781 parameter_syntax_error:
9782 showHelp(p->out, "parameter");
9783 }else
9785 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
9786 int i;
9787 for(i=1; i<nArg; i++){
9788 if( i>1 ) oputz(" ");
9789 oputz(azArg[i]);
9791 oputz("\n");
9792 }else
9794 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9795 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
9796 int i;
9797 int nn = 0;
9798 p->flgProgress = 0;
9799 p->mxProgress = 0;
9800 p->nProgress = 0;
9801 for(i=1; i<nArg; i++){
9802 const char *z = azArg[i];
9803 if( z[0]=='-' ){
9804 z++;
9805 if( z[0]=='-' ) z++;
9806 if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
9807 p->flgProgress |= SHELL_PROGRESS_QUIET;
9808 continue;
9810 if( cli_strcmp(z,"reset")==0 ){
9811 p->flgProgress |= SHELL_PROGRESS_RESET;
9812 continue;
9814 if( cli_strcmp(z,"once")==0 ){
9815 p->flgProgress |= SHELL_PROGRESS_ONCE;
9816 continue;
9818 if( cli_strcmp(z,"limit")==0 ){
9819 if( i+1>=nArg ){
9820 eputz("Error: missing argument on --limit\n");
9821 rc = 1;
9822 goto meta_command_exit;
9823 }else{
9824 p->mxProgress = (int)integerValue(azArg[++i]);
9826 continue;
9828 eputf("Error: unknown option: \"%s\"\n", azArg[i]);
9829 rc = 1;
9830 goto meta_command_exit;
9831 }else{
9832 nn = (int)integerValue(z);
9835 open_db(p, 0);
9836 sqlite3_progress_handler(p->db, nn, progress_handler, p);
9837 }else
9838 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9840 if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
9841 if( nArg >= 2) {
9842 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9844 if( nArg >= 3) {
9845 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9847 }else
9849 #ifndef SQLITE_SHELL_FIDDLE
9850 if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
9851 rc = 2;
9852 }else
9853 #endif
9855 #ifndef SQLITE_SHELL_FIDDLE
9856 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
9857 FILE *inSaved = p->in;
9858 int savedLineno = p->lineno;
9859 failIfSafeMode(p, "cannot run .read in safe mode");
9860 if( nArg!=2 ){
9861 eputz("Usage: .read FILE\n");
9862 rc = 1;
9863 goto meta_command_exit;
9865 if( azArg[1][0]=='|' ){
9866 #ifdef SQLITE_OMIT_POPEN
9867 eputz("Error: pipes are not supported in this OS\n");
9868 rc = 1;
9869 p->out = stdout;
9870 #else
9871 p->in = popen(azArg[1]+1, "r");
9872 if( p->in==0 ){
9873 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9874 rc = 1;
9875 }else{
9876 rc = process_input(p);
9877 pclose(p->in);
9879 #endif
9880 }else if( (p->in = openChrSource(azArg[1]))==0 ){
9881 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9882 rc = 1;
9883 }else{
9884 rc = process_input(p);
9885 fclose(p->in);
9887 p->in = inSaved;
9888 p->lineno = savedLineno;
9889 }else
9890 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9892 #ifndef SQLITE_SHELL_FIDDLE
9893 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
9894 const char *zSrcFile;
9895 const char *zDb;
9896 sqlite3 *pSrc;
9897 sqlite3_backup *pBackup;
9898 int nTimeout = 0;
9900 failIfSafeMode(p, "cannot run .restore in safe mode");
9901 if( nArg==2 ){
9902 zSrcFile = azArg[1];
9903 zDb = "main";
9904 }else if( nArg==3 ){
9905 zSrcFile = azArg[2];
9906 zDb = azArg[1];
9907 }else{
9908 eputz("Usage: .restore ?DB? FILE\n");
9909 rc = 1;
9910 goto meta_command_exit;
9912 rc = sqlite3_open(zSrcFile, &pSrc);
9913 if( rc!=SQLITE_OK ){
9914 eputf("Error: cannot open \"%s\"\n", zSrcFile);
9915 close_db(pSrc);
9916 return 1;
9918 open_db(p, 0);
9919 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9920 if( pBackup==0 ){
9921 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9922 close_db(pSrc);
9923 return 1;
9925 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9926 || rc==SQLITE_BUSY ){
9927 if( rc==SQLITE_BUSY ){
9928 if( nTimeout++ >= 3 ) break;
9929 sqlite3_sleep(100);
9932 sqlite3_backup_finish(pBackup);
9933 if( rc==SQLITE_DONE ){
9934 rc = 0;
9935 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9936 eputz("Error: source database is busy\n");
9937 rc = 1;
9938 }else{
9939 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9940 rc = 1;
9942 close_db(pSrc);
9943 }else
9944 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9946 if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
9947 if( nArg==2 ){
9948 if( cli_strcmp(azArg[1], "vm")==0 ){
9949 p->scanstatsOn = 3;
9950 }else
9951 if( cli_strcmp(azArg[1], "est")==0 ){
9952 p->scanstatsOn = 2;
9953 }else{
9954 p->scanstatsOn = (u8)booleanValue(azArg[1]);
9956 open_db(p, 0);
9957 sqlite3_db_config(
9958 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
9960 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9961 eputz("Warning: .scanstats not available in this build.\n");
9962 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
9963 if( p->scanstatsOn==3 ){
9964 eputz("Warning: \".scanstats vm\" not available in this build.\n");
9966 #endif
9967 }else{
9968 eputz("Usage: .scanstats on|off|est\n");
9969 rc = 1;
9971 }else
9973 if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
9974 ShellText sSelect;
9975 ShellState data;
9976 char *zErrMsg = 0;
9977 const char *zDiv = "(";
9978 const char *zName = 0;
9979 int iSchema = 0;
9980 int bDebug = 0;
9981 int bNoSystemTabs = 0;
9982 int ii;
9984 open_db(p, 0);
9985 memcpy(&data, p, sizeof(data));
9986 data.showHeader = 0;
9987 data.cMode = data.mode = MODE_Semi;
9988 initText(&sSelect);
9989 for(ii=1; ii<nArg; ii++){
9990 if( optionMatch(azArg[ii],"indent") ){
9991 data.cMode = data.mode = MODE_Pretty;
9992 }else if( optionMatch(azArg[ii],"debug") ){
9993 bDebug = 1;
9994 }else if( optionMatch(azArg[ii],"nosys") ){
9995 bNoSystemTabs = 1;
9996 }else if( azArg[ii][0]=='-' ){
9997 eputf("Unknown option: \"%s\"\n", azArg[ii]);
9998 rc = 1;
9999 goto meta_command_exit;
10000 }else if( zName==0 ){
10001 zName = azArg[ii];
10002 }else{
10003 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10004 rc = 1;
10005 goto meta_command_exit;
10008 if( zName!=0 ){
10009 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10010 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10011 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10012 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10013 if( isSchema ){
10014 char *new_argv[2], *new_colv[2];
10015 new_argv[0] = sqlite3_mprintf(
10016 "CREATE TABLE %s (\n"
10017 " type text,\n"
10018 " name text,\n"
10019 " tbl_name text,\n"
10020 " rootpage integer,\n"
10021 " sql text\n"
10022 ")", zName);
10023 shell_check_oom(new_argv[0]);
10024 new_argv[1] = 0;
10025 new_colv[0] = "sql";
10026 new_colv[1] = 0;
10027 callback(&data, 1, new_argv, new_colv);
10028 sqlite3_free(new_argv[0]);
10031 if( zDiv ){
10032 sqlite3_stmt *pStmt = 0;
10033 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10034 -1, &pStmt, 0);
10035 if( rc ){
10036 eputf("Error: %s\n", sqlite3_errmsg(p->db));
10037 sqlite3_finalize(pStmt);
10038 rc = 1;
10039 goto meta_command_exit;
10041 appendText(&sSelect, "SELECT sql FROM", 0);
10042 iSchema = 0;
10043 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10044 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10045 char zScNum[30];
10046 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10047 appendText(&sSelect, zDiv, 0);
10048 zDiv = " UNION ALL ";
10049 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10050 if( sqlite3_stricmp(zDb, "main")!=0 ){
10051 appendText(&sSelect, zDb, '\'');
10052 }else{
10053 appendText(&sSelect, "NULL", 0);
10055 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10056 appendText(&sSelect, zScNum, 0);
10057 appendText(&sSelect, " AS snum, ", 0);
10058 appendText(&sSelect, zDb, '\'');
10059 appendText(&sSelect, " AS sname FROM ", 0);
10060 appendText(&sSelect, zDb, quoteChar(zDb));
10061 appendText(&sSelect, ".sqlite_schema", 0);
10063 sqlite3_finalize(pStmt);
10064 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10065 if( zName ){
10066 appendText(&sSelect,
10067 " UNION ALL SELECT shell_module_schema(name),"
10068 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10071 #endif
10072 appendText(&sSelect, ") WHERE ", 0);
10073 if( zName ){
10074 char *zQarg = sqlite3_mprintf("%Q", zName);
10075 int bGlob;
10076 shell_check_oom(zQarg);
10077 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10078 strchr(zName, '[') != 0;
10079 if( strchr(zName, '.') ){
10080 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10081 }else{
10082 appendText(&sSelect, "lower(tbl_name)", 0);
10084 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10085 appendText(&sSelect, zQarg, 0);
10086 if( !bGlob ){
10087 appendText(&sSelect, " ESCAPE '\\' ", 0);
10089 appendText(&sSelect, " AND ", 0);
10090 sqlite3_free(zQarg);
10092 if( bNoSystemTabs ){
10093 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10095 appendText(&sSelect, "sql IS NOT NULL"
10096 " ORDER BY snum, rowid", 0);
10097 if( bDebug ){
10098 oputf("SQL: %s;\n", sSelect.z);
10099 }else{
10100 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10102 freeText(&sSelect);
10104 if( zErrMsg ){
10105 eputf("Error: %s\n", zErrMsg);
10106 sqlite3_free(zErrMsg);
10107 rc = 1;
10108 }else if( rc != SQLITE_OK ){
10109 eputz("Error: querying schema information\n");
10110 rc = 1;
10111 }else{
10112 rc = 0;
10114 }else
10116 if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
10117 || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0)
10119 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10120 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10121 }else
10123 #if defined(SQLITE_ENABLE_SESSION)
10124 if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
10125 struct AuxDb *pAuxDb = p->pAuxDb;
10126 OpenSession *pSession = &pAuxDb->aSession[0];
10127 char **azCmd = &azArg[1];
10128 int iSes = 0;
10129 int nCmd = nArg - 1;
10130 int i;
10131 if( nArg<=1 ) goto session_syntax_error;
10132 open_db(p, 0);
10133 if( nArg>=3 ){
10134 for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10135 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10137 if( iSes<pAuxDb->nSession ){
10138 pSession = &pAuxDb->aSession[iSes];
10139 azCmd++;
10140 nCmd--;
10141 }else{
10142 pSession = &pAuxDb->aSession[0];
10143 iSes = 0;
10147 /* .session attach TABLE
10148 ** Invoke the sqlite3session_attach() interface to attach a particular
10149 ** table so that it is never filtered.
10151 if( cli_strcmp(azCmd[0],"attach")==0 ){
10152 if( nCmd!=2 ) goto session_syntax_error;
10153 if( pSession->p==0 ){
10154 session_not_open:
10155 eputz("ERROR: No sessions are open\n");
10156 }else{
10157 rc = sqlite3session_attach(pSession->p, azCmd[1]);
10158 if( rc ){
10159 eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
10160 rc = 0;
10163 }else
10165 /* .session changeset FILE
10166 ** .session patchset FILE
10167 ** Write a changeset or patchset into a file. The file is overwritten.
10169 if( cli_strcmp(azCmd[0],"changeset")==0
10170 || cli_strcmp(azCmd[0],"patchset")==0
10172 FILE *out = 0;
10173 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10174 if( nCmd!=2 ) goto session_syntax_error;
10175 if( pSession->p==0 ) goto session_not_open;
10176 out = fopen(azCmd[1], "wb");
10177 if( out==0 ){
10178 eputf("ERROR: cannot open \"%s\" for writing\n",
10179 azCmd[1]);
10180 }else{
10181 int szChng;
10182 void *pChng;
10183 if( azCmd[0][0]=='c' ){
10184 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10185 }else{
10186 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10188 if( rc ){
10189 sputf(stdout, "Error: error code %d\n", rc);
10190 rc = 0;
10192 if( pChng
10193 && fwrite(pChng, szChng, 1, out)!=1 ){
10194 eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
10196 sqlite3_free(pChng);
10197 fclose(out);
10199 }else
10201 /* .session close
10202 ** Close the identified session
10204 if( cli_strcmp(azCmd[0], "close")==0 ){
10205 if( nCmd!=1 ) goto session_syntax_error;
10206 if( pAuxDb->nSession ){
10207 session_close(pSession);
10208 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10210 }else
10212 /* .session enable ?BOOLEAN?
10213 ** Query or set the enable flag
10215 if( cli_strcmp(azCmd[0], "enable")==0 ){
10216 int ii;
10217 if( nCmd>2 ) goto session_syntax_error;
10218 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10219 if( pAuxDb->nSession ){
10220 ii = sqlite3session_enable(pSession->p, ii);
10221 oputf("session %s enable flag = %d\n", pSession->zName, ii);
10223 }else
10225 /* .session filter GLOB ....
10226 ** Set a list of GLOB patterns of table names to be excluded.
10228 if( cli_strcmp(azCmd[0], "filter")==0 ){
10229 int ii, nByte;
10230 if( nCmd<2 ) goto session_syntax_error;
10231 if( pAuxDb->nSession ){
10232 for(ii=0; ii<pSession->nFilter; ii++){
10233 sqlite3_free(pSession->azFilter[ii]);
10235 sqlite3_free(pSession->azFilter);
10236 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10237 pSession->azFilter = sqlite3_malloc( nByte );
10238 shell_check_oom( pSession->azFilter );
10239 for(ii=1; ii<nCmd; ii++){
10240 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10241 shell_check_oom(x);
10243 pSession->nFilter = ii-1;
10245 }else
10247 /* .session indirect ?BOOLEAN?
10248 ** Query or set the indirect flag
10250 if( cli_strcmp(azCmd[0], "indirect")==0 ){
10251 int ii;
10252 if( nCmd>2 ) goto session_syntax_error;
10253 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10254 if( pAuxDb->nSession ){
10255 ii = sqlite3session_indirect(pSession->p, ii);
10256 oputf("session %s indirect flag = %d\n", pSession->zName, ii);
10258 }else
10260 /* .session isempty
10261 ** Determine if the session is empty
10263 if( cli_strcmp(azCmd[0], "isempty")==0 ){
10264 int ii;
10265 if( nCmd!=1 ) goto session_syntax_error;
10266 if( pAuxDb->nSession ){
10267 ii = sqlite3session_isempty(pSession->p);
10268 oputf("session %s isempty flag = %d\n", pSession->zName, ii);
10270 }else
10272 /* .session list
10273 ** List all currently open sessions
10275 if( cli_strcmp(azCmd[0],"list")==0 ){
10276 for(i=0; i<pAuxDb->nSession; i++){
10277 oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
10279 }else
10281 /* .session open DB NAME
10282 ** Open a new session called NAME on the attached database DB.
10283 ** DB is normally "main".
10285 if( cli_strcmp(azCmd[0],"open")==0 ){
10286 char *zName;
10287 if( nCmd!=3 ) goto session_syntax_error;
10288 zName = azCmd[2];
10289 if( zName[0]==0 ) goto session_syntax_error;
10290 for(i=0; i<pAuxDb->nSession; i++){
10291 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10292 eputf("Session \"%s\" already exists\n", zName);
10293 goto meta_command_exit;
10296 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10297 eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10298 goto meta_command_exit;
10300 pSession = &pAuxDb->aSession[pAuxDb->nSession];
10301 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10302 if( rc ){
10303 eputf("Cannot open session: error code=%d\n", rc);
10304 rc = 0;
10305 goto meta_command_exit;
10307 pSession->nFilter = 0;
10308 sqlite3session_table_filter(pSession->p, session_filter, pSession);
10309 pAuxDb->nSession++;
10310 pSession->zName = sqlite3_mprintf("%s", zName);
10311 shell_check_oom(pSession->zName);
10312 }else
10313 /* If no command name matches, show a syntax error */
10314 session_syntax_error:
10315 showHelp(p->out, "session");
10316 }else
10317 #endif
10319 #ifdef SQLITE_DEBUG
10320 /* Undocumented commands for internal testing. Subject to change
10321 ** without notice. */
10322 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
10323 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10324 int i, v;
10325 for(i=1; i<nArg; i++){
10326 v = booleanValue(azArg[i]);
10327 oputf("%s: %d 0x%x\n", azArg[i], v, v);
10330 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
10331 int i; sqlite3_int64 v;
10332 for(i=1; i<nArg; i++){
10333 char zBuf[200];
10334 v = integerValue(azArg[i]);
10335 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10336 oputz(zBuf);
10339 }else
10340 #endif
10342 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
10343 int bIsInit = 0; /* True to initialize the SELFTEST table */
10344 int bVerbose = 0; /* Verbose output */
10345 int bSelftestExists; /* True if SELFTEST already exists */
10346 int i, k; /* Loop counters */
10347 int nTest = 0; /* Number of tests runs */
10348 int nErr = 0; /* Number of errors seen */
10349 ShellText str; /* Answer for a query */
10350 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10352 open_db(p,0);
10353 for(i=1; i<nArg; i++){
10354 const char *z = azArg[i];
10355 if( z[0]=='-' && z[1]=='-' ) z++;
10356 if( cli_strcmp(z,"-init")==0 ){
10357 bIsInit = 1;
10358 }else
10359 if( cli_strcmp(z,"-v")==0 ){
10360 bVerbose++;
10361 }else
10363 eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
10364 eputz("Should be one of: --init -v\n");
10365 rc = 1;
10366 goto meta_command_exit;
10369 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10370 != SQLITE_OK ){
10371 bSelftestExists = 0;
10372 }else{
10373 bSelftestExists = 1;
10375 if( bIsInit ){
10376 createSelftestTable(p);
10377 bSelftestExists = 1;
10379 initText(&str);
10380 appendText(&str, "x", 0);
10381 for(k=bSelftestExists; k>=0; k--){
10382 if( k==1 ){
10383 rc = sqlite3_prepare_v2(p->db,
10384 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10385 -1, &pStmt, 0);
10386 }else{
10387 rc = sqlite3_prepare_v2(p->db,
10388 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10389 " (1,'run','PRAGMA integrity_check','ok')",
10390 -1, &pStmt, 0);
10392 if( rc ){
10393 eputz("Error querying the selftest table\n");
10394 rc = 1;
10395 sqlite3_finalize(pStmt);
10396 goto meta_command_exit;
10398 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10399 int tno = sqlite3_column_int(pStmt, 0);
10400 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10401 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10402 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10404 if( zOp==0 ) continue;
10405 if( zSql==0 ) continue;
10406 if( zAns==0 ) continue;
10407 k = 0;
10408 if( bVerbose>0 ){
10409 sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
10411 if( cli_strcmp(zOp,"memo")==0 ){
10412 oputf("%s\n", zSql);
10413 }else
10414 if( cli_strcmp(zOp,"run")==0 ){
10415 char *zErrMsg = 0;
10416 str.n = 0;
10417 str.z[0] = 0;
10418 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10419 nTest++;
10420 if( bVerbose ){
10421 oputf("Result: %s\n", str.z);
10423 if( rc || zErrMsg ){
10424 nErr++;
10425 rc = 1;
10426 oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10427 sqlite3_free(zErrMsg);
10428 }else if( cli_strcmp(zAns,str.z)!=0 ){
10429 nErr++;
10430 rc = 1;
10431 oputf("%d: Expected: [%s]\n", tno, zAns);
10432 oputf("%d: Got: [%s]\n", tno, str.z);
10435 else{
10436 eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10437 rc = 1;
10438 break;
10440 } /* End loop over rows of content from SELFTEST */
10441 sqlite3_finalize(pStmt);
10442 } /* End loop over k */
10443 freeText(&str);
10444 oputf("%d errors out of %d tests\n", nErr, nTest);
10445 }else
10447 if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
10448 if( nArg<2 || nArg>3 ){
10449 eputz("Usage: .separator COL ?ROW?\n");
10450 rc = 1;
10452 if( nArg>=2 ){
10453 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10454 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10456 if( nArg>=3 ){
10457 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10458 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10460 }else
10462 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
10463 const char *zLike = 0; /* Which table to checksum. 0 means everything */
10464 int i; /* Loop counter */
10465 int bSchema = 0; /* Also hash the schema */
10466 int bSeparate = 0; /* Hash each table separately */
10467 int iSize = 224; /* Hash algorithm to use */
10468 int bDebug = 0; /* Only show the query that would have run */
10469 sqlite3_stmt *pStmt; /* For querying tables names */
10470 char *zSql; /* SQL to be run */
10471 char *zSep; /* Separator */
10472 ShellText sSql; /* Complete SQL for the query to run the hash */
10473 ShellText sQuery; /* Set of queries used to read all content */
10474 open_db(p, 0);
10475 for(i=1; i<nArg; i++){
10476 const char *z = azArg[i];
10477 if( z[0]=='-' ){
10478 z++;
10479 if( z[0]=='-' ) z++;
10480 if( cli_strcmp(z,"schema")==0 ){
10481 bSchema = 1;
10482 }else
10483 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
10484 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
10486 iSize = atoi(&z[5]);
10487 }else
10488 if( cli_strcmp(z,"debug")==0 ){
10489 bDebug = 1;
10490 }else
10492 eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
10493 showHelp(p->out, azArg[0]);
10494 rc = 1;
10495 goto meta_command_exit;
10497 }else if( zLike ){
10498 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10499 rc = 1;
10500 goto meta_command_exit;
10501 }else{
10502 zLike = z;
10503 bSeparate = 1;
10504 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10507 if( bSchema ){
10508 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10509 " WHERE type='table' AND coalesce(rootpage,0)>1"
10510 " UNION ALL SELECT 'sqlite_schema'"
10511 " ORDER BY 1 collate nocase";
10512 }else{
10513 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10514 " WHERE type='table' AND coalesce(rootpage,0)>1"
10515 " AND name NOT LIKE 'sqlite_%'"
10516 " ORDER BY 1 collate nocase";
10518 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10519 initText(&sQuery);
10520 initText(&sSql);
10521 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10522 zSep = "VALUES(";
10523 while( SQLITE_ROW==sqlite3_step(pStmt) ){
10524 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10525 if( zTab==0 ) continue;
10526 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10527 if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
10528 appendText(&sQuery,"SELECT * FROM ", 0);
10529 appendText(&sQuery,zTab,'"');
10530 appendText(&sQuery," NOT INDEXED;", 0);
10531 }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
10532 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10533 " ORDER BY name;", 0);
10534 }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
10535 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10536 " ORDER BY name;", 0);
10537 }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
10538 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10539 " ORDER BY tbl,idx;", 0);
10540 }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
10541 appendText(&sQuery, "SELECT * FROM ", 0);
10542 appendText(&sQuery, zTab, 0);
10543 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10545 appendText(&sSql, zSep, 0);
10546 appendText(&sSql, sQuery.z, '\'');
10547 sQuery.n = 0;
10548 appendText(&sSql, ",", 0);
10549 appendText(&sSql, zTab, '\'');
10550 zSep = "),(";
10552 sqlite3_finalize(pStmt);
10553 if( bSeparate ){
10554 zSql = sqlite3_mprintf(
10555 "%s))"
10556 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10557 " FROM [sha3sum$query]",
10558 sSql.z, iSize);
10559 }else{
10560 zSql = sqlite3_mprintf(
10561 "%s))"
10562 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10563 " FROM [sha3sum$query]",
10564 sSql.z, iSize);
10566 shell_check_oom(zSql);
10567 freeText(&sQuery);
10568 freeText(&sSql);
10569 if( bDebug ){
10570 oputf("%s\n", zSql);
10571 }else{
10572 shell_exec(p, zSql, 0);
10574 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10576 int lrc;
10577 char *zRevText = /* Query for reversible to-blob-to-text check */
10578 "SELECT lower(name) as tname FROM sqlite_schema\n"
10579 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10580 "AND name NOT LIKE 'sqlite_%%'%s\n"
10581 "ORDER BY 1 collate nocase";
10582 zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
10583 zRevText = sqlite3_mprintf(
10584 /* lower-case query is first run, producing upper-case query. */
10585 "with tabcols as materialized(\n"
10586 "select tname, cname\n"
10587 "from ("
10588 " select printf('\"%%w\"',ss.tname) as tname,"
10589 " printf('\"%%w\"',ti.name) as cname\n"
10590 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10591 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10592 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10593 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10594 "FROM '||tname||' WHERE '\n"
10595 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10596 "|| ' AND typeof('||cname||')=''text'' ',\n"
10597 "' OR ') as query, tname from tabcols group by tname)"
10598 , zRevText);
10599 shell_check_oom(zRevText);
10600 if( bDebug ) oputf("%s\n", zRevText);
10601 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
10602 if( lrc!=SQLITE_OK ){
10603 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
10604 ** user does cruel and unnatural things like ".limit expr_depth 0". */
10605 rc = 1;
10606 }else{
10607 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
10608 lrc = SQLITE_ROW==sqlite3_step(pStmt);
10609 if( lrc ){
10610 const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
10611 sqlite3_stmt *pCheckStmt;
10612 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
10613 if( bDebug ) oputf("%s\n", zGenQuery);
10614 if( lrc!=SQLITE_OK ){
10615 rc = 1;
10616 }else{
10617 if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
10618 double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
10619 if( countIrreversible>0 ){
10620 int sz = (int)(countIrreversible + 0.5);
10621 eputf("Digest includes %d invalidly encoded text field%s.\n",
10622 sz, (sz>1)? "s": "");
10625 sqlite3_finalize(pCheckStmt);
10627 sqlite3_finalize(pStmt);
10630 if( rc ) eputz(".sha3sum failed.\n");
10631 sqlite3_free(zRevText);
10633 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10634 sqlite3_free(zSql);
10635 }else
10637 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10638 if( c=='s'
10639 && (cli_strncmp(azArg[0], "shell", n)==0
10640 || cli_strncmp(azArg[0],"system",n)==0)
10642 char *zCmd;
10643 int i, x;
10644 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10645 if( nArg<2 ){
10646 eputz("Usage: .system COMMAND\n");
10647 rc = 1;
10648 goto meta_command_exit;
10650 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10651 for(i=2; i<nArg && zCmd!=0; i++){
10652 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10653 zCmd, azArg[i]);
10655 consoleRestore();
10656 x = zCmd!=0 ? system(zCmd) : 1;
10657 consoleRenewSetup();
10658 sqlite3_free(zCmd);
10659 if( x ) eputf("System command returns %d\n", x);
10660 }else
10661 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10663 if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
10664 static const char *azBool[] = { "off", "on", "trigger", "full"};
10665 const char *zOut;
10666 int i;
10667 if( nArg!=1 ){
10668 eputz("Usage: .show\n");
10669 rc = 1;
10670 goto meta_command_exit;
10672 oputf("%12.12s: %s\n","echo",
10673 azBool[ShellHasFlag(p, SHFLG_Echo)]);
10674 oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10675 oputf("%12.12s: %s\n","explain",
10676 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10677 oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10678 if( p->mode==MODE_Column
10679 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10681 oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10682 modeDescr[p->mode], p->cmOpts.iWrap,
10683 p->cmOpts.bWordWrap ? "on" : "off",
10684 p->cmOpts.bQuote ? "" : "no");
10685 }else{
10686 oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
10688 oputf("%12.12s: ", "nullvalue");
10689 output_c_string(p->nullValue);
10690 oputz("\n");
10691 oputf("%12.12s: %s\n","output",
10692 strlen30(p->outfile) ? p->outfile : "stdout");
10693 oputf("%12.12s: ", "colseparator");
10694 output_c_string(p->colSeparator);
10695 oputz("\n");
10696 oputf("%12.12s: ", "rowseparator");
10697 output_c_string(p->rowSeparator);
10698 oputz("\n");
10699 switch( p->statsOn ){
10700 case 0: zOut = "off"; break;
10701 default: zOut = "on"; break;
10702 case 2: zOut = "stmt"; break;
10703 case 3: zOut = "vmstep"; break;
10705 oputf("%12.12s: %s\n","stats", zOut);
10706 oputf("%12.12s: ", "width");
10707 for (i=0;i<p->nWidth;i++) {
10708 oputf("%d ", p->colWidth[i]);
10710 oputz("\n");
10711 oputf("%12.12s: %s\n", "filename",
10712 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10713 }else
10715 if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
10716 if( nArg==2 ){
10717 if( cli_strcmp(azArg[1],"stmt")==0 ){
10718 p->statsOn = 2;
10719 }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
10720 p->statsOn = 3;
10721 }else{
10722 p->statsOn = (u8)booleanValue(azArg[1]);
10724 }else if( nArg==1 ){
10725 display_stats(p->db, p, 0);
10726 }else{
10727 eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
10728 rc = 1;
10730 }else
10732 if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
10733 || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
10734 || cli_strncmp(azArg[0], "indexes", n)==0) )
10736 sqlite3_stmt *pStmt;
10737 char **azResult;
10738 int nRow, nAlloc;
10739 int ii;
10740 ShellText s;
10741 initText(&s);
10742 open_db(p, 0);
10743 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10744 if( rc ){
10745 sqlite3_finalize(pStmt);
10746 return shellDatabaseError(p->db);
10749 if( nArg>2 && c=='i' ){
10750 /* It is an historical accident that the .indexes command shows an error
10751 ** when called with the wrong number of arguments whereas the .tables
10752 ** command does not. */
10753 eputz("Usage: .indexes ?LIKE-PATTERN?\n");
10754 rc = 1;
10755 sqlite3_finalize(pStmt);
10756 goto meta_command_exit;
10758 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10759 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10760 if( zDbName==0 ) continue;
10761 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10762 if( sqlite3_stricmp(zDbName, "main")==0 ){
10763 appendText(&s, "SELECT name FROM ", 0);
10764 }else{
10765 appendText(&s, "SELECT ", 0);
10766 appendText(&s, zDbName, '\'');
10767 appendText(&s, "||'.'||name FROM ", 0);
10769 appendText(&s, zDbName, '"');
10770 appendText(&s, ".sqlite_schema ", 0);
10771 if( c=='t' ){
10772 appendText(&s," WHERE type IN ('table','view')"
10773 " AND name NOT LIKE 'sqlite_%'"
10774 " AND name LIKE ?1", 0);
10775 }else{
10776 appendText(&s," WHERE type='index'"
10777 " AND tbl_name LIKE ?1", 0);
10780 rc = sqlite3_finalize(pStmt);
10781 if( rc==SQLITE_OK ){
10782 appendText(&s, " ORDER BY 1", 0);
10783 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10785 freeText(&s);
10786 if( rc ) return shellDatabaseError(p->db);
10788 /* Run the SQL statement prepared by the above block. Store the results
10789 ** as an array of nul-terminated strings in azResult[]. */
10790 nRow = nAlloc = 0;
10791 azResult = 0;
10792 if( nArg>1 ){
10793 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10794 }else{
10795 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10797 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10798 if( nRow>=nAlloc ){
10799 char **azNew;
10800 int n2 = nAlloc*2 + 10;
10801 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10802 shell_check_oom(azNew);
10803 nAlloc = n2;
10804 azResult = azNew;
10806 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10807 shell_check_oom(azResult[nRow]);
10808 nRow++;
10810 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10811 rc = shellDatabaseError(p->db);
10814 /* Pretty-print the contents of array azResult[] to the output */
10815 if( rc==0 && nRow>0 ){
10816 int len, maxlen = 0;
10817 int i, j;
10818 int nPrintCol, nPrintRow;
10819 for(i=0; i<nRow; i++){
10820 len = strlen30(azResult[i]);
10821 if( len>maxlen ) maxlen = len;
10823 nPrintCol = 80/(maxlen+2);
10824 if( nPrintCol<1 ) nPrintCol = 1;
10825 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10826 for(i=0; i<nPrintRow; i++){
10827 for(j=i; j<nRow; j+=nPrintRow){
10828 char *zSp = j<nPrintRow ? "" : " ";
10829 oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
10831 oputz("\n");
10835 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10836 sqlite3_free(azResult);
10837 }else
10839 #ifndef SQLITE_SHELL_FIDDLE
10840 /* Begin redirecting output to the file "testcase-out.txt" */
10841 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
10842 output_reset(p);
10843 p->out = output_file_open("testcase-out.txt", 0);
10844 if( p->out==0 ){
10845 eputz("Error: cannot open 'testcase-out.txt'\n");
10847 if( nArg>=2 ){
10848 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10849 }else{
10850 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10852 }else
10853 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10855 #ifndef SQLITE_UNTESTABLE
10856 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
10857 static const struct {
10858 const char *zCtrlName; /* Name of a test-control option */
10859 int ctrlCode; /* Integer code for that option */
10860 int unSafe; /* Not valid unless --unsafe-testing */
10861 const char *zUsage; /* Usage notes */
10862 } aCtrl[] = {
10863 {"always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
10864 {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
10865 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10866 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10867 {"byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
10868 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
10869 {"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..." },
10870 {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" },
10871 {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10872 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
10873 {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" },
10874 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
10875 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
10876 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
10877 #ifdef YYCOVERAGE
10878 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
10879 #endif
10880 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
10881 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
10882 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
10883 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
10884 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
10885 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
10886 {"tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
10887 {"uselongdouble", SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
10889 int testctrl = -1;
10890 int iCtrl = -1;
10891 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10892 int isOk = 0;
10893 int i, n2;
10894 const char *zCmd = 0;
10896 open_db(p, 0);
10897 zCmd = nArg>=2 ? azArg[1] : "help";
10899 /* The argument can optionally begin with "-" or "--" */
10900 if( zCmd[0]=='-' && zCmd[1] ){
10901 zCmd++;
10902 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10905 /* --help lists all test-controls */
10906 if( cli_strcmp(zCmd,"help")==0 ){
10907 oputz("Available test-controls:\n");
10908 for(i=0; i<ArraySize(aCtrl); i++){
10909 if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
10910 oputf(" .testctrl %s %s\n",
10911 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10913 rc = 1;
10914 goto meta_command_exit;
10917 /* convert testctrl text option to value. allow any unique prefix
10918 ** of the option name, or a numerical value. */
10919 n2 = strlen30(zCmd);
10920 for(i=0; i<ArraySize(aCtrl); i++){
10921 if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
10922 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10923 if( testctrl<0 ){
10924 testctrl = aCtrl[i].ctrlCode;
10925 iCtrl = i;
10926 }else{
10927 eputf("Error: ambiguous test-control: \"%s\"\n"
10928 "Use \".testctrl --help\" for help\n", zCmd);
10929 rc = 1;
10930 goto meta_command_exit;
10934 if( testctrl<0 ){
10935 eputf("Error: unknown test-control: %s\n"
10936 "Use \".testctrl --help\" for help\n", zCmd);
10937 }else{
10938 switch(testctrl){
10940 /* sqlite3_test_control(int, db, int) */
10941 case SQLITE_TESTCTRL_OPTIMIZATIONS:
10942 case SQLITE_TESTCTRL_FK_NO_ACTION:
10943 if( nArg==3 ){
10944 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10945 rc2 = sqlite3_test_control(testctrl, p->db, opt);
10946 isOk = 3;
10948 break;
10950 /* sqlite3_test_control(int) */
10951 case SQLITE_TESTCTRL_PRNG_SAVE:
10952 case SQLITE_TESTCTRL_PRNG_RESTORE:
10953 case SQLITE_TESTCTRL_BYTEORDER:
10954 if( nArg==2 ){
10955 rc2 = sqlite3_test_control(testctrl);
10956 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10958 break;
10960 /* sqlite3_test_control(int, uint) */
10961 case SQLITE_TESTCTRL_PENDING_BYTE:
10962 if( nArg==3 ){
10963 unsigned int opt = (unsigned int)integerValue(azArg[2]);
10964 rc2 = sqlite3_test_control(testctrl, opt);
10965 isOk = 3;
10967 break;
10969 /* sqlite3_test_control(int, int, sqlite3*) */
10970 case SQLITE_TESTCTRL_PRNG_SEED:
10971 if( nArg==3 || nArg==4 ){
10972 int ii = (int)integerValue(azArg[2]);
10973 sqlite3 *db;
10974 if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
10975 sqlite3_randomness(sizeof(ii),&ii);
10976 sputf(stdout, "-- random seed: %d\n", ii);
10978 if( nArg==3 ){
10979 db = 0;
10980 }else{
10981 db = p->db;
10982 /* Make sure the schema has been loaded */
10983 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10985 rc2 = sqlite3_test_control(testctrl, ii, db);
10986 isOk = 3;
10988 break;
10990 /* sqlite3_test_control(int, int) */
10991 case SQLITE_TESTCTRL_ASSERT:
10992 case SQLITE_TESTCTRL_ALWAYS:
10993 if( nArg==3 ){
10994 int opt = booleanValue(azArg[2]);
10995 rc2 = sqlite3_test_control(testctrl, opt);
10996 isOk = 1;
10998 break;
11000 /* sqlite3_test_control(int, int) */
11001 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11002 case SQLITE_TESTCTRL_NEVER_CORRUPT:
11003 if( nArg==3 ){
11004 int opt = booleanValue(azArg[2]);
11005 rc2 = sqlite3_test_control(testctrl, opt);
11006 isOk = 3;
11008 break;
11010 /* sqlite3_test_control(int, int) */
11011 case SQLITE_TESTCTRL_USELONGDOUBLE: {
11012 int opt = -1;
11013 if( nArg==3 ){
11014 if( cli_strcmp(azArg[2],"default")==0 ){
11015 opt = 2;
11016 }else{
11017 opt = booleanValue(azArg[2]);
11020 rc2 = sqlite3_test_control(testctrl, opt);
11021 isOk = 1;
11022 break;
11025 /* sqlite3_test_control(sqlite3*) */
11026 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11027 rc2 = sqlite3_test_control(testctrl, p->db);
11028 isOk = 3;
11029 break;
11031 case SQLITE_TESTCTRL_IMPOSTER:
11032 if( nArg==5 ){
11033 rc2 = sqlite3_test_control(testctrl, p->db,
11034 azArg[2],
11035 integerValue(azArg[3]),
11036 integerValue(azArg[4]));
11037 isOk = 3;
11039 break;
11041 case SQLITE_TESTCTRL_SEEK_COUNT: {
11042 u64 x = 0;
11043 rc2 = sqlite3_test_control(testctrl, p->db, &x);
11044 oputf("%llu\n", x);
11045 isOk = 3;
11046 break;
11049 #ifdef YYCOVERAGE
11050 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11051 if( nArg==2 ){
11052 sqlite3_test_control(testctrl, p->out);
11053 isOk = 3;
11055 break;
11057 #endif
11058 #ifdef SQLITE_DEBUG
11059 case SQLITE_TESTCTRL_TUNE: {
11060 if( nArg==4 ){
11061 int id = (int)integerValue(azArg[2]);
11062 int val = (int)integerValue(azArg[3]);
11063 sqlite3_test_control(testctrl, id, &val);
11064 isOk = 3;
11065 }else if( nArg==3 ){
11066 int id = (int)integerValue(azArg[2]);
11067 sqlite3_test_control(testctrl, -id, &rc2);
11068 isOk = 1;
11069 }else if( nArg==2 ){
11070 int id = 1;
11071 while(1){
11072 int val = 0;
11073 rc2 = sqlite3_test_control(testctrl, -id, &val);
11074 if( rc2!=SQLITE_OK ) break;
11075 if( id>1 ) oputz(" ");
11076 oputf("%d: %d", id, val);
11077 id++;
11079 if( id>1 ) oputz("\n");
11080 isOk = 3;
11082 break;
11084 #endif
11085 case SQLITE_TESTCTRL_SORTER_MMAP:
11086 if( nArg==3 ){
11087 int opt = (unsigned int)integerValue(azArg[2]);
11088 rc2 = sqlite3_test_control(testctrl, p->db, opt);
11089 isOk = 3;
11091 break;
11092 case SQLITE_TESTCTRL_JSON_SELFCHECK:
11093 if( nArg==2 ){
11094 rc2 = -1;
11095 isOk = 1;
11096 }else{
11097 rc2 = booleanValue(azArg[2]);
11098 isOk = 3;
11100 sqlite3_test_control(testctrl, &rc2);
11101 break;
11102 case SQLITE_TESTCTRL_FAULT_INSTALL: {
11103 int kk;
11104 int bShowHelp = nArg<=2;
11105 isOk = 3;
11106 for(kk=2; kk<nArg; kk++){
11107 const char *z = azArg[kk];
11108 if( z[0]=='-' && z[1]=='-' ) z++;
11109 if( cli_strcmp(z,"off")==0 ){
11110 sqlite3_test_control(testctrl, 0);
11111 }else if( cli_strcmp(z,"on")==0 ){
11112 faultsim_state.iCnt = faultsim_state.iInterval;
11113 if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
11114 sqlite3_test_control(testctrl, faultsim_callback);
11115 }else if( cli_strcmp(z,"reset")==0 ){
11116 faultsim_state.iCnt = faultsim_state.iInterval;
11117 }else if( cli_strcmp(z,"status")==0 ){
11118 oputf("faultsim.iId: %d\n", faultsim_state.iId);
11119 oputf("faultsim.iErr: %d\n", faultsim_state.iErr);
11120 oputf("faultsim.iCnt: %d\n", faultsim_state.iCnt);
11121 oputf("faultsim.iInterval: %d\n", faultsim_state.iInterval);
11122 oputf("faultsim.eVerbose: %d\n", faultsim_state.eVerbose);
11123 }else if( cli_strcmp(z,"-v")==0 ){
11124 if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
11125 }else if( cli_strcmp(z,"-q")==0 ){
11126 if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
11127 }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
11128 faultsim_state.iId = atoi(azArg[++kk]);
11129 }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
11130 faultsim_state.iErr = atoi(azArg[++kk]);
11131 }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
11132 faultsim_state.iInterval = atoi(azArg[++kk]);
11133 }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
11134 bShowHelp = 1;
11135 }else{
11136 eputf("Unrecognized fault_install argument: \"%s\"\n",
11137 azArg[kk]);
11138 rc = 1;
11139 bShowHelp = 1;
11140 break;
11143 if( bShowHelp ){
11144 oputz(
11145 "Usage: .testctrl fault_install ARGS\n"
11146 "Possible arguments:\n"
11147 " off Disable faultsim\n"
11148 " on Activate faultsim\n"
11149 " reset Reset the trigger counter\n"
11150 " status Show current status\n"
11151 " -v Increase verbosity\n"
11152 " -q Decrease verbosity\n"
11153 " --errcode N When triggered, return N as error code\n"
11154 " --id ID Trigger only for the ID specified\n"
11155 " --interval N Trigger only after every N-th call\n"
11158 break;
11162 if( isOk==0 && iCtrl>=0 ){
11163 oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11164 rc = 1;
11165 }else if( isOk==1 ){
11166 oputf("%d\n", rc2);
11167 }else if( isOk==2 ){
11168 oputf("0x%08x\n", rc2);
11170 }else
11171 #endif /* !defined(SQLITE_UNTESTABLE) */
11173 if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
11174 open_db(p, 0);
11175 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11176 }else
11178 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
11179 if( nArg==2 ){
11180 enableTimer = booleanValue(azArg[1]);
11181 if( enableTimer && !HAS_TIMER ){
11182 eputz("Error: timer not available on this system.\n");
11183 enableTimer = 0;
11185 }else{
11186 eputz("Usage: .timer on|off\n");
11187 rc = 1;
11189 }else
11191 #ifndef SQLITE_OMIT_TRACE
11192 if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
11193 int mType = 0;
11194 int jj;
11195 open_db(p, 0);
11196 for(jj=1; jj<nArg; jj++){
11197 const char *z = azArg[jj];
11198 if( z[0]=='-' ){
11199 if( optionMatch(z, "expanded") ){
11200 p->eTraceType = SHELL_TRACE_EXPANDED;
11202 #ifdef SQLITE_ENABLE_NORMALIZE
11203 else if( optionMatch(z, "normalized") ){
11204 p->eTraceType = SHELL_TRACE_NORMALIZED;
11206 #endif
11207 else if( optionMatch(z, "plain") ){
11208 p->eTraceType = SHELL_TRACE_PLAIN;
11210 else if( optionMatch(z, "profile") ){
11211 mType |= SQLITE_TRACE_PROFILE;
11213 else if( optionMatch(z, "row") ){
11214 mType |= SQLITE_TRACE_ROW;
11216 else if( optionMatch(z, "stmt") ){
11217 mType |= SQLITE_TRACE_STMT;
11219 else if( optionMatch(z, "close") ){
11220 mType |= SQLITE_TRACE_CLOSE;
11222 else {
11223 eputf("Unknown option \"%s\" on \".trace\"\n", z);
11224 rc = 1;
11225 goto meta_command_exit;
11227 }else{
11228 output_file_close(p->traceOut);
11229 p->traceOut = output_file_open(z, 0);
11232 if( p->traceOut==0 ){
11233 sqlite3_trace_v2(p->db, 0, 0, 0);
11234 }else{
11235 if( mType==0 ) mType = SQLITE_TRACE_STMT;
11236 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11238 }else
11239 #endif /* !defined(SQLITE_OMIT_TRACE) */
11241 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11242 if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
11243 int ii;
11244 int lenOpt;
11245 char *zOpt;
11246 if( nArg<2 ){
11247 eputz("Usage: .unmodule [--allexcept] NAME ...\n");
11248 rc = 1;
11249 goto meta_command_exit;
11251 open_db(p, 0);
11252 zOpt = azArg[1];
11253 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11254 lenOpt = (int)strlen(zOpt);
11255 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11256 assert( azArg[nArg]==0 );
11257 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11258 }else{
11259 for(ii=1; ii<nArg; ii++){
11260 sqlite3_create_module(p->db, azArg[ii], 0, 0);
11263 }else
11264 #endif
11266 #if SQLITE_USER_AUTHENTICATION
11267 if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
11268 if( nArg<2 ){
11269 eputz("Usage: .user SUBCOMMAND ...\n");
11270 rc = 1;
11271 goto meta_command_exit;
11273 open_db(p, 0);
11274 if( cli_strcmp(azArg[1],"login")==0 ){
11275 if( nArg!=4 ){
11276 eputz("Usage: .user login USER PASSWORD\n");
11277 rc = 1;
11278 goto meta_command_exit;
11280 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11281 strlen30(azArg[3]));
11282 if( rc ){
11283 eputf("Authentication failed for user %s\n", azArg[2]);
11284 rc = 1;
11286 }else if( cli_strcmp(azArg[1],"add")==0 ){
11287 if( nArg!=5 ){
11288 eputz("Usage: .user add USER PASSWORD ISADMIN\n");
11289 rc = 1;
11290 goto meta_command_exit;
11292 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11293 booleanValue(azArg[4]));
11294 if( rc ){
11295 eputf("User-Add failed: %d\n", rc);
11296 rc = 1;
11298 }else if( cli_strcmp(azArg[1],"edit")==0 ){
11299 if( nArg!=5 ){
11300 eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
11301 rc = 1;
11302 goto meta_command_exit;
11304 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11305 booleanValue(azArg[4]));
11306 if( rc ){
11307 eputf("User-Edit failed: %d\n", rc);
11308 rc = 1;
11310 }else if( cli_strcmp(azArg[1],"delete")==0 ){
11311 if( nArg!=3 ){
11312 eputz("Usage: .user delete USER\n");
11313 rc = 1;
11314 goto meta_command_exit;
11316 rc = sqlite3_user_delete(p->db, azArg[2]);
11317 if( rc ){
11318 eputf("User-Delete failed: %d\n", rc);
11319 rc = 1;
11321 }else{
11322 eputz("Usage: .user login|add|edit|delete ...\n");
11323 rc = 1;
11324 goto meta_command_exit;
11326 }else
11327 #endif /* SQLITE_USER_AUTHENTICATION */
11329 if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
11330 char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
11331 oputf("SQLite %s %s\n" /*extra-version-info*/,
11332 sqlite3_libversion(), sqlite3_sourceid());
11333 #if SQLITE_HAVE_ZLIB
11334 oputf("zlib version %s\n", zlibVersion());
11335 #endif
11336 #define CTIMEOPT_VAL_(opt) #opt
11337 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11338 #if defined(__clang__) && defined(__clang_major__)
11339 oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
11340 CTIMEOPT_VAL(__clang_minor__) "."
11341 CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
11342 #elif defined(_MSC_VER)
11343 oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
11344 #elif defined(__GNUC__) && defined(__VERSION__)
11345 oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
11346 #endif
11347 }else
11349 if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
11350 const char *zDbName = nArg==2 ? azArg[1] : "main";
11351 sqlite3_vfs *pVfs = 0;
11352 if( p->db ){
11353 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11354 if( pVfs ){
11355 oputf("vfs.zName = \"%s\"\n", pVfs->zName);
11356 oputf("vfs.iVersion = %d\n", pVfs->iVersion);
11357 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile);
11358 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
11361 }else
11363 if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
11364 sqlite3_vfs *pVfs;
11365 sqlite3_vfs *pCurrent = 0;
11366 if( p->db ){
11367 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11369 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11370 oputf("vfs.zName = \"%s\"%s\n", pVfs->zName,
11371 pVfs==pCurrent ? " <--- CURRENT" : "");
11372 oputf("vfs.iVersion = %d\n", pVfs->iVersion);
11373 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile);
11374 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
11375 if( pVfs->pNext ){
11376 oputz("-----------------------------------\n");
11379 }else
11381 if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
11382 const char *zDbName = nArg==2 ? azArg[1] : "main";
11383 char *zVfsName = 0;
11384 if( p->db ){
11385 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11386 if( zVfsName ){
11387 oputf("%s\n", zVfsName);
11388 sqlite3_free(zVfsName);
11391 }else
11393 if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
11394 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11395 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11396 }else
11398 if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
11399 int j;
11400 assert( nArg<=ArraySize(azArg) );
11401 p->nWidth = nArg-1;
11402 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11403 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11404 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11405 for(j=1; j<nArg; j++){
11406 p->colWidth[j-1] = (int)integerValue(azArg[j]);
11408 }else
11411 eputf("Error: unknown command or invalid arguments: "
11412 " \"%s\". Enter \".help\" for help\n", azArg[0]);
11413 rc = 1;
11416 meta_command_exit:
11417 if( p->outCount ){
11418 p->outCount--;
11419 if( p->outCount==0 ) output_reset(p);
11421 p->bSafeMode = p->bSafeModePersist;
11422 return rc;
11425 /* Line scan result and intermediate states (supporting scan resumption)
11427 #ifndef CHAR_BIT
11428 # define CHAR_BIT 8
11429 #endif
11430 typedef enum {
11431 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11432 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11433 QSS_Start = 0
11434 } QuickScanState;
11435 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11436 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11437 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11438 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11439 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11442 ** Scan line for classification to guide shell's handling.
11443 ** The scan is resumable for subsequent lines when prior
11444 ** return values are passed as the 2nd argument.
11446 static QuickScanState quickscan(char *zLine, QuickScanState qss,
11447 SCAN_TRACKER_REFTYPE pst){
11448 char cin;
11449 char cWait = (char)qss; /* intentional narrowing loss */
11450 if( cWait==0 ){
11451 PlainScan:
11452 assert( cWait==0 );
11453 while( (cin = *zLine++)!=0 ){
11454 if( IsSpace(cin) )
11455 continue;
11456 switch (cin){
11457 case '-':
11458 if( *zLine!='-' )
11459 break;
11460 while((cin = *++zLine)!=0 )
11461 if( cin=='\n')
11462 goto PlainScan;
11463 return qss;
11464 case ';':
11465 qss |= QSS_EndingSemi;
11466 continue;
11467 case '/':
11468 if( *zLine=='*' ){
11469 ++zLine;
11470 cWait = '*';
11471 CONTINUE_PROMPT_AWAITS(pst, "/*");
11472 qss = QSS_SETV(qss, cWait);
11473 goto TermScan;
11475 break;
11476 case '[':
11477 cin = ']';
11478 deliberate_fall_through;
11479 case '`': case '\'': case '"':
11480 cWait = cin;
11481 qss = QSS_HasDark | cWait;
11482 CONTINUE_PROMPT_AWAITC(pst, cin);
11483 goto TermScan;
11484 case '(':
11485 CONTINUE_PAREN_INCR(pst, 1);
11486 break;
11487 case ')':
11488 CONTINUE_PAREN_INCR(pst, -1);
11489 break;
11490 default:
11491 break;
11493 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11495 }else{
11496 TermScan:
11497 while( (cin = *zLine++)!=0 ){
11498 if( cin==cWait ){
11499 switch( cWait ){
11500 case '*':
11501 if( *zLine != '/' )
11502 continue;
11503 ++zLine;
11504 cWait = 0;
11505 CONTINUE_PROMPT_AWAITC(pst, 0);
11506 qss = QSS_SETV(qss, 0);
11507 goto PlainScan;
11508 case '`': case '\'': case '"':
11509 if(*zLine==cWait){
11510 /* Swallow doubled end-delimiter.*/
11511 ++zLine;
11512 continue;
11514 deliberate_fall_through;
11515 case ']':
11516 cWait = 0;
11517 CONTINUE_PROMPT_AWAITC(pst, 0);
11518 qss = QSS_SETV(qss, 0);
11519 goto PlainScan;
11520 default: assert(0);
11525 return qss;
11529 ** Return TRUE if the line typed in is an SQL command terminator other
11530 ** than a semi-colon. The SQL Server style "go" command is understood
11531 ** as is the Oracle "/".
11533 static int line_is_command_terminator(char *zLine){
11534 while( IsSpace(zLine[0]) ){ zLine++; };
11535 if( zLine[0]=='/' )
11536 zLine += 1; /* Oracle */
11537 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11538 zLine += 2; /* SQL Server */
11539 else
11540 return 0;
11541 return quickscan(zLine, QSS_Start, 0)==QSS_Start;
11545 ** The CLI needs a working sqlite3_complete() to work properly. So error
11546 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11548 #ifdef SQLITE_OMIT_COMPLETE
11549 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11550 #endif
11553 ** Return true if zSql is a complete SQL statement. Return false if it
11554 ** ends in the middle of a string literal or C-style comment.
11556 static int line_is_complete(char *zSql, int nSql){
11557 int rc;
11558 if( zSql==0 ) return 1;
11559 zSql[nSql] = ';';
11560 zSql[nSql+1] = 0;
11561 rc = sqlite3_complete(zSql);
11562 zSql[nSql] = 0;
11563 return rc;
11567 ** This function is called after processing each line of SQL in the
11568 ** runOneSqlLine() function. Its purpose is to detect scenarios where
11569 ** defensive mode should be automatically turned off. Specifically, when
11571 ** 1. The first line of input is "PRAGMA foreign_keys=OFF;",
11572 ** 2. The second line of input is "BEGIN TRANSACTION;",
11573 ** 3. The database is empty, and
11574 ** 4. The shell is not running in --safe mode.
11576 ** The implementation uses the ShellState.eRestoreState to maintain state:
11578 ** 0: Have not seen any SQL.
11579 ** 1: Have seen "PRAGMA foreign_keys=OFF;".
11580 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
11581 ** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
11582 ** 7: Nothing left to do. This function becomes a no-op.
11584 static int doAutoDetectRestore(ShellState *p, const char *zSql){
11585 int rc = SQLITE_OK;
11587 if( p->eRestoreState<7 ){
11588 switch( p->eRestoreState ){
11589 case 0: {
11590 const char *zExpect = "PRAGMA foreign_keys=OFF;";
11591 assert( strlen(zExpect)==24 );
11592 if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
11593 p->eRestoreState = 1;
11594 }else{
11595 p->eRestoreState = 7;
11597 break;
11600 case 1: {
11601 int bIsDump = 0;
11602 const char *zExpect = "BEGIN TRANSACTION;";
11603 assert( strlen(zExpect)==18 );
11604 if( memcmp(zSql, zExpect, 19)==0 ){
11605 /* Now check if the database is empty. */
11606 const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
11607 sqlite3_stmt *pStmt = 0;
11609 bIsDump = 1;
11610 shellPrepare(p->db, &rc, zQuery, &pStmt);
11611 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
11612 bIsDump = 0;
11614 shellFinalize(&rc, pStmt);
11616 if( bIsDump && rc==SQLITE_OK ){
11617 int bDefense = 0;
11618 int bDqsDdl = 0;
11619 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
11620 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
11621 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
11622 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
11623 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
11624 }else{
11625 p->eRestoreState = 7;
11627 break;
11630 default: {
11631 if( sqlite3_get_autocommit(p->db) ){
11632 if( (p->eRestoreState & 2) ){
11633 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
11635 if( (p->eRestoreState & 4) ){
11636 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
11638 p->eRestoreState = 7;
11640 break;
11645 return rc;
11649 ** Run a single line of SQL. Return the number of errors.
11651 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11652 int rc;
11653 char *zErrMsg = 0;
11655 open_db(p, 0);
11656 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11657 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11658 BEGIN_TIMER;
11659 rc = shell_exec(p, zSql, &zErrMsg);
11660 END_TIMER;
11661 if( rc || zErrMsg ){
11662 char zPrefix[100];
11663 const char *zErrorTail;
11664 const char *zErrorType;
11665 if( zErrMsg==0 ){
11666 zErrorType = "Error";
11667 zErrorTail = sqlite3_errmsg(p->db);
11668 }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
11669 zErrorType = "Parse error";
11670 zErrorTail = &zErrMsg[12];
11671 }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
11672 zErrorType = "Runtime error";
11673 zErrorTail = &zErrMsg[10];
11674 }else{
11675 zErrorType = "Error";
11676 zErrorTail = zErrMsg;
11678 if( in!=0 || !stdin_is_interactive ){
11679 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11680 "%s near line %d:", zErrorType, startline);
11681 }else{
11682 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11684 eputf("%s %s\n", zPrefix, zErrorTail);
11685 sqlite3_free(zErrMsg);
11686 zErrMsg = 0;
11687 return 1;
11688 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11689 char zLineBuf[2000];
11690 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11691 "changes: %lld total_changes: %lld",
11692 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11693 oputf("%s\n", zLineBuf);
11696 if( doAutoDetectRestore(p, zSql) ) return 1;
11697 return 0;
11700 static void echo_group_input(ShellState *p, const char *zDo){
11701 if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
11704 #ifdef SQLITE_SHELL_FIDDLE
11706 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11707 ** impl because we need the global shellState and cannot access it from that
11708 ** function without moving lots of code around (creating a larger/messier diff).
11710 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11711 /* Parse the next line from shellState.wasm.zInput. */
11712 const char *zBegin = shellState.wasm.zPos;
11713 const char *z = zBegin;
11714 char *zLine = 0;
11715 i64 nZ = 0;
11717 UNUSED_PARAMETER(in);
11718 UNUSED_PARAMETER(isContinuation);
11719 if(!z || !*z){
11720 return 0;
11722 while(*z && isspace(*z)) ++z;
11723 zBegin = z;
11724 for(; *z && '\n'!=*z; ++nZ, ++z){}
11725 if(nZ>0 && '\r'==zBegin[nZ-1]){
11726 --nZ;
11728 shellState.wasm.zPos = z;
11729 zLine = realloc(zPrior, nZ+1);
11730 shell_check_oom(zLine);
11731 memcpy(zLine, zBegin, nZ);
11732 zLine[nZ] = 0;
11733 return zLine;
11735 #endif /* SQLITE_SHELL_FIDDLE */
11738 ** Read input from *in and process it. If *in==0 then input
11739 ** is interactive - the user is typing it it. Otherwise, input
11740 ** is coming from a file or device. A prompt is issued and history
11741 ** is saved only if input is interactive. An interrupt signal will
11742 ** cause this routine to exit immediately, unless input is interactive.
11744 ** Return the number of errors.
11746 static int process_input(ShellState *p){
11747 char *zLine = 0; /* A single input line */
11748 char *zSql = 0; /* Accumulated SQL text */
11749 i64 nLine; /* Length of current line */
11750 i64 nSql = 0; /* Bytes of zSql[] used */
11751 i64 nAlloc = 0; /* Allocated zSql[] space */
11752 int rc; /* Error code */
11753 int errCnt = 0; /* Number of errors seen */
11754 i64 startline = 0; /* Line number for start of current input */
11755 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11757 if( p->inputNesting==MAX_INPUT_NESTING ){
11758 /* This will be more informative in a later version. */
11759 eputf("Input nesting limit (%d) reached at line %d."
11760 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11761 return 1;
11763 ++p->inputNesting;
11764 p->lineno = 0;
11765 CONTINUE_PROMPT_RESET;
11766 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11767 fflush(p->out);
11768 zLine = one_input_line(p->in, zLine, nSql>0);
11769 if( zLine==0 ){
11770 /* End of input */
11771 if( p->in==0 && stdin_is_interactive ) oputz("\n");
11772 break;
11774 if( seenInterrupt ){
11775 if( p->in!=0 ) break;
11776 seenInterrupt = 0;
11778 p->lineno++;
11779 if( QSS_INPLAIN(qss)
11780 && line_is_command_terminator(zLine)
11781 && line_is_complete(zSql, nSql) ){
11782 memcpy(zLine,";",2);
11784 qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
11785 if( QSS_PLAINWHITE(qss) && nSql==0 ){
11786 /* Just swallow single-line whitespace */
11787 echo_group_input(p, zLine);
11788 qss = QSS_Start;
11789 continue;
11791 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11792 CONTINUE_PROMPT_RESET;
11793 echo_group_input(p, zLine);
11794 if( zLine[0]=='.' ){
11795 rc = do_meta_command(zLine, p);
11796 if( rc==2 ){ /* exit requested */
11797 break;
11798 }else if( rc ){
11799 errCnt++;
11802 qss = QSS_Start;
11803 continue;
11805 /* No single-line dispositions remain; accumulate line(s). */
11806 nLine = strlen(zLine);
11807 if( nSql+nLine+2>=nAlloc ){
11808 /* Grow buffer by half-again increments when big. */
11809 nAlloc = nSql+(nSql>>1)+nLine+100;
11810 zSql = realloc(zSql, nAlloc);
11811 shell_check_oom(zSql);
11813 if( nSql==0 ){
11814 i64 i;
11815 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11816 assert( nAlloc>0 && zSql!=0 );
11817 memcpy(zSql, zLine+i, nLine+1-i);
11818 startline = p->lineno;
11819 nSql = nLine-i;
11820 }else{
11821 zSql[nSql++] = '\n';
11822 memcpy(zSql+nSql, zLine, nLine+1);
11823 nSql += nLine;
11825 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11826 echo_group_input(p, zSql);
11827 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11828 CONTINUE_PROMPT_RESET;
11829 nSql = 0;
11830 if( p->outCount ){
11831 output_reset(p);
11832 p->outCount = 0;
11833 }else{
11834 clearTempFile(p);
11836 p->bSafeMode = p->bSafeModePersist;
11837 qss = QSS_Start;
11838 }else if( nSql && QSS_PLAINWHITE(qss) ){
11839 echo_group_input(p, zSql);
11840 nSql = 0;
11841 qss = QSS_Start;
11844 if( nSql ){
11845 /* This may be incomplete. Let the SQL parser deal with that. */
11846 echo_group_input(p, zSql);
11847 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11848 CONTINUE_PROMPT_RESET;
11850 free(zSql);
11851 free(zLine);
11852 --p->inputNesting;
11853 return errCnt>0;
11857 ** Return a pathname which is the user's home directory. A
11858 ** 0 return indicates an error of some kind.
11860 static char *find_home_dir(int clearFlag){
11861 static char *home_dir = NULL;
11862 if( clearFlag ){
11863 free(home_dir);
11864 home_dir = 0;
11865 return 0;
11867 if( home_dir ) return home_dir;
11869 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11870 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11872 struct passwd *pwent;
11873 uid_t uid = getuid();
11874 if( (pwent=getpwuid(uid)) != NULL) {
11875 home_dir = pwent->pw_dir;
11878 #endif
11880 #if defined(_WIN32_WCE)
11881 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11883 home_dir = "/";
11884 #else
11886 #if defined(_WIN32) || defined(WIN32)
11887 if (!home_dir) {
11888 home_dir = getenv("USERPROFILE");
11890 #endif
11892 if (!home_dir) {
11893 home_dir = getenv("HOME");
11896 #if defined(_WIN32) || defined(WIN32)
11897 if (!home_dir) {
11898 char *zDrive, *zPath;
11899 int n;
11900 zDrive = getenv("HOMEDRIVE");
11901 zPath = getenv("HOMEPATH");
11902 if( zDrive && zPath ){
11903 n = strlen30(zDrive) + strlen30(zPath) + 1;
11904 home_dir = malloc( n );
11905 if( home_dir==0 ) return 0;
11906 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11907 return home_dir;
11909 home_dir = "c:\\";
11911 #endif
11913 #endif /* !_WIN32_WCE */
11915 if( home_dir ){
11916 i64 n = strlen(home_dir) + 1;
11917 char *z = malloc( n );
11918 if( z ) memcpy(z, home_dir, n);
11919 home_dir = z;
11922 return home_dir;
11926 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11927 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11928 ** the path to it, else return 0. The result is cached for
11929 ** subsequent calls.
11931 static const char *find_xdg_config(void){
11932 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11933 || defined(__RTP__) || defined(_WRS_KERNEL)
11934 return 0;
11935 #else
11936 static int alreadyTried = 0;
11937 static char *zConfig = 0;
11938 const char *zXdgHome;
11940 if( alreadyTried!=0 ){
11941 return zConfig;
11943 alreadyTried = 1;
11944 zXdgHome = getenv("XDG_CONFIG_HOME");
11945 if( zXdgHome==0 ){
11946 return 0;
11948 zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
11949 shell_check_oom(zConfig);
11950 if( access(zConfig,0)!=0 ){
11951 sqlite3_free(zConfig);
11952 zConfig = 0;
11954 return zConfig;
11955 #endif
11959 ** Read input from the file given by sqliterc_override. Or if that
11960 ** parameter is NULL, take input from the first of find_xdg_config()
11961 ** or ~/.sqliterc which is found.
11963 ** Returns the number of errors.
11965 static void process_sqliterc(
11966 ShellState *p, /* Configuration data */
11967 const char *sqliterc_override /* Name of config file. NULL to use default */
11969 char *home_dir = NULL;
11970 const char *sqliterc = sqliterc_override;
11971 char *zBuf = 0;
11972 FILE *inSaved = p->in;
11973 int savedLineno = p->lineno;
11975 if( sqliterc == NULL ){
11976 sqliterc = find_xdg_config();
11978 if( sqliterc == NULL ){
11979 home_dir = find_home_dir(0);
11980 if( home_dir==0 ){
11981 eputz("-- warning: cannot find home directory;"
11982 " cannot read ~/.sqliterc\n");
11983 return;
11985 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11986 shell_check_oom(zBuf);
11987 sqliterc = zBuf;
11989 p->in = fopen(sqliterc,"rb");
11990 if( p->in ){
11991 if( stdin_is_interactive ){
11992 eputf("-- Loading resources from %s\n", sqliterc);
11994 if( process_input(p) && bail_on_error ) exit(1);
11995 fclose(p->in);
11996 }else if( sqliterc_override!=0 ){
11997 eputf("cannot open: \"%s\"\n", sqliterc);
11998 if( bail_on_error ) exit(1);
12000 p->in = inSaved;
12001 p->lineno = savedLineno;
12002 sqlite3_free(zBuf);
12006 ** Show available command line options
12008 static const char zOptions[] =
12009 " -- treat no subsequent arguments as options\n"
12010 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
12011 " -A ARGS... run \".archive ARGS\" and exit\n"
12012 #endif
12013 " -append append the database to the end of the file\n"
12014 " -ascii set output mode to 'ascii'\n"
12015 " -bail stop after hitting an error\n"
12016 " -batch force batch I/O\n"
12017 " -box set output mode to 'box'\n"
12018 " -column set output mode to 'column'\n"
12019 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
12020 " -csv set output mode to 'csv'\n"
12021 #if !defined(SQLITE_OMIT_DESERIALIZE)
12022 " -deserialize open the database using sqlite3_deserialize()\n"
12023 #endif
12024 " -echo print inputs before execution\n"
12025 " -init FILENAME read/process named file\n"
12026 " -[no]header turn headers on or off\n"
12027 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12028 " -heap SIZE Size of heap for memsys3 or memsys5\n"
12029 #endif
12030 " -help show this message\n"
12031 " -html set output mode to HTML\n"
12032 " -interactive force interactive I/O\n"
12033 " -json set output mode to 'json'\n"
12034 " -line set output mode to 'line'\n"
12035 " -list set output mode to 'list'\n"
12036 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
12037 " -markdown set output mode to 'markdown'\n"
12038 #if !defined(SQLITE_OMIT_DESERIALIZE)
12039 " -maxsize N maximum size for a --deserialize database\n"
12040 #endif
12041 " -memtrace trace all memory allocations and deallocations\n"
12042 " -mmap N default mmap size set to N\n"
12043 #ifdef SQLITE_ENABLE_MULTIPLEX
12044 " -multiplex enable the multiplexor VFS\n"
12045 #endif
12046 " -newline SEP set output row separator. Default: '\\n'\n"
12047 " -nofollow refuse to open symbolic links to database files\n"
12048 " -nonce STRING set the safe-mode escape nonce\n"
12049 " -nullvalue TEXT set text string for NULL values. Default ''\n"
12050 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
12051 " -pcachetrace trace all page cache operations\n"
12052 " -quote set output mode to 'quote'\n"
12053 " -readonly open the database read-only\n"
12054 " -safe enable safe-mode\n"
12055 " -separator SEP set output column separator. Default: '|'\n"
12056 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12057 " -sorterref SIZE sorter references threshold size\n"
12058 #endif
12059 " -stats print memory stats before each finalize\n"
12060 " -table set output mode to 'table'\n"
12061 " -tabs set output mode to 'tabs'\n"
12062 " -unsafe-testing allow unsafe commands and modes for testing\n"
12063 " -version show SQLite version\n"
12064 " -vfs NAME use NAME as the default VFS\n"
12065 #ifdef SQLITE_ENABLE_VFSTRACE
12066 " -vfstrace enable tracing of all VFS calls\n"
12067 #endif
12068 #ifdef SQLITE_HAVE_ZLIB
12069 " -zip open the file as a ZIP Archive\n"
12070 #endif
12072 static void usage(int showDetail){
12073 eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
12074 "FILENAME is the name of an SQLite database. A new database is created\n"
12075 "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
12076 if( showDetail ){
12077 eputf("OPTIONS include:\n%s", zOptions);
12078 }else{
12079 eputz("Use the -help option for additional information\n");
12081 exit(0);
12085 ** Internal check: Verify that the SQLite is uninitialized. Print a
12086 ** error message if it is initialized.
12088 static void verify_uninitialized(void){
12089 if( sqlite3_config(-1)==SQLITE_MISUSE ){
12090 sputz(stdout, "WARNING: attempt to configure SQLite after"
12091 " initialization.\n");
12096 ** Initialize the state information in data
12098 static void main_init(ShellState *data) {
12099 memset(data, 0, sizeof(*data));
12100 data->normalMode = data->cMode = data->mode = MODE_List;
12101 data->autoExplain = 1;
12102 data->pAuxDb = &data->aAuxDb[0];
12103 memcpy(data->colSeparator,SEP_Column, 2);
12104 memcpy(data->rowSeparator,SEP_Row, 2);
12105 data->showHeader = 0;
12106 data->shellFlgs = SHFLG_Lookaside;
12107 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
12108 #if !defined(SQLITE_SHELL_FIDDLE)
12109 verify_uninitialized();
12110 #endif
12111 sqlite3_config(SQLITE_CONFIG_URI, 1);
12112 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
12113 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
12114 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
12118 ** Output text to the console in a font that attracts extra attention.
12120 #if defined(_WIN32) || defined(WIN32)
12121 static void printBold(const char *zText){
12122 #if !SQLITE_OS_WINRT
12123 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
12124 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
12125 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
12126 SetConsoleTextAttribute(out,
12127 FOREGROUND_RED|FOREGROUND_INTENSITY
12129 #endif
12130 sputz(stdout, zText);
12131 #if !SQLITE_OS_WINRT
12132 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
12133 #endif
12135 #else
12136 static void printBold(const char *zText){
12137 sputf(stdout, "\033[1m%s\033[0m", zText);
12139 #endif
12142 ** Get the argument to an --option. Throw an error and die if no argument
12143 ** is available.
12145 static char *cmdline_option_value(int argc, char **argv, int i){
12146 if( i==argc ){
12147 eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
12148 exit(1);
12150 return argv[i];
12153 static void sayAbnormalExit(void){
12154 if( seenInterrupt ) eputz("Program interrupted.\n");
12157 #ifndef SQLITE_SHELL_IS_UTF8
12158 # if (defined(_WIN32) || defined(WIN32)) \
12159 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12160 # define SQLITE_SHELL_IS_UTF8 (0)
12161 # else
12162 # define SQLITE_SHELL_IS_UTF8 (1)
12163 # endif
12164 #endif
12166 #ifdef SQLITE_SHELL_FIDDLE
12167 # define main fiddle_main
12168 #endif
12170 #if SQLITE_SHELL_IS_UTF8
12171 int SQLITE_CDECL main(int argc, char **argv){
12172 #else
12173 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12174 char **argv;
12175 #endif
12176 #ifdef SQLITE_DEBUG
12177 sqlite3_int64 mem_main_enter = 0;
12178 #endif
12179 char *zErrMsg = 0;
12180 #ifdef SQLITE_SHELL_FIDDLE
12181 # define data shellState
12182 #else
12183 ShellState data;
12184 StreamsAreConsole consStreams = SAC_NoConsole;
12185 #endif
12186 const char *zInitFile = 0;
12187 int i;
12188 int rc = 0;
12189 int warnInmemoryDb = 0;
12190 int readStdin = 1;
12191 int nCmd = 0;
12192 int nOptsEnd = argc;
12193 char **azCmd = 0;
12194 const char *zVfs = 0; /* Value of -vfs command-line option */
12195 #if !SQLITE_SHELL_IS_UTF8
12196 char **argvToFree = 0;
12197 int argcToFree = 0;
12198 #endif
12199 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12201 #ifdef SQLITE_SHELL_FIDDLE
12202 stdin_is_interactive = 0;
12203 stdout_is_console = 1;
12204 data.wasm.zDefaultDbName = "/fiddle.sqlite3";
12205 #else
12206 consStreams = consoleClassifySetup(stdin, stdout, stderr);
12207 stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
12208 stdout_is_console = (consStreams & SAC_OutConsole)!=0;
12209 atexit(consoleRestore);
12210 #endif
12211 atexit(sayAbnormalExit);
12212 #ifdef SQLITE_DEBUG
12213 mem_main_enter = sqlite3_memory_used();
12214 #endif
12215 #if !defined(_WIN32_WCE)
12216 if( getenv("SQLITE_DEBUG_BREAK") ){
12217 if( isatty(0) && isatty(2) ){
12218 eputf("attach debugger to process %d and press any key to continue.\n",
12219 GETPID());
12220 fgetc(stdin);
12221 }else{
12222 #if defined(_WIN32) || defined(WIN32)
12223 #if SQLITE_OS_WINRT
12224 __debugbreak();
12225 #else
12226 DebugBreak();
12227 #endif
12228 #elif defined(SIGTRAP)
12229 raise(SIGTRAP);
12230 #endif
12233 #endif
12234 /* Register a valid signal handler early, before much else is done. */
12235 #ifdef SIGINT
12236 signal(SIGINT, interrupt_handler);
12237 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12238 if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
12239 eputz("No ^C handler.\n");
12241 #endif
12243 #if USE_SYSTEM_SQLITE+0!=1
12244 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12245 eputf("SQLite header and source version mismatch\n%s\n%s\n",
12246 sqlite3_sourceid(), SQLITE_SOURCE_ID);
12247 exit(1);
12249 #endif
12250 main_init(&data);
12252 /* On Windows, we must translate command-line arguments into UTF-8.
12253 ** The SQLite memory allocator subsystem has to be enabled in order to
12254 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12255 ** subsequent sqlite3_config() calls will work. So copy all results into
12256 ** memory that does not come from the SQLite memory allocator.
12258 #if !SQLITE_SHELL_IS_UTF8
12259 sqlite3_initialize();
12260 argvToFree = malloc(sizeof(argv[0])*argc*2);
12261 shell_check_oom(argvToFree);
12262 argcToFree = argc;
12263 argv = argvToFree + argc;
12264 for(i=0; i<argc; i++){
12265 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12266 i64 n;
12267 shell_check_oom(z);
12268 n = strlen(z);
12269 argv[i] = malloc( n+1 );
12270 shell_check_oom(argv[i]);
12271 memcpy(argv[i], z, n+1);
12272 argvToFree[i] = argv[i];
12273 sqlite3_free(z);
12275 sqlite3_shutdown();
12276 #endif
12278 assert( argc>=1 && argv && argv[0] );
12279 Argv0 = argv[0];
12281 #ifdef SQLITE_SHELL_DBNAME_PROC
12283 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12284 ** of a C-function that will provide the name of the database file. Use
12285 ** this compile-time option to embed this shell program in larger
12286 ** applications. */
12287 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12288 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12289 warnInmemoryDb = 0;
12291 #endif
12293 /* Do an initial pass through the command-line argument to locate
12294 ** the name of the database file, the name of the initialization file,
12295 ** the size of the alternative malloc heap, options affecting commands
12296 ** or SQL run from the command line, and the first command to execute.
12298 #ifndef SQLITE_SHELL_FIDDLE
12299 verify_uninitialized();
12300 #endif
12301 for(i=1; i<argc; i++){
12302 char *z;
12303 z = argv[i];
12304 if( z[0]!='-' || i>nOptsEnd ){
12305 if( data.aAuxDb->zDbFilename==0 ){
12306 data.aAuxDb->zDbFilename = z;
12307 }else{
12308 /* Excess arguments are interpreted as SQL (or dot-commands) and
12309 ** mean that nothing is read from stdin */
12310 readStdin = 0;
12311 nCmd++;
12312 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12313 shell_check_oom(azCmd);
12314 azCmd[nCmd-1] = z;
12316 continue;
12318 if( z[1]=='-' ) z++;
12319 if( cli_strcmp(z, "-")==0 ){
12320 nOptsEnd = i;
12321 continue;
12322 }else if( cli_strcmp(z,"-separator")==0
12323 || cli_strcmp(z,"-nullvalue")==0
12324 || cli_strcmp(z,"-newline")==0
12325 || cli_strcmp(z,"-cmd")==0
12327 (void)cmdline_option_value(argc, argv, ++i);
12328 }else if( cli_strcmp(z,"-init")==0 ){
12329 zInitFile = cmdline_option_value(argc, argv, ++i);
12330 }else if( cli_strcmp(z,"-interactive")==0 ){
12331 }else if( cli_strcmp(z,"-batch")==0 ){
12332 /* Need to check for batch mode here to so we can avoid printing
12333 ** informational messages (like from process_sqliterc) before
12334 ** we do the actual processing of arguments later in a second pass.
12336 stdin_is_interactive = 0;
12337 }else if( cli_strcmp(z,"-utf8")==0 ){
12338 }else if( cli_strcmp(z,"-no-utf8")==0 ){
12339 }else if( cli_strcmp(z,"-heap")==0 ){
12340 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12341 const char *zSize;
12342 sqlite3_int64 szHeap;
12344 zSize = cmdline_option_value(argc, argv, ++i);
12345 szHeap = integerValue(zSize);
12346 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12347 verify_uninitialized();
12348 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12349 #else
12350 (void)cmdline_option_value(argc, argv, ++i);
12351 #endif
12352 }else if( cli_strcmp(z,"-pagecache")==0 ){
12353 sqlite3_int64 n, sz;
12354 sz = integerValue(cmdline_option_value(argc,argv,++i));
12355 if( sz>70000 ) sz = 70000;
12356 if( sz<0 ) sz = 0;
12357 n = integerValue(cmdline_option_value(argc,argv,++i));
12358 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12359 n = 0xffffffffffffLL/sz;
12361 verify_uninitialized();
12362 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12363 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12364 data.shellFlgs |= SHFLG_Pagecache;
12365 }else if( cli_strcmp(z,"-lookaside")==0 ){
12366 int n, sz;
12367 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12368 if( sz<0 ) sz = 0;
12369 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12370 if( n<0 ) n = 0;
12371 verify_uninitialized();
12372 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12373 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12374 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12375 int n;
12376 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12377 verify_uninitialized();
12378 switch( n ){
12379 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
12380 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
12381 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
12383 #ifdef SQLITE_ENABLE_VFSTRACE
12384 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12385 extern int vfstrace_register(
12386 const char *zTraceName,
12387 const char *zOldVfsName,
12388 int (*xOut)(const char*,void*),
12389 void *pOutArg,
12390 int makeDefault
12392 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12393 #endif
12394 #ifdef SQLITE_ENABLE_MULTIPLEX
12395 }else if( cli_strcmp(z,"-multiplex")==0 ){
12396 extern int sqlite3_multiplex_initialize(const char*,int);
12397 sqlite3_multiplex_initialize(0, 1);
12398 #endif
12399 }else if( cli_strcmp(z,"-mmap")==0 ){
12400 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12401 verify_uninitialized();
12402 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12403 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
12404 }else if( cli_strcmp(z,"-sorterref")==0 ){
12405 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12406 verify_uninitialized();
12407 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12408 #endif
12409 }else if( cli_strcmp(z,"-vfs")==0 ){
12410 zVfs = cmdline_option_value(argc, argv, ++i);
12411 #ifdef SQLITE_HAVE_ZLIB
12412 }else if( cli_strcmp(z,"-zip")==0 ){
12413 data.openMode = SHELL_OPEN_ZIPFILE;
12414 #endif
12415 }else if( cli_strcmp(z,"-append")==0 ){
12416 data.openMode = SHELL_OPEN_APPENDVFS;
12417 #ifndef SQLITE_OMIT_DESERIALIZE
12418 }else if( cli_strcmp(z,"-deserialize")==0 ){
12419 data.openMode = SHELL_OPEN_DESERIALIZE;
12420 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12421 data.szMax = integerValue(argv[++i]);
12422 #endif
12423 }else if( cli_strcmp(z,"-readonly")==0 ){
12424 data.openMode = SHELL_OPEN_READONLY;
12425 }else if( cli_strcmp(z,"-nofollow")==0 ){
12426 data.openFlags = SQLITE_OPEN_NOFOLLOW;
12427 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12428 }else if( cli_strncmp(z, "-A",2)==0 ){
12429 /* All remaining command-line arguments are passed to the ".archive"
12430 ** command, so ignore them */
12431 break;
12432 #endif
12433 }else if( cli_strcmp(z, "-memtrace")==0 ){
12434 sqlite3MemTraceActivate(stderr);
12435 }else if( cli_strcmp(z, "-pcachetrace")==0 ){
12436 sqlite3PcacheTraceActivate(stderr);
12437 }else if( cli_strcmp(z,"-bail")==0 ){
12438 bail_on_error = 1;
12439 }else if( cli_strcmp(z,"-nonce")==0 ){
12440 free(data.zNonce);
12441 data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
12442 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12443 ShellSetFlag(&data,SHFLG_TestingMode);
12444 }else if( cli_strcmp(z,"-safe")==0 ){
12445 /* no-op - catch this on the second pass */
12448 #ifndef SQLITE_SHELL_FIDDLE
12449 verify_uninitialized();
12450 #endif
12453 #ifdef SQLITE_SHELL_INIT_PROC
12455 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12456 ** of a C-function that will perform initialization actions on SQLite that
12457 ** occur just before or after sqlite3_initialize(). Use this compile-time
12458 ** option to embed this shell program in larger applications. */
12459 extern void SQLITE_SHELL_INIT_PROC(void);
12460 SQLITE_SHELL_INIT_PROC();
12462 #else
12463 /* All the sqlite3_config() calls have now been made. So it is safe
12464 ** to call sqlite3_initialize() and process any command line -vfs option. */
12465 sqlite3_initialize();
12466 #endif
12468 if( zVfs ){
12469 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12470 if( pVfs ){
12471 sqlite3_vfs_register(pVfs, 1);
12472 }else{
12473 eputf("no such VFS: \"%s\"\n", zVfs);
12474 exit(1);
12478 if( data.pAuxDb->zDbFilename==0 ){
12479 #ifndef SQLITE_OMIT_MEMORYDB
12480 data.pAuxDb->zDbFilename = ":memory:";
12481 warnInmemoryDb = argc==1;
12482 #else
12483 eputf("%s: Error: no database filename specified\n", Argv0);
12484 return 1;
12485 #endif
12487 data.out = stdout;
12488 #ifndef SQLITE_SHELL_FIDDLE
12489 sqlite3_appendvfs_init(0,0,0);
12490 #endif
12492 /* Go ahead and open the database file if it already exists. If the
12493 ** file does not exist, delay opening it. This prevents empty database
12494 ** files from being created if a user mistypes the database name argument
12495 ** to the sqlite command-line tool.
12497 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12498 open_db(&data, 0);
12501 /* Process the initialization file if there is one. If no -init option
12502 ** is given on the command line, look for a file named ~/.sqliterc and
12503 ** try to process it.
12505 process_sqliterc(&data,zInitFile);
12507 /* Make a second pass through the command-line argument and set
12508 ** options. This second pass is delayed until after the initialization
12509 ** file is processed so that the command-line arguments will override
12510 ** settings in the initialization file.
12512 for(i=1; i<argc; i++){
12513 char *z = argv[i];
12514 if( z[0]!='-' || i>=nOptsEnd ) continue;
12515 if( z[1]=='-' ){ z++; }
12516 if( cli_strcmp(z,"-init")==0 ){
12517 i++;
12518 }else if( cli_strcmp(z,"-html")==0 ){
12519 data.mode = MODE_Html;
12520 }else if( cli_strcmp(z,"-list")==0 ){
12521 data.mode = MODE_List;
12522 }else if( cli_strcmp(z,"-quote")==0 ){
12523 data.mode = MODE_Quote;
12524 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12525 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12526 }else if( cli_strcmp(z,"-line")==0 ){
12527 data.mode = MODE_Line;
12528 }else if( cli_strcmp(z,"-column")==0 ){
12529 data.mode = MODE_Column;
12530 }else if( cli_strcmp(z,"-json")==0 ){
12531 data.mode = MODE_Json;
12532 }else if( cli_strcmp(z,"-markdown")==0 ){
12533 data.mode = MODE_Markdown;
12534 }else if( cli_strcmp(z,"-table")==0 ){
12535 data.mode = MODE_Table;
12536 }else if( cli_strcmp(z,"-box")==0 ){
12537 data.mode = MODE_Box;
12538 }else if( cli_strcmp(z,"-csv")==0 ){
12539 data.mode = MODE_Csv;
12540 memcpy(data.colSeparator,",",2);
12541 #ifdef SQLITE_HAVE_ZLIB
12542 }else if( cli_strcmp(z,"-zip")==0 ){
12543 data.openMode = SHELL_OPEN_ZIPFILE;
12544 #endif
12545 }else if( cli_strcmp(z,"-append")==0 ){
12546 data.openMode = SHELL_OPEN_APPENDVFS;
12547 #ifndef SQLITE_OMIT_DESERIALIZE
12548 }else if( cli_strcmp(z,"-deserialize")==0 ){
12549 data.openMode = SHELL_OPEN_DESERIALIZE;
12550 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12551 data.szMax = integerValue(argv[++i]);
12552 #endif
12553 }else if( cli_strcmp(z,"-readonly")==0 ){
12554 data.openMode = SHELL_OPEN_READONLY;
12555 }else if( cli_strcmp(z,"-nofollow")==0 ){
12556 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12557 }else if( cli_strcmp(z,"-ascii")==0 ){
12558 data.mode = MODE_Ascii;
12559 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
12560 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
12561 }else if( cli_strcmp(z,"-tabs")==0 ){
12562 data.mode = MODE_List;
12563 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
12564 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
12565 }else if( cli_strcmp(z,"-separator")==0 ){
12566 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12567 "%s",cmdline_option_value(argc,argv,++i));
12568 }else if( cli_strcmp(z,"-newline")==0 ){
12569 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12570 "%s",cmdline_option_value(argc,argv,++i));
12571 }else if( cli_strcmp(z,"-nullvalue")==0 ){
12572 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12573 "%s",cmdline_option_value(argc,argv,++i));
12574 }else if( cli_strcmp(z,"-header")==0 ){
12575 data.showHeader = 1;
12576 ShellSetFlag(&data, SHFLG_HeaderSet);
12577 }else if( cli_strcmp(z,"-noheader")==0 ){
12578 data.showHeader = 0;
12579 ShellSetFlag(&data, SHFLG_HeaderSet);
12580 }else if( cli_strcmp(z,"-echo")==0 ){
12581 ShellSetFlag(&data, SHFLG_Echo);
12582 }else if( cli_strcmp(z,"-eqp")==0 ){
12583 data.autoEQP = AUTOEQP_on;
12584 }else if( cli_strcmp(z,"-eqpfull")==0 ){
12585 data.autoEQP = AUTOEQP_full;
12586 }else if( cli_strcmp(z,"-stats")==0 ){
12587 data.statsOn = 1;
12588 }else if( cli_strcmp(z,"-scanstats")==0 ){
12589 data.scanstatsOn = 1;
12590 }else if( cli_strcmp(z,"-backslash")==0 ){
12591 /* Undocumented command-line option: -backslash
12592 ** Causes C-style backslash escapes to be evaluated in SQL statements
12593 ** prior to sending the SQL into SQLite. Useful for injecting
12594 ** crazy bytes in the middle of SQL statements for testing and debugging.
12596 ShellSetFlag(&data, SHFLG_Backslash);
12597 }else if( cli_strcmp(z,"-bail")==0 ){
12598 /* No-op. The bail_on_error flag should already be set. */
12599 }else if( cli_strcmp(z,"-version")==0 ){
12600 sputf(stdout, "%s %s (%d-bit)\n",
12601 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
12602 return 0;
12603 }else if( cli_strcmp(z,"-interactive")==0 ){
12604 /* Need to check for interactive override here to so that it can
12605 ** affect console setup (for Windows only) and testing thereof.
12607 stdin_is_interactive = 1;
12608 }else if( cli_strcmp(z,"-batch")==0 ){
12609 /* already handled */
12610 }else if( cli_strcmp(z,"-utf8")==0 ){
12611 /* already handled */
12612 }else if( cli_strcmp(z,"-no-utf8")==0 ){
12613 /* already handled */
12614 }else if( cli_strcmp(z,"-heap")==0 ){
12615 i++;
12616 }else if( cli_strcmp(z,"-pagecache")==0 ){
12617 i+=2;
12618 }else if( cli_strcmp(z,"-lookaside")==0 ){
12619 i+=2;
12620 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12621 i+=2;
12622 }else if( cli_strcmp(z,"-nonce")==0 ){
12623 i += 2;
12624 }else if( cli_strcmp(z,"-mmap")==0 ){
12625 i++;
12626 }else if( cli_strcmp(z,"-memtrace")==0 ){
12627 i++;
12628 }else if( cli_strcmp(z,"-pcachetrace")==0 ){
12629 i++;
12630 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12631 }else if( cli_strcmp(z,"-sorterref")==0 ){
12632 i++;
12633 #endif
12634 }else if( cli_strcmp(z,"-vfs")==0 ){
12635 i++;
12636 #ifdef SQLITE_ENABLE_VFSTRACE
12637 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12638 i++;
12639 #endif
12640 #ifdef SQLITE_ENABLE_MULTIPLEX
12641 }else if( cli_strcmp(z,"-multiplex")==0 ){
12642 i++;
12643 #endif
12644 }else if( cli_strcmp(z,"-help")==0 ){
12645 usage(1);
12646 }else if( cli_strcmp(z,"-cmd")==0 ){
12647 /* Run commands that follow -cmd first and separately from commands
12648 ** that simply appear on the command-line. This seems goofy. It would
12649 ** be better if all commands ran in the order that they appear. But
12650 ** we retain the goofy behavior for historical compatibility. */
12651 if( i==argc-1 ) break;
12652 z = cmdline_option_value(argc,argv,++i);
12653 if( z[0]=='.' ){
12654 rc = do_meta_command(z, &data);
12655 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12656 }else{
12657 open_db(&data, 0);
12658 rc = shell_exec(&data, z, &zErrMsg);
12659 if( zErrMsg!=0 ){
12660 eputf("Error: %s\n", zErrMsg);
12661 if( bail_on_error ) return rc!=0 ? rc : 1;
12662 }else if( rc!=0 ){
12663 eputf("Error: unable to process SQL \"%s\"\n", z);
12664 if( bail_on_error ) return rc;
12667 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12668 }else if( cli_strncmp(z, "-A", 2)==0 ){
12669 if( nCmd>0 ){
12670 eputf("Error: cannot mix regular SQL or dot-commands"
12671 " with \"%s\"\n", z);
12672 return 1;
12674 open_db(&data, OPEN_DB_ZIPFILE);
12675 if( z[2] ){
12676 argv[i] = &z[2];
12677 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12678 }else{
12679 arDotCommand(&data, 1, argv+i, argc-i);
12681 readStdin = 0;
12682 break;
12683 #endif
12684 }else if( cli_strcmp(z,"-safe")==0 ){
12685 data.bSafeMode = data.bSafeModePersist = 1;
12686 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12687 /* Acted upon in first pass. */
12688 }else{
12689 eputf("%s: Error: unknown option: %s\n", Argv0, z);
12690 eputz("Use -help for a list of options.\n");
12691 return 1;
12693 data.cMode = data.mode;
12696 if( !readStdin ){
12697 /* Run all arguments that do not begin with '-' as if they were separate
12698 ** command-line inputs, except for the argToSkip argument which contains
12699 ** the database filename.
12701 for(i=0; i<nCmd; i++){
12702 if( azCmd[i][0]=='.' ){
12703 rc = do_meta_command(azCmd[i], &data);
12704 if( rc ){
12705 free(azCmd);
12706 return rc==2 ? 0 : rc;
12708 }else{
12709 open_db(&data, 0);
12710 echo_group_input(&data, azCmd[i]);
12711 rc = shell_exec(&data, azCmd[i], &zErrMsg);
12712 if( zErrMsg || rc ){
12713 if( zErrMsg!=0 ){
12714 eputf("Error: %s\n", zErrMsg);
12715 }else{
12716 eputf("Error: unable to process SQL: %s\n", azCmd[i]);
12718 sqlite3_free(zErrMsg);
12719 free(azCmd);
12720 return rc!=0 ? rc : 1;
12724 }else{
12725 /* Run commands received from standard input
12727 if( stdin_is_interactive ){
12728 char *zHome;
12729 char *zHistory;
12730 int nHistory;
12731 #if CIO_WIN_WC_XLATE
12732 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
12733 #else
12734 # define SHELL_CIO_CHAR_SET ""
12735 #endif
12736 sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
12737 "Enter \".help\" for usage hints.\n",
12738 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
12739 if( warnInmemoryDb ){
12740 sputz(stdout, "Connected to a ");
12741 printBold("transient in-memory database");
12742 sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
12743 " persistent database.\n");
12745 zHistory = getenv("SQLITE_HISTORY");
12746 if( zHistory ){
12747 zHistory = strdup(zHistory);
12748 }else if( (zHome = find_home_dir(0))!=0 ){
12749 nHistory = strlen30(zHome) + 20;
12750 if( (zHistory = malloc(nHistory))!=0 ){
12751 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12754 if( zHistory ){ shell_read_history(zHistory); }
12755 #if HAVE_READLINE || HAVE_EDITLINE
12756 rl_attempted_completion_function = readline_completion;
12757 #elif HAVE_LINENOISE
12758 linenoiseSetCompletionCallback(linenoise_completion);
12759 #endif
12760 data.in = 0;
12761 rc = process_input(&data);
12762 if( zHistory ){
12763 shell_stifle_history(2000);
12764 shell_write_history(zHistory);
12765 free(zHistory);
12767 }else{
12768 data.in = stdin;
12769 rc = process_input(&data);
12772 #ifndef SQLITE_SHELL_FIDDLE
12773 /* In WASM mode we have to leave the db state in place so that
12774 ** client code can "push" SQL into it after this call returns. */
12775 free(azCmd);
12776 set_table_name(&data, 0);
12777 if( data.db ){
12778 session_close_all(&data, -1);
12779 close_db(data.db);
12781 for(i=0; i<ArraySize(data.aAuxDb); i++){
12782 sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12783 if( data.aAuxDb[i].db ){
12784 session_close_all(&data, i);
12785 close_db(data.aAuxDb[i].db);
12788 find_home_dir(1);
12789 output_reset(&data);
12790 data.doXdgOpen = 0;
12791 clearTempFile(&data);
12792 #if !SQLITE_SHELL_IS_UTF8
12793 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12794 free(argvToFree);
12795 #endif
12796 free(data.colWidth);
12797 free(data.zNonce);
12798 /* Clear the global data structure so that valgrind will detect memory
12799 ** leaks */
12800 memset(&data, 0, sizeof(data));
12801 #ifdef SQLITE_DEBUG
12802 if( sqlite3_memory_used()>mem_main_enter ){
12803 eputf("Memory leaked: %u bytes\n",
12804 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12806 #endif
12807 #endif /* !SQLITE_SHELL_FIDDLE */
12808 return rc;
12812 #ifdef SQLITE_SHELL_FIDDLE
12813 /* Only for emcc experimentation purposes. */
12814 int fiddle_experiment(int a,int b){
12815 return a + b;
12819 ** Returns a pointer to the current DB handle.
12821 sqlite3 * fiddle_db_handle(){
12822 return globalDb;
12826 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12827 ** "main" is assumed. Returns 0 if no db with the given name is
12828 ** open.
12830 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12831 sqlite3_vfs * pVfs = 0;
12832 if(globalDb){
12833 sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12834 SQLITE_FCNTL_VFS_POINTER, &pVfs);
12836 return pVfs;
12839 /* Only for emcc experimentation purposes. */
12840 sqlite3 * fiddle_db_arg(sqlite3 *arg){
12841 oputf("fiddle_db_arg(%p)\n", (const void*)arg);
12842 return arg;
12846 ** Intended to be called via a SharedWorker() while a separate
12847 ** SharedWorker() (which manages the wasm module) is performing work
12848 ** which should be interrupted. Unfortunately, SharedWorker is not
12849 ** portable enough to make real use of.
12851 void fiddle_interrupt(void){
12852 if( globalDb ) sqlite3_interrupt(globalDb);
12856 ** Returns the filename of the given db name, assuming "main" if
12857 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12859 const char * fiddle_db_filename(const char * zDbName){
12860 return globalDb
12861 ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12862 : NULL;
12866 ** Completely wipes out the contents of the currently-opened database
12867 ** but leaves its storage intact for reuse. If any transactions are
12868 ** active, they are forcibly rolled back.
12870 void fiddle_reset_db(void){
12871 if( globalDb ){
12872 int rc;
12873 while( sqlite3_txn_state(globalDb,0)>0 ){
12875 ** Resolve problem reported in
12876 ** https://sqlite.org/forum/forumpost/0b41a25d65
12878 oputz("Rolling back in-progress transaction.\n");
12879 sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
12881 rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12882 if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12883 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12888 ** Uses the current database's VFS xRead to stream the db file's
12889 ** contents out to the given callback. The callback gets a single
12890 ** chunk of size n (its 2nd argument) on each call and must return 0
12891 ** on success, non-0 on error. This function returns 0 on success,
12892 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12893 ** code from the callback. Note that this is not thread-friendly: it
12894 ** expects that it will be the only thread reading the db file and
12895 ** takes no measures to ensure that is the case.
12897 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12898 sqlite3_int64 nSize = 0;
12899 sqlite3_int64 nPos = 0;
12900 sqlite3_file * pFile = 0;
12901 unsigned char buf[1024 * 8];
12902 int nBuf = (int)sizeof(buf);
12903 int rc = shellState.db
12904 ? sqlite3_file_control(shellState.db, "main",
12905 SQLITE_FCNTL_FILE_POINTER, &pFile)
12906 : SQLITE_NOTFOUND;
12907 if( rc ) return rc;
12908 rc = pFile->pMethods->xFileSize(pFile, &nSize);
12909 if( rc ) return rc;
12910 if(nSize % nBuf){
12911 /* DB size is not an even multiple of the buffer size. Reduce
12912 ** buffer size so that we do not unduly inflate the db size when
12913 ** exporting. */
12914 if(0 == nSize % 4096) nBuf = 4096;
12915 else if(0 == nSize % 2048) nBuf = 2048;
12916 else if(0 == nSize % 1024) nBuf = 1024;
12917 else nBuf = 512;
12919 for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12920 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12921 if(SQLITE_IOERR_SHORT_READ == rc){
12922 rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12924 if( 0==rc ) rc = xCallback(buf, nBuf);
12926 return rc;
12930 ** Trivial exportable function for emscripten. It processes zSql as if
12931 ** it were input to the sqlite3 shell and redirects all output to the
12932 ** wasm binding. fiddle_main() must have been called before this
12933 ** is called, or results are undefined.
12935 void fiddle_exec(const char * zSql){
12936 if(zSql && *zSql){
12937 if('.'==*zSql) puts(zSql);
12938 shellState.wasm.zInput = zSql;
12939 shellState.wasm.zPos = zSql;
12940 process_input(&shellState);
12941 shellState.wasm.zInput = shellState.wasm.zPos = 0;
12944 #endif /* SQLITE_SHELL_FIDDLE */