Merge sqlite-release(3.46.1) into prerelease-integration
[sqlcipher.git] / src / shell.c.in
blob03c7c9056cdbd7329f990e262dd1ff02bf219ed7
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 /* BEGIN SQLCIPHER */
854 #ifdef SQLITE_HAS_CODEC
855 /* Simplistic filtering of input lines to prevent PRAGKA key and
856 PRAGMA rekey statements from being stored in readline history.
857 Note that this will only prevent single line statements, but that
858 will be sufficient for common cases. */
859 if(zResult && *zResult && (
860 sqlite3_strlike("%pragma%key%=%", zResult, 0)==0 ||
861 sqlite3_strlike("%attach%database%as%key%", zResult, 0)==0
863 ) return zResult;
864 #endif
865 /* END SQLCIPHER */
866 if( zResult && *zResult ) shell_add_history(zResult);
867 #endif
869 return zResult;
871 #endif /* !SQLITE_SHELL_FIDDLE */
874 ** Return the value of a hexadecimal digit. Return -1 if the input
875 ** is not a hex digit.
877 static int hexDigitValue(char c){
878 if( c>='0' && c<='9' ) return c - '0';
879 if( c>='a' && c<='f' ) return c - 'a' + 10;
880 if( c>='A' && c<='F' ) return c - 'A' + 10;
881 return -1;
885 ** Interpret zArg as an integer value, possibly with suffixes.
887 static sqlite3_int64 integerValue(const char *zArg){
888 sqlite3_int64 v = 0;
889 static const struct { char *zSuffix; int iMult; } aMult[] = {
890 { "KiB", 1024 },
891 { "MiB", 1024*1024 },
892 { "GiB", 1024*1024*1024 },
893 { "KB", 1000 },
894 { "MB", 1000000 },
895 { "GB", 1000000000 },
896 { "K", 1000 },
897 { "M", 1000000 },
898 { "G", 1000000000 },
900 int i;
901 int isNeg = 0;
902 if( zArg[0]=='-' ){
903 isNeg = 1;
904 zArg++;
905 }else if( zArg[0]=='+' ){
906 zArg++;
908 if( zArg[0]=='0' && zArg[1]=='x' ){
909 int x;
910 zArg += 2;
911 while( (x = hexDigitValue(zArg[0]))>=0 ){
912 v = (v<<4) + x;
913 zArg++;
915 }else{
916 while( IsDigit(zArg[0]) ){
917 v = v*10 + zArg[0] - '0';
918 zArg++;
921 for(i=0; i<ArraySize(aMult); i++){
922 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
923 v *= aMult[i].iMult;
924 break;
927 return isNeg? -v : v;
931 ** A variable length string to which one can append text.
933 typedef struct ShellText ShellText;
934 struct ShellText {
935 char *z;
936 int n;
937 int nAlloc;
941 ** Initialize and destroy a ShellText object
943 static void initText(ShellText *p){
944 memset(p, 0, sizeof(*p));
946 static void freeText(ShellText *p){
947 free(p->z);
948 initText(p);
951 /* zIn is either a pointer to a NULL-terminated string in memory obtained
952 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
953 ** added to zIn, and the result returned in memory obtained from malloc().
954 ** zIn, if it was not NULL, is freed.
956 ** If the third argument, quote, is not '\0', then it is used as a
957 ** quote character for zAppend.
959 static void appendText(ShellText *p, const char *zAppend, char quote){
960 i64 len;
961 i64 i;
962 i64 nAppend = strlen30(zAppend);
964 len = nAppend+p->n+1;
965 if( quote ){
966 len += 2;
967 for(i=0; i<nAppend; i++){
968 if( zAppend[i]==quote ) len++;
972 if( p->z==0 || p->n+len>=p->nAlloc ){
973 p->nAlloc = p->nAlloc*2 + len + 20;
974 p->z = realloc(p->z, p->nAlloc);
975 shell_check_oom(p->z);
978 if( quote ){
979 char *zCsr = p->z+p->n;
980 *zCsr++ = quote;
981 for(i=0; i<nAppend; i++){
982 *zCsr++ = zAppend[i];
983 if( zAppend[i]==quote ) *zCsr++ = quote;
985 *zCsr++ = quote;
986 p->n = (int)(zCsr - p->z);
987 *zCsr = '\0';
988 }else{
989 memcpy(p->z+p->n, zAppend, nAppend);
990 p->n += nAppend;
991 p->z[p->n] = '\0';
996 ** Attempt to determine if identifier zName needs to be quoted, either
997 ** because it contains non-alphanumeric characters, or because it is an
998 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
999 ** that quoting is required.
1001 ** Return '"' if quoting is required. Return 0 if no quoting is required.
1003 static char quoteChar(const char *zName){
1004 int i;
1005 if( zName==0 ) return '"';
1006 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1007 for(i=0; zName[i]; i++){
1008 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1010 return sqlite3_keyword_check(zName, i) ? '"' : 0;
1014 ** Construct a fake object name and column list to describe the structure
1015 ** of the view, virtual table, or table valued function zSchema.zName.
1017 static char *shellFakeSchema(
1018 sqlite3 *db, /* The database connection containing the vtab */
1019 const char *zSchema, /* Schema of the database holding the vtab */
1020 const char *zName /* The name of the virtual table */
1022 sqlite3_stmt *pStmt = 0;
1023 char *zSql;
1024 ShellText s;
1025 char cQuote;
1026 char *zDiv = "(";
1027 int nRow = 0;
1029 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1030 zSchema ? zSchema : "main", zName);
1031 shell_check_oom(zSql);
1032 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1033 sqlite3_free(zSql);
1034 initText(&s);
1035 if( zSchema ){
1036 cQuote = quoteChar(zSchema);
1037 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1038 appendText(&s, zSchema, cQuote);
1039 appendText(&s, ".", 0);
1041 cQuote = quoteChar(zName);
1042 appendText(&s, zName, cQuote);
1043 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1044 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1045 nRow++;
1046 appendText(&s, zDiv, 0);
1047 zDiv = ",";
1048 if( zCol==0 ) zCol = "";
1049 cQuote = quoteChar(zCol);
1050 appendText(&s, zCol, cQuote);
1052 appendText(&s, ")", 0);
1053 sqlite3_finalize(pStmt);
1054 if( nRow==0 ){
1055 freeText(&s);
1056 s.z = 0;
1058 return s.z;
1062 ** SQL function: strtod(X)
1064 ** Use the C-library strtod() function to convert string X into a double.
1065 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1066 ** routines against the C-library.
1068 static void shellStrtod(
1069 sqlite3_context *pCtx,
1070 int nVal,
1071 sqlite3_value **apVal
1073 char *z = (char*)sqlite3_value_text(apVal[0]);
1074 UNUSED_PARAMETER(nVal);
1075 if( z==0 ) return;
1076 sqlite3_result_double(pCtx, strtod(z,0));
1080 ** SQL function: dtostr(X)
1082 ** Use the C-library printf() function to convert real value X into a string.
1083 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1084 ** routines against the C-library.
1086 static void shellDtostr(
1087 sqlite3_context *pCtx,
1088 int nVal,
1089 sqlite3_value **apVal
1091 double r = sqlite3_value_double(apVal[0]);
1092 int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
1093 char z[400];
1094 if( n<1 ) n = 1;
1095 if( n>350 ) n = 350;
1096 sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
1097 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
1102 ** SQL function: shell_module_schema(X)
1104 ** Return a fake schema for the table-valued function or eponymous virtual
1105 ** table X.
1107 static void shellModuleSchema(
1108 sqlite3_context *pCtx,
1109 int nVal,
1110 sqlite3_value **apVal
1112 const char *zName;
1113 char *zFake;
1114 UNUSED_PARAMETER(nVal);
1115 zName = (const char*)sqlite3_value_text(apVal[0]);
1116 zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1117 if( zFake ){
1118 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1119 -1, sqlite3_free);
1120 free(zFake);
1125 ** SQL function: shell_add_schema(S,X)
1127 ** Add the schema name X to the CREATE statement in S and return the result.
1128 ** Examples:
1130 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1132 ** Also works on
1134 ** CREATE INDEX
1135 ** CREATE UNIQUE INDEX
1136 ** CREATE VIEW
1137 ** CREATE TRIGGER
1138 ** CREATE VIRTUAL TABLE
1140 ** This UDF is used by the .schema command to insert the schema name of
1141 ** attached databases into the middle of the sqlite_schema.sql field.
1143 static void shellAddSchemaName(
1144 sqlite3_context *pCtx,
1145 int nVal,
1146 sqlite3_value **apVal
1148 static const char *aPrefix[] = {
1149 "TABLE",
1150 "INDEX",
1151 "UNIQUE INDEX",
1152 "VIEW",
1153 "TRIGGER",
1154 "VIRTUAL TABLE"
1156 int i = 0;
1157 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1158 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1159 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1160 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1161 UNUSED_PARAMETER(nVal);
1162 if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1163 for(i=0; i<ArraySize(aPrefix); i++){
1164 int n = strlen30(aPrefix[i]);
1165 if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1166 char *z = 0;
1167 char *zFake = 0;
1168 if( zSchema ){
1169 char cQuote = quoteChar(zSchema);
1170 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1171 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1172 }else{
1173 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1176 if( zName
1177 && aPrefix[i][0]=='V'
1178 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1180 if( z==0 ){
1181 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1182 }else{
1183 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1185 free(zFake);
1187 if( z ){
1188 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1189 return;
1194 sqlite3_result_value(pCtx, apVal[0]);
1198 ** The source code for several run-time loadable extensions is inserted
1199 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1200 ** code, we need to override some macros to make the included program code
1201 ** work here in the middle of this regular program.
1203 #define SQLITE_EXTENSION_INIT1
1204 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1206 #if defined(_WIN32) && defined(_MSC_VER)
1207 INCLUDE test_windirent.h
1208 INCLUDE test_windirent.c
1209 #define dirent DIRENT
1210 #endif
1211 INCLUDE ../ext/misc/memtrace.c
1212 INCLUDE ../ext/misc/pcachetrace.c
1213 INCLUDE ../ext/misc/shathree.c
1214 INCLUDE ../ext/misc/uint.c
1215 INCLUDE ../ext/misc/decimal.c
1216 #undef sqlite3_base_init
1217 #define sqlite3_base_init sqlite3_base64_init
1218 INCLUDE ../ext/misc/base64.c
1219 #undef sqlite3_base_init
1220 #define sqlite3_base_init sqlite3_base85_init
1221 #define OMIT_BASE85_CHECKER
1222 INCLUDE ../ext/misc/base85.c
1223 INCLUDE ../ext/misc/ieee754.c
1224 INCLUDE ../ext/misc/series.c
1225 INCLUDE ../ext/misc/regexp.c
1226 #ifndef SQLITE_SHELL_FIDDLE
1227 INCLUDE ../ext/misc/fileio.c
1228 INCLUDE ../ext/misc/completion.c
1229 INCLUDE ../ext/misc/appendvfs.c
1230 #endif
1231 #ifdef SQLITE_HAVE_ZLIB
1232 INCLUDE ../ext/misc/zipfile.c
1233 INCLUDE ../ext/misc/sqlar.c
1234 #endif
1235 INCLUDE ../ext/expert/sqlite3expert.h
1236 INCLUDE ../ext/expert/sqlite3expert.c
1238 INCLUDE ../ext/intck/sqlite3intck.h
1239 INCLUDE ../ext/intck/sqlite3intck.c
1241 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1242 #define SQLITE_SHELL_HAVE_RECOVER 1
1243 #else
1244 #define SQLITE_SHELL_HAVE_RECOVER 0
1245 #endif
1246 #if SQLITE_SHELL_HAVE_RECOVER
1247 INCLUDE ../ext/recover/sqlite3recover.h
1248 # ifndef SQLITE_HAVE_SQLITE3R
1249 INCLUDE ../ext/recover/dbdata.c
1250 INCLUDE ../ext/recover/sqlite3recover.c
1251 # endif /* SQLITE_HAVE_SQLITE3R */
1252 #endif
1253 #ifdef SQLITE_SHELL_EXTSRC
1254 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1255 #endif
1257 #if defined(SQLITE_ENABLE_SESSION)
1259 ** State information for a single open session
1261 typedef struct OpenSession OpenSession;
1262 struct OpenSession {
1263 char *zName; /* Symbolic name for this session */
1264 int nFilter; /* Number of xFilter rejection GLOB patterns */
1265 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1266 sqlite3_session *p; /* The open session */
1268 #endif
1270 typedef struct ExpertInfo ExpertInfo;
1271 struct ExpertInfo {
1272 sqlite3expert *pExpert;
1273 int bVerbose;
1276 /* A single line in the EQP output */
1277 typedef struct EQPGraphRow EQPGraphRow;
1278 struct EQPGraphRow {
1279 int iEqpId; /* ID for this row */
1280 int iParentId; /* ID of the parent row */
1281 EQPGraphRow *pNext; /* Next row in sequence */
1282 char zText[1]; /* Text to display for this row */
1285 /* All EQP output is collected into an instance of the following */
1286 typedef struct EQPGraph EQPGraph;
1287 struct EQPGraph {
1288 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1289 EQPGraphRow *pLast; /* Last element of the pRow list */
1290 char zPrefix[100]; /* Graph prefix */
1293 /* Parameters affecting columnar mode result display (defaulting together) */
1294 typedef struct ColModeOpts {
1295 int iWrap; /* In columnar modes, wrap lines reaching this limit */
1296 u8 bQuote; /* Quote results for .mode box and table */
1297 u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
1298 } ColModeOpts;
1299 #define ColModeOpts_default { 60, 0, 0 }
1300 #define ColModeOpts_default_qbox { 60, 1, 0 }
1303 ** State information about the database connection is contained in an
1304 ** instance of the following structure.
1306 typedef struct ShellState ShellState;
1307 struct ShellState {
1308 sqlite3 *db; /* The database */
1309 u8 autoExplain; /* Automatically turn on .explain mode */
1310 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
1311 u8 autoEQPtest; /* autoEQP is in test mode */
1312 u8 autoEQPtrace; /* autoEQP is in trace mode */
1313 u8 scanstatsOn; /* True to display scan stats before each finalize */
1314 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1315 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1316 u8 nEqpLevel; /* Depth of the EQP output graph */
1317 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1318 u8 bSafeMode; /* True to prohibit unsafe operations */
1319 u8 bSafeModePersist; /* The long-term value of bSafeMode */
1320 u8 eRestoreState; /* See comments above doAutoDetectRestore() */
1321 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
1322 unsigned statsOn; /* True to display memory stats before each finalize */
1323 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
1324 int inputNesting; /* Track nesting level of .read and other redirects */
1325 int outCount; /* Revert to stdout when reaching zero */
1326 int cnt; /* Number of records displayed so far */
1327 int lineno; /* Line number of last line read from in */
1328 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1329 FILE *in; /* Read commands from this stream */
1330 FILE *out; /* Write results here */
1331 FILE *traceOut; /* Output for sqlite3_trace() */
1332 int nErr; /* Number of errors seen */
1333 int mode; /* An output mode setting */
1334 int modePrior; /* Saved mode */
1335 int cMode; /* temporary output mode for the current query */
1336 int normalMode; /* Output mode before ".explain on" */
1337 int writableSchema; /* True if PRAGMA writable_schema=ON */
1338 int showHeader; /* True to show column names in List or Column mode */
1339 int nCheck; /* Number of ".check" commands run */
1340 unsigned nProgress; /* Number of progress callbacks encountered */
1341 unsigned mxProgress; /* Maximum progress callbacks before failing */
1342 unsigned flgProgress; /* Flags for the progress callback */
1343 unsigned shellFlgs; /* Various flags */
1344 unsigned priorShFlgs; /* Saved copy of flags */
1345 sqlite3_int64 szMax; /* --maxsize argument to .open */
1346 char *zDestTable; /* Name of destination table when MODE_Insert */
1347 char *zTempFile; /* Temporary file that might need deleting */
1348 char zTestcase[30]; /* Name of current test case */
1349 char colSeparator[20]; /* Column separator character for several modes */
1350 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1351 char colSepPrior[20]; /* Saved column separator */
1352 char rowSepPrior[20]; /* Saved row separator */
1353 int *colWidth; /* Requested width of each column in columnar modes */
1354 int *actualWidth; /* Actual width of each column */
1355 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1356 char nullValue[20]; /* The text to print when a NULL comes back from
1357 ** the database */
1358 char outfile[FILENAME_MAX]; /* Filename for *out */
1359 sqlite3_stmt *pStmt; /* Current statement if any. */
1360 FILE *pLog; /* Write log output here */
1361 struct AuxDb { /* Storage space for auxiliary database connections */
1362 sqlite3 *db; /* Connection pointer */
1363 const char *zDbFilename; /* Filename used to open the connection */
1364 char *zFreeOnClose; /* Free this memory allocation on close */
1365 #if defined(SQLITE_ENABLE_SESSION)
1366 int nSession; /* Number of active sessions */
1367 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1368 #endif
1369 } aAuxDb[5], /* Array of all database connections */
1370 *pAuxDb; /* Currently active database connection */
1371 int *aiIndent; /* Array of indents used in MODE_Explain */
1372 int nIndent; /* Size of array aiIndent[] */
1373 int iIndent; /* Index of current op in aiIndent[] */
1374 char *zNonce; /* Nonce for temporary safe-mode escapes */
1375 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1376 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1377 #ifdef SQLITE_SHELL_FIDDLE
1378 struct {
1379 const char * zInput; /* Input string from wasm/JS proxy */
1380 const char * zPos; /* Cursor pos into zInput */
1381 const char * zDefaultDbName; /* Default name for db file */
1382 } wasm;
1383 #endif
1386 #ifdef SQLITE_SHELL_FIDDLE
1387 static ShellState shellState;
1388 #endif
1391 /* Allowed values for ShellState.autoEQP
1393 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1394 #define AUTOEQP_on 1 /* Automatic EQP is on */
1395 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1396 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1398 /* Allowed values for ShellState.openMode
1400 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1401 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1402 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1403 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1404 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1405 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1406 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1408 /* Allowed values for ShellState.eTraceType
1410 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1411 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1412 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1414 /* Bits in the ShellState.flgProgress variable */
1415 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1416 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
1417 ** callback limit is reached, and for each
1418 ** top-level SQL statement */
1419 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1422 ** These are the allowed shellFlgs values
1424 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1425 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1426 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1427 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1428 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1429 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1430 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1431 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1432 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1433 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1434 #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */
1437 ** Macros for testing and setting shellFlgs
1439 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1440 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1441 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1444 ** These are the allowed modes.
1446 #define MODE_Line 0 /* One column per line. Blank line between records */
1447 #define MODE_Column 1 /* One record per line in neat columns */
1448 #define MODE_List 2 /* One record per line with a separator */
1449 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1450 #define MODE_Html 4 /* Generate an XHTML table */
1451 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1452 #define MODE_Quote 6 /* Quote values as for SQL */
1453 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1454 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1455 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1456 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1457 #define MODE_Pretty 11 /* Pretty-print schemas */
1458 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1459 #define MODE_Json 13 /* Output JSON */
1460 #define MODE_Markdown 14 /* Markdown formatting */
1461 #define MODE_Table 15 /* MySQL-style table formatting */
1462 #define MODE_Box 16 /* Unicode box-drawing characters */
1463 #define MODE_Count 17 /* Output only a count of the rows of output */
1464 #define MODE_Off 18 /* No query output shown */
1465 #define MODE_ScanExp 19 /* Like MODE_Explain, but for ".scanstats vm" */
1467 static const char *modeDescr[] = {
1468 "line",
1469 "column",
1470 "list",
1471 "semi",
1472 "html",
1473 "insert",
1474 "quote",
1475 "tcl",
1476 "csv",
1477 "explain",
1478 "ascii",
1479 "prettyprint",
1480 "eqp",
1481 "json",
1482 "markdown",
1483 "table",
1484 "box",
1485 "count",
1486 "off"
1490 ** These are the column/row/line separators used by the various
1491 ** import/export modes.
1493 #define SEP_Column "|"
1494 #define SEP_Row "\n"
1495 #define SEP_Tab "\t"
1496 #define SEP_Space " "
1497 #define SEP_Comma ","
1498 #define SEP_CrLf "\r\n"
1499 #define SEP_Unit "\x1F"
1500 #define SEP_Record "\x1E"
1503 ** Limit input nesting via .read or any other input redirect.
1504 ** It's not too expensive, so a generous allowance can be made.
1506 #define MAX_INPUT_NESTING 25
1509 ** A callback for the sqlite3_log() interface.
1511 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1512 ShellState *p = (ShellState*)pArg;
1513 if( p->pLog==0 ) return;
1514 sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1515 fflush(p->pLog);
1519 ** SQL function: shell_putsnl(X)
1521 ** Write the text X to the screen (or whatever output is being directed)
1522 ** adding a newline at the end, and then return X.
1524 static void shellPutsFunc(
1525 sqlite3_context *pCtx,
1526 int nVal,
1527 sqlite3_value **apVal
1529 /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
1530 (void)nVal;
1531 oputf("%s\n", sqlite3_value_text(apVal[0]));
1532 sqlite3_result_value(pCtx, apVal[0]);
1536 ** If in safe mode, print an error message described by the arguments
1537 ** and exit immediately.
1539 static void failIfSafeMode(
1540 ShellState *p,
1541 const char *zErrMsg,
1544 if( p->bSafeMode ){
1545 va_list ap;
1546 char *zMsg;
1547 va_start(ap, zErrMsg);
1548 zMsg = sqlite3_vmprintf(zErrMsg, ap);
1549 va_end(ap);
1550 eputf("line %d: %s\n", p->lineno, zMsg);
1551 exit(1);
1556 ** SQL function: edit(VALUE)
1557 ** edit(VALUE,EDITOR)
1559 ** These steps:
1561 ** (1) Write VALUE into a temporary file.
1562 ** (2) Run program EDITOR on that temporary file.
1563 ** (3) Read the temporary file back and return its content as the result.
1564 ** (4) Delete the temporary file
1566 ** If the EDITOR argument is omitted, use the value in the VISUAL
1567 ** environment variable. If still there is no EDITOR, through an error.
1569 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1571 #ifndef SQLITE_NOHAVE_SYSTEM
1572 static void editFunc(
1573 sqlite3_context *context,
1574 int argc,
1575 sqlite3_value **argv
1577 const char *zEditor;
1578 char *zTempFile = 0;
1579 sqlite3 *db;
1580 char *zCmd = 0;
1581 int bBin;
1582 int rc;
1583 int hasCRNL = 0;
1584 FILE *f = 0;
1585 sqlite3_int64 sz;
1586 sqlite3_int64 x;
1587 unsigned char *p = 0;
1589 if( argc==2 ){
1590 zEditor = (const char*)sqlite3_value_text(argv[1]);
1591 }else{
1592 zEditor = getenv("VISUAL");
1594 if( zEditor==0 ){
1595 sqlite3_result_error(context, "no editor for edit()", -1);
1596 return;
1598 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1599 sqlite3_result_error(context, "NULL input to edit()", -1);
1600 return;
1602 db = sqlite3_context_db_handle(context);
1603 zTempFile = 0;
1604 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1605 if( zTempFile==0 ){
1606 sqlite3_uint64 r = 0;
1607 sqlite3_randomness(sizeof(r), &r);
1608 zTempFile = sqlite3_mprintf("temp%llx", r);
1609 if( zTempFile==0 ){
1610 sqlite3_result_error_nomem(context);
1611 return;
1614 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1615 /* When writing the file to be edited, do \n to \r\n conversions on systems
1616 ** that want \r\n line endings */
1617 f = fopen(zTempFile, bBin ? "wb" : "w");
1618 if( f==0 ){
1619 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1620 goto edit_func_end;
1622 sz = sqlite3_value_bytes(argv[0]);
1623 if( bBin ){
1624 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1625 }else{
1626 const char *z = (const char*)sqlite3_value_text(argv[0]);
1627 /* Remember whether or not the value originally contained \r\n */
1628 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1629 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1631 fclose(f);
1632 f = 0;
1633 if( x!=sz ){
1634 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1635 goto edit_func_end;
1637 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1638 if( zCmd==0 ){
1639 sqlite3_result_error_nomem(context);
1640 goto edit_func_end;
1642 rc = system(zCmd);
1643 sqlite3_free(zCmd);
1644 if( rc ){
1645 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1646 goto edit_func_end;
1648 f = fopen(zTempFile, "rb");
1649 if( f==0 ){
1650 sqlite3_result_error(context,
1651 "edit() cannot reopen temp file after edit", -1);
1652 goto edit_func_end;
1654 fseek(f, 0, SEEK_END);
1655 sz = ftell(f);
1656 rewind(f);
1657 p = sqlite3_malloc64( sz+1 );
1658 if( p==0 ){
1659 sqlite3_result_error_nomem(context);
1660 goto edit_func_end;
1662 x = fread(p, 1, (size_t)sz, f);
1663 fclose(f);
1664 f = 0;
1665 if( x!=sz ){
1666 sqlite3_result_error(context, "could not read back the whole file", -1);
1667 goto edit_func_end;
1669 if( bBin ){
1670 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1671 }else{
1672 sqlite3_int64 i, j;
1673 if( hasCRNL ){
1674 /* If the original contains \r\n then do no conversions back to \n */
1675 }else{
1676 /* If the file did not originally contain \r\n then convert any new
1677 ** \r\n back into \n */
1678 p[sz] = 0;
1679 for(i=j=0; i<sz; i++){
1680 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1681 p[j++] = p[i];
1683 sz = j;
1684 p[sz] = 0;
1686 sqlite3_result_text64(context, (const char*)p, sz,
1687 sqlite3_free, SQLITE_UTF8);
1689 p = 0;
1691 edit_func_end:
1692 if( f ) fclose(f);
1693 unlink(zTempFile);
1694 sqlite3_free(zTempFile);
1695 sqlite3_free(p);
1697 #endif /* SQLITE_NOHAVE_SYSTEM */
1700 ** Save or restore the current output mode
1702 static void outputModePush(ShellState *p){
1703 p->modePrior = p->mode;
1704 p->priorShFlgs = p->shellFlgs;
1705 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1706 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1708 static void outputModePop(ShellState *p){
1709 p->mode = p->modePrior;
1710 p->shellFlgs = p->priorShFlgs;
1711 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1712 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1716 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1718 static void output_hex_blob(const void *pBlob, int nBlob){
1719 int i;
1720 unsigned char *aBlob = (unsigned char*)pBlob;
1722 char *zStr = sqlite3_malloc(nBlob*2 + 1);
1723 shell_check_oom(zStr);
1725 for(i=0; i<nBlob; i++){
1726 static const char aHex[] = {
1727 '0', '1', '2', '3', '4', '5', '6', '7',
1728 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1730 zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1731 zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1733 zStr[i*2] = '\0';
1735 oputf("X'%s'", zStr);
1736 sqlite3_free(zStr);
1740 ** Find a string that is not found anywhere in z[]. Return a pointer
1741 ** to that string.
1743 ** Try to use zA and zB first. If both of those are already found in z[]
1744 ** then make up some string and store it in the buffer zBuf.
1746 static const char *unused_string(
1747 const char *z, /* Result must not appear anywhere in z */
1748 const char *zA, const char *zB, /* Try these first */
1749 char *zBuf /* Space to store a generated string */
1751 unsigned i = 0;
1752 if( strstr(z, zA)==0 ) return zA;
1753 if( strstr(z, zB)==0 ) return zB;
1755 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1756 }while( strstr(z,zBuf)!=0 );
1757 return zBuf;
1761 ** Output the given string as a quoted string using SQL quoting conventions.
1763 ** See also: output_quoted_escaped_string()
1765 static void output_quoted_string(const char *z){
1766 int i;
1767 char c;
1768 #ifndef SQLITE_SHELL_FIDDLE
1769 FILE *pfO = setOutputStream(invalidFileStream);
1770 setBinaryMode(pfO, 1);
1771 #endif
1772 if( z==0 ) return;
1773 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1774 if( c==0 ){
1775 oputf("'%s'",z);
1776 }else{
1777 oputz("'");
1778 while( *z ){
1779 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1780 if( c=='\'' ) i++;
1781 if( i ){
1782 oputf("%.*s", i, z);
1783 z += i;
1785 if( c=='\'' ){
1786 oputz("'");
1787 continue;
1789 if( c==0 ){
1790 break;
1792 z++;
1794 oputz("'");
1796 #ifndef SQLITE_SHELL_FIDDLE
1797 setTextMode(pfO, 1);
1798 #else
1799 setTextMode(stdout, 1);
1800 #endif
1804 ** Output the given string as a quoted string using SQL quoting conventions.
1805 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1806 ** get corrupted by end-of-line translation facilities in some operating
1807 ** systems.
1809 ** This is like output_quoted_string() but with the addition of the \r\n
1810 ** escape mechanism.
1812 static void output_quoted_escaped_string(const char *z){
1813 int i;
1814 char c;
1815 #ifndef SQLITE_SHELL_FIDDLE
1816 FILE *pfO = setOutputStream(invalidFileStream);
1817 setBinaryMode(pfO, 1);
1818 #endif
1819 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1820 if( c==0 ){
1821 oputf("'%s'",z);
1822 }else{
1823 const char *zNL = 0;
1824 const char *zCR = 0;
1825 int nNL = 0;
1826 int nCR = 0;
1827 char zBuf1[20], zBuf2[20];
1828 for(i=0; z[i]; i++){
1829 if( z[i]=='\n' ) nNL++;
1830 if( z[i]=='\r' ) nCR++;
1832 if( nNL ){
1833 oputz("replace(");
1834 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1836 if( nCR ){
1837 oputz("replace(");
1838 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1840 oputz("'");
1841 while( *z ){
1842 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1843 if( c=='\'' ) i++;
1844 if( i ){
1845 oputf("%.*s", i, z);
1846 z += i;
1848 if( c=='\'' ){
1849 oputz("'");
1850 continue;
1852 if( c==0 ){
1853 break;
1855 z++;
1856 if( c=='\n' ){
1857 oputz(zNL);
1858 continue;
1860 oputz(zCR);
1862 oputz("'");
1863 if( nCR ){
1864 oputf(",'%s',char(13))", zCR);
1866 if( nNL ){
1867 oputf(",'%s',char(10))", zNL);
1870 #ifndef SQLITE_SHELL_FIDDLE
1871 setTextMode(pfO, 1);
1872 #else
1873 setTextMode(stdout, 1);
1874 #endif
1878 ** Find earliest of chars within s specified in zAny.
1879 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
1881 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
1882 const char *pcFirst = 0;
1883 if( ns == ~(size_t)0 ) ns = strlen(s);
1884 while(*zAny){
1885 const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
1886 if( pc ){
1887 pcFirst = pc;
1888 ns = pcFirst - s;
1890 ++zAny;
1892 return pcFirst;
1895 ** Output the given string as a quoted according to C or TCL quoting rules.
1897 static void output_c_string(const char *z){
1898 char c;
1899 static const char *zq = "\"";
1900 static long ctrlMask = ~0L;
1901 static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
1902 char ace[3] = "\\?";
1903 char cbsSay;
1904 oputz(zq);
1905 while( *z!=0 ){
1906 const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
1907 const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
1908 const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
1909 if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
1910 if( (c = *pcEnd)==0 ) break;
1911 ++pcEnd;
1912 switch( c ){
1913 case '\\': case '"':
1914 cbsSay = (char)c;
1915 break;
1916 case '\t': cbsSay = 't'; break;
1917 case '\n': cbsSay = 'n'; break;
1918 case '\r': cbsSay = 'r'; break;
1919 case '\f': cbsSay = 'f'; break;
1920 default: cbsSay = 0; break;
1922 if( cbsSay ){
1923 ace[1] = cbsSay;
1924 oputz(ace);
1925 }else if( !isprint(c&0xff) ){
1926 oputf("\\%03o", c&0xff);
1927 }else{
1928 ace[1] = (char)c;
1929 oputz(ace+1);
1931 z = pcEnd;
1933 oputz(zq);
1937 ** Output the given string as a quoted according to JSON quoting rules.
1939 static void output_json_string(const char *z, i64 n){
1940 char c;
1941 static const char *zq = "\"";
1942 static long ctrlMask = ~0L;
1943 static const char *zDQBS = "\"\\";
1944 const char *pcLimit;
1945 char ace[3] = "\\?";
1946 char cbsSay;
1948 if( z==0 ) z = "";
1949 pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
1950 oputz(zq);
1951 while( z < pcLimit ){
1952 const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
1953 const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
1954 const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
1955 if( pcEnd > z ){
1956 oputb(z, (int)(pcEnd-z));
1957 z = pcEnd;
1959 if( z >= pcLimit ) break;
1960 c = *(z++);
1961 switch( c ){
1962 case '"': case '\\':
1963 cbsSay = (char)c;
1964 break;
1965 case '\b': cbsSay = 'b'; break;
1966 case '\f': cbsSay = 'f'; break;
1967 case '\n': cbsSay = 'n'; break;
1968 case '\r': cbsSay = 'r'; break;
1969 case '\t': cbsSay = 't'; break;
1970 default: cbsSay = 0; break;
1972 if( cbsSay ){
1973 ace[1] = cbsSay;
1974 oputz(ace);
1975 }else if( c<=0x1f ){
1976 oputf("u%04x", c);
1977 }else{
1978 ace[1] = (char)c;
1979 oputz(ace+1);
1982 oputz(zq);
1986 ** Output the given string with characters that are special to
1987 ** HTML escaped.
1989 static void output_html_string(const char *z){
1990 int i;
1991 if( z==0 ) z = "";
1992 while( *z ){
1993 for(i=0; z[i]
1994 && z[i]!='<'
1995 && z[i]!='&'
1996 && z[i]!='>'
1997 && z[i]!='\"'
1998 && z[i]!='\'';
1999 i++){}
2000 if( i>0 ){
2001 oputf("%.*s",i,z);
2003 if( z[i]=='<' ){
2004 oputz("&lt;");
2005 }else if( z[i]=='&' ){
2006 oputz("&amp;");
2007 }else if( z[i]=='>' ){
2008 oputz("&gt;");
2009 }else if( z[i]=='\"' ){
2010 oputz("&quot;");
2011 }else if( z[i]=='\'' ){
2012 oputz("&#39;");
2013 }else{
2014 break;
2016 z += i + 1;
2021 ** If a field contains any character identified by a 1 in the following
2022 ** array, then the string must be quoted for CSV.
2024 static const char needCsvQuote[] = {
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, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2028 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2029 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2030 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2031 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2032 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2033 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2034 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2035 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2036 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2037 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2038 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2039 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2040 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2044 ** Output a single term of CSV. Actually, p->colSeparator is used for
2045 ** the separator, which may or may not be a comma. p->nullValue is
2046 ** the null value. Strings are quoted if necessary. The separator
2047 ** is only issued if bSep is true.
2049 static void output_csv(ShellState *p, const char *z, int bSep){
2050 if( z==0 ){
2051 oputf("%s",p->nullValue);
2052 }else{
2053 unsigned i;
2054 for(i=0; z[i]; i++){
2055 if( needCsvQuote[((unsigned char*)z)[i]] ){
2056 i = 0;
2057 break;
2060 if( i==0 || strstr(z, p->colSeparator)!=0 ){
2061 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
2062 shell_check_oom(zQuoted);
2063 oputz(zQuoted);
2064 sqlite3_free(zQuoted);
2065 }else{
2066 oputz(z);
2069 if( bSep ){
2070 oputz(p->colSeparator);
2075 ** This routine runs when the user presses Ctrl-C
2077 static void interrupt_handler(int NotUsed){
2078 UNUSED_PARAMETER(NotUsed);
2079 if( ++seenInterrupt>1 ) exit(1);
2080 if( globalDb ) sqlite3_interrupt(globalDb);
2083 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
2085 ** This routine runs for console events (e.g. Ctrl-C) on Win32
2087 static BOOL WINAPI ConsoleCtrlHandler(
2088 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
2090 if( dwCtrlType==CTRL_C_EVENT ){
2091 interrupt_handler(0);
2092 return TRUE;
2094 return FALSE;
2096 #endif
2098 #ifndef SQLITE_OMIT_AUTHORIZATION
2100 ** This authorizer runs in safe mode.
2102 static int safeModeAuth(
2103 void *pClientData,
2104 int op,
2105 const char *zA1,
2106 const char *zA2,
2107 const char *zA3,
2108 const char *zA4
2110 ShellState *p = (ShellState*)pClientData;
2111 static const char *azProhibitedFunctions[] = {
2112 "edit",
2113 "fts3_tokenizer",
2114 "load_extension",
2115 "readfile",
2116 "writefile",
2117 "zipfile",
2118 "zipfile_cds",
2120 UNUSED_PARAMETER(zA1);
2121 UNUSED_PARAMETER(zA3);
2122 UNUSED_PARAMETER(zA4);
2123 switch( op ){
2124 case SQLITE_ATTACH: {
2125 #ifndef SQLITE_SHELL_FIDDLE
2126 /* In WASM builds the filesystem is a virtual sandbox, so
2127 ** there's no harm in using ATTACH. */
2128 failIfSafeMode(p, "cannot run ATTACH in safe mode");
2129 #endif
2130 break;
2132 case SQLITE_FUNCTION: {
2133 int i;
2134 for(i=0; i<ArraySize(azProhibitedFunctions); i++){
2135 if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
2136 failIfSafeMode(p, "cannot use the %s() function in safe mode",
2137 azProhibitedFunctions[i]);
2140 break;
2143 return SQLITE_OK;
2147 ** When the ".auth ON" is set, the following authorizer callback is
2148 ** invoked. It always returns SQLITE_OK.
2150 static int shellAuth(
2151 void *pClientData,
2152 int op,
2153 const char *zA1,
2154 const char *zA2,
2155 const char *zA3,
2156 const char *zA4
2158 ShellState *p = (ShellState*)pClientData;
2159 static const char *azAction[] = { 0,
2160 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2161 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2162 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2163 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2164 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2165 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2166 "PRAGMA", "READ", "SELECT",
2167 "TRANSACTION", "UPDATE", "ATTACH",
2168 "DETACH", "ALTER_TABLE", "REINDEX",
2169 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2170 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2172 int i;
2173 const char *az[4];
2174 az[0] = zA1;
2175 az[1] = zA2;
2176 az[2] = zA3;
2177 az[3] = zA4;
2178 oputf("authorizer: %s", azAction[op]);
2179 for(i=0; i<4; i++){
2180 oputz(" ");
2181 if( az[i] ){
2182 output_c_string(az[i]);
2183 }else{
2184 oputz("NULL");
2187 oputz("\n");
2188 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
2189 return SQLITE_OK;
2191 #endif
2194 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2196 ** This routine converts some CREATE TABLE statements for shadow tables
2197 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2199 ** If the schema statement in z[] contains a start-of-comment and if
2200 ** sqlite3_complete() returns false, try to terminate the comment before
2201 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2203 static void printSchemaLine(const char *z, const char *zTail){
2204 char *zToFree = 0;
2205 if( z==0 ) return;
2206 if( zTail==0 ) return;
2207 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
2208 const char *zOrig = z;
2209 static const char *azTerm[] = { "", "*/", "\n" };
2210 int i;
2211 for(i=0; i<ArraySize(azTerm); i++){
2212 char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
2213 shell_check_oom(zNew);
2214 if( sqlite3_complete(zNew) ){
2215 size_t n = strlen(zNew);
2216 zNew[n-1] = 0;
2217 zToFree = zNew;
2218 z = zNew;
2219 break;
2221 sqlite3_free(zNew);
2224 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
2225 oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
2226 }else{
2227 oputf("%s%s", z, zTail);
2229 sqlite3_free(zToFree);
2231 static void printSchemaLineN(char *z, int n, const char *zTail){
2232 char c = z[n];
2233 z[n] = 0;
2234 printSchemaLine(z, zTail);
2235 z[n] = c;
2239 ** Return true if string z[] has nothing but whitespace and comments to the
2240 ** end of the first line.
2242 static int wsToEol(const char *z){
2243 int i;
2244 for(i=0; z[i]; i++){
2245 if( z[i]=='\n' ) return 1;
2246 if( IsSpace(z[i]) ) continue;
2247 if( z[i]=='-' && z[i+1]=='-' ) return 1;
2248 return 0;
2250 return 1;
2254 ** Add a new entry to the EXPLAIN QUERY PLAN data
2256 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
2257 EQPGraphRow *pNew;
2258 i64 nText;
2259 if( zText==0 ) return;
2260 nText = strlen(zText);
2261 if( p->autoEQPtest ){
2262 oputf("%d,%d,%s\n", iEqpId, p2, zText);
2264 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
2265 shell_check_oom(pNew);
2266 pNew->iEqpId = iEqpId;
2267 pNew->iParentId = p2;
2268 memcpy(pNew->zText, zText, nText+1);
2269 pNew->pNext = 0;
2270 if( p->sGraph.pLast ){
2271 p->sGraph.pLast->pNext = pNew;
2272 }else{
2273 p->sGraph.pRow = pNew;
2275 p->sGraph.pLast = pNew;
2279 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2280 ** in p->sGraph.
2282 static void eqp_reset(ShellState *p){
2283 EQPGraphRow *pRow, *pNext;
2284 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2285 pNext = pRow->pNext;
2286 sqlite3_free(pRow);
2288 memset(&p->sGraph, 0, sizeof(p->sGraph));
2291 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2292 ** pOld, or return the first such line if pOld is NULL
2294 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2295 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2296 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2297 return pRow;
2300 /* Render a single level of the graph that has iEqpId as its parent. Called
2301 ** recursively to render sublevels.
2303 static void eqp_render_level(ShellState *p, int iEqpId){
2304 EQPGraphRow *pRow, *pNext;
2305 i64 n = strlen(p->sGraph.zPrefix);
2306 char *z;
2307 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2308 pNext = eqp_next_row(p, iEqpId, pRow);
2309 z = pRow->zText;
2310 oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
2311 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
2312 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
2313 eqp_render_level(p, pRow->iEqpId);
2314 p->sGraph.zPrefix[n] = 0;
2320 ** Display and reset the EXPLAIN QUERY PLAN data
2322 static void eqp_render(ShellState *p, i64 nCycle){
2323 EQPGraphRow *pRow = p->sGraph.pRow;
2324 if( pRow ){
2325 if( pRow->zText[0]=='-' ){
2326 if( pRow->pNext==0 ){
2327 eqp_reset(p);
2328 return;
2330 oputf("%s\n", pRow->zText+3);
2331 p->sGraph.pRow = pRow->pNext;
2332 sqlite3_free(pRow);
2333 }else if( nCycle>0 ){
2334 oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
2335 }else{
2336 oputz("QUERY PLAN\n");
2338 p->sGraph.zPrefix[0] = 0;
2339 eqp_render_level(p, 0);
2340 eqp_reset(p);
2344 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2346 ** Progress handler callback.
2348 static int progress_handler(void *pClientData) {
2349 ShellState *p = (ShellState*)pClientData;
2350 p->nProgress++;
2351 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2352 oputf("Progress limit reached (%u)\n", p->nProgress);
2353 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2354 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2355 return 1;
2357 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2358 oputf("Progress %u\n", p->nProgress);
2360 return 0;
2362 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2365 ** Print N dashes
2367 static void print_dashes(int N){
2368 const char zDash[] = "--------------------------------------------------";
2369 const int nDash = sizeof(zDash) - 1;
2370 while( N>nDash ){
2371 oputz(zDash);
2372 N -= nDash;
2374 oputf("%.*s", N, zDash);
2378 ** Print a markdown or table-style row separator using ascii-art
2380 static void print_row_separator(
2381 ShellState *p,
2382 int nArg,
2383 const char *zSep
2385 int i;
2386 if( nArg>0 ){
2387 oputz(zSep);
2388 print_dashes(p->actualWidth[0]+2);
2389 for(i=1; i<nArg; i++){
2390 oputz(zSep);
2391 print_dashes(p->actualWidth[i]+2);
2393 oputz(zSep);
2395 oputz("\n");
2399 ** This is the callback routine that the shell
2400 ** invokes for each row of a query result.
2402 static int shell_callback(
2403 void *pArg,
2404 int nArg, /* Number of result columns */
2405 char **azArg, /* Text of each result column */
2406 char **azCol, /* Column names */
2407 int *aiType /* Column types. Might be NULL */
2409 int i;
2410 ShellState *p = (ShellState*)pArg;
2412 if( azArg==0 ) return 0;
2413 switch( p->cMode ){
2414 case MODE_Count:
2415 case MODE_Off: {
2416 break;
2418 case MODE_Line: {
2419 int w = 5;
2420 if( azArg==0 ) break;
2421 for(i=0; i<nArg; i++){
2422 int len = strlen30(azCol[i] ? azCol[i] : "");
2423 if( len>w ) w = len;
2425 if( p->cnt++>0 ) oputz(p->rowSeparator);
2426 for(i=0; i<nArg; i++){
2427 oputf("%*s = %s%s", w, azCol[i],
2428 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2430 break;
2432 case MODE_ScanExp:
2433 case MODE_Explain: {
2434 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2435 static const int aExplainMap[] = {0, 1, 2, 3, 4, 5, 6, 7 };
2436 static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
2437 static const int aScanExpMap[] = {0, 9, 8, 1, 2, 3, 4, 5, 6, 7 };
2439 const int *aWidth = aExplainWidth;
2440 const int *aMap = aExplainMap;
2441 int nWidth = ArraySize(aExplainWidth);
2442 int iIndent = 1;
2444 if( p->cMode==MODE_ScanExp ){
2445 aWidth = aScanExpWidth;
2446 aMap = aScanExpMap;
2447 nWidth = ArraySize(aScanExpWidth);
2448 iIndent = 3;
2450 if( nArg>nWidth ) nArg = nWidth;
2452 /* If this is the first row seen, print out the headers */
2453 if( p->cnt++==0 ){
2454 for(i=0; i<nArg; i++){
2455 utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
2456 oputz(i==nArg-1 ? "\n" : " ");
2458 for(i=0; i<nArg; i++){
2459 print_dashes(aWidth[i]);
2460 oputz(i==nArg-1 ? "\n" : " ");
2464 /* If there is no data, exit early. */
2465 if( azArg==0 ) break;
2467 for(i=0; i<nArg; i++){
2468 const char *zSep = " ";
2469 int w = aWidth[i];
2470 const char *zVal = azArg[ aMap[i] ];
2471 if( i==nArg-1 ) w = 0;
2472 if( zVal && strlenChar(zVal)>w ){
2473 w = strlenChar(zVal);
2474 zSep = " ";
2476 if( i==iIndent && p->aiIndent && p->pStmt ){
2477 if( p->iIndent<p->nIndent ){
2478 oputf("%*.s", p->aiIndent[p->iIndent], "");
2480 p->iIndent++;
2482 utf8_width_print(w, zVal ? zVal : p->nullValue);
2483 oputz(i==nArg-1 ? "\n" : zSep);
2485 break;
2487 case MODE_Semi: { /* .schema and .fullschema output */
2488 printSchemaLine(azArg[0], ";\n");
2489 break;
2491 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2492 char *z;
2493 int j;
2494 int nParen = 0;
2495 char cEnd = 0;
2496 char c;
2497 int nLine = 0;
2498 assert( nArg==1 );
2499 if( azArg[0]==0 ) break;
2500 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2501 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2503 oputf("%s;\n", azArg[0]);
2504 break;
2506 z = sqlite3_mprintf("%s", azArg[0]);
2507 shell_check_oom(z);
2508 j = 0;
2509 for(i=0; IsSpace(z[i]); i++){}
2510 for(; (c = z[i])!=0; i++){
2511 if( IsSpace(c) ){
2512 if( z[j-1]=='\r' ) z[j-1] = '\n';
2513 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2514 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2515 j--;
2517 z[j++] = c;
2519 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2520 z[j] = 0;
2521 if( strlen30(z)>=79 ){
2522 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2523 if( c==cEnd ){
2524 cEnd = 0;
2525 }else if( c=='"' || c=='\'' || c=='`' ){
2526 cEnd = c;
2527 }else if( c=='[' ){
2528 cEnd = ']';
2529 }else if( c=='-' && z[i+1]=='-' ){
2530 cEnd = '\n';
2531 }else if( c=='(' ){
2532 nParen++;
2533 }else if( c==')' ){
2534 nParen--;
2535 if( nLine>0 && nParen==0 && j>0 ){
2536 printSchemaLineN(z, j, "\n");
2537 j = 0;
2540 z[j++] = c;
2541 if( nParen==1 && cEnd==0
2542 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2544 if( c=='\n' ) j--;
2545 printSchemaLineN(z, j, "\n ");
2546 j = 0;
2547 nLine++;
2548 while( IsSpace(z[i+1]) ){ i++; }
2551 z[j] = 0;
2553 printSchemaLine(z, ";\n");
2554 sqlite3_free(z);
2555 break;
2557 case MODE_List: {
2558 if( p->cnt++==0 && p->showHeader ){
2559 for(i=0; i<nArg; i++){
2560 oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
2563 if( azArg==0 ) break;
2564 for(i=0; i<nArg; i++){
2565 char *z = azArg[i];
2566 if( z==0 ) z = p->nullValue;
2567 oputz(z);
2568 oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
2570 break;
2572 case MODE_Html: {
2573 if( p->cnt++==0 && p->showHeader ){
2574 oputz("<TR>");
2575 for(i=0; i<nArg; i++){
2576 oputz("<TH>");
2577 output_html_string(azCol[i]);
2578 oputz("</TH>\n");
2580 oputz("</TR>\n");
2582 if( azArg==0 ) break;
2583 oputz("<TR>");
2584 for(i=0; i<nArg; i++){
2585 oputz("<TD>");
2586 output_html_string(azArg[i] ? azArg[i] : p->nullValue);
2587 oputz("</TD>\n");
2589 oputz("</TR>\n");
2590 break;
2592 case MODE_Tcl: {
2593 if( p->cnt++==0 && p->showHeader ){
2594 for(i=0; i<nArg; i++){
2595 output_c_string(azCol[i] ? azCol[i] : "");
2596 if(i<nArg-1) oputz(p->colSeparator);
2598 oputz(p->rowSeparator);
2600 if( azArg==0 ) break;
2601 for(i=0; i<nArg; i++){
2602 output_c_string(azArg[i] ? azArg[i] : p->nullValue);
2603 if(i<nArg-1) oputz(p->colSeparator);
2605 oputz(p->rowSeparator);
2606 break;
2608 case MODE_Csv: {
2609 setBinaryMode(p->out, 1);
2610 if( p->cnt++==0 && p->showHeader ){
2611 for(i=0; i<nArg; i++){
2612 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2614 oputz(p->rowSeparator);
2616 if( nArg>0 ){
2617 for(i=0; i<nArg; i++){
2618 output_csv(p, azArg[i], i<nArg-1);
2620 oputz(p->rowSeparator);
2622 setTextMode(p->out, 1);
2623 break;
2625 case MODE_Insert: {
2626 if( azArg==0 ) break;
2627 oputf("INSERT INTO %s",p->zDestTable);
2628 if( p->showHeader ){
2629 oputz("(");
2630 for(i=0; i<nArg; i++){
2631 if( i>0 ) oputz(",");
2632 if( quoteChar(azCol[i]) ){
2633 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2634 shell_check_oom(z);
2635 oputz(z);
2636 sqlite3_free(z);
2637 }else{
2638 oputf("%s", azCol[i]);
2641 oputz(")");
2643 p->cnt++;
2644 for(i=0; i<nArg; i++){
2645 oputz(i>0 ? "," : " VALUES(");
2646 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2647 oputz("NULL");
2648 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2649 if( ShellHasFlag(p, SHFLG_Newlines) ){
2650 output_quoted_string(azArg[i]);
2651 }else{
2652 output_quoted_escaped_string(azArg[i]);
2654 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2655 oputz(azArg[i]);
2656 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2657 char z[50];
2658 double r = sqlite3_column_double(p->pStmt, i);
2659 sqlite3_uint64 ur;
2660 memcpy(&ur,&r,sizeof(r));
2661 if( ur==0x7ff0000000000000LL ){
2662 oputz("9.0e+999");
2663 }else if( ur==0xfff0000000000000LL ){
2664 oputz("-9.0e+999");
2665 }else{
2666 sqlite3_int64 ir = (sqlite3_int64)r;
2667 if( r==(double)ir ){
2668 sqlite3_snprintf(50,z,"%lld.0", ir);
2669 }else{
2670 sqlite3_snprintf(50,z,"%!.20g", r);
2672 oputz(z);
2674 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2675 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2676 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2677 output_hex_blob(pBlob, nBlob);
2678 }else if( isNumber(azArg[i], 0) ){
2679 oputz(azArg[i]);
2680 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2681 output_quoted_string(azArg[i]);
2682 }else{
2683 output_quoted_escaped_string(azArg[i]);
2686 oputz(");\n");
2687 break;
2689 case MODE_Json: {
2690 if( azArg==0 ) break;
2691 if( p->cnt==0 ){
2692 fputs("[{", p->out);
2693 }else{
2694 fputs(",\n{", p->out);
2696 p->cnt++;
2697 for(i=0; i<nArg; i++){
2698 output_json_string(azCol[i], -1);
2699 oputz(":");
2700 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2701 oputz("null");
2702 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2703 char z[50];
2704 double r = sqlite3_column_double(p->pStmt, i);
2705 sqlite3_uint64 ur;
2706 memcpy(&ur,&r,sizeof(r));
2707 if( ur==0x7ff0000000000000LL ){
2708 oputz("9.0e+999");
2709 }else if( ur==0xfff0000000000000LL ){
2710 oputz("-9.0e+999");
2711 }else{
2712 sqlite3_snprintf(50,z,"%!.20g", r);
2713 oputz(z);
2715 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2716 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2717 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2718 output_json_string(pBlob, nBlob);
2719 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2720 output_json_string(azArg[i], -1);
2721 }else{
2722 oputz(azArg[i]);
2724 if( i<nArg-1 ){
2725 oputz(",");
2728 oputz("}");
2729 break;
2731 case MODE_Quote: {
2732 if( azArg==0 ) break;
2733 if( p->cnt==0 && p->showHeader ){
2734 for(i=0; i<nArg; i++){
2735 if( i>0 ) fputs(p->colSeparator, p->out);
2736 output_quoted_string(azCol[i]);
2738 fputs(p->rowSeparator, p->out);
2740 p->cnt++;
2741 for(i=0; i<nArg; i++){
2742 if( i>0 ) fputs(p->colSeparator, p->out);
2743 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2744 oputz("NULL");
2745 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2746 output_quoted_string(azArg[i]);
2747 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2748 oputz(azArg[i]);
2749 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2750 char z[50];
2751 double r = sqlite3_column_double(p->pStmt, i);
2752 sqlite3_snprintf(50,z,"%!.20g", r);
2753 oputz(z);
2754 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2755 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2756 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2757 output_hex_blob(pBlob, nBlob);
2758 }else if( isNumber(azArg[i], 0) ){
2759 oputz(azArg[i]);
2760 }else{
2761 output_quoted_string(azArg[i]);
2764 fputs(p->rowSeparator, p->out);
2765 break;
2767 case MODE_Ascii: {
2768 if( p->cnt++==0 && p->showHeader ){
2769 for(i=0; i<nArg; i++){
2770 if( i>0 ) oputz(p->colSeparator);
2771 oputz(azCol[i] ? azCol[i] : "");
2773 oputz(p->rowSeparator);
2775 if( azArg==0 ) break;
2776 for(i=0; i<nArg; i++){
2777 if( i>0 ) oputz(p->colSeparator);
2778 oputz(azArg[i] ? azArg[i] : p->nullValue);
2780 oputz(p->rowSeparator);
2781 break;
2783 case MODE_EQP: {
2784 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2785 break;
2788 return 0;
2792 ** This is the callback routine that the SQLite library
2793 ** invokes for each row of a query result.
2795 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2796 /* since we don't have type info, call the shell_callback with a NULL value */
2797 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2801 ** This is the callback routine from sqlite3_exec() that appends all
2802 ** output onto the end of a ShellText object.
2804 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2805 ShellText *p = (ShellText*)pArg;
2806 int i;
2807 UNUSED_PARAMETER(az);
2808 if( azArg==0 ) return 0;
2809 if( p->n ) appendText(p, "|", 0);
2810 for(i=0; i<nArg; i++){
2811 if( i ) appendText(p, ",", 0);
2812 if( azArg[i] ) appendText(p, azArg[i], 0);
2814 return 0;
2818 ** Generate an appropriate SELFTEST table in the main database.
2820 static void createSelftestTable(ShellState *p){
2821 char *zErrMsg = 0;
2822 sqlite3_exec(p->db,
2823 "SAVEPOINT selftest_init;\n"
2824 "CREATE TABLE IF NOT EXISTS selftest(\n"
2825 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2826 " op TEXT,\n" /* Operator: memo run */
2827 " cmd TEXT,\n" /* Command text */
2828 " ans TEXT\n" /* Desired answer */
2829 ");"
2830 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2831 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2832 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2833 " 'memo','Tests generated by --init');\n"
2834 "INSERT INTO [_shell$self]\n"
2835 " SELECT 'run',\n"
2836 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2837 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2838 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2839 "FROM sqlite_schema ORDER BY 2',224));\n"
2840 "INSERT INTO [_shell$self]\n"
2841 " SELECT 'run',"
2842 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2843 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2844 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2845 " FROM (\n"
2846 " SELECT name FROM sqlite_schema\n"
2847 " WHERE type='table'\n"
2848 " AND name<>'selftest'\n"
2849 " AND coalesce(rootpage,0)>0\n"
2850 " )\n"
2851 " ORDER BY name;\n"
2852 "INSERT INTO [_shell$self]\n"
2853 " VALUES('run','PRAGMA integrity_check','ok');\n"
2854 "INSERT INTO selftest(tno,op,cmd,ans)"
2855 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2856 "DROP TABLE [_shell$self];"
2857 ,0,0,&zErrMsg);
2858 if( zErrMsg ){
2859 eputf("SELFTEST initialization failure: %s\n", zErrMsg);
2860 sqlite3_free(zErrMsg);
2862 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2867 ** Set the destination table field of the ShellState structure to
2868 ** the name of the table given. Escape any quote characters in the
2869 ** table name.
2871 static void set_table_name(ShellState *p, const char *zName){
2872 int i, n;
2873 char cQuote;
2874 char *z;
2876 if( p->zDestTable ){
2877 free(p->zDestTable);
2878 p->zDestTable = 0;
2880 if( zName==0 ) return;
2881 cQuote = quoteChar(zName);
2882 n = strlen30(zName);
2883 if( cQuote ) n += n+2;
2884 z = p->zDestTable = malloc( n+1 );
2885 shell_check_oom(z);
2886 n = 0;
2887 if( cQuote ) z[n++] = cQuote;
2888 for(i=0; zName[i]; i++){
2889 z[n++] = zName[i];
2890 if( zName[i]==cQuote ) z[n++] = cQuote;
2892 if( cQuote ) z[n++] = cQuote;
2893 z[n] = 0;
2897 ** Maybe construct two lines of text that point out the position of a
2898 ** syntax error. Return a pointer to the text, in memory obtained from
2899 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2900 ** specific token that we can point to, return an empty string.
2902 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2903 ** and should be released by the caller invoking sqlite3_free().
2905 static char *shell_error_context(const char *zSql, sqlite3 *db){
2906 int iOffset;
2907 size_t len;
2908 char *zCode;
2909 char *zMsg;
2910 int i;
2911 if( db==0
2912 || zSql==0
2913 || (iOffset = sqlite3_error_offset(db))<0
2914 || iOffset>=(int)strlen(zSql)
2916 return sqlite3_mprintf("");
2918 while( iOffset>50 ){
2919 iOffset--;
2920 zSql++;
2921 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2923 len = strlen(zSql);
2924 if( len>78 ){
2925 len = 78;
2926 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
2928 zCode = sqlite3_mprintf("%.*s", len, zSql);
2929 shell_check_oom(zCode);
2930 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2931 if( iOffset<25 ){
2932 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
2933 }else{
2934 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,"");
2936 return zMsg;
2941 ** Execute a query statement that will generate SQL output. Print
2942 ** the result columns, comma-separated, on a line and then add a
2943 ** semicolon terminator to the end of that line.
2945 ** If the number of columns is 1 and that column contains text "--"
2946 ** then write the semicolon on a separate line. That way, if a
2947 ** "--" comment occurs at the end of the statement, the comment
2948 ** won't consume the semicolon terminator.
2950 static int run_table_dump_query(
2951 ShellState *p, /* Query context */
2952 const char *zSelect /* SELECT statement to extract content */
2954 sqlite3_stmt *pSelect;
2955 int rc;
2956 int nResult;
2957 int i;
2958 const char *z;
2959 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2960 if( rc!=SQLITE_OK || !pSelect ){
2961 char *zContext = shell_error_context(zSelect, p->db);
2962 oputf("/**** ERROR: (%d) %s *****/\n%s",
2963 rc, sqlite3_errmsg(p->db), zContext);
2964 sqlite3_free(zContext);
2965 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2966 return rc;
2968 rc = sqlite3_step(pSelect);
2969 nResult = sqlite3_column_count(pSelect);
2970 while( rc==SQLITE_ROW ){
2971 z = (const char*)sqlite3_column_text(pSelect, 0);
2972 oputf("%s", z);
2973 for(i=1; i<nResult; i++){
2974 oputf(",%s", sqlite3_column_text(pSelect, i));
2976 if( z==0 ) z = "";
2977 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2978 if( z[0] ){
2979 oputz("\n;\n");
2980 }else{
2981 oputz(";\n");
2983 rc = sqlite3_step(pSelect);
2985 rc = sqlite3_finalize(pSelect);
2986 if( rc!=SQLITE_OK ){
2987 oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
2988 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2990 return rc;
2994 ** Allocate space and save off string indicating current error.
2996 static char *save_err_msg(
2997 sqlite3 *db, /* Database to query */
2998 const char *zPhase, /* When the error occurs */
2999 int rc, /* Error code returned from API */
3000 const char *zSql /* SQL string, or NULL */
3002 char *zErr;
3003 char *zContext;
3004 sqlite3_str *pStr = sqlite3_str_new(0);
3005 sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
3006 if( rc>1 ){
3007 sqlite3_str_appendf(pStr, " (%d)", rc);
3009 zContext = shell_error_context(zSql, db);
3010 if( zContext ){
3011 sqlite3_str_appendall(pStr, zContext);
3012 sqlite3_free(zContext);
3014 zErr = sqlite3_str_finish(pStr);
3015 shell_check_oom(zErr);
3016 return zErr;
3019 #ifdef __linux__
3021 ** Attempt to display I/O stats on Linux using /proc/PID/io
3023 static void displayLinuxIoStats(void){
3024 FILE *in;
3025 char z[200];
3026 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
3027 in = fopen(z, "rb");
3028 if( in==0 ) return;
3029 while( fgets(z, sizeof(z), in)!=0 ){
3030 static const struct {
3031 const char *zPattern;
3032 const char *zDesc;
3033 } aTrans[] = {
3034 { "rchar: ", "Bytes received by read():" },
3035 { "wchar: ", "Bytes sent to write():" },
3036 { "syscr: ", "Read() system calls:" },
3037 { "syscw: ", "Write() system calls:" },
3038 { "read_bytes: ", "Bytes read from storage:" },
3039 { "write_bytes: ", "Bytes written to storage:" },
3040 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
3042 int i;
3043 for(i=0; i<ArraySize(aTrans); i++){
3044 int n = strlen30(aTrans[i].zPattern);
3045 if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
3046 oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
3047 break;
3051 fclose(in);
3053 #endif
3056 ** Display a single line of status using 64-bit values.
3058 static void displayStatLine(
3059 char *zLabel, /* Label for this one line */
3060 char *zFormat, /* Format for the result */
3061 int iStatusCtrl, /* Which status to display */
3062 int bReset /* True to reset the stats */
3064 sqlite3_int64 iCur = -1;
3065 sqlite3_int64 iHiwtr = -1;
3066 int i, nPercent;
3067 char zLine[200];
3068 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
3069 for(i=0, nPercent=0; zFormat[i]; i++){
3070 if( zFormat[i]=='%' ) nPercent++;
3072 if( nPercent>1 ){
3073 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
3074 }else{
3075 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
3077 oputf("%-36s %s\n", zLabel, zLine);
3081 ** Display memory stats.
3083 static int display_stats(
3084 sqlite3 *db, /* Database to query */
3085 ShellState *pArg, /* Pointer to ShellState */
3086 int bReset /* True to reset the stats */
3088 int iCur;
3089 int iHiwtr;
3090 if( pArg==0 || pArg->out==0 ) return 0;
3092 if( pArg->pStmt && pArg->statsOn==2 ){
3093 int nCol, i, x;
3094 sqlite3_stmt *pStmt = pArg->pStmt;
3095 char z[100];
3096 nCol = sqlite3_column_count(pStmt);
3097 oputf("%-36s %d\n", "Number of output columns:", nCol);
3098 for(i=0; i<nCol; i++){
3099 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
3100 oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
3101 #ifndef SQLITE_OMIT_DECLTYPE
3102 sqlite3_snprintf(30, z+x, "declared type:");
3103 oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
3104 #endif
3105 #ifdef SQLITE_ENABLE_COLUMN_METADATA
3106 sqlite3_snprintf(30, z+x, "database name:");
3107 oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
3108 sqlite3_snprintf(30, z+x, "table name:");
3109 oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
3110 sqlite3_snprintf(30, z+x, "origin name:");
3111 oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
3112 #endif
3116 if( pArg->statsOn==3 ){
3117 if( pArg->pStmt ){
3118 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
3119 oputf("VM-steps: %d\n", iCur);
3121 return 0;
3124 displayStatLine("Memory Used:",
3125 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
3126 displayStatLine("Number of Outstanding Allocations:",
3127 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
3128 if( pArg->shellFlgs & SHFLG_Pagecache ){
3129 displayStatLine("Number of Pcache Pages Used:",
3130 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
3132 displayStatLine("Number of Pcache Overflow Bytes:",
3133 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
3134 displayStatLine("Largest Allocation:",
3135 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
3136 displayStatLine("Largest Pcache Allocation:",
3137 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
3138 #ifdef YYTRACKMAXSTACKDEPTH
3139 displayStatLine("Deepest Parser Stack:",
3140 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
3141 #endif
3143 if( db ){
3144 if( pArg->shellFlgs & SHFLG_Lookaside ){
3145 iHiwtr = iCur = -1;
3146 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
3147 &iCur, &iHiwtr, bReset);
3148 oputf("Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
3149 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
3150 &iCur, &iHiwtr, bReset);
3151 oputf("Successful lookaside attempts: %d\n", iHiwtr);
3152 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
3153 &iCur, &iHiwtr, bReset);
3154 oputf("Lookaside failures due to size: %d\n", iHiwtr);
3155 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
3156 &iCur, &iHiwtr, bReset);
3157 oputf("Lookaside failures due to OOM: %d\n", iHiwtr);
3159 iHiwtr = iCur = -1;
3160 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
3161 oputf("Pager Heap Usage: %d bytes\n", iCur);
3162 iHiwtr = iCur = -1;
3163 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
3164 oputf("Page cache hits: %d\n", iCur);
3165 iHiwtr = iCur = -1;
3166 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
3167 oputf("Page cache misses: %d\n", iCur);
3168 iHiwtr = iCur = -1;
3169 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
3170 oputf("Page cache writes: %d\n", iCur);
3171 iHiwtr = iCur = -1;
3172 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
3173 oputf("Page cache spills: %d\n", iCur);
3174 iHiwtr = iCur = -1;
3175 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
3176 oputf("Schema Heap Usage: %d bytes\n", iCur);
3177 iHiwtr = iCur = -1;
3178 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
3179 oputf("Statement Heap/Lookaside Usage: %d bytes\n", iCur);
3182 if( pArg->pStmt ){
3183 int iHit, iMiss;
3184 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
3185 bReset);
3186 oputf("Fullscan Steps: %d\n", iCur);
3187 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
3188 oputf("Sort Operations: %d\n", iCur);
3189 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
3190 oputf("Autoindex Inserts: %d\n", iCur);
3191 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
3192 bReset);
3193 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
3194 bReset);
3195 if( iHit || iMiss ){
3196 oputf("Bloom filter bypass taken: %d/%d\n", iHit, iHit+iMiss);
3198 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
3199 oputf("Virtual Machine Steps: %d\n", iCur);
3200 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
3201 oputf("Reprepare operations: %d\n", iCur);
3202 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
3203 oputf("Number of times run: %d\n", iCur);
3204 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
3205 oputf("Memory used by prepared stmt: %d\n", iCur);
3208 #ifdef __linux__
3209 displayLinuxIoStats();
3210 #endif
3212 /* Do not remove this machine readable comment: extra-stats-output-here */
3214 return 0;
3218 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3219 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
3220 int iPid = 0;
3221 int ret = 1;
3222 sqlite3_stmt_scanstatus_v2(p, iEntry,
3223 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3225 while( iPid!=0 ){
3226 int ii;
3227 for(ii=0; 1; ii++){
3228 int iId;
3229 int res;
3230 res = sqlite3_stmt_scanstatus_v2(p, ii,
3231 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
3233 if( res ) break;
3234 if( iId==iPid ){
3235 sqlite3_stmt_scanstatus_v2(p, ii,
3236 SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3240 ret++;
3242 return ret;
3244 #endif
3246 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3247 static void display_explain_scanstats(
3248 sqlite3 *db, /* Database to query */
3249 ShellState *pArg /* Pointer to ShellState */
3251 static const int f = SQLITE_SCANSTAT_COMPLEX;
3252 sqlite3_stmt *p = pArg->pStmt;
3253 int ii = 0;
3254 i64 nTotal = 0;
3255 int nWidth = 0;
3256 eqp_reset(pArg);
3258 for(ii=0; 1; ii++){
3259 const char *z = 0;
3260 int n = 0;
3261 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
3262 break;
3264 n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
3265 if( n>nWidth ) nWidth = n;
3267 nWidth += 4;
3269 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
3270 for(ii=0; 1; ii++){
3271 i64 nLoop = 0;
3272 i64 nRow = 0;
3273 i64 nCycle = 0;
3274 int iId = 0;
3275 int iPid = 0;
3276 const char *zo = 0;
3277 const char *zName = 0;
3278 char *zText = 0;
3279 double rEst = 0.0;
3281 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
3282 break;
3284 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
3285 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
3286 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
3287 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
3288 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
3289 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
3290 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
3292 zText = sqlite3_mprintf("%s", zo);
3293 if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
3294 char *z = 0;
3295 if( nCycle>=0 && nTotal>0 ){
3296 z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
3297 nCycle, ((nCycle*100)+nTotal/2) / nTotal
3300 if( nLoop>=0 ){
3301 z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
3303 if( nRow>=0 ){
3304 z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
3307 if( zName && pArg->scanstatsOn>1 ){
3308 double rpl = (double)nRow / (double)nLoop;
3309 z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
3312 zText = sqlite3_mprintf(
3313 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
3317 eqp_append(pArg, iId, iPid, zText);
3318 sqlite3_free(zText);
3321 eqp_render(pArg, nTotal);
3323 #endif
3327 ** Parameter azArray points to a zero-terminated array of strings. zStr
3328 ** points to a single nul-terminated string. Return non-zero if zStr
3329 ** is equal, according to strcmp(), to any of the strings in the array.
3330 ** Otherwise, return zero.
3332 static int str_in_array(const char *zStr, const char **azArray){
3333 int i;
3334 for(i=0; azArray[i]; i++){
3335 if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
3337 return 0;
3341 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3342 ** and populate the ShellState.aiIndent[] array with the number of
3343 ** spaces each opcode should be indented before it is output.
3345 ** The indenting rules are:
3347 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3348 ** all opcodes that occur between the p2 jump destination and the opcode
3349 ** itself by 2 spaces.
3351 ** * Do the previous for "Return" instructions for when P2 is positive.
3352 ** See tag-20220407a in wherecode.c and vdbe.c.
3354 ** * For each "Goto", if the jump destination is earlier in the program
3355 ** and ends on one of:
3356 ** Yield SeekGt SeekLt RowSetRead Rewind
3357 ** or if the P1 parameter is one instead of zero,
3358 ** then indent all opcodes between the earlier instruction
3359 ** and "Goto" by 2 spaces.
3361 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3362 int *abYield = 0; /* True if op is an OP_Yield */
3363 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
3364 int iOp; /* Index of operation in p->aiIndent[] */
3366 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3367 "Return", 0 };
3368 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3369 "Rewind", 0 };
3370 const char *azGoto[] = { "Goto", 0 };
3372 /* The caller guarantees that the leftmost 4 columns of the statement
3373 ** passed to this function are equivalent to the leftmost 4 columns
3374 ** of EXPLAIN statement output. In practice the statement may be
3375 ** an EXPLAIN, or it may be a query on the bytecode() virtual table. */
3376 assert( sqlite3_column_count(pSql)>=4 );
3377 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
3378 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
3379 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
3380 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
3382 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3383 int i;
3384 int iAddr = sqlite3_column_int(pSql, 0);
3385 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3386 int p1 = sqlite3_column_int(pSql, 2);
3387 int p2 = sqlite3_column_int(pSql, 3);
3389 /* Assuming that p2 is an instruction address, set variable p2op to the
3390 ** index of that instruction in the aiIndent[] array. p2 and p2op may be
3391 ** different if the current instruction is part of a sub-program generated
3392 ** by an SQL trigger or foreign key. */
3393 int p2op = (p2 + (iOp-iAddr));
3395 /* Grow the p->aiIndent array as required */
3396 if( iOp>=nAlloc ){
3397 nAlloc += 100;
3398 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3399 shell_check_oom(p->aiIndent);
3400 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3401 shell_check_oom(abYield);
3404 abYield[iOp] = str_in_array(zOp, azYield);
3405 p->aiIndent[iOp] = 0;
3406 p->nIndent = iOp+1;
3407 if( str_in_array(zOp, azNext) && p2op>0 ){
3408 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3410 if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
3411 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3415 p->iIndent = 0;
3416 sqlite3_free(abYield);
3417 sqlite3_reset(pSql);
3421 ** Free the array allocated by explain_data_prepare().
3423 static void explain_data_delete(ShellState *p){
3424 sqlite3_free(p->aiIndent);
3425 p->aiIndent = 0;
3426 p->nIndent = 0;
3427 p->iIndent = 0;
3430 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
3433 ** Display scan stats.
3435 static void display_scanstats(
3436 sqlite3 *db, /* Database to query */
3437 ShellState *pArg /* Pointer to ShellState */
3439 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3440 UNUSED_PARAMETER(db);
3441 UNUSED_PARAMETER(pArg);
3442 #else
3443 if( pArg->scanstatsOn==3 ){
3444 const char *zSql =
3445 " SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
3446 " round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
3447 " FROM bytecode(?)";
3449 int rc = SQLITE_OK;
3450 sqlite3_stmt *pStmt = 0;
3451 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3452 if( rc==SQLITE_OK ){
3453 sqlite3_stmt *pSave = pArg->pStmt;
3454 pArg->pStmt = pStmt;
3455 sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
3457 pArg->cnt = 0;
3458 pArg->cMode = MODE_ScanExp;
3459 explain_data_prepare(pArg, pStmt);
3460 exec_prepared_stmt(pArg, pStmt);
3461 explain_data_delete(pArg);
3463 sqlite3_finalize(pStmt);
3464 pArg->pStmt = pSave;
3466 }else{
3467 display_explain_scanstats(db, pArg);
3469 #endif
3473 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3475 static unsigned int savedSelectTrace;
3476 static unsigned int savedWhereTrace;
3477 static void disable_debug_trace_modes(void){
3478 unsigned int zero = 0;
3479 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3480 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3481 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3482 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3484 static void restore_debug_trace_modes(void){
3485 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3486 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3489 /* Create the TEMP table used to store parameter bindings */
3490 static void bind_table_init(ShellState *p){
3491 int wrSchema = 0;
3492 int defensiveMode = 0;
3493 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3494 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3495 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3496 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3497 sqlite3_exec(p->db,
3498 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3499 " key TEXT PRIMARY KEY,\n"
3500 " value\n"
3501 ") WITHOUT ROWID;",
3502 0, 0, 0);
3503 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3504 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3508 ** Bind parameters on a prepared statement.
3510 ** Parameter bindings are taken from a TEMP table of the form:
3512 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3513 ** WITHOUT ROWID;
3515 ** No bindings occur if this table does not exist. The name of the table
3516 ** begins with "sqlite_" so that it will not collide with ordinary application
3517 ** tables. The table must be in the TEMP schema.
3519 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3520 int nVar;
3521 int i;
3522 int rc;
3523 sqlite3_stmt *pQ = 0;
3525 nVar = sqlite3_bind_parameter_count(pStmt);
3526 if( nVar==0 ) return; /* Nothing to do */
3527 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3528 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3529 rc = SQLITE_NOTFOUND;
3530 pQ = 0;
3531 }else{
3532 rc = sqlite3_prepare_v2(pArg->db,
3533 "SELECT value FROM temp.sqlite_parameters"
3534 " WHERE key=?1", -1, &pQ, 0);
3536 for(i=1; i<=nVar; i++){
3537 char zNum[30];
3538 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3539 if( zVar==0 ){
3540 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3541 zVar = zNum;
3543 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3544 if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
3545 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3546 #ifdef NAN
3547 }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
3548 sqlite3_bind_double(pStmt, i, NAN);
3549 #endif
3550 #ifdef INFINITY
3551 }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
3552 sqlite3_bind_double(pStmt, i, INFINITY);
3553 #endif
3554 }else{
3555 sqlite3_bind_null(pStmt, i);
3557 sqlite3_reset(pQ);
3559 sqlite3_finalize(pQ);
3563 ** UTF8 box-drawing characters. Imagine box lines like this:
3565 ** 1
3566 ** |
3567 ** 4 --+-- 2
3568 ** |
3569 ** 3
3571 ** Each box characters has between 2 and 4 of the lines leading from
3572 ** the center. The characters are here identified by the numbers of
3573 ** their corresponding lines.
3575 #define BOX_24 "\342\224\200" /* U+2500 --- */
3576 #define BOX_13 "\342\224\202" /* U+2502 | */
3577 #define BOX_23 "\342\224\214" /* U+250c ,- */
3578 #define BOX_34 "\342\224\220" /* U+2510 -, */
3579 #define BOX_12 "\342\224\224" /* U+2514 '- */
3580 #define BOX_14 "\342\224\230" /* U+2518 -' */
3581 #define BOX_123 "\342\224\234" /* U+251c |- */
3582 #define BOX_134 "\342\224\244" /* U+2524 -| */
3583 #define BOX_234 "\342\224\254" /* U+252c -,- */
3584 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3585 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3587 /* Draw horizontal line N characters long using unicode box
3588 ** characters
3590 static void print_box_line(int N){
3591 const char zDash[] =
3592 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3593 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3594 const int nDash = sizeof(zDash) - 1;
3595 N *= 3;
3596 while( N>nDash ){
3597 oputz(zDash);
3598 N -= nDash;
3600 oputf("%.*s", N, zDash);
3604 ** Draw a horizontal separator for a MODE_Box table.
3606 static void print_box_row_separator(
3607 ShellState *p,
3608 int nArg,
3609 const char *zSep1,
3610 const char *zSep2,
3611 const char *zSep3
3613 int i;
3614 if( nArg>0 ){
3615 oputz(zSep1);
3616 print_box_line(p->actualWidth[0]+2);
3617 for(i=1; i<nArg; i++){
3618 oputz(zSep2);
3619 print_box_line(p->actualWidth[i]+2);
3621 oputz(zSep3);
3623 oputz("\n");
3627 ** z[] is a line of text that is to be displayed the .mode box or table or
3628 ** similar tabular formats. z[] might contain control characters such
3629 ** as \n, \t, \f, or \r.
3631 ** Compute characters to display on the first line of z[]. Stop at the
3632 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3633 ** from malloc()) of that first line, which caller should free sometime.
3634 ** Write anything to display on the next line into *pzTail. If this is
3635 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3637 static char *translateForDisplayAndDup(
3638 const unsigned char *z, /* Input text to be transformed */
3639 const unsigned char **pzTail, /* OUT: Tail of the input for next line */
3640 int mxWidth, /* Max width. 0 means no limit */
3641 u8 bWordWrap /* If true, avoid breaking mid-word */
3643 int i; /* Input bytes consumed */
3644 int j; /* Output bytes generated */
3645 int k; /* Input bytes to be displayed */
3646 int n; /* Output column number */
3647 unsigned char *zOut; /* Output text */
3649 if( z==0 ){
3650 *pzTail = 0;
3651 return 0;
3653 if( mxWidth<0 ) mxWidth = -mxWidth;
3654 if( mxWidth==0 ) mxWidth = 1000000;
3655 i = j = n = 0;
3656 while( n<mxWidth ){
3657 if( z[i]>=' ' ){
3658 n++;
3659 do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3660 continue;
3662 if( z[i]=='\t' ){
3664 n++;
3665 j++;
3666 }while( (n&7)!=0 && n<mxWidth );
3667 i++;
3668 continue;
3670 break;
3672 if( n>=mxWidth && bWordWrap ){
3673 /* Perhaps try to back up to a better place to break the line */
3674 for(k=i; k>i/2; k--){
3675 if( isspace(z[k-1]) ) break;
3677 if( k<=i/2 ){
3678 for(k=i; k>i/2; k--){
3679 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3682 if( k<=i/2 ){
3683 k = i;
3684 }else{
3685 i = k;
3686 while( z[i]==' ' ) i++;
3688 }else{
3689 k = i;
3691 if( n>=mxWidth && z[i]>=' ' ){
3692 *pzTail = &z[i];
3693 }else if( z[i]=='\r' && z[i+1]=='\n' ){
3694 *pzTail = z[i+2] ? &z[i+2] : 0;
3695 }else if( z[i]==0 || z[i+1]==0 ){
3696 *pzTail = 0;
3697 }else{
3698 *pzTail = &z[i+1];
3700 zOut = malloc( j+1 );
3701 shell_check_oom(zOut);
3702 i = j = n = 0;
3703 while( i<k ){
3704 if( z[i]>=' ' ){
3705 n++;
3706 do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3707 continue;
3709 if( z[i]=='\t' ){
3711 n++;
3712 zOut[j++] = ' ';
3713 }while( (n&7)!=0 && n<mxWidth );
3714 i++;
3715 continue;
3717 break;
3719 zOut[j] = 0;
3720 return (char*)zOut;
3723 /* Extract the value of the i-th current column for pStmt as an SQL literal
3724 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3725 ** the caller.
3727 static char *quoted_column(sqlite3_stmt *pStmt, int i){
3728 switch( sqlite3_column_type(pStmt, i) ){
3729 case SQLITE_NULL: {
3730 return sqlite3_mprintf("NULL");
3732 case SQLITE_INTEGER:
3733 case SQLITE_FLOAT: {
3734 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3736 case SQLITE_TEXT: {
3737 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3739 case SQLITE_BLOB: {
3740 int j;
3741 sqlite3_str *pStr = sqlite3_str_new(0);
3742 const unsigned char *a = sqlite3_column_blob(pStmt,i);
3743 int n = sqlite3_column_bytes(pStmt,i);
3744 sqlite3_str_append(pStr, "x'", 2);
3745 for(j=0; j<n; j++){
3746 sqlite3_str_appendf(pStr, "%02x", a[j]);
3748 sqlite3_str_append(pStr, "'", 1);
3749 return sqlite3_str_finish(pStr);
3752 return 0; /* Not reached */
3756 ** Run a prepared statement and output the result in one of the
3757 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3758 ** or MODE_Box.
3760 ** This is different from ordinary exec_prepared_stmt() in that
3761 ** it has to run the entire query and gather the results into memory
3762 ** first, in order to determine column widths, before providing
3763 ** any output.
3765 static void exec_prepared_stmt_columnar(
3766 ShellState *p, /* Pointer to ShellState */
3767 sqlite3_stmt *pStmt /* Statement to run */
3769 sqlite3_int64 nRow = 0;
3770 int nColumn = 0;
3771 char **azData = 0;
3772 sqlite3_int64 nAlloc = 0;
3773 char *abRowDiv = 0;
3774 const unsigned char *uz;
3775 const char *z;
3776 char **azQuoted = 0;
3777 int rc;
3778 sqlite3_int64 i, nData;
3779 int j, nTotal, w, n;
3780 const char *colSep = 0;
3781 const char *rowSep = 0;
3782 const unsigned char **azNextLine = 0;
3783 int bNextLine = 0;
3784 int bMultiLineRowExists = 0;
3785 int bw = p->cmOpts.bWordWrap;
3786 const char *zEmpty = "";
3787 const char *zShowNull = p->nullValue;
3789 rc = sqlite3_step(pStmt);
3790 if( rc!=SQLITE_ROW ) return;
3791 nColumn = sqlite3_column_count(pStmt);
3792 if( nColumn==0 ) goto columnar_end;
3793 nAlloc = nColumn*4;
3794 if( nAlloc<=0 ) nAlloc = 1;
3795 azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3796 shell_check_oom(azData);
3797 azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3798 shell_check_oom(azNextLine);
3799 memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3800 if( p->cmOpts.bQuote ){
3801 azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3802 shell_check_oom(azQuoted);
3803 memset(azQuoted, 0, nColumn*sizeof(char*) );
3805 abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3806 shell_check_oom(abRowDiv);
3807 if( nColumn>p->nWidth ){
3808 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3809 shell_check_oom(p->colWidth);
3810 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3811 p->nWidth = nColumn;
3812 p->actualWidth = &p->colWidth[nColumn];
3814 memset(p->actualWidth, 0, nColumn*sizeof(int));
3815 for(i=0; i<nColumn; i++){
3816 w = p->colWidth[i];
3817 if( w<0 ) w = -w;
3818 p->actualWidth[i] = w;
3820 for(i=0; i<nColumn; i++){
3821 const unsigned char *zNotUsed;
3822 int wx = p->colWidth[i];
3823 if( wx==0 ){
3824 wx = p->cmOpts.iWrap;
3826 if( wx<0 ) wx = -wx;
3827 uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3828 if( uz==0 ) uz = (u8*)"";
3829 azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3832 int useNextLine = bNextLine;
3833 bNextLine = 0;
3834 if( (nRow+2)*nColumn >= nAlloc ){
3835 nAlloc *= 2;
3836 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3837 shell_check_oom(azData);
3838 abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3839 shell_check_oom(abRowDiv);
3841 abRowDiv[nRow] = 1;
3842 nRow++;
3843 for(i=0; i<nColumn; i++){
3844 int wx = p->colWidth[i];
3845 if( wx==0 ){
3846 wx = p->cmOpts.iWrap;
3848 if( wx<0 ) wx = -wx;
3849 if( useNextLine ){
3850 uz = azNextLine[i];
3851 if( uz==0 ) uz = (u8*)zEmpty;
3852 }else if( p->cmOpts.bQuote ){
3853 sqlite3_free(azQuoted[i]);
3854 azQuoted[i] = quoted_column(pStmt,i);
3855 uz = (const unsigned char*)azQuoted[i];
3856 }else{
3857 uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3858 if( uz==0 ) uz = (u8*)zShowNull;
3860 azData[nRow*nColumn + i]
3861 = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3862 if( azNextLine[i] ){
3863 bNextLine = 1;
3864 abRowDiv[nRow-1] = 0;
3865 bMultiLineRowExists = 1;
3868 }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3869 nTotal = nColumn*(nRow+1);
3870 for(i=0; i<nTotal; i++){
3871 z = azData[i];
3872 if( z==0 ) z = (char*)zEmpty;
3873 n = strlenChar(z);
3874 j = i%nColumn;
3875 if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3877 if( seenInterrupt ) goto columnar_end;
3878 switch( p->cMode ){
3879 case MODE_Column: {
3880 colSep = " ";
3881 rowSep = "\n";
3882 if( p->showHeader ){
3883 for(i=0; i<nColumn; i++){
3884 w = p->actualWidth[i];
3885 if( p->colWidth[i]<0 ) w = -w;
3886 utf8_width_print(w, azData[i]);
3887 fputs(i==nColumn-1?"\n":" ", p->out);
3889 for(i=0; i<nColumn; i++){
3890 print_dashes(p->actualWidth[i]);
3891 fputs(i==nColumn-1?"\n":" ", p->out);
3894 break;
3896 case MODE_Table: {
3897 colSep = " | ";
3898 rowSep = " |\n";
3899 print_row_separator(p, nColumn, "+");
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_Markdown: {
3911 colSep = " | ";
3912 rowSep = " |\n";
3913 fputs("| ", p->out);
3914 for(i=0; i<nColumn; i++){
3915 w = p->actualWidth[i];
3916 n = strlenChar(azData[i]);
3917 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3918 oputz(i==nColumn-1?" |\n":" | ");
3920 print_row_separator(p, nColumn, "|");
3921 break;
3923 case MODE_Box: {
3924 colSep = " " BOX_13 " ";
3925 rowSep = " " BOX_13 "\n";
3926 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3927 oputz(BOX_13 " ");
3928 for(i=0; i<nColumn; i++){
3929 w = p->actualWidth[i];
3930 n = strlenChar(azData[i]);
3931 oputf("%*s%s%*s%s",
3932 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3933 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3935 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3936 break;
3939 for(i=nColumn, j=0; i<nTotal; i++, j++){
3940 if( j==0 && p->cMode!=MODE_Column ){
3941 oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
3943 z = azData[i];
3944 if( z==0 ) z = p->nullValue;
3945 w = p->actualWidth[j];
3946 if( p->colWidth[j]<0 ) w = -w;
3947 utf8_width_print(w, z);
3948 if( j==nColumn-1 ){
3949 oputz(rowSep);
3950 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3951 if( p->cMode==MODE_Table ){
3952 print_row_separator(p, nColumn, "+");
3953 }else if( p->cMode==MODE_Box ){
3954 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3955 }else if( p->cMode==MODE_Column ){
3956 oputz("\n");
3959 j = -1;
3960 if( seenInterrupt ) goto columnar_end;
3961 }else{
3962 oputz(colSep);
3965 if( p->cMode==MODE_Table ){
3966 print_row_separator(p, nColumn, "+");
3967 }else if( p->cMode==MODE_Box ){
3968 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3970 columnar_end:
3971 if( seenInterrupt ){
3972 oputz("Interrupt\n");
3974 nData = (nRow+1)*nColumn;
3975 for(i=0; i<nData; i++){
3976 z = azData[i];
3977 if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3979 sqlite3_free(azData);
3980 sqlite3_free((void*)azNextLine);
3981 sqlite3_free(abRowDiv);
3982 if( azQuoted ){
3983 for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3984 sqlite3_free(azQuoted);
3989 ** Run a prepared statement
3991 static void exec_prepared_stmt(
3992 ShellState *pArg, /* Pointer to ShellState */
3993 sqlite3_stmt *pStmt /* Statement to run */
3995 int rc;
3996 sqlite3_uint64 nRow = 0;
3998 if( pArg->cMode==MODE_Column
3999 || pArg->cMode==MODE_Table
4000 || pArg->cMode==MODE_Box
4001 || pArg->cMode==MODE_Markdown
4003 exec_prepared_stmt_columnar(pArg, pStmt);
4004 return;
4007 /* perform the first step. this will tell us if we
4008 ** have a result set or not and how wide it is.
4010 rc = sqlite3_step(pStmt);
4011 /* if we have a result set... */
4012 if( SQLITE_ROW == rc ){
4013 /* allocate space for col name ptr, value ptr, and type */
4014 int nCol = sqlite3_column_count(pStmt);
4015 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
4016 if( !pData ){
4017 shell_out_of_memory();
4018 }else{
4019 char **azCols = (char **)pData; /* Names of result columns */
4020 char **azVals = &azCols[nCol]; /* Results */
4021 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
4022 int i, x;
4023 assert(sizeof(int) <= sizeof(char *));
4024 /* save off ptrs to column names */
4025 for(i=0; i<nCol; i++){
4026 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
4029 nRow++;
4030 /* extract the data and data types */
4031 for(i=0; i<nCol; i++){
4032 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
4033 if( x==SQLITE_BLOB
4034 && pArg
4035 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
4037 azVals[i] = "";
4038 }else{
4039 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
4041 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
4042 rc = SQLITE_NOMEM;
4043 break; /* from for */
4045 } /* end for */
4047 /* if data and types extracted successfully... */
4048 if( SQLITE_ROW == rc ){
4049 /* call the supplied callback with the result row data */
4050 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
4051 rc = SQLITE_ABORT;
4052 }else{
4053 rc = sqlite3_step(pStmt);
4056 } while( SQLITE_ROW == rc );
4057 sqlite3_free(pData);
4058 if( pArg->cMode==MODE_Json ){
4059 fputs("]\n", pArg->out);
4060 }else if( pArg->cMode==MODE_Count ){
4061 char zBuf[200];
4062 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
4063 nRow, nRow!=1 ? "s" : "");
4064 printf("%s", zBuf);
4070 #ifndef SQLITE_OMIT_VIRTUALTABLE
4072 ** This function is called to process SQL if the previous shell command
4073 ** was ".expert". It passes the SQL in the second argument directly to
4074 ** the sqlite3expert object.
4076 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4077 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4078 ** an English language error message. It is the responsibility of the
4079 ** caller to eventually free this buffer using sqlite3_free().
4081 static int expertHandleSQL(
4082 ShellState *pState,
4083 const char *zSql,
4084 char **pzErr
4086 assert( pState->expert.pExpert );
4087 assert( pzErr==0 || *pzErr==0 );
4088 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
4092 ** This function is called either to silently clean up the object
4093 ** created by the ".expert" command (if bCancel==1), or to generate a
4094 ** report from it and then clean it up (if bCancel==0).
4096 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4097 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4098 ** an English language error message. It is the responsibility of the
4099 ** caller to eventually free this buffer using sqlite3_free().
4101 static int expertFinish(
4102 ShellState *pState,
4103 int bCancel,
4104 char **pzErr
4106 int rc = SQLITE_OK;
4107 sqlite3expert *p = pState->expert.pExpert;
4108 assert( p );
4109 assert( bCancel || pzErr==0 || *pzErr==0 );
4110 if( bCancel==0 ){
4111 int bVerbose = pState->expert.bVerbose;
4113 rc = sqlite3_expert_analyze(p, pzErr);
4114 if( rc==SQLITE_OK ){
4115 int nQuery = sqlite3_expert_count(p);
4116 int i;
4118 if( bVerbose ){
4119 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
4120 oputz("-- Candidates -----------------------------\n");
4121 oputf("%s\n", zCand);
4123 for(i=0; i<nQuery; i++){
4124 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
4125 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
4126 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
4127 if( zIdx==0 ) zIdx = "(no new indexes)\n";
4128 if( bVerbose ){
4129 oputf("-- Query %d --------------------------------\n",i+1);
4130 oputf("%s\n\n", zSql);
4132 oputf("%s\n", zIdx);
4133 oputf("%s\n", zEQP);
4137 sqlite3_expert_destroy(p);
4138 pState->expert.pExpert = 0;
4139 return rc;
4143 ** Implementation of ".expert" dot command.
4145 static int expertDotCommand(
4146 ShellState *pState, /* Current shell tool state */
4147 char **azArg, /* Array of arguments passed to dot command */
4148 int nArg /* Number of entries in azArg[] */
4150 int rc = SQLITE_OK;
4151 char *zErr = 0;
4152 int i;
4153 int iSample = 0;
4155 assert( pState->expert.pExpert==0 );
4156 memset(&pState->expert, 0, sizeof(ExpertInfo));
4158 for(i=1; rc==SQLITE_OK && i<nArg; i++){
4159 char *z = azArg[i];
4160 int n;
4161 if( z[0]=='-' && z[1]=='-' ) z++;
4162 n = strlen30(z);
4163 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
4164 pState->expert.bVerbose = 1;
4166 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
4167 if( i==(nArg-1) ){
4168 eputf("option requires an argument: %s\n", z);
4169 rc = SQLITE_ERROR;
4170 }else{
4171 iSample = (int)integerValue(azArg[++i]);
4172 if( iSample<0 || iSample>100 ){
4173 eputf("value out of range: %s\n", azArg[i]);
4174 rc = SQLITE_ERROR;
4178 else{
4179 eputf("unknown option: %s\n", z);
4180 rc = SQLITE_ERROR;
4184 if( rc==SQLITE_OK ){
4185 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
4186 if( pState->expert.pExpert==0 ){
4187 eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
4188 rc = SQLITE_ERROR;
4189 }else{
4190 sqlite3_expert_config(
4191 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
4195 sqlite3_free(zErr);
4197 return rc;
4199 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4202 ** Execute a statement or set of statements. Print
4203 ** any result rows/columns depending on the current mode
4204 ** set via the supplied callback.
4206 ** This is very similar to SQLite's built-in sqlite3_exec()
4207 ** function except it takes a slightly different callback
4208 ** and callback data argument.
4210 static int shell_exec(
4211 ShellState *pArg, /* Pointer to ShellState */
4212 const char *zSql, /* SQL to be evaluated */
4213 char **pzErrMsg /* Error msg written here */
4215 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
4216 int rc = SQLITE_OK; /* Return Code */
4217 int rc2;
4218 const char *zLeftover; /* Tail of unprocessed SQL */
4219 sqlite3 *db = pArg->db;
4221 if( pzErrMsg ){
4222 *pzErrMsg = NULL;
4225 #ifndef SQLITE_OMIT_VIRTUALTABLE
4226 if( pArg->expert.pExpert ){
4227 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
4228 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
4230 #endif
4232 while( zSql[0] && (SQLITE_OK == rc) ){
4233 static const char *zStmtSql;
4234 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
4235 if( SQLITE_OK != rc ){
4236 if( pzErrMsg ){
4237 *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
4239 }else{
4240 if( !pStmt ){
4241 /* this happens for a comment or white-space */
4242 zSql = zLeftover;
4243 while( IsSpace(zSql[0]) ) zSql++;
4244 continue;
4246 zStmtSql = sqlite3_sql(pStmt);
4247 if( zStmtSql==0 ) zStmtSql = "";
4248 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
4250 /* save off the prepared statement handle and reset row count */
4251 if( pArg ){
4252 pArg->pStmt = pStmt;
4253 pArg->cnt = 0;
4256 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4257 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
4258 sqlite3_stmt *pExplain;
4259 int triggerEQP = 0;
4260 disable_debug_trace_modes();
4261 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
4262 if( pArg->autoEQP>=AUTOEQP_trigger ){
4263 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
4265 pExplain = pStmt;
4266 sqlite3_reset(pExplain);
4267 rc = sqlite3_stmt_explain(pExplain, 2);
4268 if( rc==SQLITE_OK ){
4269 while( sqlite3_step(pExplain)==SQLITE_ROW ){
4270 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
4271 int iEqpId = sqlite3_column_int(pExplain, 0);
4272 int iParentId = sqlite3_column_int(pExplain, 1);
4273 if( zEQPLine==0 ) zEQPLine = "";
4274 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
4275 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
4277 eqp_render(pArg, 0);
4279 if( pArg->autoEQP>=AUTOEQP_full ){
4280 /* Also do an EXPLAIN for ".eqp full" mode */
4281 sqlite3_reset(pExplain);
4282 rc = sqlite3_stmt_explain(pExplain, 1);
4283 if( rc==SQLITE_OK ){
4284 pArg->cMode = MODE_Explain;
4285 assert( sqlite3_stmt_isexplain(pExplain)==1 );
4286 explain_data_prepare(pArg, pExplain);
4287 exec_prepared_stmt(pArg, pExplain);
4288 explain_data_delete(pArg);
4291 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
4292 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
4294 sqlite3_reset(pStmt);
4295 sqlite3_stmt_explain(pStmt, 0);
4296 restore_debug_trace_modes();
4299 if( pArg ){
4300 int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
4301 pArg->cMode = pArg->mode;
4302 if( pArg->autoExplain ){
4303 if( bIsExplain ){
4304 pArg->cMode = MODE_Explain;
4306 if( sqlite3_stmt_isexplain(pStmt)==2 ){
4307 pArg->cMode = MODE_EQP;
4311 /* If the shell is currently in ".explain" mode, gather the extra
4312 ** data required to add indents to the output.*/
4313 if( pArg->cMode==MODE_Explain && bIsExplain ){
4314 explain_data_prepare(pArg, pStmt);
4318 bind_prepared_stmt(pArg, pStmt);
4319 exec_prepared_stmt(pArg, pStmt);
4320 explain_data_delete(pArg);
4321 eqp_render(pArg, 0);
4323 /* print usage stats if stats on */
4324 if( pArg && pArg->statsOn ){
4325 display_stats(db, pArg, 0);
4328 /* print loop-counters if required */
4329 if( pArg && pArg->scanstatsOn ){
4330 display_scanstats(db, pArg);
4333 /* Finalize the statement just executed. If this fails, save a
4334 ** copy of the error message. Otherwise, set zSql to point to the
4335 ** next statement to execute. */
4336 rc2 = sqlite3_finalize(pStmt);
4337 if( rc!=SQLITE_NOMEM ) rc = rc2;
4338 if( rc==SQLITE_OK ){
4339 zSql = zLeftover;
4340 while( IsSpace(zSql[0]) ) zSql++;
4341 }else if( pzErrMsg ){
4342 *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
4345 /* clear saved stmt handle */
4346 if( pArg ){
4347 pArg->pStmt = NULL;
4350 } /* end while */
4352 return rc;
4356 ** Release memory previously allocated by tableColumnList().
4358 static void freeColumnList(char **azCol){
4359 int i;
4360 for(i=1; azCol[i]; i++){
4361 sqlite3_free(azCol[i]);
4363 /* azCol[0] is a static string */
4364 sqlite3_free(azCol);
4368 ** Return a list of pointers to strings which are the names of all
4369 ** columns in table zTab. The memory to hold the names is dynamically
4370 ** allocated and must be released by the caller using a subsequent call
4371 ** to freeColumnList().
4373 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4374 ** value that needs to be preserved, then azCol[0] is filled in with the
4375 ** name of the rowid column.
4377 ** The first regular column in the table is azCol[1]. The list is terminated
4378 ** by an entry with azCol[i]==0.
4380 static char **tableColumnList(ShellState *p, const char *zTab){
4381 char **azCol = 0;
4382 sqlite3_stmt *pStmt;
4383 char *zSql;
4384 int nCol = 0;
4385 int nAlloc = 0;
4386 int nPK = 0; /* Number of PRIMARY KEY columns seen */
4387 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
4388 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4389 int rc;
4391 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4392 shell_check_oom(zSql);
4393 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4394 sqlite3_free(zSql);
4395 if( rc ) return 0;
4396 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4397 if( nCol>=nAlloc-2 ){
4398 nAlloc = nAlloc*2 + nCol + 10;
4399 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4400 shell_check_oom(azCol);
4402 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4403 shell_check_oom(azCol[nCol]);
4404 if( sqlite3_column_int(pStmt, 5) ){
4405 nPK++;
4406 if( nPK==1
4407 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4408 "INTEGER")==0
4410 isIPK = 1;
4411 }else{
4412 isIPK = 0;
4416 sqlite3_finalize(pStmt);
4417 if( azCol==0 ) return 0;
4418 azCol[0] = 0;
4419 azCol[nCol+1] = 0;
4421 /* The decision of whether or not a rowid really needs to be preserved
4422 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4423 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4424 ** rowids on tables where the rowid is inaccessible because there are other
4425 ** columns in the table named "rowid", "_rowid_", and "oid".
4427 if( preserveRowid && isIPK ){
4428 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4429 ** might be an alias for the ROWID. But it might also be a WITHOUT ROWID
4430 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4431 ** ROWID aliases. To distinguish these cases, check to see if
4432 ** there is a "pk" entry in "PRAGMA index_list". There will be
4433 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4435 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4436 " WHERE origin='pk'", zTab);
4437 shell_check_oom(zSql);
4438 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4439 sqlite3_free(zSql);
4440 if( rc ){
4441 freeColumnList(azCol);
4442 return 0;
4444 rc = sqlite3_step(pStmt);
4445 sqlite3_finalize(pStmt);
4446 preserveRowid = rc==SQLITE_ROW;
4448 if( preserveRowid ){
4449 /* Only preserve the rowid if we can find a name to use for the
4450 ** rowid */
4451 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4452 int i, j;
4453 for(j=0; j<3; j++){
4454 for(i=1; i<=nCol; i++){
4455 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4457 if( i>nCol ){
4458 /* At this point, we know that azRowid[j] is not the name of any
4459 ** ordinary column in the table. Verify that azRowid[j] is a valid
4460 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4461 ** tables will fail this last check */
4462 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4463 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4464 break;
4468 return azCol;
4472 ** Toggle the reverse_unordered_selects setting.
4474 static void toggleSelectOrder(sqlite3 *db){
4475 sqlite3_stmt *pStmt = 0;
4476 int iSetting = 0;
4477 char zStmt[100];
4478 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4479 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4480 iSetting = sqlite3_column_int(pStmt, 0);
4482 sqlite3_finalize(pStmt);
4483 sqlite3_snprintf(sizeof(zStmt), zStmt,
4484 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4485 sqlite3_exec(db, zStmt, 0, 0, 0);
4489 ** This is a different callback routine used for dumping the database.
4490 ** Each row received by this callback consists of a table name,
4491 ** the table type ("index" or "table") and SQL to create the table.
4492 ** This routine should print text sufficient to recreate the table.
4494 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4495 int rc;
4496 const char *zTable;
4497 const char *zType;
4498 const char *zSql;
4499 ShellState *p = (ShellState *)pArg;
4500 int dataOnly;
4501 int noSys;
4503 UNUSED_PARAMETER(azNotUsed);
4504 if( nArg!=3 || azArg==0 ) return 0;
4505 zTable = azArg[0];
4506 zType = azArg[1];
4507 zSql = azArg[2];
4508 if( zTable==0 ) return 0;
4509 if( zType==0 ) return 0;
4510 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4511 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4513 if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4514 if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
4515 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4516 if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
4517 }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
4518 return 0;
4519 }else if( dataOnly ){
4520 /* no-op */
4521 }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4522 char *zIns;
4523 if( !p->writableSchema ){
4524 oputz("PRAGMA writable_schema=ON;\n");
4525 p->writableSchema = 1;
4527 zIns = sqlite3_mprintf(
4528 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4529 "VALUES('table','%q','%q',0,'%q');",
4530 zTable, zTable, zSql);
4531 shell_check_oom(zIns);
4532 oputf("%s\n", zIns);
4533 sqlite3_free(zIns);
4534 return 0;
4535 }else{
4536 printSchemaLine(zSql, ";\n");
4539 if( cli_strcmp(zType, "table")==0 ){
4540 ShellText sSelect;
4541 ShellText sTable;
4542 char **azCol;
4543 int i;
4544 char *savedDestTable;
4545 int savedMode;
4547 azCol = tableColumnList(p, zTable);
4548 if( azCol==0 ){
4549 p->nErr++;
4550 return 0;
4553 /* Always quote the table name, even if it appears to be pure ascii,
4554 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4555 initText(&sTable);
4556 appendText(&sTable, zTable, quoteChar(zTable));
4557 /* If preserving the rowid, add a column list after the table name.
4558 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4559 ** instead of the usual "INSERT INTO tab VALUES(...)".
4561 if( azCol[0] ){
4562 appendText(&sTable, "(", 0);
4563 appendText(&sTable, azCol[0], 0);
4564 for(i=1; azCol[i]; i++){
4565 appendText(&sTable, ",", 0);
4566 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4568 appendText(&sTable, ")", 0);
4571 /* Build an appropriate SELECT statement */
4572 initText(&sSelect);
4573 appendText(&sSelect, "SELECT ", 0);
4574 if( azCol[0] ){
4575 appendText(&sSelect, azCol[0], 0);
4576 appendText(&sSelect, ",", 0);
4578 for(i=1; azCol[i]; i++){
4579 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4580 if( azCol[i+1] ){
4581 appendText(&sSelect, ",", 0);
4584 freeColumnList(azCol);
4585 appendText(&sSelect, " FROM ", 0);
4586 appendText(&sSelect, zTable, quoteChar(zTable));
4588 savedDestTable = p->zDestTable;
4589 savedMode = p->mode;
4590 p->zDestTable = sTable.z;
4591 p->mode = p->cMode = MODE_Insert;
4592 rc = shell_exec(p, sSelect.z, 0);
4593 if( (rc&0xff)==SQLITE_CORRUPT ){
4594 oputz("/****** CORRUPTION ERROR *******/\n");
4595 toggleSelectOrder(p->db);
4596 shell_exec(p, sSelect.z, 0);
4597 toggleSelectOrder(p->db);
4599 p->zDestTable = savedDestTable;
4600 p->mode = savedMode;
4601 freeText(&sTable);
4602 freeText(&sSelect);
4603 if( rc ) p->nErr++;
4605 return 0;
4609 ** Run zQuery. Use dump_callback() as the callback routine so that
4610 ** the contents of the query are output as SQL statements.
4612 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4613 ** "ORDER BY rowid DESC" to the end.
4615 static int run_schema_dump_query(
4616 ShellState *p,
4617 const char *zQuery
4619 int rc;
4620 char *zErr = 0;
4621 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4622 if( rc==SQLITE_CORRUPT ){
4623 char *zQ2;
4624 int len = strlen30(zQuery);
4625 oputz("/****** CORRUPTION ERROR *******/\n");
4626 if( zErr ){
4627 oputf("/****** %s ******/\n", zErr);
4628 sqlite3_free(zErr);
4629 zErr = 0;
4631 zQ2 = malloc( len+100 );
4632 if( zQ2==0 ) return rc;
4633 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4634 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4635 if( rc ){
4636 oputf("/****** ERROR: %s ******/\n", zErr);
4637 }else{
4638 rc = SQLITE_CORRUPT;
4640 sqlite3_free(zErr);
4641 free(zQ2);
4643 return rc;
4647 ** Text of help messages.
4649 ** The help text for each individual command begins with a line that starts
4650 ** with ".". Subsequent lines are supplemental information.
4652 ** There must be two or more spaces between the end of the command and the
4653 ** start of the description of what that command does.
4655 static const char *(azHelp[]) = {
4656 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4657 && !defined(SQLITE_SHELL_FIDDLE)
4658 ".archive ... Manage SQL archives",
4659 " Each command must have exactly one of the following options:",
4660 " -c, --create Create a new archive",
4661 " -u, --update Add or update files with changed mtime",
4662 " -i, --insert Like -u but always add even if unchanged",
4663 " -r, --remove Remove files from archive",
4664 " -t, --list List contents of archive",
4665 " -x, --extract Extract files from archive",
4666 " Optional arguments:",
4667 " -v, --verbose Print each filename as it is processed",
4668 " -f FILE, --file FILE Use archive FILE (default is current db)",
4669 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4670 " -C DIR, --directory DIR Read/extract files from directory DIR",
4671 " -g, --glob Use glob matching for names in archive",
4672 " -n, --dryrun Show the SQL that would have occurred",
4673 " Examples:",
4674 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4675 " .ar -tf ARCHIVE # List members of ARCHIVE",
4676 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4677 " See also:",
4678 " http://sqlite.org/cli.html#sqlite_archive_support",
4679 #endif
4680 #ifndef SQLITE_OMIT_AUTHORIZATION
4681 ".auth ON|OFF Show authorizer callbacks",
4682 #endif
4683 #ifndef SQLITE_SHELL_FIDDLE
4684 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4685 " Options:",
4686 " --append Use the appendvfs",
4687 " --async Write to FILE without journal and fsync()",
4688 #endif
4689 ".bail on|off Stop after hitting an error. Default OFF",
4690 #ifndef SQLITE_SHELL_FIDDLE
4691 ".cd DIRECTORY Change the working directory to DIRECTORY",
4692 #endif
4693 ".changes on|off Show number of rows changed by SQL",
4694 #ifndef SQLITE_SHELL_FIDDLE
4695 ".check GLOB Fail if output since .testcase does not match",
4696 ".clone NEWDB Clone data into NEWDB from the existing database",
4697 #endif
4698 ".connection [close] [#] Open or close an auxiliary database connection",
4699 #if defined(_WIN32) || defined(WIN32)
4700 ".crnl on|off Translate \\n to \\r\\n. Default ON",
4701 #endif
4702 ".databases List names and files of attached databases",
4703 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4704 #if SQLITE_SHELL_HAVE_RECOVER
4705 ".dbinfo ?DB? Show status information about the database",
4706 #endif
4707 ".dump ?OBJECTS? Render database content as SQL",
4708 " Options:",
4709 " --data-only Output only INSERT statements",
4710 " --newlines Allow unescaped newline characters in output",
4711 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4712 " --preserve-rowids Include ROWID values in the output",
4713 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4714 " Additional LIKE patterns can be given in subsequent arguments",
4715 ".echo on|off Turn command echo on or off",
4716 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4717 " Other Modes:",
4718 #ifdef SQLITE_DEBUG
4719 " test Show raw EXPLAIN QUERY PLAN output",
4720 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4721 #endif
4722 " trigger Like \"full\" but also show trigger bytecode",
4723 #ifndef SQLITE_SHELL_FIDDLE
4724 ".excel Display the output of next command in spreadsheet",
4725 " --bom Put a UTF8 byte-order mark on intermediate file",
4726 #endif
4727 #ifndef SQLITE_SHELL_FIDDLE
4728 ".exit ?CODE? Exit this program with return-code CODE",
4729 #endif
4730 ".expert EXPERIMENTAL. Suggest indexes for queries",
4731 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4732 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4733 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4734 " --help Show CMD details",
4735 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4736 ".headers on|off Turn display of headers on or off",
4737 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4738 #ifndef SQLITE_SHELL_FIDDLE
4739 ".import FILE TABLE Import data from FILE into TABLE",
4740 " Options:",
4741 " --ascii Use \\037 and \\036 as column and row separators",
4742 " --csv Use , and \\n as column and row separators",
4743 " --skip N Skip the first N rows of input",
4744 " --schema S Target table to be S.TABLE",
4745 " -v \"Verbose\" - increase auxiliary output",
4746 " Notes:",
4747 " * If TABLE does not exist, it is created. The first row of input",
4748 " determines the column names.",
4749 " * If neither --csv or --ascii are used, the input mode is derived",
4750 " from the \".mode\" output mode",
4751 " * If FILE begins with \"|\" then it is a command that generates the",
4752 " input text.",
4753 #endif
4754 #ifndef SQLITE_OMIT_TEST_CONTROL
4755 ",imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4756 #endif
4757 ".indexes ?TABLE? Show names of indexes",
4758 " If TABLE is specified, only show indexes for",
4759 " tables matching TABLE using the LIKE operator.",
4760 ".intck ?STEPS_PER_UNLOCK? Run an incremental integrity check on the db",
4761 #ifdef SQLITE_ENABLE_IOTRACE
4762 ",iotrace FILE Enable I/O diagnostic logging to FILE",
4763 #endif
4764 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4765 ".lint OPTIONS Report potential schema issues.",
4766 " Options:",
4767 " fkey-indexes Find missing foreign key indexes",
4768 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4769 ".load FILE ?ENTRY? Load an extension library",
4770 #endif
4771 #if !defined(SQLITE_SHELL_FIDDLE)
4772 ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout",
4773 #else
4774 ".log on|off Turn logging on or off.",
4775 #endif
4776 ".mode MODE ?OPTIONS? Set output mode",
4777 " MODE is one of:",
4778 " ascii Columns/rows delimited by 0x1F and 0x1E",
4779 " box Tables using unicode box-drawing characters",
4780 " csv Comma-separated values",
4781 " column Output in columns. (See .width)",
4782 " html HTML <table> code",
4783 " insert SQL insert statements for TABLE",
4784 " json Results in a JSON array",
4785 " line One value per line",
4786 " list Values delimited by \"|\"",
4787 " markdown Markdown table format",
4788 " qbox Shorthand for \"box --wrap 60 --quote\"",
4789 " quote Escape answers as for SQL",
4790 " table ASCII-art table",
4791 " tabs Tab-separated values",
4792 " tcl TCL list elements",
4793 " OPTIONS: (for columnar modes or insert mode):",
4794 " --wrap N Wrap output lines to no longer than N characters",
4795 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4796 " --ww Shorthand for \"--wordwrap 1\"",
4797 " --quote Quote output text as SQL literals",
4798 " --noquote Do not quote output text",
4799 " TABLE The name of SQL table used for \"insert\" mode",
4800 #ifndef SQLITE_SHELL_FIDDLE
4801 ".nonce STRING Suspend safe mode for one command if nonce matches",
4802 #endif
4803 ".nullvalue STRING Use STRING in place of NULL values",
4804 #ifndef SQLITE_SHELL_FIDDLE
4805 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4806 " If FILE begins with '|' then open as a pipe",
4807 " --bom Put a UTF8 byte-order mark at the beginning",
4808 " -e Send output to the system text editor",
4809 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4810 /* Note that .open is (partially) available in WASM builds but is
4811 ** currently only intended to be used by the fiddle tool, not
4812 ** end users, so is "undocumented." */
4813 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4814 " Options:",
4815 " --append Use appendvfs to append database to the end of FILE",
4816 #endif
4817 #ifndef SQLITE_OMIT_DESERIALIZE
4818 " --deserialize Load into memory using sqlite3_deserialize()",
4819 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4820 " --maxsize N Maximum size for --hexdb or --deserialized database",
4821 #endif
4822 " --new Initialize FILE to an empty database",
4823 " --nofollow Do not follow symbolic links",
4824 " --readonly Open FILE readonly",
4825 " --zip FILE is a ZIP archive",
4826 #ifndef SQLITE_SHELL_FIDDLE
4827 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4828 " If FILE begins with '|' then open it as a pipe.",
4829 " Options:",
4830 " --bom Prefix output with a UTF8 byte-order mark",
4831 " -e Send output to the system text editor",
4832 " -x Send output as CSV to a spreadsheet",
4833 #endif
4834 ".parameter CMD ... Manage SQL parameter bindings",
4835 " clear Erase all bindings",
4836 " init Initialize the TEMP table that holds bindings",
4837 " list List the current parameter bindings",
4838 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4839 " PARAMETER should start with one of: $ : @ ?",
4840 " unset PARAMETER Remove PARAMETER from the binding table",
4841 ".print STRING... Print literal STRING",
4842 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4843 ".progress N Invoke progress handler after every N opcodes",
4844 " --limit N Interrupt after N progress callbacks",
4845 " --once Do no more than one progress interrupt",
4846 " --quiet|-q No output except at interrupts",
4847 " --reset Reset the count for each input and interrupt",
4848 #endif
4849 ".prompt MAIN CONTINUE Replace the standard prompts",
4850 #ifndef SQLITE_SHELL_FIDDLE
4851 ".quit Stop interpreting input stream, exit if primary.",
4852 ".read FILE Read input from FILE or command output",
4853 " If FILE begins with \"|\", it is a command that generates the input.",
4854 #endif
4855 #if SQLITE_SHELL_HAVE_RECOVER
4856 ".recover Recover as much data as possible from corrupt db.",
4857 " --ignore-freelist Ignore pages that appear to be on db freelist",
4858 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4859 " --no-rowids Do not attempt to recover rowid values",
4860 " that are not also INTEGER PRIMARY KEYs",
4861 #endif
4862 #ifndef SQLITE_SHELL_FIDDLE
4863 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4864 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4865 #endif
4866 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4867 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4868 " Options:",
4869 " --indent Try to pretty-print the schema",
4870 " --nosys Omit objects whose names start with \"sqlite_\"",
4871 ",selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4872 " Options:",
4873 " --init Create a new SELFTEST table",
4874 " -v Verbose output",
4875 ".separator COL ?ROW? Change the column and row separators",
4876 #if defined(SQLITE_ENABLE_SESSION)
4877 ".session ?NAME? CMD ... Create or control sessions",
4878 " Subcommands:",
4879 " attach TABLE Attach TABLE",
4880 " changeset FILE Write a changeset into FILE",
4881 " close Close one session",
4882 " enable ?BOOLEAN? Set or query the enable bit",
4883 " filter GLOB... Reject tables matching GLOBs",
4884 " indirect ?BOOLEAN? Mark or query the indirect status",
4885 " isempty Query whether the session is empty",
4886 " list List currently open session names",
4887 " open DB NAME Open a new session on DB",
4888 " patchset FILE Write a patchset into FILE",
4889 " If ?NAME? is omitted, the first defined session is used.",
4890 #endif
4891 ".sha3sum ... Compute a SHA3 hash of database content",
4892 " Options:",
4893 " --schema Also hash the sqlite_schema table",
4894 " --sha3-224 Use the sha3-224 algorithm",
4895 " --sha3-256 Use the sha3-256 algorithm (default)",
4896 " --sha3-384 Use the sha3-384 algorithm",
4897 " --sha3-512 Use the sha3-512 algorithm",
4898 " Any other argument is a LIKE pattern for tables to hash",
4899 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4900 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4901 #endif
4902 ".show Show the current values for various settings",
4903 ".stats ?ARG? Show stats or turn stats on or off",
4904 " off Turn off automatic stat display",
4905 " on Turn on automatic stat display",
4906 " stmt Show statement stats",
4907 " vmstep Show the virtual machine step count only",
4908 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4909 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4910 #endif
4911 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4912 #ifndef SQLITE_SHELL_FIDDLE
4913 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
4914 #endif
4915 ",testctrl CMD ... Run various sqlite3_test_control() operations",
4916 " Run \".testctrl\" with no arguments for details",
4917 ".timeout MS Try opening locked tables for MS milliseconds",
4918 ".timer on|off Turn SQL timer on or off",
4919 #ifndef SQLITE_OMIT_TRACE
4920 ".trace ?OPTIONS? Output each SQL statement as it is run",
4921 " FILE Send output to FILE",
4922 " stdout Send output to stdout",
4923 " stderr Send output to stderr",
4924 " off Disable tracing",
4925 " --expanded Expand query parameters",
4926 #ifdef SQLITE_ENABLE_NORMALIZE
4927 " --normalized Normal the SQL statements",
4928 #endif
4929 " --plain Show SQL as it is input",
4930 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4931 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4932 " --row Trace each row (SQLITE_TRACE_ROW)",
4933 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4934 #endif /* SQLITE_OMIT_TRACE */
4935 #ifdef SQLITE_DEBUG
4936 ".unmodule NAME ... Unregister virtual table modules",
4937 " --allexcept Unregister everything except those named",
4938 #endif
4939 ".version Show source, library and compiler versions",
4940 ".vfsinfo ?AUX? Information about the top-level VFS",
4941 ".vfslist List all available VFSes",
4942 ".vfsname ?AUX? Print the name of the VFS stack",
4943 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4944 " Negative values right-justify",
4948 ** Output help text.
4950 ** zPattern describes the set of commands for which help text is provided.
4951 ** If zPattern is NULL, then show all commands, but only give a one-line
4952 ** description of each.
4954 ** Return the number of matches.
4956 static int showHelp(FILE *out, const char *zPattern){
4957 int i = 0;
4958 int j = 0;
4959 int n = 0;
4960 char *zPat;
4961 if( zPattern==0
4962 || zPattern[0]=='0'
4963 || cli_strcmp(zPattern,"-a")==0
4964 || cli_strcmp(zPattern,"-all")==0
4965 || cli_strcmp(zPattern,"--all")==0
4967 enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
4968 enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
4969 /* Show all or most commands
4970 ** *zPattern==0 => summary of documented commands only
4971 ** *zPattern=='0' => whole help for undocumented commands
4972 ** Otherwise => whole help for documented commands
4974 enum HelpWanted hw = HW_SummaryOnly;
4975 enum HelpHave hh = HH_More;
4976 if( zPattern!=0 ){
4977 hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
4979 for(i=0; i<ArraySize(azHelp); i++){
4980 switch( azHelp[i][0] ){
4981 case ',':
4982 hh = HH_Summary|HH_Undoc;
4983 break;
4984 case '.':
4985 hh = HH_Summary;
4986 break;
4987 default:
4988 hh &= ~HH_Summary;
4989 break;
4991 if( ((hw^hh)&HH_Undoc)==0 ){
4992 if( (hh&HH_Summary)!=0 ){
4993 sputf(out, ".%s\n", azHelp[i]+1);
4994 ++n;
4995 }else if( (hw&HW_SummaryOnly)==0 ){
4996 sputf(out, "%s\n", azHelp[i]);
5000 }else{
5001 /* Seek documented commands for which zPattern is an exact prefix */
5002 zPat = sqlite3_mprintf(".%s*", zPattern);
5003 shell_check_oom(zPat);
5004 for(i=0; i<ArraySize(azHelp); i++){
5005 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
5006 sputf(out, "%s\n", azHelp[i]);
5007 j = i+1;
5008 n++;
5011 sqlite3_free(zPat);
5012 if( n ){
5013 if( n==1 ){
5014 /* when zPattern is a prefix of exactly one command, then include
5015 ** the details of that command, which should begin at offset j */
5016 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
5017 sputf(out, "%s\n", azHelp[j]);
5018 j++;
5021 return n;
5023 /* Look for documented commands that contain zPattern anywhere.
5024 ** Show complete text of all documented commands that match. */
5025 zPat = sqlite3_mprintf("%%%s%%", zPattern);
5026 shell_check_oom(zPat);
5027 for(i=0; i<ArraySize(azHelp); i++){
5028 if( azHelp[i][0]==',' ){
5029 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
5030 continue;
5032 if( azHelp[i][0]=='.' ) j = i;
5033 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
5034 sputf(out, "%s\n", azHelp[j]);
5035 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
5036 j++;
5037 sputf(out, "%s\n", azHelp[j]);
5039 i = j;
5040 n++;
5043 sqlite3_free(zPat);
5045 return n;
5048 /* Forward reference */
5049 static int process_input(ShellState *p);
5052 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
5053 ** and return a pointer to the buffer. The caller is responsible for freeing
5054 ** the memory.
5056 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
5057 ** read.
5059 ** For convenience, a nul-terminator byte is always appended to the data read
5060 ** from the file before the buffer is returned. This byte is not included in
5061 ** the final value of (*pnByte), if applicable.
5063 ** NULL is returned if any error is encountered. The final value of *pnByte
5064 ** is undefined in this case.
5066 static char *readFile(const char *zName, int *pnByte){
5067 FILE *in = fopen(zName, "rb");
5068 long nIn;
5069 size_t nRead;
5070 char *pBuf;
5071 int rc;
5072 if( in==0 ) return 0;
5073 rc = fseek(in, 0, SEEK_END);
5074 if( rc!=0 ){
5075 eputf("Error: '%s' not seekable\n", zName);
5076 fclose(in);
5077 return 0;
5079 nIn = ftell(in);
5080 rewind(in);
5081 pBuf = sqlite3_malloc64( nIn+1 );
5082 if( pBuf==0 ){
5083 eputz("Error: out of memory\n");
5084 fclose(in);
5085 return 0;
5087 nRead = fread(pBuf, nIn, 1, in);
5088 fclose(in);
5089 if( nRead!=1 ){
5090 sqlite3_free(pBuf);
5091 eputf("Error: cannot read '%s'\n", zName);
5092 return 0;
5094 pBuf[nIn] = 0;
5095 if( pnByte ) *pnByte = nIn;
5096 return pBuf;
5099 #if defined(SQLITE_ENABLE_SESSION)
5101 ** Close a single OpenSession object and release all of its associated
5102 ** resources.
5104 static void session_close(OpenSession *pSession){
5105 int i;
5106 sqlite3session_delete(pSession->p);
5107 sqlite3_free(pSession->zName);
5108 for(i=0; i<pSession->nFilter; i++){
5109 sqlite3_free(pSession->azFilter[i]);
5111 sqlite3_free(pSession->azFilter);
5112 memset(pSession, 0, sizeof(OpenSession));
5114 #endif
5117 ** Close all OpenSession objects and release all associated resources.
5119 #if defined(SQLITE_ENABLE_SESSION)
5120 static void session_close_all(ShellState *p, int i){
5121 int j;
5122 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
5123 for(j=0; j<pAuxDb->nSession; j++){
5124 session_close(&pAuxDb->aSession[j]);
5126 pAuxDb->nSession = 0;
5128 #else
5129 # define session_close_all(X,Y)
5130 #endif
5133 ** Implementation of the xFilter function for an open session. Omit
5134 ** any tables named by ".session filter" but let all other table through.
5136 #if defined(SQLITE_ENABLE_SESSION)
5137 static int session_filter(void *pCtx, const char *zTab){
5138 OpenSession *pSession = (OpenSession*)pCtx;
5139 int i;
5140 for(i=0; i<pSession->nFilter; i++){
5141 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
5143 return 1;
5145 #endif
5148 ** Try to deduce the type of file for zName based on its content. Return
5149 ** one of the SHELL_OPEN_* constants.
5151 ** If the file does not exist or is empty but its name looks like a ZIP
5152 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
5153 ** Otherwise, assume an ordinary database regardless of the filename if
5154 ** the type cannot be determined from content.
5156 int deduceDatabaseType(const char *zName, int dfltZip){
5157 FILE *f = fopen(zName, "rb");
5158 size_t n;
5159 int rc = SHELL_OPEN_UNSPEC;
5160 char zBuf[100];
5161 if( f==0 ){
5162 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5163 return SHELL_OPEN_ZIPFILE;
5164 }else{
5165 return SHELL_OPEN_NORMAL;
5168 n = fread(zBuf, 16, 1, f);
5169 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
5170 fclose(f);
5171 return SHELL_OPEN_NORMAL;
5173 fseek(f, -25, SEEK_END);
5174 n = fread(zBuf, 25, 1, f);
5175 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
5176 rc = SHELL_OPEN_APPENDVFS;
5177 }else{
5178 fseek(f, -22, SEEK_END);
5179 n = fread(zBuf, 22, 1, f);
5180 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
5181 && zBuf[3]==0x06 ){
5182 rc = SHELL_OPEN_ZIPFILE;
5183 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5184 rc = SHELL_OPEN_ZIPFILE;
5187 fclose(f);
5188 return rc;
5191 #ifndef SQLITE_OMIT_DESERIALIZE
5193 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5194 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5195 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5197 static unsigned char *readHexDb(ShellState *p, int *pnData){
5198 unsigned char *a = 0;
5199 int nLine;
5200 int n = 0;
5201 int pgsz = 0;
5202 int iOffset = 0;
5203 int j, k;
5204 int rc;
5205 FILE *in;
5206 const char *zDbFilename = p->pAuxDb->zDbFilename;
5207 unsigned int x[16];
5208 char zLine[1000];
5209 if( zDbFilename ){
5210 in = fopen(zDbFilename, "r");
5211 if( in==0 ){
5212 eputf("cannot open \"%s\" for reading\n", zDbFilename);
5213 return 0;
5215 nLine = 0;
5216 }else{
5217 in = p->in;
5218 nLine = p->lineno;
5219 if( in==0 ) in = stdin;
5221 *pnData = 0;
5222 nLine++;
5223 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
5224 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
5225 if( rc!=2 ) goto readHexDb_error;
5226 if( n<0 ) goto readHexDb_error;
5227 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
5228 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
5229 a = sqlite3_malloc( n ? n : 1 );
5230 shell_check_oom(a);
5231 memset(a, 0, n);
5232 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
5233 eputz("invalid pagesize\n");
5234 goto readHexDb_error;
5236 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
5237 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
5238 if( rc==2 ){
5239 iOffset = k;
5240 continue;
5242 if( cli_strncmp(zLine, "| end ", 6)==0 ){
5243 break;
5245 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5246 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
5247 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
5248 if( rc==17 ){
5249 k = iOffset+j;
5250 if( k+16<=n && k>=0 ){
5251 int ii;
5252 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
5256 *pnData = n;
5257 if( in!=p->in ){
5258 fclose(in);
5259 }else{
5260 p->lineno = nLine;
5262 return a;
5264 readHexDb_error:
5265 if( in!=p->in ){
5266 fclose(in);
5267 }else{
5268 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
5269 nLine++;
5270 if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
5272 p->lineno = nLine;
5274 sqlite3_free(a);
5275 eputf("Error on line %d of --hexdb input\n", nLine);
5276 return 0;
5278 #endif /* SQLITE_OMIT_DESERIALIZE */
5281 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5283 static void shellUSleepFunc(
5284 sqlite3_context *context,
5285 int argcUnused,
5286 sqlite3_value **argv
5288 int sleep = sqlite3_value_int(argv[0]);
5289 (void)argcUnused;
5290 sqlite3_sleep(sleep/1000);
5291 sqlite3_result_int(context, sleep);
5294 /* Flags for open_db().
5296 ** The default behavior of open_db() is to exit(1) if the database fails to
5297 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5298 ** but still returns without calling exit.
5300 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5301 ** ZIP archive if the file does not exist or is empty and its name matches
5302 ** the *.zip pattern.
5304 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5305 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5308 ** Make sure the database is open. If it is not, then open it. If
5309 ** the database fails to open, print an error message and exit.
5311 static void open_db(ShellState *p, int openFlags){
5312 if( p->db==0 ){
5313 const char *zDbFilename = p->pAuxDb->zDbFilename;
5314 if( p->openMode==SHELL_OPEN_UNSPEC ){
5315 if( zDbFilename==0 || zDbFilename[0]==0 ){
5316 p->openMode = SHELL_OPEN_NORMAL;
5317 }else{
5318 p->openMode = (u8)deduceDatabaseType(zDbFilename,
5319 (openFlags & OPEN_DB_ZIPFILE)!=0);
5322 switch( p->openMode ){
5323 case SHELL_OPEN_APPENDVFS: {
5324 sqlite3_open_v2(zDbFilename, &p->db,
5325 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5326 break;
5328 case SHELL_OPEN_HEXDB:
5329 case SHELL_OPEN_DESERIALIZE: {
5330 sqlite3_open(0, &p->db);
5331 break;
5333 case SHELL_OPEN_ZIPFILE: {
5334 sqlite3_open(":memory:", &p->db);
5335 break;
5337 case SHELL_OPEN_READONLY: {
5338 sqlite3_open_v2(zDbFilename, &p->db,
5339 SQLITE_OPEN_READONLY|p->openFlags, 0);
5340 break;
5342 case SHELL_OPEN_UNSPEC:
5343 case SHELL_OPEN_NORMAL: {
5344 sqlite3_open_v2(zDbFilename, &p->db,
5345 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5346 break;
5349 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5350 eputf("Error: unable to open database \"%s\": %s\n",
5351 zDbFilename, sqlite3_errmsg(p->db));
5352 if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
5353 exit(1);
5355 sqlite3_close(p->db);
5356 sqlite3_open(":memory:", &p->db);
5357 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5358 eputz("Also: unable to open substitute in-memory database.\n");
5359 exit(1);
5360 }else{
5361 eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
5362 zDbFilename);
5365 globalDb = p->db;
5366 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
5368 /* Reflect the use or absence of --unsafe-testing invocation. */
5370 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
5371 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
5372 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
5375 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5376 sqlite3_enable_load_extension(p->db, 1);
5377 #endif
5378 sqlite3_shathree_init(p->db, 0, 0);
5379 sqlite3_uint_init(p->db, 0, 0);
5380 sqlite3_decimal_init(p->db, 0, 0);
5381 sqlite3_base64_init(p->db, 0, 0);
5382 sqlite3_base85_init(p->db, 0, 0);
5383 sqlite3_regexp_init(p->db, 0, 0);
5384 sqlite3_ieee_init(p->db, 0, 0);
5385 sqlite3_series_init(p->db, 0, 0);
5386 #ifndef SQLITE_SHELL_FIDDLE
5387 sqlite3_fileio_init(p->db, 0, 0);
5388 sqlite3_completion_init(p->db, 0, 0);
5389 #endif
5390 #ifdef SQLITE_HAVE_ZLIB
5391 if( !p->bSafeModePersist ){
5392 sqlite3_zipfile_init(p->db, 0, 0);
5393 sqlite3_sqlar_init(p->db, 0, 0);
5395 #endif
5396 #ifdef SQLITE_SHELL_EXTFUNCS
5397 /* Create a preprocessing mechanism for extensions to make
5398 * their own provisions for being built into the shell.
5399 * This is a short-span macro. See further below for usage.
5401 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5402 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5403 /* Let custom-included extensions get their ..._init() called.
5404 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5405 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5406 * initialization routine to be called.
5409 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
5410 /* Let custom-included extensions expose their functionality.
5411 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5412 * the SQL functions, virtual tables, collating sequences or
5413 * VFS's implemented by the extension to be registered.
5415 if( irc==SQLITE_OK
5416 || irc==SQLITE_OK_LOAD_PERMANENTLY ){
5417 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
5419 #undef SHELL_SUB_MACRO
5420 #undef SHELL_SUBMACRO
5422 #endif
5424 sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
5425 shellStrtod, 0, 0);
5426 sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
5427 shellDtostr, 0, 0);
5428 sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
5429 shellDtostr, 0, 0);
5430 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5431 shellAddSchemaName, 0, 0);
5432 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5433 shellModuleSchema, 0, 0);
5434 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5435 shellPutsFunc, 0, 0);
5436 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5437 shellUSleepFunc, 0, 0);
5438 #ifndef SQLITE_NOHAVE_SYSTEM
5439 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5440 editFunc, 0, 0);
5441 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5442 editFunc, 0, 0);
5443 #endif
5445 if( p->openMode==SHELL_OPEN_ZIPFILE ){
5446 char *zSql = sqlite3_mprintf(
5447 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5448 shell_check_oom(zSql);
5449 sqlite3_exec(p->db, zSql, 0, 0, 0);
5450 sqlite3_free(zSql);
5452 #ifndef SQLITE_OMIT_DESERIALIZE
5453 else
5454 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5455 int rc;
5456 int nData = 0;
5457 unsigned char *aData;
5458 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5459 aData = (unsigned char*)readFile(zDbFilename, &nData);
5460 }else{
5461 aData = readHexDb(p, &nData);
5463 if( aData==0 ){
5464 return;
5466 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5467 SQLITE_DESERIALIZE_RESIZEABLE |
5468 SQLITE_DESERIALIZE_FREEONCLOSE);
5469 if( rc ){
5470 eputf("Error: sqlite3_deserialize() returns %d\n", rc);
5472 if( p->szMax>0 ){
5473 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5476 #endif
5478 if( p->db!=0 ){
5479 if( p->bSafeModePersist ){
5480 sqlite3_set_authorizer(p->db, safeModeAuth, p);
5482 sqlite3_db_config(
5483 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
5489 ** Attempt to close the database connection. Report errors.
5491 void close_db(sqlite3 *db){
5492 int rc = sqlite3_close(db);
5493 if( rc ){
5494 eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
5498 #if HAVE_READLINE || HAVE_EDITLINE
5500 ** Readline completion callbacks
5502 static char *readline_completion_generator(const char *text, int state){
5503 static sqlite3_stmt *pStmt = 0;
5504 char *zRet;
5505 if( state==0 ){
5506 char *zSql;
5507 sqlite3_finalize(pStmt);
5508 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5509 " FROM completion(%Q) ORDER BY 1", text);
5510 shell_check_oom(zSql);
5511 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5512 sqlite3_free(zSql);
5514 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5515 const char *z = (const char*)sqlite3_column_text(pStmt,0);
5516 zRet = z ? strdup(z) : 0;
5517 }else{
5518 sqlite3_finalize(pStmt);
5519 pStmt = 0;
5520 zRet = 0;
5522 return zRet;
5524 static char **readline_completion(const char *zText, int iStart, int iEnd){
5525 (void)iStart;
5526 (void)iEnd;
5527 rl_attempted_completion_over = 1;
5528 return rl_completion_matches(zText, readline_completion_generator);
5531 #elif HAVE_LINENOISE
5533 ** Linenoise completion callback
5535 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5536 i64 nLine = strlen(zLine);
5537 i64 i, iStart;
5538 sqlite3_stmt *pStmt = 0;
5539 char *zSql;
5540 char zBuf[1000];
5542 if( nLine>(i64)sizeof(zBuf)-30 ) return;
5543 if( zLine[0]=='.' || zLine[0]=='#') return;
5544 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5545 if( i==nLine-1 ) return;
5546 iStart = i+1;
5547 memcpy(zBuf, zLine, iStart);
5548 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5549 " FROM completion(%Q,%Q) ORDER BY 1",
5550 &zLine[iStart], zLine);
5551 shell_check_oom(zSql);
5552 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5553 sqlite3_free(zSql);
5554 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5555 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5556 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5557 int nCompletion = sqlite3_column_bytes(pStmt, 0);
5558 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
5559 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5560 linenoiseAddCompletion(lc, zBuf);
5563 sqlite3_finalize(pStmt);
5565 #endif
5568 ** Do C-language style dequoting.
5570 ** \a -> alarm
5571 ** \b -> backspace
5572 ** \t -> tab
5573 ** \n -> newline
5574 ** \v -> vertical tab
5575 ** \f -> form feed
5576 ** \r -> carriage return
5577 ** \s -> space
5578 ** \" -> "
5579 ** \' -> '
5580 ** \\ -> backslash
5581 ** \NNN -> ascii character NNN in octal
5582 ** \xHH -> ascii character HH in hexadecimal
5584 static void resolve_backslashes(char *z){
5585 int i, j;
5586 char c;
5587 while( *z && *z!='\\' ) z++;
5588 for(i=j=0; (c = z[i])!=0; i++, j++){
5589 if( c=='\\' && z[i+1]!=0 ){
5590 c = z[++i];
5591 if( c=='a' ){
5592 c = '\a';
5593 }else if( c=='b' ){
5594 c = '\b';
5595 }else if( c=='t' ){
5596 c = '\t';
5597 }else if( c=='n' ){
5598 c = '\n';
5599 }else if( c=='v' ){
5600 c = '\v';
5601 }else if( c=='f' ){
5602 c = '\f';
5603 }else if( c=='r' ){
5604 c = '\r';
5605 }else if( c=='"' ){
5606 c = '"';
5607 }else if( c=='\'' ){
5608 c = '\'';
5609 }else if( c=='\\' ){
5610 c = '\\';
5611 }else if( c=='x' ){
5612 int nhd = 0, hdv;
5613 u8 hv = 0;
5614 while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
5615 hv = (u8)((hv<<4)|hdv);
5616 ++nhd;
5618 i += nhd;
5619 c = (u8)hv;
5620 }else if( c>='0' && c<='7' ){
5621 c -= '0';
5622 if( z[i+1]>='0' && z[i+1]<='7' ){
5623 i++;
5624 c = (c<<3) + z[i] - '0';
5625 if( z[i+1]>='0' && z[i+1]<='7' ){
5626 i++;
5627 c = (c<<3) + z[i] - '0';
5632 z[j] = c;
5634 if( j<i ) z[j] = 0;
5638 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5639 ** for TRUE and FALSE. Return the integer value if appropriate.
5641 static int booleanValue(const char *zArg){
5642 int i;
5643 if( zArg[0]=='0' && zArg[1]=='x' ){
5644 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5645 }else{
5646 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5648 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5649 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5650 return 1;
5652 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5653 return 0;
5655 eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
5656 return 0;
5660 ** Set or clear a shell flag according to a boolean value.
5662 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5663 if( booleanValue(zArg) ){
5664 ShellSetFlag(p, mFlag);
5665 }else{
5666 ShellClearFlag(p, mFlag);
5671 ** Close an output file, assuming it is not stderr or stdout
5673 static void output_file_close(FILE *f){
5674 if( f && f!=stdout && f!=stderr ) fclose(f);
5678 ** Try to open an output file. The names "stdout" and "stderr" are
5679 ** recognized and do the right thing. NULL is returned if the output
5680 ** filename is "off".
5682 static FILE *output_file_open(const char *zFile, int bTextMode){
5683 FILE *f;
5684 if( cli_strcmp(zFile,"stdout")==0 ){
5685 f = stdout;
5686 }else if( cli_strcmp(zFile, "stderr")==0 ){
5687 f = stderr;
5688 }else if( cli_strcmp(zFile, "off")==0 ){
5689 f = 0;
5690 }else{
5691 f = fopen(zFile, bTextMode ? "w" : "wb");
5692 if( f==0 ){
5693 eputf("Error: cannot open \"%s\"\n", zFile);
5696 return f;
5699 #ifndef SQLITE_OMIT_TRACE
5701 ** A routine for handling output from sqlite3_trace().
5703 static int sql_trace_callback(
5704 unsigned mType, /* The trace type */
5705 void *pArg, /* The ShellState pointer */
5706 void *pP, /* Usually a pointer to sqlite_stmt */
5707 void *pX /* Auxiliary output */
5709 ShellState *p = (ShellState*)pArg;
5710 sqlite3_stmt *pStmt;
5711 const char *zSql;
5712 i64 nSql;
5713 if( p->traceOut==0 ) return 0;
5714 if( mType==SQLITE_TRACE_CLOSE ){
5715 sputz(p->traceOut, "-- closing database connection\n");
5716 return 0;
5718 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
5719 zSql = (const char*)pX;
5720 }else{
5721 pStmt = (sqlite3_stmt*)pP;
5722 switch( p->eTraceType ){
5723 case SHELL_TRACE_EXPANDED: {
5724 zSql = sqlite3_expanded_sql(pStmt);
5725 break;
5727 #ifdef SQLITE_ENABLE_NORMALIZE
5728 case SHELL_TRACE_NORMALIZED: {
5729 zSql = sqlite3_normalized_sql(pStmt);
5730 break;
5732 #endif
5733 default: {
5734 zSql = sqlite3_sql(pStmt);
5735 break;
5739 if( zSql==0 ) return 0;
5740 nSql = strlen(zSql);
5741 if( nSql>1000000000 ) nSql = 1000000000;
5742 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5743 switch( mType ){
5744 case SQLITE_TRACE_ROW:
5745 case SQLITE_TRACE_STMT: {
5746 sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5747 break;
5749 case SQLITE_TRACE_PROFILE: {
5750 sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
5751 sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5752 break;
5755 return 0;
5757 #endif
5760 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5761 ** a useful spot to set a debugger breakpoint.
5763 ** This routine does not do anything practical. The code are there simply
5764 ** to prevent the compiler from optimizing this routine out.
5766 static void test_breakpoint(void){
5767 static unsigned int nCall = 0;
5768 if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
5772 ** An object used to read a CSV and other files for import.
5774 typedef struct ImportCtx ImportCtx;
5775 struct ImportCtx {
5776 const char *zFile; /* Name of the input file */
5777 FILE *in; /* Read the CSV text from this input stream */
5778 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
5779 char *z; /* Accumulated text for a field */
5780 int n; /* Number of bytes in z */
5781 int nAlloc; /* Space allocated for z[] */
5782 int nLine; /* Current line number */
5783 int nRow; /* Number of rows imported */
5784 int nErr; /* Number of errors encountered */
5785 int bNotFirst; /* True if one or more bytes already read */
5786 int cTerm; /* Character that terminated the most recent field */
5787 int cColSep; /* The column separator character. (Usually ",") */
5788 int cRowSep; /* The row separator character. (Usually "\n") */
5791 /* Clean up resourced used by an ImportCtx */
5792 static void import_cleanup(ImportCtx *p){
5793 if( p->in!=0 && p->xCloser!=0 ){
5794 p->xCloser(p->in);
5795 p->in = 0;
5797 sqlite3_free(p->z);
5798 p->z = 0;
5801 /* Append a single byte to z[] */
5802 static void import_append_char(ImportCtx *p, int c){
5803 if( p->n+1>=p->nAlloc ){
5804 p->nAlloc += p->nAlloc + 100;
5805 p->z = sqlite3_realloc64(p->z, p->nAlloc);
5806 shell_check_oom(p->z);
5808 p->z[p->n++] = (char)c;
5811 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5812 ** with the option of having a separator other than ",".
5814 ** + Input comes from p->in.
5815 ** + Store results in p->z of length p->n. Space to hold p->z comes
5816 ** from sqlite3_malloc64().
5817 ** + Use p->cSep as the column separator. The default is ",".
5818 ** + Use p->rSep as the row separator. The default is "\n".
5819 ** + Keep track of the line number in p->nLine.
5820 ** + Store the character that terminates the field in p->cTerm. Store
5821 ** EOF on end-of-file.
5822 ** + Report syntax errors on stderr
5824 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5825 int c;
5826 int cSep = (u8)p->cColSep;
5827 int rSep = (u8)p->cRowSep;
5828 p->n = 0;
5829 c = fgetc(p->in);
5830 if( c==EOF || seenInterrupt ){
5831 p->cTerm = EOF;
5832 return 0;
5834 if( c=='"' ){
5835 int pc, ppc;
5836 int startLine = p->nLine;
5837 int cQuote = c;
5838 pc = ppc = 0;
5839 while( 1 ){
5840 c = fgetc(p->in);
5841 if( c==rSep ) p->nLine++;
5842 if( c==cQuote ){
5843 if( pc==cQuote ){
5844 pc = 0;
5845 continue;
5848 if( (c==cSep && pc==cQuote)
5849 || (c==rSep && pc==cQuote)
5850 || (c==rSep && pc=='\r' && ppc==cQuote)
5851 || (c==EOF && pc==cQuote)
5853 do{ p->n--; }while( p->z[p->n]!=cQuote );
5854 p->cTerm = c;
5855 break;
5857 if( pc==cQuote && c!='\r' ){
5858 eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
5860 if( c==EOF ){
5861 eputf("%s:%d: unterminated %c-quoted field\n",
5862 p->zFile, startLine, cQuote);
5863 p->cTerm = c;
5864 break;
5866 import_append_char(p, c);
5867 ppc = pc;
5868 pc = c;
5870 }else{
5871 /* If this is the first field being parsed and it begins with the
5872 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5873 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5874 import_append_char(p, c);
5875 c = fgetc(p->in);
5876 if( (c&0xff)==0xbb ){
5877 import_append_char(p, c);
5878 c = fgetc(p->in);
5879 if( (c&0xff)==0xbf ){
5880 p->bNotFirst = 1;
5881 p->n = 0;
5882 return csv_read_one_field(p);
5886 while( c!=EOF && c!=cSep && c!=rSep ){
5887 import_append_char(p, c);
5888 c = fgetc(p->in);
5890 if( c==rSep ){
5891 p->nLine++;
5892 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5894 p->cTerm = c;
5896 if( p->z ) p->z[p->n] = 0;
5897 p->bNotFirst = 1;
5898 return p->z;
5901 /* Read a single field of ASCII delimited text.
5903 ** + Input comes from p->in.
5904 ** + Store results in p->z of length p->n. Space to hold p->z comes
5905 ** from sqlite3_malloc64().
5906 ** + Use p->cSep as the column separator. The default is "\x1F".
5907 ** + Use p->rSep as the row separator. The default is "\x1E".
5908 ** + Keep track of the row number in p->nLine.
5909 ** + Store the character that terminates the field in p->cTerm. Store
5910 ** EOF on end-of-file.
5911 ** + Report syntax errors on stderr
5913 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5914 int c;
5915 int cSep = (u8)p->cColSep;
5916 int rSep = (u8)p->cRowSep;
5917 p->n = 0;
5918 c = fgetc(p->in);
5919 if( c==EOF || seenInterrupt ){
5920 p->cTerm = EOF;
5921 return 0;
5923 while( c!=EOF && c!=cSep && c!=rSep ){
5924 import_append_char(p, c);
5925 c = fgetc(p->in);
5927 if( c==rSep ){
5928 p->nLine++;
5930 p->cTerm = c;
5931 if( p->z ) p->z[p->n] = 0;
5932 return p->z;
5936 ** Try to transfer data for table zTable. If an error is seen while
5937 ** moving forward, try to go backwards. The backwards movement won't
5938 ** work for WITHOUT ROWID tables.
5940 static void tryToCloneData(
5941 ShellState *p,
5942 sqlite3 *newDb,
5943 const char *zTable
5945 sqlite3_stmt *pQuery = 0;
5946 sqlite3_stmt *pInsert = 0;
5947 char *zQuery = 0;
5948 char *zInsert = 0;
5949 int rc;
5950 int i, j, n;
5951 int nTable = strlen30(zTable);
5952 int k = 0;
5953 int cnt = 0;
5954 const int spinRate = 10000;
5956 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5957 shell_check_oom(zQuery);
5958 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5959 if( rc ){
5960 eputf("Error %d: %s on [%s]\n",
5961 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
5962 goto end_data_xfer;
5964 n = sqlite3_column_count(pQuery);
5965 zInsert = sqlite3_malloc64(200 + nTable + n*3);
5966 shell_check_oom(zInsert);
5967 sqlite3_snprintf(200+nTable,zInsert,
5968 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5969 i = strlen30(zInsert);
5970 for(j=1; j<n; j++){
5971 memcpy(zInsert+i, ",?", 2);
5972 i += 2;
5974 memcpy(zInsert+i, ");", 3);
5975 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5976 if( rc ){
5977 eputf("Error %d: %s on [%s]\n",
5978 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
5979 goto end_data_xfer;
5981 for(k=0; k<2; k++){
5982 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5983 for(i=0; i<n; i++){
5984 switch( sqlite3_column_type(pQuery, i) ){
5985 case SQLITE_NULL: {
5986 sqlite3_bind_null(pInsert, i+1);
5987 break;
5989 case SQLITE_INTEGER: {
5990 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5991 break;
5993 case SQLITE_FLOAT: {
5994 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5995 break;
5997 case SQLITE_TEXT: {
5998 sqlite3_bind_text(pInsert, i+1,
5999 (const char*)sqlite3_column_text(pQuery,i),
6000 -1, SQLITE_STATIC);
6001 break;
6003 case SQLITE_BLOB: {
6004 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
6005 sqlite3_column_bytes(pQuery,i),
6006 SQLITE_STATIC);
6007 break;
6010 } /* End for */
6011 rc = sqlite3_step(pInsert);
6012 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
6013 eputf("Error %d: %s\n",
6014 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
6016 sqlite3_reset(pInsert);
6017 cnt++;
6018 if( (cnt%spinRate)==0 ){
6019 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
6020 fflush(stdout);
6022 } /* End while */
6023 if( rc==SQLITE_DONE ) break;
6024 sqlite3_finalize(pQuery);
6025 sqlite3_free(zQuery);
6026 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
6027 zTable);
6028 shell_check_oom(zQuery);
6029 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6030 if( rc ){
6031 eputf("Warning: cannot step \"%s\" backwards", zTable);
6032 break;
6034 } /* End for(k=0...) */
6036 end_data_xfer:
6037 sqlite3_finalize(pQuery);
6038 sqlite3_finalize(pInsert);
6039 sqlite3_free(zQuery);
6040 sqlite3_free(zInsert);
6045 ** Try to transfer all rows of the schema that match zWhere. For
6046 ** each row, invoke xForEach() on the object defined by that row.
6047 ** If an error is encountered while moving forward through the
6048 ** sqlite_schema table, try again moving backwards.
6050 static void tryToCloneSchema(
6051 ShellState *p,
6052 sqlite3 *newDb,
6053 const char *zWhere,
6054 void (*xForEach)(ShellState*,sqlite3*,const char*)
6056 sqlite3_stmt *pQuery = 0;
6057 char *zQuery = 0;
6058 int rc;
6059 const unsigned char *zName;
6060 const unsigned char *zSql;
6061 char *zErrMsg = 0;
6063 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6064 " WHERE %s ORDER BY rowid ASC", zWhere);
6065 shell_check_oom(zQuery);
6066 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6067 if( rc ){
6068 eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
6069 sqlite3_errmsg(p->db), zQuery);
6070 goto end_schema_xfer;
6072 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
6073 zName = sqlite3_column_text(pQuery, 0);
6074 zSql = sqlite3_column_text(pQuery, 1);
6075 if( zName==0 || zSql==0 ) continue;
6076 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
6077 sputf(stdout, "%s... ", zName); fflush(stdout);
6078 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6079 if( zErrMsg ){
6080 eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6081 sqlite3_free(zErrMsg);
6082 zErrMsg = 0;
6085 if( xForEach ){
6086 xForEach(p, newDb, (const char*)zName);
6088 sputz(stdout, "done\n");
6090 if( rc!=SQLITE_DONE ){
6091 sqlite3_finalize(pQuery);
6092 sqlite3_free(zQuery);
6093 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6094 " WHERE %s ORDER BY rowid DESC", zWhere);
6095 shell_check_oom(zQuery);
6096 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6097 if( rc ){
6098 eputf("Error: (%d) %s on [%s]\n",
6099 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
6100 goto end_schema_xfer;
6102 while( sqlite3_step(pQuery)==SQLITE_ROW ){
6103 zName = sqlite3_column_text(pQuery, 0);
6104 zSql = sqlite3_column_text(pQuery, 1);
6105 if( zName==0 || zSql==0 ) continue;
6106 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
6107 sputf(stdout, "%s... ", zName); fflush(stdout);
6108 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6109 if( zErrMsg ){
6110 eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6111 sqlite3_free(zErrMsg);
6112 zErrMsg = 0;
6114 if( xForEach ){
6115 xForEach(p, newDb, (const char*)zName);
6117 sputz(stdout, "done\n");
6120 end_schema_xfer:
6121 sqlite3_finalize(pQuery);
6122 sqlite3_free(zQuery);
6126 ** Open a new database file named "zNewDb". Try to recover as much information
6127 ** as possible out of the main database (which might be corrupt) and write it
6128 ** into zNewDb.
6130 static void tryToClone(ShellState *p, const char *zNewDb){
6131 int rc;
6132 sqlite3 *newDb = 0;
6133 if( access(zNewDb,0)==0 ){
6134 eputf("File \"%s\" already exists.\n", zNewDb);
6135 return;
6137 rc = sqlite3_open(zNewDb, &newDb);
6138 if( rc ){
6139 eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
6140 }else{
6141 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
6142 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
6143 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
6144 tryToCloneSchema(p, newDb, "type!='table'", 0);
6145 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
6146 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6148 close_db(newDb);
6151 #ifndef SQLITE_SHELL_FIDDLE
6153 ** Change the output stream (file or pipe or console) to something else.
6155 static void output_redir(ShellState *p, FILE *pfNew){
6156 if( p->out != stdout ) eputz("Output already redirected.\n");
6157 else{
6158 p->out = pfNew;
6159 setOutputStream(pfNew);
6164 ** Change the output file back to stdout.
6166 ** If the p->doXdgOpen flag is set, that means the output was being
6167 ** redirected to a temporary file named by p->zTempFile. In that case,
6168 ** launch start/open/xdg-open on that temporary file.
6170 static void output_reset(ShellState *p){
6171 if( p->outfile[0]=='|' ){
6172 #ifndef SQLITE_OMIT_POPEN
6173 pclose(p->out);
6174 #endif
6175 }else{
6176 output_file_close(p->out);
6177 #ifndef SQLITE_NOHAVE_SYSTEM
6178 if( p->doXdgOpen ){
6179 const char *zXdgOpenCmd =
6180 #if defined(_WIN32)
6181 "start";
6182 #elif defined(__APPLE__)
6183 "open";
6184 #else
6185 "xdg-open";
6186 #endif
6187 char *zCmd;
6188 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
6189 if( system(zCmd) ){
6190 eputf("Failed: [%s]\n", zCmd);
6191 }else{
6192 /* Give the start/open/xdg-open command some time to get
6193 ** going before we continue, and potential delete the
6194 ** p->zTempFile data file out from under it */
6195 sqlite3_sleep(2000);
6197 sqlite3_free(zCmd);
6198 outputModePop(p);
6199 p->doXdgOpen = 0;
6201 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6203 p->outfile[0] = 0;
6204 p->out = stdout;
6205 setOutputStream(stdout);
6207 #else
6208 # define output_redir(SS,pfO)
6209 # define output_reset(SS)
6210 #endif
6213 ** Run an SQL command and return the single integer result.
6215 static int db_int(sqlite3 *db, const char *zSql){
6216 sqlite3_stmt *pStmt;
6217 int res = 0;
6218 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
6219 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
6220 res = sqlite3_column_int(pStmt,0);
6222 sqlite3_finalize(pStmt);
6223 return res;
6226 #if SQLITE_SHELL_HAVE_RECOVER
6228 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6230 static unsigned int get2byteInt(unsigned char *a){
6231 return (a[0]<<8) + a[1];
6233 static unsigned int get4byteInt(unsigned char *a){
6234 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
6238 ** Implementation of the ".dbinfo" command.
6240 ** Return 1 on error, 2 to exit, and 0 otherwise.
6242 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
6243 static const struct { const char *zName; int ofst; } aField[] = {
6244 { "file change counter:", 24 },
6245 { "database page count:", 28 },
6246 { "freelist page count:", 36 },
6247 { "schema cookie:", 40 },
6248 { "schema format:", 44 },
6249 { "default cache size:", 48 },
6250 { "autovacuum top root:", 52 },
6251 { "incremental vacuum:", 64 },
6252 { "text encoding:", 56 },
6253 { "user version:", 60 },
6254 { "application id:", 68 },
6255 { "software version:", 96 },
6257 static const struct { const char *zName; const char *zSql; } aQuery[] = {
6258 { "number of tables:",
6259 "SELECT count(*) FROM %s WHERE type='table'" },
6260 { "number of indexes:",
6261 "SELECT count(*) FROM %s WHERE type='index'" },
6262 { "number of triggers:",
6263 "SELECT count(*) FROM %s WHERE type='trigger'" },
6264 { "number of views:",
6265 "SELECT count(*) FROM %s WHERE type='view'" },
6266 { "schema size:",
6267 "SELECT total(length(sql)) FROM %s" },
6269 int i, rc;
6270 unsigned iDataVersion;
6271 char *zSchemaTab;
6272 char *zDb = nArg>=2 ? azArg[1] : "main";
6273 sqlite3_stmt *pStmt = 0;
6274 unsigned char aHdr[100];
6275 open_db(p, 0);
6276 if( p->db==0 ) return 1;
6277 rc = sqlite3_prepare_v2(p->db,
6278 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6279 -1, &pStmt, 0);
6280 if( rc ){
6281 eputf("error: %s\n", sqlite3_errmsg(p->db));
6282 sqlite3_finalize(pStmt);
6283 return 1;
6285 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
6286 if( sqlite3_step(pStmt)==SQLITE_ROW
6287 && sqlite3_column_bytes(pStmt,0)>100
6289 const u8 *pb = sqlite3_column_blob(pStmt,0);
6290 shell_check_oom(pb);
6291 memcpy(aHdr, pb, 100);
6292 sqlite3_finalize(pStmt);
6293 }else{
6294 eputz("unable to read database header\n");
6295 sqlite3_finalize(pStmt);
6296 return 1;
6298 i = get2byteInt(aHdr+16);
6299 if( i==1 ) i = 65536;
6300 oputf("%-20s %d\n", "database page size:", i);
6301 oputf("%-20s %d\n", "write format:", aHdr[18]);
6302 oputf("%-20s %d\n", "read format:", aHdr[19]);
6303 oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
6304 for(i=0; i<ArraySize(aField); i++){
6305 int ofst = aField[i].ofst;
6306 unsigned int val = get4byteInt(aHdr + ofst);
6307 oputf("%-20s %u", aField[i].zName, val);
6308 switch( ofst ){
6309 case 56: {
6310 if( val==1 ) oputz(" (utf8)");
6311 if( val==2 ) oputz(" (utf16le)");
6312 if( val==3 ) oputz(" (utf16be)");
6315 oputz("\n");
6317 if( zDb==0 ){
6318 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
6319 }else if( cli_strcmp(zDb,"temp")==0 ){
6320 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
6321 }else{
6322 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
6324 for(i=0; i<ArraySize(aQuery); i++){
6325 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
6326 int val = db_int(p->db, zSql);
6327 sqlite3_free(zSql);
6328 oputf("%-20s %d\n", aQuery[i].zName, val);
6330 sqlite3_free(zSchemaTab);
6331 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
6332 oputf("%-20s %u\n", "data version", iDataVersion);
6333 return 0;
6335 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6338 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6340 static int shellDatabaseError(sqlite3 *db){
6341 const char *zErr = sqlite3_errmsg(db);
6342 eputf("Error: %s\n", zErr);
6343 return 1;
6347 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6348 ** if they match and FALSE (0) if they do not match.
6350 ** Globbing rules:
6352 ** '*' Matches any sequence of zero or more characters.
6354 ** '?' Matches exactly one character.
6356 ** [...] Matches one character from the enclosed list of
6357 ** characters.
6359 ** [^...] Matches one character not in the enclosed list.
6361 ** '#' Matches any sequence of one or more digits with an
6362 ** optional + or - sign in front
6364 ** ' ' Any span of whitespace matches any other span of
6365 ** whitespace.
6367 ** Extra whitespace at the end of z[] is ignored.
6369 static int testcase_glob(const char *zGlob, const char *z){
6370 int c, c2;
6371 int invert;
6372 int seen;
6374 while( (c = (*(zGlob++)))!=0 ){
6375 if( IsSpace(c) ){
6376 if( !IsSpace(*z) ) return 0;
6377 while( IsSpace(*zGlob) ) zGlob++;
6378 while( IsSpace(*z) ) z++;
6379 }else if( c=='*' ){
6380 while( (c=(*(zGlob++))) == '*' || c=='?' ){
6381 if( c=='?' && (*(z++))==0 ) return 0;
6383 if( c==0 ){
6384 return 1;
6385 }else if( c=='[' ){
6386 while( *z && testcase_glob(zGlob-1,z)==0 ){
6387 z++;
6389 return (*z)!=0;
6391 while( (c2 = (*(z++)))!=0 ){
6392 while( c2!=c ){
6393 c2 = *(z++);
6394 if( c2==0 ) return 0;
6396 if( testcase_glob(zGlob,z) ) return 1;
6398 return 0;
6399 }else if( c=='?' ){
6400 if( (*(z++))==0 ) return 0;
6401 }else if( c=='[' ){
6402 int prior_c = 0;
6403 seen = 0;
6404 invert = 0;
6405 c = *(z++);
6406 if( c==0 ) return 0;
6407 c2 = *(zGlob++);
6408 if( c2=='^' ){
6409 invert = 1;
6410 c2 = *(zGlob++);
6412 if( c2==']' ){
6413 if( c==']' ) seen = 1;
6414 c2 = *(zGlob++);
6416 while( c2 && c2!=']' ){
6417 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6418 c2 = *(zGlob++);
6419 if( c>=prior_c && c<=c2 ) seen = 1;
6420 prior_c = 0;
6421 }else{
6422 if( c==c2 ){
6423 seen = 1;
6425 prior_c = c2;
6427 c2 = *(zGlob++);
6429 if( c2==0 || (seen ^ invert)==0 ) return 0;
6430 }else if( c=='#' ){
6431 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6432 if( !IsDigit(z[0]) ) return 0;
6433 z++;
6434 while( IsDigit(z[0]) ){ z++; }
6435 }else{
6436 if( c!=(*(z++)) ) return 0;
6439 while( IsSpace(*z) ){ z++; }
6440 return *z==0;
6445 ** Compare the string as a command-line option with either one or two
6446 ** initial "-" characters.
6448 static int optionMatch(const char *zStr, const char *zOpt){
6449 if( zStr[0]!='-' ) return 0;
6450 zStr++;
6451 if( zStr[0]=='-' ) zStr++;
6452 return cli_strcmp(zStr, zOpt)==0;
6456 ** Delete a file.
6458 int shellDeleteFile(const char *zFilename){
6459 int rc;
6460 #ifdef _WIN32
6461 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6462 rc = _wunlink(z);
6463 sqlite3_free(z);
6464 #else
6465 rc = unlink(zFilename);
6466 #endif
6467 return rc;
6471 ** Try to delete the temporary file (if there is one) and free the
6472 ** memory used to hold the name of the temp file.
6474 static void clearTempFile(ShellState *p){
6475 if( p->zTempFile==0 ) return;
6476 if( p->doXdgOpen ) return;
6477 if( shellDeleteFile(p->zTempFile) ) return;
6478 sqlite3_free(p->zTempFile);
6479 p->zTempFile = 0;
6483 ** Create a new temp file name with the given suffix.
6485 static void newTempFile(ShellState *p, const char *zSuffix){
6486 clearTempFile(p);
6487 sqlite3_free(p->zTempFile);
6488 p->zTempFile = 0;
6489 if( p->db ){
6490 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6492 if( p->zTempFile==0 ){
6493 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6494 ** will not work and we will need to fallback to guessing */
6495 char *zTemp;
6496 sqlite3_uint64 r;
6497 sqlite3_randomness(sizeof(r), &r);
6498 zTemp = getenv("TEMP");
6499 if( zTemp==0 ) zTemp = getenv("TMP");
6500 if( zTemp==0 ){
6501 #ifdef _WIN32
6502 zTemp = "\\tmp";
6503 #else
6504 zTemp = "/tmp";
6505 #endif
6507 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6508 }else{
6509 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6511 shell_check_oom(p->zTempFile);
6516 ** The implementation of SQL scalar function fkey_collate_clause(), used
6517 ** by the ".lint fkey-indexes" command. This scalar function is always
6518 ** called with four arguments - the parent table name, the parent column name,
6519 ** the child table name and the child column name.
6521 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6523 ** If either of the named tables or columns do not exist, this function
6524 ** returns an empty string. An empty string is also returned if both tables
6525 ** and columns exist but have the same default collation sequence. Or,
6526 ** if both exist but the default collation sequences are different, this
6527 ** function returns the string " COLLATE <parent-collation>", where
6528 ** <parent-collation> is the default collation sequence of the parent column.
6530 static void shellFkeyCollateClause(
6531 sqlite3_context *pCtx,
6532 int nVal,
6533 sqlite3_value **apVal
6535 sqlite3 *db = sqlite3_context_db_handle(pCtx);
6536 const char *zParent;
6537 const char *zParentCol;
6538 const char *zParentSeq;
6539 const char *zChild;
6540 const char *zChildCol;
6541 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
6542 int rc;
6544 assert( nVal==4 );
6545 zParent = (const char*)sqlite3_value_text(apVal[0]);
6546 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6547 zChild = (const char*)sqlite3_value_text(apVal[2]);
6548 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6550 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6551 rc = sqlite3_table_column_metadata(
6552 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6554 if( rc==SQLITE_OK ){
6555 rc = sqlite3_table_column_metadata(
6556 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6560 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6561 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6562 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6563 sqlite3_free(z);
6569 ** The implementation of dot-command ".lint fkey-indexes".
6571 static int lintFkeyIndexes(
6572 ShellState *pState, /* Current shell tool state */
6573 char **azArg, /* Array of arguments passed to dot command */
6574 int nArg /* Number of entries in azArg[] */
6576 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
6577 int bVerbose = 0; /* If -verbose is present */
6578 int bGroupByParent = 0; /* If -groupbyparent is present */
6579 int i; /* To iterate through azArg[] */
6580 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
6581 int rc; /* Return code */
6582 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
6585 ** This SELECT statement returns one row for each foreign key constraint
6586 ** in the schema of the main database. The column values are:
6588 ** 0. The text of an SQL statement similar to:
6590 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6592 ** This SELECT is similar to the one that the foreign keys implementation
6593 ** needs to run internally on child tables. If there is an index that can
6594 ** be used to optimize this query, then it can also be used by the FK
6595 ** implementation to optimize DELETE or UPDATE statements on the parent
6596 ** table.
6598 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6599 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6600 ** contains an index that can be used to optimize the query.
6602 ** 2. Human readable text that describes the child table and columns. e.g.
6604 ** "child_table(child_key1, child_key2)"
6606 ** 3. Human readable text that describes the parent table and columns. e.g.
6608 ** "parent_table(parent_key1, parent_key2)"
6610 ** 4. A full CREATE INDEX statement for an index that could be used to
6611 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6613 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6615 ** 5. The name of the parent table.
6617 ** These six values are used by the C logic below to generate the report.
6619 const char *zSql =
6620 "SELECT "
6621 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6622 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6623 " || fkey_collate_clause("
6624 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6625 ", "
6626 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6627 " || group_concat('*=?', ' AND ') || ')'"
6628 ", "
6629 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6630 ", "
6631 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6632 ", "
6633 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6634 " || ' ON ' || quote(s.name) || '('"
6635 " || group_concat(quote(f.[from]) ||"
6636 " fkey_collate_clause("
6637 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6638 " || ');'"
6639 ", "
6640 " f.[table] "
6641 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6642 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6643 "GROUP BY s.name, f.id "
6644 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6646 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6648 for(i=2; i<nArg; i++){
6649 int n = strlen30(azArg[i]);
6650 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6651 bVerbose = 1;
6653 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6654 bGroupByParent = 1;
6655 zIndent = " ";
6657 else{
6658 eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
6659 return SQLITE_ERROR;
6663 /* Register the fkey_collate_clause() SQL function */
6664 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6665 0, shellFkeyCollateClause, 0, 0
6669 if( rc==SQLITE_OK ){
6670 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6672 if( rc==SQLITE_OK ){
6673 sqlite3_bind_int(pSql, 1, bGroupByParent);
6676 if( rc==SQLITE_OK ){
6677 int rc2;
6678 char *zPrev = 0;
6679 while( SQLITE_ROW==sqlite3_step(pSql) ){
6680 int res = -1;
6681 sqlite3_stmt *pExplain = 0;
6682 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6683 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6684 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6685 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6686 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6687 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6689 if( zEQP==0 ) continue;
6690 if( zGlob==0 ) continue;
6691 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6692 if( rc!=SQLITE_OK ) break;
6693 if( SQLITE_ROW==sqlite3_step(pExplain) ){
6694 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6695 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
6696 || 0==sqlite3_strglob(zGlobIPK, zPlan));
6698 rc = sqlite3_finalize(pExplain);
6699 if( rc!=SQLITE_OK ) break;
6701 if( res<0 ){
6702 eputz("Error: internal error");
6703 break;
6704 }else{
6705 if( bGroupByParent
6706 && (bVerbose || res==0)
6707 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6709 oputf("-- Parent table %s\n", zParent);
6710 sqlite3_free(zPrev);
6711 zPrev = sqlite3_mprintf("%s", zParent);
6714 if( res==0 ){
6715 oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
6716 }else if( bVerbose ){
6717 oputf("%s/* no extra indexes required for %s -> %s */\n",
6718 zIndent, zFrom, zTarget
6723 sqlite3_free(zPrev);
6725 if( rc!=SQLITE_OK ){
6726 eputf("%s\n", sqlite3_errmsg(db));
6729 rc2 = sqlite3_finalize(pSql);
6730 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6731 rc = rc2;
6732 eputf("%s\n", sqlite3_errmsg(db));
6734 }else{
6735 eputf("%s\n", sqlite3_errmsg(db));
6738 return rc;
6742 ** Implementation of ".lint" dot command.
6744 static int lintDotCommand(
6745 ShellState *pState, /* Current shell tool state */
6746 char **azArg, /* Array of arguments passed to dot command */
6747 int nArg /* Number of entries in azArg[] */
6749 int n;
6750 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6751 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6752 return lintFkeyIndexes(pState, azArg, nArg);
6754 usage:
6755 eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
6756 eputz("Where sub-commands are:\n");
6757 eputz(" fkey-indexes\n");
6758 return SQLITE_ERROR;
6761 static void shellPrepare(
6762 sqlite3 *db,
6763 int *pRc,
6764 const char *zSql,
6765 sqlite3_stmt **ppStmt
6767 *ppStmt = 0;
6768 if( *pRc==SQLITE_OK ){
6769 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6770 if( rc!=SQLITE_OK ){
6771 eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
6772 *pRc = rc;
6778 ** Create a prepared statement using printf-style arguments for the SQL.
6780 static void shellPreparePrintf(
6781 sqlite3 *db,
6782 int *pRc,
6783 sqlite3_stmt **ppStmt,
6784 const char *zFmt,
6787 *ppStmt = 0;
6788 if( *pRc==SQLITE_OK ){
6789 va_list ap;
6790 char *z;
6791 va_start(ap, zFmt);
6792 z = sqlite3_vmprintf(zFmt, ap);
6793 va_end(ap);
6794 if( z==0 ){
6795 *pRc = SQLITE_NOMEM;
6796 }else{
6797 shellPrepare(db, pRc, z, ppStmt);
6798 sqlite3_free(z);
6804 ** Finalize the prepared statement created using shellPreparePrintf().
6806 static void shellFinalize(
6807 int *pRc,
6808 sqlite3_stmt *pStmt
6810 if( pStmt ){
6811 sqlite3 *db = sqlite3_db_handle(pStmt);
6812 int rc = sqlite3_finalize(pStmt);
6813 if( *pRc==SQLITE_OK ){
6814 if( rc!=SQLITE_OK ){
6815 eputf("SQL error: %s\n", sqlite3_errmsg(db));
6817 *pRc = rc;
6822 #if !defined SQLITE_OMIT_VIRTUALTABLE
6823 /* Reset the prepared statement created using shellPreparePrintf().
6825 ** This routine is could be marked "static". But it is not always used,
6826 ** depending on compile-time options. By omitting the "static", we avoid
6827 ** nuisance compiler warnings about "defined but not used".
6829 void shellReset(
6830 int *pRc,
6831 sqlite3_stmt *pStmt
6833 int rc = sqlite3_reset(pStmt);
6834 if( *pRc==SQLITE_OK ){
6835 if( rc!=SQLITE_OK ){
6836 sqlite3 *db = sqlite3_db_handle(pStmt);
6837 eputf("SQL error: %s\n", sqlite3_errmsg(db));
6839 *pRc = rc;
6842 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6844 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6845 /******************************************************************************
6846 ** The ".archive" or ".ar" command.
6849 ** Structure representing a single ".ar" command.
6851 typedef struct ArCommand ArCommand;
6852 struct ArCommand {
6853 u8 eCmd; /* An AR_CMD_* value */
6854 u8 bVerbose; /* True if --verbose */
6855 u8 bZip; /* True if the archive is a ZIP */
6856 u8 bDryRun; /* True if --dry-run */
6857 u8 bAppend; /* True if --append */
6858 u8 bGlob; /* True if --glob */
6859 u8 fromCmdLine; /* Run from -A instead of .archive */
6860 int nArg; /* Number of command arguments */
6861 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6862 const char *zFile; /* --file argument, or NULL */
6863 const char *zDir; /* --directory argument, or NULL */
6864 char **azArg; /* Array of command arguments */
6865 ShellState *p; /* Shell state */
6866 sqlite3 *db; /* Database containing the archive */
6870 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6872 static int arUsage(FILE *f){
6873 showHelp(f,"archive");
6874 return SQLITE_ERROR;
6878 ** Print an error message for the .ar command to stderr and return
6879 ** SQLITE_ERROR.
6881 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6882 va_list ap;
6883 char *z;
6884 va_start(ap, zFmt);
6885 z = sqlite3_vmprintf(zFmt, ap);
6886 va_end(ap);
6887 eputf("Error: %s\n", z);
6888 if( pAr->fromCmdLine ){
6889 eputz("Use \"-A\" for more help\n");
6890 }else{
6891 eputz("Use \".archive --help\" for more help\n");
6893 sqlite3_free(z);
6894 return SQLITE_ERROR;
6898 ** Values for ArCommand.eCmd.
6900 #define AR_CMD_CREATE 1
6901 #define AR_CMD_UPDATE 2
6902 #define AR_CMD_INSERT 3
6903 #define AR_CMD_EXTRACT 4
6904 #define AR_CMD_LIST 5
6905 #define AR_CMD_HELP 6
6906 #define AR_CMD_REMOVE 7
6909 ** Other (non-command) switches.
6911 #define AR_SWITCH_VERBOSE 8
6912 #define AR_SWITCH_FILE 9
6913 #define AR_SWITCH_DIRECTORY 10
6914 #define AR_SWITCH_APPEND 11
6915 #define AR_SWITCH_DRYRUN 12
6916 #define AR_SWITCH_GLOB 13
6918 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6919 switch( eSwitch ){
6920 case AR_CMD_CREATE:
6921 case AR_CMD_EXTRACT:
6922 case AR_CMD_LIST:
6923 case AR_CMD_REMOVE:
6924 case AR_CMD_UPDATE:
6925 case AR_CMD_INSERT:
6926 case AR_CMD_HELP:
6927 if( pAr->eCmd ){
6928 return arErrorMsg(pAr, "multiple command options");
6930 pAr->eCmd = eSwitch;
6931 break;
6933 case AR_SWITCH_DRYRUN:
6934 pAr->bDryRun = 1;
6935 break;
6936 case AR_SWITCH_GLOB:
6937 pAr->bGlob = 1;
6938 break;
6939 case AR_SWITCH_VERBOSE:
6940 pAr->bVerbose = 1;
6941 break;
6942 case AR_SWITCH_APPEND:
6943 pAr->bAppend = 1;
6944 deliberate_fall_through;
6945 case AR_SWITCH_FILE:
6946 pAr->zFile = zArg;
6947 break;
6948 case AR_SWITCH_DIRECTORY:
6949 pAr->zDir = zArg;
6950 break;
6953 return SQLITE_OK;
6957 ** Parse the command line for an ".ar" command. The results are written into
6958 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6959 ** successfully, otherwise an error message is written to stderr and
6960 ** SQLITE_ERROR returned.
6962 static int arParseCommand(
6963 char **azArg, /* Array of arguments passed to dot command */
6964 int nArg, /* Number of entries in azArg[] */
6965 ArCommand *pAr /* Populate this object */
6967 struct ArSwitch {
6968 const char *zLong;
6969 char cShort;
6970 u8 eSwitch;
6971 u8 bArg;
6972 } aSwitch[] = {
6973 { "create", 'c', AR_CMD_CREATE, 0 },
6974 { "extract", 'x', AR_CMD_EXTRACT, 0 },
6975 { "insert", 'i', AR_CMD_INSERT, 0 },
6976 { "list", 't', AR_CMD_LIST, 0 },
6977 { "remove", 'r', AR_CMD_REMOVE, 0 },
6978 { "update", 'u', AR_CMD_UPDATE, 0 },
6979 { "help", 'h', AR_CMD_HELP, 0 },
6980 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
6981 { "file", 'f', AR_SWITCH_FILE, 1 },
6982 { "append", 'a', AR_SWITCH_APPEND, 1 },
6983 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6984 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
6985 { "glob", 'g', AR_SWITCH_GLOB, 0 },
6987 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6988 struct ArSwitch *pEnd = &aSwitch[nSwitch];
6990 if( nArg<=1 ){
6991 eputz("Wrong number of arguments. Usage:\n");
6992 return arUsage(stderr);
6993 }else{
6994 char *z = azArg[1];
6995 if( z[0]!='-' ){
6996 /* Traditional style [tar] invocation */
6997 int i;
6998 int iArg = 2;
6999 for(i=0; z[i]; i++){
7000 const char *zArg = 0;
7001 struct ArSwitch *pOpt;
7002 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7003 if( z[i]==pOpt->cShort ) break;
7005 if( pOpt==pEnd ){
7006 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
7008 if( pOpt->bArg ){
7009 if( iArg>=nArg ){
7010 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
7012 zArg = azArg[iArg++];
7014 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7016 pAr->nArg = nArg-iArg;
7017 if( pAr->nArg>0 ){
7018 pAr->azArg = &azArg[iArg];
7020 }else{
7021 /* Non-traditional invocation */
7022 int iArg;
7023 for(iArg=1; iArg<nArg; iArg++){
7024 int n;
7025 z = azArg[iArg];
7026 if( z[0]!='-' ){
7027 /* All remaining command line words are command arguments. */
7028 pAr->azArg = &azArg[iArg];
7029 pAr->nArg = nArg-iArg;
7030 break;
7032 n = strlen30(z);
7034 if( z[1]!='-' ){
7035 int i;
7036 /* One or more short options */
7037 for(i=1; i<n; i++){
7038 const char *zArg = 0;
7039 struct ArSwitch *pOpt;
7040 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7041 if( z[i]==pOpt->cShort ) break;
7043 if( pOpt==pEnd ){
7044 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
7046 if( pOpt->bArg ){
7047 if( i<(n-1) ){
7048 zArg = &z[i+1];
7049 i = n;
7050 }else{
7051 if( iArg>=(nArg-1) ){
7052 return arErrorMsg(pAr, "option requires an argument: %c",
7053 z[i]);
7055 zArg = azArg[++iArg];
7058 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7060 }else if( z[2]=='\0' ){
7061 /* A -- option, indicating that all remaining command line words
7062 ** are command arguments. */
7063 pAr->azArg = &azArg[iArg+1];
7064 pAr->nArg = nArg-iArg-1;
7065 break;
7066 }else{
7067 /* A long option */
7068 const char *zArg = 0; /* Argument for option, if any */
7069 struct ArSwitch *pMatch = 0; /* Matching option */
7070 struct ArSwitch *pOpt; /* Iterator */
7071 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7072 const char *zLong = pOpt->zLong;
7073 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
7074 if( pMatch ){
7075 return arErrorMsg(pAr, "ambiguous option: %s",z);
7076 }else{
7077 pMatch = pOpt;
7082 if( pMatch==0 ){
7083 return arErrorMsg(pAr, "unrecognized option: %s", z);
7085 if( pMatch->bArg ){
7086 if( iArg>=(nArg-1) ){
7087 return arErrorMsg(pAr, "option requires an argument: %s", z);
7089 zArg = azArg[++iArg];
7091 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
7096 if( pAr->eCmd==0 ){
7097 eputz("Required argument missing. Usage:\n");
7098 return arUsage(stderr);
7100 return SQLITE_OK;
7104 ** This function assumes that all arguments within the ArCommand.azArg[]
7105 ** array refer to archive members, as for the --extract, --list or --remove
7106 ** commands. It checks that each of them are "present". If any specified
7107 ** file is not present in the archive, an error is printed to stderr and an
7108 ** error code returned. Otherwise, if all specified arguments are present
7109 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7110 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7111 ** when pAr->bGlob is true.
7113 ** This function strips any trailing '/' characters from each argument.
7114 ** This is consistent with the way the [tar] command seems to work on
7115 ** Linux.
7117 static int arCheckEntries(ArCommand *pAr){
7118 int rc = SQLITE_OK;
7119 if( pAr->nArg ){
7120 int i, j;
7121 sqlite3_stmt *pTest = 0;
7122 const char *zSel = (pAr->bGlob)
7123 ? "SELECT name FROM %s WHERE glob($name,name)"
7124 : "SELECT name FROM %s WHERE name=$name";
7126 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
7127 j = sqlite3_bind_parameter_index(pTest, "$name");
7128 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7129 char *z = pAr->azArg[i];
7130 int n = strlen30(z);
7131 int bOk = 0;
7132 while( n>0 && z[n-1]=='/' ) n--;
7133 z[n] = '\0';
7134 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
7135 if( SQLITE_ROW==sqlite3_step(pTest) ){
7136 bOk = 1;
7138 shellReset(&rc, pTest);
7139 if( rc==SQLITE_OK && bOk==0 ){
7140 eputf("not found in archive: %s\n", z);
7141 rc = SQLITE_ERROR;
7144 shellFinalize(&rc, pTest);
7146 return rc;
7150 ** Format a WHERE clause that can be used against the "sqlar" table to
7151 ** identify all archive members that match the command arguments held
7152 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7153 ** The caller is responsible for eventually calling sqlite3_free() on
7154 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7155 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7157 static void arWhereClause(
7158 int *pRc,
7159 ArCommand *pAr,
7160 char **pzWhere /* OUT: New WHERE clause */
7162 char *zWhere = 0;
7163 const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
7164 if( *pRc==SQLITE_OK ){
7165 if( pAr->nArg==0 ){
7166 zWhere = sqlite3_mprintf("1");
7167 }else{
7168 int i;
7169 const char *zSep = "";
7170 for(i=0; i<pAr->nArg; i++){
7171 const char *z = pAr->azArg[i];
7172 zWhere = sqlite3_mprintf(
7173 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7174 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
7176 if( zWhere==0 ){
7177 *pRc = SQLITE_NOMEM;
7178 break;
7180 zSep = " OR ";
7184 *pzWhere = zWhere;
7188 ** Implementation of .ar "lisT" command.
7190 static int arListCommand(ArCommand *pAr){
7191 const char *zSql = "SELECT %s FROM %s WHERE %s";
7192 const char *azCols[] = {
7193 "name",
7194 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7197 char *zWhere = 0;
7198 sqlite3_stmt *pSql = 0;
7199 int rc;
7201 rc = arCheckEntries(pAr);
7202 arWhereClause(&rc, pAr, &zWhere);
7204 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
7205 pAr->zSrcTable, zWhere);
7206 if( pAr->bDryRun ){
7207 oputf("%s\n", sqlite3_sql(pSql));
7208 }else{
7209 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7210 if( pAr->bVerbose ){
7211 oputf("%s % 10d %s %s\n",
7212 sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
7213 sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
7214 }else{
7215 oputf("%s\n", sqlite3_column_text(pSql, 0));
7219 shellFinalize(&rc, pSql);
7220 sqlite3_free(zWhere);
7221 return rc;
7225 ** Implementation of .ar "Remove" command.
7227 static int arRemoveCommand(ArCommand *pAr){
7228 int rc = 0;
7229 char *zSql = 0;
7230 char *zWhere = 0;
7232 if( pAr->nArg ){
7233 /* Verify that args actually exist within the archive before proceeding.
7234 ** And formulate a WHERE clause to match them. */
7235 rc = arCheckEntries(pAr);
7236 arWhereClause(&rc, pAr, &zWhere);
7238 if( rc==SQLITE_OK ){
7239 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7240 pAr->zSrcTable, zWhere);
7241 if( pAr->bDryRun ){
7242 oputf("%s\n", zSql);
7243 }else{
7244 char *zErr = 0;
7245 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
7246 if( rc==SQLITE_OK ){
7247 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7248 if( rc!=SQLITE_OK ){
7249 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7250 }else{
7251 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
7254 if( zErr ){
7255 sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
7256 sqlite3_free(zErr);
7260 sqlite3_free(zWhere);
7261 sqlite3_free(zSql);
7262 return rc;
7266 ** Implementation of .ar "eXtract" command.
7268 static int arExtractCommand(ArCommand *pAr){
7269 const char *zSql1 =
7270 "SELECT "
7271 " ($dir || name),"
7272 " writefile(($dir || name), %s, mode, mtime) "
7273 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7274 " AND name NOT GLOB '*..[/\\]*'";
7276 const char *azExtraArg[] = {
7277 "sqlar_uncompress(data, sz)",
7278 "data"
7281 sqlite3_stmt *pSql = 0;
7282 int rc = SQLITE_OK;
7283 char *zDir = 0;
7284 char *zWhere = 0;
7285 int i, j;
7287 /* If arguments are specified, check that they actually exist within
7288 ** the archive before proceeding. And formulate a WHERE clause to
7289 ** match them. */
7290 rc = arCheckEntries(pAr);
7291 arWhereClause(&rc, pAr, &zWhere);
7293 if( rc==SQLITE_OK ){
7294 if( pAr->zDir ){
7295 zDir = sqlite3_mprintf("%s/", pAr->zDir);
7296 }else{
7297 zDir = sqlite3_mprintf("");
7299 if( zDir==0 ) rc = SQLITE_NOMEM;
7302 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
7303 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
7306 if( rc==SQLITE_OK ){
7307 j = sqlite3_bind_parameter_index(pSql, "$dir");
7308 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
7310 /* Run the SELECT statement twice. The first time, writefile() is called
7311 ** for all archive members that should be extracted. The second time,
7312 ** only for the directories. This is because the timestamps for
7313 ** extracted directories must be reset after they are populated (as
7314 ** populating them changes the timestamp). */
7315 for(i=0; i<2; i++){
7316 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
7317 sqlite3_bind_int(pSql, j, i);
7318 if( pAr->bDryRun ){
7319 oputf("%s\n", sqlite3_sql(pSql));
7320 }else{
7321 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7322 if( i==0 && pAr->bVerbose ){
7323 oputf("%s\n", sqlite3_column_text(pSql, 0));
7327 shellReset(&rc, pSql);
7329 shellFinalize(&rc, pSql);
7332 sqlite3_free(zDir);
7333 sqlite3_free(zWhere);
7334 return rc;
7338 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7340 static int arExecSql(ArCommand *pAr, const char *zSql){
7341 int rc;
7342 if( pAr->bDryRun ){
7343 oputf("%s\n", zSql);
7344 rc = SQLITE_OK;
7345 }else{
7346 char *zErr = 0;
7347 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7348 if( zErr ){
7349 sputf(stdout, "ERROR: %s\n", zErr);
7350 sqlite3_free(zErr);
7353 return rc;
7358 ** Implementation of .ar "create", "insert", and "update" commands.
7360 ** create -> Create a new SQL archive
7361 ** insert -> Insert or reinsert all files listed
7362 ** update -> Insert files that have changed or that were not
7363 ** previously in the archive
7365 ** Create the "sqlar" table in the database if it does not already exist.
7366 ** Then add each file in the azFile[] array to the archive. Directories
7367 ** are added recursively. If argument bVerbose is non-zero, a message is
7368 ** printed on stdout for each file archived.
7370 ** The create command is the same as update, except that it drops
7371 ** any existing "sqlar" table before beginning. The "insert" command
7372 ** always overwrites every file named on the command-line, where as
7373 ** "update" only overwrites if the size or mtime or mode has changed.
7375 static int arCreateOrUpdateCommand(
7376 ArCommand *pAr, /* Command arguments and options */
7377 int bUpdate, /* true for a --create. */
7378 int bOnlyIfChanged /* Only update if file has changed */
7380 const char *zCreate =
7381 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7382 " name TEXT PRIMARY KEY, -- name of the file\n"
7383 " mode INT, -- access permissions\n"
7384 " mtime INT, -- last modification time\n"
7385 " sz INT, -- original file size\n"
7386 " data BLOB -- compressed content\n"
7387 ")";
7388 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7389 const char *zInsertFmt[2] = {
7390 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7391 " SELECT\n"
7392 " %s,\n"
7393 " mode,\n"
7394 " mtime,\n"
7395 " CASE substr(lsmode(mode),1,1)\n"
7396 " WHEN '-' THEN length(data)\n"
7397 " WHEN 'd' THEN 0\n"
7398 " ELSE -1 END,\n"
7399 " sqlar_compress(data)\n"
7400 " FROM fsdir(%Q,%Q) AS disk\n"
7401 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7403 "REPLACE INTO %s(name,mode,mtime,data)\n"
7404 " SELECT\n"
7405 " %s,\n"
7406 " mode,\n"
7407 " mtime,\n"
7408 " data\n"
7409 " FROM fsdir(%Q,%Q) AS disk\n"
7410 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7412 int i; /* For iterating through azFile[] */
7413 int rc; /* Return code */
7414 const char *zTab = 0; /* SQL table into which to insert */
7415 char *zSql;
7416 char zTemp[50];
7417 char *zExists = 0;
7419 arExecSql(pAr, "PRAGMA page_size=512");
7420 rc = arExecSql(pAr, "SAVEPOINT ar;");
7421 if( rc!=SQLITE_OK ) return rc;
7422 zTemp[0] = 0;
7423 if( pAr->bZip ){
7424 /* Initialize the zipfile virtual table, if necessary */
7425 if( pAr->zFile ){
7426 sqlite3_uint64 r;
7427 sqlite3_randomness(sizeof(r),&r);
7428 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7429 zTab = zTemp;
7430 zSql = sqlite3_mprintf(
7431 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7432 zTab, pAr->zFile
7434 rc = arExecSql(pAr, zSql);
7435 sqlite3_free(zSql);
7436 }else{
7437 zTab = "zip";
7439 }else{
7440 /* Initialize the table for an SQLAR */
7441 zTab = "sqlar";
7442 if( bUpdate==0 ){
7443 rc = arExecSql(pAr, zDrop);
7444 if( rc!=SQLITE_OK ) goto end_ar_transaction;
7446 rc = arExecSql(pAr, zCreate);
7448 if( bOnlyIfChanged ){
7449 zExists = sqlite3_mprintf(
7450 " AND NOT EXISTS("
7451 "SELECT 1 FROM %s AS mem"
7452 " WHERE mem.name=disk.name"
7453 " AND mem.mtime=disk.mtime"
7454 " AND mem.mode=disk.mode)", zTab);
7455 }else{
7456 zExists = sqlite3_mprintf("");
7458 if( zExists==0 ) rc = SQLITE_NOMEM;
7459 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7460 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7461 pAr->bVerbose ? "shell_putsnl(name)" : "name",
7462 pAr->azArg[i], pAr->zDir, zExists);
7463 rc = arExecSql(pAr, zSql2);
7464 sqlite3_free(zSql2);
7466 end_ar_transaction:
7467 if( rc!=SQLITE_OK ){
7468 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7469 }else{
7470 rc = arExecSql(pAr, "RELEASE ar;");
7471 if( pAr->bZip && pAr->zFile ){
7472 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7473 arExecSql(pAr, zSql);
7474 sqlite3_free(zSql);
7477 sqlite3_free(zExists);
7478 return rc;
7482 ** Implementation of ".ar" dot command.
7484 static int arDotCommand(
7485 ShellState *pState, /* Current shell tool state */
7486 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
7487 char **azArg, /* Array of arguments passed to dot command */
7488 int nArg /* Number of entries in azArg[] */
7490 ArCommand cmd;
7491 int rc;
7492 memset(&cmd, 0, sizeof(cmd));
7493 cmd.fromCmdLine = fromCmdLine;
7494 rc = arParseCommand(azArg, nArg, &cmd);
7495 if( rc==SQLITE_OK ){
7496 int eDbType = SHELL_OPEN_UNSPEC;
7497 cmd.p = pState;
7498 cmd.db = pState->db;
7499 if( cmd.zFile ){
7500 eDbType = deduceDatabaseType(cmd.zFile, 1);
7501 }else{
7502 eDbType = pState->openMode;
7504 if( eDbType==SHELL_OPEN_ZIPFILE ){
7505 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7506 if( cmd.zFile==0 ){
7507 cmd.zSrcTable = sqlite3_mprintf("zip");
7508 }else{
7509 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7512 cmd.bZip = 1;
7513 }else if( cmd.zFile ){
7514 int flags;
7515 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7516 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7517 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7518 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7519 }else{
7520 flags = SQLITE_OPEN_READONLY;
7522 cmd.db = 0;
7523 if( cmd.bDryRun ){
7524 oputf("-- open database '%s'%s\n", cmd.zFile,
7525 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7527 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7528 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7529 if( rc!=SQLITE_OK ){
7530 eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
7531 goto end_ar_command;
7533 sqlite3_fileio_init(cmd.db, 0, 0);
7534 sqlite3_sqlar_init(cmd.db, 0, 0);
7535 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7536 shellPutsFunc, 0, 0);
7539 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7540 if( cmd.eCmd!=AR_CMD_CREATE
7541 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7543 eputz("database does not contain an 'sqlar' table\n");
7544 rc = SQLITE_ERROR;
7545 goto end_ar_command;
7547 cmd.zSrcTable = sqlite3_mprintf("sqlar");
7550 switch( cmd.eCmd ){
7551 case AR_CMD_CREATE:
7552 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7553 break;
7555 case AR_CMD_EXTRACT:
7556 rc = arExtractCommand(&cmd);
7557 break;
7559 case AR_CMD_LIST:
7560 rc = arListCommand(&cmd);
7561 break;
7563 case AR_CMD_HELP:
7564 arUsage(pState->out);
7565 break;
7567 case AR_CMD_INSERT:
7568 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7569 break;
7571 case AR_CMD_REMOVE:
7572 rc = arRemoveCommand(&cmd);
7573 break;
7575 default:
7576 assert( cmd.eCmd==AR_CMD_UPDATE );
7577 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7578 break;
7581 end_ar_command:
7582 if( cmd.db!=pState->db ){
7583 close_db(cmd.db);
7585 sqlite3_free(cmd.zSrcTable);
7587 return rc;
7589 /* End of the ".archive" or ".ar" command logic
7590 *******************************************************************************/
7591 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7593 #if SQLITE_SHELL_HAVE_RECOVER
7596 ** This function is used as a callback by the recover extension. Simply
7597 ** print the supplied SQL statement to stdout.
7599 static int recoverSqlCb(void *pCtx, const char *zSql){
7600 ShellState *pState = (ShellState*)pCtx;
7601 sputf(pState->out, "%s;\n", zSql);
7602 return SQLITE_OK;
7606 ** This function is called to recover data from the database. A script
7607 ** to construct a new database containing all recovered data is output
7608 ** on stream pState->out.
7610 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7611 int rc = SQLITE_OK;
7612 const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
7613 const char *zLAF = "lost_and_found";
7614 int bFreelist = 1; /* 0 if --ignore-freelist is specified */
7615 int bRowids = 1; /* 0 if --no-rowids */
7616 sqlite3_recover *p = 0;
7617 int i = 0;
7619 for(i=1; i<nArg; i++){
7620 char *z = azArg[i];
7621 int n;
7622 if( z[0]=='-' && z[1]=='-' ) z++;
7623 n = strlen30(z);
7624 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
7625 bFreelist = 0;
7626 }else
7627 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7628 /* This option determines the name of the ATTACH-ed database used
7629 ** internally by the recovery extension. The default is "" which
7630 ** means to use a temporary database that is automatically deleted
7631 ** when closed. This option is undocumented and might disappear at
7632 ** any moment. */
7633 i++;
7634 zRecoveryDb = azArg[i];
7635 }else
7636 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7637 i++;
7638 zLAF = azArg[i];
7639 }else
7640 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7641 bRowids = 0;
7643 else{
7644 eputf("unexpected option: %s\n", azArg[i]);
7645 showHelp(pState->out, azArg[0]);
7646 return 1;
7650 p = sqlite3_recover_init_sql(
7651 pState->db, "main", recoverSqlCb, (void*)pState
7654 sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */
7655 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7656 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7657 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7659 sqlite3_recover_run(p);
7660 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7661 const char *zErr = sqlite3_recover_errmsg(p);
7662 int errCode = sqlite3_recover_errcode(p);
7663 eputf("sql error: %s (%d)\n", zErr, errCode);
7665 rc = sqlite3_recover_finish(p);
7666 return rc;
7668 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7671 ** Implementation of ".intck STEPS_PER_UNLOCK" command.
7673 static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){
7674 sqlite3_intck *p = 0;
7675 int rc = SQLITE_OK;
7677 rc = sqlite3_intck_open(pState->db, "main", &p);
7678 if( rc==SQLITE_OK ){
7679 i64 nStep = 0;
7680 i64 nError = 0;
7681 const char *zErr = 0;
7682 while( SQLITE_OK==sqlite3_intck_step(p) ){
7683 const char *zMsg = sqlite3_intck_message(p);
7684 if( zMsg ){
7685 oputf("%s\n", zMsg);
7686 nError++;
7688 nStep++;
7689 if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){
7690 sqlite3_intck_unlock(p);
7693 rc = sqlite3_intck_error(p, &zErr);
7694 if( zErr ){
7695 eputf("%s\n", zErr);
7697 sqlite3_intck_close(p);
7699 oputf("%lld steps, %lld errors\n", nStep, nError);
7702 return rc;
7706 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7707 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7708 * close db and set it to 0, and return the columns spec, to later
7709 * be sqlite3_free()'ed by the caller.
7710 * The return is 0 when either:
7711 * (a) The db was not initialized and zCol==0 (There are no columns.)
7712 * (b) zCol!=0 (Column was added, db initialized as needed.)
7713 * The 3rd argument, pRenamed, references an out parameter. If the
7714 * pointer is non-zero, its referent will be set to a summary of renames
7715 * done if renaming was necessary, or set to 0 if none was done. The out
7716 * string (if any) must be sqlite3_free()'ed by the caller.
7718 #ifdef SHELL_DEBUG
7719 #define rc_err_oom_die(rc) \
7720 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7721 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7722 eputf("E:%d\n",rc), assert(0)
7723 #else
7724 static void rc_err_oom_die(int rc){
7725 if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7726 assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7728 #endif
7730 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7731 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7732 #else /* Otherwise, memory is faster/better for the transient DB. */
7733 static const char *zCOL_DB = ":memory:";
7734 #endif
7736 /* Define character (as C string) to separate generated column ordinal
7737 * from protected part of incoming column names. This defaults to "_"
7738 * so that incoming column identifiers that did not need not be quoted
7739 * remain usable without being quoted. It must be one character.
7741 #ifndef SHELL_AUTOCOLUMN_SEP
7742 # define AUTOCOLUMN_SEP "_"
7743 #else
7744 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7745 #endif
7747 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7748 /* Queries and D{D,M}L used here */
7749 static const char * const zTabMake = "\
7750 CREATE TABLE ColNames(\
7751 cpos INTEGER PRIMARY KEY,\
7752 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7753 CREATE VIEW RepeatedNames AS \
7754 SELECT DISTINCT t.name FROM ColNames t \
7755 WHERE t.name COLLATE NOCASE IN (\
7756 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7759 static const char * const zTabFill = "\
7760 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7761 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7763 static const char * const zHasDupes = "\
7764 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7765 <count(name) FROM ColNames\
7767 #ifdef SHELL_COLUMN_RENAME_CLEAN
7768 static const char * const zDedoctor = "\
7769 UPDATE ColNames SET chop=iif(\
7770 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7771 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7772 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7776 #endif
7777 static const char * const zSetReps = "\
7778 UPDATE ColNames AS t SET reps=\
7779 (SELECT count(*) FROM ColNames d \
7780 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7781 COLLATE NOCASE\
7784 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7785 static const char * const zColDigits = "\
7786 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7788 #else
7789 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7790 static const char * const zColDigits = "\
7791 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7792 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7793 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7795 #endif
7796 static const char * const zRenameRank =
7797 #ifdef SHELL_COLUMN_RENAME_CLEAN
7798 "UPDATE ColNames AS t SET suff="
7799 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7800 #else /* ...RENAME_MINIMAL_ONE_PASS */
7801 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7802 " SELECT 0 AS nlz"
7803 " UNION"
7804 " SELECT nlz+1 AS nlz FROM Lzn"
7805 " WHERE EXISTS("
7806 " SELECT 1"
7807 " FROM ColNames t, ColNames o"
7808 " WHERE"
7809 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7810 " printf('%s"AUTOCOLUMN_SEP"%s',"
7811 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7812 " t.name"
7813 " )"
7814 " ="
7815 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7816 " printf('%s"AUTOCOLUMN_SEP"%s',"
7817 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7818 " o.name"
7819 " )"
7820 " COLLATE NOCASE"
7821 " AND o.cpos<>t.cpos"
7822 " GROUP BY t.cpos"
7823 " )"
7824 ") UPDATE Colnames AS t SET"
7825 " chop = 0," /* No chopping, never touch incoming names. */
7826 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7827 " printf('"AUTOCOLUMN_SEP"%s', substring("
7828 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7829 " ''"
7830 " )"
7831 #endif
7833 static const char * const zCollectVar = "\
7834 SELECT\
7835 '('||x'0a'\
7836 || group_concat(\
7837 cname||' TEXT',\
7838 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7839 ||')' AS ColsSpec \
7840 FROM (\
7841 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7842 FROM ColNames ORDER BY cpos\
7844 static const char * const zRenamesDone =
7845 "SELECT group_concat("
7846 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7847 " ','||x'0a')"
7848 "FROM ColNames WHERE suff<>'' OR chop!=0"
7850 int rc;
7851 sqlite3_stmt *pStmt = 0;
7852 assert(pDb!=0);
7853 if( zColNew ){
7854 /* Add initial or additional column. Init db if necessary. */
7855 if( *pDb==0 ){
7856 if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7857 #ifdef SHELL_COLFIX_DB
7858 if(*zCOL_DB!=':')
7859 sqlite3_exec(*pDb,"drop table if exists ColNames;"
7860 "drop view if exists RepeatedNames;",0,0,0);
7861 #endif
7862 #undef SHELL_COLFIX_DB
7863 rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7864 rc_err_oom_die(rc);
7866 assert(*pDb!=0);
7867 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7868 rc_err_oom_die(rc);
7869 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7870 rc_err_oom_die(rc);
7871 rc = sqlite3_step(pStmt);
7872 rc_err_oom_die(rc);
7873 sqlite3_finalize(pStmt);
7874 return 0;
7875 }else if( *pDb==0 ){
7876 return 0;
7877 }else{
7878 /* Formulate the columns spec, close the DB, zero *pDb. */
7879 char *zColsSpec = 0;
7880 int hasDupes = db_int(*pDb, zHasDupes);
7881 int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7882 if( hasDupes ){
7883 #ifdef SHELL_COLUMN_RENAME_CLEAN
7884 rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7885 rc_err_oom_die(rc);
7886 #endif
7887 rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7888 rc_err_oom_die(rc);
7889 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7890 rc_err_oom_die(rc);
7891 sqlite3_bind_int(pStmt, 1, nDigits);
7892 rc = sqlite3_step(pStmt);
7893 sqlite3_finalize(pStmt);
7894 if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
7896 assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7897 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7898 rc_err_oom_die(rc);
7899 rc = sqlite3_step(pStmt);
7900 if( rc==SQLITE_ROW ){
7901 zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7902 }else{
7903 zColsSpec = 0;
7905 if( pzRenamed!=0 ){
7906 if( !hasDupes ) *pzRenamed = 0;
7907 else{
7908 sqlite3_finalize(pStmt);
7909 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7910 && SQLITE_ROW==sqlite3_step(pStmt) ){
7911 *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7912 }else
7913 *pzRenamed = 0;
7916 sqlite3_finalize(pStmt);
7917 sqlite3_close(*pDb);
7918 *pDb = 0;
7919 return zColsSpec;
7924 ** Check if the sqlite_schema table contains one or more virtual tables. If
7925 ** parameter zLike is not NULL, then it is an SQL expression that the
7926 ** sqlite_schema row must also match. If one or more such rows are found,
7927 ** print the following warning to the output:
7929 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
7931 static int outputDumpWarning(ShellState *p, const char *zLike){
7932 int rc = SQLITE_OK;
7933 sqlite3_stmt *pStmt = 0;
7934 shellPreparePrintf(p->db, &rc, &pStmt,
7935 "SELECT 1 FROM sqlite_schema o WHERE "
7936 "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
7938 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7939 oputz("/* WARNING: "
7940 "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
7943 shellFinalize(&rc, pStmt);
7944 return rc;
7948 ** Fault-Simulator state and logic.
7950 static struct {
7951 int iId; /* ID that triggers a simulated fault. -1 means "any" */
7952 int iErr; /* The error code to return on a fault */
7953 int iCnt; /* Trigger the fault only if iCnt is already zero */
7954 int iInterval; /* Reset iCnt to this value after each fault */
7955 int eVerbose; /* When to print output */
7956 int nHit; /* Number of hits seen so far */
7957 int nRepeat; /* Turn off after this many hits. 0 for never */
7958 int nSkip; /* Skip this many before first fault */
7959 } faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
7962 ** This is the fault-sim callback
7964 static int faultsim_callback(int iArg){
7965 if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
7966 return SQLITE_OK;
7968 if( faultsim_state.iCnt ){
7969 if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--;
7970 if( faultsim_state.eVerbose>=2 ){
7971 oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
7973 return SQLITE_OK;
7975 if( faultsim_state.eVerbose>=1 ){
7976 oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
7978 faultsim_state.iCnt = faultsim_state.iInterval;
7979 faultsim_state.nHit++;
7980 if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){
7981 faultsim_state.iCnt = -1;
7983 return faultsim_state.iErr;
7987 ** If an input line begins with "." then invoke this routine to
7988 ** process that line.
7990 ** Return 1 on error, 2 to exit, and 0 otherwise.
7992 static int do_meta_command(char *zLine, ShellState *p){
7993 int h = 1;
7994 int nArg = 0;
7995 int n, c;
7996 int rc = 0;
7997 char *azArg[52];
7999 #ifndef SQLITE_OMIT_VIRTUALTABLE
8000 if( p->expert.pExpert ){
8001 expertFinish(p, 1, 0);
8003 #endif
8005 /* Parse the input line into tokens.
8007 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8008 while( IsSpace(zLine[h]) ){ h++; }
8009 if( zLine[h]==0 ) break;
8010 if( zLine[h]=='\'' || zLine[h]=='"' ){
8011 int delim = zLine[h++];
8012 azArg[nArg++] = &zLine[h];
8013 while( zLine[h] && zLine[h]!=delim ){
8014 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8015 h++;
8017 if( zLine[h]==delim ){
8018 zLine[h++] = 0;
8020 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8021 }else{
8022 azArg[nArg++] = &zLine[h];
8023 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8024 if( zLine[h] ) zLine[h++] = 0;
8027 azArg[nArg] = 0;
8029 /* Process the input line.
8031 if( nArg==0 ) return 0; /* no tokens, no error */
8032 n = strlen30(azArg[0]);
8033 c = azArg[0][0];
8034 clearTempFile(p);
8036 #ifndef SQLITE_OMIT_AUTHORIZATION
8037 if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
8038 if( nArg!=2 ){
8039 eputz("Usage: .auth ON|OFF\n");
8040 rc = 1;
8041 goto meta_command_exit;
8043 open_db(p, 0);
8044 if( booleanValue(azArg[1]) ){
8045 sqlite3_set_authorizer(p->db, shellAuth, p);
8046 }else if( p->bSafeModePersist ){
8047 sqlite3_set_authorizer(p->db, safeModeAuth, p);
8048 }else{
8049 sqlite3_set_authorizer(p->db, 0, 0);
8051 }else
8052 #endif
8054 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8055 && !defined(SQLITE_SHELL_FIDDLE)
8056 if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
8057 open_db(p, 0);
8058 failIfSafeMode(p, "cannot run .archive in safe mode");
8059 rc = arDotCommand(p, 0, azArg, nArg);
8060 }else
8061 #endif
8063 #ifndef SQLITE_SHELL_FIDDLE
8064 if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
8065 || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
8067 const char *zDestFile = 0;
8068 const char *zDb = 0;
8069 sqlite3 *pDest;
8070 sqlite3_backup *pBackup;
8071 int j;
8072 int bAsync = 0;
8073 const char *zVfs = 0;
8074 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8075 for(j=1; j<nArg; j++){
8076 const char *z = azArg[j];
8077 if( z[0]=='-' ){
8078 if( z[1]=='-' ) z++;
8079 if( cli_strcmp(z, "-append")==0 ){
8080 zVfs = "apndvfs";
8081 }else
8082 if( cli_strcmp(z, "-async")==0 ){
8083 bAsync = 1;
8084 }else
8086 eputf("unknown option: %s\n", azArg[j]);
8087 return 1;
8089 }else if( zDestFile==0 ){
8090 zDestFile = azArg[j];
8091 }else if( zDb==0 ){
8092 zDb = zDestFile;
8093 zDestFile = azArg[j];
8094 }else{
8095 eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8096 return 1;
8099 if( zDestFile==0 ){
8100 eputz("missing FILENAME argument on .backup\n");
8101 return 1;
8103 if( zDb==0 ) zDb = "main";
8104 rc = sqlite3_open_v2(zDestFile, &pDest,
8105 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8106 if( rc!=SQLITE_OK ){
8107 eputf("Error: cannot open \"%s\"\n", zDestFile);
8108 close_db(pDest);
8109 return 1;
8111 if( bAsync ){
8112 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8113 0, 0, 0);
8115 open_db(p, 0);
8116 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8117 if( pBackup==0 ){
8118 eputf("Error: %s\n", sqlite3_errmsg(pDest));
8119 close_db(pDest);
8120 return 1;
8122 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8123 sqlite3_backup_finish(pBackup);
8124 if( rc==SQLITE_DONE ){
8125 rc = 0;
8126 }else{
8127 eputf("Error: %s\n", sqlite3_errmsg(pDest));
8128 rc = 1;
8130 close_db(pDest);
8131 }else
8132 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8134 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
8135 if( nArg==2 ){
8136 bail_on_error = booleanValue(azArg[1]);
8137 }else{
8138 eputz("Usage: .bail on|off\n");
8139 rc = 1;
8141 }else
8143 /* Undocumented. Legacy only. See "crnl" below */
8144 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
8145 if( nArg==2 ){
8146 if( booleanValue(azArg[1]) ){
8147 setBinaryMode(p->out, 1);
8148 }else{
8149 setTextMode(p->out, 1);
8151 }else{
8152 eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
8153 "Usage: .binary on|off\n");
8154 rc = 1;
8156 }else
8158 /* The undocumented ".breakpoint" command causes a call to the no-op
8159 ** routine named test_breakpoint().
8161 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
8162 test_breakpoint();
8163 }else
8165 #ifndef SQLITE_SHELL_FIDDLE
8166 if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
8167 failIfSafeMode(p, "cannot run .cd in safe mode");
8168 if( nArg==2 ){
8169 #if defined(_WIN32) || defined(WIN32)
8170 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8171 rc = !SetCurrentDirectoryW(z);
8172 sqlite3_free(z);
8173 #else
8174 rc = chdir(azArg[1]);
8175 #endif
8176 if( rc ){
8177 eputf("Cannot change to directory \"%s\"\n", azArg[1]);
8178 rc = 1;
8180 }else{
8181 eputz("Usage: .cd DIRECTORY\n");
8182 rc = 1;
8184 }else
8185 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8187 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
8188 if( nArg==2 ){
8189 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8190 }else{
8191 eputz("Usage: .changes on|off\n");
8192 rc = 1;
8194 }else
8196 #ifndef SQLITE_SHELL_FIDDLE
8197 /* Cancel output redirection, if it is currently set (by .testcase)
8198 ** Then read the content of the testcase-out.txt file and compare against
8199 ** azArg[1]. If there are differences, report an error and exit.
8201 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
8202 char *zRes = 0;
8203 output_reset(p);
8204 if( nArg!=2 ){
8205 eputz("Usage: .check GLOB-PATTERN\n");
8206 rc = 2;
8207 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8208 rc = 2;
8209 }else if( testcase_glob(azArg[1],zRes)==0 ){
8210 eputf("testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8211 p->zTestcase, azArg[1], zRes);
8212 rc = 1;
8213 }else{
8214 oputf("testcase-%s ok\n", p->zTestcase);
8215 p->nCheck++;
8217 sqlite3_free(zRes);
8218 }else
8219 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8221 #ifndef SQLITE_SHELL_FIDDLE
8222 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
8223 failIfSafeMode(p, "cannot run .clone in safe mode");
8224 if( nArg==2 ){
8225 tryToClone(p, azArg[1]);
8226 }else{
8227 eputz("Usage: .clone FILENAME\n");
8228 rc = 1;
8230 }else
8231 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8233 if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
8234 if( nArg==1 ){
8235 /* List available connections */
8236 int i;
8237 for(i=0; i<ArraySize(p->aAuxDb); i++){
8238 const char *zFile = p->aAuxDb[i].zDbFilename;
8239 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8240 zFile = "(not open)";
8241 }else if( zFile==0 ){
8242 zFile = "(memory)";
8243 }else if( zFile[0]==0 ){
8244 zFile = "(temporary-file)";
8246 if( p->pAuxDb == &p->aAuxDb[i] ){
8247 sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
8248 }else if( p->aAuxDb[i].db!=0 ){
8249 sputf(stdout, " %d: %s\n", i, zFile);
8252 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8253 int i = azArg[1][0] - '0';
8254 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8255 p->pAuxDb->db = p->db;
8256 p->pAuxDb = &p->aAuxDb[i];
8257 globalDb = p->db = p->pAuxDb->db;
8258 p->pAuxDb->db = 0;
8260 }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
8261 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8262 int i = azArg[2][0] - '0';
8263 if( i<0 || i>=ArraySize(p->aAuxDb) ){
8264 /* No-op */
8265 }else if( p->pAuxDb == &p->aAuxDb[i] ){
8266 eputz("cannot close the active database connection\n");
8267 rc = 1;
8268 }else if( p->aAuxDb[i].db ){
8269 session_close_all(p, i);
8270 close_db(p->aAuxDb[i].db);
8271 p->aAuxDb[i].db = 0;
8273 }else{
8274 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
8275 rc = 1;
8277 }else
8279 if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
8280 if( nArg==2 ){
8281 if( booleanValue(azArg[1]) ){
8282 setTextMode(p->out, 1);
8283 }else{
8284 setBinaryMode(p->out, 1);
8286 }else{
8287 #if !defined(_WIN32) && !defined(WIN32)
8288 eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
8289 #endif
8290 eputz("Usage: .crnl on|off\n");
8291 rc = 1;
8293 }else
8295 if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
8296 char **azName = 0;
8297 int nName = 0;
8298 sqlite3_stmt *pStmt;
8299 int i;
8300 open_db(p, 0);
8301 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8302 if( rc ){
8303 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8304 rc = 1;
8305 }else{
8306 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8307 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8308 const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8309 if( zSchema==0 || zFile==0 ) continue;
8310 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8311 shell_check_oom(azName);
8312 azName[nName*2] = strdup(zSchema);
8313 azName[nName*2+1] = strdup(zFile);
8314 nName++;
8317 sqlite3_finalize(pStmt);
8318 for(i=0; i<nName; i++){
8319 int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8320 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8321 const char *z = azName[i*2+1];
8322 oputf("%s: %s %s%s\n",
8323 azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
8324 eTxn==SQLITE_TXN_NONE ? "" :
8325 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8326 free(azName[i*2]);
8327 free(azName[i*2+1]);
8329 sqlite3_free(azName);
8330 }else
8332 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
8333 static const struct DbConfigChoices {
8334 const char *zName;
8335 int op;
8336 } aDbConfig[] = {
8337 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
8338 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
8339 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
8340 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
8341 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
8342 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
8343 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
8344 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8345 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
8346 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
8347 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8348 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
8349 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
8350 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
8351 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
8352 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
8353 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
8354 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
8356 int ii, v;
8357 open_db(p, 0);
8358 for(ii=0; ii<ArraySize(aDbConfig); ii++){
8359 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8360 if( nArg>=3 ){
8361 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8363 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8364 oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8365 if( nArg>1 ) break;
8367 if( nArg>1 && ii==ArraySize(aDbConfig) ){
8368 eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
8369 eputz("Enter \".dbconfig\" with no arguments for a list\n");
8371 }else
8373 #if SQLITE_SHELL_HAVE_RECOVER
8374 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
8375 rc = shell_dbinfo_command(p, nArg, azArg);
8376 }else
8378 if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
8379 open_db(p, 0);
8380 rc = recoverDatabaseCmd(p, nArg, azArg);
8381 }else
8382 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8384 if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
8385 char *zLike = 0;
8386 char *zSql;
8387 int i;
8388 int savedShowHeader = p->showHeader;
8389 int savedShellFlags = p->shellFlgs;
8390 ShellClearFlag(p,
8391 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8392 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8393 for(i=1; i<nArg; i++){
8394 if( azArg[i][0]=='-' ){
8395 const char *z = azArg[i]+1;
8396 if( z[0]=='-' ) z++;
8397 if( cli_strcmp(z,"preserve-rowids")==0 ){
8398 #ifdef SQLITE_OMIT_VIRTUALTABLE
8399 eputz("The --preserve-rowids option is not compatible"
8400 " with SQLITE_OMIT_VIRTUALTABLE\n");
8401 rc = 1;
8402 sqlite3_free(zLike);
8403 goto meta_command_exit;
8404 #else
8405 ShellSetFlag(p, SHFLG_PreserveRowid);
8406 #endif
8407 }else
8408 if( cli_strcmp(z,"newlines")==0 ){
8409 ShellSetFlag(p, SHFLG_Newlines);
8410 }else
8411 if( cli_strcmp(z,"data-only")==0 ){
8412 ShellSetFlag(p, SHFLG_DumpDataOnly);
8413 }else
8414 if( cli_strcmp(z,"nosys")==0 ){
8415 ShellSetFlag(p, SHFLG_DumpNoSys);
8416 }else
8418 eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8419 rc = 1;
8420 sqlite3_free(zLike);
8421 goto meta_command_exit;
8423 }else{
8424 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8425 ** only dump data for tables for which either the table name matches
8426 ** the LIKE pattern, or the table appears to be a shadow table of
8427 ** a virtual table for which the name matches the LIKE pattern.
8429 char *zExpr = sqlite3_mprintf(
8430 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8431 " SELECT 1 FROM sqlite_schema WHERE "
8432 " name LIKE %Q ESCAPE '\\' AND"
8433 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8434 " substr(o.name, 1, length(name)+1) == (name||'_')"
8435 ")", azArg[i], azArg[i]
8438 if( zLike ){
8439 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8440 }else{
8441 zLike = zExpr;
8446 open_db(p, 0);
8448 outputDumpWarning(p, zLike);
8449 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8450 /* When playing back a "dump", the content might appear in an order
8451 ** which causes immediate foreign key constraints to be violated.
8452 ** So disable foreign-key constraint enforcement to prevent problems. */
8453 oputz("PRAGMA foreign_keys=OFF;\n");
8454 oputz("BEGIN TRANSACTION;\n");
8456 p->writableSchema = 0;
8457 p->showHeader = 0;
8458 /* Set writable_schema=ON since doing so forces SQLite to initialize
8459 ** as much of the schema as it can even if the sqlite_schema table is
8460 ** corrupt. */
8461 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8462 p->nErr = 0;
8463 if( zLike==0 ) zLike = sqlite3_mprintf("true");
8464 zSql = sqlite3_mprintf(
8465 "SELECT name, type, sql FROM sqlite_schema AS o "
8466 "WHERE (%s) AND type=='table'"
8467 " AND sql NOT NULL"
8468 " ORDER BY tbl_name='sqlite_sequence', rowid",
8469 zLike
8471 run_schema_dump_query(p,zSql);
8472 sqlite3_free(zSql);
8473 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8474 zSql = sqlite3_mprintf(
8475 "SELECT sql FROM sqlite_schema AS o "
8476 "WHERE (%s) AND sql NOT NULL"
8477 " AND type IN ('index','trigger','view') "
8478 "ORDER BY type COLLATE NOCASE DESC",
8479 zLike
8481 run_table_dump_query(p, zSql);
8482 sqlite3_free(zSql);
8484 sqlite3_free(zLike);
8485 if( p->writableSchema ){
8486 oputz("PRAGMA writable_schema=OFF;\n");
8487 p->writableSchema = 0;
8489 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8490 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8491 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8492 oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8494 p->showHeader = savedShowHeader;
8495 p->shellFlgs = savedShellFlags;
8496 }else
8498 if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
8499 if( nArg==2 ){
8500 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8501 }else{
8502 eputz("Usage: .echo on|off\n");
8503 rc = 1;
8505 }else
8507 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
8508 if( nArg==2 ){
8509 p->autoEQPtest = 0;
8510 if( p->autoEQPtrace ){
8511 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8512 p->autoEQPtrace = 0;
8514 if( cli_strcmp(azArg[1],"full")==0 ){
8515 p->autoEQP = AUTOEQP_full;
8516 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
8517 p->autoEQP = AUTOEQP_trigger;
8518 #ifdef SQLITE_DEBUG
8519 }else if( cli_strcmp(azArg[1],"test")==0 ){
8520 p->autoEQP = AUTOEQP_on;
8521 p->autoEQPtest = 1;
8522 }else if( cli_strcmp(azArg[1],"trace")==0 ){
8523 p->autoEQP = AUTOEQP_full;
8524 p->autoEQPtrace = 1;
8525 open_db(p, 0);
8526 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8527 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8528 #endif
8529 }else{
8530 p->autoEQP = (u8)booleanValue(azArg[1]);
8532 }else{
8533 eputz("Usage: .eqp off|on|trace|trigger|full\n");
8534 rc = 1;
8536 }else
8538 #ifndef SQLITE_SHELL_FIDDLE
8539 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
8540 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8541 rc = 2;
8542 }else
8543 #endif
8545 /* The ".explain" command is automatic now. It is largely pointless. It
8546 ** retained purely for backwards compatibility */
8547 if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
8548 int val = 1;
8549 if( nArg>=2 ){
8550 if( cli_strcmp(azArg[1],"auto")==0 ){
8551 val = 99;
8552 }else{
8553 val = booleanValue(azArg[1]);
8556 if( val==1 && p->mode!=MODE_Explain ){
8557 p->normalMode = p->mode;
8558 p->mode = MODE_Explain;
8559 p->autoExplain = 0;
8560 }else if( val==0 ){
8561 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8562 p->autoExplain = 0;
8563 }else if( val==99 ){
8564 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8565 p->autoExplain = 1;
8567 }else
8569 #ifndef SQLITE_OMIT_VIRTUALTABLE
8570 if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
8571 if( p->bSafeMode ){
8572 eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
8573 azArg[0]);
8574 rc = 1;
8575 }else{
8576 open_db(p, 0);
8577 expertDotCommand(p, azArg, nArg);
8579 }else
8580 #endif
8582 if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
8583 static const struct {
8584 const char *zCtrlName; /* Name of a test-control option */
8585 int ctrlCode; /* Integer code for that option */
8586 const char *zUsage; /* Usage notes */
8587 } aCtrl[] = {
8588 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
8589 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
8590 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
8591 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
8592 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
8593 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8594 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
8595 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
8596 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
8597 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
8598 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8600 int filectrl = -1;
8601 int iCtrl = -1;
8602 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
8603 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
8604 int n2, i;
8605 const char *zCmd = 0;
8606 const char *zSchema = 0;
8608 open_db(p, 0);
8609 zCmd = nArg>=2 ? azArg[1] : "help";
8611 if( zCmd[0]=='-'
8612 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
8613 && nArg>=4
8615 zSchema = azArg[2];
8616 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8617 nArg -= 2;
8618 zCmd = azArg[1];
8621 /* The argument can optionally begin with "-" or "--" */
8622 if( zCmd[0]=='-' && zCmd[1] ){
8623 zCmd++;
8624 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8627 /* --help lists all file-controls */
8628 if( cli_strcmp(zCmd,"help")==0 ){
8629 oputz("Available file-controls:\n");
8630 for(i=0; i<ArraySize(aCtrl); i++){
8631 oputf(" .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8633 rc = 1;
8634 goto meta_command_exit;
8637 /* convert filectrl text option to value. allow any unique prefix
8638 ** of the option name, or a numerical value. */
8639 n2 = strlen30(zCmd);
8640 for(i=0; i<ArraySize(aCtrl); i++){
8641 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8642 if( filectrl<0 ){
8643 filectrl = aCtrl[i].ctrlCode;
8644 iCtrl = i;
8645 }else{
8646 eputf("Error: ambiguous file-control: \"%s\"\n"
8647 "Use \".filectrl --help\" for help\n", zCmd);
8648 rc = 1;
8649 goto meta_command_exit;
8653 if( filectrl<0 ){
8654 eputf("Error: unknown file-control: %s\n"
8655 "Use \".filectrl --help\" for help\n", zCmd);
8656 }else{
8657 switch(filectrl){
8658 case SQLITE_FCNTL_SIZE_LIMIT: {
8659 if( nArg!=2 && nArg!=3 ) break;
8660 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8661 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8662 isOk = 1;
8663 break;
8665 case SQLITE_FCNTL_LOCK_TIMEOUT:
8666 case SQLITE_FCNTL_CHUNK_SIZE: {
8667 int x;
8668 if( nArg!=3 ) break;
8669 x = (int)integerValue(azArg[2]);
8670 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8671 isOk = 2;
8672 break;
8674 case SQLITE_FCNTL_PERSIST_WAL:
8675 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8676 int x;
8677 if( nArg!=2 && nArg!=3 ) break;
8678 x = nArg==3 ? booleanValue(azArg[2]) : -1;
8679 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8680 iRes = x;
8681 isOk = 1;
8682 break;
8684 case SQLITE_FCNTL_DATA_VERSION:
8685 case SQLITE_FCNTL_HAS_MOVED: {
8686 int x;
8687 if( nArg!=2 ) break;
8688 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8689 iRes = x;
8690 isOk = 1;
8691 break;
8693 case SQLITE_FCNTL_TEMPFILENAME: {
8694 char *z = 0;
8695 if( nArg!=2 ) break;
8696 sqlite3_file_control(p->db, zSchema, filectrl, &z);
8697 if( z ){
8698 oputf("%s\n", z);
8699 sqlite3_free(z);
8701 isOk = 2;
8702 break;
8704 case SQLITE_FCNTL_RESERVE_BYTES: {
8705 int x;
8706 if( nArg>=3 ){
8707 x = atoi(azArg[2]);
8708 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8710 x = -1;
8711 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8712 oputf("%d\n", x);
8713 isOk = 2;
8714 break;
8718 if( isOk==0 && iCtrl>=0 ){
8719 oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8720 rc = 1;
8721 }else if( isOk==1 ){
8722 char zBuf[100];
8723 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8724 oputf("%s\n", zBuf);
8726 }else
8728 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
8729 ShellState data;
8730 int doStats = 0;
8731 memcpy(&data, p, sizeof(data));
8732 data.showHeader = 0;
8733 data.cMode = data.mode = MODE_Semi;
8734 if( nArg==2 && optionMatch(azArg[1], "indent") ){
8735 data.cMode = data.mode = MODE_Pretty;
8736 nArg = 1;
8738 if( nArg!=1 ){
8739 eputz("Usage: .fullschema ?--indent?\n");
8740 rc = 1;
8741 goto meta_command_exit;
8743 open_db(p, 0);
8744 rc = sqlite3_exec(p->db,
8745 "SELECT sql FROM"
8746 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8747 " FROM sqlite_schema UNION ALL"
8748 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8749 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8750 "ORDER BY x",
8751 callback, &data, 0
8753 if( rc==SQLITE_OK ){
8754 sqlite3_stmt *pStmt;
8755 rc = sqlite3_prepare_v2(p->db,
8756 "SELECT rowid FROM sqlite_schema"
8757 " WHERE name GLOB 'sqlite_stat[134]'",
8758 -1, &pStmt, 0);
8759 if( rc==SQLITE_OK ){
8760 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8761 sqlite3_finalize(pStmt);
8764 if( doStats==0 ){
8765 oputz("/* No STAT tables available */\n");
8766 }else{
8767 oputz("ANALYZE sqlite_schema;\n");
8768 data.cMode = data.mode = MODE_Insert;
8769 data.zDestTable = "sqlite_stat1";
8770 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8771 data.zDestTable = "sqlite_stat4";
8772 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8773 oputz("ANALYZE sqlite_schema;\n");
8775 }else
8777 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
8778 if( nArg==2 ){
8779 p->showHeader = booleanValue(azArg[1]);
8780 p->shellFlgs |= SHFLG_HeaderSet;
8781 }else{
8782 eputz("Usage: .headers on|off\n");
8783 rc = 1;
8785 }else
8787 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
8788 if( nArg>=2 ){
8789 n = showHelp(p->out, azArg[1]);
8790 if( n==0 ){
8791 oputf("Nothing matches '%s'\n", azArg[1]);
8793 }else{
8794 showHelp(p->out, 0);
8796 }else
8798 #ifndef SQLITE_SHELL_FIDDLE
8799 if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
8800 char *zTable = 0; /* Insert data into this table */
8801 char *zSchema = 0; /* Schema of zTable */
8802 char *zFile = 0; /* Name of file to extra content from */
8803 sqlite3_stmt *pStmt = NULL; /* A statement */
8804 int nCol; /* Number of columns in the table */
8805 i64 nByte; /* Number of bytes in an SQL string */
8806 int i, j; /* Loop counters */
8807 int needCommit; /* True to COMMIT or ROLLBACK at end */
8808 int nSep; /* Number of bytes in p->colSeparator[] */
8809 char *zSql = 0; /* An SQL statement */
8810 ImportCtx sCtx; /* Reader context */
8811 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8812 int eVerbose = 0; /* Larger for more console output */
8813 int nSkip = 0; /* Initial lines to skip */
8814 int useOutputMode = 1; /* Use output mode to determine separators */
8815 char *zCreate = 0; /* CREATE TABLE statement text */
8817 failIfSafeMode(p, "cannot run .import in safe mode");
8818 memset(&sCtx, 0, sizeof(sCtx));
8819 if( p->mode==MODE_Ascii ){
8820 xRead = ascii_read_one_field;
8821 }else{
8822 xRead = csv_read_one_field;
8824 rc = 1;
8825 for(i=1; i<nArg; i++){
8826 char *z = azArg[i];
8827 if( z[0]=='-' && z[1]=='-' ) z++;
8828 if( z[0]!='-' ){
8829 if( zFile==0 ){
8830 zFile = z;
8831 }else if( zTable==0 ){
8832 zTable = z;
8833 }else{
8834 oputf("ERROR: extra argument: \"%s\". Usage:\n", z);
8835 showHelp(p->out, "import");
8836 goto meta_command_exit;
8838 }else if( cli_strcmp(z,"-v")==0 ){
8839 eVerbose++;
8840 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
8841 zSchema = azArg[++i];
8842 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
8843 nSkip = integerValue(azArg[++i]);
8844 }else if( cli_strcmp(z,"-ascii")==0 ){
8845 sCtx.cColSep = SEP_Unit[0];
8846 sCtx.cRowSep = SEP_Record[0];
8847 xRead = ascii_read_one_field;
8848 useOutputMode = 0;
8849 }else if( cli_strcmp(z,"-csv")==0 ){
8850 sCtx.cColSep = ',';
8851 sCtx.cRowSep = '\n';
8852 xRead = csv_read_one_field;
8853 useOutputMode = 0;
8854 }else{
8855 oputf("ERROR: unknown option: \"%s\". Usage:\n", z);
8856 showHelp(p->out, "import");
8857 goto meta_command_exit;
8860 if( zTable==0 ){
8861 oputf("ERROR: missing %s argument. Usage:\n",
8862 zFile==0 ? "FILE" : "TABLE");
8863 showHelp(p->out, "import");
8864 goto meta_command_exit;
8866 seenInterrupt = 0;
8867 open_db(p, 0);
8868 if( useOutputMode ){
8869 /* If neither the --csv or --ascii options are specified, then set
8870 ** the column and row separator characters from the output mode. */
8871 nSep = strlen30(p->colSeparator);
8872 if( nSep==0 ){
8873 eputz("Error: non-null column separator required for import\n");
8874 goto meta_command_exit;
8876 if( nSep>1 ){
8877 eputz("Error: multi-character column separators not allowed"
8878 " for import\n");
8879 goto meta_command_exit;
8881 nSep = strlen30(p->rowSeparator);
8882 if( nSep==0 ){
8883 eputz("Error: non-null row separator required for import\n");
8884 goto meta_command_exit;
8886 if( nSep==2 && p->mode==MODE_Csv
8887 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
8889 /* When importing CSV (only), if the row separator is set to the
8890 ** default output row separator, change it to the default input
8891 ** row separator. This avoids having to maintain different input
8892 ** and output row separators. */
8893 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8894 nSep = strlen30(p->rowSeparator);
8896 if( nSep>1 ){
8897 eputz("Error: multi-character row separators not allowed"
8898 " for import\n");
8899 goto meta_command_exit;
8901 sCtx.cColSep = (u8)p->colSeparator[0];
8902 sCtx.cRowSep = (u8)p->rowSeparator[0];
8904 sCtx.zFile = zFile;
8905 sCtx.nLine = 1;
8906 if( sCtx.zFile[0]=='|' ){
8907 #ifdef SQLITE_OMIT_POPEN
8908 eputz("Error: pipes are not supported in this OS\n");
8909 goto meta_command_exit;
8910 #else
8911 sCtx.in = popen(sCtx.zFile+1, "r");
8912 sCtx.zFile = "<pipe>";
8913 sCtx.xCloser = pclose;
8914 #endif
8915 }else{
8916 sCtx.in = fopen(sCtx.zFile, "rb");
8917 sCtx.xCloser = fclose;
8919 if( sCtx.in==0 ){
8920 eputf("Error: cannot open \"%s\"\n", zFile);
8921 goto meta_command_exit;
8923 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8924 char zSep[2];
8925 zSep[1] = 0;
8926 zSep[0] = sCtx.cColSep;
8927 oputz("Column separator ");
8928 output_c_string(zSep);
8929 oputz(", row separator ");
8930 zSep[0] = sCtx.cRowSep;
8931 output_c_string(zSep);
8932 oputz("\n");
8934 sCtx.z = sqlite3_malloc64(120);
8935 if( sCtx.z==0 ){
8936 import_cleanup(&sCtx);
8937 shell_out_of_memory();
8939 /* Below, resources must be freed before exit. */
8940 while( (nSkip--)>0 ){
8941 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8943 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
8944 if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) ){
8945 /* Table does not exist. Create it. */
8946 sqlite3 *dbCols = 0;
8947 char *zRenames = 0;
8948 char *zColDefs;
8949 zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
8950 zSchema ? zSchema : "main", zTable);
8951 while( xRead(&sCtx) ){
8952 zAutoColumn(sCtx.z, &dbCols, 0);
8953 if( sCtx.cTerm!=sCtx.cColSep ) break;
8955 zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8956 if( zRenames!=0 ){
8957 sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8958 "Columns renamed during .import %s due to duplicates:\n"
8959 "%s\n", sCtx.zFile, zRenames);
8960 sqlite3_free(zRenames);
8962 assert(dbCols==0);
8963 if( zColDefs==0 ){
8964 eputf("%s: empty file\n", sCtx.zFile);
8965 import_cleanup(&sCtx);
8966 rc = 1;
8967 goto meta_command_exit;
8969 zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8970 if( zCreate==0 ){
8971 import_cleanup(&sCtx);
8972 shell_out_of_memory();
8974 if( eVerbose>=1 ){
8975 oputf("%s\n", zCreate);
8977 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8978 sqlite3_free(zCreate);
8979 zCreate = 0;
8980 if( rc ){
8981 eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8982 import_cleanup(&sCtx);
8983 rc = 1;
8984 goto meta_command_exit;
8987 zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
8988 zTable, zSchema);
8989 if( zSql==0 ){
8990 import_cleanup(&sCtx);
8991 shell_out_of_memory();
8993 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8994 sqlite3_free(zSql);
8995 zSql = 0;
8996 if( rc ){
8997 if (pStmt) sqlite3_finalize(pStmt);
8998 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8999 import_cleanup(&sCtx);
9000 rc = 1;
9001 goto meta_command_exit;
9003 if( sqlite3_step(pStmt)==SQLITE_ROW ){
9004 nCol = sqlite3_column_int(pStmt, 0);
9005 }else{
9006 nCol = 0;
9008 sqlite3_finalize(pStmt);
9009 pStmt = 0;
9010 if( nCol==0 ) return 0; /* no columns, no error */
9012 nByte = 64 /* space for "INSERT INTO", "VALUES(", ")\0" */
9013 + (zSchema ? strlen(zSchema)*2 + 2: 0) /* Quoted schema name */
9014 + strlen(zTable)*2 + 2 /* Quoted table name */
9015 + nCol*2; /* Space for ",?" for each column */
9016 zSql = sqlite3_malloc64( nByte );
9017 if( zSql==0 ){
9018 import_cleanup(&sCtx);
9019 shell_out_of_memory();
9021 if( zSchema ){
9022 sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?",
9023 zSchema, zTable);
9024 }else{
9025 sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
9027 j = strlen30(zSql);
9028 for(i=1; i<nCol; i++){
9029 zSql[j++] = ',';
9030 zSql[j++] = '?';
9032 zSql[j++] = ')';
9033 zSql[j] = 0;
9034 assert( j<nByte );
9035 if( eVerbose>=2 ){
9036 oputf("Insert using: %s\n", zSql);
9038 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9039 sqlite3_free(zSql);
9040 zSql = 0;
9041 if( rc ){
9042 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9043 if (pStmt) sqlite3_finalize(pStmt);
9044 import_cleanup(&sCtx);
9045 rc = 1;
9046 goto meta_command_exit;
9048 needCommit = sqlite3_get_autocommit(p->db);
9049 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9051 int startLine = sCtx.nLine;
9052 for(i=0; i<nCol; i++){
9053 char *z = xRead(&sCtx);
9055 ** Did we reach end-of-file before finding any columns?
9056 ** If so, stop instead of NULL filling the remaining columns.
9058 if( z==0 && i==0 ) break;
9060 ** Did we reach end-of-file OR end-of-line before finding any
9061 ** columns in ASCII mode? If so, stop instead of NULL filling
9062 ** the remaining columns.
9064 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9066 ** For CSV mode, per RFC 4180, accept EOF in lieu of final
9067 ** record terminator but only for last field of multi-field row.
9068 ** (If there are too few fields, it's not valid CSV anyway.)
9070 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
9071 z = "";
9073 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9074 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9075 eputf("%s:%d: expected %d columns but found %d"
9076 " - filling the rest with NULL\n",
9077 sCtx.zFile, startLine, nCol, i+1);
9078 i += 2;
9079 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9082 if( sCtx.cTerm==sCtx.cColSep ){
9084 xRead(&sCtx);
9085 i++;
9086 }while( sCtx.cTerm==sCtx.cColSep );
9087 eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
9088 sCtx.zFile, startLine, nCol, i);
9090 if( i>=nCol ){
9091 sqlite3_step(pStmt);
9092 rc = sqlite3_reset(pStmt);
9093 if( rc!=SQLITE_OK ){
9094 eputf("%s:%d: INSERT failed: %s\n",
9095 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
9096 sCtx.nErr++;
9097 }else{
9098 sCtx.nRow++;
9101 }while( sCtx.cTerm!=EOF );
9103 import_cleanup(&sCtx);
9104 sqlite3_finalize(pStmt);
9105 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9106 if( eVerbose>0 ){
9107 oputf("Added %d rows with %d errors using %d lines of input\n",
9108 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9110 }else
9111 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9113 #ifndef SQLITE_UNTESTABLE
9114 if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
9115 char *zSql;
9116 char *zCollist = 0;
9117 sqlite3_stmt *pStmt;
9118 int tnum = 0;
9119 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
9120 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9121 int i;
9122 if( !ShellHasFlag(p,SHFLG_TestingMode) ){
9123 eputf(".%s unavailable without --unsafe-testing\n",
9124 "imposter");
9125 rc = 1;
9126 goto meta_command_exit;
9128 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9129 eputz("Usage: .imposter INDEX IMPOSTER\n"
9130 " .imposter off\n");
9131 /* Also allowed, but not documented:
9133 ** .imposter TABLE IMPOSTER
9135 ** where TABLE is a WITHOUT ROWID table. In that case, the
9136 ** imposter is another WITHOUT ROWID table with the columns in
9137 ** storage order. */
9138 rc = 1;
9139 goto meta_command_exit;
9141 open_db(p, 0);
9142 if( nArg==2 ){
9143 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9144 goto meta_command_exit;
9146 zSql = sqlite3_mprintf(
9147 "SELECT rootpage, 0 FROM sqlite_schema"
9148 " WHERE name='%q' AND type='index'"
9149 "UNION ALL "
9150 "SELECT rootpage, 1 FROM sqlite_schema"
9151 " WHERE name='%q' AND type='table'"
9152 " AND sql LIKE '%%without%%rowid%%'",
9153 azArg[1], azArg[1]
9155 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9156 sqlite3_free(zSql);
9157 if( sqlite3_step(pStmt)==SQLITE_ROW ){
9158 tnum = sqlite3_column_int(pStmt, 0);
9159 isWO = sqlite3_column_int(pStmt, 1);
9161 sqlite3_finalize(pStmt);
9162 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9163 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9164 sqlite3_free(zSql);
9165 i = 0;
9166 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9167 char zLabel[20];
9168 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9169 i++;
9170 if( zCol==0 ){
9171 if( sqlite3_column_int(pStmt,1)==-1 ){
9172 zCol = "_ROWID_";
9173 }else{
9174 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9175 zCol = zLabel;
9178 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9179 lenPK = (int)strlen(zCollist);
9181 if( zCollist==0 ){
9182 zCollist = sqlite3_mprintf("\"%w\"", zCol);
9183 }else{
9184 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9187 sqlite3_finalize(pStmt);
9188 if( i==0 || tnum==0 ){
9189 eputf("no such index: \"%s\"\n", azArg[1]);
9190 rc = 1;
9191 sqlite3_free(zCollist);
9192 goto meta_command_exit;
9194 if( lenPK==0 ) lenPK = 100000;
9195 zSql = sqlite3_mprintf(
9196 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9197 azArg[2], zCollist, lenPK, zCollist);
9198 sqlite3_free(zCollist);
9199 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9200 if( rc==SQLITE_OK ){
9201 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9202 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9203 if( rc ){
9204 eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9205 }else{
9206 sputf(stdout, "%s;\n", zSql);
9207 sputf(stdout, "WARNING: writing to an imposter table will corrupt"
9208 " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
9210 }else{
9211 eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9212 rc = 1;
9214 sqlite3_free(zSql);
9215 }else
9216 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9218 if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
9219 i64 iArg = 0;
9220 if( nArg==2 ){
9221 iArg = integerValue(azArg[1]);
9222 if( iArg==0 ) iArg = -1;
9224 if( (nArg!=1 && nArg!=2) || iArg<0 ){
9225 eputf("%s","Usage: .intck STEPS_PER_UNLOCK\n");
9226 rc = 1;
9227 goto meta_command_exit;
9229 open_db(p, 0);
9230 rc = intckDatabaseCmd(p, iArg);
9231 }else
9233 #ifdef SQLITE_ENABLE_IOTRACE
9234 if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
9235 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9236 if( iotrace && iotrace!=stdout ) fclose(iotrace);
9237 iotrace = 0;
9238 if( nArg<2 ){
9239 sqlite3IoTrace = 0;
9240 }else if( cli_strcmp(azArg[1], "-")==0 ){
9241 sqlite3IoTrace = iotracePrintf;
9242 iotrace = stdout;
9243 }else{
9244 iotrace = fopen(azArg[1], "w");
9245 if( iotrace==0 ){
9246 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9247 sqlite3IoTrace = 0;
9248 rc = 1;
9249 }else{
9250 sqlite3IoTrace = iotracePrintf;
9253 }else
9254 #endif
9256 if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
9257 static const struct {
9258 const char *zLimitName; /* Name of a limit */
9259 int limitCode; /* Integer code for that limit */
9260 } aLimit[] = {
9261 { "length", SQLITE_LIMIT_LENGTH },
9262 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
9263 { "column", SQLITE_LIMIT_COLUMN },
9264 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
9265 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
9266 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
9267 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
9268 { "attached", SQLITE_LIMIT_ATTACHED },
9269 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
9270 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
9271 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
9272 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
9274 int i, n2;
9275 open_db(p, 0);
9276 if( nArg==1 ){
9277 for(i=0; i<ArraySize(aLimit); i++){
9278 sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
9279 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9281 }else if( nArg>3 ){
9282 eputz("Usage: .limit NAME ?NEW-VALUE?\n");
9283 rc = 1;
9284 goto meta_command_exit;
9285 }else{
9286 int iLimit = -1;
9287 n2 = strlen30(azArg[1]);
9288 for(i=0; i<ArraySize(aLimit); i++){
9289 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9290 if( iLimit<0 ){
9291 iLimit = i;
9292 }else{
9293 eputf("ambiguous limit: \"%s\"\n", azArg[1]);
9294 rc = 1;
9295 goto meta_command_exit;
9299 if( iLimit<0 ){
9300 eputf("unknown limit: \"%s\"\n"
9301 "enter \".limits\" with no arguments for a list.\n",
9302 azArg[1]);
9303 rc = 1;
9304 goto meta_command_exit;
9306 if( nArg==3 ){
9307 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9308 (int)integerValue(azArg[2]));
9310 sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
9311 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9313 }else
9315 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
9316 open_db(p, 0);
9317 lintDotCommand(p, azArg, nArg);
9318 }else
9320 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9321 if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
9322 const char *zFile, *zProc;
9323 char *zErrMsg = 0;
9324 failIfSafeMode(p, "cannot run .load in safe mode");
9325 if( nArg<2 || azArg[1][0]==0 ){
9326 /* Must have a non-empty FILE. (Will not load self.) */
9327 eputz("Usage: .load FILE ?ENTRYPOINT?\n");
9328 rc = 1;
9329 goto meta_command_exit;
9331 zFile = azArg[1];
9332 zProc = nArg>=3 ? azArg[2] : 0;
9333 open_db(p, 0);
9334 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9335 if( rc!=SQLITE_OK ){
9336 eputf("Error: %s\n", zErrMsg);
9337 sqlite3_free(zErrMsg);
9338 rc = 1;
9340 }else
9341 #endif
9343 if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
9344 if( nArg!=2 ){
9345 eputz("Usage: .log FILENAME\n");
9346 rc = 1;
9347 }else{
9348 const char *zFile = azArg[1];
9349 if( p->bSafeMode
9350 && cli_strcmp(zFile,"on")!=0
9351 && cli_strcmp(zFile,"off")!=0
9353 sputz(stdout, "cannot set .log to anything other"
9354 " than \"on\" or \"off\"\n");
9355 zFile = "off";
9357 output_file_close(p->pLog);
9358 if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
9359 p->pLog = output_file_open(zFile, 0);
9361 }else
9363 if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
9364 const char *zMode = 0;
9365 const char *zTabname = 0;
9366 int i, n2;
9367 ColModeOpts cmOpts = ColModeOpts_default;
9368 for(i=1; i<nArg; i++){
9369 const char *z = azArg[i];
9370 if( optionMatch(z,"wrap") && i+1<nArg ){
9371 cmOpts.iWrap = integerValue(azArg[++i]);
9372 }else if( optionMatch(z,"ww") ){
9373 cmOpts.bWordWrap = 1;
9374 }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9375 cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9376 }else if( optionMatch(z,"quote") ){
9377 cmOpts.bQuote = 1;
9378 }else if( optionMatch(z,"noquote") ){
9379 cmOpts.bQuote = 0;
9380 }else if( zMode==0 ){
9381 zMode = z;
9382 /* Apply defaults for qbox pseudo-mode. If that
9383 * overwrites already-set values, user was informed of this.
9385 if( cli_strcmp(z, "qbox")==0 ){
9386 ColModeOpts cmo = ColModeOpts_default_qbox;
9387 zMode = "box";
9388 cmOpts = cmo;
9390 }else if( zTabname==0 ){
9391 zTabname = z;
9392 }else if( z[0]=='-' ){
9393 eputf("unknown option: %s\n", z);
9394 eputz("options:\n"
9395 " --noquote\n"
9396 " --quote\n"
9397 " --wordwrap on/off\n"
9398 " --wrap N\n"
9399 " --ww\n");
9400 rc = 1;
9401 goto meta_command_exit;
9402 }else{
9403 eputf("extra argument: \"%s\"\n", z);
9404 rc = 1;
9405 goto meta_command_exit;
9408 if( zMode==0 ){
9409 if( p->mode==MODE_Column
9410 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9412 oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9413 modeDescr[p->mode], p->cmOpts.iWrap,
9414 p->cmOpts.bWordWrap ? "on" : "off",
9415 p->cmOpts.bQuote ? "" : "no");
9416 }else{
9417 oputf("current output mode: %s\n", modeDescr[p->mode]);
9419 zMode = modeDescr[p->mode];
9421 n2 = strlen30(zMode);
9422 if( cli_strncmp(zMode,"lines",n2)==0 ){
9423 p->mode = MODE_Line;
9424 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9425 }else if( cli_strncmp(zMode,"columns",n2)==0 ){
9426 p->mode = MODE_Column;
9427 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9428 p->showHeader = 1;
9430 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9431 p->cmOpts = cmOpts;
9432 }else if( cli_strncmp(zMode,"list",n2)==0 ){
9433 p->mode = MODE_List;
9434 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9435 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9436 }else if( cli_strncmp(zMode,"html",n2)==0 ){
9437 p->mode = MODE_Html;
9438 }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
9439 p->mode = MODE_Tcl;
9440 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9441 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9442 }else if( cli_strncmp(zMode,"csv",n2)==0 ){
9443 p->mode = MODE_Csv;
9444 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9445 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9446 }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
9447 p->mode = MODE_List;
9448 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9449 }else if( cli_strncmp(zMode,"insert",n2)==0 ){
9450 p->mode = MODE_Insert;
9451 set_table_name(p, zTabname ? zTabname : "table");
9452 }else if( cli_strncmp(zMode,"quote",n2)==0 ){
9453 p->mode = MODE_Quote;
9454 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9455 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9456 }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
9457 p->mode = MODE_Ascii;
9458 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9459 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9460 }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
9461 p->mode = MODE_Markdown;
9462 p->cmOpts = cmOpts;
9463 }else if( cli_strncmp(zMode,"table",n2)==0 ){
9464 p->mode = MODE_Table;
9465 p->cmOpts = cmOpts;
9466 }else if( cli_strncmp(zMode,"box",n2)==0 ){
9467 p->mode = MODE_Box;
9468 p->cmOpts = cmOpts;
9469 }else if( cli_strncmp(zMode,"count",n2)==0 ){
9470 p->mode = MODE_Count;
9471 }else if( cli_strncmp(zMode,"off",n2)==0 ){
9472 p->mode = MODE_Off;
9473 }else if( cli_strncmp(zMode,"json",n2)==0 ){
9474 p->mode = MODE_Json;
9475 }else{
9476 eputz("Error: mode should be one of: "
9477 "ascii box column csv html insert json line list markdown "
9478 "qbox quote table tabs tcl\n");
9479 rc = 1;
9481 p->cMode = p->mode;
9482 }else
9484 #ifndef SQLITE_SHELL_FIDDLE
9485 if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
9486 if( nArg!=2 ){
9487 eputz("Usage: .nonce NONCE\n");
9488 rc = 1;
9489 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
9490 eputf("line %d: incorrect nonce: \"%s\"\n",
9491 p->lineno, azArg[1]);
9492 exit(1);
9493 }else{
9494 p->bSafeMode = 0;
9495 return 0; /* Return immediately to bypass the safe mode reset
9496 ** at the end of this procedure */
9498 }else
9499 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9501 if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
9502 if( nArg==2 ){
9503 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9504 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9505 }else{
9506 eputz("Usage: .nullvalue STRING\n");
9507 rc = 1;
9509 }else
9511 if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
9512 const char *zFN = 0; /* Pointer to constant filename */
9513 char *zNewFilename = 0; /* Name of the database file to open */
9514 int iName = 1; /* Index in azArg[] of the filename */
9515 int newFlag = 0; /* True to delete file before opening */
9516 int openMode = SHELL_OPEN_UNSPEC;
9518 /* Check for command-line arguments */
9519 for(iName=1; iName<nArg; iName++){
9520 const char *z = azArg[iName];
9521 #ifndef SQLITE_SHELL_FIDDLE
9522 if( optionMatch(z,"new") ){
9523 newFlag = 1;
9524 #ifdef SQLITE_HAVE_ZLIB
9525 }else if( optionMatch(z, "zip") ){
9526 openMode = SHELL_OPEN_ZIPFILE;
9527 #endif
9528 }else if( optionMatch(z, "append") ){
9529 openMode = SHELL_OPEN_APPENDVFS;
9530 }else if( optionMatch(z, "readonly") ){
9531 openMode = SHELL_OPEN_READONLY;
9532 }else if( optionMatch(z, "nofollow") ){
9533 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9534 #ifndef SQLITE_OMIT_DESERIALIZE
9535 }else if( optionMatch(z, "deserialize") ){
9536 openMode = SHELL_OPEN_DESERIALIZE;
9537 }else if( optionMatch(z, "hexdb") ){
9538 openMode = SHELL_OPEN_HEXDB;
9539 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9540 p->szMax = integerValue(azArg[++iName]);
9541 #endif /* SQLITE_OMIT_DESERIALIZE */
9542 }else
9543 #endif /* !SQLITE_SHELL_FIDDLE */
9544 if( z[0]=='-' ){
9545 eputf("unknown option: %s\n", z);
9546 rc = 1;
9547 goto meta_command_exit;
9548 }else if( zFN ){
9549 eputf("extra argument: \"%s\"\n", z);
9550 rc = 1;
9551 goto meta_command_exit;
9552 }else{
9553 zFN = z;
9557 /* Close the existing database */
9558 session_close_all(p, -1);
9559 close_db(p->db);
9560 p->db = 0;
9561 p->pAuxDb->zDbFilename = 0;
9562 sqlite3_free(p->pAuxDb->zFreeOnClose);
9563 p->pAuxDb->zFreeOnClose = 0;
9564 p->openMode = openMode;
9565 p->openFlags = 0;
9566 p->szMax = 0;
9568 /* If a filename is specified, try to open it first */
9569 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9570 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9571 #ifndef SQLITE_SHELL_FIDDLE
9572 if( p->bSafeMode
9573 && p->openMode!=SHELL_OPEN_HEXDB
9574 && zFN
9575 && cli_strcmp(zFN,":memory:")!=0
9577 failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9579 #else
9580 /* WASM mode has its own sandboxed pseudo-filesystem. */
9581 #endif
9582 if( zFN ){
9583 zNewFilename = sqlite3_mprintf("%s", zFN);
9584 shell_check_oom(zNewFilename);
9585 }else{
9586 zNewFilename = 0;
9588 p->pAuxDb->zDbFilename = zNewFilename;
9589 open_db(p, OPEN_DB_KEEPALIVE);
9590 if( p->db==0 ){
9591 eputf("Error: cannot open '%s'\n", zNewFilename);
9592 sqlite3_free(zNewFilename);
9593 }else{
9594 p->pAuxDb->zFreeOnClose = zNewFilename;
9597 if( p->db==0 ){
9598 /* As a fall-back open a TEMP database */
9599 p->pAuxDb->zDbFilename = 0;
9600 open_db(p, 0);
9602 }else
9604 #ifndef SQLITE_SHELL_FIDDLE
9605 if( (c=='o'
9606 && (cli_strncmp(azArg[0], "output", n)==0
9607 || cli_strncmp(azArg[0], "once", n)==0))
9608 || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
9610 char *zFile = 0;
9611 int bTxtMode = 0;
9612 int i;
9613 int eMode = 0;
9614 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
9615 static const char *zBomUtf8 = "\xef\xbb\xbf";
9616 const char *zBom = 0;
9618 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9619 if( c=='e' ){
9620 eMode = 'x';
9621 bOnce = 2;
9622 }else if( cli_strncmp(azArg[0],"once",n)==0 ){
9623 bOnce = 1;
9625 for(i=1; i<nArg; i++){
9626 char *z = azArg[i];
9627 if( z[0]=='-' ){
9628 if( z[1]=='-' ) z++;
9629 if( cli_strcmp(z,"-bom")==0 ){
9630 zBom = zBomUtf8;
9631 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
9632 eMode = 'x'; /* spreadsheet */
9633 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
9634 eMode = 'e'; /* text editor */
9635 }else{
9636 oputf("ERROR: unknown option: \"%s\". Usage:\n", azArg[i]);
9637 showHelp(p->out, azArg[0]);
9638 rc = 1;
9639 goto meta_command_exit;
9641 }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9642 zFile = sqlite3_mprintf("%s", z);
9643 if( zFile && zFile[0]=='|' ){
9644 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9645 break;
9647 }else{
9648 oputf("ERROR: extra parameter: \"%s\". Usage:\n", azArg[i]);
9649 showHelp(p->out, azArg[0]);
9650 rc = 1;
9651 sqlite3_free(zFile);
9652 goto meta_command_exit;
9655 if( zFile==0 ){
9656 zFile = sqlite3_mprintf("stdout");
9658 if( bOnce ){
9659 p->outCount = 2;
9660 }else{
9661 p->outCount = 0;
9663 output_reset(p);
9664 #ifndef SQLITE_NOHAVE_SYSTEM
9665 if( eMode=='e' || eMode=='x' ){
9666 p->doXdgOpen = 1;
9667 outputModePush(p);
9668 if( eMode=='x' ){
9669 /* spreadsheet mode. Output as CSV. */
9670 newTempFile(p, "csv");
9671 ShellClearFlag(p, SHFLG_Echo);
9672 p->mode = MODE_Csv;
9673 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9674 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9675 }else{
9676 /* text editor mode */
9677 newTempFile(p, "txt");
9678 bTxtMode = 1;
9680 sqlite3_free(zFile);
9681 zFile = sqlite3_mprintf("%s", p->zTempFile);
9683 #endif /* SQLITE_NOHAVE_SYSTEM */
9684 shell_check_oom(zFile);
9685 if( zFile[0]=='|' ){
9686 #ifdef SQLITE_OMIT_POPEN
9687 eputz("Error: pipes are not supported in this OS\n");
9688 rc = 1;
9689 output_redir(p, stdout);
9690 #else
9691 FILE *pfPipe = popen(zFile + 1, "w");
9692 if( pfPipe==0 ){
9693 eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
9694 rc = 1;
9695 }else{
9696 output_redir(p, pfPipe);
9697 if( zBom ) oputz(zBom);
9698 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9700 #endif
9701 }else{
9702 FILE *pfFile = output_file_open(zFile, bTxtMode);
9703 if( pfFile==0 ){
9704 if( cli_strcmp(zFile,"off")!=0 ){
9705 eputf("Error: cannot write to \"%s\"\n", zFile);
9707 rc = 1;
9708 } else {
9709 output_redir(p, pfFile);
9710 if( zBom ) oputz(zBom);
9711 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9714 sqlite3_free(zFile);
9715 }else
9716 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9718 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
9719 open_db(p,0);
9720 if( nArg<=1 ) goto parameter_syntax_error;
9722 /* .parameter clear
9723 ** Clear all bind parameters by dropping the TEMP table that holds them.
9725 if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
9726 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9727 0, 0, 0);
9728 }else
9730 /* .parameter list
9731 ** List all bind parameters.
9733 if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
9734 sqlite3_stmt *pStmt = 0;
9735 int rx;
9736 int len = 0;
9737 rx = sqlite3_prepare_v2(p->db,
9738 "SELECT max(length(key)) "
9739 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9740 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9741 len = sqlite3_column_int(pStmt, 0);
9742 if( len>40 ) len = 40;
9744 sqlite3_finalize(pStmt);
9745 pStmt = 0;
9746 if( len ){
9747 rx = sqlite3_prepare_v2(p->db,
9748 "SELECT key, quote(value) "
9749 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9750 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9751 oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9752 sqlite3_column_text(pStmt,1));
9754 sqlite3_finalize(pStmt);
9756 }else
9758 /* .parameter init
9759 ** Make sure the TEMP table used to hold bind parameters exists.
9760 ** Create it if necessary.
9762 if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
9763 bind_table_init(p);
9764 }else
9766 /* .parameter set NAME VALUE
9767 ** Set or reset a bind parameter. NAME should be the full parameter
9768 ** name exactly as it appears in the query. (ex: $abc, @def). The
9769 ** VALUE can be in either SQL literal notation, or if not it will be
9770 ** understood to be a text string.
9772 if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
9773 int rx;
9774 char *zSql;
9775 sqlite3_stmt *pStmt;
9776 const char *zKey = azArg[2];
9777 const char *zValue = azArg[3];
9778 bind_table_init(p);
9779 zSql = sqlite3_mprintf(
9780 "REPLACE INTO temp.sqlite_parameters(key,value)"
9781 "VALUES(%Q,%s);", zKey, zValue);
9782 shell_check_oom(zSql);
9783 pStmt = 0;
9784 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9785 sqlite3_free(zSql);
9786 if( rx!=SQLITE_OK ){
9787 sqlite3_finalize(pStmt);
9788 pStmt = 0;
9789 zSql = sqlite3_mprintf(
9790 "REPLACE INTO temp.sqlite_parameters(key,value)"
9791 "VALUES(%Q,%Q);", zKey, zValue);
9792 shell_check_oom(zSql);
9793 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9794 sqlite3_free(zSql);
9795 if( rx!=SQLITE_OK ){
9796 oputf("Error: %s\n", sqlite3_errmsg(p->db));
9797 sqlite3_finalize(pStmt);
9798 pStmt = 0;
9799 rc = 1;
9802 sqlite3_step(pStmt);
9803 sqlite3_finalize(pStmt);
9804 }else
9806 /* .parameter unset NAME
9807 ** Remove the NAME binding from the parameter binding table, if it
9808 ** exists.
9810 if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
9811 char *zSql = sqlite3_mprintf(
9812 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9813 shell_check_oom(zSql);
9814 sqlite3_exec(p->db, zSql, 0, 0, 0);
9815 sqlite3_free(zSql);
9816 }else
9817 /* If no command name matches, show a syntax error */
9818 parameter_syntax_error:
9819 showHelp(p->out, "parameter");
9820 }else
9822 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
9823 int i;
9824 for(i=1; i<nArg; i++){
9825 if( i>1 ) oputz(" ");
9826 oputz(azArg[i]);
9828 oputz("\n");
9829 }else
9831 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9832 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
9833 int i;
9834 int nn = 0;
9835 p->flgProgress = 0;
9836 p->mxProgress = 0;
9837 p->nProgress = 0;
9838 for(i=1; i<nArg; i++){
9839 const char *z = azArg[i];
9840 if( z[0]=='-' ){
9841 z++;
9842 if( z[0]=='-' ) z++;
9843 if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
9844 p->flgProgress |= SHELL_PROGRESS_QUIET;
9845 continue;
9847 if( cli_strcmp(z,"reset")==0 ){
9848 p->flgProgress |= SHELL_PROGRESS_RESET;
9849 continue;
9851 if( cli_strcmp(z,"once")==0 ){
9852 p->flgProgress |= SHELL_PROGRESS_ONCE;
9853 continue;
9855 if( cli_strcmp(z,"limit")==0 ){
9856 if( i+1>=nArg ){
9857 eputz("Error: missing argument on --limit\n");
9858 rc = 1;
9859 goto meta_command_exit;
9860 }else{
9861 p->mxProgress = (int)integerValue(azArg[++i]);
9863 continue;
9865 eputf("Error: unknown option: \"%s\"\n", azArg[i]);
9866 rc = 1;
9867 goto meta_command_exit;
9868 }else{
9869 nn = (int)integerValue(z);
9872 open_db(p, 0);
9873 sqlite3_progress_handler(p->db, nn, progress_handler, p);
9874 }else
9875 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9877 if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
9878 if( nArg >= 2) {
9879 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9881 if( nArg >= 3) {
9882 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9884 }else
9886 #ifndef SQLITE_SHELL_FIDDLE
9887 if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
9888 rc = 2;
9889 }else
9890 #endif
9892 #ifndef SQLITE_SHELL_FIDDLE
9893 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
9894 FILE *inSaved = p->in;
9895 int savedLineno = p->lineno;
9896 failIfSafeMode(p, "cannot run .read in safe mode");
9897 if( nArg!=2 ){
9898 eputz("Usage: .read FILE\n");
9899 rc = 1;
9900 goto meta_command_exit;
9902 if( azArg[1][0]=='|' ){
9903 #ifdef SQLITE_OMIT_POPEN
9904 eputz("Error: pipes are not supported in this OS\n");
9905 rc = 1;
9906 p->out = stdout;
9907 #else
9908 p->in = popen(azArg[1]+1, "r");
9909 if( p->in==0 ){
9910 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9911 rc = 1;
9912 }else{
9913 rc = process_input(p);
9914 pclose(p->in);
9916 #endif
9917 }else if( (p->in = openChrSource(azArg[1]))==0 ){
9918 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9919 rc = 1;
9920 }else{
9921 rc = process_input(p);
9922 fclose(p->in);
9924 p->in = inSaved;
9925 p->lineno = savedLineno;
9926 }else
9927 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9929 #ifndef SQLITE_SHELL_FIDDLE
9930 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
9931 const char *zSrcFile;
9932 const char *zDb;
9933 sqlite3 *pSrc;
9934 sqlite3_backup *pBackup;
9935 int nTimeout = 0;
9937 failIfSafeMode(p, "cannot run .restore in safe mode");
9938 if( nArg==2 ){
9939 zSrcFile = azArg[1];
9940 zDb = "main";
9941 }else if( nArg==3 ){
9942 zSrcFile = azArg[2];
9943 zDb = azArg[1];
9944 }else{
9945 eputz("Usage: .restore ?DB? FILE\n");
9946 rc = 1;
9947 goto meta_command_exit;
9949 rc = sqlite3_open(zSrcFile, &pSrc);
9950 if( rc!=SQLITE_OK ){
9951 eputf("Error: cannot open \"%s\"\n", zSrcFile);
9952 close_db(pSrc);
9953 return 1;
9955 open_db(p, 0);
9956 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9957 if( pBackup==0 ){
9958 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9959 close_db(pSrc);
9960 return 1;
9962 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9963 || rc==SQLITE_BUSY ){
9964 if( rc==SQLITE_BUSY ){
9965 if( nTimeout++ >= 3 ) break;
9966 sqlite3_sleep(100);
9969 sqlite3_backup_finish(pBackup);
9970 if( rc==SQLITE_DONE ){
9971 rc = 0;
9972 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9973 eputz("Error: source database is busy\n");
9974 rc = 1;
9975 }else{
9976 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9977 rc = 1;
9979 close_db(pSrc);
9980 }else
9981 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9983 if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
9984 if( nArg==2 ){
9985 if( cli_strcmp(azArg[1], "vm")==0 ){
9986 p->scanstatsOn = 3;
9987 }else
9988 if( cli_strcmp(azArg[1], "est")==0 ){
9989 p->scanstatsOn = 2;
9990 }else{
9991 p->scanstatsOn = (u8)booleanValue(azArg[1]);
9993 open_db(p, 0);
9994 sqlite3_db_config(
9995 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
9997 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9998 eputz("Warning: .scanstats not available in this build.\n");
9999 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
10000 if( p->scanstatsOn==3 ){
10001 eputz("Warning: \".scanstats vm\" not available in this build.\n");
10003 #endif
10004 }else{
10005 eputz("Usage: .scanstats on|off|est\n");
10006 rc = 1;
10008 }else
10010 if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
10011 ShellText sSelect;
10012 ShellState data;
10013 char *zErrMsg = 0;
10014 const char *zDiv = "(";
10015 const char *zName = 0;
10016 int iSchema = 0;
10017 int bDebug = 0;
10018 int bNoSystemTabs = 0;
10019 int ii;
10021 open_db(p, 0);
10022 memcpy(&data, p, sizeof(data));
10023 data.showHeader = 0;
10024 data.cMode = data.mode = MODE_Semi;
10025 initText(&sSelect);
10026 for(ii=1; ii<nArg; ii++){
10027 if( optionMatch(azArg[ii],"indent") ){
10028 data.cMode = data.mode = MODE_Pretty;
10029 }else if( optionMatch(azArg[ii],"debug") ){
10030 bDebug = 1;
10031 }else if( optionMatch(azArg[ii],"nosys") ){
10032 bNoSystemTabs = 1;
10033 }else if( azArg[ii][0]=='-' ){
10034 eputf("Unknown option: \"%s\"\n", azArg[ii]);
10035 rc = 1;
10036 goto meta_command_exit;
10037 }else if( zName==0 ){
10038 zName = azArg[ii];
10039 }else{
10040 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10041 rc = 1;
10042 goto meta_command_exit;
10045 if( zName!=0 ){
10046 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10047 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10048 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10049 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10050 if( isSchema ){
10051 char *new_argv[2], *new_colv[2];
10052 new_argv[0] = sqlite3_mprintf(
10053 "CREATE TABLE %s (\n"
10054 " type text,\n"
10055 " name text,\n"
10056 " tbl_name text,\n"
10057 " rootpage integer,\n"
10058 " sql text\n"
10059 ")", zName);
10060 shell_check_oom(new_argv[0]);
10061 new_argv[1] = 0;
10062 new_colv[0] = "sql";
10063 new_colv[1] = 0;
10064 callback(&data, 1, new_argv, new_colv);
10065 sqlite3_free(new_argv[0]);
10068 if( zDiv ){
10069 sqlite3_stmt *pStmt = 0;
10070 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10071 -1, &pStmt, 0);
10072 if( rc ){
10073 eputf("Error: %s\n", sqlite3_errmsg(p->db));
10074 sqlite3_finalize(pStmt);
10075 rc = 1;
10076 goto meta_command_exit;
10078 appendText(&sSelect, "SELECT sql FROM", 0);
10079 iSchema = 0;
10080 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10081 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10082 char zScNum[30];
10083 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10084 appendText(&sSelect, zDiv, 0);
10085 zDiv = " UNION ALL ";
10086 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10087 if( sqlite3_stricmp(zDb, "main")!=0 ){
10088 appendText(&sSelect, zDb, '\'');
10089 }else{
10090 appendText(&sSelect, "NULL", 0);
10092 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10093 appendText(&sSelect, zScNum, 0);
10094 appendText(&sSelect, " AS snum, ", 0);
10095 appendText(&sSelect, zDb, '\'');
10096 appendText(&sSelect, " AS sname FROM ", 0);
10097 appendText(&sSelect, zDb, quoteChar(zDb));
10098 appendText(&sSelect, ".sqlite_schema", 0);
10100 sqlite3_finalize(pStmt);
10101 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10102 if( zName ){
10103 appendText(&sSelect,
10104 " UNION ALL SELECT shell_module_schema(name),"
10105 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10108 #endif
10109 appendText(&sSelect, ") WHERE ", 0);
10110 if( zName ){
10111 char *zQarg = sqlite3_mprintf("%Q", zName);
10112 int bGlob;
10113 shell_check_oom(zQarg);
10114 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10115 strchr(zName, '[') != 0;
10116 if( strchr(zName, '.') ){
10117 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10118 }else{
10119 appendText(&sSelect, "lower(tbl_name)", 0);
10121 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10122 appendText(&sSelect, zQarg, 0);
10123 if( !bGlob ){
10124 appendText(&sSelect, " ESCAPE '\\' ", 0);
10126 appendText(&sSelect, " AND ", 0);
10127 sqlite3_free(zQarg);
10129 if( bNoSystemTabs ){
10130 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10132 appendText(&sSelect, "sql IS NOT NULL"
10133 " ORDER BY snum, rowid", 0);
10134 if( bDebug ){
10135 oputf("SQL: %s;\n", sSelect.z);
10136 }else{
10137 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10139 freeText(&sSelect);
10141 if( zErrMsg ){
10142 eputf("Error: %s\n", zErrMsg);
10143 sqlite3_free(zErrMsg);
10144 rc = 1;
10145 }else if( rc != SQLITE_OK ){
10146 eputz("Error: querying schema information\n");
10147 rc = 1;
10148 }else{
10149 rc = 0;
10151 }else
10153 if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
10154 || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0)
10156 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10157 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10158 }else
10160 #if defined(SQLITE_ENABLE_SESSION)
10161 if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
10162 struct AuxDb *pAuxDb = p->pAuxDb;
10163 OpenSession *pSession = &pAuxDb->aSession[0];
10164 char **azCmd = &azArg[1];
10165 int iSes = 0;
10166 int nCmd = nArg - 1;
10167 int i;
10168 if( nArg<=1 ) goto session_syntax_error;
10169 open_db(p, 0);
10170 if( nArg>=3 ){
10171 for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10172 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10174 if( iSes<pAuxDb->nSession ){
10175 pSession = &pAuxDb->aSession[iSes];
10176 azCmd++;
10177 nCmd--;
10178 }else{
10179 pSession = &pAuxDb->aSession[0];
10180 iSes = 0;
10184 /* .session attach TABLE
10185 ** Invoke the sqlite3session_attach() interface to attach a particular
10186 ** table so that it is never filtered.
10188 if( cli_strcmp(azCmd[0],"attach")==0 ){
10189 if( nCmd!=2 ) goto session_syntax_error;
10190 if( pSession->p==0 ){
10191 session_not_open:
10192 eputz("ERROR: No sessions are open\n");
10193 }else{
10194 rc = sqlite3session_attach(pSession->p, azCmd[1]);
10195 if( rc ){
10196 eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
10197 rc = 0;
10200 }else
10202 /* .session changeset FILE
10203 ** .session patchset FILE
10204 ** Write a changeset or patchset into a file. The file is overwritten.
10206 if( cli_strcmp(azCmd[0],"changeset")==0
10207 || cli_strcmp(azCmd[0],"patchset")==0
10209 FILE *out = 0;
10210 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10211 if( nCmd!=2 ) goto session_syntax_error;
10212 if( pSession->p==0 ) goto session_not_open;
10213 out = fopen(azCmd[1], "wb");
10214 if( out==0 ){
10215 eputf("ERROR: cannot open \"%s\" for writing\n",
10216 azCmd[1]);
10217 }else{
10218 int szChng;
10219 void *pChng;
10220 if( azCmd[0][0]=='c' ){
10221 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10222 }else{
10223 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10225 if( rc ){
10226 sputf(stdout, "Error: error code %d\n", rc);
10227 rc = 0;
10229 if( pChng
10230 && fwrite(pChng, szChng, 1, out)!=1 ){
10231 eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
10233 sqlite3_free(pChng);
10234 fclose(out);
10236 }else
10238 /* .session close
10239 ** Close the identified session
10241 if( cli_strcmp(azCmd[0], "close")==0 ){
10242 if( nCmd!=1 ) goto session_syntax_error;
10243 if( pAuxDb->nSession ){
10244 session_close(pSession);
10245 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10247 }else
10249 /* .session enable ?BOOLEAN?
10250 ** Query or set the enable flag
10252 if( cli_strcmp(azCmd[0], "enable")==0 ){
10253 int ii;
10254 if( nCmd>2 ) goto session_syntax_error;
10255 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10256 if( pAuxDb->nSession ){
10257 ii = sqlite3session_enable(pSession->p, ii);
10258 oputf("session %s enable flag = %d\n", pSession->zName, ii);
10260 }else
10262 /* .session filter GLOB ....
10263 ** Set a list of GLOB patterns of table names to be excluded.
10265 if( cli_strcmp(azCmd[0], "filter")==0 ){
10266 int ii, nByte;
10267 if( nCmd<2 ) goto session_syntax_error;
10268 if( pAuxDb->nSession ){
10269 for(ii=0; ii<pSession->nFilter; ii++){
10270 sqlite3_free(pSession->azFilter[ii]);
10272 sqlite3_free(pSession->azFilter);
10273 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10274 pSession->azFilter = sqlite3_malloc( nByte );
10275 shell_check_oom( pSession->azFilter );
10276 for(ii=1; ii<nCmd; ii++){
10277 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10278 shell_check_oom(x);
10280 pSession->nFilter = ii-1;
10282 }else
10284 /* .session indirect ?BOOLEAN?
10285 ** Query or set the indirect flag
10287 if( cli_strcmp(azCmd[0], "indirect")==0 ){
10288 int ii;
10289 if( nCmd>2 ) goto session_syntax_error;
10290 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10291 if( pAuxDb->nSession ){
10292 ii = sqlite3session_indirect(pSession->p, ii);
10293 oputf("session %s indirect flag = %d\n", pSession->zName, ii);
10295 }else
10297 /* .session isempty
10298 ** Determine if the session is empty
10300 if( cli_strcmp(azCmd[0], "isempty")==0 ){
10301 int ii;
10302 if( nCmd!=1 ) goto session_syntax_error;
10303 if( pAuxDb->nSession ){
10304 ii = sqlite3session_isempty(pSession->p);
10305 oputf("session %s isempty flag = %d\n", pSession->zName, ii);
10307 }else
10309 /* .session list
10310 ** List all currently open sessions
10312 if( cli_strcmp(azCmd[0],"list")==0 ){
10313 for(i=0; i<pAuxDb->nSession; i++){
10314 oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
10316 }else
10318 /* .session open DB NAME
10319 ** Open a new session called NAME on the attached database DB.
10320 ** DB is normally "main".
10322 if( cli_strcmp(azCmd[0],"open")==0 ){
10323 char *zName;
10324 if( nCmd!=3 ) goto session_syntax_error;
10325 zName = azCmd[2];
10326 if( zName[0]==0 ) goto session_syntax_error;
10327 for(i=0; i<pAuxDb->nSession; i++){
10328 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10329 eputf("Session \"%s\" already exists\n", zName);
10330 goto meta_command_exit;
10333 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10334 eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10335 goto meta_command_exit;
10337 pSession = &pAuxDb->aSession[pAuxDb->nSession];
10338 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10339 if( rc ){
10340 eputf("Cannot open session: error code=%d\n", rc);
10341 rc = 0;
10342 goto meta_command_exit;
10344 pSession->nFilter = 0;
10345 sqlite3session_table_filter(pSession->p, session_filter, pSession);
10346 pAuxDb->nSession++;
10347 pSession->zName = sqlite3_mprintf("%s", zName);
10348 shell_check_oom(pSession->zName);
10349 }else
10350 /* If no command name matches, show a syntax error */
10351 session_syntax_error:
10352 showHelp(p->out, "session");
10353 }else
10354 #endif
10356 #ifdef SQLITE_DEBUG
10357 /* Undocumented commands for internal testing. Subject to change
10358 ** without notice. */
10359 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
10360 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10361 int i, v;
10362 for(i=1; i<nArg; i++){
10363 v = booleanValue(azArg[i]);
10364 oputf("%s: %d 0x%x\n", azArg[i], v, v);
10367 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
10368 int i; sqlite3_int64 v;
10369 for(i=1; i<nArg; i++){
10370 char zBuf[200];
10371 v = integerValue(azArg[i]);
10372 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10373 oputz(zBuf);
10376 }else
10377 #endif
10379 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
10380 int bIsInit = 0; /* True to initialize the SELFTEST table */
10381 int bVerbose = 0; /* Verbose output */
10382 int bSelftestExists; /* True if SELFTEST already exists */
10383 int i, k; /* Loop counters */
10384 int nTest = 0; /* Number of tests runs */
10385 int nErr = 0; /* Number of errors seen */
10386 ShellText str; /* Answer for a query */
10387 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10389 open_db(p,0);
10390 for(i=1; i<nArg; i++){
10391 const char *z = azArg[i];
10392 if( z[0]=='-' && z[1]=='-' ) z++;
10393 if( cli_strcmp(z,"-init")==0 ){
10394 bIsInit = 1;
10395 }else
10396 if( cli_strcmp(z,"-v")==0 ){
10397 bVerbose++;
10398 }else
10400 eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
10401 eputz("Should be one of: --init -v\n");
10402 rc = 1;
10403 goto meta_command_exit;
10406 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10407 != SQLITE_OK ){
10408 bSelftestExists = 0;
10409 }else{
10410 bSelftestExists = 1;
10412 if( bIsInit ){
10413 createSelftestTable(p);
10414 bSelftestExists = 1;
10416 initText(&str);
10417 appendText(&str, "x", 0);
10418 for(k=bSelftestExists; k>=0; k--){
10419 if( k==1 ){
10420 rc = sqlite3_prepare_v2(p->db,
10421 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10422 -1, &pStmt, 0);
10423 }else{
10424 rc = sqlite3_prepare_v2(p->db,
10425 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10426 " (1,'run','PRAGMA integrity_check','ok')",
10427 -1, &pStmt, 0);
10429 if( rc ){
10430 eputz("Error querying the selftest table\n");
10431 rc = 1;
10432 sqlite3_finalize(pStmt);
10433 goto meta_command_exit;
10435 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10436 int tno = sqlite3_column_int(pStmt, 0);
10437 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10438 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10439 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10441 if( zOp==0 ) continue;
10442 if( zSql==0 ) continue;
10443 if( zAns==0 ) continue;
10444 k = 0;
10445 if( bVerbose>0 ){
10446 sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
10448 if( cli_strcmp(zOp,"memo")==0 ){
10449 oputf("%s\n", zSql);
10450 }else
10451 if( cli_strcmp(zOp,"run")==0 ){
10452 char *zErrMsg = 0;
10453 str.n = 0;
10454 str.z[0] = 0;
10455 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10456 nTest++;
10457 if( bVerbose ){
10458 oputf("Result: %s\n", str.z);
10460 if( rc || zErrMsg ){
10461 nErr++;
10462 rc = 1;
10463 oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10464 sqlite3_free(zErrMsg);
10465 }else if( cli_strcmp(zAns,str.z)!=0 ){
10466 nErr++;
10467 rc = 1;
10468 oputf("%d: Expected: [%s]\n", tno, zAns);
10469 oputf("%d: Got: [%s]\n", tno, str.z);
10472 else{
10473 eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10474 rc = 1;
10475 break;
10477 } /* End loop over rows of content from SELFTEST */
10478 sqlite3_finalize(pStmt);
10479 } /* End loop over k */
10480 freeText(&str);
10481 oputf("%d errors out of %d tests\n", nErr, nTest);
10482 }else
10484 if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
10485 if( nArg<2 || nArg>3 ){
10486 eputz("Usage: .separator COL ?ROW?\n");
10487 rc = 1;
10489 if( nArg>=2 ){
10490 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10491 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10493 if( nArg>=3 ){
10494 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10495 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10497 }else
10499 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
10500 const char *zLike = 0; /* Which table to checksum. 0 means everything */
10501 int i; /* Loop counter */
10502 int bSchema = 0; /* Also hash the schema */
10503 int bSeparate = 0; /* Hash each table separately */
10504 int iSize = 224; /* Hash algorithm to use */
10505 int bDebug = 0; /* Only show the query that would have run */
10506 sqlite3_stmt *pStmt; /* For querying tables names */
10507 char *zSql; /* SQL to be run */
10508 char *zSep; /* Separator */
10509 ShellText sSql; /* Complete SQL for the query to run the hash */
10510 ShellText sQuery; /* Set of queries used to read all content */
10511 open_db(p, 0);
10512 for(i=1; i<nArg; i++){
10513 const char *z = azArg[i];
10514 if( z[0]=='-' ){
10515 z++;
10516 if( z[0]=='-' ) z++;
10517 if( cli_strcmp(z,"schema")==0 ){
10518 bSchema = 1;
10519 }else
10520 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
10521 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
10523 iSize = atoi(&z[5]);
10524 }else
10525 if( cli_strcmp(z,"debug")==0 ){
10526 bDebug = 1;
10527 }else
10529 eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
10530 showHelp(p->out, azArg[0]);
10531 rc = 1;
10532 goto meta_command_exit;
10534 }else if( zLike ){
10535 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10536 rc = 1;
10537 goto meta_command_exit;
10538 }else{
10539 zLike = z;
10540 bSeparate = 1;
10541 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10544 if( bSchema ){
10545 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10546 " WHERE type='table' AND coalesce(rootpage,0)>1"
10547 " UNION ALL SELECT 'sqlite_schema'"
10548 " ORDER BY 1 collate nocase";
10549 }else{
10550 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10551 " WHERE type='table' AND coalesce(rootpage,0)>1"
10552 " AND name NOT LIKE 'sqlite_%'"
10553 " ORDER BY 1 collate nocase";
10555 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10556 initText(&sQuery);
10557 initText(&sSql);
10558 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10559 zSep = "VALUES(";
10560 while( SQLITE_ROW==sqlite3_step(pStmt) ){
10561 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10562 if( zTab==0 ) continue;
10563 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10564 if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
10565 appendText(&sQuery,"SELECT * FROM ", 0);
10566 appendText(&sQuery,zTab,'"');
10567 appendText(&sQuery," NOT INDEXED;", 0);
10568 }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
10569 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10570 " ORDER BY name;", 0);
10571 }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
10572 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10573 " ORDER BY name;", 0);
10574 }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
10575 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10576 " ORDER BY tbl,idx;", 0);
10577 }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
10578 appendText(&sQuery, "SELECT * FROM ", 0);
10579 appendText(&sQuery, zTab, 0);
10580 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10582 appendText(&sSql, zSep, 0);
10583 appendText(&sSql, sQuery.z, '\'');
10584 sQuery.n = 0;
10585 appendText(&sSql, ",", 0);
10586 appendText(&sSql, zTab, '\'');
10587 zSep = "),(";
10589 sqlite3_finalize(pStmt);
10590 if( bSeparate ){
10591 zSql = sqlite3_mprintf(
10592 "%s))"
10593 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10594 " FROM [sha3sum$query]",
10595 sSql.z, iSize);
10596 }else{
10597 zSql = sqlite3_mprintf(
10598 "%s))"
10599 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10600 " FROM [sha3sum$query]",
10601 sSql.z, iSize);
10603 shell_check_oom(zSql);
10604 freeText(&sQuery);
10605 freeText(&sSql);
10606 if( bDebug ){
10607 oputf("%s\n", zSql);
10608 }else{
10609 shell_exec(p, zSql, 0);
10611 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10613 int lrc;
10614 char *zRevText = /* Query for reversible to-blob-to-text check */
10615 "SELECT lower(name) as tname FROM sqlite_schema\n"
10616 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10617 "AND name NOT LIKE 'sqlite_%%'%s\n"
10618 "ORDER BY 1 collate nocase";
10619 zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
10620 zRevText = sqlite3_mprintf(
10621 /* lower-case query is first run, producing upper-case query. */
10622 "with tabcols as materialized(\n"
10623 "select tname, cname\n"
10624 "from ("
10625 " select printf('\"%%w\"',ss.tname) as tname,"
10626 " printf('\"%%w\"',ti.name) as cname\n"
10627 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10628 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10629 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10630 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10631 "FROM '||tname||' WHERE '\n"
10632 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10633 "|| ' AND typeof('||cname||')=''text'' ',\n"
10634 "' OR ') as query, tname from tabcols group by tname)"
10635 , zRevText);
10636 shell_check_oom(zRevText);
10637 if( bDebug ) oputf("%s\n", zRevText);
10638 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
10639 if( lrc!=SQLITE_OK ){
10640 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
10641 ** user does cruel and unnatural things like ".limit expr_depth 0". */
10642 rc = 1;
10643 }else{
10644 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
10645 lrc = SQLITE_ROW==sqlite3_step(pStmt);
10646 if( lrc ){
10647 const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
10648 sqlite3_stmt *pCheckStmt;
10649 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
10650 if( bDebug ) oputf("%s\n", zGenQuery);
10651 if( lrc!=SQLITE_OK ){
10652 rc = 1;
10653 }else{
10654 if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
10655 double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
10656 if( countIrreversible>0 ){
10657 int sz = (int)(countIrreversible + 0.5);
10658 eputf("Digest includes %d invalidly encoded text field%s.\n",
10659 sz, (sz>1)? "s": "");
10662 sqlite3_finalize(pCheckStmt);
10664 sqlite3_finalize(pStmt);
10667 if( rc ) eputz(".sha3sum failed.\n");
10668 sqlite3_free(zRevText);
10670 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10671 sqlite3_free(zSql);
10672 }else
10674 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10675 if( c=='s'
10676 && (cli_strncmp(azArg[0], "shell", n)==0
10677 || cli_strncmp(azArg[0],"system",n)==0)
10679 char *zCmd;
10680 int i, x;
10681 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10682 if( nArg<2 ){
10683 eputz("Usage: .system COMMAND\n");
10684 rc = 1;
10685 goto meta_command_exit;
10687 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10688 for(i=2; i<nArg && zCmd!=0; i++){
10689 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10690 zCmd, azArg[i]);
10692 consoleRestore();
10693 x = zCmd!=0 ? system(zCmd) : 1;
10694 consoleRenewSetup();
10695 sqlite3_free(zCmd);
10696 if( x ) eputf("System command returns %d\n", x);
10697 }else
10698 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10700 if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
10701 static const char *azBool[] = { "off", "on", "trigger", "full"};
10702 const char *zOut;
10703 int i;
10704 if( nArg!=1 ){
10705 eputz("Usage: .show\n");
10706 rc = 1;
10707 goto meta_command_exit;
10709 oputf("%12.12s: %s\n","echo",
10710 azBool[ShellHasFlag(p, SHFLG_Echo)]);
10711 oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10712 oputf("%12.12s: %s\n","explain",
10713 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10714 oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10715 if( p->mode==MODE_Column
10716 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10718 oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10719 modeDescr[p->mode], p->cmOpts.iWrap,
10720 p->cmOpts.bWordWrap ? "on" : "off",
10721 p->cmOpts.bQuote ? "" : "no");
10722 }else{
10723 oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
10725 oputf("%12.12s: ", "nullvalue");
10726 output_c_string(p->nullValue);
10727 oputz("\n");
10728 oputf("%12.12s: %s\n","output",
10729 strlen30(p->outfile) ? p->outfile : "stdout");
10730 oputf("%12.12s: ", "colseparator");
10731 output_c_string(p->colSeparator);
10732 oputz("\n");
10733 oputf("%12.12s: ", "rowseparator");
10734 output_c_string(p->rowSeparator);
10735 oputz("\n");
10736 switch( p->statsOn ){
10737 case 0: zOut = "off"; break;
10738 default: zOut = "on"; break;
10739 case 2: zOut = "stmt"; break;
10740 case 3: zOut = "vmstep"; break;
10742 oputf("%12.12s: %s\n","stats", zOut);
10743 oputf("%12.12s: ", "width");
10744 for (i=0;i<p->nWidth;i++) {
10745 oputf("%d ", p->colWidth[i]);
10747 oputz("\n");
10748 oputf("%12.12s: %s\n", "filename",
10749 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10750 }else
10752 if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
10753 if( nArg==2 ){
10754 if( cli_strcmp(azArg[1],"stmt")==0 ){
10755 p->statsOn = 2;
10756 }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
10757 p->statsOn = 3;
10758 }else{
10759 p->statsOn = (u8)booleanValue(azArg[1]);
10761 }else if( nArg==1 ){
10762 display_stats(p->db, p, 0);
10763 }else{
10764 eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
10765 rc = 1;
10767 }else
10769 if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
10770 || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
10771 || cli_strncmp(azArg[0], "indexes", n)==0) )
10773 sqlite3_stmt *pStmt;
10774 char **azResult;
10775 int nRow, nAlloc;
10776 int ii;
10777 ShellText s;
10778 initText(&s);
10779 open_db(p, 0);
10780 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10781 if( rc ){
10782 sqlite3_finalize(pStmt);
10783 return shellDatabaseError(p->db);
10786 if( nArg>2 && c=='i' ){
10787 /* It is an historical accident that the .indexes command shows an error
10788 ** when called with the wrong number of arguments whereas the .tables
10789 ** command does not. */
10790 eputz("Usage: .indexes ?LIKE-PATTERN?\n");
10791 rc = 1;
10792 sqlite3_finalize(pStmt);
10793 goto meta_command_exit;
10795 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10796 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10797 if( zDbName==0 ) continue;
10798 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10799 if( sqlite3_stricmp(zDbName, "main")==0 ){
10800 appendText(&s, "SELECT name FROM ", 0);
10801 }else{
10802 appendText(&s, "SELECT ", 0);
10803 appendText(&s, zDbName, '\'');
10804 appendText(&s, "||'.'||name FROM ", 0);
10806 appendText(&s, zDbName, '"');
10807 appendText(&s, ".sqlite_schema ", 0);
10808 if( c=='t' ){
10809 appendText(&s," WHERE type IN ('table','view')"
10810 " AND name NOT LIKE 'sqlite_%'"
10811 " AND name LIKE ?1", 0);
10812 }else{
10813 appendText(&s," WHERE type='index'"
10814 " AND tbl_name LIKE ?1", 0);
10817 rc = sqlite3_finalize(pStmt);
10818 if( rc==SQLITE_OK ){
10819 appendText(&s, " ORDER BY 1", 0);
10820 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10822 freeText(&s);
10823 if( rc ) return shellDatabaseError(p->db);
10825 /* Run the SQL statement prepared by the above block. Store the results
10826 ** as an array of nul-terminated strings in azResult[]. */
10827 nRow = nAlloc = 0;
10828 azResult = 0;
10829 if( nArg>1 ){
10830 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10831 }else{
10832 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10834 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10835 if( nRow>=nAlloc ){
10836 char **azNew;
10837 int n2 = nAlloc*2 + 10;
10838 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10839 shell_check_oom(azNew);
10840 nAlloc = n2;
10841 azResult = azNew;
10843 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10844 shell_check_oom(azResult[nRow]);
10845 nRow++;
10847 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10848 rc = shellDatabaseError(p->db);
10851 /* Pretty-print the contents of array azResult[] to the output */
10852 if( rc==0 && nRow>0 ){
10853 int len, maxlen = 0;
10854 int i, j;
10855 int nPrintCol, nPrintRow;
10856 for(i=0; i<nRow; i++){
10857 len = strlen30(azResult[i]);
10858 if( len>maxlen ) maxlen = len;
10860 nPrintCol = 80/(maxlen+2);
10861 if( nPrintCol<1 ) nPrintCol = 1;
10862 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10863 for(i=0; i<nPrintRow; i++){
10864 for(j=i; j<nRow; j+=nPrintRow){
10865 char *zSp = j<nPrintRow ? "" : " ";
10866 oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
10868 oputz("\n");
10872 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10873 sqlite3_free(azResult);
10874 }else
10876 #ifndef SQLITE_SHELL_FIDDLE
10877 /* Begin redirecting output to the file "testcase-out.txt" */
10878 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
10879 output_reset(p);
10880 p->out = output_file_open("testcase-out.txt", 0);
10881 if( p->out==0 ){
10882 eputz("Error: cannot open 'testcase-out.txt'\n");
10884 if( nArg>=2 ){
10885 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10886 }else{
10887 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10889 }else
10890 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10892 #ifndef SQLITE_UNTESTABLE
10893 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
10894 static const struct {
10895 const char *zCtrlName; /* Name of a test-control option */
10896 int ctrlCode; /* Integer code for that option */
10897 int unSafe; /* Not valid unless --unsafe-testing */
10898 const char *zUsage; /* Usage notes */
10899 } aCtrl[] = {
10900 {"always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
10901 {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
10902 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10903 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10904 {"byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
10905 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
10906 {"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..." },
10907 {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" },
10908 {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10909 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
10910 {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" },
10911 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
10912 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
10913 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
10914 #ifdef YYCOVERAGE
10915 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
10916 #endif
10917 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
10918 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
10919 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
10920 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
10921 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
10922 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
10923 {"tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
10924 {"uselongdouble", SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
10926 int testctrl = -1;
10927 int iCtrl = -1;
10928 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10929 int isOk = 0;
10930 int i, n2;
10931 const char *zCmd = 0;
10933 open_db(p, 0);
10934 zCmd = nArg>=2 ? azArg[1] : "help";
10936 /* The argument can optionally begin with "-" or "--" */
10937 if( zCmd[0]=='-' && zCmd[1] ){
10938 zCmd++;
10939 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10942 /* --help lists all test-controls */
10943 if( cli_strcmp(zCmd,"help")==0 ){
10944 oputz("Available test-controls:\n");
10945 for(i=0; i<ArraySize(aCtrl); i++){
10946 if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
10947 oputf(" .testctrl %s %s\n",
10948 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10950 rc = 1;
10951 goto meta_command_exit;
10954 /* convert testctrl text option to value. allow any unique prefix
10955 ** of the option name, or a numerical value. */
10956 n2 = strlen30(zCmd);
10957 for(i=0; i<ArraySize(aCtrl); i++){
10958 if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
10959 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10960 if( testctrl<0 ){
10961 testctrl = aCtrl[i].ctrlCode;
10962 iCtrl = i;
10963 }else{
10964 eputf("Error: ambiguous test-control: \"%s\"\n"
10965 "Use \".testctrl --help\" for help\n", zCmd);
10966 rc = 1;
10967 goto meta_command_exit;
10971 if( testctrl<0 ){
10972 eputf("Error: unknown test-control: %s\n"
10973 "Use \".testctrl --help\" for help\n", zCmd);
10974 }else{
10975 switch(testctrl){
10977 /* sqlite3_test_control(int, db, int) */
10978 case SQLITE_TESTCTRL_OPTIMIZATIONS:
10979 case SQLITE_TESTCTRL_FK_NO_ACTION:
10980 if( nArg==3 ){
10981 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10982 rc2 = sqlite3_test_control(testctrl, p->db, opt);
10983 isOk = 3;
10985 break;
10987 /* sqlite3_test_control(int) */
10988 case SQLITE_TESTCTRL_PRNG_SAVE:
10989 case SQLITE_TESTCTRL_PRNG_RESTORE:
10990 case SQLITE_TESTCTRL_BYTEORDER:
10991 if( nArg==2 ){
10992 rc2 = sqlite3_test_control(testctrl);
10993 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10995 break;
10997 /* sqlite3_test_control(int, uint) */
10998 case SQLITE_TESTCTRL_PENDING_BYTE:
10999 if( nArg==3 ){
11000 unsigned int opt = (unsigned int)integerValue(azArg[2]);
11001 rc2 = sqlite3_test_control(testctrl, opt);
11002 isOk = 3;
11004 break;
11006 /* sqlite3_test_control(int, int, sqlite3*) */
11007 case SQLITE_TESTCTRL_PRNG_SEED:
11008 if( nArg==3 || nArg==4 ){
11009 int ii = (int)integerValue(azArg[2]);
11010 sqlite3 *db;
11011 if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
11012 sqlite3_randomness(sizeof(ii),&ii);
11013 sputf(stdout, "-- random seed: %d\n", ii);
11015 if( nArg==3 ){
11016 db = 0;
11017 }else{
11018 db = p->db;
11019 /* Make sure the schema has been loaded */
11020 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11022 rc2 = sqlite3_test_control(testctrl, ii, db);
11023 isOk = 3;
11025 break;
11027 /* sqlite3_test_control(int, int) */
11028 case SQLITE_TESTCTRL_ASSERT:
11029 case SQLITE_TESTCTRL_ALWAYS:
11030 if( nArg==3 ){
11031 int opt = booleanValue(azArg[2]);
11032 rc2 = sqlite3_test_control(testctrl, opt);
11033 isOk = 1;
11035 break;
11037 /* sqlite3_test_control(int, int) */
11038 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11039 case SQLITE_TESTCTRL_NEVER_CORRUPT:
11040 if( nArg==3 ){
11041 int opt = booleanValue(azArg[2]);
11042 rc2 = sqlite3_test_control(testctrl, opt);
11043 isOk = 3;
11045 break;
11047 /* sqlite3_test_control(int, int) */
11048 case SQLITE_TESTCTRL_USELONGDOUBLE: {
11049 int opt = -1;
11050 if( nArg==3 ){
11051 if( cli_strcmp(azArg[2],"default")==0 ){
11052 opt = 2;
11053 }else{
11054 opt = booleanValue(azArg[2]);
11057 rc2 = sqlite3_test_control(testctrl, opt);
11058 isOk = 1;
11059 break;
11062 /* sqlite3_test_control(sqlite3*) */
11063 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11064 rc2 = sqlite3_test_control(testctrl, p->db);
11065 isOk = 3;
11066 break;
11068 case SQLITE_TESTCTRL_IMPOSTER:
11069 if( nArg==5 ){
11070 rc2 = sqlite3_test_control(testctrl, p->db,
11071 azArg[2],
11072 integerValue(azArg[3]),
11073 integerValue(azArg[4]));
11074 isOk = 3;
11076 break;
11078 case SQLITE_TESTCTRL_SEEK_COUNT: {
11079 u64 x = 0;
11080 rc2 = sqlite3_test_control(testctrl, p->db, &x);
11081 oputf("%llu\n", x);
11082 isOk = 3;
11083 break;
11086 #ifdef YYCOVERAGE
11087 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11088 if( nArg==2 ){
11089 sqlite3_test_control(testctrl, p->out);
11090 isOk = 3;
11092 break;
11094 #endif
11095 #ifdef SQLITE_DEBUG
11096 case SQLITE_TESTCTRL_TUNE: {
11097 if( nArg==4 ){
11098 int id = (int)integerValue(azArg[2]);
11099 int val = (int)integerValue(azArg[3]);
11100 sqlite3_test_control(testctrl, id, &val);
11101 isOk = 3;
11102 }else if( nArg==3 ){
11103 int id = (int)integerValue(azArg[2]);
11104 sqlite3_test_control(testctrl, -id, &rc2);
11105 isOk = 1;
11106 }else if( nArg==2 ){
11107 int id = 1;
11108 while(1){
11109 int val = 0;
11110 rc2 = sqlite3_test_control(testctrl, -id, &val);
11111 if( rc2!=SQLITE_OK ) break;
11112 if( id>1 ) oputz(" ");
11113 oputf("%d: %d", id, val);
11114 id++;
11116 if( id>1 ) oputz("\n");
11117 isOk = 3;
11119 break;
11121 #endif
11122 case SQLITE_TESTCTRL_SORTER_MMAP:
11123 if( nArg==3 ){
11124 int opt = (unsigned int)integerValue(azArg[2]);
11125 rc2 = sqlite3_test_control(testctrl, p->db, opt);
11126 isOk = 3;
11128 break;
11129 case SQLITE_TESTCTRL_JSON_SELFCHECK:
11130 if( nArg==2 ){
11131 rc2 = -1;
11132 isOk = 1;
11133 }else{
11134 rc2 = booleanValue(azArg[2]);
11135 isOk = 3;
11137 sqlite3_test_control(testctrl, &rc2);
11138 break;
11139 case SQLITE_TESTCTRL_FAULT_INSTALL: {
11140 int kk;
11141 int bShowHelp = nArg<=2;
11142 isOk = 3;
11143 for(kk=2; kk<nArg; kk++){
11144 const char *z = azArg[kk];
11145 if( z[0]=='-' && z[1]=='-' ) z++;
11146 if( cli_strcmp(z,"off")==0 ){
11147 sqlite3_test_control(testctrl, 0);
11148 }else if( cli_strcmp(z,"on")==0 ){
11149 faultsim_state.iCnt = faultsim_state.nSkip;
11150 if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
11151 faultsim_state.nHit = 0;
11152 sqlite3_test_control(testctrl, faultsim_callback);
11153 }else if( cli_strcmp(z,"reset")==0 ){
11154 faultsim_state.iCnt = faultsim_state.nSkip;
11155 faultsim_state.nHit = 0;
11156 sqlite3_test_control(testctrl, faultsim_callback);
11157 }else if( cli_strcmp(z,"status")==0 ){
11158 oputf("faultsim.iId: %d\n", faultsim_state.iId);
11159 oputf("faultsim.iErr: %d\n", faultsim_state.iErr);
11160 oputf("faultsim.iCnt: %d\n", faultsim_state.iCnt);
11161 oputf("faultsim.nHit: %d\n", faultsim_state.nHit);
11162 oputf("faultsim.iInterval: %d\n", faultsim_state.iInterval);
11163 oputf("faultsim.eVerbose: %d\n", faultsim_state.eVerbose);
11164 oputf("faultsim.nRepeat: %d\n", faultsim_state.nRepeat);
11165 oputf("faultsim.nSkip: %d\n", faultsim_state.nSkip);
11166 }else if( cli_strcmp(z,"-v")==0 ){
11167 if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
11168 }else if( cli_strcmp(z,"-q")==0 ){
11169 if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
11170 }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
11171 faultsim_state.iId = atoi(azArg[++kk]);
11172 }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
11173 faultsim_state.iErr = atoi(azArg[++kk]);
11174 }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
11175 faultsim_state.iInterval = atoi(azArg[++kk]);
11176 }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){
11177 faultsim_state.nRepeat = atoi(azArg[++kk]);
11178 }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){
11179 faultsim_state.nSkip = atoi(azArg[++kk]);
11180 }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
11181 bShowHelp = 1;
11182 }else{
11183 eputf("Unrecognized fault_install argument: \"%s\"\n",
11184 azArg[kk]);
11185 rc = 1;
11186 bShowHelp = 1;
11187 break;
11190 if( bShowHelp ){
11191 oputz(
11192 "Usage: .testctrl fault_install ARGS\n"
11193 "Possible arguments:\n"
11194 " off Disable faultsim\n"
11195 " on Activate faultsim\n"
11196 " reset Reset the trigger counter\n"
11197 " status Show current status\n"
11198 " -v Increase verbosity\n"
11199 " -q Decrease verbosity\n"
11200 " --errcode N When triggered, return N as error code\n"
11201 " --id ID Trigger only for the ID specified\n"
11202 " --interval N Trigger only after every N-th call\n"
11203 " --repeat N Turn off after N hits. 0 means never\n"
11204 " --skip N Skip the first N encounters\n"
11207 break;
11211 if( isOk==0 && iCtrl>=0 ){
11212 oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11213 rc = 1;
11214 }else if( isOk==1 ){
11215 oputf("%d\n", rc2);
11216 }else if( isOk==2 ){
11217 oputf("0x%08x\n", rc2);
11219 }else
11220 #endif /* !defined(SQLITE_UNTESTABLE) */
11222 if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
11223 open_db(p, 0);
11224 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11225 }else
11227 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
11228 if( nArg==2 ){
11229 enableTimer = booleanValue(azArg[1]);
11230 if( enableTimer && !HAS_TIMER ){
11231 eputz("Error: timer not available on this system.\n");
11232 enableTimer = 0;
11234 }else{
11235 eputz("Usage: .timer on|off\n");
11236 rc = 1;
11238 }else
11240 #ifndef SQLITE_OMIT_TRACE
11241 if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
11242 int mType = 0;
11243 int jj;
11244 open_db(p, 0);
11245 for(jj=1; jj<nArg; jj++){
11246 const char *z = azArg[jj];
11247 if( z[0]=='-' ){
11248 if( optionMatch(z, "expanded") ){
11249 p->eTraceType = SHELL_TRACE_EXPANDED;
11251 #ifdef SQLITE_ENABLE_NORMALIZE
11252 else if( optionMatch(z, "normalized") ){
11253 p->eTraceType = SHELL_TRACE_NORMALIZED;
11255 #endif
11256 else if( optionMatch(z, "plain") ){
11257 p->eTraceType = SHELL_TRACE_PLAIN;
11259 else if( optionMatch(z, "profile") ){
11260 mType |= SQLITE_TRACE_PROFILE;
11262 else if( optionMatch(z, "row") ){
11263 mType |= SQLITE_TRACE_ROW;
11265 else if( optionMatch(z, "stmt") ){
11266 mType |= SQLITE_TRACE_STMT;
11268 else if( optionMatch(z, "close") ){
11269 mType |= SQLITE_TRACE_CLOSE;
11271 else {
11272 eputf("Unknown option \"%s\" on \".trace\"\n", z);
11273 rc = 1;
11274 goto meta_command_exit;
11276 }else{
11277 output_file_close(p->traceOut);
11278 p->traceOut = output_file_open(z, 0);
11281 if( p->traceOut==0 ){
11282 sqlite3_trace_v2(p->db, 0, 0, 0);
11283 }else{
11284 if( mType==0 ) mType = SQLITE_TRACE_STMT;
11285 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11287 }else
11288 #endif /* !defined(SQLITE_OMIT_TRACE) */
11290 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11291 if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
11292 int ii;
11293 int lenOpt;
11294 char *zOpt;
11295 if( nArg<2 ){
11296 eputz("Usage: .unmodule [--allexcept] NAME ...\n");
11297 rc = 1;
11298 goto meta_command_exit;
11300 open_db(p, 0);
11301 zOpt = azArg[1];
11302 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11303 lenOpt = (int)strlen(zOpt);
11304 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11305 assert( azArg[nArg]==0 );
11306 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11307 }else{
11308 for(ii=1; ii<nArg; ii++){
11309 sqlite3_create_module(p->db, azArg[ii], 0, 0);
11312 }else
11313 #endif
11315 #if SQLITE_USER_AUTHENTICATION
11316 if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
11317 if( nArg<2 ){
11318 eputz("Usage: .user SUBCOMMAND ...\n");
11319 rc = 1;
11320 goto meta_command_exit;
11322 open_db(p, 0);
11323 if( cli_strcmp(azArg[1],"login")==0 ){
11324 if( nArg!=4 ){
11325 eputz("Usage: .user login USER PASSWORD\n");
11326 rc = 1;
11327 goto meta_command_exit;
11329 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11330 strlen30(azArg[3]));
11331 if( rc ){
11332 eputf("Authentication failed for user %s\n", azArg[2]);
11333 rc = 1;
11335 }else if( cli_strcmp(azArg[1],"add")==0 ){
11336 if( nArg!=5 ){
11337 eputz("Usage: .user add USER PASSWORD ISADMIN\n");
11338 rc = 1;
11339 goto meta_command_exit;
11341 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11342 booleanValue(azArg[4]));
11343 if( rc ){
11344 eputf("User-Add failed: %d\n", rc);
11345 rc = 1;
11347 }else if( cli_strcmp(azArg[1],"edit")==0 ){
11348 if( nArg!=5 ){
11349 eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
11350 rc = 1;
11351 goto meta_command_exit;
11353 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11354 booleanValue(azArg[4]));
11355 if( rc ){
11356 eputf("User-Edit failed: %d\n", rc);
11357 rc = 1;
11359 }else if( cli_strcmp(azArg[1],"delete")==0 ){
11360 if( nArg!=3 ){
11361 eputz("Usage: .user delete USER\n");
11362 rc = 1;
11363 goto meta_command_exit;
11365 rc = sqlite3_user_delete(p->db, azArg[2]);
11366 if( rc ){
11367 eputf("User-Delete failed: %d\n", rc);
11368 rc = 1;
11370 }else{
11371 eputz("Usage: .user login|add|edit|delete ...\n");
11372 rc = 1;
11373 goto meta_command_exit;
11375 }else
11376 #endif /* SQLITE_USER_AUTHENTICATION */
11378 if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
11379 char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
11380 oputf("SQLite %s %s\n" /*extra-version-info*/,
11381 sqlite3_libversion(), sqlite3_sourceid());
11382 /* BEGIN SQLCIPHER */
11383 #ifdef SQLITE_HAS_CODEC
11385 extern char* sqlcipher_version();
11386 char *sqlcipher_ver = sqlcipher_version();
11387 oputf("SQLCipher %s\n", sqlcipher_ver);
11388 sqlite3_free(sqlcipher_ver);
11390 #endif
11391 /* END SQLCIPHER */
11392 #if SQLITE_HAVE_ZLIB
11393 oputf("zlib version %s\n", zlibVersion());
11394 #endif
11395 #define CTIMEOPT_VAL_(opt) #opt
11396 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11397 #if defined(__clang__) && defined(__clang_major__)
11398 oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
11399 CTIMEOPT_VAL(__clang_minor__) "."
11400 CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
11401 #elif defined(_MSC_VER)
11402 oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
11403 #elif defined(__GNUC__) && defined(__VERSION__)
11404 oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
11405 #endif
11406 }else
11408 if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
11409 const char *zDbName = nArg==2 ? azArg[1] : "main";
11410 sqlite3_vfs *pVfs = 0;
11411 if( p->db ){
11412 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11413 if( pVfs ){
11414 oputf("vfs.zName = \"%s\"\n", pVfs->zName);
11415 oputf("vfs.iVersion = %d\n", pVfs->iVersion);
11416 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile);
11417 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
11420 }else
11422 if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
11423 sqlite3_vfs *pVfs;
11424 sqlite3_vfs *pCurrent = 0;
11425 if( p->db ){
11426 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11428 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11429 oputf("vfs.zName = \"%s\"%s\n", pVfs->zName,
11430 pVfs==pCurrent ? " <--- CURRENT" : "");
11431 oputf("vfs.iVersion = %d\n", pVfs->iVersion);
11432 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile);
11433 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
11434 if( pVfs->pNext ){
11435 oputz("-----------------------------------\n");
11438 }else
11440 if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
11441 const char *zDbName = nArg==2 ? azArg[1] : "main";
11442 char *zVfsName = 0;
11443 if( p->db ){
11444 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11445 if( zVfsName ){
11446 oputf("%s\n", zVfsName);
11447 sqlite3_free(zVfsName);
11450 }else
11452 if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
11453 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11454 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11455 }else
11457 if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
11458 int j;
11459 assert( nArg<=ArraySize(azArg) );
11460 p->nWidth = nArg-1;
11461 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11462 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11463 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11464 for(j=1; j<nArg; j++){
11465 p->colWidth[j-1] = (int)integerValue(azArg[j]);
11467 }else
11470 eputf("Error: unknown command or invalid arguments: "
11471 " \"%s\". Enter \".help\" for help\n", azArg[0]);
11472 rc = 1;
11475 meta_command_exit:
11476 if( p->outCount ){
11477 p->outCount--;
11478 if( p->outCount==0 ) output_reset(p);
11480 p->bSafeMode = p->bSafeModePersist;
11481 return rc;
11484 /* Line scan result and intermediate states (supporting scan resumption)
11486 #ifndef CHAR_BIT
11487 # define CHAR_BIT 8
11488 #endif
11489 typedef enum {
11490 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11491 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11492 QSS_Start = 0
11493 } QuickScanState;
11494 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11495 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11496 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11497 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11498 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11501 ** Scan line for classification to guide shell's handling.
11502 ** The scan is resumable for subsequent lines when prior
11503 ** return values are passed as the 2nd argument.
11505 static QuickScanState quickscan(char *zLine, QuickScanState qss,
11506 SCAN_TRACKER_REFTYPE pst){
11507 char cin;
11508 char cWait = (char)qss; /* intentional narrowing loss */
11509 if( cWait==0 ){
11510 PlainScan:
11511 assert( cWait==0 );
11512 while( (cin = *zLine++)!=0 ){
11513 if( IsSpace(cin) )
11514 continue;
11515 switch (cin){
11516 case '-':
11517 if( *zLine!='-' )
11518 break;
11519 while((cin = *++zLine)!=0 )
11520 if( cin=='\n')
11521 goto PlainScan;
11522 return qss;
11523 case ';':
11524 qss |= QSS_EndingSemi;
11525 continue;
11526 case '/':
11527 if( *zLine=='*' ){
11528 ++zLine;
11529 cWait = '*';
11530 CONTINUE_PROMPT_AWAITS(pst, "/*");
11531 qss = QSS_SETV(qss, cWait);
11532 goto TermScan;
11534 break;
11535 case '[':
11536 cin = ']';
11537 deliberate_fall_through;
11538 case '`': case '\'': case '"':
11539 cWait = cin;
11540 qss = QSS_HasDark | cWait;
11541 CONTINUE_PROMPT_AWAITC(pst, cin);
11542 goto TermScan;
11543 case '(':
11544 CONTINUE_PAREN_INCR(pst, 1);
11545 break;
11546 case ')':
11547 CONTINUE_PAREN_INCR(pst, -1);
11548 break;
11549 default:
11550 break;
11552 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11554 }else{
11555 TermScan:
11556 while( (cin = *zLine++)!=0 ){
11557 if( cin==cWait ){
11558 switch( cWait ){
11559 case '*':
11560 if( *zLine != '/' )
11561 continue;
11562 ++zLine;
11563 cWait = 0;
11564 CONTINUE_PROMPT_AWAITC(pst, 0);
11565 qss = QSS_SETV(qss, 0);
11566 goto PlainScan;
11567 case '`': case '\'': case '"':
11568 if(*zLine==cWait){
11569 /* Swallow doubled end-delimiter.*/
11570 ++zLine;
11571 continue;
11573 deliberate_fall_through;
11574 case ']':
11575 cWait = 0;
11576 CONTINUE_PROMPT_AWAITC(pst, 0);
11577 qss = QSS_SETV(qss, 0);
11578 goto PlainScan;
11579 default: assert(0);
11584 return qss;
11588 ** Return TRUE if the line typed in is an SQL command terminator other
11589 ** than a semi-colon. The SQL Server style "go" command is understood
11590 ** as is the Oracle "/".
11592 static int line_is_command_terminator(char *zLine){
11593 while( IsSpace(zLine[0]) ){ zLine++; };
11594 if( zLine[0]=='/' )
11595 zLine += 1; /* Oracle */
11596 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11597 zLine += 2; /* SQL Server */
11598 else
11599 return 0;
11600 return quickscan(zLine, QSS_Start, 0)==QSS_Start;
11604 ** The CLI needs a working sqlite3_complete() to work properly. So error
11605 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11607 #ifdef SQLITE_OMIT_COMPLETE
11608 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11609 #endif
11612 ** Return true if zSql is a complete SQL statement. Return false if it
11613 ** ends in the middle of a string literal or C-style comment.
11615 static int line_is_complete(char *zSql, int nSql){
11616 int rc;
11617 if( zSql==0 ) return 1;
11618 zSql[nSql] = ';';
11619 zSql[nSql+1] = 0;
11620 rc = sqlite3_complete(zSql);
11621 zSql[nSql] = 0;
11622 return rc;
11626 ** This function is called after processing each line of SQL in the
11627 ** runOneSqlLine() function. Its purpose is to detect scenarios where
11628 ** defensive mode should be automatically turned off. Specifically, when
11630 ** 1. The first line of input is "PRAGMA foreign_keys=OFF;",
11631 ** 2. The second line of input is "BEGIN TRANSACTION;",
11632 ** 3. The database is empty, and
11633 ** 4. The shell is not running in --safe mode.
11635 ** The implementation uses the ShellState.eRestoreState to maintain state:
11637 ** 0: Have not seen any SQL.
11638 ** 1: Have seen "PRAGMA foreign_keys=OFF;".
11639 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
11640 ** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
11641 ** 7: Nothing left to do. This function becomes a no-op.
11643 static int doAutoDetectRestore(ShellState *p, const char *zSql){
11644 int rc = SQLITE_OK;
11646 if( p->eRestoreState<7 ){
11647 switch( p->eRestoreState ){
11648 case 0: {
11649 const char *zExpect = "PRAGMA foreign_keys=OFF;";
11650 assert( strlen(zExpect)==24 );
11651 if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
11652 p->eRestoreState = 1;
11653 }else{
11654 p->eRestoreState = 7;
11656 break;
11659 case 1: {
11660 int bIsDump = 0;
11661 const char *zExpect = "BEGIN TRANSACTION;";
11662 assert( strlen(zExpect)==18 );
11663 if( memcmp(zSql, zExpect, 19)==0 ){
11664 /* Now check if the database is empty. */
11665 const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
11666 sqlite3_stmt *pStmt = 0;
11668 bIsDump = 1;
11669 shellPrepare(p->db, &rc, zQuery, &pStmt);
11670 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
11671 bIsDump = 0;
11673 shellFinalize(&rc, pStmt);
11675 if( bIsDump && rc==SQLITE_OK ){
11676 int bDefense = 0;
11677 int bDqsDdl = 0;
11678 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
11679 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
11680 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
11681 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
11682 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
11683 }else{
11684 p->eRestoreState = 7;
11686 break;
11689 default: {
11690 if( sqlite3_get_autocommit(p->db) ){
11691 if( (p->eRestoreState & 2) ){
11692 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
11694 if( (p->eRestoreState & 4) ){
11695 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
11697 p->eRestoreState = 7;
11699 break;
11704 return rc;
11708 ** Run a single line of SQL. Return the number of errors.
11710 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11711 int rc;
11712 char *zErrMsg = 0;
11714 open_db(p, 0);
11715 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11716 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11717 BEGIN_TIMER;
11718 rc = shell_exec(p, zSql, &zErrMsg);
11719 END_TIMER;
11720 if( rc || zErrMsg ){
11721 char zPrefix[100];
11722 const char *zErrorTail;
11723 const char *zErrorType;
11724 if( zErrMsg==0 ){
11725 zErrorType = "Error";
11726 zErrorTail = sqlite3_errmsg(p->db);
11727 }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
11728 zErrorType = "Parse error";
11729 zErrorTail = &zErrMsg[12];
11730 }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
11731 zErrorType = "Runtime error";
11732 zErrorTail = &zErrMsg[10];
11733 }else{
11734 zErrorType = "Error";
11735 zErrorTail = zErrMsg;
11737 if( in!=0 || !stdin_is_interactive ){
11738 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11739 "%s near line %d:", zErrorType, startline);
11740 }else{
11741 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11743 eputf("%s %s\n", zPrefix, zErrorTail);
11744 sqlite3_free(zErrMsg);
11745 zErrMsg = 0;
11746 return 1;
11747 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11748 char zLineBuf[2000];
11749 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11750 "changes: %lld total_changes: %lld",
11751 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11752 oputf("%s\n", zLineBuf);
11755 if( doAutoDetectRestore(p, zSql) ) return 1;
11756 return 0;
11759 static void echo_group_input(ShellState *p, const char *zDo){
11760 if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
11763 #ifdef SQLITE_SHELL_FIDDLE
11765 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11766 ** impl because we need the global shellState and cannot access it from that
11767 ** function without moving lots of code around (creating a larger/messier diff).
11769 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11770 /* Parse the next line from shellState.wasm.zInput. */
11771 const char *zBegin = shellState.wasm.zPos;
11772 const char *z = zBegin;
11773 char *zLine = 0;
11774 i64 nZ = 0;
11776 UNUSED_PARAMETER(in);
11777 UNUSED_PARAMETER(isContinuation);
11778 if(!z || !*z){
11779 return 0;
11781 while(*z && isspace(*z)) ++z;
11782 zBegin = z;
11783 for(; *z && '\n'!=*z; ++nZ, ++z){}
11784 if(nZ>0 && '\r'==zBegin[nZ-1]){
11785 --nZ;
11787 shellState.wasm.zPos = z;
11788 zLine = realloc(zPrior, nZ+1);
11789 shell_check_oom(zLine);
11790 memcpy(zLine, zBegin, nZ);
11791 zLine[nZ] = 0;
11792 return zLine;
11794 #endif /* SQLITE_SHELL_FIDDLE */
11797 ** Read input from *in and process it. If *in==0 then input
11798 ** is interactive - the user is typing it it. Otherwise, input
11799 ** is coming from a file or device. A prompt is issued and history
11800 ** is saved only if input is interactive. An interrupt signal will
11801 ** cause this routine to exit immediately, unless input is interactive.
11803 ** Return the number of errors.
11805 static int process_input(ShellState *p){
11806 char *zLine = 0; /* A single input line */
11807 char *zSql = 0; /* Accumulated SQL text */
11808 i64 nLine; /* Length of current line */
11809 i64 nSql = 0; /* Bytes of zSql[] used */
11810 i64 nAlloc = 0; /* Allocated zSql[] space */
11811 int rc; /* Error code */
11812 int errCnt = 0; /* Number of errors seen */
11813 i64 startline = 0; /* Line number for start of current input */
11814 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11816 if( p->inputNesting==MAX_INPUT_NESTING ){
11817 /* This will be more informative in a later version. */
11818 eputf("Input nesting limit (%d) reached at line %d."
11819 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11820 return 1;
11822 ++p->inputNesting;
11823 p->lineno = 0;
11824 CONTINUE_PROMPT_RESET;
11825 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11826 fflush(p->out);
11827 zLine = one_input_line(p->in, zLine, nSql>0);
11828 if( zLine==0 ){
11829 /* End of input */
11830 if( p->in==0 && stdin_is_interactive ) oputz("\n");
11831 break;
11833 if( seenInterrupt ){
11834 if( p->in!=0 ) break;
11835 seenInterrupt = 0;
11837 p->lineno++;
11838 if( QSS_INPLAIN(qss)
11839 && line_is_command_terminator(zLine)
11840 && line_is_complete(zSql, nSql) ){
11841 memcpy(zLine,";",2);
11843 qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
11844 if( QSS_PLAINWHITE(qss) && nSql==0 ){
11845 /* Just swallow single-line whitespace */
11846 echo_group_input(p, zLine);
11847 qss = QSS_Start;
11848 continue;
11850 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11851 CONTINUE_PROMPT_RESET;
11852 echo_group_input(p, zLine);
11853 if( zLine[0]=='.' ){
11854 rc = do_meta_command(zLine, p);
11855 if( rc==2 ){ /* exit requested */
11856 break;
11857 }else if( rc ){
11858 errCnt++;
11861 qss = QSS_Start;
11862 continue;
11864 /* No single-line dispositions remain; accumulate line(s). */
11865 nLine = strlen(zLine);
11866 if( nSql+nLine+2>=nAlloc ){
11867 /* Grow buffer by half-again increments when big. */
11868 nAlloc = nSql+(nSql>>1)+nLine+100;
11869 zSql = realloc(zSql, nAlloc);
11870 shell_check_oom(zSql);
11872 if( nSql==0 ){
11873 i64 i;
11874 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11875 assert( nAlloc>0 && zSql!=0 );
11876 memcpy(zSql, zLine+i, nLine+1-i);
11877 startline = p->lineno;
11878 nSql = nLine-i;
11879 }else{
11880 zSql[nSql++] = '\n';
11881 memcpy(zSql+nSql, zLine, nLine+1);
11882 nSql += nLine;
11884 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11885 echo_group_input(p, zSql);
11886 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11887 CONTINUE_PROMPT_RESET;
11888 nSql = 0;
11889 if( p->outCount ){
11890 output_reset(p);
11891 p->outCount = 0;
11892 }else{
11893 clearTempFile(p);
11895 p->bSafeMode = p->bSafeModePersist;
11896 qss = QSS_Start;
11897 }else if( nSql && QSS_PLAINWHITE(qss) ){
11898 echo_group_input(p, zSql);
11899 nSql = 0;
11900 qss = QSS_Start;
11903 if( nSql ){
11904 /* This may be incomplete. Let the SQL parser deal with that. */
11905 echo_group_input(p, zSql);
11906 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11907 CONTINUE_PROMPT_RESET;
11909 free(zSql);
11910 free(zLine);
11911 --p->inputNesting;
11912 return errCnt>0;
11916 ** Return a pathname which is the user's home directory. A
11917 ** 0 return indicates an error of some kind.
11919 static char *find_home_dir(int clearFlag){
11920 static char *home_dir = NULL;
11921 if( clearFlag ){
11922 free(home_dir);
11923 home_dir = 0;
11924 return 0;
11926 if( home_dir ) return home_dir;
11928 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11929 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11931 struct passwd *pwent;
11932 uid_t uid = getuid();
11933 if( (pwent=getpwuid(uid)) != NULL) {
11934 home_dir = pwent->pw_dir;
11937 #endif
11939 #if defined(_WIN32_WCE)
11940 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11942 home_dir = "/";
11943 #else
11945 #if defined(_WIN32) || defined(WIN32)
11946 if (!home_dir) {
11947 home_dir = getenv("USERPROFILE");
11949 #endif
11951 if (!home_dir) {
11952 home_dir = getenv("HOME");
11955 #if defined(_WIN32) || defined(WIN32)
11956 if (!home_dir) {
11957 char *zDrive, *zPath;
11958 int n;
11959 zDrive = getenv("HOMEDRIVE");
11960 zPath = getenv("HOMEPATH");
11961 if( zDrive && zPath ){
11962 n = strlen30(zDrive) + strlen30(zPath) + 1;
11963 home_dir = malloc( n );
11964 if( home_dir==0 ) return 0;
11965 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11966 return home_dir;
11968 home_dir = "c:\\";
11970 #endif
11972 #endif /* !_WIN32_WCE */
11974 if( home_dir ){
11975 i64 n = strlen(home_dir) + 1;
11976 char *z = malloc( n );
11977 if( z ) memcpy(z, home_dir, n);
11978 home_dir = z;
11981 return home_dir;
11985 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11986 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11987 ** the path to it, else return 0. The result is cached for
11988 ** subsequent calls.
11990 static const char *find_xdg_config(void){
11991 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11992 || defined(__RTP__) || defined(_WRS_KERNEL)
11993 return 0;
11994 #else
11995 static int alreadyTried = 0;
11996 static char *zConfig = 0;
11997 const char *zXdgHome;
11999 if( alreadyTried!=0 ){
12000 return zConfig;
12002 alreadyTried = 1;
12003 zXdgHome = getenv("XDG_CONFIG_HOME");
12004 if( zXdgHome==0 ){
12005 return 0;
12007 zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
12008 shell_check_oom(zConfig);
12009 if( access(zConfig,0)!=0 ){
12010 sqlite3_free(zConfig);
12011 zConfig = 0;
12013 return zConfig;
12014 #endif
12018 ** Read input from the file given by sqliterc_override. Or if that
12019 ** parameter is NULL, take input from the first of find_xdg_config()
12020 ** or ~/.sqliterc which is found.
12022 ** Returns the number of errors.
12024 static void process_sqliterc(
12025 ShellState *p, /* Configuration data */
12026 const char *sqliterc_override /* Name of config file. NULL to use default */
12028 char *home_dir = NULL;
12029 const char *sqliterc = sqliterc_override;
12030 char *zBuf = 0;
12031 FILE *inSaved = p->in;
12032 int savedLineno = p->lineno;
12034 if( sqliterc == NULL ){
12035 sqliterc = find_xdg_config();
12037 if( sqliterc == NULL ){
12038 home_dir = find_home_dir(0);
12039 if( home_dir==0 ){
12040 eputz("-- warning: cannot find home directory;"
12041 " cannot read ~/.sqliterc\n");
12042 return;
12044 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
12045 shell_check_oom(zBuf);
12046 sqliterc = zBuf;
12048 p->in = fopen(sqliterc,"rb");
12049 if( p->in ){
12050 if( stdin_is_interactive ){
12051 eputf("-- Loading resources from %s\n", sqliterc);
12053 if( process_input(p) && bail_on_error ) exit(1);
12054 fclose(p->in);
12055 }else if( sqliterc_override!=0 ){
12056 eputf("cannot open: \"%s\"\n", sqliterc);
12057 if( bail_on_error ) exit(1);
12059 p->in = inSaved;
12060 p->lineno = savedLineno;
12061 sqlite3_free(zBuf);
12065 ** Show available command line options
12067 static const char zOptions[] =
12068 " -- treat no subsequent arguments as options\n"
12069 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
12070 " -A ARGS... run \".archive ARGS\" and exit\n"
12071 #endif
12072 " -append append the database to the end of the file\n"
12073 " -ascii set output mode to 'ascii'\n"
12074 " -bail stop after hitting an error\n"
12075 " -batch force batch I/O\n"
12076 " -box set output mode to 'box'\n"
12077 " -column set output mode to 'column'\n"
12078 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
12079 " -csv set output mode to 'csv'\n"
12080 #if !defined(SQLITE_OMIT_DESERIALIZE)
12081 " -deserialize open the database using sqlite3_deserialize()\n"
12082 #endif
12083 " -echo print inputs before execution\n"
12084 " -init FILENAME read/process named file\n"
12085 " -[no]header turn headers on or off\n"
12086 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12087 " -heap SIZE Size of heap for memsys3 or memsys5\n"
12088 #endif
12089 " -help show this message\n"
12090 " -html set output mode to HTML\n"
12091 " -interactive force interactive I/O\n"
12092 " -json set output mode to 'json'\n"
12093 " -line set output mode to 'line'\n"
12094 " -list set output mode to 'list'\n"
12095 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
12096 " -markdown set output mode to 'markdown'\n"
12097 #if !defined(SQLITE_OMIT_DESERIALIZE)
12098 " -maxsize N maximum size for a --deserialize database\n"
12099 #endif
12100 " -memtrace trace all memory allocations and deallocations\n"
12101 " -mmap N default mmap size set to N\n"
12102 #ifdef SQLITE_ENABLE_MULTIPLEX
12103 " -multiplex enable the multiplexor VFS\n"
12104 #endif
12105 " -newline SEP set output row separator. Default: '\\n'\n"
12106 " -nofollow refuse to open symbolic links to database files\n"
12107 " -nonce STRING set the safe-mode escape nonce\n"
12108 " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n"
12109 " -nullvalue TEXT set text string for NULL values. Default ''\n"
12110 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
12111 " -pcachetrace trace all page cache operations\n"
12112 " -quote set output mode to 'quote'\n"
12113 " -readonly open the database read-only\n"
12114 " -safe enable safe-mode\n"
12115 " -separator SEP set output column separator. Default: '|'\n"
12116 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12117 " -sorterref SIZE sorter references threshold size\n"
12118 #endif
12119 " -stats print memory stats before each finalize\n"
12120 " -table set output mode to 'table'\n"
12121 " -tabs set output mode to 'tabs'\n"
12122 " -unsafe-testing allow unsafe commands and modes for testing\n"
12123 " -version show SQLite version\n"
12124 " -vfs NAME use NAME as the default VFS\n"
12125 #ifdef SQLITE_ENABLE_VFSTRACE
12126 " -vfstrace enable tracing of all VFS calls\n"
12127 #endif
12128 #ifdef SQLITE_HAVE_ZLIB
12129 " -zip open the file as a ZIP Archive\n"
12130 #endif
12132 static void usage(int showDetail){
12133 eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
12134 "FILENAME is the name of an SQLite database. A new database is created\n"
12135 "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
12136 if( showDetail ){
12137 eputf("OPTIONS include:\n%s", zOptions);
12138 }else{
12139 eputz("Use the -help option for additional information\n");
12141 exit(0);
12145 ** Internal check: Verify that the SQLite is uninitialized. Print a
12146 ** error message if it is initialized.
12148 static void verify_uninitialized(void){
12149 if( sqlite3_config(-1)==SQLITE_MISUSE ){
12150 sputz(stdout, "WARNING: attempt to configure SQLite after"
12151 " initialization.\n");
12156 ** Initialize the state information in data
12158 static void main_init(ShellState *data) {
12159 memset(data, 0, sizeof(*data));
12160 data->normalMode = data->cMode = data->mode = MODE_List;
12161 data->autoExplain = 1;
12162 data->pAuxDb = &data->aAuxDb[0];
12163 memcpy(data->colSeparator,SEP_Column, 2);
12164 memcpy(data->rowSeparator,SEP_Row, 2);
12165 data->showHeader = 0;
12166 data->shellFlgs = SHFLG_Lookaside;
12167 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
12168 #if !defined(SQLITE_SHELL_FIDDLE)
12169 verify_uninitialized();
12170 #endif
12171 sqlite3_config(SQLITE_CONFIG_URI, 1);
12172 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
12173 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
12174 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
12178 ** Output text to the console in a font that attracts extra attention.
12180 #if defined(_WIN32) || defined(WIN32)
12181 static void printBold(const char *zText){
12182 #if !SQLITE_OS_WINRT
12183 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
12184 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
12185 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
12186 SetConsoleTextAttribute(out,
12187 FOREGROUND_RED|FOREGROUND_INTENSITY
12189 #endif
12190 sputz(stdout, zText);
12191 #if !SQLITE_OS_WINRT
12192 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
12193 #endif
12195 #else
12196 static void printBold(const char *zText){
12197 sputf(stdout, "\033[1m%s\033[0m", zText);
12199 #endif
12202 ** Get the argument to an --option. Throw an error and die if no argument
12203 ** is available.
12205 static char *cmdline_option_value(int argc, char **argv, int i){
12206 if( i==argc ){
12207 eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
12208 exit(1);
12210 return argv[i];
12213 static void sayAbnormalExit(void){
12214 if( seenInterrupt ) eputz("Program interrupted.\n");
12217 #ifndef SQLITE_SHELL_IS_UTF8
12218 # if (defined(_WIN32) || defined(WIN32)) \
12219 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12220 # define SQLITE_SHELL_IS_UTF8 (0)
12221 # else
12222 # define SQLITE_SHELL_IS_UTF8 (1)
12223 # endif
12224 #endif
12226 #ifdef SQLITE_SHELL_FIDDLE
12227 # define main fiddle_main
12228 #endif
12230 #if SQLITE_SHELL_IS_UTF8
12231 int SQLITE_CDECL main(int argc, char **argv){
12232 #else
12233 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12234 char **argv;
12235 #endif
12236 #ifdef SQLITE_DEBUG
12237 sqlite3_int64 mem_main_enter = 0;
12238 #endif
12239 char *zErrMsg = 0;
12240 #ifdef SQLITE_SHELL_FIDDLE
12241 # define data shellState
12242 #else
12243 ShellState data;
12244 StreamsAreConsole consStreams = SAC_NoConsole;
12245 #endif
12246 const char *zInitFile = 0;
12247 int i;
12248 int rc = 0;
12249 int warnInmemoryDb = 0;
12250 int readStdin = 1;
12251 int nCmd = 0;
12252 int nOptsEnd = argc;
12253 char **azCmd = 0;
12254 const char *zVfs = 0; /* Value of -vfs command-line option */
12255 #if !SQLITE_SHELL_IS_UTF8
12256 char **argvToFree = 0;
12257 int argcToFree = 0;
12258 #endif
12259 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12261 #ifdef SQLITE_SHELL_FIDDLE
12262 stdin_is_interactive = 0;
12263 stdout_is_console = 1;
12264 data.wasm.zDefaultDbName = "/fiddle.sqlite3";
12265 #else
12266 consStreams = consoleClassifySetup(stdin, stdout, stderr);
12267 stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
12268 stdout_is_console = (consStreams & SAC_OutConsole)!=0;
12269 atexit(consoleRestore);
12270 #endif
12271 atexit(sayAbnormalExit);
12272 #ifdef SQLITE_DEBUG
12273 mem_main_enter = sqlite3_memory_used();
12274 #endif
12275 #if !defined(_WIN32_WCE)
12276 if( getenv("SQLITE_DEBUG_BREAK") ){
12277 if( isatty(0) && isatty(2) ){
12278 eputf("attach debugger to process %d and press any key to continue.\n",
12279 GETPID());
12280 fgetc(stdin);
12281 }else{
12282 #if defined(_WIN32) || defined(WIN32)
12283 #if SQLITE_OS_WINRT
12284 __debugbreak();
12285 #else
12286 DebugBreak();
12287 #endif
12288 #elif defined(SIGTRAP)
12289 raise(SIGTRAP);
12290 #endif
12293 #endif
12294 /* Register a valid signal handler early, before much else is done. */
12295 #ifdef SIGINT
12296 signal(SIGINT, interrupt_handler);
12297 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12298 if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
12299 eputz("No ^C handler.\n");
12301 #endif
12303 #if USE_SYSTEM_SQLITE+0!=1
12304 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12305 eputf("SQLite header and source version mismatch\n%s\n%s\n",
12306 sqlite3_sourceid(), SQLITE_SOURCE_ID);
12307 exit(1);
12309 #endif
12310 main_init(&data);
12312 /* On Windows, we must translate command-line arguments into UTF-8.
12313 ** The SQLite memory allocator subsystem has to be enabled in order to
12314 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12315 ** subsequent sqlite3_config() calls will work. So copy all results into
12316 ** memory that does not come from the SQLite memory allocator.
12318 #if !SQLITE_SHELL_IS_UTF8
12319 sqlite3_initialize();
12320 argvToFree = malloc(sizeof(argv[0])*argc*2);
12321 shell_check_oom(argvToFree);
12322 argcToFree = argc;
12323 argv = argvToFree + argc;
12324 for(i=0; i<argc; i++){
12325 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12326 i64 n;
12327 shell_check_oom(z);
12328 n = strlen(z);
12329 argv[i] = malloc( n+1 );
12330 shell_check_oom(argv[i]);
12331 memcpy(argv[i], z, n+1);
12332 argvToFree[i] = argv[i];
12333 sqlite3_free(z);
12335 sqlite3_shutdown();
12336 #endif
12338 assert( argc>=1 && argv && argv[0] );
12339 Argv0 = argv[0];
12341 #ifdef SQLITE_SHELL_DBNAME_PROC
12343 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12344 ** of a C-function that will provide the name of the database file. Use
12345 ** this compile-time option to embed this shell program in larger
12346 ** applications. */
12347 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12348 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12349 warnInmemoryDb = 0;
12351 #endif
12353 /* Do an initial pass through the command-line argument to locate
12354 ** the name of the database file, the name of the initialization file,
12355 ** the size of the alternative malloc heap, options affecting commands
12356 ** or SQL run from the command line, and the first command to execute.
12358 #ifndef SQLITE_SHELL_FIDDLE
12359 verify_uninitialized();
12360 #endif
12361 for(i=1; i<argc; i++){
12362 char *z;
12363 z = argv[i];
12364 if( z[0]!='-' || i>nOptsEnd ){
12365 if( data.aAuxDb->zDbFilename==0 ){
12366 data.aAuxDb->zDbFilename = z;
12367 }else{
12368 /* Excess arguments are interpreted as SQL (or dot-commands) and
12369 ** mean that nothing is read from stdin */
12370 readStdin = 0;
12371 nCmd++;
12372 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12373 shell_check_oom(azCmd);
12374 azCmd[nCmd-1] = z;
12376 continue;
12378 if( z[1]=='-' ) z++;
12379 if( cli_strcmp(z, "-")==0 ){
12380 nOptsEnd = i;
12381 continue;
12382 }else if( cli_strcmp(z,"-separator")==0
12383 || cli_strcmp(z,"-nullvalue")==0
12384 || cli_strcmp(z,"-newline")==0
12385 || cli_strcmp(z,"-cmd")==0
12387 (void)cmdline_option_value(argc, argv, ++i);
12388 }else if( cli_strcmp(z,"-init")==0 ){
12389 zInitFile = cmdline_option_value(argc, argv, ++i);
12390 }else if( cli_strcmp(z,"-interactive")==0 ){
12391 }else if( cli_strcmp(z,"-batch")==0 ){
12392 /* Need to check for batch mode here to so we can avoid printing
12393 ** informational messages (like from process_sqliterc) before
12394 ** we do the actual processing of arguments later in a second pass.
12396 stdin_is_interactive = 0;
12397 }else if( cli_strcmp(z,"-utf8")==0 ){
12398 }else if( cli_strcmp(z,"-no-utf8")==0 ){
12399 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
12400 int val = 0;
12401 sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
12402 assert( val==0 );
12403 }else if( cli_strcmp(z,"-heap")==0 ){
12404 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12405 const char *zSize;
12406 sqlite3_int64 szHeap;
12408 zSize = cmdline_option_value(argc, argv, ++i);
12409 szHeap = integerValue(zSize);
12410 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12411 verify_uninitialized();
12412 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12413 #else
12414 (void)cmdline_option_value(argc, argv, ++i);
12415 #endif
12416 }else if( cli_strcmp(z,"-pagecache")==0 ){
12417 sqlite3_int64 n, sz;
12418 sz = integerValue(cmdline_option_value(argc,argv,++i));
12419 if( sz>70000 ) sz = 70000;
12420 if( sz<0 ) sz = 0;
12421 n = integerValue(cmdline_option_value(argc,argv,++i));
12422 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12423 n = 0xffffffffffffLL/sz;
12425 verify_uninitialized();
12426 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12427 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12428 data.shellFlgs |= SHFLG_Pagecache;
12429 }else if( cli_strcmp(z,"-lookaside")==0 ){
12430 int n, sz;
12431 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12432 if( sz<0 ) sz = 0;
12433 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12434 if( n<0 ) n = 0;
12435 verify_uninitialized();
12436 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12437 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12438 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12439 int n;
12440 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12441 verify_uninitialized();
12442 switch( n ){
12443 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
12444 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
12445 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
12447 #ifdef SQLITE_ENABLE_VFSTRACE
12448 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12449 extern int vfstrace_register(
12450 const char *zTraceName,
12451 const char *zOldVfsName,
12452 int (*xOut)(const char*,void*),
12453 void *pOutArg,
12454 int makeDefault
12456 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12457 #endif
12458 #ifdef SQLITE_ENABLE_MULTIPLEX
12459 }else if( cli_strcmp(z,"-multiplex")==0 ){
12460 extern int sqlite3_multiplex_initialize(const char*,int);
12461 sqlite3_multiplex_initialize(0, 1);
12462 #endif
12463 }else if( cli_strcmp(z,"-mmap")==0 ){
12464 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12465 verify_uninitialized();
12466 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12467 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
12468 }else if( cli_strcmp(z,"-sorterref")==0 ){
12469 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12470 verify_uninitialized();
12471 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12472 #endif
12473 }else if( cli_strcmp(z,"-vfs")==0 ){
12474 zVfs = cmdline_option_value(argc, argv, ++i);
12475 #ifdef SQLITE_HAVE_ZLIB
12476 }else if( cli_strcmp(z,"-zip")==0 ){
12477 data.openMode = SHELL_OPEN_ZIPFILE;
12478 #endif
12479 }else if( cli_strcmp(z,"-append")==0 ){
12480 data.openMode = SHELL_OPEN_APPENDVFS;
12481 #ifndef SQLITE_OMIT_DESERIALIZE
12482 }else if( cli_strcmp(z,"-deserialize")==0 ){
12483 data.openMode = SHELL_OPEN_DESERIALIZE;
12484 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12485 data.szMax = integerValue(argv[++i]);
12486 #endif
12487 }else if( cli_strcmp(z,"-readonly")==0 ){
12488 data.openMode = SHELL_OPEN_READONLY;
12489 }else if( cli_strcmp(z,"-nofollow")==0 ){
12490 data.openFlags = SQLITE_OPEN_NOFOLLOW;
12491 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12492 }else if( cli_strncmp(z, "-A",2)==0 ){
12493 /* All remaining command-line arguments are passed to the ".archive"
12494 ** command, so ignore them */
12495 break;
12496 #endif
12497 }else if( cli_strcmp(z, "-memtrace")==0 ){
12498 sqlite3MemTraceActivate(stderr);
12499 }else if( cli_strcmp(z, "-pcachetrace")==0 ){
12500 sqlite3PcacheTraceActivate(stderr);
12501 }else if( cli_strcmp(z,"-bail")==0 ){
12502 bail_on_error = 1;
12503 }else if( cli_strcmp(z,"-nonce")==0 ){
12504 free(data.zNonce);
12505 data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
12506 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12507 ShellSetFlag(&data,SHFLG_TestingMode);
12508 }else if( cli_strcmp(z,"-safe")==0 ){
12509 /* no-op - catch this on the second pass */
12512 #ifndef SQLITE_SHELL_FIDDLE
12513 verify_uninitialized();
12514 #endif
12517 #ifdef SQLITE_SHELL_INIT_PROC
12519 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12520 ** of a C-function that will perform initialization actions on SQLite that
12521 ** occur just before or after sqlite3_initialize(). Use this compile-time
12522 ** option to embed this shell program in larger applications. */
12523 extern void SQLITE_SHELL_INIT_PROC(void);
12524 SQLITE_SHELL_INIT_PROC();
12526 #else
12527 /* All the sqlite3_config() calls have now been made. So it is safe
12528 ** to call sqlite3_initialize() and process any command line -vfs option. */
12529 sqlite3_initialize();
12530 #endif
12532 if( zVfs ){
12533 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12534 if( pVfs ){
12535 sqlite3_vfs_register(pVfs, 1);
12536 }else{
12537 eputf("no such VFS: \"%s\"\n", zVfs);
12538 exit(1);
12542 if( data.pAuxDb->zDbFilename==0 ){
12543 #ifndef SQLITE_OMIT_MEMORYDB
12544 data.pAuxDb->zDbFilename = ":memory:";
12545 warnInmemoryDb = argc==1;
12546 #else
12547 eputf("%s: Error: no database filename specified\n", Argv0);
12548 return 1;
12549 #endif
12551 data.out = stdout;
12552 #ifndef SQLITE_SHELL_FIDDLE
12553 sqlite3_appendvfs_init(0,0,0);
12554 #endif
12556 /* Go ahead and open the database file if it already exists. If the
12557 ** file does not exist, delay opening it. This prevents empty database
12558 ** files from being created if a user mistypes the database name argument
12559 ** to the sqlite command-line tool.
12561 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12562 open_db(&data, 0);
12565 /* Process the initialization file if there is one. If no -init option
12566 ** is given on the command line, look for a file named ~/.sqliterc and
12567 ** try to process it.
12569 process_sqliterc(&data,zInitFile);
12571 /* Make a second pass through the command-line argument and set
12572 ** options. This second pass is delayed until after the initialization
12573 ** file is processed so that the command-line arguments will override
12574 ** settings in the initialization file.
12576 for(i=1; i<argc; i++){
12577 char *z = argv[i];
12578 if( z[0]!='-' || i>=nOptsEnd ) continue;
12579 if( z[1]=='-' ){ z++; }
12580 if( cli_strcmp(z,"-init")==0 ){
12581 i++;
12582 }else if( cli_strcmp(z,"-html")==0 ){
12583 data.mode = MODE_Html;
12584 }else if( cli_strcmp(z,"-list")==0 ){
12585 data.mode = MODE_List;
12586 }else if( cli_strcmp(z,"-quote")==0 ){
12587 data.mode = MODE_Quote;
12588 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12589 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12590 }else if( cli_strcmp(z,"-line")==0 ){
12591 data.mode = MODE_Line;
12592 }else if( cli_strcmp(z,"-column")==0 ){
12593 data.mode = MODE_Column;
12594 }else if( cli_strcmp(z,"-json")==0 ){
12595 data.mode = MODE_Json;
12596 }else if( cli_strcmp(z,"-markdown")==0 ){
12597 data.mode = MODE_Markdown;
12598 }else if( cli_strcmp(z,"-table")==0 ){
12599 data.mode = MODE_Table;
12600 }else if( cli_strcmp(z,"-box")==0 ){
12601 data.mode = MODE_Box;
12602 }else if( cli_strcmp(z,"-csv")==0 ){
12603 data.mode = MODE_Csv;
12604 memcpy(data.colSeparator,",",2);
12605 #ifdef SQLITE_HAVE_ZLIB
12606 }else if( cli_strcmp(z,"-zip")==0 ){
12607 data.openMode = SHELL_OPEN_ZIPFILE;
12608 #endif
12609 }else if( cli_strcmp(z,"-append")==0 ){
12610 data.openMode = SHELL_OPEN_APPENDVFS;
12611 #ifndef SQLITE_OMIT_DESERIALIZE
12612 }else if( cli_strcmp(z,"-deserialize")==0 ){
12613 data.openMode = SHELL_OPEN_DESERIALIZE;
12614 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12615 data.szMax = integerValue(argv[++i]);
12616 #endif
12617 }else if( cli_strcmp(z,"-readonly")==0 ){
12618 data.openMode = SHELL_OPEN_READONLY;
12619 }else if( cli_strcmp(z,"-nofollow")==0 ){
12620 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12621 }else if( cli_strcmp(z,"-ascii")==0 ){
12622 data.mode = MODE_Ascii;
12623 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
12624 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
12625 }else if( cli_strcmp(z,"-tabs")==0 ){
12626 data.mode = MODE_List;
12627 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
12628 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
12629 }else if( cli_strcmp(z,"-separator")==0 ){
12630 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12631 "%s",cmdline_option_value(argc,argv,++i));
12632 }else if( cli_strcmp(z,"-newline")==0 ){
12633 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12634 "%s",cmdline_option_value(argc,argv,++i));
12635 }else if( cli_strcmp(z,"-nullvalue")==0 ){
12636 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12637 "%s",cmdline_option_value(argc,argv,++i));
12638 }else if( cli_strcmp(z,"-header")==0 ){
12639 data.showHeader = 1;
12640 ShellSetFlag(&data, SHFLG_HeaderSet);
12641 }else if( cli_strcmp(z,"-noheader")==0 ){
12642 data.showHeader = 0;
12643 ShellSetFlag(&data, SHFLG_HeaderSet);
12644 }else if( cli_strcmp(z,"-echo")==0 ){
12645 ShellSetFlag(&data, SHFLG_Echo);
12646 }else if( cli_strcmp(z,"-eqp")==0 ){
12647 data.autoEQP = AUTOEQP_on;
12648 }else if( cli_strcmp(z,"-eqpfull")==0 ){
12649 data.autoEQP = AUTOEQP_full;
12650 }else if( cli_strcmp(z,"-stats")==0 ){
12651 data.statsOn = 1;
12652 }else if( cli_strcmp(z,"-scanstats")==0 ){
12653 data.scanstatsOn = 1;
12654 }else if( cli_strcmp(z,"-backslash")==0 ){
12655 /* Undocumented command-line option: -backslash
12656 ** Causes C-style backslash escapes to be evaluated in SQL statements
12657 ** prior to sending the SQL into SQLite. Useful for injecting
12658 ** crazy bytes in the middle of SQL statements for testing and debugging.
12660 ShellSetFlag(&data, SHFLG_Backslash);
12661 }else if( cli_strcmp(z,"-bail")==0 ){
12662 /* No-op. The bail_on_error flag should already be set. */
12663 }else if( cli_strcmp(z,"-version")==0 ){
12664 /* BEGIN SQLCIPHER */
12665 #ifdef SQLITE_HAS_CODEC
12666 extern char* sqlcipher_version();
12667 char *sqlcipher_ver = sqlcipher_version();
12668 sputf(stdout, "%s %s (%d-bit)",
12669 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
12670 sputf(stdout, " (SQLCipher %s)\n", sqlcipher_ver);
12671 sqlite3_free(sqlcipher_ver);
12672 #else
12673 sputf(stdout, "%s %s (%d-bit)\n",
12674 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
12675 #endif
12676 /* END SQLCIPHER */
12677 return 0;
12678 }else if( cli_strcmp(z,"-interactive")==0 ){
12679 /* Need to check for interactive override here to so that it can
12680 ** affect console setup (for Windows only) and testing thereof.
12682 stdin_is_interactive = 1;
12683 }else if( cli_strcmp(z,"-batch")==0 ){
12684 /* already handled */
12685 }else if( cli_strcmp(z,"-utf8")==0 ){
12686 /* already handled */
12687 }else if( cli_strcmp(z,"-no-utf8")==0 ){
12688 /* already handled */
12689 }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
12690 /* already handled */
12691 }else if( cli_strcmp(z,"-heap")==0 ){
12692 i++;
12693 }else if( cli_strcmp(z,"-pagecache")==0 ){
12694 i+=2;
12695 }else if( cli_strcmp(z,"-lookaside")==0 ){
12696 i+=2;
12697 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12698 i+=2;
12699 }else if( cli_strcmp(z,"-nonce")==0 ){
12700 i += 2;
12701 }else if( cli_strcmp(z,"-mmap")==0 ){
12702 i++;
12703 }else if( cli_strcmp(z,"-memtrace")==0 ){
12704 i++;
12705 }else if( cli_strcmp(z,"-pcachetrace")==0 ){
12706 i++;
12707 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12708 }else if( cli_strcmp(z,"-sorterref")==0 ){
12709 i++;
12710 #endif
12711 }else if( cli_strcmp(z,"-vfs")==0 ){
12712 i++;
12713 #ifdef SQLITE_ENABLE_VFSTRACE
12714 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12715 i++;
12716 #endif
12717 #ifdef SQLITE_ENABLE_MULTIPLEX
12718 }else if( cli_strcmp(z,"-multiplex")==0 ){
12719 i++;
12720 #endif
12721 }else if( cli_strcmp(z,"-help")==0 ){
12722 usage(1);
12723 }else if( cli_strcmp(z,"-cmd")==0 ){
12724 /* Run commands that follow -cmd first and separately from commands
12725 ** that simply appear on the command-line. This seems goofy. It would
12726 ** be better if all commands ran in the order that they appear. But
12727 ** we retain the goofy behavior for historical compatibility. */
12728 if( i==argc-1 ) break;
12729 z = cmdline_option_value(argc,argv,++i);
12730 if( z[0]=='.' ){
12731 rc = do_meta_command(z, &data);
12732 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12733 }else{
12734 open_db(&data, 0);
12735 rc = shell_exec(&data, z, &zErrMsg);
12736 if( zErrMsg!=0 ){
12737 eputf("Error: %s\n", zErrMsg);
12738 if( bail_on_error ) return rc!=0 ? rc : 1;
12739 }else if( rc!=0 ){
12740 eputf("Error: unable to process SQL \"%s\"\n", z);
12741 if( bail_on_error ) return rc;
12744 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12745 }else if( cli_strncmp(z, "-A", 2)==0 ){
12746 if( nCmd>0 ){
12747 eputf("Error: cannot mix regular SQL or dot-commands"
12748 " with \"%s\"\n", z);
12749 return 1;
12751 open_db(&data, OPEN_DB_ZIPFILE);
12752 if( z[2] ){
12753 argv[i] = &z[2];
12754 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12755 }else{
12756 arDotCommand(&data, 1, argv+i, argc-i);
12758 readStdin = 0;
12759 break;
12760 #endif
12761 }else if( cli_strcmp(z,"-safe")==0 ){
12762 data.bSafeMode = data.bSafeModePersist = 1;
12763 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12764 /* Acted upon in first pass. */
12765 }else{
12766 eputf("%s: Error: unknown option: %s\n", Argv0, z);
12767 eputz("Use -help for a list of options.\n");
12768 return 1;
12770 data.cMode = data.mode;
12773 if( !readStdin ){
12774 /* Run all arguments that do not begin with '-' as if they were separate
12775 ** command-line inputs, except for the argToSkip argument which contains
12776 ** the database filename.
12778 for(i=0; i<nCmd; i++){
12779 if( azCmd[i][0]=='.' ){
12780 rc = do_meta_command(azCmd[i], &data);
12781 if( rc ){
12782 free(azCmd);
12783 return rc==2 ? 0 : rc;
12785 }else{
12786 open_db(&data, 0);
12787 echo_group_input(&data, azCmd[i]);
12788 rc = shell_exec(&data, azCmd[i], &zErrMsg);
12789 if( zErrMsg || rc ){
12790 if( zErrMsg!=0 ){
12791 eputf("Error: %s\n", zErrMsg);
12792 }else{
12793 eputf("Error: unable to process SQL: %s\n", azCmd[i]);
12795 sqlite3_free(zErrMsg);
12796 free(azCmd);
12797 return rc!=0 ? rc : 1;
12801 }else{
12802 /* Run commands received from standard input
12804 if( stdin_is_interactive ){
12805 char *zHome;
12806 char *zHistory;
12807 int nHistory;
12808 #if CIO_WIN_WC_XLATE
12809 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
12810 #else
12811 # define SHELL_CIO_CHAR_SET ""
12812 #endif
12813 /* BEGIN SQLCIPHER */
12814 #ifdef SQLITE_HAS_CODEC
12816 extern char* sqlcipher_version();
12817 char *sqlcipher_ver = sqlcipher_version();
12818 sputf(stdout, "SQLite version %s %.19s%s" /*extra-version-info*/
12819 " (SQLCipher %s)\n" /*sqlcipher version info*/
12820 "Enter \".help\" for usage hints.\n",
12821 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET, sqlcipher_ver);
12822 sqlite3_free(sqlcipher_ver);
12824 #else
12825 sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
12826 "Enter \".help\" for usage hints.\n",
12827 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
12828 #endif
12829 /* END SQLCIPHER */
12830 if( warnInmemoryDb ){
12831 sputz(stdout, "Connected to a ");
12832 printBold("transient in-memory database");
12833 sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
12834 " persistent database.\n");
12836 zHistory = getenv("SQLITE_HISTORY");
12837 if( zHistory ){
12838 zHistory = strdup(zHistory);
12839 }else if( (zHome = find_home_dir(0))!=0 ){
12840 nHistory = strlen30(zHome) + 20;
12841 if( (zHistory = malloc(nHistory))!=0 ){
12842 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12845 if( zHistory ){ shell_read_history(zHistory); }
12846 #if HAVE_READLINE || HAVE_EDITLINE
12847 rl_attempted_completion_function = readline_completion;
12848 #elif HAVE_LINENOISE
12849 linenoiseSetCompletionCallback(linenoise_completion);
12850 #endif
12851 data.in = 0;
12852 rc = process_input(&data);
12853 if( zHistory ){
12854 shell_stifle_history(2000);
12855 shell_write_history(zHistory);
12856 free(zHistory);
12858 }else{
12859 data.in = stdin;
12860 rc = process_input(&data);
12863 #ifndef SQLITE_SHELL_FIDDLE
12864 /* In WASM mode we have to leave the db state in place so that
12865 ** client code can "push" SQL into it after this call returns. */
12866 #ifndef SQLITE_OMIT_VIRTUALTABLE
12867 if( data.expert.pExpert ){
12868 expertFinish(&data, 1, 0);
12870 #endif
12871 free(azCmd);
12872 set_table_name(&data, 0);
12873 if( data.db ){
12874 session_close_all(&data, -1);
12875 close_db(data.db);
12877 for(i=0; i<ArraySize(data.aAuxDb); i++){
12878 sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12879 if( data.aAuxDb[i].db ){
12880 session_close_all(&data, i);
12881 close_db(data.aAuxDb[i].db);
12884 find_home_dir(1);
12885 output_reset(&data);
12886 data.doXdgOpen = 0;
12887 clearTempFile(&data);
12888 #if !SQLITE_SHELL_IS_UTF8
12889 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12890 free(argvToFree);
12891 #endif
12892 free(data.colWidth);
12893 free(data.zNonce);
12894 /* Clear the global data structure so that valgrind will detect memory
12895 ** leaks */
12896 memset(&data, 0, sizeof(data));
12897 #ifdef SQLITE_DEBUG
12898 if( sqlite3_memory_used()>mem_main_enter ){
12899 eputf("Memory leaked: %u bytes\n",
12900 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12902 #endif
12903 #endif /* !SQLITE_SHELL_FIDDLE */
12904 return rc;
12908 #ifdef SQLITE_SHELL_FIDDLE
12909 /* Only for emcc experimentation purposes. */
12910 int fiddle_experiment(int a,int b){
12911 return a + b;
12915 ** Returns a pointer to the current DB handle.
12917 sqlite3 * fiddle_db_handle(){
12918 return globalDb;
12922 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12923 ** "main" is assumed. Returns 0 if no db with the given name is
12924 ** open.
12926 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12927 sqlite3_vfs * pVfs = 0;
12928 if(globalDb){
12929 sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12930 SQLITE_FCNTL_VFS_POINTER, &pVfs);
12932 return pVfs;
12935 /* Only for emcc experimentation purposes. */
12936 sqlite3 * fiddle_db_arg(sqlite3 *arg){
12937 oputf("fiddle_db_arg(%p)\n", (const void*)arg);
12938 return arg;
12942 ** Intended to be called via a SharedWorker() while a separate
12943 ** SharedWorker() (which manages the wasm module) is performing work
12944 ** which should be interrupted. Unfortunately, SharedWorker is not
12945 ** portable enough to make real use of.
12947 void fiddle_interrupt(void){
12948 if( globalDb ) sqlite3_interrupt(globalDb);
12952 ** Returns the filename of the given db name, assuming "main" if
12953 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12955 const char * fiddle_db_filename(const char * zDbName){
12956 return globalDb
12957 ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12958 : NULL;
12962 ** Completely wipes out the contents of the currently-opened database
12963 ** but leaves its storage intact for reuse. If any transactions are
12964 ** active, they are forcibly rolled back.
12966 void fiddle_reset_db(void){
12967 if( globalDb ){
12968 int rc;
12969 while( sqlite3_txn_state(globalDb,0)>0 ){
12971 ** Resolve problem reported in
12972 ** https://sqlite.org/forum/forumpost/0b41a25d65
12974 oputz("Rolling back in-progress transaction.\n");
12975 sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
12977 rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12978 if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12979 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12984 ** Uses the current database's VFS xRead to stream the db file's
12985 ** contents out to the given callback. The callback gets a single
12986 ** chunk of size n (its 2nd argument) on each call and must return 0
12987 ** on success, non-0 on error. This function returns 0 on success,
12988 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12989 ** code from the callback. Note that this is not thread-friendly: it
12990 ** expects that it will be the only thread reading the db file and
12991 ** takes no measures to ensure that is the case.
12993 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12994 sqlite3_int64 nSize = 0;
12995 sqlite3_int64 nPos = 0;
12996 sqlite3_file * pFile = 0;
12997 unsigned char buf[1024 * 8];
12998 int nBuf = (int)sizeof(buf);
12999 int rc = shellState.db
13000 ? sqlite3_file_control(shellState.db, "main",
13001 SQLITE_FCNTL_FILE_POINTER, &pFile)
13002 : SQLITE_NOTFOUND;
13003 if( rc ) return rc;
13004 rc = pFile->pMethods->xFileSize(pFile, &nSize);
13005 if( rc ) return rc;
13006 if(nSize % nBuf){
13007 /* DB size is not an even multiple of the buffer size. Reduce
13008 ** buffer size so that we do not unduly inflate the db size when
13009 ** exporting. */
13010 if(0 == nSize % 4096) nBuf = 4096;
13011 else if(0 == nSize % 2048) nBuf = 2048;
13012 else if(0 == nSize % 1024) nBuf = 1024;
13013 else nBuf = 512;
13015 for( ; 0==rc && nPos<nSize; nPos += nBuf ){
13016 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
13017 if(SQLITE_IOERR_SHORT_READ == rc){
13018 rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
13020 if( 0==rc ) rc = xCallback(buf, nBuf);
13022 return rc;
13026 ** Trivial exportable function for emscripten. It processes zSql as if
13027 ** it were input to the sqlite3 shell and redirects all output to the
13028 ** wasm binding. fiddle_main() must have been called before this
13029 ** is called, or results are undefined.
13031 void fiddle_exec(const char * zSql){
13032 if(zSql && *zSql){
13033 if('.'==*zSql) puts(zSql);
13034 shellState.wasm.zInput = zSql;
13035 shellState.wasm.zPos = zSql;
13036 process_input(&shellState);
13037 shellState.wasm.zInput = shellState.wasm.zPos = 0;
13040 #endif /* SQLITE_SHELL_FIDDLE */