allow exclusion of device-specific log functionality via SQLCIPHER_OMIT_LOG_DEVICE
[sqlcipher.git] / src / shell.c.in
blob16aade94591e1ee0a616a2020f39e1a81429407e
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 # define sputz(s,z) fPutsUtf8(z,s)
273 # define sputf fPrintfUtf8
274 # define oputz(z) oPutsUtf8(z)
275 # define oputf oPrintfUtf8
276 # define eputz(z) ePutsUtf8(z)
277 # define eputf ePrintfUtf8
278 # define oputb(buf,na) oPutbUtf8(buf,na)
280 #else
281 /* For Fiddle, all console handling and emit redirection is omitted. */
282 # define sputz(fp,z) fputs(z,fp)
283 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
284 # define oputz(z) fputs(z,stdout)
285 # define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
286 # define eputz(z) fputs(z,stderr)
287 # define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
288 # define oputb(buf,na) fwrite(buf,1,na,stdout)
289 #endif
291 /* True if the timer is enabled */
292 static int enableTimer = 0;
294 /* A version of strcmp() that works with NULL values */
295 static int cli_strcmp(const char *a, const char *b){
296 if( a==0 ) a = "";
297 if( b==0 ) b = "";
298 return strcmp(a,b);
300 static int cli_strncmp(const char *a, const char *b, size_t n){
301 if( a==0 ) a = "";
302 if( b==0 ) b = "";
303 return strncmp(a,b,n);
306 /* Return the current wall-clock time */
307 static sqlite3_int64 timeOfDay(void){
308 static sqlite3_vfs *clockVfs = 0;
309 sqlite3_int64 t;
310 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
311 if( clockVfs==0 ) return 0; /* Never actually happens */
312 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
313 clockVfs->xCurrentTimeInt64(clockVfs, &t);
314 }else{
315 double r;
316 clockVfs->xCurrentTime(clockVfs, &r);
317 t = (sqlite3_int64)(r*86400000.0);
319 return t;
322 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
323 #include <sys/time.h>
324 #include <sys/resource.h>
326 /* VxWorks does not support getrusage() as far as we can determine */
327 #if defined(_WRS_KERNEL) || defined(__RTP__)
328 struct rusage {
329 struct timeval ru_utime; /* user CPU time used */
330 struct timeval ru_stime; /* system CPU time used */
332 #define getrusage(A,B) memset(B,0,sizeof(*B))
333 #endif
335 /* Saved resource information for the beginning of an operation */
336 static struct rusage sBegin; /* CPU time at start */
337 static sqlite3_int64 iBegin; /* Wall-clock time at start */
340 ** Begin timing an operation
342 static void beginTimer(void){
343 if( enableTimer ){
344 getrusage(RUSAGE_SELF, &sBegin);
345 iBegin = timeOfDay();
349 /* Return the difference of two time_structs in seconds */
350 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
351 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
352 (double)(pEnd->tv_sec - pStart->tv_sec);
356 ** Print the timing results.
358 static void endTimer(void){
359 if( enableTimer ){
360 sqlite3_int64 iEnd = timeOfDay();
361 struct rusage sEnd;
362 getrusage(RUSAGE_SELF, &sEnd);
363 sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
364 (iEnd - iBegin)*0.001,
365 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
366 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
370 #define BEGIN_TIMER beginTimer()
371 #define END_TIMER endTimer()
372 #define HAS_TIMER 1
374 #elif (defined(_WIN32) || defined(WIN32))
376 /* Saved resource information for the beginning of an operation */
377 static HANDLE hProcess;
378 static FILETIME ftKernelBegin;
379 static FILETIME ftUserBegin;
380 static sqlite3_int64 ftWallBegin;
381 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
382 LPFILETIME, LPFILETIME);
383 static GETPROCTIMES getProcessTimesAddr = NULL;
386 ** Check to see if we have timer support. Return 1 if necessary
387 ** support found (or found previously).
389 static int hasTimer(void){
390 if( getProcessTimesAddr ){
391 return 1;
392 } else {
393 #if !SQLITE_OS_WINRT
394 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
395 ** versions. See if the version we are running on has it, and if it
396 ** does, save off a pointer to it and the current process handle.
398 hProcess = GetCurrentProcess();
399 if( hProcess ){
400 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
401 if( NULL != hinstLib ){
402 getProcessTimesAddr =
403 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
404 if( NULL != getProcessTimesAddr ){
405 return 1;
407 FreeLibrary(hinstLib);
410 #endif
412 return 0;
416 ** Begin timing an operation
418 static void beginTimer(void){
419 if( enableTimer && getProcessTimesAddr ){
420 FILETIME ftCreation, ftExit;
421 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
422 &ftKernelBegin,&ftUserBegin);
423 ftWallBegin = timeOfDay();
427 /* Return the difference of two FILETIME structs in seconds */
428 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
429 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
430 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
431 return (double) ((i64End - i64Start) / 10000000.0);
435 ** Print the timing results.
437 static void endTimer(void){
438 if( enableTimer && getProcessTimesAddr){
439 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
440 sqlite3_int64 ftWallEnd = timeOfDay();
441 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
442 sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
443 (ftWallEnd - ftWallBegin)*0.001,
444 timeDiff(&ftUserBegin, &ftUserEnd),
445 timeDiff(&ftKernelBegin, &ftKernelEnd));
449 #define BEGIN_TIMER beginTimer()
450 #define END_TIMER endTimer()
451 #define HAS_TIMER hasTimer()
453 #else
454 #define BEGIN_TIMER
455 #define END_TIMER
456 #define HAS_TIMER 0
457 #endif
460 ** Used to prevent warnings about unused parameters
462 #define UNUSED_PARAMETER(x) (void)(x)
465 ** Number of elements in an array
467 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
470 ** If the following flag is set, then command execution stops
471 ** at an error if we are not interactive.
473 static int bail_on_error = 0;
476 ** Treat stdin as an interactive input if the following variable
477 ** is true. Otherwise, assume stdin is connected to a file or pipe.
479 static int stdin_is_interactive = 1;
482 ** On Windows systems we need to know if standard output is a console
483 ** in order to show that UTF-16 translation is done in the sign-on
484 ** banner. The following variable is true if it is the console.
486 static int stdout_is_console = 1;
489 ** The following is the open SQLite database. We make a pointer
490 ** to this database a static variable so that it can be accessed
491 ** by the SIGINT handler to interrupt database processing.
493 static sqlite3 *globalDb = 0;
496 ** True if an interrupt (Control-C) has been received.
498 static volatile int seenInterrupt = 0;
501 ** This is the name of our program. It is set in main(), used
502 ** in a number of other places, mostly for error messages.
504 static char *Argv0;
507 ** Prompt strings. Initialized in main. Settable with
508 ** .prompt main continue
510 #define PROMPT_LEN_MAX 20
511 /* First line prompt. default: "sqlite> " */
512 static char mainPrompt[PROMPT_LEN_MAX];
513 /* Continuation prompt. default: " ...> " */
514 static char continuePrompt[PROMPT_LEN_MAX];
516 /* This is variant of the standard-library strncpy() routine with the
517 ** one change that the destination string is always zero-terminated, even
518 ** if there is no zero-terminator in the first n-1 characters of the source
519 ** string.
521 static char *shell_strncpy(char *dest, const char *src, size_t n){
522 size_t i;
523 for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
524 dest[i] = 0;
525 return dest;
529 ** Optionally disable dynamic continuation prompt.
530 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
531 ** or open parentheses level if non-zero, or continuation prompt as set.
532 ** This facility interacts with the scanner and process_input() where the
533 ** below 5 macros are used.
535 #ifdef SQLITE_OMIT_DYNAPROMPT
536 # define CONTINUATION_PROMPT continuePrompt
537 # define CONTINUE_PROMPT_RESET
538 # define CONTINUE_PROMPT_AWAITS(p,s)
539 # define CONTINUE_PROMPT_AWAITC(p,c)
540 # define CONTINUE_PAREN_INCR(p,n)
541 # define CONTINUE_PROMPT_PSTATE 0
542 typedef void *t_NoDynaPrompt;
543 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
544 #else
545 # define CONTINUATION_PROMPT dynamicContinuePrompt()
546 # define CONTINUE_PROMPT_RESET \
547 do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
548 # define CONTINUE_PROMPT_AWAITS(p,s) \
549 if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
550 # define CONTINUE_PROMPT_AWAITC(p,c) \
551 if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
552 # define CONTINUE_PAREN_INCR(p,n) \
553 if(p && stdin_is_interactive) (trackParenLevel(p,n))
554 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
555 typedef struct DynaPrompt *t_DynaPromptRef;
556 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
558 static struct DynaPrompt {
559 char dynamicPrompt[PROMPT_LEN_MAX];
560 char acAwait[2];
561 int inParenLevel;
562 char *zScannerAwaits;
563 } dynPrompt = { {0}, {0}, 0, 0 };
565 /* Record parenthesis nesting level change, or force level to 0. */
566 static void trackParenLevel(struct DynaPrompt *p, int ni){
567 p->inParenLevel += ni;
568 if( ni==0 ) p->inParenLevel = 0;
569 p->zScannerAwaits = 0;
572 /* Record that a lexeme is opened, or closed with args==0. */
573 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
574 if( s!=0 || c==0 ){
575 p->zScannerAwaits = s;
576 p->acAwait[0] = 0;
577 }else{
578 p->acAwait[0] = c;
579 p->zScannerAwaits = p->acAwait;
583 /* Upon demand, derive the continuation prompt to display. */
584 static char *dynamicContinuePrompt(void){
585 if( continuePrompt[0]==0
586 || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
587 return continuePrompt;
588 }else{
589 if( dynPrompt.zScannerAwaits ){
590 size_t ncp = strlen(continuePrompt);
591 size_t ndp = strlen(dynPrompt.zScannerAwaits);
592 if( ndp > ncp-3 ) return continuePrompt;
593 strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
594 while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
595 shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
596 PROMPT_LEN_MAX-4);
597 }else{
598 if( dynPrompt.inParenLevel>9 ){
599 shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
600 }else if( dynPrompt.inParenLevel<0 ){
601 shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
602 }else{
603 shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
604 dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
606 shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
607 PROMPT_LEN_MAX-4);
610 return dynPrompt.dynamicPrompt;
612 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
614 /* Indicate out-of-memory and exit. */
615 static void shell_out_of_memory(void){
616 eputz("Error: out of memory\n");
617 exit(1);
620 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
621 ** out-of-memory error.
623 static void shell_check_oom(const void *p){
624 if( p==0 ) shell_out_of_memory();
628 ** Write I/O traces to the following stream.
630 #ifdef SQLITE_ENABLE_IOTRACE
631 static FILE *iotrace = 0;
632 #endif
635 ** This routine works like printf in that its first argument is a
636 ** format string and subsequent arguments are values to be substituted
637 ** in place of % fields. The result of formatting this string
638 ** is written to iotrace.
640 #ifdef SQLITE_ENABLE_IOTRACE
641 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
642 va_list ap;
643 char *z;
644 if( iotrace==0 ) return;
645 va_start(ap, zFormat);
646 z = sqlite3_vmprintf(zFormat, ap);
647 va_end(ap);
648 sputf(iotrace, "%s", z);
649 sqlite3_free(z);
651 #endif
654 ** Output string zUtf to Out stream as w characters. If w is negative,
655 ** then right-justify the text. W is the width in UTF-8 characters, not
656 ** in bytes. This is different from the %*.*s specification in printf
657 ** since with %*.*s the width is measured in bytes, not characters.
659 static void utf8_width_print(int w, const char *zUtf){
660 int i;
661 int n;
662 int aw = w<0 ? -w : w;
663 if( zUtf==0 ) zUtf = "";
664 for(i=n=0; zUtf[i]; i++){
665 if( (zUtf[i]&0xc0)!=0x80 ){
666 n++;
667 if( n==aw ){
668 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
669 break;
673 if( n>=aw ){
674 oputf("%.*s", i, zUtf);
675 }else if( w<0 ){
676 oputf("%*s%s", aw-n, "", zUtf);
677 }else{
678 oputf("%s%*s", zUtf, aw-n, "");
684 ** Determines if a string is a number of not.
686 static int isNumber(const char *z, int *realnum){
687 if( *z=='-' || *z=='+' ) z++;
688 if( !IsDigit(*z) ){
689 return 0;
691 z++;
692 if( realnum ) *realnum = 0;
693 while( IsDigit(*z) ){ z++; }
694 if( *z=='.' ){
695 z++;
696 if( !IsDigit(*z) ) return 0;
697 while( IsDigit(*z) ){ z++; }
698 if( realnum ) *realnum = 1;
700 if( *z=='e' || *z=='E' ){
701 z++;
702 if( *z=='+' || *z=='-' ) z++;
703 if( !IsDigit(*z) ) return 0;
704 while( IsDigit(*z) ){ z++; }
705 if( realnum ) *realnum = 1;
707 return *z==0;
711 ** Compute a string length that is limited to what can be stored in
712 ** lower 30 bits of a 32-bit signed integer.
714 static int strlen30(const char *z){
715 const char *z2 = z;
716 while( *z2 ){ z2++; }
717 return 0x3fffffff & (int)(z2 - z);
721 ** Return the length of a string in characters. Multibyte UTF8 characters
722 ** count as a single character.
724 static int strlenChar(const char *z){
725 int n = 0;
726 while( *z ){
727 if( (0xc0&*(z++))!=0x80 ) n++;
729 return n;
733 ** Return open FILE * if zFile exists, can be opened for read
734 ** and is an ordinary file or a character stream source.
735 ** Otherwise return 0.
737 static FILE * openChrSource(const char *zFile){
738 #if defined(_WIN32) || defined(WIN32)
739 struct __stat64 x = {0};
740 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
741 /* On Windows, open first, then check the stream nature. This order
742 ** is necessary because _stat() and sibs, when checking a named pipe,
743 ** effectively break the pipe as its supplier sees it. */
744 FILE *rv = fopen(zFile, "rb");
745 if( rv==0 ) return 0;
746 if( _fstat64(_fileno(rv), &x) != 0
747 || !STAT_CHR_SRC(x.st_mode)){
748 fclose(rv);
749 rv = 0;
751 return rv;
752 #else
753 struct stat x = {0};
754 int rc = stat(zFile, &x);
755 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
756 if( rc!=0 ) return 0;
757 if( STAT_CHR_SRC(x.st_mode) ){
758 return fopen(zFile, "rb");
759 }else{
760 return 0;
762 #endif
763 #undef STAT_CHR_SRC
767 ** This routine reads a line of text from FILE in, stores
768 ** the text in memory obtained from malloc() and returns a pointer
769 ** to the text. NULL is returned at end of file, or if malloc()
770 ** fails.
772 ** If zLine is not NULL then it is a malloced buffer returned from
773 ** a previous call to this routine that may be reused.
775 static char *local_getline(char *zLine, FILE *in){
776 int nLine = zLine==0 ? 0 : 100;
777 int n = 0;
779 while( 1 ){
780 if( n+100>nLine ){
781 nLine = nLine*2 + 100;
782 zLine = realloc(zLine, nLine);
783 shell_check_oom(zLine);
785 if( fgets(&zLine[n], nLine - n, in)==0 ){
786 if( n==0 ){
787 free(zLine);
788 return 0;
790 zLine[n] = 0;
791 break;
793 while( zLine[n] ) n++;
794 if( n>0 && zLine[n-1]=='\n' ){
795 n--;
796 if( n>0 && zLine[n-1]=='\r' ) n--;
797 zLine[n] = 0;
798 break;
801 return zLine;
805 ** Retrieve a single line of input text.
807 ** If in==0 then read from standard input and prompt before each line.
808 ** If isContinuation is true, then a continuation prompt is appropriate.
809 ** If isContinuation is zero, then the main prompt should be used.
811 ** If zPrior is not NULL then it is a buffer from a prior call to this
812 ** routine that can be reused.
814 ** The result is stored in space obtained from malloc() and must either
815 ** be freed by the caller or else passed back into this routine via the
816 ** zPrior argument for reuse.
818 #ifndef SQLITE_SHELL_FIDDLE
819 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
820 char *zPrompt;
821 char *zResult;
822 if( in!=0 ){
823 zResult = local_getline(zPrior, in);
824 }else{
825 zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
826 #if SHELL_USE_LOCAL_GETLINE
827 sputz(stdout, zPrompt);
828 fflush(stdout);
830 zResult = local_getline(zPrior, stdin);
831 zPrior = 0;
832 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
833 if( zResult==0 ) sqlite3_sleep(50);
834 }while( zResult==0 && seenInterrupt>0 );
835 #else
836 free(zPrior);
837 zResult = shell_readline(zPrompt);
838 while( zResult==0 ){
839 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
840 sqlite3_sleep(50);
841 if( seenInterrupt==0 ) break;
842 zResult = shell_readline("");
844 /* BEGIN SQLCIPHER */
845 #ifdef SQLITE_HAS_CODEC
846 /* Simplistic filtering of input lines to prevent PRAGKA key and
847 PRAGMA rekey statements from being stored in readline history.
848 Note that this will only prevent single line statements, but that
849 will be sufficient for common cases. */
850 if(zResult && *zResult && (
851 sqlite3_strlike("%pragma%key%=%", zResult, 0)==0 ||
852 sqlite3_strlike("%attach%database%as%key%", zResult, 0)==0
854 ) return zResult;
855 #endif
856 /* END SQLCIPHER */
857 if( zResult && *zResult ) shell_add_history(zResult);
858 #endif
860 return zResult;
862 #endif /* !SQLITE_SHELL_FIDDLE */
865 ** Return the value of a hexadecimal digit. Return -1 if the input
866 ** is not a hex digit.
868 static int hexDigitValue(char c){
869 if( c>='0' && c<='9' ) return c - '0';
870 if( c>='a' && c<='f' ) return c - 'a' + 10;
871 if( c>='A' && c<='F' ) return c - 'A' + 10;
872 return -1;
876 ** Interpret zArg as an integer value, possibly with suffixes.
878 static sqlite3_int64 integerValue(const char *zArg){
879 sqlite3_int64 v = 0;
880 static const struct { char *zSuffix; int iMult; } aMult[] = {
881 { "KiB", 1024 },
882 { "MiB", 1024*1024 },
883 { "GiB", 1024*1024*1024 },
884 { "KB", 1000 },
885 { "MB", 1000000 },
886 { "GB", 1000000000 },
887 { "K", 1000 },
888 { "M", 1000000 },
889 { "G", 1000000000 },
891 int i;
892 int isNeg = 0;
893 if( zArg[0]=='-' ){
894 isNeg = 1;
895 zArg++;
896 }else if( zArg[0]=='+' ){
897 zArg++;
899 if( zArg[0]=='0' && zArg[1]=='x' ){
900 int x;
901 zArg += 2;
902 while( (x = hexDigitValue(zArg[0]))>=0 ){
903 v = (v<<4) + x;
904 zArg++;
906 }else{
907 while( IsDigit(zArg[0]) ){
908 v = v*10 + zArg[0] - '0';
909 zArg++;
912 for(i=0; i<ArraySize(aMult); i++){
913 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
914 v *= aMult[i].iMult;
915 break;
918 return isNeg? -v : v;
922 ** A variable length string to which one can append text.
924 typedef struct ShellText ShellText;
925 struct ShellText {
926 char *z;
927 int n;
928 int nAlloc;
932 ** Initialize and destroy a ShellText object
934 static void initText(ShellText *p){
935 memset(p, 0, sizeof(*p));
937 static void freeText(ShellText *p){
938 free(p->z);
939 initText(p);
942 /* zIn is either a pointer to a NULL-terminated string in memory obtained
943 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
944 ** added to zIn, and the result returned in memory obtained from malloc().
945 ** zIn, if it was not NULL, is freed.
947 ** If the third argument, quote, is not '\0', then it is used as a
948 ** quote character for zAppend.
950 static void appendText(ShellText *p, const char *zAppend, char quote){
951 i64 len;
952 i64 i;
953 i64 nAppend = strlen30(zAppend);
955 len = nAppend+p->n+1;
956 if( quote ){
957 len += 2;
958 for(i=0; i<nAppend; i++){
959 if( zAppend[i]==quote ) len++;
963 if( p->z==0 || p->n+len>=p->nAlloc ){
964 p->nAlloc = p->nAlloc*2 + len + 20;
965 p->z = realloc(p->z, p->nAlloc);
966 shell_check_oom(p->z);
969 if( quote ){
970 char *zCsr = p->z+p->n;
971 *zCsr++ = quote;
972 for(i=0; i<nAppend; i++){
973 *zCsr++ = zAppend[i];
974 if( zAppend[i]==quote ) *zCsr++ = quote;
976 *zCsr++ = quote;
977 p->n = (int)(zCsr - p->z);
978 *zCsr = '\0';
979 }else{
980 memcpy(p->z+p->n, zAppend, nAppend);
981 p->n += nAppend;
982 p->z[p->n] = '\0';
987 ** Attempt to determine if identifier zName needs to be quoted, either
988 ** because it contains non-alphanumeric characters, or because it is an
989 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
990 ** that quoting is required.
992 ** Return '"' if quoting is required. Return 0 if no quoting is required.
994 static char quoteChar(const char *zName){
995 int i;
996 if( zName==0 ) return '"';
997 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
998 for(i=0; zName[i]; i++){
999 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1001 return sqlite3_keyword_check(zName, i) ? '"' : 0;
1005 ** Construct a fake object name and column list to describe the structure
1006 ** of the view, virtual table, or table valued function zSchema.zName.
1008 static char *shellFakeSchema(
1009 sqlite3 *db, /* The database connection containing the vtab */
1010 const char *zSchema, /* Schema of the database holding the vtab */
1011 const char *zName /* The name of the virtual table */
1013 sqlite3_stmt *pStmt = 0;
1014 char *zSql;
1015 ShellText s;
1016 char cQuote;
1017 char *zDiv = "(";
1018 int nRow = 0;
1020 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1021 zSchema ? zSchema : "main", zName);
1022 shell_check_oom(zSql);
1023 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1024 sqlite3_free(zSql);
1025 initText(&s);
1026 if( zSchema ){
1027 cQuote = quoteChar(zSchema);
1028 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1029 appendText(&s, zSchema, cQuote);
1030 appendText(&s, ".", 0);
1032 cQuote = quoteChar(zName);
1033 appendText(&s, zName, cQuote);
1034 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1035 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1036 nRow++;
1037 appendText(&s, zDiv, 0);
1038 zDiv = ",";
1039 if( zCol==0 ) zCol = "";
1040 cQuote = quoteChar(zCol);
1041 appendText(&s, zCol, cQuote);
1043 appendText(&s, ")", 0);
1044 sqlite3_finalize(pStmt);
1045 if( nRow==0 ){
1046 freeText(&s);
1047 s.z = 0;
1049 return s.z;
1053 ** SQL function: strtod(X)
1055 ** Use the C-library strtod() function to convert string X into a double.
1056 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1057 ** routines against the C-library.
1059 static void shellStrtod(
1060 sqlite3_context *pCtx,
1061 int nVal,
1062 sqlite3_value **apVal
1064 char *z = (char*)sqlite3_value_text(apVal[0]);
1065 UNUSED_PARAMETER(nVal);
1066 if( z==0 ) return;
1067 sqlite3_result_double(pCtx, strtod(z,0));
1071 ** SQL function: dtostr(X)
1073 ** Use the C-library printf() function to convert real value X into a string.
1074 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1075 ** routines against the C-library.
1077 static void shellDtostr(
1078 sqlite3_context *pCtx,
1079 int nVal,
1080 sqlite3_value **apVal
1082 double r = sqlite3_value_double(apVal[0]);
1083 int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
1084 char z[400];
1085 if( n<1 ) n = 1;
1086 if( n>350 ) n = 350;
1087 sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
1088 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
1093 ** SQL function: shell_module_schema(X)
1095 ** Return a fake schema for the table-valued function or eponymous virtual
1096 ** table X.
1098 static void shellModuleSchema(
1099 sqlite3_context *pCtx,
1100 int nVal,
1101 sqlite3_value **apVal
1103 const char *zName;
1104 char *zFake;
1105 UNUSED_PARAMETER(nVal);
1106 zName = (const char*)sqlite3_value_text(apVal[0]);
1107 zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1108 if( zFake ){
1109 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1110 -1, sqlite3_free);
1111 free(zFake);
1116 ** SQL function: shell_add_schema(S,X)
1118 ** Add the schema name X to the CREATE statement in S and return the result.
1119 ** Examples:
1121 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1123 ** Also works on
1125 ** CREATE INDEX
1126 ** CREATE UNIQUE INDEX
1127 ** CREATE VIEW
1128 ** CREATE TRIGGER
1129 ** CREATE VIRTUAL TABLE
1131 ** This UDF is used by the .schema command to insert the schema name of
1132 ** attached databases into the middle of the sqlite_schema.sql field.
1134 static void shellAddSchemaName(
1135 sqlite3_context *pCtx,
1136 int nVal,
1137 sqlite3_value **apVal
1139 static const char *aPrefix[] = {
1140 "TABLE",
1141 "INDEX",
1142 "UNIQUE INDEX",
1143 "VIEW",
1144 "TRIGGER",
1145 "VIRTUAL TABLE"
1147 int i = 0;
1148 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1149 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1150 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1151 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1152 UNUSED_PARAMETER(nVal);
1153 if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1154 for(i=0; i<ArraySize(aPrefix); i++){
1155 int n = strlen30(aPrefix[i]);
1156 if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1157 char *z = 0;
1158 char *zFake = 0;
1159 if( zSchema ){
1160 char cQuote = quoteChar(zSchema);
1161 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1162 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1163 }else{
1164 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1167 if( zName
1168 && aPrefix[i][0]=='V'
1169 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1171 if( z==0 ){
1172 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1173 }else{
1174 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1176 free(zFake);
1178 if( z ){
1179 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1180 return;
1185 sqlite3_result_value(pCtx, apVal[0]);
1189 ** The source code for several run-time loadable extensions is inserted
1190 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1191 ** code, we need to override some macros to make the included program code
1192 ** work here in the middle of this regular program.
1194 #define SQLITE_EXTENSION_INIT1
1195 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1197 #if defined(_WIN32) && defined(_MSC_VER)
1198 INCLUDE test_windirent.h
1199 INCLUDE test_windirent.c
1200 #define dirent DIRENT
1201 #endif
1202 INCLUDE ../ext/misc/memtrace.c
1203 INCLUDE ../ext/misc/pcachetrace.c
1204 INCLUDE ../ext/misc/shathree.c
1205 INCLUDE ../ext/misc/uint.c
1206 INCLUDE ../ext/misc/decimal.c
1207 #undef sqlite3_base_init
1208 #define sqlite3_base_init sqlite3_base64_init
1209 INCLUDE ../ext/misc/base64.c
1210 #undef sqlite3_base_init
1211 #define sqlite3_base_init sqlite3_base85_init
1212 #define OMIT_BASE85_CHECKER
1213 INCLUDE ../ext/misc/base85.c
1214 INCLUDE ../ext/misc/ieee754.c
1215 INCLUDE ../ext/misc/series.c
1216 INCLUDE ../ext/misc/regexp.c
1217 #ifndef SQLITE_SHELL_FIDDLE
1218 INCLUDE ../ext/misc/fileio.c
1219 INCLUDE ../ext/misc/completion.c
1220 INCLUDE ../ext/misc/appendvfs.c
1221 #endif
1222 #ifdef SQLITE_HAVE_ZLIB
1223 INCLUDE ../ext/misc/zipfile.c
1224 INCLUDE ../ext/misc/sqlar.c
1225 #endif
1226 INCLUDE ../ext/expert/sqlite3expert.h
1227 INCLUDE ../ext/expert/sqlite3expert.c
1229 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1230 #define SQLITE_SHELL_HAVE_RECOVER 1
1231 #else
1232 #define SQLITE_SHELL_HAVE_RECOVER 0
1233 #endif
1234 #if SQLITE_SHELL_HAVE_RECOVER
1235 INCLUDE ../ext/recover/sqlite3recover.h
1236 # ifndef SQLITE_HAVE_SQLITE3R
1237 INCLUDE ../ext/recover/dbdata.c
1238 INCLUDE ../ext/recover/sqlite3recover.c
1239 # endif /* SQLITE_HAVE_SQLITE3R */
1240 #endif
1241 #ifdef SQLITE_SHELL_EXTSRC
1242 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1243 #endif
1245 #if defined(SQLITE_ENABLE_SESSION)
1247 ** State information for a single open session
1249 typedef struct OpenSession OpenSession;
1250 struct OpenSession {
1251 char *zName; /* Symbolic name for this session */
1252 int nFilter; /* Number of xFilter rejection GLOB patterns */
1253 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1254 sqlite3_session *p; /* The open session */
1256 #endif
1258 typedef struct ExpertInfo ExpertInfo;
1259 struct ExpertInfo {
1260 sqlite3expert *pExpert;
1261 int bVerbose;
1264 /* A single line in the EQP output */
1265 typedef struct EQPGraphRow EQPGraphRow;
1266 struct EQPGraphRow {
1267 int iEqpId; /* ID for this row */
1268 int iParentId; /* ID of the parent row */
1269 EQPGraphRow *pNext; /* Next row in sequence */
1270 char zText[1]; /* Text to display for this row */
1273 /* All EQP output is collected into an instance of the following */
1274 typedef struct EQPGraph EQPGraph;
1275 struct EQPGraph {
1276 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1277 EQPGraphRow *pLast; /* Last element of the pRow list */
1278 char zPrefix[100]; /* Graph prefix */
1281 /* Parameters affecting columnar mode result display (defaulting together) */
1282 typedef struct ColModeOpts {
1283 int iWrap; /* In columnar modes, wrap lines reaching this limit */
1284 u8 bQuote; /* Quote results for .mode box and table */
1285 u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
1286 } ColModeOpts;
1287 #define ColModeOpts_default { 60, 0, 0 }
1288 #define ColModeOpts_default_qbox { 60, 1, 0 }
1291 ** State information about the database connection is contained in an
1292 ** instance of the following structure.
1294 typedef struct ShellState ShellState;
1295 struct ShellState {
1296 sqlite3 *db; /* The database */
1297 u8 autoExplain; /* Automatically turn on .explain mode */
1298 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
1299 u8 autoEQPtest; /* autoEQP is in test mode */
1300 u8 autoEQPtrace; /* autoEQP is in trace mode */
1301 u8 scanstatsOn; /* True to display scan stats before each finalize */
1302 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1303 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1304 u8 nEqpLevel; /* Depth of the EQP output graph */
1305 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1306 u8 bSafeMode; /* True to prohibit unsafe operations */
1307 u8 bSafeModePersist; /* The long-term value of bSafeMode */
1308 u8 eRestoreState; /* See comments above doAutoDetectRestore() */
1309 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
1310 unsigned statsOn; /* True to display memory stats before each finalize */
1311 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
1312 int inputNesting; /* Track nesting level of .read and other redirects */
1313 int outCount; /* Revert to stdout when reaching zero */
1314 int cnt; /* Number of records displayed so far */
1315 int lineno; /* Line number of last line read from in */
1316 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1317 FILE *in; /* Read commands from this stream */
1318 FILE *out; /* Write results here */
1319 FILE *traceOut; /* Output for sqlite3_trace() */
1320 int nErr; /* Number of errors seen */
1321 int mode; /* An output mode setting */
1322 int modePrior; /* Saved mode */
1323 int cMode; /* temporary output mode for the current query */
1324 int normalMode; /* Output mode before ".explain on" */
1325 int writableSchema; /* True if PRAGMA writable_schema=ON */
1326 int showHeader; /* True to show column names in List or Column mode */
1327 int nCheck; /* Number of ".check" commands run */
1328 unsigned nProgress; /* Number of progress callbacks encountered */
1329 unsigned mxProgress; /* Maximum progress callbacks before failing */
1330 unsigned flgProgress; /* Flags for the progress callback */
1331 unsigned shellFlgs; /* Various flags */
1332 unsigned priorShFlgs; /* Saved copy of flags */
1333 sqlite3_int64 szMax; /* --maxsize argument to .open */
1334 char *zDestTable; /* Name of destination table when MODE_Insert */
1335 char *zTempFile; /* Temporary file that might need deleting */
1336 char zTestcase[30]; /* Name of current test case */
1337 char colSeparator[20]; /* Column separator character for several modes */
1338 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1339 char colSepPrior[20]; /* Saved column separator */
1340 char rowSepPrior[20]; /* Saved row separator */
1341 int *colWidth; /* Requested width of each column in columnar modes */
1342 int *actualWidth; /* Actual width of each column */
1343 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1344 char nullValue[20]; /* The text to print when a NULL comes back from
1345 ** the database */
1346 char outfile[FILENAME_MAX]; /* Filename for *out */
1347 sqlite3_stmt *pStmt; /* Current statement if any. */
1348 FILE *pLog; /* Write log output here */
1349 struct AuxDb { /* Storage space for auxiliary database connections */
1350 sqlite3 *db; /* Connection pointer */
1351 const char *zDbFilename; /* Filename used to open the connection */
1352 char *zFreeOnClose; /* Free this memory allocation on close */
1353 #if defined(SQLITE_ENABLE_SESSION)
1354 int nSession; /* Number of active sessions */
1355 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1356 #endif
1357 } aAuxDb[5], /* Array of all database connections */
1358 *pAuxDb; /* Currently active database connection */
1359 int *aiIndent; /* Array of indents used in MODE_Explain */
1360 int nIndent; /* Size of array aiIndent[] */
1361 int iIndent; /* Index of current op in aiIndent[] */
1362 char *zNonce; /* Nonce for temporary safe-mode escapes */
1363 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1364 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1365 #ifdef SQLITE_SHELL_FIDDLE
1366 struct {
1367 const char * zInput; /* Input string from wasm/JS proxy */
1368 const char * zPos; /* Cursor pos into zInput */
1369 const char * zDefaultDbName; /* Default name for db file */
1370 } wasm;
1371 #endif
1374 #ifdef SQLITE_SHELL_FIDDLE
1375 static ShellState shellState;
1376 #endif
1379 /* Allowed values for ShellState.autoEQP
1381 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1382 #define AUTOEQP_on 1 /* Automatic EQP is on */
1383 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1384 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1386 /* Allowed values for ShellState.openMode
1388 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1389 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1390 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1391 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1392 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1393 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1394 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1396 /* Allowed values for ShellState.eTraceType
1398 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1399 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1400 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1402 /* Bits in the ShellState.flgProgress variable */
1403 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1404 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
1405 ** callback limit is reached, and for each
1406 ** top-level SQL statement */
1407 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1410 ** These are the allowed shellFlgs values
1412 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1413 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1414 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1415 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1416 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1417 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1418 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1419 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1420 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1421 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1422 #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */
1425 ** Macros for testing and setting shellFlgs
1427 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1428 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1429 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1432 ** These are the allowed modes.
1434 #define MODE_Line 0 /* One column per line. Blank line between records */
1435 #define MODE_Column 1 /* One record per line in neat columns */
1436 #define MODE_List 2 /* One record per line with a separator */
1437 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1438 #define MODE_Html 4 /* Generate an XHTML table */
1439 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1440 #define MODE_Quote 6 /* Quote values as for SQL */
1441 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1442 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1443 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1444 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1445 #define MODE_Pretty 11 /* Pretty-print schemas */
1446 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1447 #define MODE_Json 13 /* Output JSON */
1448 #define MODE_Markdown 14 /* Markdown formatting */
1449 #define MODE_Table 15 /* MySQL-style table formatting */
1450 #define MODE_Box 16 /* Unicode box-drawing characters */
1451 #define MODE_Count 17 /* Output only a count of the rows of output */
1452 #define MODE_Off 18 /* No query output shown */
1453 #define MODE_ScanExp 19 /* Like MODE_Explain, but for ".scanstats vm" */
1455 static const char *modeDescr[] = {
1456 "line",
1457 "column",
1458 "list",
1459 "semi",
1460 "html",
1461 "insert",
1462 "quote",
1463 "tcl",
1464 "csv",
1465 "explain",
1466 "ascii",
1467 "prettyprint",
1468 "eqp",
1469 "json",
1470 "markdown",
1471 "table",
1472 "box",
1473 "count",
1474 "off"
1478 ** These are the column/row/line separators used by the various
1479 ** import/export modes.
1481 #define SEP_Column "|"
1482 #define SEP_Row "\n"
1483 #define SEP_Tab "\t"
1484 #define SEP_Space " "
1485 #define SEP_Comma ","
1486 #define SEP_CrLf "\r\n"
1487 #define SEP_Unit "\x1F"
1488 #define SEP_Record "\x1E"
1491 ** Limit input nesting via .read or any other input redirect.
1492 ** It's not too expensive, so a generous allowance can be made.
1494 #define MAX_INPUT_NESTING 25
1497 ** A callback for the sqlite3_log() interface.
1499 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1500 ShellState *p = (ShellState*)pArg;
1501 if( p->pLog==0 ) return;
1502 sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1503 fflush(p->pLog);
1507 ** SQL function: shell_putsnl(X)
1509 ** Write the text X to the screen (or whatever output is being directed)
1510 ** adding a newline at the end, and then return X.
1512 static void shellPutsFunc(
1513 sqlite3_context *pCtx,
1514 int nVal,
1515 sqlite3_value **apVal
1517 /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
1518 (void)nVal;
1519 oputf("%s\n", sqlite3_value_text(apVal[0]));
1520 sqlite3_result_value(pCtx, apVal[0]);
1524 ** If in safe mode, print an error message described by the arguments
1525 ** and exit immediately.
1527 static void failIfSafeMode(
1528 ShellState *p,
1529 const char *zErrMsg,
1532 if( p->bSafeMode ){
1533 va_list ap;
1534 char *zMsg;
1535 va_start(ap, zErrMsg);
1536 zMsg = sqlite3_vmprintf(zErrMsg, ap);
1537 va_end(ap);
1538 eputf("line %d: %s\n", p->lineno, zMsg);
1539 exit(1);
1544 ** SQL function: edit(VALUE)
1545 ** edit(VALUE,EDITOR)
1547 ** These steps:
1549 ** (1) Write VALUE into a temporary file.
1550 ** (2) Run program EDITOR on that temporary file.
1551 ** (3) Read the temporary file back and return its content as the result.
1552 ** (4) Delete the temporary file
1554 ** If the EDITOR argument is omitted, use the value in the VISUAL
1555 ** environment variable. If still there is no EDITOR, through an error.
1557 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1559 #ifndef SQLITE_NOHAVE_SYSTEM
1560 static void editFunc(
1561 sqlite3_context *context,
1562 int argc,
1563 sqlite3_value **argv
1565 const char *zEditor;
1566 char *zTempFile = 0;
1567 sqlite3 *db;
1568 char *zCmd = 0;
1569 int bBin;
1570 int rc;
1571 int hasCRNL = 0;
1572 FILE *f = 0;
1573 sqlite3_int64 sz;
1574 sqlite3_int64 x;
1575 unsigned char *p = 0;
1577 if( argc==2 ){
1578 zEditor = (const char*)sqlite3_value_text(argv[1]);
1579 }else{
1580 zEditor = getenv("VISUAL");
1582 if( zEditor==0 ){
1583 sqlite3_result_error(context, "no editor for edit()", -1);
1584 return;
1586 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1587 sqlite3_result_error(context, "NULL input to edit()", -1);
1588 return;
1590 db = sqlite3_context_db_handle(context);
1591 zTempFile = 0;
1592 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1593 if( zTempFile==0 ){
1594 sqlite3_uint64 r = 0;
1595 sqlite3_randomness(sizeof(r), &r);
1596 zTempFile = sqlite3_mprintf("temp%llx", r);
1597 if( zTempFile==0 ){
1598 sqlite3_result_error_nomem(context);
1599 return;
1602 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1603 /* When writing the file to be edited, do \n to \r\n conversions on systems
1604 ** that want \r\n line endings */
1605 f = fopen(zTempFile, bBin ? "wb" : "w");
1606 if( f==0 ){
1607 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1608 goto edit_func_end;
1610 sz = sqlite3_value_bytes(argv[0]);
1611 if( bBin ){
1612 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1613 }else{
1614 const char *z = (const char*)sqlite3_value_text(argv[0]);
1615 /* Remember whether or not the value originally contained \r\n */
1616 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1617 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1619 fclose(f);
1620 f = 0;
1621 if( x!=sz ){
1622 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1623 goto edit_func_end;
1625 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1626 if( zCmd==0 ){
1627 sqlite3_result_error_nomem(context);
1628 goto edit_func_end;
1630 rc = system(zCmd);
1631 sqlite3_free(zCmd);
1632 if( rc ){
1633 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1634 goto edit_func_end;
1636 f = fopen(zTempFile, "rb");
1637 if( f==0 ){
1638 sqlite3_result_error(context,
1639 "edit() cannot reopen temp file after edit", -1);
1640 goto edit_func_end;
1642 fseek(f, 0, SEEK_END);
1643 sz = ftell(f);
1644 rewind(f);
1645 p = sqlite3_malloc64( sz+1 );
1646 if( p==0 ){
1647 sqlite3_result_error_nomem(context);
1648 goto edit_func_end;
1650 x = fread(p, 1, (size_t)sz, f);
1651 fclose(f);
1652 f = 0;
1653 if( x!=sz ){
1654 sqlite3_result_error(context, "could not read back the whole file", -1);
1655 goto edit_func_end;
1657 if( bBin ){
1658 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1659 }else{
1660 sqlite3_int64 i, j;
1661 if( hasCRNL ){
1662 /* If the original contains \r\n then do no conversions back to \n */
1663 }else{
1664 /* If the file did not originally contain \r\n then convert any new
1665 ** \r\n back into \n */
1666 p[sz] = 0;
1667 for(i=j=0; i<sz; i++){
1668 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1669 p[j++] = p[i];
1671 sz = j;
1672 p[sz] = 0;
1674 sqlite3_result_text64(context, (const char*)p, sz,
1675 sqlite3_free, SQLITE_UTF8);
1677 p = 0;
1679 edit_func_end:
1680 if( f ) fclose(f);
1681 unlink(zTempFile);
1682 sqlite3_free(zTempFile);
1683 sqlite3_free(p);
1685 #endif /* SQLITE_NOHAVE_SYSTEM */
1688 ** Save or restore the current output mode
1690 static void outputModePush(ShellState *p){
1691 p->modePrior = p->mode;
1692 p->priorShFlgs = p->shellFlgs;
1693 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1694 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1696 static void outputModePop(ShellState *p){
1697 p->mode = p->modePrior;
1698 p->shellFlgs = p->priorShFlgs;
1699 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1700 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1704 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1706 static void output_hex_blob(const void *pBlob, int nBlob){
1707 int i;
1708 unsigned char *aBlob = (unsigned char*)pBlob;
1710 char *zStr = sqlite3_malloc(nBlob*2 + 1);
1711 shell_check_oom(zStr);
1713 for(i=0; i<nBlob; i++){
1714 static const char aHex[] = {
1715 '0', '1', '2', '3', '4', '5', '6', '7',
1716 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1718 zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1719 zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1721 zStr[i*2] = '\0';
1723 oputf("X'%s'", zStr);
1724 sqlite3_free(zStr);
1728 ** Find a string that is not found anywhere in z[]. Return a pointer
1729 ** to that string.
1731 ** Try to use zA and zB first. If both of those are already found in z[]
1732 ** then make up some string and store it in the buffer zBuf.
1734 static const char *unused_string(
1735 const char *z, /* Result must not appear anywhere in z */
1736 const char *zA, const char *zB, /* Try these first */
1737 char *zBuf /* Space to store a generated string */
1739 unsigned i = 0;
1740 if( strstr(z, zA)==0 ) return zA;
1741 if( strstr(z, zB)==0 ) return zB;
1743 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1744 }while( strstr(z,zBuf)!=0 );
1745 return zBuf;
1749 ** Output the given string as a quoted string using SQL quoting conventions.
1751 ** See also: output_quoted_escaped_string()
1753 static void output_quoted_string(const char *z){
1754 int i;
1755 char c;
1756 #ifndef SQLITE_SHELL_FIDDLE
1757 FILE *pfO = setOutputStream(invalidFileStream);
1758 setBinaryMode(pfO, 1);
1759 #endif
1760 if( z==0 ) return;
1761 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1762 if( c==0 ){
1763 oputf("'%s'",z);
1764 }else{
1765 oputz("'");
1766 while( *z ){
1767 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1768 if( c=='\'' ) i++;
1769 if( i ){
1770 oputf("%.*s", i, z);
1771 z += i;
1773 if( c=='\'' ){
1774 oputz("'");
1775 continue;
1777 if( c==0 ){
1778 break;
1780 z++;
1782 oputz("'");
1784 #ifndef SQLITE_SHELL_FIDDLE
1785 setTextMode(pfO, 1);
1786 #else
1787 setTextMode(stdout, 1);
1788 #endif
1792 ** Output the given string as a quoted string using SQL quoting conventions.
1793 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1794 ** get corrupted by end-of-line translation facilities in some operating
1795 ** systems.
1797 ** This is like output_quoted_string() but with the addition of the \r\n
1798 ** escape mechanism.
1800 static void output_quoted_escaped_string(const char *z){
1801 int i;
1802 char c;
1803 #ifndef SQLITE_SHELL_FIDDLE
1804 FILE *pfO = setOutputStream(invalidFileStream);
1805 setBinaryMode(pfO, 1);
1806 #endif
1807 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1808 if( c==0 ){
1809 oputf("'%s'",z);
1810 }else{
1811 const char *zNL = 0;
1812 const char *zCR = 0;
1813 int nNL = 0;
1814 int nCR = 0;
1815 char zBuf1[20], zBuf2[20];
1816 for(i=0; z[i]; i++){
1817 if( z[i]=='\n' ) nNL++;
1818 if( z[i]=='\r' ) nCR++;
1820 if( nNL ){
1821 oputz("replace(");
1822 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1824 if( nCR ){
1825 oputz("replace(");
1826 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1828 oputz("'");
1829 while( *z ){
1830 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1831 if( c=='\'' ) i++;
1832 if( i ){
1833 oputf("%.*s", i, z);
1834 z += i;
1836 if( c=='\'' ){
1837 oputz("'");
1838 continue;
1840 if( c==0 ){
1841 break;
1843 z++;
1844 if( c=='\n' ){
1845 oputz(zNL);
1846 continue;
1848 oputz(zCR);
1850 oputz("'");
1851 if( nCR ){
1852 oputf(",'%s',char(13))", zCR);
1854 if( nNL ){
1855 oputf(",'%s',char(10))", zNL);
1858 #ifndef SQLITE_SHELL_FIDDLE
1859 setTextMode(pfO, 1);
1860 #else
1861 setTextMode(stdout, 1);
1862 #endif
1866 ** Find earliest of chars within s specified in zAny.
1867 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
1869 static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
1870 const char *pcFirst = 0;
1871 if( ns == ~(size_t)0 ) ns = strlen(s);
1872 while(*zAny){
1873 const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
1874 if( pc ){
1875 pcFirst = pc;
1876 ns = pcFirst - s;
1878 ++zAny;
1880 return pcFirst;
1883 ** Output the given string as a quoted according to C or TCL quoting rules.
1885 static void output_c_string(const char *z){
1886 char c;
1887 static const char *zq = "\"";
1888 static long ctrlMask = ~0L;
1889 static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
1890 char ace[3] = "\\?";
1891 char cbsSay;
1892 oputz(zq);
1893 while( *z!=0 ){
1894 const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
1895 const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
1896 const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
1897 if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
1898 if( (c = *pcEnd)==0 ) break;
1899 ++pcEnd;
1900 switch( c ){
1901 case '\\': case '"':
1902 cbsSay = (char)c;
1903 break;
1904 case '\t': cbsSay = 't'; break;
1905 case '\n': cbsSay = 'n'; break;
1906 case '\r': cbsSay = 'r'; break;
1907 case '\f': cbsSay = 'f'; break;
1908 default: cbsSay = 0; break;
1910 if( cbsSay ){
1911 ace[1] = cbsSay;
1912 oputz(ace);
1913 }else if( !isprint(c&0xff) ){
1914 oputf("\\%03o", c&0xff);
1915 }else{
1916 ace[1] = (char)c;
1917 oputz(ace+1);
1919 z = pcEnd;
1921 oputz(zq);
1925 ** Output the given string as a quoted according to JSON quoting rules.
1927 static void output_json_string(const char *z, i64 n){
1928 char c;
1929 static const char *zq = "\"";
1930 static long ctrlMask = ~0L;
1931 static const char *zDQBS = "\"\\";
1932 const char *pcLimit;
1933 char ace[3] = "\\?";
1934 char cbsSay;
1936 if( z==0 ) z = "";
1937 pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
1938 oputz(zq);
1939 while( z < pcLimit ){
1940 const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
1941 const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
1942 const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
1943 if( pcEnd > z ){
1944 oputb(z, (int)(pcEnd-z));
1945 z = pcEnd;
1947 if( z >= pcLimit ) break;
1948 c = *(z++);
1949 switch( c ){
1950 case '"': case '\\':
1951 cbsSay = (char)c;
1952 break;
1953 case '\b': cbsSay = 'b'; break;
1954 case '\f': cbsSay = 'f'; break;
1955 case '\n': cbsSay = 'n'; break;
1956 case '\r': cbsSay = 'r'; break;
1957 case '\t': cbsSay = 't'; break;
1958 default: cbsSay = 0; break;
1960 if( cbsSay ){
1961 ace[1] = cbsSay;
1962 oputz(ace);
1963 }else if( c<=0x1f ){
1964 oputf("u%04x", c);
1965 }else{
1966 ace[1] = (char)c;
1967 oputz(ace+1);
1970 oputz(zq);
1974 ** Output the given string with characters that are special to
1975 ** HTML escaped.
1977 static void output_html_string(const char *z){
1978 int i;
1979 if( z==0 ) z = "";
1980 while( *z ){
1981 for(i=0; z[i]
1982 && z[i]!='<'
1983 && z[i]!='&'
1984 && z[i]!='>'
1985 && z[i]!='\"'
1986 && z[i]!='\'';
1987 i++){}
1988 if( i>0 ){
1989 oputf("%.*s",i,z);
1991 if( z[i]=='<' ){
1992 oputz("&lt;");
1993 }else if( z[i]=='&' ){
1994 oputz("&amp;");
1995 }else if( z[i]=='>' ){
1996 oputz("&gt;");
1997 }else if( z[i]=='\"' ){
1998 oputz("&quot;");
1999 }else if( z[i]=='\'' ){
2000 oputz("&#39;");
2001 }else{
2002 break;
2004 z += i + 1;
2009 ** If a field contains any character identified by a 1 in the following
2010 ** array, then the string must be quoted for CSV.
2012 static const char needCsvQuote[] = {
2013 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2014 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2015 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2016 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2017 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2018 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2019 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2020 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2021 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2022 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2023 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2024 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2025 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2026 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2027 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2028 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2032 ** Output a single term of CSV. Actually, p->colSeparator is used for
2033 ** the separator, which may or may not be a comma. p->nullValue is
2034 ** the null value. Strings are quoted if necessary. The separator
2035 ** is only issued if bSep is true.
2037 static void output_csv(ShellState *p, const char *z, int bSep){
2038 if( z==0 ){
2039 oputf("%s",p->nullValue);
2040 }else{
2041 unsigned i;
2042 for(i=0; z[i]; i++){
2043 if( needCsvQuote[((unsigned char*)z)[i]] ){
2044 i = 0;
2045 break;
2048 if( i==0 || strstr(z, p->colSeparator)!=0 ){
2049 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
2050 shell_check_oom(zQuoted);
2051 oputz(zQuoted);
2052 sqlite3_free(zQuoted);
2053 }else{
2054 oputz(z);
2057 if( bSep ){
2058 oputz(p->colSeparator);
2063 ** This routine runs when the user presses Ctrl-C
2065 static void interrupt_handler(int NotUsed){
2066 UNUSED_PARAMETER(NotUsed);
2067 if( ++seenInterrupt>1 ) exit(1);
2068 if( globalDb ) sqlite3_interrupt(globalDb);
2071 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
2073 ** This routine runs for console events (e.g. Ctrl-C) on Win32
2075 static BOOL WINAPI ConsoleCtrlHandler(
2076 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
2078 if( dwCtrlType==CTRL_C_EVENT ){
2079 interrupt_handler(0);
2080 return TRUE;
2082 return FALSE;
2084 #endif
2086 #ifndef SQLITE_OMIT_AUTHORIZATION
2088 ** This authorizer runs in safe mode.
2090 static int safeModeAuth(
2091 void *pClientData,
2092 int op,
2093 const char *zA1,
2094 const char *zA2,
2095 const char *zA3,
2096 const char *zA4
2098 ShellState *p = (ShellState*)pClientData;
2099 static const char *azProhibitedFunctions[] = {
2100 "edit",
2101 "fts3_tokenizer",
2102 "load_extension",
2103 "readfile",
2104 "writefile",
2105 "zipfile",
2106 "zipfile_cds",
2108 UNUSED_PARAMETER(zA1);
2109 UNUSED_PARAMETER(zA3);
2110 UNUSED_PARAMETER(zA4);
2111 switch( op ){
2112 case SQLITE_ATTACH: {
2113 #ifndef SQLITE_SHELL_FIDDLE
2114 /* In WASM builds the filesystem is a virtual sandbox, so
2115 ** there's no harm in using ATTACH. */
2116 failIfSafeMode(p, "cannot run ATTACH in safe mode");
2117 #endif
2118 break;
2120 case SQLITE_FUNCTION: {
2121 int i;
2122 for(i=0; i<ArraySize(azProhibitedFunctions); i++){
2123 if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
2124 failIfSafeMode(p, "cannot use the %s() function in safe mode",
2125 azProhibitedFunctions[i]);
2128 break;
2131 return SQLITE_OK;
2135 ** When the ".auth ON" is set, the following authorizer callback is
2136 ** invoked. It always returns SQLITE_OK.
2138 static int shellAuth(
2139 void *pClientData,
2140 int op,
2141 const char *zA1,
2142 const char *zA2,
2143 const char *zA3,
2144 const char *zA4
2146 ShellState *p = (ShellState*)pClientData;
2147 static const char *azAction[] = { 0,
2148 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2149 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2150 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2151 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2152 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2153 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2154 "PRAGMA", "READ", "SELECT",
2155 "TRANSACTION", "UPDATE", "ATTACH",
2156 "DETACH", "ALTER_TABLE", "REINDEX",
2157 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2158 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2160 int i;
2161 const char *az[4];
2162 az[0] = zA1;
2163 az[1] = zA2;
2164 az[2] = zA3;
2165 az[3] = zA4;
2166 oputf("authorizer: %s", azAction[op]);
2167 for(i=0; i<4; i++){
2168 oputz(" ");
2169 if( az[i] ){
2170 output_c_string(az[i]);
2171 }else{
2172 oputz("NULL");
2175 oputz("\n");
2176 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
2177 return SQLITE_OK;
2179 #endif
2182 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2184 ** This routine converts some CREATE TABLE statements for shadow tables
2185 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2187 ** If the schema statement in z[] contains a start-of-comment and if
2188 ** sqlite3_complete() returns false, try to terminate the comment before
2189 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2191 static void printSchemaLine(const char *z, const char *zTail){
2192 char *zToFree = 0;
2193 if( z==0 ) return;
2194 if( zTail==0 ) return;
2195 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
2196 const char *zOrig = z;
2197 static const char *azTerm[] = { "", "*/", "\n" };
2198 int i;
2199 for(i=0; i<ArraySize(azTerm); i++){
2200 char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
2201 shell_check_oom(zNew);
2202 if( sqlite3_complete(zNew) ){
2203 size_t n = strlen(zNew);
2204 zNew[n-1] = 0;
2205 zToFree = zNew;
2206 z = zNew;
2207 break;
2209 sqlite3_free(zNew);
2212 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
2213 oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
2214 }else{
2215 oputf("%s%s", z, zTail);
2217 sqlite3_free(zToFree);
2219 static void printSchemaLineN(char *z, int n, const char *zTail){
2220 char c = z[n];
2221 z[n] = 0;
2222 printSchemaLine(z, zTail);
2223 z[n] = c;
2227 ** Return true if string z[] has nothing but whitespace and comments to the
2228 ** end of the first line.
2230 static int wsToEol(const char *z){
2231 int i;
2232 for(i=0; z[i]; i++){
2233 if( z[i]=='\n' ) return 1;
2234 if( IsSpace(z[i]) ) continue;
2235 if( z[i]=='-' && z[i+1]=='-' ) return 1;
2236 return 0;
2238 return 1;
2242 ** Add a new entry to the EXPLAIN QUERY PLAN data
2244 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
2245 EQPGraphRow *pNew;
2246 i64 nText;
2247 if( zText==0 ) return;
2248 nText = strlen(zText);
2249 if( p->autoEQPtest ){
2250 oputf("%d,%d,%s\n", iEqpId, p2, zText);
2252 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
2253 shell_check_oom(pNew);
2254 pNew->iEqpId = iEqpId;
2255 pNew->iParentId = p2;
2256 memcpy(pNew->zText, zText, nText+1);
2257 pNew->pNext = 0;
2258 if( p->sGraph.pLast ){
2259 p->sGraph.pLast->pNext = pNew;
2260 }else{
2261 p->sGraph.pRow = pNew;
2263 p->sGraph.pLast = pNew;
2267 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2268 ** in p->sGraph.
2270 static void eqp_reset(ShellState *p){
2271 EQPGraphRow *pRow, *pNext;
2272 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2273 pNext = pRow->pNext;
2274 sqlite3_free(pRow);
2276 memset(&p->sGraph, 0, sizeof(p->sGraph));
2279 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2280 ** pOld, or return the first such line if pOld is NULL
2282 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2283 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2284 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2285 return pRow;
2288 /* Render a single level of the graph that has iEqpId as its parent. Called
2289 ** recursively to render sublevels.
2291 static void eqp_render_level(ShellState *p, int iEqpId){
2292 EQPGraphRow *pRow, *pNext;
2293 i64 n = strlen(p->sGraph.zPrefix);
2294 char *z;
2295 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2296 pNext = eqp_next_row(p, iEqpId, pRow);
2297 z = pRow->zText;
2298 oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
2299 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
2300 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
2301 eqp_render_level(p, pRow->iEqpId);
2302 p->sGraph.zPrefix[n] = 0;
2308 ** Display and reset the EXPLAIN QUERY PLAN data
2310 static void eqp_render(ShellState *p, i64 nCycle){
2311 EQPGraphRow *pRow = p->sGraph.pRow;
2312 if( pRow ){
2313 if( pRow->zText[0]=='-' ){
2314 if( pRow->pNext==0 ){
2315 eqp_reset(p);
2316 return;
2318 oputf("%s\n", pRow->zText+3);
2319 p->sGraph.pRow = pRow->pNext;
2320 sqlite3_free(pRow);
2321 }else if( nCycle>0 ){
2322 oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
2323 }else{
2324 oputz("QUERY PLAN\n");
2326 p->sGraph.zPrefix[0] = 0;
2327 eqp_render_level(p, 0);
2328 eqp_reset(p);
2332 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2334 ** Progress handler callback.
2336 static int progress_handler(void *pClientData) {
2337 ShellState *p = (ShellState*)pClientData;
2338 p->nProgress++;
2339 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2340 oputf("Progress limit reached (%u)\n", p->nProgress);
2341 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2342 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2343 return 1;
2345 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2346 oputf("Progress %u\n", p->nProgress);
2348 return 0;
2350 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2353 ** Print N dashes
2355 static void print_dashes(int N){
2356 const char zDash[] = "--------------------------------------------------";
2357 const int nDash = sizeof(zDash) - 1;
2358 while( N>nDash ){
2359 oputz(zDash);
2360 N -= nDash;
2362 oputf("%.*s", N, zDash);
2366 ** Print a markdown or table-style row separator using ascii-art
2368 static void print_row_separator(
2369 ShellState *p,
2370 int nArg,
2371 const char *zSep
2373 int i;
2374 if( nArg>0 ){
2375 oputz(zSep);
2376 print_dashes(p->actualWidth[0]+2);
2377 for(i=1; i<nArg; i++){
2378 oputz(zSep);
2379 print_dashes(p->actualWidth[i]+2);
2381 oputz(zSep);
2383 oputz("\n");
2387 ** This is the callback routine that the shell
2388 ** invokes for each row of a query result.
2390 static int shell_callback(
2391 void *pArg,
2392 int nArg, /* Number of result columns */
2393 char **azArg, /* Text of each result column */
2394 char **azCol, /* Column names */
2395 int *aiType /* Column types. Might be NULL */
2397 int i;
2398 ShellState *p = (ShellState*)pArg;
2400 if( azArg==0 ) return 0;
2401 switch( p->cMode ){
2402 case MODE_Count:
2403 case MODE_Off: {
2404 break;
2406 case MODE_Line: {
2407 int w = 5;
2408 if( azArg==0 ) break;
2409 for(i=0; i<nArg; i++){
2410 int len = strlen30(azCol[i] ? azCol[i] : "");
2411 if( len>w ) w = len;
2413 if( p->cnt++>0 ) oputz(p->rowSeparator);
2414 for(i=0; i<nArg; i++){
2415 oputf("%*s = %s%s", w, azCol[i],
2416 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2418 break;
2420 case MODE_ScanExp:
2421 case MODE_Explain: {
2422 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2423 static const int aExplainMap[] = {0, 1, 2, 3, 4, 5, 6, 7 };
2424 static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
2425 static const int aScanExpMap[] = {0, 9, 8, 1, 2, 3, 4, 5, 6, 7 };
2427 const int *aWidth = aExplainWidth;
2428 const int *aMap = aExplainMap;
2429 int nWidth = ArraySize(aExplainWidth);
2430 int iIndent = 1;
2432 if( p->cMode==MODE_ScanExp ){
2433 aWidth = aScanExpWidth;
2434 aMap = aScanExpMap;
2435 nWidth = ArraySize(aScanExpWidth);
2436 iIndent = 3;
2438 if( nArg>nWidth ) nArg = nWidth;
2440 /* If this is the first row seen, print out the headers */
2441 if( p->cnt++==0 ){
2442 for(i=0; i<nArg; i++){
2443 utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
2444 oputz(i==nArg-1 ? "\n" : " ");
2446 for(i=0; i<nArg; i++){
2447 print_dashes(aWidth[i]);
2448 oputz(i==nArg-1 ? "\n" : " ");
2452 /* If there is no data, exit early. */
2453 if( azArg==0 ) break;
2455 for(i=0; i<nArg; i++){
2456 const char *zSep = " ";
2457 int w = aWidth[i];
2458 const char *zVal = azArg[ aMap[i] ];
2459 if( i==nArg-1 ) w = 0;
2460 if( zVal && strlenChar(zVal)>w ){
2461 w = strlenChar(zVal);
2462 zSep = " ";
2464 if( i==iIndent && p->aiIndent && p->pStmt ){
2465 if( p->iIndent<p->nIndent ){
2466 oputf("%*.s", p->aiIndent[p->iIndent], "");
2468 p->iIndent++;
2470 utf8_width_print(w, zVal ? zVal : p->nullValue);
2471 oputz(i==nArg-1 ? "\n" : zSep);
2473 break;
2475 case MODE_Semi: { /* .schema and .fullschema output */
2476 printSchemaLine(azArg[0], ";\n");
2477 break;
2479 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2480 char *z;
2481 int j;
2482 int nParen = 0;
2483 char cEnd = 0;
2484 char c;
2485 int nLine = 0;
2486 assert( nArg==1 );
2487 if( azArg[0]==0 ) break;
2488 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2489 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2491 oputf("%s;\n", azArg[0]);
2492 break;
2494 z = sqlite3_mprintf("%s", azArg[0]);
2495 shell_check_oom(z);
2496 j = 0;
2497 for(i=0; IsSpace(z[i]); i++){}
2498 for(; (c = z[i])!=0; i++){
2499 if( IsSpace(c) ){
2500 if( z[j-1]=='\r' ) z[j-1] = '\n';
2501 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2502 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2503 j--;
2505 z[j++] = c;
2507 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2508 z[j] = 0;
2509 if( strlen30(z)>=79 ){
2510 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2511 if( c==cEnd ){
2512 cEnd = 0;
2513 }else if( c=='"' || c=='\'' || c=='`' ){
2514 cEnd = c;
2515 }else if( c=='[' ){
2516 cEnd = ']';
2517 }else if( c=='-' && z[i+1]=='-' ){
2518 cEnd = '\n';
2519 }else if( c=='(' ){
2520 nParen++;
2521 }else if( c==')' ){
2522 nParen--;
2523 if( nLine>0 && nParen==0 && j>0 ){
2524 printSchemaLineN(z, j, "\n");
2525 j = 0;
2528 z[j++] = c;
2529 if( nParen==1 && cEnd==0
2530 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2532 if( c=='\n' ) j--;
2533 printSchemaLineN(z, j, "\n ");
2534 j = 0;
2535 nLine++;
2536 while( IsSpace(z[i+1]) ){ i++; }
2539 z[j] = 0;
2541 printSchemaLine(z, ";\n");
2542 sqlite3_free(z);
2543 break;
2545 case MODE_List: {
2546 if( p->cnt++==0 && p->showHeader ){
2547 for(i=0; i<nArg; i++){
2548 oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
2551 if( azArg==0 ) break;
2552 for(i=0; i<nArg; i++){
2553 char *z = azArg[i];
2554 if( z==0 ) z = p->nullValue;
2555 oputz(z);
2556 oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
2558 break;
2560 case MODE_Html: {
2561 if( p->cnt++==0 && p->showHeader ){
2562 oputz("<TR>");
2563 for(i=0; i<nArg; i++){
2564 oputz("<TH>");
2565 output_html_string(azCol[i]);
2566 oputz("</TH>\n");
2568 oputz("</TR>\n");
2570 if( azArg==0 ) break;
2571 oputz("<TR>");
2572 for(i=0; i<nArg; i++){
2573 oputz("<TD>");
2574 output_html_string(azArg[i] ? azArg[i] : p->nullValue);
2575 oputz("</TD>\n");
2577 oputz("</TR>\n");
2578 break;
2580 case MODE_Tcl: {
2581 if( p->cnt++==0 && p->showHeader ){
2582 for(i=0; i<nArg; i++){
2583 output_c_string(azCol[i] ? azCol[i] : "");
2584 if(i<nArg-1) oputz(p->colSeparator);
2586 oputz(p->rowSeparator);
2588 if( azArg==0 ) break;
2589 for(i=0; i<nArg; i++){
2590 output_c_string(azArg[i] ? azArg[i] : p->nullValue);
2591 if(i<nArg-1) oputz(p->colSeparator);
2593 oputz(p->rowSeparator);
2594 break;
2596 case MODE_Csv: {
2597 setBinaryMode(p->out, 1);
2598 if( p->cnt++==0 && p->showHeader ){
2599 for(i=0; i<nArg; i++){
2600 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2602 oputz(p->rowSeparator);
2604 if( nArg>0 ){
2605 for(i=0; i<nArg; i++){
2606 output_csv(p, azArg[i], i<nArg-1);
2608 oputz(p->rowSeparator);
2610 setTextMode(p->out, 1);
2611 break;
2613 case MODE_Insert: {
2614 if( azArg==0 ) break;
2615 oputf("INSERT INTO %s",p->zDestTable);
2616 if( p->showHeader ){
2617 oputz("(");
2618 for(i=0; i<nArg; i++){
2619 if( i>0 ) oputz(",");
2620 if( quoteChar(azCol[i]) ){
2621 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2622 shell_check_oom(z);
2623 oputz(z);
2624 sqlite3_free(z);
2625 }else{
2626 oputf("%s", azCol[i]);
2629 oputz(")");
2631 p->cnt++;
2632 for(i=0; i<nArg; i++){
2633 oputz(i>0 ? "," : " VALUES(");
2634 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2635 oputz("NULL");
2636 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2637 if( ShellHasFlag(p, SHFLG_Newlines) ){
2638 output_quoted_string(azArg[i]);
2639 }else{
2640 output_quoted_escaped_string(azArg[i]);
2642 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2643 oputz(azArg[i]);
2644 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2645 char z[50];
2646 double r = sqlite3_column_double(p->pStmt, i);
2647 sqlite3_uint64 ur;
2648 memcpy(&ur,&r,sizeof(r));
2649 if( ur==0x7ff0000000000000LL ){
2650 oputz("9.0e+999");
2651 }else if( ur==0xfff0000000000000LL ){
2652 oputz("-9.0e+999");
2653 }else{
2654 sqlite3_int64 ir = (sqlite3_int64)r;
2655 if( r==(double)ir ){
2656 sqlite3_snprintf(50,z,"%lld.0", ir);
2657 }else{
2658 sqlite3_snprintf(50,z,"%!.20g", r);
2660 oputz(z);
2662 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2663 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2664 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2665 output_hex_blob(pBlob, nBlob);
2666 }else if( isNumber(azArg[i], 0) ){
2667 oputz(azArg[i]);
2668 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2669 output_quoted_string(azArg[i]);
2670 }else{
2671 output_quoted_escaped_string(azArg[i]);
2674 oputz(");\n");
2675 break;
2677 case MODE_Json: {
2678 if( azArg==0 ) break;
2679 if( p->cnt==0 ){
2680 fputs("[{", p->out);
2681 }else{
2682 fputs(",\n{", p->out);
2684 p->cnt++;
2685 for(i=0; i<nArg; i++){
2686 output_json_string(azCol[i], -1);
2687 oputz(":");
2688 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2689 oputz("null");
2690 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2691 char z[50];
2692 double r = sqlite3_column_double(p->pStmt, i);
2693 sqlite3_uint64 ur;
2694 memcpy(&ur,&r,sizeof(r));
2695 if( ur==0x7ff0000000000000LL ){
2696 oputz("9.0e+999");
2697 }else if( ur==0xfff0000000000000LL ){
2698 oputz("-9.0e+999");
2699 }else{
2700 sqlite3_snprintf(50,z,"%!.20g", r);
2701 oputz(z);
2703 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2704 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2705 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2706 output_json_string(pBlob, nBlob);
2707 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2708 output_json_string(azArg[i], -1);
2709 }else{
2710 oputz(azArg[i]);
2712 if( i<nArg-1 ){
2713 oputz(",");
2716 oputz("}");
2717 break;
2719 case MODE_Quote: {
2720 if( azArg==0 ) break;
2721 if( p->cnt==0 && p->showHeader ){
2722 for(i=0; i<nArg; i++){
2723 if( i>0 ) fputs(p->colSeparator, p->out);
2724 output_quoted_string(azCol[i]);
2726 fputs(p->rowSeparator, p->out);
2728 p->cnt++;
2729 for(i=0; i<nArg; i++){
2730 if( i>0 ) fputs(p->colSeparator, p->out);
2731 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2732 oputz("NULL");
2733 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2734 output_quoted_string(azArg[i]);
2735 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2736 oputz(azArg[i]);
2737 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2738 char z[50];
2739 double r = sqlite3_column_double(p->pStmt, i);
2740 sqlite3_snprintf(50,z,"%!.20g", r);
2741 oputz(z);
2742 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2743 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2744 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2745 output_hex_blob(pBlob, nBlob);
2746 }else if( isNumber(azArg[i], 0) ){
2747 oputz(azArg[i]);
2748 }else{
2749 output_quoted_string(azArg[i]);
2752 fputs(p->rowSeparator, p->out);
2753 break;
2755 case MODE_Ascii: {
2756 if( p->cnt++==0 && p->showHeader ){
2757 for(i=0; i<nArg; i++){
2758 if( i>0 ) oputz(p->colSeparator);
2759 oputz(azCol[i] ? azCol[i] : "");
2761 oputz(p->rowSeparator);
2763 if( azArg==0 ) break;
2764 for(i=0; i<nArg; i++){
2765 if( i>0 ) oputz(p->colSeparator);
2766 oputz(azArg[i] ? azArg[i] : p->nullValue);
2768 oputz(p->rowSeparator);
2769 break;
2771 case MODE_EQP: {
2772 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2773 break;
2776 return 0;
2780 ** This is the callback routine that the SQLite library
2781 ** invokes for each row of a query result.
2783 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2784 /* since we don't have type info, call the shell_callback with a NULL value */
2785 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2789 ** This is the callback routine from sqlite3_exec() that appends all
2790 ** output onto the end of a ShellText object.
2792 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2793 ShellText *p = (ShellText*)pArg;
2794 int i;
2795 UNUSED_PARAMETER(az);
2796 if( azArg==0 ) return 0;
2797 if( p->n ) appendText(p, "|", 0);
2798 for(i=0; i<nArg; i++){
2799 if( i ) appendText(p, ",", 0);
2800 if( azArg[i] ) appendText(p, azArg[i], 0);
2802 return 0;
2806 ** Generate an appropriate SELFTEST table in the main database.
2808 static void createSelftestTable(ShellState *p){
2809 char *zErrMsg = 0;
2810 sqlite3_exec(p->db,
2811 "SAVEPOINT selftest_init;\n"
2812 "CREATE TABLE IF NOT EXISTS selftest(\n"
2813 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2814 " op TEXT,\n" /* Operator: memo run */
2815 " cmd TEXT,\n" /* Command text */
2816 " ans TEXT\n" /* Desired answer */
2817 ");"
2818 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2819 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2820 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2821 " 'memo','Tests generated by --init');\n"
2822 "INSERT INTO [_shell$self]\n"
2823 " SELECT 'run',\n"
2824 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2825 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2826 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2827 "FROM sqlite_schema ORDER BY 2',224));\n"
2828 "INSERT INTO [_shell$self]\n"
2829 " SELECT 'run',"
2830 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2831 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2832 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2833 " FROM (\n"
2834 " SELECT name FROM sqlite_schema\n"
2835 " WHERE type='table'\n"
2836 " AND name<>'selftest'\n"
2837 " AND coalesce(rootpage,0)>0\n"
2838 " )\n"
2839 " ORDER BY name;\n"
2840 "INSERT INTO [_shell$self]\n"
2841 " VALUES('run','PRAGMA integrity_check','ok');\n"
2842 "INSERT INTO selftest(tno,op,cmd,ans)"
2843 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2844 "DROP TABLE [_shell$self];"
2845 ,0,0,&zErrMsg);
2846 if( zErrMsg ){
2847 eputf("SELFTEST initialization failure: %s\n", zErrMsg);
2848 sqlite3_free(zErrMsg);
2850 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2855 ** Set the destination table field of the ShellState structure to
2856 ** the name of the table given. Escape any quote characters in the
2857 ** table name.
2859 static void set_table_name(ShellState *p, const char *zName){
2860 int i, n;
2861 char cQuote;
2862 char *z;
2864 if( p->zDestTable ){
2865 free(p->zDestTable);
2866 p->zDestTable = 0;
2868 if( zName==0 ) return;
2869 cQuote = quoteChar(zName);
2870 n = strlen30(zName);
2871 if( cQuote ) n += n+2;
2872 z = p->zDestTable = malloc( n+1 );
2873 shell_check_oom(z);
2874 n = 0;
2875 if( cQuote ) z[n++] = cQuote;
2876 for(i=0; zName[i]; i++){
2877 z[n++] = zName[i];
2878 if( zName[i]==cQuote ) z[n++] = cQuote;
2880 if( cQuote ) z[n++] = cQuote;
2881 z[n] = 0;
2885 ** Maybe construct two lines of text that point out the position of a
2886 ** syntax error. Return a pointer to the text, in memory obtained from
2887 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2888 ** specific token that we can point to, return an empty string.
2890 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2891 ** and should be released by the caller invoking sqlite3_free().
2893 static char *shell_error_context(const char *zSql, sqlite3 *db){
2894 int iOffset;
2895 size_t len;
2896 char *zCode;
2897 char *zMsg;
2898 int i;
2899 if( db==0
2900 || zSql==0
2901 || (iOffset = sqlite3_error_offset(db))<0
2902 || iOffset>=(int)strlen(zSql)
2904 return sqlite3_mprintf("");
2906 while( iOffset>50 ){
2907 iOffset--;
2908 zSql++;
2909 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2911 len = strlen(zSql);
2912 if( len>78 ){
2913 len = 78;
2914 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
2916 zCode = sqlite3_mprintf("%.*s", len, zSql);
2917 shell_check_oom(zCode);
2918 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2919 if( iOffset<25 ){
2920 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
2921 }else{
2922 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,"");
2924 return zMsg;
2929 ** Execute a query statement that will generate SQL output. Print
2930 ** the result columns, comma-separated, on a line and then add a
2931 ** semicolon terminator to the end of that line.
2933 ** If the number of columns is 1 and that column contains text "--"
2934 ** then write the semicolon on a separate line. That way, if a
2935 ** "--" comment occurs at the end of the statement, the comment
2936 ** won't consume the semicolon terminator.
2938 static int run_table_dump_query(
2939 ShellState *p, /* Query context */
2940 const char *zSelect /* SELECT statement to extract content */
2942 sqlite3_stmt *pSelect;
2943 int rc;
2944 int nResult;
2945 int i;
2946 const char *z;
2947 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2948 if( rc!=SQLITE_OK || !pSelect ){
2949 char *zContext = shell_error_context(zSelect, p->db);
2950 oputf("/**** ERROR: (%d) %s *****/\n%s",
2951 rc, sqlite3_errmsg(p->db), zContext);
2952 sqlite3_free(zContext);
2953 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2954 return rc;
2956 rc = sqlite3_step(pSelect);
2957 nResult = sqlite3_column_count(pSelect);
2958 while( rc==SQLITE_ROW ){
2959 z = (const char*)sqlite3_column_text(pSelect, 0);
2960 oputf("%s", z);
2961 for(i=1; i<nResult; i++){
2962 oputf(",%s", sqlite3_column_text(pSelect, i));
2964 if( z==0 ) z = "";
2965 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2966 if( z[0] ){
2967 oputz("\n;\n");
2968 }else{
2969 oputz(";\n");
2971 rc = sqlite3_step(pSelect);
2973 rc = sqlite3_finalize(pSelect);
2974 if( rc!=SQLITE_OK ){
2975 oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
2976 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2978 return rc;
2982 ** Allocate space and save off string indicating current error.
2984 static char *save_err_msg(
2985 sqlite3 *db, /* Database to query */
2986 const char *zPhase, /* When the error occurs */
2987 int rc, /* Error code returned from API */
2988 const char *zSql /* SQL string, or NULL */
2990 char *zErr;
2991 char *zContext;
2992 sqlite3_str *pStr = sqlite3_str_new(0);
2993 sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2994 if( rc>1 ){
2995 sqlite3_str_appendf(pStr, " (%d)", rc);
2997 zContext = shell_error_context(zSql, db);
2998 if( zContext ){
2999 sqlite3_str_appendall(pStr, zContext);
3000 sqlite3_free(zContext);
3002 zErr = sqlite3_str_finish(pStr);
3003 shell_check_oom(zErr);
3004 return zErr;
3007 #ifdef __linux__
3009 ** Attempt to display I/O stats on Linux using /proc/PID/io
3011 static void displayLinuxIoStats(void){
3012 FILE *in;
3013 char z[200];
3014 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
3015 in = fopen(z, "rb");
3016 if( in==0 ) return;
3017 while( fgets(z, sizeof(z), in)!=0 ){
3018 static const struct {
3019 const char *zPattern;
3020 const char *zDesc;
3021 } aTrans[] = {
3022 { "rchar: ", "Bytes received by read():" },
3023 { "wchar: ", "Bytes sent to write():" },
3024 { "syscr: ", "Read() system calls:" },
3025 { "syscw: ", "Write() system calls:" },
3026 { "read_bytes: ", "Bytes read from storage:" },
3027 { "write_bytes: ", "Bytes written to storage:" },
3028 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
3030 int i;
3031 for(i=0; i<ArraySize(aTrans); i++){
3032 int n = strlen30(aTrans[i].zPattern);
3033 if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
3034 oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
3035 break;
3039 fclose(in);
3041 #endif
3044 ** Display a single line of status using 64-bit values.
3046 static void displayStatLine(
3047 char *zLabel, /* Label for this one line */
3048 char *zFormat, /* Format for the result */
3049 int iStatusCtrl, /* Which status to display */
3050 int bReset /* True to reset the stats */
3052 sqlite3_int64 iCur = -1;
3053 sqlite3_int64 iHiwtr = -1;
3054 int i, nPercent;
3055 char zLine[200];
3056 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
3057 for(i=0, nPercent=0; zFormat[i]; i++){
3058 if( zFormat[i]=='%' ) nPercent++;
3060 if( nPercent>1 ){
3061 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
3062 }else{
3063 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
3065 oputf("%-36s %s\n", zLabel, zLine);
3069 ** Display memory stats.
3071 static int display_stats(
3072 sqlite3 *db, /* Database to query */
3073 ShellState *pArg, /* Pointer to ShellState */
3074 int bReset /* True to reset the stats */
3076 int iCur;
3077 int iHiwtr;
3078 if( pArg==0 || pArg->out==0 ) return 0;
3080 if( pArg->pStmt && pArg->statsOn==2 ){
3081 int nCol, i, x;
3082 sqlite3_stmt *pStmt = pArg->pStmt;
3083 char z[100];
3084 nCol = sqlite3_column_count(pStmt);
3085 oputf("%-36s %d\n", "Number of output columns:", nCol);
3086 for(i=0; i<nCol; i++){
3087 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
3088 oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
3089 #ifndef SQLITE_OMIT_DECLTYPE
3090 sqlite3_snprintf(30, z+x, "declared type:");
3091 oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
3092 #endif
3093 #ifdef SQLITE_ENABLE_COLUMN_METADATA
3094 sqlite3_snprintf(30, z+x, "database name:");
3095 oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
3096 sqlite3_snprintf(30, z+x, "table name:");
3097 oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
3098 sqlite3_snprintf(30, z+x, "origin name:");
3099 oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
3100 #endif
3104 if( pArg->statsOn==3 ){
3105 if( pArg->pStmt ){
3106 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
3107 oputf("VM-steps: %d\n", iCur);
3109 return 0;
3112 displayStatLine("Memory Used:",
3113 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
3114 displayStatLine("Number of Outstanding Allocations:",
3115 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
3116 if( pArg->shellFlgs & SHFLG_Pagecache ){
3117 displayStatLine("Number of Pcache Pages Used:",
3118 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
3120 displayStatLine("Number of Pcache Overflow Bytes:",
3121 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
3122 displayStatLine("Largest Allocation:",
3123 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
3124 displayStatLine("Largest Pcache Allocation:",
3125 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
3126 #ifdef YYTRACKMAXSTACKDEPTH
3127 displayStatLine("Deepest Parser Stack:",
3128 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
3129 #endif
3131 if( db ){
3132 if( pArg->shellFlgs & SHFLG_Lookaside ){
3133 iHiwtr = iCur = -1;
3134 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
3135 &iCur, &iHiwtr, bReset);
3136 oputf("Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
3137 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
3138 &iCur, &iHiwtr, bReset);
3139 oputf("Successful lookaside attempts: %d\n", iHiwtr);
3140 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
3141 &iCur, &iHiwtr, bReset);
3142 oputf("Lookaside failures due to size: %d\n", iHiwtr);
3143 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
3144 &iCur, &iHiwtr, bReset);
3145 oputf("Lookaside failures due to OOM: %d\n", iHiwtr);
3147 iHiwtr = iCur = -1;
3148 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
3149 oputf("Pager Heap Usage: %d bytes\n", iCur);
3150 iHiwtr = iCur = -1;
3151 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
3152 oputf("Page cache hits: %d\n", iCur);
3153 iHiwtr = iCur = -1;
3154 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
3155 oputf("Page cache misses: %d\n", iCur);
3156 iHiwtr = iCur = -1;
3157 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
3158 oputf("Page cache writes: %d\n", iCur);
3159 iHiwtr = iCur = -1;
3160 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
3161 oputf("Page cache spills: %d\n", iCur);
3162 iHiwtr = iCur = -1;
3163 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
3164 oputf("Schema Heap Usage: %d bytes\n", iCur);
3165 iHiwtr = iCur = -1;
3166 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
3167 oputf("Statement Heap/Lookaside Usage: %d bytes\n", iCur);
3170 if( pArg->pStmt ){
3171 int iHit, iMiss;
3172 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
3173 bReset);
3174 oputf("Fullscan Steps: %d\n", iCur);
3175 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
3176 oputf("Sort Operations: %d\n", iCur);
3177 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
3178 oputf("Autoindex Inserts: %d\n", iCur);
3179 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
3180 bReset);
3181 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
3182 bReset);
3183 if( iHit || iMiss ){
3184 oputf("Bloom filter bypass taken: %d/%d\n", iHit, iHit+iMiss);
3186 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
3187 oputf("Virtual Machine Steps: %d\n", iCur);
3188 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
3189 oputf("Reprepare operations: %d\n", iCur);
3190 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
3191 oputf("Number of times run: %d\n", iCur);
3192 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
3193 oputf("Memory used by prepared stmt: %d\n", iCur);
3196 #ifdef __linux__
3197 displayLinuxIoStats();
3198 #endif
3200 /* Do not remove this machine readable comment: extra-stats-output-here */
3202 return 0;
3206 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3207 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
3208 int iPid = 0;
3209 int ret = 1;
3210 sqlite3_stmt_scanstatus_v2(p, iEntry,
3211 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3213 while( iPid!=0 ){
3214 int ii;
3215 for(ii=0; 1; ii++){
3216 int iId;
3217 int res;
3218 res = sqlite3_stmt_scanstatus_v2(p, ii,
3219 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
3221 if( res ) break;
3222 if( iId==iPid ){
3223 sqlite3_stmt_scanstatus_v2(p, ii,
3224 SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3228 ret++;
3230 return ret;
3232 #endif
3234 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3235 static void display_explain_scanstats(
3236 sqlite3 *db, /* Database to query */
3237 ShellState *pArg /* Pointer to ShellState */
3239 static const int f = SQLITE_SCANSTAT_COMPLEX;
3240 sqlite3_stmt *p = pArg->pStmt;
3241 int ii = 0;
3242 i64 nTotal = 0;
3243 int nWidth = 0;
3244 eqp_reset(pArg);
3246 for(ii=0; 1; ii++){
3247 const char *z = 0;
3248 int n = 0;
3249 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
3250 break;
3252 n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
3253 if( n>nWidth ) nWidth = n;
3255 nWidth += 4;
3257 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
3258 for(ii=0; 1; ii++){
3259 i64 nLoop = 0;
3260 i64 nRow = 0;
3261 i64 nCycle = 0;
3262 int iId = 0;
3263 int iPid = 0;
3264 const char *zo = 0;
3265 const char *zName = 0;
3266 char *zText = 0;
3267 double rEst = 0.0;
3269 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
3270 break;
3272 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
3273 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
3274 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
3275 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
3276 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
3277 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
3278 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
3280 zText = sqlite3_mprintf("%s", zo);
3281 if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
3282 char *z = 0;
3283 if( nCycle>=0 && nTotal>0 ){
3284 z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
3285 nCycle, ((nCycle*100)+nTotal/2) / nTotal
3288 if( nLoop>=0 ){
3289 z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
3291 if( nRow>=0 ){
3292 z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
3295 if( zName && pArg->scanstatsOn>1 ){
3296 double rpl = (double)nRow / (double)nLoop;
3297 z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
3300 zText = sqlite3_mprintf(
3301 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
3305 eqp_append(pArg, iId, iPid, zText);
3306 sqlite3_free(zText);
3309 eqp_render(pArg, nTotal);
3311 #endif
3315 ** Parameter azArray points to a zero-terminated array of strings. zStr
3316 ** points to a single nul-terminated string. Return non-zero if zStr
3317 ** is equal, according to strcmp(), to any of the strings in the array.
3318 ** Otherwise, return zero.
3320 static int str_in_array(const char *zStr, const char **azArray){
3321 int i;
3322 for(i=0; azArray[i]; i++){
3323 if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
3325 return 0;
3329 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3330 ** and populate the ShellState.aiIndent[] array with the number of
3331 ** spaces each opcode should be indented before it is output.
3333 ** The indenting rules are:
3335 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3336 ** all opcodes that occur between the p2 jump destination and the opcode
3337 ** itself by 2 spaces.
3339 ** * Do the previous for "Return" instructions for when P2 is positive.
3340 ** See tag-20220407a in wherecode.c and vdbe.c.
3342 ** * For each "Goto", if the jump destination is earlier in the program
3343 ** and ends on one of:
3344 ** Yield SeekGt SeekLt RowSetRead Rewind
3345 ** or if the P1 parameter is one instead of zero,
3346 ** then indent all opcodes between the earlier instruction
3347 ** and "Goto" by 2 spaces.
3349 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3350 int *abYield = 0; /* True if op is an OP_Yield */
3351 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
3352 int iOp; /* Index of operation in p->aiIndent[] */
3354 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3355 "Return", 0 };
3356 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3357 "Rewind", 0 };
3358 const char *azGoto[] = { "Goto", 0 };
3360 /* The caller guarantees that the leftmost 4 columns of the statement
3361 ** passed to this function are equivalent to the leftmost 4 columns
3362 ** of EXPLAIN statement output. In practice the statement may be
3363 ** an EXPLAIN, or it may be a query on the bytecode() virtual table. */
3364 assert( sqlite3_column_count(pSql)>=4 );
3365 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
3366 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
3367 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
3368 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
3370 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3371 int i;
3372 int iAddr = sqlite3_column_int(pSql, 0);
3373 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3374 int p1 = sqlite3_column_int(pSql, 2);
3375 int p2 = sqlite3_column_int(pSql, 3);
3377 /* Assuming that p2 is an instruction address, set variable p2op to the
3378 ** index of that instruction in the aiIndent[] array. p2 and p2op may be
3379 ** different if the current instruction is part of a sub-program generated
3380 ** by an SQL trigger or foreign key. */
3381 int p2op = (p2 + (iOp-iAddr));
3383 /* Grow the p->aiIndent array as required */
3384 if( iOp>=nAlloc ){
3385 nAlloc += 100;
3386 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3387 shell_check_oom(p->aiIndent);
3388 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3389 shell_check_oom(abYield);
3392 abYield[iOp] = str_in_array(zOp, azYield);
3393 p->aiIndent[iOp] = 0;
3394 p->nIndent = iOp+1;
3395 if( str_in_array(zOp, azNext) && p2op>0 ){
3396 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3398 if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
3399 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3403 p->iIndent = 0;
3404 sqlite3_free(abYield);
3405 sqlite3_reset(pSql);
3409 ** Free the array allocated by explain_data_prepare().
3411 static void explain_data_delete(ShellState *p){
3412 sqlite3_free(p->aiIndent);
3413 p->aiIndent = 0;
3414 p->nIndent = 0;
3415 p->iIndent = 0;
3418 static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
3421 ** Display scan stats.
3423 static void display_scanstats(
3424 sqlite3 *db, /* Database to query */
3425 ShellState *pArg /* Pointer to ShellState */
3427 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3428 UNUSED_PARAMETER(db);
3429 UNUSED_PARAMETER(pArg);
3430 #else
3431 if( pArg->scanstatsOn==3 ){
3432 const char *zSql =
3433 " SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
3434 " round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
3435 " FROM bytecode(?)";
3437 int rc = SQLITE_OK;
3438 sqlite3_stmt *pStmt = 0;
3439 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3440 if( rc==SQLITE_OK ){
3441 sqlite3_stmt *pSave = pArg->pStmt;
3442 pArg->pStmt = pStmt;
3443 sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
3445 pArg->cnt = 0;
3446 pArg->cMode = MODE_ScanExp;
3447 explain_data_prepare(pArg, pStmt);
3448 exec_prepared_stmt(pArg, pStmt);
3449 explain_data_delete(pArg);
3451 sqlite3_finalize(pStmt);
3452 pArg->pStmt = pSave;
3454 }else{
3455 display_explain_scanstats(db, pArg);
3457 #endif
3461 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3463 static unsigned int savedSelectTrace;
3464 static unsigned int savedWhereTrace;
3465 static void disable_debug_trace_modes(void){
3466 unsigned int zero = 0;
3467 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3468 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3469 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3470 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3472 static void restore_debug_trace_modes(void){
3473 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3474 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3477 /* Create the TEMP table used to store parameter bindings */
3478 static void bind_table_init(ShellState *p){
3479 int wrSchema = 0;
3480 int defensiveMode = 0;
3481 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3482 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3483 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3484 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3485 sqlite3_exec(p->db,
3486 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3487 " key TEXT PRIMARY KEY,\n"
3488 " value\n"
3489 ") WITHOUT ROWID;",
3490 0, 0, 0);
3491 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3492 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3496 ** Bind parameters on a prepared statement.
3498 ** Parameter bindings are taken from a TEMP table of the form:
3500 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3501 ** WITHOUT ROWID;
3503 ** No bindings occur if this table does not exist. The name of the table
3504 ** begins with "sqlite_" so that it will not collide with ordinary application
3505 ** tables. The table must be in the TEMP schema.
3507 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3508 int nVar;
3509 int i;
3510 int rc;
3511 sqlite3_stmt *pQ = 0;
3513 nVar = sqlite3_bind_parameter_count(pStmt);
3514 if( nVar==0 ) return; /* Nothing to do */
3515 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3516 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3517 rc = SQLITE_NOTFOUND;
3518 pQ = 0;
3519 }else{
3520 rc = sqlite3_prepare_v2(pArg->db,
3521 "SELECT value FROM temp.sqlite_parameters"
3522 " WHERE key=?1", -1, &pQ, 0);
3524 for(i=1; i<=nVar; i++){
3525 char zNum[30];
3526 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3527 if( zVar==0 ){
3528 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3529 zVar = zNum;
3531 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3532 if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
3533 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3534 #ifdef NAN
3535 }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
3536 sqlite3_bind_double(pStmt, i, NAN);
3537 #endif
3538 #ifdef INFINITY
3539 }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
3540 sqlite3_bind_double(pStmt, i, INFINITY);
3541 #endif
3542 }else{
3543 sqlite3_bind_null(pStmt, i);
3545 sqlite3_reset(pQ);
3547 sqlite3_finalize(pQ);
3551 ** UTF8 box-drawing characters. Imagine box lines like this:
3553 ** 1
3554 ** |
3555 ** 4 --+-- 2
3556 ** |
3557 ** 3
3559 ** Each box characters has between 2 and 4 of the lines leading from
3560 ** the center. The characters are here identified by the numbers of
3561 ** their corresponding lines.
3563 #define BOX_24 "\342\224\200" /* U+2500 --- */
3564 #define BOX_13 "\342\224\202" /* U+2502 | */
3565 #define BOX_23 "\342\224\214" /* U+250c ,- */
3566 #define BOX_34 "\342\224\220" /* U+2510 -, */
3567 #define BOX_12 "\342\224\224" /* U+2514 '- */
3568 #define BOX_14 "\342\224\230" /* U+2518 -' */
3569 #define BOX_123 "\342\224\234" /* U+251c |- */
3570 #define BOX_134 "\342\224\244" /* U+2524 -| */
3571 #define BOX_234 "\342\224\254" /* U+252c -,- */
3572 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3573 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3575 /* Draw horizontal line N characters long using unicode box
3576 ** characters
3578 static void print_box_line(int N){
3579 const char zDash[] =
3580 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3581 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3582 const int nDash = sizeof(zDash) - 1;
3583 N *= 3;
3584 while( N>nDash ){
3585 oputz(zDash);
3586 N -= nDash;
3588 oputf("%.*s", N, zDash);
3592 ** Draw a horizontal separator for a MODE_Box table.
3594 static void print_box_row_separator(
3595 ShellState *p,
3596 int nArg,
3597 const char *zSep1,
3598 const char *zSep2,
3599 const char *zSep3
3601 int i;
3602 if( nArg>0 ){
3603 oputz(zSep1);
3604 print_box_line(p->actualWidth[0]+2);
3605 for(i=1; i<nArg; i++){
3606 oputz(zSep2);
3607 print_box_line(p->actualWidth[i]+2);
3609 oputz(zSep3);
3611 oputz("\n");
3615 ** z[] is a line of text that is to be displayed the .mode box or table or
3616 ** similar tabular formats. z[] might contain control characters such
3617 ** as \n, \t, \f, or \r.
3619 ** Compute characters to display on the first line of z[]. Stop at the
3620 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3621 ** from malloc()) of that first line, which caller should free sometime.
3622 ** Write anything to display on the next line into *pzTail. If this is
3623 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3625 static char *translateForDisplayAndDup(
3626 const unsigned char *z, /* Input text to be transformed */
3627 const unsigned char **pzTail, /* OUT: Tail of the input for next line */
3628 int mxWidth, /* Max width. 0 means no limit */
3629 u8 bWordWrap /* If true, avoid breaking mid-word */
3631 int i; /* Input bytes consumed */
3632 int j; /* Output bytes generated */
3633 int k; /* Input bytes to be displayed */
3634 int n; /* Output column number */
3635 unsigned char *zOut; /* Output text */
3637 if( z==0 ){
3638 *pzTail = 0;
3639 return 0;
3641 if( mxWidth<0 ) mxWidth = -mxWidth;
3642 if( mxWidth==0 ) mxWidth = 1000000;
3643 i = j = n = 0;
3644 while( n<mxWidth ){
3645 if( z[i]>=' ' ){
3646 n++;
3647 do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3648 continue;
3650 if( z[i]=='\t' ){
3652 n++;
3653 j++;
3654 }while( (n&7)!=0 && n<mxWidth );
3655 i++;
3656 continue;
3658 break;
3660 if( n>=mxWidth && bWordWrap ){
3661 /* Perhaps try to back up to a better place to break the line */
3662 for(k=i; k>i/2; k--){
3663 if( isspace(z[k-1]) ) break;
3665 if( k<=i/2 ){
3666 for(k=i; k>i/2; k--){
3667 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3670 if( k<=i/2 ){
3671 k = i;
3672 }else{
3673 i = k;
3674 while( z[i]==' ' ) i++;
3676 }else{
3677 k = i;
3679 if( n>=mxWidth && z[i]>=' ' ){
3680 *pzTail = &z[i];
3681 }else if( z[i]=='\r' && z[i+1]=='\n' ){
3682 *pzTail = z[i+2] ? &z[i+2] : 0;
3683 }else if( z[i]==0 || z[i+1]==0 ){
3684 *pzTail = 0;
3685 }else{
3686 *pzTail = &z[i+1];
3688 zOut = malloc( j+1 );
3689 shell_check_oom(zOut);
3690 i = j = n = 0;
3691 while( i<k ){
3692 if( z[i]>=' ' ){
3693 n++;
3694 do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3695 continue;
3697 if( z[i]=='\t' ){
3699 n++;
3700 zOut[j++] = ' ';
3701 }while( (n&7)!=0 && n<mxWidth );
3702 i++;
3703 continue;
3705 break;
3707 zOut[j] = 0;
3708 return (char*)zOut;
3711 /* Extract the value of the i-th current column for pStmt as an SQL literal
3712 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3713 ** the caller.
3715 static char *quoted_column(sqlite3_stmt *pStmt, int i){
3716 switch( sqlite3_column_type(pStmt, i) ){
3717 case SQLITE_NULL: {
3718 return sqlite3_mprintf("NULL");
3720 case SQLITE_INTEGER:
3721 case SQLITE_FLOAT: {
3722 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3724 case SQLITE_TEXT: {
3725 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3727 case SQLITE_BLOB: {
3728 int j;
3729 sqlite3_str *pStr = sqlite3_str_new(0);
3730 const unsigned char *a = sqlite3_column_blob(pStmt,i);
3731 int n = sqlite3_column_bytes(pStmt,i);
3732 sqlite3_str_append(pStr, "x'", 2);
3733 for(j=0; j<n; j++){
3734 sqlite3_str_appendf(pStr, "%02x", a[j]);
3736 sqlite3_str_append(pStr, "'", 1);
3737 return sqlite3_str_finish(pStr);
3740 return 0; /* Not reached */
3744 ** Run a prepared statement and output the result in one of the
3745 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3746 ** or MODE_Box.
3748 ** This is different from ordinary exec_prepared_stmt() in that
3749 ** it has to run the entire query and gather the results into memory
3750 ** first, in order to determine column widths, before providing
3751 ** any output.
3753 static void exec_prepared_stmt_columnar(
3754 ShellState *p, /* Pointer to ShellState */
3755 sqlite3_stmt *pStmt /* Statement to run */
3757 sqlite3_int64 nRow = 0;
3758 int nColumn = 0;
3759 char **azData = 0;
3760 sqlite3_int64 nAlloc = 0;
3761 char *abRowDiv = 0;
3762 const unsigned char *uz;
3763 const char *z;
3764 char **azQuoted = 0;
3765 int rc;
3766 sqlite3_int64 i, nData;
3767 int j, nTotal, w, n;
3768 const char *colSep = 0;
3769 const char *rowSep = 0;
3770 const unsigned char **azNextLine = 0;
3771 int bNextLine = 0;
3772 int bMultiLineRowExists = 0;
3773 int bw = p->cmOpts.bWordWrap;
3774 const char *zEmpty = "";
3775 const char *zShowNull = p->nullValue;
3777 rc = sqlite3_step(pStmt);
3778 if( rc!=SQLITE_ROW ) return;
3779 nColumn = sqlite3_column_count(pStmt);
3780 nAlloc = nColumn*4;
3781 if( nAlloc<=0 ) nAlloc = 1;
3782 azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3783 shell_check_oom(azData);
3784 azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3785 shell_check_oom(azNextLine);
3786 memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3787 if( p->cmOpts.bQuote ){
3788 azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3789 shell_check_oom(azQuoted);
3790 memset(azQuoted, 0, nColumn*sizeof(char*) );
3792 abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3793 shell_check_oom(abRowDiv);
3794 if( nColumn>p->nWidth ){
3795 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3796 shell_check_oom(p->colWidth);
3797 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3798 p->nWidth = nColumn;
3799 p->actualWidth = &p->colWidth[nColumn];
3801 memset(p->actualWidth, 0, nColumn*sizeof(int));
3802 for(i=0; i<nColumn; i++){
3803 w = p->colWidth[i];
3804 if( w<0 ) w = -w;
3805 p->actualWidth[i] = w;
3807 for(i=0; i<nColumn; i++){
3808 const unsigned char *zNotUsed;
3809 int wx = p->colWidth[i];
3810 if( wx==0 ){
3811 wx = p->cmOpts.iWrap;
3813 if( wx<0 ) wx = -wx;
3814 uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3815 if( uz==0 ) uz = (u8*)"";
3816 azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3819 int useNextLine = bNextLine;
3820 bNextLine = 0;
3821 if( (nRow+2)*nColumn >= nAlloc ){
3822 nAlloc *= 2;
3823 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3824 shell_check_oom(azData);
3825 abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3826 shell_check_oom(abRowDiv);
3828 abRowDiv[nRow] = 1;
3829 nRow++;
3830 for(i=0; i<nColumn; i++){
3831 int wx = p->colWidth[i];
3832 if( wx==0 ){
3833 wx = p->cmOpts.iWrap;
3835 if( wx<0 ) wx = -wx;
3836 if( useNextLine ){
3837 uz = azNextLine[i];
3838 if( uz==0 ) uz = (u8*)zEmpty;
3839 }else if( p->cmOpts.bQuote ){
3840 sqlite3_free(azQuoted[i]);
3841 azQuoted[i] = quoted_column(pStmt,i);
3842 uz = (const unsigned char*)azQuoted[i];
3843 }else{
3844 uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3845 if( uz==0 ) uz = (u8*)zShowNull;
3847 azData[nRow*nColumn + i]
3848 = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3849 if( azNextLine[i] ){
3850 bNextLine = 1;
3851 abRowDiv[nRow-1] = 0;
3852 bMultiLineRowExists = 1;
3855 }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3856 nTotal = nColumn*(nRow+1);
3857 for(i=0; i<nTotal; i++){
3858 z = azData[i];
3859 if( z==0 ) z = (char*)zEmpty;
3860 n = strlenChar(z);
3861 j = i%nColumn;
3862 if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3864 if( seenInterrupt ) goto columnar_end;
3865 if( nColumn==0 ) goto columnar_end;
3866 switch( p->cMode ){
3867 case MODE_Column: {
3868 colSep = " ";
3869 rowSep = "\n";
3870 if( p->showHeader ){
3871 for(i=0; i<nColumn; i++){
3872 w = p->actualWidth[i];
3873 if( p->colWidth[i]<0 ) w = -w;
3874 utf8_width_print(w, azData[i]);
3875 fputs(i==nColumn-1?"\n":" ", p->out);
3877 for(i=0; i<nColumn; i++){
3878 print_dashes(p->actualWidth[i]);
3879 fputs(i==nColumn-1?"\n":" ", p->out);
3882 break;
3884 case MODE_Table: {
3885 colSep = " | ";
3886 rowSep = " |\n";
3887 print_row_separator(p, nColumn, "+");
3888 fputs("| ", p->out);
3889 for(i=0; i<nColumn; i++){
3890 w = p->actualWidth[i];
3891 n = strlenChar(azData[i]);
3892 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3893 oputz(i==nColumn-1?" |\n":" | ");
3895 print_row_separator(p, nColumn, "+");
3896 break;
3898 case MODE_Markdown: {
3899 colSep = " | ";
3900 rowSep = " |\n";
3901 fputs("| ", p->out);
3902 for(i=0; i<nColumn; i++){
3903 w = p->actualWidth[i];
3904 n = strlenChar(azData[i]);
3905 oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3906 oputz(i==nColumn-1?" |\n":" | ");
3908 print_row_separator(p, nColumn, "|");
3909 break;
3911 case MODE_Box: {
3912 colSep = " " BOX_13 " ";
3913 rowSep = " " BOX_13 "\n";
3914 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3915 oputz(BOX_13 " ");
3916 for(i=0; i<nColumn; i++){
3917 w = p->actualWidth[i];
3918 n = strlenChar(azData[i]);
3919 oputf("%*s%s%*s%s",
3920 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3921 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3923 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3924 break;
3927 for(i=nColumn, j=0; i<nTotal; i++, j++){
3928 if( j==0 && p->cMode!=MODE_Column ){
3929 oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
3931 z = azData[i];
3932 if( z==0 ) z = p->nullValue;
3933 w = p->actualWidth[j];
3934 if( p->colWidth[j]<0 ) w = -w;
3935 utf8_width_print(w, z);
3936 if( j==nColumn-1 ){
3937 oputz(rowSep);
3938 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3939 if( p->cMode==MODE_Table ){
3940 print_row_separator(p, nColumn, "+");
3941 }else if( p->cMode==MODE_Box ){
3942 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3943 }else if( p->cMode==MODE_Column ){
3944 oputz("\n");
3947 j = -1;
3948 if( seenInterrupt ) goto columnar_end;
3949 }else{
3950 oputz(colSep);
3953 if( p->cMode==MODE_Table ){
3954 print_row_separator(p, nColumn, "+");
3955 }else if( p->cMode==MODE_Box ){
3956 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3958 columnar_end:
3959 if( seenInterrupt ){
3960 oputz("Interrupt\n");
3962 nData = (nRow+1)*nColumn;
3963 for(i=0; i<nData; i++){
3964 z = azData[i];
3965 if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3967 sqlite3_free(azData);
3968 sqlite3_free((void*)azNextLine);
3969 sqlite3_free(abRowDiv);
3970 if( azQuoted ){
3971 for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3972 sqlite3_free(azQuoted);
3977 ** Run a prepared statement
3979 static void exec_prepared_stmt(
3980 ShellState *pArg, /* Pointer to ShellState */
3981 sqlite3_stmt *pStmt /* Statement to run */
3983 int rc;
3984 sqlite3_uint64 nRow = 0;
3986 if( pArg->cMode==MODE_Column
3987 || pArg->cMode==MODE_Table
3988 || pArg->cMode==MODE_Box
3989 || pArg->cMode==MODE_Markdown
3991 exec_prepared_stmt_columnar(pArg, pStmt);
3992 return;
3995 /* perform the first step. this will tell us if we
3996 ** have a result set or not and how wide it is.
3998 rc = sqlite3_step(pStmt);
3999 /* if we have a result set... */
4000 if( SQLITE_ROW == rc ){
4001 /* allocate space for col name ptr, value ptr, and type */
4002 int nCol = sqlite3_column_count(pStmt);
4003 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
4004 if( !pData ){
4005 shell_out_of_memory();
4006 }else{
4007 char **azCols = (char **)pData; /* Names of result columns */
4008 char **azVals = &azCols[nCol]; /* Results */
4009 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
4010 int i, x;
4011 assert(sizeof(int) <= sizeof(char *));
4012 /* save off ptrs to column names */
4013 for(i=0; i<nCol; i++){
4014 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
4017 nRow++;
4018 /* extract the data and data types */
4019 for(i=0; i<nCol; i++){
4020 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
4021 if( x==SQLITE_BLOB
4022 && pArg
4023 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
4025 azVals[i] = "";
4026 }else{
4027 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
4029 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
4030 rc = SQLITE_NOMEM;
4031 break; /* from for */
4033 } /* end for */
4035 /* if data and types extracted successfully... */
4036 if( SQLITE_ROW == rc ){
4037 /* call the supplied callback with the result row data */
4038 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
4039 rc = SQLITE_ABORT;
4040 }else{
4041 rc = sqlite3_step(pStmt);
4044 } while( SQLITE_ROW == rc );
4045 sqlite3_free(pData);
4046 if( pArg->cMode==MODE_Json ){
4047 fputs("]\n", pArg->out);
4048 }else if( pArg->cMode==MODE_Count ){
4049 char zBuf[200];
4050 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
4051 nRow, nRow!=1 ? "s" : "");
4052 printf("%s", zBuf);
4058 #ifndef SQLITE_OMIT_VIRTUALTABLE
4060 ** This function is called to process SQL if the previous shell command
4061 ** was ".expert". It passes the SQL in the second argument directly to
4062 ** the sqlite3expert object.
4064 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4065 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4066 ** an English language error message. It is the responsibility of the
4067 ** caller to eventually free this buffer using sqlite3_free().
4069 static int expertHandleSQL(
4070 ShellState *pState,
4071 const char *zSql,
4072 char **pzErr
4074 assert( pState->expert.pExpert );
4075 assert( pzErr==0 || *pzErr==0 );
4076 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
4080 ** This function is called either to silently clean up the object
4081 ** created by the ".expert" command (if bCancel==1), or to generate a
4082 ** report from it and then clean it up (if bCancel==0).
4084 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4085 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4086 ** an English language error message. It is the responsibility of the
4087 ** caller to eventually free this buffer using sqlite3_free().
4089 static int expertFinish(
4090 ShellState *pState,
4091 int bCancel,
4092 char **pzErr
4094 int rc = SQLITE_OK;
4095 sqlite3expert *p = pState->expert.pExpert;
4096 assert( p );
4097 assert( bCancel || pzErr==0 || *pzErr==0 );
4098 if( bCancel==0 ){
4099 int bVerbose = pState->expert.bVerbose;
4101 rc = sqlite3_expert_analyze(p, pzErr);
4102 if( rc==SQLITE_OK ){
4103 int nQuery = sqlite3_expert_count(p);
4104 int i;
4106 if( bVerbose ){
4107 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
4108 oputz("-- Candidates -----------------------------\n");
4109 oputf("%s\n", zCand);
4111 for(i=0; i<nQuery; i++){
4112 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
4113 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
4114 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
4115 if( zIdx==0 ) zIdx = "(no new indexes)\n";
4116 if( bVerbose ){
4117 oputf("-- Query %d --------------------------------\n",i+1);
4118 oputf("%s\n\n", zSql);
4120 oputf("%s\n", zIdx);
4121 oputf("%s\n", zEQP);
4125 sqlite3_expert_destroy(p);
4126 pState->expert.pExpert = 0;
4127 return rc;
4131 ** Implementation of ".expert" dot command.
4133 static int expertDotCommand(
4134 ShellState *pState, /* Current shell tool state */
4135 char **azArg, /* Array of arguments passed to dot command */
4136 int nArg /* Number of entries in azArg[] */
4138 int rc = SQLITE_OK;
4139 char *zErr = 0;
4140 int i;
4141 int iSample = 0;
4143 assert( pState->expert.pExpert==0 );
4144 memset(&pState->expert, 0, sizeof(ExpertInfo));
4146 for(i=1; rc==SQLITE_OK && i<nArg; i++){
4147 char *z = azArg[i];
4148 int n;
4149 if( z[0]=='-' && z[1]=='-' ) z++;
4150 n = strlen30(z);
4151 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
4152 pState->expert.bVerbose = 1;
4154 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
4155 if( i==(nArg-1) ){
4156 eputf("option requires an argument: %s\n", z);
4157 rc = SQLITE_ERROR;
4158 }else{
4159 iSample = (int)integerValue(azArg[++i]);
4160 if( iSample<0 || iSample>100 ){
4161 eputf("value out of range: %s\n", azArg[i]);
4162 rc = SQLITE_ERROR;
4166 else{
4167 eputf("unknown option: %s\n", z);
4168 rc = SQLITE_ERROR;
4172 if( rc==SQLITE_OK ){
4173 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
4174 if( pState->expert.pExpert==0 ){
4175 eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
4176 rc = SQLITE_ERROR;
4177 }else{
4178 sqlite3_expert_config(
4179 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
4183 sqlite3_free(zErr);
4185 return rc;
4187 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4190 ** Execute a statement or set of statements. Print
4191 ** any result rows/columns depending on the current mode
4192 ** set via the supplied callback.
4194 ** This is very similar to SQLite's built-in sqlite3_exec()
4195 ** function except it takes a slightly different callback
4196 ** and callback data argument.
4198 static int shell_exec(
4199 ShellState *pArg, /* Pointer to ShellState */
4200 const char *zSql, /* SQL to be evaluated */
4201 char **pzErrMsg /* Error msg written here */
4203 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
4204 int rc = SQLITE_OK; /* Return Code */
4205 int rc2;
4206 const char *zLeftover; /* Tail of unprocessed SQL */
4207 sqlite3 *db = pArg->db;
4209 if( pzErrMsg ){
4210 *pzErrMsg = NULL;
4213 #ifndef SQLITE_OMIT_VIRTUALTABLE
4214 if( pArg->expert.pExpert ){
4215 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
4216 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
4218 #endif
4220 while( zSql[0] && (SQLITE_OK == rc) ){
4221 static const char *zStmtSql;
4222 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
4223 if( SQLITE_OK != rc ){
4224 if( pzErrMsg ){
4225 *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
4227 }else{
4228 if( !pStmt ){
4229 /* this happens for a comment or white-space */
4230 zSql = zLeftover;
4231 while( IsSpace(zSql[0]) ) zSql++;
4232 continue;
4234 zStmtSql = sqlite3_sql(pStmt);
4235 if( zStmtSql==0 ) zStmtSql = "";
4236 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
4238 /* save off the prepared statement handle and reset row count */
4239 if( pArg ){
4240 pArg->pStmt = pStmt;
4241 pArg->cnt = 0;
4244 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4245 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
4246 sqlite3_stmt *pExplain;
4247 int triggerEQP = 0;
4248 disable_debug_trace_modes();
4249 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
4250 if( pArg->autoEQP>=AUTOEQP_trigger ){
4251 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
4253 pExplain = pStmt;
4254 sqlite3_reset(pExplain);
4255 rc = sqlite3_stmt_explain(pExplain, 2);
4256 if( rc==SQLITE_OK ){
4257 while( sqlite3_step(pExplain)==SQLITE_ROW ){
4258 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
4259 int iEqpId = sqlite3_column_int(pExplain, 0);
4260 int iParentId = sqlite3_column_int(pExplain, 1);
4261 if( zEQPLine==0 ) zEQPLine = "";
4262 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
4263 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
4265 eqp_render(pArg, 0);
4267 if( pArg->autoEQP>=AUTOEQP_full ){
4268 /* Also do an EXPLAIN for ".eqp full" mode */
4269 sqlite3_reset(pExplain);
4270 rc = sqlite3_stmt_explain(pExplain, 1);
4271 if( rc==SQLITE_OK ){
4272 pArg->cMode = MODE_Explain;
4273 assert( sqlite3_stmt_isexplain(pExplain)==1 );
4274 explain_data_prepare(pArg, pExplain);
4275 exec_prepared_stmt(pArg, pExplain);
4276 explain_data_delete(pArg);
4279 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
4280 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
4282 sqlite3_reset(pStmt);
4283 sqlite3_stmt_explain(pStmt, 0);
4284 restore_debug_trace_modes();
4287 if( pArg ){
4288 int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
4289 pArg->cMode = pArg->mode;
4290 if( pArg->autoExplain ){
4291 if( bIsExplain ){
4292 pArg->cMode = MODE_Explain;
4294 if( sqlite3_stmt_isexplain(pStmt)==2 ){
4295 pArg->cMode = MODE_EQP;
4299 /* If the shell is currently in ".explain" mode, gather the extra
4300 ** data required to add indents to the output.*/
4301 if( pArg->cMode==MODE_Explain && bIsExplain ){
4302 explain_data_prepare(pArg, pStmt);
4306 bind_prepared_stmt(pArg, pStmt);
4307 exec_prepared_stmt(pArg, pStmt);
4308 explain_data_delete(pArg);
4309 eqp_render(pArg, 0);
4311 /* print usage stats if stats on */
4312 if( pArg && pArg->statsOn ){
4313 display_stats(db, pArg, 0);
4316 /* print loop-counters if required */
4317 if( pArg && pArg->scanstatsOn ){
4318 display_scanstats(db, pArg);
4321 /* Finalize the statement just executed. If this fails, save a
4322 ** copy of the error message. Otherwise, set zSql to point to the
4323 ** next statement to execute. */
4324 rc2 = sqlite3_finalize(pStmt);
4325 if( rc!=SQLITE_NOMEM ) rc = rc2;
4326 if( rc==SQLITE_OK ){
4327 zSql = zLeftover;
4328 while( IsSpace(zSql[0]) ) zSql++;
4329 }else if( pzErrMsg ){
4330 *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
4333 /* clear saved stmt handle */
4334 if( pArg ){
4335 pArg->pStmt = NULL;
4338 } /* end while */
4340 return rc;
4344 ** Release memory previously allocated by tableColumnList().
4346 static void freeColumnList(char **azCol){
4347 int i;
4348 for(i=1; azCol[i]; i++){
4349 sqlite3_free(azCol[i]);
4351 /* azCol[0] is a static string */
4352 sqlite3_free(azCol);
4356 ** Return a list of pointers to strings which are the names of all
4357 ** columns in table zTab. The memory to hold the names is dynamically
4358 ** allocated and must be released by the caller using a subsequent call
4359 ** to freeColumnList().
4361 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4362 ** value that needs to be preserved, then azCol[0] is filled in with the
4363 ** name of the rowid column.
4365 ** The first regular column in the table is azCol[1]. The list is terminated
4366 ** by an entry with azCol[i]==0.
4368 static char **tableColumnList(ShellState *p, const char *zTab){
4369 char **azCol = 0;
4370 sqlite3_stmt *pStmt;
4371 char *zSql;
4372 int nCol = 0;
4373 int nAlloc = 0;
4374 int nPK = 0; /* Number of PRIMARY KEY columns seen */
4375 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
4376 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4377 int rc;
4379 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4380 shell_check_oom(zSql);
4381 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4382 sqlite3_free(zSql);
4383 if( rc ) return 0;
4384 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4385 if( nCol>=nAlloc-2 ){
4386 nAlloc = nAlloc*2 + nCol + 10;
4387 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4388 shell_check_oom(azCol);
4390 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4391 shell_check_oom(azCol[nCol]);
4392 if( sqlite3_column_int(pStmt, 5) ){
4393 nPK++;
4394 if( nPK==1
4395 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4396 "INTEGER")==0
4398 isIPK = 1;
4399 }else{
4400 isIPK = 0;
4404 sqlite3_finalize(pStmt);
4405 if( azCol==0 ) return 0;
4406 azCol[0] = 0;
4407 azCol[nCol+1] = 0;
4409 /* The decision of whether or not a rowid really needs to be preserved
4410 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4411 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4412 ** rowids on tables where the rowid is inaccessible because there are other
4413 ** columns in the table named "rowid", "_rowid_", and "oid".
4415 if( preserveRowid && isIPK ){
4416 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4417 ** might be an alias for the ROWID. But it might also be a WITHOUT ROWID
4418 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4419 ** ROWID aliases. To distinguish these cases, check to see if
4420 ** there is a "pk" entry in "PRAGMA index_list". There will be
4421 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4423 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4424 " WHERE origin='pk'", zTab);
4425 shell_check_oom(zSql);
4426 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4427 sqlite3_free(zSql);
4428 if( rc ){
4429 freeColumnList(azCol);
4430 return 0;
4432 rc = sqlite3_step(pStmt);
4433 sqlite3_finalize(pStmt);
4434 preserveRowid = rc==SQLITE_ROW;
4436 if( preserveRowid ){
4437 /* Only preserve the rowid if we can find a name to use for the
4438 ** rowid */
4439 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4440 int i, j;
4441 for(j=0; j<3; j++){
4442 for(i=1; i<=nCol; i++){
4443 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4445 if( i>nCol ){
4446 /* At this point, we know that azRowid[j] is not the name of any
4447 ** ordinary column in the table. Verify that azRowid[j] is a valid
4448 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4449 ** tables will fail this last check */
4450 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4451 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4452 break;
4456 return azCol;
4460 ** Toggle the reverse_unordered_selects setting.
4462 static void toggleSelectOrder(sqlite3 *db){
4463 sqlite3_stmt *pStmt = 0;
4464 int iSetting = 0;
4465 char zStmt[100];
4466 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4467 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4468 iSetting = sqlite3_column_int(pStmt, 0);
4470 sqlite3_finalize(pStmt);
4471 sqlite3_snprintf(sizeof(zStmt), zStmt,
4472 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4473 sqlite3_exec(db, zStmt, 0, 0, 0);
4477 ** This is a different callback routine used for dumping the database.
4478 ** Each row received by this callback consists of a table name,
4479 ** the table type ("index" or "table") and SQL to create the table.
4480 ** This routine should print text sufficient to recreate the table.
4482 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4483 int rc;
4484 const char *zTable;
4485 const char *zType;
4486 const char *zSql;
4487 ShellState *p = (ShellState *)pArg;
4488 int dataOnly;
4489 int noSys;
4491 UNUSED_PARAMETER(azNotUsed);
4492 if( nArg!=3 || azArg==0 ) return 0;
4493 zTable = azArg[0];
4494 zType = azArg[1];
4495 zSql = azArg[2];
4496 if( zTable==0 ) return 0;
4497 if( zType==0 ) return 0;
4498 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4499 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4501 if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4502 if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
4503 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4504 if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
4505 }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
4506 return 0;
4507 }else if( dataOnly ){
4508 /* no-op */
4509 }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4510 char *zIns;
4511 if( !p->writableSchema ){
4512 oputz("PRAGMA writable_schema=ON;\n");
4513 p->writableSchema = 1;
4515 zIns = sqlite3_mprintf(
4516 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4517 "VALUES('table','%q','%q',0,'%q');",
4518 zTable, zTable, zSql);
4519 shell_check_oom(zIns);
4520 oputf("%s\n", zIns);
4521 sqlite3_free(zIns);
4522 return 0;
4523 }else{
4524 printSchemaLine(zSql, ";\n");
4527 if( cli_strcmp(zType, "table")==0 ){
4528 ShellText sSelect;
4529 ShellText sTable;
4530 char **azCol;
4531 int i;
4532 char *savedDestTable;
4533 int savedMode;
4535 azCol = tableColumnList(p, zTable);
4536 if( azCol==0 ){
4537 p->nErr++;
4538 return 0;
4541 /* Always quote the table name, even if it appears to be pure ascii,
4542 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4543 initText(&sTable);
4544 appendText(&sTable, zTable, quoteChar(zTable));
4545 /* If preserving the rowid, add a column list after the table name.
4546 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4547 ** instead of the usual "INSERT INTO tab VALUES(...)".
4549 if( azCol[0] ){
4550 appendText(&sTable, "(", 0);
4551 appendText(&sTable, azCol[0], 0);
4552 for(i=1; azCol[i]; i++){
4553 appendText(&sTable, ",", 0);
4554 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4556 appendText(&sTable, ")", 0);
4559 /* Build an appropriate SELECT statement */
4560 initText(&sSelect);
4561 appendText(&sSelect, "SELECT ", 0);
4562 if( azCol[0] ){
4563 appendText(&sSelect, azCol[0], 0);
4564 appendText(&sSelect, ",", 0);
4566 for(i=1; azCol[i]; i++){
4567 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4568 if( azCol[i+1] ){
4569 appendText(&sSelect, ",", 0);
4572 freeColumnList(azCol);
4573 appendText(&sSelect, " FROM ", 0);
4574 appendText(&sSelect, zTable, quoteChar(zTable));
4576 savedDestTable = p->zDestTable;
4577 savedMode = p->mode;
4578 p->zDestTable = sTable.z;
4579 p->mode = p->cMode = MODE_Insert;
4580 rc = shell_exec(p, sSelect.z, 0);
4581 if( (rc&0xff)==SQLITE_CORRUPT ){
4582 oputz("/****** CORRUPTION ERROR *******/\n");
4583 toggleSelectOrder(p->db);
4584 shell_exec(p, sSelect.z, 0);
4585 toggleSelectOrder(p->db);
4587 p->zDestTable = savedDestTable;
4588 p->mode = savedMode;
4589 freeText(&sTable);
4590 freeText(&sSelect);
4591 if( rc ) p->nErr++;
4593 return 0;
4597 ** Run zQuery. Use dump_callback() as the callback routine so that
4598 ** the contents of the query are output as SQL statements.
4600 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4601 ** "ORDER BY rowid DESC" to the end.
4603 static int run_schema_dump_query(
4604 ShellState *p,
4605 const char *zQuery
4607 int rc;
4608 char *zErr = 0;
4609 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4610 if( rc==SQLITE_CORRUPT ){
4611 char *zQ2;
4612 int len = strlen30(zQuery);
4613 oputz("/****** CORRUPTION ERROR *******/\n");
4614 if( zErr ){
4615 oputf("/****** %s ******/\n", zErr);
4616 sqlite3_free(zErr);
4617 zErr = 0;
4619 zQ2 = malloc( len+100 );
4620 if( zQ2==0 ) return rc;
4621 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4622 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4623 if( rc ){
4624 oputf("/****** ERROR: %s ******/\n", zErr);
4625 }else{
4626 rc = SQLITE_CORRUPT;
4628 sqlite3_free(zErr);
4629 free(zQ2);
4631 return rc;
4635 ** Text of help messages.
4637 ** The help text for each individual command begins with a line that starts
4638 ** with ".". Subsequent lines are supplemental information.
4640 ** There must be two or more spaces between the end of the command and the
4641 ** start of the description of what that command does.
4643 static const char *(azHelp[]) = {
4644 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4645 && !defined(SQLITE_SHELL_FIDDLE)
4646 ".archive ... Manage SQL archives",
4647 " Each command must have exactly one of the following options:",
4648 " -c, --create Create a new archive",
4649 " -u, --update Add or update files with changed mtime",
4650 " -i, --insert Like -u but always add even if unchanged",
4651 " -r, --remove Remove files from archive",
4652 " -t, --list List contents of archive",
4653 " -x, --extract Extract files from archive",
4654 " Optional arguments:",
4655 " -v, --verbose Print each filename as it is processed",
4656 " -f FILE, --file FILE Use archive FILE (default is current db)",
4657 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4658 " -C DIR, --directory DIR Read/extract files from directory DIR",
4659 " -g, --glob Use glob matching for names in archive",
4660 " -n, --dryrun Show the SQL that would have occurred",
4661 " Examples:",
4662 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4663 " .ar -tf ARCHIVE # List members of ARCHIVE",
4664 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4665 " See also:",
4666 " http://sqlite.org/cli.html#sqlite_archive_support",
4667 #endif
4668 #ifndef SQLITE_OMIT_AUTHORIZATION
4669 ".auth ON|OFF Show authorizer callbacks",
4670 #endif
4671 #ifndef SQLITE_SHELL_FIDDLE
4672 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4673 " Options:",
4674 " --append Use the appendvfs",
4675 " --async Write to FILE without journal and fsync()",
4676 #endif
4677 ".bail on|off Stop after hitting an error. Default OFF",
4678 #ifndef SQLITE_SHELL_FIDDLE
4679 ".cd DIRECTORY Change the working directory to DIRECTORY",
4680 #endif
4681 ".changes on|off Show number of rows changed by SQL",
4682 #ifndef SQLITE_SHELL_FIDDLE
4683 ".check GLOB Fail if output since .testcase does not match",
4684 ".clone NEWDB Clone data into NEWDB from the existing database",
4685 #endif
4686 ".connection [close] [#] Open or close an auxiliary database connection",
4687 #if defined(_WIN32) || defined(WIN32)
4688 ".crnl on|off Translate \\n to \\r\\n. Default ON",
4689 #endif
4690 ".databases List names and files of attached databases",
4691 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4692 #if SQLITE_SHELL_HAVE_RECOVER
4693 ".dbinfo ?DB? Show status information about the database",
4694 #endif
4695 ".dump ?OBJECTS? Render database content as SQL",
4696 " Options:",
4697 " --data-only Output only INSERT statements",
4698 " --newlines Allow unescaped newline characters in output",
4699 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4700 " --preserve-rowids Include ROWID values in the output",
4701 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4702 " Additional LIKE patterns can be given in subsequent arguments",
4703 ".echo on|off Turn command echo on or off",
4704 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4705 " Other Modes:",
4706 #ifdef SQLITE_DEBUG
4707 " test Show raw EXPLAIN QUERY PLAN output",
4708 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4709 #endif
4710 " trigger Like \"full\" but also show trigger bytecode",
4711 #ifndef SQLITE_SHELL_FIDDLE
4712 ".excel Display the output of next command in spreadsheet",
4713 " --bom Put a UTF8 byte-order mark on intermediate file",
4714 #endif
4715 #ifndef SQLITE_SHELL_FIDDLE
4716 ".exit ?CODE? Exit this program with return-code CODE",
4717 #endif
4718 ".expert EXPERIMENTAL. Suggest indexes for queries",
4719 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4720 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4721 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4722 " --help Show CMD details",
4723 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4724 ".headers on|off Turn display of headers on or off",
4725 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4726 #ifndef SQLITE_SHELL_FIDDLE
4727 ".import FILE TABLE Import data from FILE into TABLE",
4728 " Options:",
4729 " --ascii Use \\037 and \\036 as column and row separators",
4730 " --csv Use , and \\n as column and row separators",
4731 " --skip N Skip the first N rows of input",
4732 " --schema S Target table to be S.TABLE",
4733 " -v \"Verbose\" - increase auxiliary output",
4734 " Notes:",
4735 " * If TABLE does not exist, it is created. The first row of input",
4736 " determines the column names.",
4737 " * If neither --csv or --ascii are used, the input mode is derived",
4738 " from the \".mode\" output mode",
4739 " * If FILE begins with \"|\" then it is a command that generates the",
4740 " input text.",
4741 #endif
4742 #ifndef SQLITE_OMIT_TEST_CONTROL
4743 ",imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4744 #endif
4745 ".indexes ?TABLE? Show names of indexes",
4746 " If TABLE is specified, only show indexes for",
4747 " tables matching TABLE using the LIKE operator.",
4748 #ifdef SQLITE_ENABLE_IOTRACE
4749 ",iotrace FILE Enable I/O diagnostic logging to FILE",
4750 #endif
4751 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4752 ".lint OPTIONS Report potential schema issues.",
4753 " Options:",
4754 " fkey-indexes Find missing foreign key indexes",
4755 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4756 ".load FILE ?ENTRY? Load an extension library",
4757 #endif
4758 #if !defined(SQLITE_SHELL_FIDDLE)
4759 ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout",
4760 #else
4761 ".log on|off Turn logging on or off.",
4762 #endif
4763 ".mode MODE ?OPTIONS? Set output mode",
4764 " MODE is one of:",
4765 " ascii Columns/rows delimited by 0x1F and 0x1E",
4766 " box Tables using unicode box-drawing characters",
4767 " csv Comma-separated values",
4768 " column Output in columns. (See .width)",
4769 " html HTML <table> code",
4770 " insert SQL insert statements for TABLE",
4771 " json Results in a JSON array",
4772 " line One value per line",
4773 " list Values delimited by \"|\"",
4774 " markdown Markdown table format",
4775 " qbox Shorthand for \"box --wrap 60 --quote\"",
4776 " quote Escape answers as for SQL",
4777 " table ASCII-art table",
4778 " tabs Tab-separated values",
4779 " tcl TCL list elements",
4780 " OPTIONS: (for columnar modes or insert mode):",
4781 " --wrap N Wrap output lines to no longer than N characters",
4782 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4783 " --ww Shorthand for \"--wordwrap 1\"",
4784 " --quote Quote output text as SQL literals",
4785 " --noquote Do not quote output text",
4786 " TABLE The name of SQL table used for \"insert\" mode",
4787 #ifndef SQLITE_SHELL_FIDDLE
4788 ".nonce STRING Suspend safe mode for one command if nonce matches",
4789 #endif
4790 ".nullvalue STRING Use STRING in place of NULL values",
4791 #ifndef SQLITE_SHELL_FIDDLE
4792 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4793 " If FILE begins with '|' then open as a pipe",
4794 " --bom Put a UTF8 byte-order mark at the beginning",
4795 " -e Send output to the system text editor",
4796 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4797 /* Note that .open is (partially) available in WASM builds but is
4798 ** currently only intended to be used by the fiddle tool, not
4799 ** end users, so is "undocumented." */
4800 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4801 " Options:",
4802 " --append Use appendvfs to append database to the end of FILE",
4803 #endif
4804 #ifndef SQLITE_OMIT_DESERIALIZE
4805 " --deserialize Load into memory using sqlite3_deserialize()",
4806 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4807 " --maxsize N Maximum size for --hexdb or --deserialized database",
4808 #endif
4809 " --new Initialize FILE to an empty database",
4810 " --nofollow Do not follow symbolic links",
4811 " --readonly Open FILE readonly",
4812 " --zip FILE is a ZIP archive",
4813 #ifndef SQLITE_SHELL_FIDDLE
4814 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4815 " If FILE begins with '|' then open it as a pipe.",
4816 " Options:",
4817 " --bom Prefix output with a UTF8 byte-order mark",
4818 " -e Send output to the system text editor",
4819 " -x Send output as CSV to a spreadsheet",
4820 #endif
4821 ".parameter CMD ... Manage SQL parameter bindings",
4822 " clear Erase all bindings",
4823 " init Initialize the TEMP table that holds bindings",
4824 " list List the current parameter bindings",
4825 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4826 " PARAMETER should start with one of: $ : @ ?",
4827 " unset PARAMETER Remove PARAMETER from the binding table",
4828 ".print STRING... Print literal STRING",
4829 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4830 ".progress N Invoke progress handler after every N opcodes",
4831 " --limit N Interrupt after N progress callbacks",
4832 " --once Do no more than one progress interrupt",
4833 " --quiet|-q No output except at interrupts",
4834 " --reset Reset the count for each input and interrupt",
4835 #endif
4836 ".prompt MAIN CONTINUE Replace the standard prompts",
4837 #ifndef SQLITE_SHELL_FIDDLE
4838 ".quit Stop interpreting input stream, exit if primary.",
4839 ".read FILE Read input from FILE or command output",
4840 " If FILE begins with \"|\", it is a command that generates the input.",
4841 #endif
4842 #if SQLITE_SHELL_HAVE_RECOVER
4843 ".recover Recover as much data as possible from corrupt db.",
4844 " --ignore-freelist Ignore pages that appear to be on db freelist",
4845 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4846 " --no-rowids Do not attempt to recover rowid values",
4847 " that are not also INTEGER PRIMARY KEYs",
4848 #endif
4849 #ifndef SQLITE_SHELL_FIDDLE
4850 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4851 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4852 #endif
4853 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4854 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4855 " Options:",
4856 " --indent Try to pretty-print the schema",
4857 " --nosys Omit objects whose names start with \"sqlite_\"",
4858 ",selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4859 " Options:",
4860 " --init Create a new SELFTEST table",
4861 " -v Verbose output",
4862 ".separator COL ?ROW? Change the column and row separators",
4863 #if defined(SQLITE_ENABLE_SESSION)
4864 ".session ?NAME? CMD ... Create or control sessions",
4865 " Subcommands:",
4866 " attach TABLE Attach TABLE",
4867 " changeset FILE Write a changeset into FILE",
4868 " close Close one session",
4869 " enable ?BOOLEAN? Set or query the enable bit",
4870 " filter GLOB... Reject tables matching GLOBs",
4871 " indirect ?BOOLEAN? Mark or query the indirect status",
4872 " isempty Query whether the session is empty",
4873 " list List currently open session names",
4874 " open DB NAME Open a new session on DB",
4875 " patchset FILE Write a patchset into FILE",
4876 " If ?NAME? is omitted, the first defined session is used.",
4877 #endif
4878 ".sha3sum ... Compute a SHA3 hash of database content",
4879 " Options:",
4880 " --schema Also hash the sqlite_schema table",
4881 " --sha3-224 Use the sha3-224 algorithm",
4882 " --sha3-256 Use the sha3-256 algorithm (default)",
4883 " --sha3-384 Use the sha3-384 algorithm",
4884 " --sha3-512 Use the sha3-512 algorithm",
4885 " Any other argument is a LIKE pattern for tables to hash",
4886 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4887 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4888 #endif
4889 ".show Show the current values for various settings",
4890 ".stats ?ARG? Show stats or turn stats on or off",
4891 " off Turn off automatic stat display",
4892 " on Turn on automatic stat display",
4893 " stmt Show statement stats",
4894 " vmstep Show the virtual machine step count only",
4895 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4896 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4897 #endif
4898 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4899 #ifndef SQLITE_SHELL_FIDDLE
4900 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
4901 #endif
4902 ",testctrl CMD ... Run various sqlite3_test_control() operations",
4903 " Run \".testctrl\" with no arguments for details",
4904 ".timeout MS Try opening locked tables for MS milliseconds",
4905 ".timer on|off Turn SQL timer on or off",
4906 #ifndef SQLITE_OMIT_TRACE
4907 ".trace ?OPTIONS? Output each SQL statement as it is run",
4908 " FILE Send output to FILE",
4909 " stdout Send output to stdout",
4910 " stderr Send output to stderr",
4911 " off Disable tracing",
4912 " --expanded Expand query parameters",
4913 #ifdef SQLITE_ENABLE_NORMALIZE
4914 " --normalized Normal the SQL statements",
4915 #endif
4916 " --plain Show SQL as it is input",
4917 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4918 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4919 " --row Trace each row (SQLITE_TRACE_ROW)",
4920 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4921 #endif /* SQLITE_OMIT_TRACE */
4922 #ifdef SQLITE_DEBUG
4923 ".unmodule NAME ... Unregister virtual table modules",
4924 " --allexcept Unregister everything except those named",
4925 #endif
4926 ".version Show source, library and compiler versions",
4927 ".vfsinfo ?AUX? Information about the top-level VFS",
4928 ".vfslist List all available VFSes",
4929 ".vfsname ?AUX? Print the name of the VFS stack",
4930 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4931 " Negative values right-justify",
4935 ** Output help text.
4937 ** zPattern describes the set of commands for which help text is provided.
4938 ** If zPattern is NULL, then show all commands, but only give a one-line
4939 ** description of each.
4941 ** Return the number of matches.
4943 static int showHelp(FILE *out, const char *zPattern){
4944 int i = 0;
4945 int j = 0;
4946 int n = 0;
4947 char *zPat;
4948 if( zPattern==0
4949 || zPattern[0]=='0'
4950 || cli_strcmp(zPattern,"-a")==0
4951 || cli_strcmp(zPattern,"-all")==0
4952 || cli_strcmp(zPattern,"--all")==0
4954 enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
4955 enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
4956 /* Show all or most commands
4957 ** *zPattern==0 => summary of documented commands only
4958 ** *zPattern=='0' => whole help for undocumented commands
4959 ** Otherwise => whole help for documented commands
4961 enum HelpWanted hw = HW_SummaryOnly;
4962 enum HelpHave hh = HH_More;
4963 if( zPattern!=0 ){
4964 hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
4966 for(i=0; i<ArraySize(azHelp); i++){
4967 switch( azHelp[i][0] ){
4968 case ',':
4969 hh = HH_Summary|HH_Undoc;
4970 break;
4971 case '.':
4972 hh = HH_Summary;
4973 break;
4974 default:
4975 hh &= ~HH_Summary;
4976 break;
4978 if( ((hw^hh)&HH_Undoc)==0 ){
4979 if( (hh&HH_Summary)!=0 ){
4980 sputf(out, ".%s\n", azHelp[i]+1);
4981 ++n;
4982 }else if( (hw&HW_SummaryOnly)==0 ){
4983 sputf(out, "%s\n", azHelp[i]);
4987 }else{
4988 /* Seek documented commands for which zPattern is an exact prefix */
4989 zPat = sqlite3_mprintf(".%s*", zPattern);
4990 shell_check_oom(zPat);
4991 for(i=0; i<ArraySize(azHelp); i++){
4992 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4993 sputf(out, "%s\n", azHelp[i]);
4994 j = i+1;
4995 n++;
4998 sqlite3_free(zPat);
4999 if( n ){
5000 if( n==1 ){
5001 /* when zPattern is a prefix of exactly one command, then include
5002 ** the details of that command, which should begin at offset j */
5003 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
5004 sputf(out, "%s\n", azHelp[j]);
5005 j++;
5008 return n;
5010 /* Look for documented commands that contain zPattern anywhere.
5011 ** Show complete text of all documented commands that match. */
5012 zPat = sqlite3_mprintf("%%%s%%", zPattern);
5013 shell_check_oom(zPat);
5014 for(i=0; i<ArraySize(azHelp); i++){
5015 if( azHelp[i][0]==',' ){
5016 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
5017 continue;
5019 if( azHelp[i][0]=='.' ) j = i;
5020 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
5021 sputf(out, "%s\n", azHelp[j]);
5022 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
5023 j++;
5024 sputf(out, "%s\n", azHelp[j]);
5026 i = j;
5027 n++;
5030 sqlite3_free(zPat);
5032 return n;
5035 /* Forward reference */
5036 static int process_input(ShellState *p);
5039 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
5040 ** and return a pointer to the buffer. The caller is responsible for freeing
5041 ** the memory.
5043 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
5044 ** read.
5046 ** For convenience, a nul-terminator byte is always appended to the data read
5047 ** from the file before the buffer is returned. This byte is not included in
5048 ** the final value of (*pnByte), if applicable.
5050 ** NULL is returned if any error is encountered. The final value of *pnByte
5051 ** is undefined in this case.
5053 static char *readFile(const char *zName, int *pnByte){
5054 FILE *in = fopen(zName, "rb");
5055 long nIn;
5056 size_t nRead;
5057 char *pBuf;
5058 int rc;
5059 if( in==0 ) return 0;
5060 rc = fseek(in, 0, SEEK_END);
5061 if( rc!=0 ){
5062 eputf("Error: '%s' not seekable\n", zName);
5063 fclose(in);
5064 return 0;
5066 nIn = ftell(in);
5067 rewind(in);
5068 pBuf = sqlite3_malloc64( nIn+1 );
5069 if( pBuf==0 ){
5070 eputz("Error: out of memory\n");
5071 fclose(in);
5072 return 0;
5074 nRead = fread(pBuf, nIn, 1, in);
5075 fclose(in);
5076 if( nRead!=1 ){
5077 sqlite3_free(pBuf);
5078 eputf("Error: cannot read '%s'\n", zName);
5079 return 0;
5081 pBuf[nIn] = 0;
5082 if( pnByte ) *pnByte = nIn;
5083 return pBuf;
5086 #if defined(SQLITE_ENABLE_SESSION)
5088 ** Close a single OpenSession object and release all of its associated
5089 ** resources.
5091 static void session_close(OpenSession *pSession){
5092 int i;
5093 sqlite3session_delete(pSession->p);
5094 sqlite3_free(pSession->zName);
5095 for(i=0; i<pSession->nFilter; i++){
5096 sqlite3_free(pSession->azFilter[i]);
5098 sqlite3_free(pSession->azFilter);
5099 memset(pSession, 0, sizeof(OpenSession));
5101 #endif
5104 ** Close all OpenSession objects and release all associated resources.
5106 #if defined(SQLITE_ENABLE_SESSION)
5107 static void session_close_all(ShellState *p, int i){
5108 int j;
5109 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
5110 for(j=0; j<pAuxDb->nSession; j++){
5111 session_close(&pAuxDb->aSession[j]);
5113 pAuxDb->nSession = 0;
5115 #else
5116 # define session_close_all(X,Y)
5117 #endif
5120 ** Implementation of the xFilter function for an open session. Omit
5121 ** any tables named by ".session filter" but let all other table through.
5123 #if defined(SQLITE_ENABLE_SESSION)
5124 static int session_filter(void *pCtx, const char *zTab){
5125 OpenSession *pSession = (OpenSession*)pCtx;
5126 int i;
5127 for(i=0; i<pSession->nFilter; i++){
5128 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
5130 return 1;
5132 #endif
5135 ** Try to deduce the type of file for zName based on its content. Return
5136 ** one of the SHELL_OPEN_* constants.
5138 ** If the file does not exist or is empty but its name looks like a ZIP
5139 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
5140 ** Otherwise, assume an ordinary database regardless of the filename if
5141 ** the type cannot be determined from content.
5143 int deduceDatabaseType(const char *zName, int dfltZip){
5144 FILE *f = fopen(zName, "rb");
5145 size_t n;
5146 int rc = SHELL_OPEN_UNSPEC;
5147 char zBuf[100];
5148 if( f==0 ){
5149 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5150 return SHELL_OPEN_ZIPFILE;
5151 }else{
5152 return SHELL_OPEN_NORMAL;
5155 n = fread(zBuf, 16, 1, f);
5156 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
5157 fclose(f);
5158 return SHELL_OPEN_NORMAL;
5160 fseek(f, -25, SEEK_END);
5161 n = fread(zBuf, 25, 1, f);
5162 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
5163 rc = SHELL_OPEN_APPENDVFS;
5164 }else{
5165 fseek(f, -22, SEEK_END);
5166 n = fread(zBuf, 22, 1, f);
5167 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
5168 && zBuf[3]==0x06 ){
5169 rc = SHELL_OPEN_ZIPFILE;
5170 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5171 rc = SHELL_OPEN_ZIPFILE;
5174 fclose(f);
5175 return rc;
5178 #ifndef SQLITE_OMIT_DESERIALIZE
5180 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5181 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5182 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5184 static unsigned char *readHexDb(ShellState *p, int *pnData){
5185 unsigned char *a = 0;
5186 int nLine;
5187 int n = 0;
5188 int pgsz = 0;
5189 int iOffset = 0;
5190 int j, k;
5191 int rc;
5192 FILE *in;
5193 const char *zDbFilename = p->pAuxDb->zDbFilename;
5194 unsigned int x[16];
5195 char zLine[1000];
5196 if( zDbFilename ){
5197 in = fopen(zDbFilename, "r");
5198 if( in==0 ){
5199 eputf("cannot open \"%s\" for reading\n", zDbFilename);
5200 return 0;
5202 nLine = 0;
5203 }else{
5204 in = p->in;
5205 nLine = p->lineno;
5206 if( in==0 ) in = stdin;
5208 *pnData = 0;
5209 nLine++;
5210 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
5211 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
5212 if( rc!=2 ) goto readHexDb_error;
5213 if( n<0 ) goto readHexDb_error;
5214 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
5215 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
5216 a = sqlite3_malloc( n ? n : 1 );
5217 shell_check_oom(a);
5218 memset(a, 0, n);
5219 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
5220 eputz("invalid pagesize\n");
5221 goto readHexDb_error;
5223 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
5224 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
5225 if( rc==2 ){
5226 iOffset = k;
5227 continue;
5229 if( cli_strncmp(zLine, "| end ", 6)==0 ){
5230 break;
5232 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5233 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
5234 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
5235 if( rc==17 ){
5236 k = iOffset+j;
5237 if( k+16<=n && k>=0 ){
5238 int ii;
5239 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
5243 *pnData = n;
5244 if( in!=p->in ){
5245 fclose(in);
5246 }else{
5247 p->lineno = nLine;
5249 return a;
5251 readHexDb_error:
5252 if( in!=p->in ){
5253 fclose(in);
5254 }else{
5255 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
5256 nLine++;
5257 if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
5259 p->lineno = nLine;
5261 sqlite3_free(a);
5262 eputf("Error on line %d of --hexdb input\n", nLine);
5263 return 0;
5265 #endif /* SQLITE_OMIT_DESERIALIZE */
5268 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5270 static void shellUSleepFunc(
5271 sqlite3_context *context,
5272 int argcUnused,
5273 sqlite3_value **argv
5275 int sleep = sqlite3_value_int(argv[0]);
5276 (void)argcUnused;
5277 sqlite3_sleep(sleep/1000);
5278 sqlite3_result_int(context, sleep);
5281 /* Flags for open_db().
5283 ** The default behavior of open_db() is to exit(1) if the database fails to
5284 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5285 ** but still returns without calling exit.
5287 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5288 ** ZIP archive if the file does not exist or is empty and its name matches
5289 ** the *.zip pattern.
5291 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5292 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5295 ** Make sure the database is open. If it is not, then open it. If
5296 ** the database fails to open, print an error message and exit.
5298 static void open_db(ShellState *p, int openFlags){
5299 if( p->db==0 ){
5300 const char *zDbFilename = p->pAuxDb->zDbFilename;
5301 if( p->openMode==SHELL_OPEN_UNSPEC ){
5302 if( zDbFilename==0 || zDbFilename[0]==0 ){
5303 p->openMode = SHELL_OPEN_NORMAL;
5304 }else{
5305 p->openMode = (u8)deduceDatabaseType(zDbFilename,
5306 (openFlags & OPEN_DB_ZIPFILE)!=0);
5309 switch( p->openMode ){
5310 case SHELL_OPEN_APPENDVFS: {
5311 sqlite3_open_v2(zDbFilename, &p->db,
5312 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5313 break;
5315 case SHELL_OPEN_HEXDB:
5316 case SHELL_OPEN_DESERIALIZE: {
5317 sqlite3_open(0, &p->db);
5318 break;
5320 case SHELL_OPEN_ZIPFILE: {
5321 sqlite3_open(":memory:", &p->db);
5322 break;
5324 case SHELL_OPEN_READONLY: {
5325 sqlite3_open_v2(zDbFilename, &p->db,
5326 SQLITE_OPEN_READONLY|p->openFlags, 0);
5327 break;
5329 case SHELL_OPEN_UNSPEC:
5330 case SHELL_OPEN_NORMAL: {
5331 sqlite3_open_v2(zDbFilename, &p->db,
5332 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5333 break;
5336 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5337 eputf("Error: unable to open database \"%s\": %s\n",
5338 zDbFilename, sqlite3_errmsg(p->db));
5339 if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
5340 exit(1);
5342 sqlite3_close(p->db);
5343 sqlite3_open(":memory:", &p->db);
5344 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5345 eputz("Also: unable to open substitute in-memory database.\n");
5346 exit(1);
5347 }else{
5348 eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
5349 zDbFilename);
5352 globalDb = p->db;
5353 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
5355 /* Reflect the use or absence of --unsafe-testing invocation. */
5357 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
5358 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
5359 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
5362 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5363 sqlite3_enable_load_extension(p->db, 1);
5364 #endif
5365 sqlite3_shathree_init(p->db, 0, 0);
5366 sqlite3_uint_init(p->db, 0, 0);
5367 sqlite3_decimal_init(p->db, 0, 0);
5368 sqlite3_base64_init(p->db, 0, 0);
5369 sqlite3_base85_init(p->db, 0, 0);
5370 sqlite3_regexp_init(p->db, 0, 0);
5371 sqlite3_ieee_init(p->db, 0, 0);
5372 sqlite3_series_init(p->db, 0, 0);
5373 #ifndef SQLITE_SHELL_FIDDLE
5374 sqlite3_fileio_init(p->db, 0, 0);
5375 sqlite3_completion_init(p->db, 0, 0);
5376 #endif
5377 #ifdef SQLITE_HAVE_ZLIB
5378 if( !p->bSafeModePersist ){
5379 sqlite3_zipfile_init(p->db, 0, 0);
5380 sqlite3_sqlar_init(p->db, 0, 0);
5382 #endif
5383 #ifdef SQLITE_SHELL_EXTFUNCS
5384 /* Create a preprocessing mechanism for extensions to make
5385 * their own provisions for being built into the shell.
5386 * This is a short-span macro. See further below for usage.
5388 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5389 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5390 /* Let custom-included extensions get their ..._init() called.
5391 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5392 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5393 * initialization routine to be called.
5396 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
5397 /* Let custom-included extensions expose their functionality.
5398 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5399 * the SQL functions, virtual tables, collating sequences or
5400 * VFS's implemented by the extension to be registered.
5402 if( irc==SQLITE_OK
5403 || irc==SQLITE_OK_LOAD_PERMANENTLY ){
5404 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
5406 #undef SHELL_SUB_MACRO
5407 #undef SHELL_SUBMACRO
5409 #endif
5411 sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
5412 shellStrtod, 0, 0);
5413 sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
5414 shellDtostr, 0, 0);
5415 sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
5416 shellDtostr, 0, 0);
5417 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5418 shellAddSchemaName, 0, 0);
5419 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5420 shellModuleSchema, 0, 0);
5421 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5422 shellPutsFunc, 0, 0);
5423 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5424 shellUSleepFunc, 0, 0);
5425 #ifndef SQLITE_NOHAVE_SYSTEM
5426 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5427 editFunc, 0, 0);
5428 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5429 editFunc, 0, 0);
5430 #endif
5432 if( p->openMode==SHELL_OPEN_ZIPFILE ){
5433 char *zSql = sqlite3_mprintf(
5434 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5435 shell_check_oom(zSql);
5436 sqlite3_exec(p->db, zSql, 0, 0, 0);
5437 sqlite3_free(zSql);
5439 #ifndef SQLITE_OMIT_DESERIALIZE
5440 else
5441 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5442 int rc;
5443 int nData = 0;
5444 unsigned char *aData;
5445 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5446 aData = (unsigned char*)readFile(zDbFilename, &nData);
5447 }else{
5448 aData = readHexDb(p, &nData);
5450 if( aData==0 ){
5451 return;
5453 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5454 SQLITE_DESERIALIZE_RESIZEABLE |
5455 SQLITE_DESERIALIZE_FREEONCLOSE);
5456 if( rc ){
5457 eputf("Error: sqlite3_deserialize() returns %d\n", rc);
5459 if( p->szMax>0 ){
5460 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5463 #endif
5465 if( p->db!=0 ){
5466 if( p->bSafeModePersist ){
5467 sqlite3_set_authorizer(p->db, safeModeAuth, p);
5469 sqlite3_db_config(
5470 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
5476 ** Attempt to close the database connection. Report errors.
5478 void close_db(sqlite3 *db){
5479 int rc = sqlite3_close(db);
5480 if( rc ){
5481 eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
5485 #if HAVE_READLINE || HAVE_EDITLINE
5487 ** Readline completion callbacks
5489 static char *readline_completion_generator(const char *text, int state){
5490 static sqlite3_stmt *pStmt = 0;
5491 char *zRet;
5492 if( state==0 ){
5493 char *zSql;
5494 sqlite3_finalize(pStmt);
5495 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5496 " FROM completion(%Q) ORDER BY 1", text);
5497 shell_check_oom(zSql);
5498 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5499 sqlite3_free(zSql);
5501 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5502 const char *z = (const char*)sqlite3_column_text(pStmt,0);
5503 zRet = z ? strdup(z) : 0;
5504 }else{
5505 sqlite3_finalize(pStmt);
5506 pStmt = 0;
5507 zRet = 0;
5509 return zRet;
5511 static char **readline_completion(const char *zText, int iStart, int iEnd){
5512 (void)iStart;
5513 (void)iEnd;
5514 rl_attempted_completion_over = 1;
5515 return rl_completion_matches(zText, readline_completion_generator);
5518 #elif HAVE_LINENOISE
5520 ** Linenoise completion callback
5522 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5523 i64 nLine = strlen(zLine);
5524 i64 i, iStart;
5525 sqlite3_stmt *pStmt = 0;
5526 char *zSql;
5527 char zBuf[1000];
5529 if( nLine>(i64)sizeof(zBuf)-30 ) return;
5530 if( zLine[0]=='.' || zLine[0]=='#') return;
5531 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5532 if( i==nLine-1 ) return;
5533 iStart = i+1;
5534 memcpy(zBuf, zLine, iStart);
5535 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5536 " FROM completion(%Q,%Q) ORDER BY 1",
5537 &zLine[iStart], zLine);
5538 shell_check_oom(zSql);
5539 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5540 sqlite3_free(zSql);
5541 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5542 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5543 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5544 int nCompletion = sqlite3_column_bytes(pStmt, 0);
5545 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
5546 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5547 linenoiseAddCompletion(lc, zBuf);
5550 sqlite3_finalize(pStmt);
5552 #endif
5555 ** Do C-language style dequoting.
5557 ** \a -> alarm
5558 ** \b -> backspace
5559 ** \t -> tab
5560 ** \n -> newline
5561 ** \v -> vertical tab
5562 ** \f -> form feed
5563 ** \r -> carriage return
5564 ** \s -> space
5565 ** \" -> "
5566 ** \' -> '
5567 ** \\ -> backslash
5568 ** \NNN -> ascii character NNN in octal
5569 ** \xHH -> ascii character HH in hexadecimal
5571 static void resolve_backslashes(char *z){
5572 int i, j;
5573 char c;
5574 while( *z && *z!='\\' ) z++;
5575 for(i=j=0; (c = z[i])!=0; i++, j++){
5576 if( c=='\\' && z[i+1]!=0 ){
5577 c = z[++i];
5578 if( c=='a' ){
5579 c = '\a';
5580 }else if( c=='b' ){
5581 c = '\b';
5582 }else if( c=='t' ){
5583 c = '\t';
5584 }else if( c=='n' ){
5585 c = '\n';
5586 }else if( c=='v' ){
5587 c = '\v';
5588 }else if( c=='f' ){
5589 c = '\f';
5590 }else if( c=='r' ){
5591 c = '\r';
5592 }else if( c=='"' ){
5593 c = '"';
5594 }else if( c=='\'' ){
5595 c = '\'';
5596 }else if( c=='\\' ){
5597 c = '\\';
5598 }else if( c=='x' ){
5599 int nhd = 0, hdv;
5600 u8 hv = 0;
5601 while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
5602 hv = (u8)((hv<<4)|hdv);
5603 ++nhd;
5605 i += nhd;
5606 c = (u8)hv;
5607 }else if( c>='0' && c<='7' ){
5608 c -= '0';
5609 if( z[i+1]>='0' && z[i+1]<='7' ){
5610 i++;
5611 c = (c<<3) + z[i] - '0';
5612 if( z[i+1]>='0' && z[i+1]<='7' ){
5613 i++;
5614 c = (c<<3) + z[i] - '0';
5619 z[j] = c;
5621 if( j<i ) z[j] = 0;
5625 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5626 ** for TRUE and FALSE. Return the integer value if appropriate.
5628 static int booleanValue(const char *zArg){
5629 int i;
5630 if( zArg[0]=='0' && zArg[1]=='x' ){
5631 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5632 }else{
5633 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5635 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5636 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5637 return 1;
5639 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5640 return 0;
5642 eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
5643 return 0;
5647 ** Set or clear a shell flag according to a boolean value.
5649 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5650 if( booleanValue(zArg) ){
5651 ShellSetFlag(p, mFlag);
5652 }else{
5653 ShellClearFlag(p, mFlag);
5658 ** Close an output file, assuming it is not stderr or stdout
5660 static void output_file_close(FILE *f){
5661 if( f && f!=stdout && f!=stderr ) fclose(f);
5665 ** Try to open an output file. The names "stdout" and "stderr" are
5666 ** recognized and do the right thing. NULL is returned if the output
5667 ** filename is "off".
5669 static FILE *output_file_open(const char *zFile, int bTextMode){
5670 FILE *f;
5671 if( cli_strcmp(zFile,"stdout")==0 ){
5672 f = stdout;
5673 }else if( cli_strcmp(zFile, "stderr")==0 ){
5674 f = stderr;
5675 }else if( cli_strcmp(zFile, "off")==0 ){
5676 f = 0;
5677 }else{
5678 f = fopen(zFile, bTextMode ? "w" : "wb");
5679 if( f==0 ){
5680 eputf("Error: cannot open \"%s\"\n", zFile);
5683 return f;
5686 #ifndef SQLITE_OMIT_TRACE
5688 ** A routine for handling output from sqlite3_trace().
5690 static int sql_trace_callback(
5691 unsigned mType, /* The trace type */
5692 void *pArg, /* The ShellState pointer */
5693 void *pP, /* Usually a pointer to sqlite_stmt */
5694 void *pX /* Auxiliary output */
5696 ShellState *p = (ShellState*)pArg;
5697 sqlite3_stmt *pStmt;
5698 const char *zSql;
5699 i64 nSql;
5700 if( p->traceOut==0 ) return 0;
5701 if( mType==SQLITE_TRACE_CLOSE ){
5702 sputz(p->traceOut, "-- closing database connection\n");
5703 return 0;
5705 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
5706 zSql = (const char*)pX;
5707 }else{
5708 pStmt = (sqlite3_stmt*)pP;
5709 switch( p->eTraceType ){
5710 case SHELL_TRACE_EXPANDED: {
5711 zSql = sqlite3_expanded_sql(pStmt);
5712 break;
5714 #ifdef SQLITE_ENABLE_NORMALIZE
5715 case SHELL_TRACE_NORMALIZED: {
5716 zSql = sqlite3_normalized_sql(pStmt);
5717 break;
5719 #endif
5720 default: {
5721 zSql = sqlite3_sql(pStmt);
5722 break;
5726 if( zSql==0 ) return 0;
5727 nSql = strlen(zSql);
5728 if( nSql>1000000000 ) nSql = 1000000000;
5729 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5730 switch( mType ){
5731 case SQLITE_TRACE_ROW:
5732 case SQLITE_TRACE_STMT: {
5733 sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5734 break;
5736 case SQLITE_TRACE_PROFILE: {
5737 sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
5738 sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5739 break;
5742 return 0;
5744 #endif
5747 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5748 ** a useful spot to set a debugger breakpoint.
5750 ** This routine does not do anything practical. The code are there simply
5751 ** to prevent the compiler from optimizing this routine out.
5753 static void test_breakpoint(void){
5754 static unsigned int nCall = 0;
5755 if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
5759 ** An object used to read a CSV and other files for import.
5761 typedef struct ImportCtx ImportCtx;
5762 struct ImportCtx {
5763 const char *zFile; /* Name of the input file */
5764 FILE *in; /* Read the CSV text from this input stream */
5765 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
5766 char *z; /* Accumulated text for a field */
5767 int n; /* Number of bytes in z */
5768 int nAlloc; /* Space allocated for z[] */
5769 int nLine; /* Current line number */
5770 int nRow; /* Number of rows imported */
5771 int nErr; /* Number of errors encountered */
5772 int bNotFirst; /* True if one or more bytes already read */
5773 int cTerm; /* Character that terminated the most recent field */
5774 int cColSep; /* The column separator character. (Usually ",") */
5775 int cRowSep; /* The row separator character. (Usually "\n") */
5778 /* Clean up resourced used by an ImportCtx */
5779 static void import_cleanup(ImportCtx *p){
5780 if( p->in!=0 && p->xCloser!=0 ){
5781 p->xCloser(p->in);
5782 p->in = 0;
5784 sqlite3_free(p->z);
5785 p->z = 0;
5788 /* Append a single byte to z[] */
5789 static void import_append_char(ImportCtx *p, int c){
5790 if( p->n+1>=p->nAlloc ){
5791 p->nAlloc += p->nAlloc + 100;
5792 p->z = sqlite3_realloc64(p->z, p->nAlloc);
5793 shell_check_oom(p->z);
5795 p->z[p->n++] = (char)c;
5798 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5799 ** with the option of having a separator other than ",".
5801 ** + Input comes from p->in.
5802 ** + Store results in p->z of length p->n. Space to hold p->z comes
5803 ** from sqlite3_malloc64().
5804 ** + Use p->cSep as the column separator. The default is ",".
5805 ** + Use p->rSep as the row separator. The default is "\n".
5806 ** + Keep track of the line number in p->nLine.
5807 ** + Store the character that terminates the field in p->cTerm. Store
5808 ** EOF on end-of-file.
5809 ** + Report syntax errors on stderr
5811 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5812 int c;
5813 int cSep = (u8)p->cColSep;
5814 int rSep = (u8)p->cRowSep;
5815 p->n = 0;
5816 c = fgetc(p->in);
5817 if( c==EOF || seenInterrupt ){
5818 p->cTerm = EOF;
5819 return 0;
5821 if( c=='"' ){
5822 int pc, ppc;
5823 int startLine = p->nLine;
5824 int cQuote = c;
5825 pc = ppc = 0;
5826 while( 1 ){
5827 c = fgetc(p->in);
5828 if( c==rSep ) p->nLine++;
5829 if( c==cQuote ){
5830 if( pc==cQuote ){
5831 pc = 0;
5832 continue;
5835 if( (c==cSep && pc==cQuote)
5836 || (c==rSep && pc==cQuote)
5837 || (c==rSep && pc=='\r' && ppc==cQuote)
5838 || (c==EOF && pc==cQuote)
5840 do{ p->n--; }while( p->z[p->n]!=cQuote );
5841 p->cTerm = c;
5842 break;
5844 if( pc==cQuote && c!='\r' ){
5845 eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
5847 if( c==EOF ){
5848 eputf("%s:%d: unterminated %c-quoted field\n",
5849 p->zFile, startLine, cQuote);
5850 p->cTerm = c;
5851 break;
5853 import_append_char(p, c);
5854 ppc = pc;
5855 pc = c;
5857 }else{
5858 /* If this is the first field being parsed and it begins with the
5859 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5860 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5861 import_append_char(p, c);
5862 c = fgetc(p->in);
5863 if( (c&0xff)==0xbb ){
5864 import_append_char(p, c);
5865 c = fgetc(p->in);
5866 if( (c&0xff)==0xbf ){
5867 p->bNotFirst = 1;
5868 p->n = 0;
5869 return csv_read_one_field(p);
5873 while( c!=EOF && c!=cSep && c!=rSep ){
5874 import_append_char(p, c);
5875 c = fgetc(p->in);
5877 if( c==rSep ){
5878 p->nLine++;
5879 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5881 p->cTerm = c;
5883 if( p->z ) p->z[p->n] = 0;
5884 p->bNotFirst = 1;
5885 return p->z;
5888 /* Read a single field of ASCII delimited text.
5890 ** + Input comes from p->in.
5891 ** + Store results in p->z of length p->n. Space to hold p->z comes
5892 ** from sqlite3_malloc64().
5893 ** + Use p->cSep as the column separator. The default is "\x1F".
5894 ** + Use p->rSep as the row separator. The default is "\x1E".
5895 ** + Keep track of the row number in p->nLine.
5896 ** + Store the character that terminates the field in p->cTerm. Store
5897 ** EOF on end-of-file.
5898 ** + Report syntax errors on stderr
5900 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5901 int c;
5902 int cSep = (u8)p->cColSep;
5903 int rSep = (u8)p->cRowSep;
5904 p->n = 0;
5905 c = fgetc(p->in);
5906 if( c==EOF || seenInterrupt ){
5907 p->cTerm = EOF;
5908 return 0;
5910 while( c!=EOF && c!=cSep && c!=rSep ){
5911 import_append_char(p, c);
5912 c = fgetc(p->in);
5914 if( c==rSep ){
5915 p->nLine++;
5917 p->cTerm = c;
5918 if( p->z ) p->z[p->n] = 0;
5919 return p->z;
5923 ** Try to transfer data for table zTable. If an error is seen while
5924 ** moving forward, try to go backwards. The backwards movement won't
5925 ** work for WITHOUT ROWID tables.
5927 static void tryToCloneData(
5928 ShellState *p,
5929 sqlite3 *newDb,
5930 const char *zTable
5932 sqlite3_stmt *pQuery = 0;
5933 sqlite3_stmt *pInsert = 0;
5934 char *zQuery = 0;
5935 char *zInsert = 0;
5936 int rc;
5937 int i, j, n;
5938 int nTable = strlen30(zTable);
5939 int k = 0;
5940 int cnt = 0;
5941 const int spinRate = 10000;
5943 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5944 shell_check_oom(zQuery);
5945 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5946 if( rc ){
5947 eputf("Error %d: %s on [%s]\n",
5948 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
5949 goto end_data_xfer;
5951 n = sqlite3_column_count(pQuery);
5952 zInsert = sqlite3_malloc64(200 + nTable + n*3);
5953 shell_check_oom(zInsert);
5954 sqlite3_snprintf(200+nTable,zInsert,
5955 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5956 i = strlen30(zInsert);
5957 for(j=1; j<n; j++){
5958 memcpy(zInsert+i, ",?", 2);
5959 i += 2;
5961 memcpy(zInsert+i, ");", 3);
5962 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5963 if( rc ){
5964 eputf("Error %d: %s on [%s]\n",
5965 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
5966 goto end_data_xfer;
5968 for(k=0; k<2; k++){
5969 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5970 for(i=0; i<n; i++){
5971 switch( sqlite3_column_type(pQuery, i) ){
5972 case SQLITE_NULL: {
5973 sqlite3_bind_null(pInsert, i+1);
5974 break;
5976 case SQLITE_INTEGER: {
5977 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5978 break;
5980 case SQLITE_FLOAT: {
5981 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5982 break;
5984 case SQLITE_TEXT: {
5985 sqlite3_bind_text(pInsert, i+1,
5986 (const char*)sqlite3_column_text(pQuery,i),
5987 -1, SQLITE_STATIC);
5988 break;
5990 case SQLITE_BLOB: {
5991 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5992 sqlite3_column_bytes(pQuery,i),
5993 SQLITE_STATIC);
5994 break;
5997 } /* End for */
5998 rc = sqlite3_step(pInsert);
5999 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
6000 eputf("Error %d: %s\n",
6001 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
6003 sqlite3_reset(pInsert);
6004 cnt++;
6005 if( (cnt%spinRate)==0 ){
6006 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
6007 fflush(stdout);
6009 } /* End while */
6010 if( rc==SQLITE_DONE ) break;
6011 sqlite3_finalize(pQuery);
6012 sqlite3_free(zQuery);
6013 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
6014 zTable);
6015 shell_check_oom(zQuery);
6016 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6017 if( rc ){
6018 eputf("Warning: cannot step \"%s\" backwards", zTable);
6019 break;
6021 } /* End for(k=0...) */
6023 end_data_xfer:
6024 sqlite3_finalize(pQuery);
6025 sqlite3_finalize(pInsert);
6026 sqlite3_free(zQuery);
6027 sqlite3_free(zInsert);
6032 ** Try to transfer all rows of the schema that match zWhere. For
6033 ** each row, invoke xForEach() on the object defined by that row.
6034 ** If an error is encountered while moving forward through the
6035 ** sqlite_schema table, try again moving backwards.
6037 static void tryToCloneSchema(
6038 ShellState *p,
6039 sqlite3 *newDb,
6040 const char *zWhere,
6041 void (*xForEach)(ShellState*,sqlite3*,const char*)
6043 sqlite3_stmt *pQuery = 0;
6044 char *zQuery = 0;
6045 int rc;
6046 const unsigned char *zName;
6047 const unsigned char *zSql;
6048 char *zErrMsg = 0;
6050 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6051 " WHERE %s ORDER BY rowid ASC", zWhere);
6052 shell_check_oom(zQuery);
6053 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6054 if( rc ){
6055 eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
6056 sqlite3_errmsg(p->db), zQuery);
6057 goto end_schema_xfer;
6059 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
6060 zName = sqlite3_column_text(pQuery, 0);
6061 zSql = sqlite3_column_text(pQuery, 1);
6062 if( zName==0 || zSql==0 ) continue;
6063 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
6064 sputf(stdout, "%s... ", zName); fflush(stdout);
6065 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6066 if( zErrMsg ){
6067 eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6068 sqlite3_free(zErrMsg);
6069 zErrMsg = 0;
6072 if( xForEach ){
6073 xForEach(p, newDb, (const char*)zName);
6075 sputz(stdout, "done\n");
6077 if( rc!=SQLITE_DONE ){
6078 sqlite3_finalize(pQuery);
6079 sqlite3_free(zQuery);
6080 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6081 " WHERE %s ORDER BY rowid DESC", zWhere);
6082 shell_check_oom(zQuery);
6083 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6084 if( rc ){
6085 eputf("Error: (%d) %s on [%s]\n",
6086 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
6087 goto end_schema_xfer;
6089 while( sqlite3_step(pQuery)==SQLITE_ROW ){
6090 zName = sqlite3_column_text(pQuery, 0);
6091 zSql = sqlite3_column_text(pQuery, 1);
6092 if( zName==0 || zSql==0 ) continue;
6093 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
6094 sputf(stdout, "%s... ", zName); fflush(stdout);
6095 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6096 if( zErrMsg ){
6097 eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6098 sqlite3_free(zErrMsg);
6099 zErrMsg = 0;
6101 if( xForEach ){
6102 xForEach(p, newDb, (const char*)zName);
6104 sputz(stdout, "done\n");
6107 end_schema_xfer:
6108 sqlite3_finalize(pQuery);
6109 sqlite3_free(zQuery);
6113 ** Open a new database file named "zNewDb". Try to recover as much information
6114 ** as possible out of the main database (which might be corrupt) and write it
6115 ** into zNewDb.
6117 static void tryToClone(ShellState *p, const char *zNewDb){
6118 int rc;
6119 sqlite3 *newDb = 0;
6120 if( access(zNewDb,0)==0 ){
6121 eputf("File \"%s\" already exists.\n", zNewDb);
6122 return;
6124 rc = sqlite3_open(zNewDb, &newDb);
6125 if( rc ){
6126 eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
6127 }else{
6128 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
6129 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
6130 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
6131 tryToCloneSchema(p, newDb, "type!='table'", 0);
6132 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
6133 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6135 close_db(newDb);
6138 #ifndef SQLITE_SHELL_FIDDLE
6140 ** Change the output stream (file or pipe or console) to something else.
6142 static void output_redir(ShellState *p, FILE *pfNew){
6143 if( p->out != stdout ) eputz("Output already redirected.\n");
6144 else{
6145 p->out = pfNew;
6146 setOutputStream(pfNew);
6151 ** Change the output file back to stdout.
6153 ** If the p->doXdgOpen flag is set, that means the output was being
6154 ** redirected to a temporary file named by p->zTempFile. In that case,
6155 ** launch start/open/xdg-open on that temporary file.
6157 static void output_reset(ShellState *p){
6158 if( p->outfile[0]=='|' ){
6159 #ifndef SQLITE_OMIT_POPEN
6160 pclose(p->out);
6161 #endif
6162 }else{
6163 output_file_close(p->out);
6164 #ifndef SQLITE_NOHAVE_SYSTEM
6165 if( p->doXdgOpen ){
6166 const char *zXdgOpenCmd =
6167 #if defined(_WIN32)
6168 "start";
6169 #elif defined(__APPLE__)
6170 "open";
6171 #else
6172 "xdg-open";
6173 #endif
6174 char *zCmd;
6175 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
6176 if( system(zCmd) ){
6177 eputf("Failed: [%s]\n", zCmd);
6178 }else{
6179 /* Give the start/open/xdg-open command some time to get
6180 ** going before we continue, and potential delete the
6181 ** p->zTempFile data file out from under it */
6182 sqlite3_sleep(2000);
6184 sqlite3_free(zCmd);
6185 outputModePop(p);
6186 p->doXdgOpen = 0;
6188 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6190 p->outfile[0] = 0;
6191 p->out = stdout;
6192 setOutputStream(stdout);
6194 #else
6195 # define output_redir(SS,pfO)
6196 # define output_reset(SS)
6197 #endif
6200 ** Run an SQL command and return the single integer result.
6202 static int db_int(sqlite3 *db, const char *zSql){
6203 sqlite3_stmt *pStmt;
6204 int res = 0;
6205 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
6206 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
6207 res = sqlite3_column_int(pStmt,0);
6209 sqlite3_finalize(pStmt);
6210 return res;
6213 #if SQLITE_SHELL_HAVE_RECOVER
6215 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6217 static unsigned int get2byteInt(unsigned char *a){
6218 return (a[0]<<8) + a[1];
6220 static unsigned int get4byteInt(unsigned char *a){
6221 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
6225 ** Implementation of the ".dbinfo" command.
6227 ** Return 1 on error, 2 to exit, and 0 otherwise.
6229 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
6230 static const struct { const char *zName; int ofst; } aField[] = {
6231 { "file change counter:", 24 },
6232 { "database page count:", 28 },
6233 { "freelist page count:", 36 },
6234 { "schema cookie:", 40 },
6235 { "schema format:", 44 },
6236 { "default cache size:", 48 },
6237 { "autovacuum top root:", 52 },
6238 { "incremental vacuum:", 64 },
6239 { "text encoding:", 56 },
6240 { "user version:", 60 },
6241 { "application id:", 68 },
6242 { "software version:", 96 },
6244 static const struct { const char *zName; const char *zSql; } aQuery[] = {
6245 { "number of tables:",
6246 "SELECT count(*) FROM %s WHERE type='table'" },
6247 { "number of indexes:",
6248 "SELECT count(*) FROM %s WHERE type='index'" },
6249 { "number of triggers:",
6250 "SELECT count(*) FROM %s WHERE type='trigger'" },
6251 { "number of views:",
6252 "SELECT count(*) FROM %s WHERE type='view'" },
6253 { "schema size:",
6254 "SELECT total(length(sql)) FROM %s" },
6256 int i, rc;
6257 unsigned iDataVersion;
6258 char *zSchemaTab;
6259 char *zDb = nArg>=2 ? azArg[1] : "main";
6260 sqlite3_stmt *pStmt = 0;
6261 unsigned char aHdr[100];
6262 open_db(p, 0);
6263 if( p->db==0 ) return 1;
6264 rc = sqlite3_prepare_v2(p->db,
6265 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6266 -1, &pStmt, 0);
6267 if( rc ){
6268 eputf("error: %s\n", sqlite3_errmsg(p->db));
6269 sqlite3_finalize(pStmt);
6270 return 1;
6272 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
6273 if( sqlite3_step(pStmt)==SQLITE_ROW
6274 && sqlite3_column_bytes(pStmt,0)>100
6276 const u8 *pb = sqlite3_column_blob(pStmt,0);
6277 shell_check_oom(pb);
6278 memcpy(aHdr, pb, 100);
6279 sqlite3_finalize(pStmt);
6280 }else{
6281 eputz("unable to read database header\n");
6282 sqlite3_finalize(pStmt);
6283 return 1;
6285 i = get2byteInt(aHdr+16);
6286 if( i==1 ) i = 65536;
6287 oputf("%-20s %d\n", "database page size:", i);
6288 oputf("%-20s %d\n", "write format:", aHdr[18]);
6289 oputf("%-20s %d\n", "read format:", aHdr[19]);
6290 oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
6291 for(i=0; i<ArraySize(aField); i++){
6292 int ofst = aField[i].ofst;
6293 unsigned int val = get4byteInt(aHdr + ofst);
6294 oputf("%-20s %u", aField[i].zName, val);
6295 switch( ofst ){
6296 case 56: {
6297 if( val==1 ) oputz(" (utf8)");
6298 if( val==2 ) oputz(" (utf16le)");
6299 if( val==3 ) oputz(" (utf16be)");
6302 oputz("\n");
6304 if( zDb==0 ){
6305 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
6306 }else if( cli_strcmp(zDb,"temp")==0 ){
6307 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
6308 }else{
6309 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
6311 for(i=0; i<ArraySize(aQuery); i++){
6312 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
6313 int val = db_int(p->db, zSql);
6314 sqlite3_free(zSql);
6315 oputf("%-20s %d\n", aQuery[i].zName, val);
6317 sqlite3_free(zSchemaTab);
6318 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
6319 oputf("%-20s %u\n", "data version", iDataVersion);
6320 return 0;
6322 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6325 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6327 static int shellDatabaseError(sqlite3 *db){
6328 const char *zErr = sqlite3_errmsg(db);
6329 eputf("Error: %s\n", zErr);
6330 return 1;
6334 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6335 ** if they match and FALSE (0) if they do not match.
6337 ** Globbing rules:
6339 ** '*' Matches any sequence of zero or more characters.
6341 ** '?' Matches exactly one character.
6343 ** [...] Matches one character from the enclosed list of
6344 ** characters.
6346 ** [^...] Matches one character not in the enclosed list.
6348 ** '#' Matches any sequence of one or more digits with an
6349 ** optional + or - sign in front
6351 ** ' ' Any span of whitespace matches any other span of
6352 ** whitespace.
6354 ** Extra whitespace at the end of z[] is ignored.
6356 static int testcase_glob(const char *zGlob, const char *z){
6357 int c, c2;
6358 int invert;
6359 int seen;
6361 while( (c = (*(zGlob++)))!=0 ){
6362 if( IsSpace(c) ){
6363 if( !IsSpace(*z) ) return 0;
6364 while( IsSpace(*zGlob) ) zGlob++;
6365 while( IsSpace(*z) ) z++;
6366 }else if( c=='*' ){
6367 while( (c=(*(zGlob++))) == '*' || c=='?' ){
6368 if( c=='?' && (*(z++))==0 ) return 0;
6370 if( c==0 ){
6371 return 1;
6372 }else if( c=='[' ){
6373 while( *z && testcase_glob(zGlob-1,z)==0 ){
6374 z++;
6376 return (*z)!=0;
6378 while( (c2 = (*(z++)))!=0 ){
6379 while( c2!=c ){
6380 c2 = *(z++);
6381 if( c2==0 ) return 0;
6383 if( testcase_glob(zGlob,z) ) return 1;
6385 return 0;
6386 }else if( c=='?' ){
6387 if( (*(z++))==0 ) return 0;
6388 }else if( c=='[' ){
6389 int prior_c = 0;
6390 seen = 0;
6391 invert = 0;
6392 c = *(z++);
6393 if( c==0 ) return 0;
6394 c2 = *(zGlob++);
6395 if( c2=='^' ){
6396 invert = 1;
6397 c2 = *(zGlob++);
6399 if( c2==']' ){
6400 if( c==']' ) seen = 1;
6401 c2 = *(zGlob++);
6403 while( c2 && c2!=']' ){
6404 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6405 c2 = *(zGlob++);
6406 if( c>=prior_c && c<=c2 ) seen = 1;
6407 prior_c = 0;
6408 }else{
6409 if( c==c2 ){
6410 seen = 1;
6412 prior_c = c2;
6414 c2 = *(zGlob++);
6416 if( c2==0 || (seen ^ invert)==0 ) return 0;
6417 }else if( c=='#' ){
6418 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6419 if( !IsDigit(z[0]) ) return 0;
6420 z++;
6421 while( IsDigit(z[0]) ){ z++; }
6422 }else{
6423 if( c!=(*(z++)) ) return 0;
6426 while( IsSpace(*z) ){ z++; }
6427 return *z==0;
6432 ** Compare the string as a command-line option with either one or two
6433 ** initial "-" characters.
6435 static int optionMatch(const char *zStr, const char *zOpt){
6436 if( zStr[0]!='-' ) return 0;
6437 zStr++;
6438 if( zStr[0]=='-' ) zStr++;
6439 return cli_strcmp(zStr, zOpt)==0;
6443 ** Delete a file.
6445 int shellDeleteFile(const char *zFilename){
6446 int rc;
6447 #ifdef _WIN32
6448 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6449 rc = _wunlink(z);
6450 sqlite3_free(z);
6451 #else
6452 rc = unlink(zFilename);
6453 #endif
6454 return rc;
6458 ** Try to delete the temporary file (if there is one) and free the
6459 ** memory used to hold the name of the temp file.
6461 static void clearTempFile(ShellState *p){
6462 if( p->zTempFile==0 ) return;
6463 if( p->doXdgOpen ) return;
6464 if( shellDeleteFile(p->zTempFile) ) return;
6465 sqlite3_free(p->zTempFile);
6466 p->zTempFile = 0;
6470 ** Create a new temp file name with the given suffix.
6472 static void newTempFile(ShellState *p, const char *zSuffix){
6473 clearTempFile(p);
6474 sqlite3_free(p->zTempFile);
6475 p->zTempFile = 0;
6476 if( p->db ){
6477 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6479 if( p->zTempFile==0 ){
6480 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6481 ** will not work and we will need to fallback to guessing */
6482 char *zTemp;
6483 sqlite3_uint64 r;
6484 sqlite3_randomness(sizeof(r), &r);
6485 zTemp = getenv("TEMP");
6486 if( zTemp==0 ) zTemp = getenv("TMP");
6487 if( zTemp==0 ){
6488 #ifdef _WIN32
6489 zTemp = "\\tmp";
6490 #else
6491 zTemp = "/tmp";
6492 #endif
6494 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6495 }else{
6496 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6498 shell_check_oom(p->zTempFile);
6503 ** The implementation of SQL scalar function fkey_collate_clause(), used
6504 ** by the ".lint fkey-indexes" command. This scalar function is always
6505 ** called with four arguments - the parent table name, the parent column name,
6506 ** the child table name and the child column name.
6508 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6510 ** If either of the named tables or columns do not exist, this function
6511 ** returns an empty string. An empty string is also returned if both tables
6512 ** and columns exist but have the same default collation sequence. Or,
6513 ** if both exist but the default collation sequences are different, this
6514 ** function returns the string " COLLATE <parent-collation>", where
6515 ** <parent-collation> is the default collation sequence of the parent column.
6517 static void shellFkeyCollateClause(
6518 sqlite3_context *pCtx,
6519 int nVal,
6520 sqlite3_value **apVal
6522 sqlite3 *db = sqlite3_context_db_handle(pCtx);
6523 const char *zParent;
6524 const char *zParentCol;
6525 const char *zParentSeq;
6526 const char *zChild;
6527 const char *zChildCol;
6528 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
6529 int rc;
6531 assert( nVal==4 );
6532 zParent = (const char*)sqlite3_value_text(apVal[0]);
6533 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6534 zChild = (const char*)sqlite3_value_text(apVal[2]);
6535 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6537 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6538 rc = sqlite3_table_column_metadata(
6539 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6541 if( rc==SQLITE_OK ){
6542 rc = sqlite3_table_column_metadata(
6543 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6547 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6548 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6549 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6550 sqlite3_free(z);
6556 ** The implementation of dot-command ".lint fkey-indexes".
6558 static int lintFkeyIndexes(
6559 ShellState *pState, /* Current shell tool state */
6560 char **azArg, /* Array of arguments passed to dot command */
6561 int nArg /* Number of entries in azArg[] */
6563 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
6564 int bVerbose = 0; /* If -verbose is present */
6565 int bGroupByParent = 0; /* If -groupbyparent is present */
6566 int i; /* To iterate through azArg[] */
6567 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
6568 int rc; /* Return code */
6569 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
6572 ** This SELECT statement returns one row for each foreign key constraint
6573 ** in the schema of the main database. The column values are:
6575 ** 0. The text of an SQL statement similar to:
6577 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6579 ** This SELECT is similar to the one that the foreign keys implementation
6580 ** needs to run internally on child tables. If there is an index that can
6581 ** be used to optimize this query, then it can also be used by the FK
6582 ** implementation to optimize DELETE or UPDATE statements on the parent
6583 ** table.
6585 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6586 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6587 ** contains an index that can be used to optimize the query.
6589 ** 2. Human readable text that describes the child table and columns. e.g.
6591 ** "child_table(child_key1, child_key2)"
6593 ** 3. Human readable text that describes the parent table and columns. e.g.
6595 ** "parent_table(parent_key1, parent_key2)"
6597 ** 4. A full CREATE INDEX statement for an index that could be used to
6598 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6600 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6602 ** 5. The name of the parent table.
6604 ** These six values are used by the C logic below to generate the report.
6606 const char *zSql =
6607 "SELECT "
6608 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6609 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6610 " || fkey_collate_clause("
6611 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6612 ", "
6613 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6614 " || group_concat('*=?', ' AND ') || ')'"
6615 ", "
6616 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6617 ", "
6618 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6619 ", "
6620 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6621 " || ' ON ' || quote(s.name) || '('"
6622 " || group_concat(quote(f.[from]) ||"
6623 " fkey_collate_clause("
6624 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6625 " || ');'"
6626 ", "
6627 " f.[table] "
6628 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6629 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6630 "GROUP BY s.name, f.id "
6631 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6633 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6635 for(i=2; i<nArg; i++){
6636 int n = strlen30(azArg[i]);
6637 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6638 bVerbose = 1;
6640 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6641 bGroupByParent = 1;
6642 zIndent = " ";
6644 else{
6645 eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
6646 return SQLITE_ERROR;
6650 /* Register the fkey_collate_clause() SQL function */
6651 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6652 0, shellFkeyCollateClause, 0, 0
6656 if( rc==SQLITE_OK ){
6657 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6659 if( rc==SQLITE_OK ){
6660 sqlite3_bind_int(pSql, 1, bGroupByParent);
6663 if( rc==SQLITE_OK ){
6664 int rc2;
6665 char *zPrev = 0;
6666 while( SQLITE_ROW==sqlite3_step(pSql) ){
6667 int res = -1;
6668 sqlite3_stmt *pExplain = 0;
6669 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6670 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6671 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6672 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6673 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6674 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6676 if( zEQP==0 ) continue;
6677 if( zGlob==0 ) continue;
6678 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6679 if( rc!=SQLITE_OK ) break;
6680 if( SQLITE_ROW==sqlite3_step(pExplain) ){
6681 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6682 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
6683 || 0==sqlite3_strglob(zGlobIPK, zPlan));
6685 rc = sqlite3_finalize(pExplain);
6686 if( rc!=SQLITE_OK ) break;
6688 if( res<0 ){
6689 eputz("Error: internal error");
6690 break;
6691 }else{
6692 if( bGroupByParent
6693 && (bVerbose || res==0)
6694 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6696 oputf("-- Parent table %s\n", zParent);
6697 sqlite3_free(zPrev);
6698 zPrev = sqlite3_mprintf("%s", zParent);
6701 if( res==0 ){
6702 oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
6703 }else if( bVerbose ){
6704 oputf("%s/* no extra indexes required for %s -> %s */\n",
6705 zIndent, zFrom, zTarget
6710 sqlite3_free(zPrev);
6712 if( rc!=SQLITE_OK ){
6713 eputf("%s\n", sqlite3_errmsg(db));
6716 rc2 = sqlite3_finalize(pSql);
6717 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6718 rc = rc2;
6719 eputf("%s\n", sqlite3_errmsg(db));
6721 }else{
6722 eputf("%s\n", sqlite3_errmsg(db));
6725 return rc;
6729 ** Implementation of ".lint" dot command.
6731 static int lintDotCommand(
6732 ShellState *pState, /* Current shell tool state */
6733 char **azArg, /* Array of arguments passed to dot command */
6734 int nArg /* Number of entries in azArg[] */
6736 int n;
6737 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6738 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6739 return lintFkeyIndexes(pState, azArg, nArg);
6741 usage:
6742 eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
6743 eputz("Where sub-commands are:\n");
6744 eputz(" fkey-indexes\n");
6745 return SQLITE_ERROR;
6748 static void shellPrepare(
6749 sqlite3 *db,
6750 int *pRc,
6751 const char *zSql,
6752 sqlite3_stmt **ppStmt
6754 *ppStmt = 0;
6755 if( *pRc==SQLITE_OK ){
6756 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6757 if( rc!=SQLITE_OK ){
6758 eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
6759 *pRc = rc;
6765 ** Create a prepared statement using printf-style arguments for the SQL.
6767 static void shellPreparePrintf(
6768 sqlite3 *db,
6769 int *pRc,
6770 sqlite3_stmt **ppStmt,
6771 const char *zFmt,
6774 *ppStmt = 0;
6775 if( *pRc==SQLITE_OK ){
6776 va_list ap;
6777 char *z;
6778 va_start(ap, zFmt);
6779 z = sqlite3_vmprintf(zFmt, ap);
6780 va_end(ap);
6781 if( z==0 ){
6782 *pRc = SQLITE_NOMEM;
6783 }else{
6784 shellPrepare(db, pRc, z, ppStmt);
6785 sqlite3_free(z);
6791 ** Finalize the prepared statement created using shellPreparePrintf().
6793 static void shellFinalize(
6794 int *pRc,
6795 sqlite3_stmt *pStmt
6797 if( pStmt ){
6798 sqlite3 *db = sqlite3_db_handle(pStmt);
6799 int rc = sqlite3_finalize(pStmt);
6800 if( *pRc==SQLITE_OK ){
6801 if( rc!=SQLITE_OK ){
6802 eputf("SQL error: %s\n", sqlite3_errmsg(db));
6804 *pRc = rc;
6809 #if !defined SQLITE_OMIT_VIRTUALTABLE
6810 /* Reset the prepared statement created using shellPreparePrintf().
6812 ** This routine is could be marked "static". But it is not always used,
6813 ** depending on compile-time options. By omitting the "static", we avoid
6814 ** nuisance compiler warnings about "defined but not used".
6816 void shellReset(
6817 int *pRc,
6818 sqlite3_stmt *pStmt
6820 int rc = sqlite3_reset(pStmt);
6821 if( *pRc==SQLITE_OK ){
6822 if( rc!=SQLITE_OK ){
6823 sqlite3 *db = sqlite3_db_handle(pStmt);
6824 eputf("SQL error: %s\n", sqlite3_errmsg(db));
6826 *pRc = rc;
6829 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6831 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6832 /******************************************************************************
6833 ** The ".archive" or ".ar" command.
6836 ** Structure representing a single ".ar" command.
6838 typedef struct ArCommand ArCommand;
6839 struct ArCommand {
6840 u8 eCmd; /* An AR_CMD_* value */
6841 u8 bVerbose; /* True if --verbose */
6842 u8 bZip; /* True if the archive is a ZIP */
6843 u8 bDryRun; /* True if --dry-run */
6844 u8 bAppend; /* True if --append */
6845 u8 bGlob; /* True if --glob */
6846 u8 fromCmdLine; /* Run from -A instead of .archive */
6847 int nArg; /* Number of command arguments */
6848 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6849 const char *zFile; /* --file argument, or NULL */
6850 const char *zDir; /* --directory argument, or NULL */
6851 char **azArg; /* Array of command arguments */
6852 ShellState *p; /* Shell state */
6853 sqlite3 *db; /* Database containing the archive */
6857 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6859 static int arUsage(FILE *f){
6860 showHelp(f,"archive");
6861 return SQLITE_ERROR;
6865 ** Print an error message for the .ar command to stderr and return
6866 ** SQLITE_ERROR.
6868 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6869 va_list ap;
6870 char *z;
6871 va_start(ap, zFmt);
6872 z = sqlite3_vmprintf(zFmt, ap);
6873 va_end(ap);
6874 eputf("Error: %s\n", z);
6875 if( pAr->fromCmdLine ){
6876 eputz("Use \"-A\" for more help\n");
6877 }else{
6878 eputz("Use \".archive --help\" for more help\n");
6880 sqlite3_free(z);
6881 return SQLITE_ERROR;
6885 ** Values for ArCommand.eCmd.
6887 #define AR_CMD_CREATE 1
6888 #define AR_CMD_UPDATE 2
6889 #define AR_CMD_INSERT 3
6890 #define AR_CMD_EXTRACT 4
6891 #define AR_CMD_LIST 5
6892 #define AR_CMD_HELP 6
6893 #define AR_CMD_REMOVE 7
6896 ** Other (non-command) switches.
6898 #define AR_SWITCH_VERBOSE 8
6899 #define AR_SWITCH_FILE 9
6900 #define AR_SWITCH_DIRECTORY 10
6901 #define AR_SWITCH_APPEND 11
6902 #define AR_SWITCH_DRYRUN 12
6903 #define AR_SWITCH_GLOB 13
6905 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6906 switch( eSwitch ){
6907 case AR_CMD_CREATE:
6908 case AR_CMD_EXTRACT:
6909 case AR_CMD_LIST:
6910 case AR_CMD_REMOVE:
6911 case AR_CMD_UPDATE:
6912 case AR_CMD_INSERT:
6913 case AR_CMD_HELP:
6914 if( pAr->eCmd ){
6915 return arErrorMsg(pAr, "multiple command options");
6917 pAr->eCmd = eSwitch;
6918 break;
6920 case AR_SWITCH_DRYRUN:
6921 pAr->bDryRun = 1;
6922 break;
6923 case AR_SWITCH_GLOB:
6924 pAr->bGlob = 1;
6925 break;
6926 case AR_SWITCH_VERBOSE:
6927 pAr->bVerbose = 1;
6928 break;
6929 case AR_SWITCH_APPEND:
6930 pAr->bAppend = 1;
6931 deliberate_fall_through;
6932 case AR_SWITCH_FILE:
6933 pAr->zFile = zArg;
6934 break;
6935 case AR_SWITCH_DIRECTORY:
6936 pAr->zDir = zArg;
6937 break;
6940 return SQLITE_OK;
6944 ** Parse the command line for an ".ar" command. The results are written into
6945 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6946 ** successfully, otherwise an error message is written to stderr and
6947 ** SQLITE_ERROR returned.
6949 static int arParseCommand(
6950 char **azArg, /* Array of arguments passed to dot command */
6951 int nArg, /* Number of entries in azArg[] */
6952 ArCommand *pAr /* Populate this object */
6954 struct ArSwitch {
6955 const char *zLong;
6956 char cShort;
6957 u8 eSwitch;
6958 u8 bArg;
6959 } aSwitch[] = {
6960 { "create", 'c', AR_CMD_CREATE, 0 },
6961 { "extract", 'x', AR_CMD_EXTRACT, 0 },
6962 { "insert", 'i', AR_CMD_INSERT, 0 },
6963 { "list", 't', AR_CMD_LIST, 0 },
6964 { "remove", 'r', AR_CMD_REMOVE, 0 },
6965 { "update", 'u', AR_CMD_UPDATE, 0 },
6966 { "help", 'h', AR_CMD_HELP, 0 },
6967 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
6968 { "file", 'f', AR_SWITCH_FILE, 1 },
6969 { "append", 'a', AR_SWITCH_APPEND, 1 },
6970 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6971 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
6972 { "glob", 'g', AR_SWITCH_GLOB, 0 },
6974 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6975 struct ArSwitch *pEnd = &aSwitch[nSwitch];
6977 if( nArg<=1 ){
6978 eputz("Wrong number of arguments. Usage:\n");
6979 return arUsage(stderr);
6980 }else{
6981 char *z = azArg[1];
6982 if( z[0]!='-' ){
6983 /* Traditional style [tar] invocation */
6984 int i;
6985 int iArg = 2;
6986 for(i=0; z[i]; i++){
6987 const char *zArg = 0;
6988 struct ArSwitch *pOpt;
6989 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6990 if( z[i]==pOpt->cShort ) break;
6992 if( pOpt==pEnd ){
6993 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6995 if( pOpt->bArg ){
6996 if( iArg>=nArg ){
6997 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6999 zArg = azArg[iArg++];
7001 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7003 pAr->nArg = nArg-iArg;
7004 if( pAr->nArg>0 ){
7005 pAr->azArg = &azArg[iArg];
7007 }else{
7008 /* Non-traditional invocation */
7009 int iArg;
7010 for(iArg=1; iArg<nArg; iArg++){
7011 int n;
7012 z = azArg[iArg];
7013 if( z[0]!='-' ){
7014 /* All remaining command line words are command arguments. */
7015 pAr->azArg = &azArg[iArg];
7016 pAr->nArg = nArg-iArg;
7017 break;
7019 n = strlen30(z);
7021 if( z[1]!='-' ){
7022 int i;
7023 /* One or more short options */
7024 for(i=1; i<n; i++){
7025 const char *zArg = 0;
7026 struct ArSwitch *pOpt;
7027 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7028 if( z[i]==pOpt->cShort ) break;
7030 if( pOpt==pEnd ){
7031 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
7033 if( pOpt->bArg ){
7034 if( i<(n-1) ){
7035 zArg = &z[i+1];
7036 i = n;
7037 }else{
7038 if( iArg>=(nArg-1) ){
7039 return arErrorMsg(pAr, "option requires an argument: %c",
7040 z[i]);
7042 zArg = azArg[++iArg];
7045 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7047 }else if( z[2]=='\0' ){
7048 /* A -- option, indicating that all remaining command line words
7049 ** are command arguments. */
7050 pAr->azArg = &azArg[iArg+1];
7051 pAr->nArg = nArg-iArg-1;
7052 break;
7053 }else{
7054 /* A long option */
7055 const char *zArg = 0; /* Argument for option, if any */
7056 struct ArSwitch *pMatch = 0; /* Matching option */
7057 struct ArSwitch *pOpt; /* Iterator */
7058 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7059 const char *zLong = pOpt->zLong;
7060 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
7061 if( pMatch ){
7062 return arErrorMsg(pAr, "ambiguous option: %s",z);
7063 }else{
7064 pMatch = pOpt;
7069 if( pMatch==0 ){
7070 return arErrorMsg(pAr, "unrecognized option: %s", z);
7072 if( pMatch->bArg ){
7073 if( iArg>=(nArg-1) ){
7074 return arErrorMsg(pAr, "option requires an argument: %s", z);
7076 zArg = azArg[++iArg];
7078 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
7083 if( pAr->eCmd==0 ){
7084 eputz("Required argument missing. Usage:\n");
7085 return arUsage(stderr);
7087 return SQLITE_OK;
7091 ** This function assumes that all arguments within the ArCommand.azArg[]
7092 ** array refer to archive members, as for the --extract, --list or --remove
7093 ** commands. It checks that each of them are "present". If any specified
7094 ** file is not present in the archive, an error is printed to stderr and an
7095 ** error code returned. Otherwise, if all specified arguments are present
7096 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7097 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7098 ** when pAr->bGlob is true.
7100 ** This function strips any trailing '/' characters from each argument.
7101 ** This is consistent with the way the [tar] command seems to work on
7102 ** Linux.
7104 static int arCheckEntries(ArCommand *pAr){
7105 int rc = SQLITE_OK;
7106 if( pAr->nArg ){
7107 int i, j;
7108 sqlite3_stmt *pTest = 0;
7109 const char *zSel = (pAr->bGlob)
7110 ? "SELECT name FROM %s WHERE glob($name,name)"
7111 : "SELECT name FROM %s WHERE name=$name";
7113 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
7114 j = sqlite3_bind_parameter_index(pTest, "$name");
7115 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7116 char *z = pAr->azArg[i];
7117 int n = strlen30(z);
7118 int bOk = 0;
7119 while( n>0 && z[n-1]=='/' ) n--;
7120 z[n] = '\0';
7121 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
7122 if( SQLITE_ROW==sqlite3_step(pTest) ){
7123 bOk = 1;
7125 shellReset(&rc, pTest);
7126 if( rc==SQLITE_OK && bOk==0 ){
7127 eputf("not found in archive: %s\n", z);
7128 rc = SQLITE_ERROR;
7131 shellFinalize(&rc, pTest);
7133 return rc;
7137 ** Format a WHERE clause that can be used against the "sqlar" table to
7138 ** identify all archive members that match the command arguments held
7139 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7140 ** The caller is responsible for eventually calling sqlite3_free() on
7141 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7142 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7144 static void arWhereClause(
7145 int *pRc,
7146 ArCommand *pAr,
7147 char **pzWhere /* OUT: New WHERE clause */
7149 char *zWhere = 0;
7150 const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
7151 if( *pRc==SQLITE_OK ){
7152 if( pAr->nArg==0 ){
7153 zWhere = sqlite3_mprintf("1");
7154 }else{
7155 int i;
7156 const char *zSep = "";
7157 for(i=0; i<pAr->nArg; i++){
7158 const char *z = pAr->azArg[i];
7159 zWhere = sqlite3_mprintf(
7160 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7161 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
7163 if( zWhere==0 ){
7164 *pRc = SQLITE_NOMEM;
7165 break;
7167 zSep = " OR ";
7171 *pzWhere = zWhere;
7175 ** Implementation of .ar "lisT" command.
7177 static int arListCommand(ArCommand *pAr){
7178 const char *zSql = "SELECT %s FROM %s WHERE %s";
7179 const char *azCols[] = {
7180 "name",
7181 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7184 char *zWhere = 0;
7185 sqlite3_stmt *pSql = 0;
7186 int rc;
7188 rc = arCheckEntries(pAr);
7189 arWhereClause(&rc, pAr, &zWhere);
7191 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
7192 pAr->zSrcTable, zWhere);
7193 if( pAr->bDryRun ){
7194 oputf("%s\n", sqlite3_sql(pSql));
7195 }else{
7196 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7197 if( pAr->bVerbose ){
7198 oputf("%s % 10d %s %s\n",
7199 sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
7200 sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
7201 }else{
7202 oputf("%s\n", sqlite3_column_text(pSql, 0));
7206 shellFinalize(&rc, pSql);
7207 sqlite3_free(zWhere);
7208 return rc;
7212 ** Implementation of .ar "Remove" command.
7214 static int arRemoveCommand(ArCommand *pAr){
7215 int rc = 0;
7216 char *zSql = 0;
7217 char *zWhere = 0;
7219 if( pAr->nArg ){
7220 /* Verify that args actually exist within the archive before proceeding.
7221 ** And formulate a WHERE clause to match them. */
7222 rc = arCheckEntries(pAr);
7223 arWhereClause(&rc, pAr, &zWhere);
7225 if( rc==SQLITE_OK ){
7226 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7227 pAr->zSrcTable, zWhere);
7228 if( pAr->bDryRun ){
7229 oputf("%s\n", zSql);
7230 }else{
7231 char *zErr = 0;
7232 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
7233 if( rc==SQLITE_OK ){
7234 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7235 if( rc!=SQLITE_OK ){
7236 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7237 }else{
7238 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
7241 if( zErr ){
7242 sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
7243 sqlite3_free(zErr);
7247 sqlite3_free(zWhere);
7248 sqlite3_free(zSql);
7249 return rc;
7253 ** Implementation of .ar "eXtract" command.
7255 static int arExtractCommand(ArCommand *pAr){
7256 const char *zSql1 =
7257 "SELECT "
7258 " ($dir || name),"
7259 " writefile(($dir || name), %s, mode, mtime) "
7260 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7261 " AND name NOT GLOB '*..[/\\]*'";
7263 const char *azExtraArg[] = {
7264 "sqlar_uncompress(data, sz)",
7265 "data"
7268 sqlite3_stmt *pSql = 0;
7269 int rc = SQLITE_OK;
7270 char *zDir = 0;
7271 char *zWhere = 0;
7272 int i, j;
7274 /* If arguments are specified, check that they actually exist within
7275 ** the archive before proceeding. And formulate a WHERE clause to
7276 ** match them. */
7277 rc = arCheckEntries(pAr);
7278 arWhereClause(&rc, pAr, &zWhere);
7280 if( rc==SQLITE_OK ){
7281 if( pAr->zDir ){
7282 zDir = sqlite3_mprintf("%s/", pAr->zDir);
7283 }else{
7284 zDir = sqlite3_mprintf("");
7286 if( zDir==0 ) rc = SQLITE_NOMEM;
7289 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
7290 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
7293 if( rc==SQLITE_OK ){
7294 j = sqlite3_bind_parameter_index(pSql, "$dir");
7295 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
7297 /* Run the SELECT statement twice. The first time, writefile() is called
7298 ** for all archive members that should be extracted. The second time,
7299 ** only for the directories. This is because the timestamps for
7300 ** extracted directories must be reset after they are populated (as
7301 ** populating them changes the timestamp). */
7302 for(i=0; i<2; i++){
7303 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
7304 sqlite3_bind_int(pSql, j, i);
7305 if( pAr->bDryRun ){
7306 oputf("%s\n", sqlite3_sql(pSql));
7307 }else{
7308 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7309 if( i==0 && pAr->bVerbose ){
7310 oputf("%s\n", sqlite3_column_text(pSql, 0));
7314 shellReset(&rc, pSql);
7316 shellFinalize(&rc, pSql);
7319 sqlite3_free(zDir);
7320 sqlite3_free(zWhere);
7321 return rc;
7325 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7327 static int arExecSql(ArCommand *pAr, const char *zSql){
7328 int rc;
7329 if( pAr->bDryRun ){
7330 oputf("%s\n", zSql);
7331 rc = SQLITE_OK;
7332 }else{
7333 char *zErr = 0;
7334 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7335 if( zErr ){
7336 sputf(stdout, "ERROR: %s\n", zErr);
7337 sqlite3_free(zErr);
7340 return rc;
7345 ** Implementation of .ar "create", "insert", and "update" commands.
7347 ** create -> Create a new SQL archive
7348 ** insert -> Insert or reinsert all files listed
7349 ** update -> Insert files that have changed or that were not
7350 ** previously in the archive
7352 ** Create the "sqlar" table in the database if it does not already exist.
7353 ** Then add each file in the azFile[] array to the archive. Directories
7354 ** are added recursively. If argument bVerbose is non-zero, a message is
7355 ** printed on stdout for each file archived.
7357 ** The create command is the same as update, except that it drops
7358 ** any existing "sqlar" table before beginning. The "insert" command
7359 ** always overwrites every file named on the command-line, where as
7360 ** "update" only overwrites if the size or mtime or mode has changed.
7362 static int arCreateOrUpdateCommand(
7363 ArCommand *pAr, /* Command arguments and options */
7364 int bUpdate, /* true for a --create. */
7365 int bOnlyIfChanged /* Only update if file has changed */
7367 const char *zCreate =
7368 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7369 " name TEXT PRIMARY KEY, -- name of the file\n"
7370 " mode INT, -- access permissions\n"
7371 " mtime INT, -- last modification time\n"
7372 " sz INT, -- original file size\n"
7373 " data BLOB -- compressed content\n"
7374 ")";
7375 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7376 const char *zInsertFmt[2] = {
7377 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7378 " SELECT\n"
7379 " %s,\n"
7380 " mode,\n"
7381 " mtime,\n"
7382 " CASE substr(lsmode(mode),1,1)\n"
7383 " WHEN '-' THEN length(data)\n"
7384 " WHEN 'd' THEN 0\n"
7385 " ELSE -1 END,\n"
7386 " sqlar_compress(data)\n"
7387 " FROM fsdir(%Q,%Q) AS disk\n"
7388 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7390 "REPLACE INTO %s(name,mode,mtime,data)\n"
7391 " SELECT\n"
7392 " %s,\n"
7393 " mode,\n"
7394 " mtime,\n"
7395 " data\n"
7396 " FROM fsdir(%Q,%Q) AS disk\n"
7397 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7399 int i; /* For iterating through azFile[] */
7400 int rc; /* Return code */
7401 const char *zTab = 0; /* SQL table into which to insert */
7402 char *zSql;
7403 char zTemp[50];
7404 char *zExists = 0;
7406 arExecSql(pAr, "PRAGMA page_size=512");
7407 rc = arExecSql(pAr, "SAVEPOINT ar;");
7408 if( rc!=SQLITE_OK ) return rc;
7409 zTemp[0] = 0;
7410 if( pAr->bZip ){
7411 /* Initialize the zipfile virtual table, if necessary */
7412 if( pAr->zFile ){
7413 sqlite3_uint64 r;
7414 sqlite3_randomness(sizeof(r),&r);
7415 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7416 zTab = zTemp;
7417 zSql = sqlite3_mprintf(
7418 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7419 zTab, pAr->zFile
7421 rc = arExecSql(pAr, zSql);
7422 sqlite3_free(zSql);
7423 }else{
7424 zTab = "zip";
7426 }else{
7427 /* Initialize the table for an SQLAR */
7428 zTab = "sqlar";
7429 if( bUpdate==0 ){
7430 rc = arExecSql(pAr, zDrop);
7431 if( rc!=SQLITE_OK ) goto end_ar_transaction;
7433 rc = arExecSql(pAr, zCreate);
7435 if( bOnlyIfChanged ){
7436 zExists = sqlite3_mprintf(
7437 " AND NOT EXISTS("
7438 "SELECT 1 FROM %s AS mem"
7439 " WHERE mem.name=disk.name"
7440 " AND mem.mtime=disk.mtime"
7441 " AND mem.mode=disk.mode)", zTab);
7442 }else{
7443 zExists = sqlite3_mprintf("");
7445 if( zExists==0 ) rc = SQLITE_NOMEM;
7446 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7447 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7448 pAr->bVerbose ? "shell_putsnl(name)" : "name",
7449 pAr->azArg[i], pAr->zDir, zExists);
7450 rc = arExecSql(pAr, zSql2);
7451 sqlite3_free(zSql2);
7453 end_ar_transaction:
7454 if( rc!=SQLITE_OK ){
7455 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7456 }else{
7457 rc = arExecSql(pAr, "RELEASE ar;");
7458 if( pAr->bZip && pAr->zFile ){
7459 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7460 arExecSql(pAr, zSql);
7461 sqlite3_free(zSql);
7464 sqlite3_free(zExists);
7465 return rc;
7469 ** Implementation of ".ar" dot command.
7471 static int arDotCommand(
7472 ShellState *pState, /* Current shell tool state */
7473 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
7474 char **azArg, /* Array of arguments passed to dot command */
7475 int nArg /* Number of entries in azArg[] */
7477 ArCommand cmd;
7478 int rc;
7479 memset(&cmd, 0, sizeof(cmd));
7480 cmd.fromCmdLine = fromCmdLine;
7481 rc = arParseCommand(azArg, nArg, &cmd);
7482 if( rc==SQLITE_OK ){
7483 int eDbType = SHELL_OPEN_UNSPEC;
7484 cmd.p = pState;
7485 cmd.db = pState->db;
7486 if( cmd.zFile ){
7487 eDbType = deduceDatabaseType(cmd.zFile, 1);
7488 }else{
7489 eDbType = pState->openMode;
7491 if( eDbType==SHELL_OPEN_ZIPFILE ){
7492 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7493 if( cmd.zFile==0 ){
7494 cmd.zSrcTable = sqlite3_mprintf("zip");
7495 }else{
7496 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7499 cmd.bZip = 1;
7500 }else if( cmd.zFile ){
7501 int flags;
7502 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7503 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7504 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7505 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7506 }else{
7507 flags = SQLITE_OPEN_READONLY;
7509 cmd.db = 0;
7510 if( cmd.bDryRun ){
7511 oputf("-- open database '%s'%s\n", cmd.zFile,
7512 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7514 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7515 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7516 if( rc!=SQLITE_OK ){
7517 eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
7518 goto end_ar_command;
7520 sqlite3_fileio_init(cmd.db, 0, 0);
7521 sqlite3_sqlar_init(cmd.db, 0, 0);
7522 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7523 shellPutsFunc, 0, 0);
7526 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7527 if( cmd.eCmd!=AR_CMD_CREATE
7528 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7530 eputz("database does not contain an 'sqlar' table\n");
7531 rc = SQLITE_ERROR;
7532 goto end_ar_command;
7534 cmd.zSrcTable = sqlite3_mprintf("sqlar");
7537 switch( cmd.eCmd ){
7538 case AR_CMD_CREATE:
7539 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7540 break;
7542 case AR_CMD_EXTRACT:
7543 rc = arExtractCommand(&cmd);
7544 break;
7546 case AR_CMD_LIST:
7547 rc = arListCommand(&cmd);
7548 break;
7550 case AR_CMD_HELP:
7551 arUsage(pState->out);
7552 break;
7554 case AR_CMD_INSERT:
7555 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7556 break;
7558 case AR_CMD_REMOVE:
7559 rc = arRemoveCommand(&cmd);
7560 break;
7562 default:
7563 assert( cmd.eCmd==AR_CMD_UPDATE );
7564 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7565 break;
7568 end_ar_command:
7569 if( cmd.db!=pState->db ){
7570 close_db(cmd.db);
7572 sqlite3_free(cmd.zSrcTable);
7574 return rc;
7576 /* End of the ".archive" or ".ar" command logic
7577 *******************************************************************************/
7578 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7580 #if SQLITE_SHELL_HAVE_RECOVER
7583 ** This function is used as a callback by the recover extension. Simply
7584 ** print the supplied SQL statement to stdout.
7586 static int recoverSqlCb(void *pCtx, const char *zSql){
7587 ShellState *pState = (ShellState*)pCtx;
7588 sputf(pState->out, "%s;\n", zSql);
7589 return SQLITE_OK;
7593 ** This function is called to recover data from the database. A script
7594 ** to construct a new database containing all recovered data is output
7595 ** on stream pState->out.
7597 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7598 int rc = SQLITE_OK;
7599 const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
7600 const char *zLAF = "lost_and_found";
7601 int bFreelist = 1; /* 0 if --ignore-freelist is specified */
7602 int bRowids = 1; /* 0 if --no-rowids */
7603 sqlite3_recover *p = 0;
7604 int i = 0;
7606 for(i=1; i<nArg; i++){
7607 char *z = azArg[i];
7608 int n;
7609 if( z[0]=='-' && z[1]=='-' ) z++;
7610 n = strlen30(z);
7611 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
7612 bFreelist = 0;
7613 }else
7614 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7615 /* This option determines the name of the ATTACH-ed database used
7616 ** internally by the recovery extension. The default is "" which
7617 ** means to use a temporary database that is automatically deleted
7618 ** when closed. This option is undocumented and might disappear at
7619 ** any moment. */
7620 i++;
7621 zRecoveryDb = azArg[i];
7622 }else
7623 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7624 i++;
7625 zLAF = azArg[i];
7626 }else
7627 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7628 bRowids = 0;
7630 else{
7631 eputf("unexpected option: %s\n", azArg[i]);
7632 showHelp(pState->out, azArg[0]);
7633 return 1;
7637 p = sqlite3_recover_init_sql(
7638 pState->db, "main", recoverSqlCb, (void*)pState
7641 sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */
7642 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7643 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7644 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7646 sqlite3_recover_run(p);
7647 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7648 const char *zErr = sqlite3_recover_errmsg(p);
7649 int errCode = sqlite3_recover_errcode(p);
7650 eputf("sql error: %s (%d)\n", zErr, errCode);
7652 rc = sqlite3_recover_finish(p);
7653 return rc;
7655 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7659 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7660 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7661 * close db and set it to 0, and return the columns spec, to later
7662 * be sqlite3_free()'ed by the caller.
7663 * The return is 0 when either:
7664 * (a) The db was not initialized and zCol==0 (There are no columns.)
7665 * (b) zCol!=0 (Column was added, db initialized as needed.)
7666 * The 3rd argument, pRenamed, references an out parameter. If the
7667 * pointer is non-zero, its referent will be set to a summary of renames
7668 * done if renaming was necessary, or set to 0 if none was done. The out
7669 * string (if any) must be sqlite3_free()'ed by the caller.
7671 #ifdef SHELL_DEBUG
7672 #define rc_err_oom_die(rc) \
7673 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7674 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7675 eputf("E:%d\n",rc), assert(0)
7676 #else
7677 static void rc_err_oom_die(int rc){
7678 if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7679 assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7681 #endif
7683 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7684 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7685 #else /* Otherwise, memory is faster/better for the transient DB. */
7686 static const char *zCOL_DB = ":memory:";
7687 #endif
7689 /* Define character (as C string) to separate generated column ordinal
7690 * from protected part of incoming column names. This defaults to "_"
7691 * so that incoming column identifiers that did not need not be quoted
7692 * remain usable without being quoted. It must be one character.
7694 #ifndef SHELL_AUTOCOLUMN_SEP
7695 # define AUTOCOLUMN_SEP "_"
7696 #else
7697 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7698 #endif
7700 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7701 /* Queries and D{D,M}L used here */
7702 static const char * const zTabMake = "\
7703 CREATE TABLE ColNames(\
7704 cpos INTEGER PRIMARY KEY,\
7705 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7706 CREATE VIEW RepeatedNames AS \
7707 SELECT DISTINCT t.name FROM ColNames t \
7708 WHERE t.name COLLATE NOCASE IN (\
7709 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7712 static const char * const zTabFill = "\
7713 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7714 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7716 static const char * const zHasDupes = "\
7717 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7718 <count(name) FROM ColNames\
7720 #ifdef SHELL_COLUMN_RENAME_CLEAN
7721 static const char * const zDedoctor = "\
7722 UPDATE ColNames SET chop=iif(\
7723 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7724 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7725 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7729 #endif
7730 static const char * const zSetReps = "\
7731 UPDATE ColNames AS t SET reps=\
7732 (SELECT count(*) FROM ColNames d \
7733 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7734 COLLATE NOCASE\
7737 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7738 static const char * const zColDigits = "\
7739 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7741 #else
7742 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7743 static const char * const zColDigits = "\
7744 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7745 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7746 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7748 #endif
7749 static const char * const zRenameRank =
7750 #ifdef SHELL_COLUMN_RENAME_CLEAN
7751 "UPDATE ColNames AS t SET suff="
7752 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7753 #else /* ...RENAME_MINIMAL_ONE_PASS */
7754 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7755 " SELECT 0 AS nlz"
7756 " UNION"
7757 " SELECT nlz+1 AS nlz FROM Lzn"
7758 " WHERE EXISTS("
7759 " SELECT 1"
7760 " FROM ColNames t, ColNames o"
7761 " WHERE"
7762 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7763 " printf('%s"AUTOCOLUMN_SEP"%s',"
7764 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7765 " t.name"
7766 " )"
7767 " ="
7768 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7769 " printf('%s"AUTOCOLUMN_SEP"%s',"
7770 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7771 " o.name"
7772 " )"
7773 " COLLATE NOCASE"
7774 " AND o.cpos<>t.cpos"
7775 " GROUP BY t.cpos"
7776 " )"
7777 ") UPDATE Colnames AS t SET"
7778 " chop = 0," /* No chopping, never touch incoming names. */
7779 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7780 " printf('"AUTOCOLUMN_SEP"%s', substring("
7781 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7782 " ''"
7783 " )"
7784 #endif
7786 static const char * const zCollectVar = "\
7787 SELECT\
7788 '('||x'0a'\
7789 || group_concat(\
7790 cname||' TEXT',\
7791 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7792 ||')' AS ColsSpec \
7793 FROM (\
7794 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7795 FROM ColNames ORDER BY cpos\
7797 static const char * const zRenamesDone =
7798 "SELECT group_concat("
7799 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7800 " ','||x'0a')"
7801 "FROM ColNames WHERE suff<>'' OR chop!=0"
7803 int rc;
7804 sqlite3_stmt *pStmt = 0;
7805 assert(pDb!=0);
7806 if( zColNew ){
7807 /* Add initial or additional column. Init db if necessary. */
7808 if( *pDb==0 ){
7809 if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7810 #ifdef SHELL_COLFIX_DB
7811 if(*zCOL_DB!=':')
7812 sqlite3_exec(*pDb,"drop table if exists ColNames;"
7813 "drop view if exists RepeatedNames;",0,0,0);
7814 #endif
7815 #undef SHELL_COLFIX_DB
7816 rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7817 rc_err_oom_die(rc);
7819 assert(*pDb!=0);
7820 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7821 rc_err_oom_die(rc);
7822 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7823 rc_err_oom_die(rc);
7824 rc = sqlite3_step(pStmt);
7825 rc_err_oom_die(rc);
7826 sqlite3_finalize(pStmt);
7827 return 0;
7828 }else if( *pDb==0 ){
7829 return 0;
7830 }else{
7831 /* Formulate the columns spec, close the DB, zero *pDb. */
7832 char *zColsSpec = 0;
7833 int hasDupes = db_int(*pDb, zHasDupes);
7834 int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7835 if( hasDupes ){
7836 #ifdef SHELL_COLUMN_RENAME_CLEAN
7837 rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7838 rc_err_oom_die(rc);
7839 #endif
7840 rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7841 rc_err_oom_die(rc);
7842 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7843 rc_err_oom_die(rc);
7844 sqlite3_bind_int(pStmt, 1, nDigits);
7845 rc = sqlite3_step(pStmt);
7846 sqlite3_finalize(pStmt);
7847 if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
7849 assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7850 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7851 rc_err_oom_die(rc);
7852 rc = sqlite3_step(pStmt);
7853 if( rc==SQLITE_ROW ){
7854 zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7855 }else{
7856 zColsSpec = 0;
7858 if( pzRenamed!=0 ){
7859 if( !hasDupes ) *pzRenamed = 0;
7860 else{
7861 sqlite3_finalize(pStmt);
7862 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7863 && SQLITE_ROW==sqlite3_step(pStmt) ){
7864 *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7865 }else
7866 *pzRenamed = 0;
7869 sqlite3_finalize(pStmt);
7870 sqlite3_close(*pDb);
7871 *pDb = 0;
7872 return zColsSpec;
7877 ** Check if the sqlite_schema table contains one or more virtual tables. If
7878 ** parameter zLike is not NULL, then it is an SQL expression that the
7879 ** sqlite_schema row must also match. If one or more such rows are found,
7880 ** print the following warning to the output:
7882 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
7884 static int outputDumpWarning(ShellState *p, const char *zLike){
7885 int rc = SQLITE_OK;
7886 sqlite3_stmt *pStmt = 0;
7887 shellPreparePrintf(p->db, &rc, &pStmt,
7888 "SELECT 1 FROM sqlite_schema o WHERE "
7889 "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
7891 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7892 oputz("/* WARNING: "
7893 "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
7896 shellFinalize(&rc, pStmt);
7897 return rc;
7901 ** If an input line begins with "." then invoke this routine to
7902 ** process that line.
7904 ** Return 1 on error, 2 to exit, and 0 otherwise.
7906 static int do_meta_command(char *zLine, ShellState *p){
7907 int h = 1;
7908 int nArg = 0;
7909 int n, c;
7910 int rc = 0;
7911 char *azArg[52];
7913 #ifndef SQLITE_OMIT_VIRTUALTABLE
7914 if( p->expert.pExpert ){
7915 expertFinish(p, 1, 0);
7917 #endif
7919 /* Parse the input line into tokens.
7921 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7922 while( IsSpace(zLine[h]) ){ h++; }
7923 if( zLine[h]==0 ) break;
7924 if( zLine[h]=='\'' || zLine[h]=='"' ){
7925 int delim = zLine[h++];
7926 azArg[nArg++] = &zLine[h];
7927 while( zLine[h] && zLine[h]!=delim ){
7928 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7929 h++;
7931 if( zLine[h]==delim ){
7932 zLine[h++] = 0;
7934 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7935 }else{
7936 azArg[nArg++] = &zLine[h];
7937 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7938 if( zLine[h] ) zLine[h++] = 0;
7941 azArg[nArg] = 0;
7943 /* Process the input line.
7945 if( nArg==0 ) return 0; /* no tokens, no error */
7946 n = strlen30(azArg[0]);
7947 c = azArg[0][0];
7948 clearTempFile(p);
7950 #ifndef SQLITE_OMIT_AUTHORIZATION
7951 if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
7952 if( nArg!=2 ){
7953 eputz("Usage: .auth ON|OFF\n");
7954 rc = 1;
7955 goto meta_command_exit;
7957 open_db(p, 0);
7958 if( booleanValue(azArg[1]) ){
7959 sqlite3_set_authorizer(p->db, shellAuth, p);
7960 }else if( p->bSafeModePersist ){
7961 sqlite3_set_authorizer(p->db, safeModeAuth, p);
7962 }else{
7963 sqlite3_set_authorizer(p->db, 0, 0);
7965 }else
7966 #endif
7968 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7969 && !defined(SQLITE_SHELL_FIDDLE)
7970 if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
7971 open_db(p, 0);
7972 failIfSafeMode(p, "cannot run .archive in safe mode");
7973 rc = arDotCommand(p, 0, azArg, nArg);
7974 }else
7975 #endif
7977 #ifndef SQLITE_SHELL_FIDDLE
7978 if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
7979 || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
7981 const char *zDestFile = 0;
7982 const char *zDb = 0;
7983 sqlite3 *pDest;
7984 sqlite3_backup *pBackup;
7985 int j;
7986 int bAsync = 0;
7987 const char *zVfs = 0;
7988 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7989 for(j=1; j<nArg; j++){
7990 const char *z = azArg[j];
7991 if( z[0]=='-' ){
7992 if( z[1]=='-' ) z++;
7993 if( cli_strcmp(z, "-append")==0 ){
7994 zVfs = "apndvfs";
7995 }else
7996 if( cli_strcmp(z, "-async")==0 ){
7997 bAsync = 1;
7998 }else
8000 eputf("unknown option: %s\n", azArg[j]);
8001 return 1;
8003 }else if( zDestFile==0 ){
8004 zDestFile = azArg[j];
8005 }else if( zDb==0 ){
8006 zDb = zDestFile;
8007 zDestFile = azArg[j];
8008 }else{
8009 eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8010 return 1;
8013 if( zDestFile==0 ){
8014 eputz("missing FILENAME argument on .backup\n");
8015 return 1;
8017 if( zDb==0 ) zDb = "main";
8018 rc = sqlite3_open_v2(zDestFile, &pDest,
8019 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8020 if( rc!=SQLITE_OK ){
8021 eputf("Error: cannot open \"%s\"\n", zDestFile);
8022 close_db(pDest);
8023 return 1;
8025 if( bAsync ){
8026 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8027 0, 0, 0);
8029 open_db(p, 0);
8030 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8031 if( pBackup==0 ){
8032 eputf("Error: %s\n", sqlite3_errmsg(pDest));
8033 close_db(pDest);
8034 return 1;
8036 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8037 sqlite3_backup_finish(pBackup);
8038 if( rc==SQLITE_DONE ){
8039 rc = 0;
8040 }else{
8041 eputf("Error: %s\n", sqlite3_errmsg(pDest));
8042 rc = 1;
8044 close_db(pDest);
8045 }else
8046 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8048 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
8049 if( nArg==2 ){
8050 bail_on_error = booleanValue(azArg[1]);
8051 }else{
8052 eputz("Usage: .bail on|off\n");
8053 rc = 1;
8055 }else
8057 /* Undocumented. Legacy only. See "crnl" below */
8058 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
8059 if( nArg==2 ){
8060 if( booleanValue(azArg[1]) ){
8061 setBinaryMode(p->out, 1);
8062 }else{
8063 setTextMode(p->out, 1);
8065 }else{
8066 eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
8067 "Usage: .binary on|off\n");
8068 rc = 1;
8070 }else
8072 /* The undocumented ".breakpoint" command causes a call to the no-op
8073 ** routine named test_breakpoint().
8075 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
8076 test_breakpoint();
8077 }else
8079 #ifndef SQLITE_SHELL_FIDDLE
8080 if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
8081 failIfSafeMode(p, "cannot run .cd in safe mode");
8082 if( nArg==2 ){
8083 #if defined(_WIN32) || defined(WIN32)
8084 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8085 rc = !SetCurrentDirectoryW(z);
8086 sqlite3_free(z);
8087 #else
8088 rc = chdir(azArg[1]);
8089 #endif
8090 if( rc ){
8091 eputf("Cannot change to directory \"%s\"\n", azArg[1]);
8092 rc = 1;
8094 }else{
8095 eputz("Usage: .cd DIRECTORY\n");
8096 rc = 1;
8098 }else
8099 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8101 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
8102 if( nArg==2 ){
8103 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8104 }else{
8105 eputz("Usage: .changes on|off\n");
8106 rc = 1;
8108 }else
8110 #ifndef SQLITE_SHELL_FIDDLE
8111 /* Cancel output redirection, if it is currently set (by .testcase)
8112 ** Then read the content of the testcase-out.txt file and compare against
8113 ** azArg[1]. If there are differences, report an error and exit.
8115 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
8116 char *zRes = 0;
8117 output_reset(p);
8118 if( nArg!=2 ){
8119 eputz("Usage: .check GLOB-PATTERN\n");
8120 rc = 2;
8121 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8122 rc = 2;
8123 }else if( testcase_glob(azArg[1],zRes)==0 ){
8124 eputf("testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8125 p->zTestcase, azArg[1], zRes);
8126 rc = 1;
8127 }else{
8128 oputf("testcase-%s ok\n", p->zTestcase);
8129 p->nCheck++;
8131 sqlite3_free(zRes);
8132 }else
8133 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8135 #ifndef SQLITE_SHELL_FIDDLE
8136 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
8137 failIfSafeMode(p, "cannot run .clone in safe mode");
8138 if( nArg==2 ){
8139 tryToClone(p, azArg[1]);
8140 }else{
8141 eputz("Usage: .clone FILENAME\n");
8142 rc = 1;
8144 }else
8145 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8147 if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
8148 if( nArg==1 ){
8149 /* List available connections */
8150 int i;
8151 for(i=0; i<ArraySize(p->aAuxDb); i++){
8152 const char *zFile = p->aAuxDb[i].zDbFilename;
8153 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8154 zFile = "(not open)";
8155 }else if( zFile==0 ){
8156 zFile = "(memory)";
8157 }else if( zFile[0]==0 ){
8158 zFile = "(temporary-file)";
8160 if( p->pAuxDb == &p->aAuxDb[i] ){
8161 sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
8162 }else if( p->aAuxDb[i].db!=0 ){
8163 sputf(stdout, " %d: %s\n", i, zFile);
8166 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8167 int i = azArg[1][0] - '0';
8168 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8169 p->pAuxDb->db = p->db;
8170 p->pAuxDb = &p->aAuxDb[i];
8171 globalDb = p->db = p->pAuxDb->db;
8172 p->pAuxDb->db = 0;
8174 }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
8175 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8176 int i = azArg[2][0] - '0';
8177 if( i<0 || i>=ArraySize(p->aAuxDb) ){
8178 /* No-op */
8179 }else if( p->pAuxDb == &p->aAuxDb[i] ){
8180 eputz("cannot close the active database connection\n");
8181 rc = 1;
8182 }else if( p->aAuxDb[i].db ){
8183 session_close_all(p, i);
8184 close_db(p->aAuxDb[i].db);
8185 p->aAuxDb[i].db = 0;
8187 }else{
8188 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
8189 rc = 1;
8191 }else
8193 if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
8194 if( nArg==2 ){
8195 if( booleanValue(azArg[1]) ){
8196 setTextMode(p->out, 1);
8197 }else{
8198 setBinaryMode(p->out, 1);
8200 }else{
8201 #if !defined(_WIN32) && !defined(WIN32)
8202 eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
8203 #endif
8204 eputz("Usage: .crnl on|off\n");
8205 rc = 1;
8207 }else
8209 if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
8210 char **azName = 0;
8211 int nName = 0;
8212 sqlite3_stmt *pStmt;
8213 int i;
8214 open_db(p, 0);
8215 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8216 if( rc ){
8217 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8218 rc = 1;
8219 }else{
8220 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8221 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8222 const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8223 if( zSchema==0 || zFile==0 ) continue;
8224 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8225 shell_check_oom(azName);
8226 azName[nName*2] = strdup(zSchema);
8227 azName[nName*2+1] = strdup(zFile);
8228 nName++;
8231 sqlite3_finalize(pStmt);
8232 for(i=0; i<nName; i++){
8233 int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8234 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8235 const char *z = azName[i*2+1];
8236 oputf("%s: %s %s%s\n",
8237 azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
8238 eTxn==SQLITE_TXN_NONE ? "" :
8239 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8240 free(azName[i*2]);
8241 free(azName[i*2+1]);
8243 sqlite3_free(azName);
8244 }else
8246 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
8247 static const struct DbConfigChoices {
8248 const char *zName;
8249 int op;
8250 } aDbConfig[] = {
8251 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
8252 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
8253 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
8254 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
8255 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
8256 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
8257 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
8258 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8259 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
8260 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
8261 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8262 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
8263 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
8264 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
8265 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
8266 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
8267 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
8268 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
8270 int ii, v;
8271 open_db(p, 0);
8272 for(ii=0; ii<ArraySize(aDbConfig); ii++){
8273 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8274 if( nArg>=3 ){
8275 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8277 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8278 oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8279 if( nArg>1 ) break;
8281 if( nArg>1 && ii==ArraySize(aDbConfig) ){
8282 eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
8283 eputz("Enter \".dbconfig\" with no arguments for a list\n");
8285 }else
8287 #if SQLITE_SHELL_HAVE_RECOVER
8288 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
8289 rc = shell_dbinfo_command(p, nArg, azArg);
8290 }else
8292 if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
8293 open_db(p, 0);
8294 rc = recoverDatabaseCmd(p, nArg, azArg);
8295 }else
8296 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8298 if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
8299 char *zLike = 0;
8300 char *zSql;
8301 int i;
8302 int savedShowHeader = p->showHeader;
8303 int savedShellFlags = p->shellFlgs;
8304 ShellClearFlag(p,
8305 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8306 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8307 for(i=1; i<nArg; i++){
8308 if( azArg[i][0]=='-' ){
8309 const char *z = azArg[i]+1;
8310 if( z[0]=='-' ) z++;
8311 if( cli_strcmp(z,"preserve-rowids")==0 ){
8312 #ifdef SQLITE_OMIT_VIRTUALTABLE
8313 eputz("The --preserve-rowids option is not compatible"
8314 " with SQLITE_OMIT_VIRTUALTABLE\n");
8315 rc = 1;
8316 sqlite3_free(zLike);
8317 goto meta_command_exit;
8318 #else
8319 ShellSetFlag(p, SHFLG_PreserveRowid);
8320 #endif
8321 }else
8322 if( cli_strcmp(z,"newlines")==0 ){
8323 ShellSetFlag(p, SHFLG_Newlines);
8324 }else
8325 if( cli_strcmp(z,"data-only")==0 ){
8326 ShellSetFlag(p, SHFLG_DumpDataOnly);
8327 }else
8328 if( cli_strcmp(z,"nosys")==0 ){
8329 ShellSetFlag(p, SHFLG_DumpNoSys);
8330 }else
8332 eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8333 rc = 1;
8334 sqlite3_free(zLike);
8335 goto meta_command_exit;
8337 }else{
8338 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8339 ** only dump data for tables for which either the table name matches
8340 ** the LIKE pattern, or the table appears to be a shadow table of
8341 ** a virtual table for which the name matches the LIKE pattern.
8343 char *zExpr = sqlite3_mprintf(
8344 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8345 " SELECT 1 FROM sqlite_schema WHERE "
8346 " name LIKE %Q ESCAPE '\\' AND"
8347 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8348 " substr(o.name, 1, length(name)+1) == (name||'_')"
8349 ")", azArg[i], azArg[i]
8352 if( zLike ){
8353 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8354 }else{
8355 zLike = zExpr;
8360 open_db(p, 0);
8362 outputDumpWarning(p, zLike);
8363 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8364 /* When playing back a "dump", the content might appear in an order
8365 ** which causes immediate foreign key constraints to be violated.
8366 ** So disable foreign-key constraint enforcement to prevent problems. */
8367 oputz("PRAGMA foreign_keys=OFF;\n");
8368 oputz("BEGIN TRANSACTION;\n");
8370 p->writableSchema = 0;
8371 p->showHeader = 0;
8372 /* Set writable_schema=ON since doing so forces SQLite to initialize
8373 ** as much of the schema as it can even if the sqlite_schema table is
8374 ** corrupt. */
8375 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8376 p->nErr = 0;
8377 if( zLike==0 ) zLike = sqlite3_mprintf("true");
8378 zSql = sqlite3_mprintf(
8379 "SELECT name, type, sql FROM sqlite_schema AS o "
8380 "WHERE (%s) AND type=='table'"
8381 " AND sql NOT NULL"
8382 " ORDER BY tbl_name='sqlite_sequence', rowid",
8383 zLike
8385 run_schema_dump_query(p,zSql);
8386 sqlite3_free(zSql);
8387 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8388 zSql = sqlite3_mprintf(
8389 "SELECT sql FROM sqlite_schema AS o "
8390 "WHERE (%s) AND sql NOT NULL"
8391 " AND type IN ('index','trigger','view')",
8392 zLike
8394 run_table_dump_query(p, zSql);
8395 sqlite3_free(zSql);
8397 sqlite3_free(zLike);
8398 if( p->writableSchema ){
8399 oputz("PRAGMA writable_schema=OFF;\n");
8400 p->writableSchema = 0;
8402 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8403 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8404 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8405 oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8407 p->showHeader = savedShowHeader;
8408 p->shellFlgs = savedShellFlags;
8409 }else
8411 if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
8412 if( nArg==2 ){
8413 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8414 }else{
8415 eputz("Usage: .echo on|off\n");
8416 rc = 1;
8418 }else
8420 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
8421 if( nArg==2 ){
8422 p->autoEQPtest = 0;
8423 if( p->autoEQPtrace ){
8424 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8425 p->autoEQPtrace = 0;
8427 if( cli_strcmp(azArg[1],"full")==0 ){
8428 p->autoEQP = AUTOEQP_full;
8429 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
8430 p->autoEQP = AUTOEQP_trigger;
8431 #ifdef SQLITE_DEBUG
8432 }else if( cli_strcmp(azArg[1],"test")==0 ){
8433 p->autoEQP = AUTOEQP_on;
8434 p->autoEQPtest = 1;
8435 }else if( cli_strcmp(azArg[1],"trace")==0 ){
8436 p->autoEQP = AUTOEQP_full;
8437 p->autoEQPtrace = 1;
8438 open_db(p, 0);
8439 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8440 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8441 #endif
8442 }else{
8443 p->autoEQP = (u8)booleanValue(azArg[1]);
8445 }else{
8446 eputz("Usage: .eqp off|on|trace|trigger|full\n");
8447 rc = 1;
8449 }else
8451 #ifndef SQLITE_SHELL_FIDDLE
8452 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
8453 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8454 rc = 2;
8455 }else
8456 #endif
8458 /* The ".explain" command is automatic now. It is largely pointless. It
8459 ** retained purely for backwards compatibility */
8460 if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
8461 int val = 1;
8462 if( nArg>=2 ){
8463 if( cli_strcmp(azArg[1],"auto")==0 ){
8464 val = 99;
8465 }else{
8466 val = booleanValue(azArg[1]);
8469 if( val==1 && p->mode!=MODE_Explain ){
8470 p->normalMode = p->mode;
8471 p->mode = MODE_Explain;
8472 p->autoExplain = 0;
8473 }else if( val==0 ){
8474 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8475 p->autoExplain = 0;
8476 }else if( val==99 ){
8477 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8478 p->autoExplain = 1;
8480 }else
8482 #ifndef SQLITE_OMIT_VIRTUALTABLE
8483 if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
8484 if( p->bSafeMode ){
8485 eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
8486 azArg[0]);
8487 rc = 1;
8488 }else{
8489 open_db(p, 0);
8490 expertDotCommand(p, azArg, nArg);
8492 }else
8493 #endif
8495 if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
8496 static const struct {
8497 const char *zCtrlName; /* Name of a test-control option */
8498 int ctrlCode; /* Integer code for that option */
8499 const char *zUsage; /* Usage notes */
8500 } aCtrl[] = {
8501 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
8502 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
8503 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
8504 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
8505 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
8506 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8507 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
8508 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
8509 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
8510 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
8511 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8513 int filectrl = -1;
8514 int iCtrl = -1;
8515 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
8516 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
8517 int n2, i;
8518 const char *zCmd = 0;
8519 const char *zSchema = 0;
8521 open_db(p, 0);
8522 zCmd = nArg>=2 ? azArg[1] : "help";
8524 if( zCmd[0]=='-'
8525 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
8526 && nArg>=4
8528 zSchema = azArg[2];
8529 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8530 nArg -= 2;
8531 zCmd = azArg[1];
8534 /* The argument can optionally begin with "-" or "--" */
8535 if( zCmd[0]=='-' && zCmd[1] ){
8536 zCmd++;
8537 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8540 /* --help lists all file-controls */
8541 if( cli_strcmp(zCmd,"help")==0 ){
8542 oputz("Available file-controls:\n");
8543 for(i=0; i<ArraySize(aCtrl); i++){
8544 oputf(" .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8546 rc = 1;
8547 goto meta_command_exit;
8550 /* convert filectrl text option to value. allow any unique prefix
8551 ** of the option name, or a numerical value. */
8552 n2 = strlen30(zCmd);
8553 for(i=0; i<ArraySize(aCtrl); i++){
8554 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8555 if( filectrl<0 ){
8556 filectrl = aCtrl[i].ctrlCode;
8557 iCtrl = i;
8558 }else{
8559 eputf("Error: ambiguous file-control: \"%s\"\n"
8560 "Use \".filectrl --help\" for help\n", zCmd);
8561 rc = 1;
8562 goto meta_command_exit;
8566 if( filectrl<0 ){
8567 eputf("Error: unknown file-control: %s\n"
8568 "Use \".filectrl --help\" for help\n", zCmd);
8569 }else{
8570 switch(filectrl){
8571 case SQLITE_FCNTL_SIZE_LIMIT: {
8572 if( nArg!=2 && nArg!=3 ) break;
8573 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8574 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8575 isOk = 1;
8576 break;
8578 case SQLITE_FCNTL_LOCK_TIMEOUT:
8579 case SQLITE_FCNTL_CHUNK_SIZE: {
8580 int x;
8581 if( nArg!=3 ) break;
8582 x = (int)integerValue(azArg[2]);
8583 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8584 isOk = 2;
8585 break;
8587 case SQLITE_FCNTL_PERSIST_WAL:
8588 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8589 int x;
8590 if( nArg!=2 && nArg!=3 ) break;
8591 x = nArg==3 ? booleanValue(azArg[2]) : -1;
8592 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8593 iRes = x;
8594 isOk = 1;
8595 break;
8597 case SQLITE_FCNTL_DATA_VERSION:
8598 case SQLITE_FCNTL_HAS_MOVED: {
8599 int x;
8600 if( nArg!=2 ) break;
8601 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8602 iRes = x;
8603 isOk = 1;
8604 break;
8606 case SQLITE_FCNTL_TEMPFILENAME: {
8607 char *z = 0;
8608 if( nArg!=2 ) break;
8609 sqlite3_file_control(p->db, zSchema, filectrl, &z);
8610 if( z ){
8611 oputf("%s\n", z);
8612 sqlite3_free(z);
8614 isOk = 2;
8615 break;
8617 case SQLITE_FCNTL_RESERVE_BYTES: {
8618 int x;
8619 if( nArg>=3 ){
8620 x = atoi(azArg[2]);
8621 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8623 x = -1;
8624 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8625 oputf("%d\n", x);
8626 isOk = 2;
8627 break;
8631 if( isOk==0 && iCtrl>=0 ){
8632 oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8633 rc = 1;
8634 }else if( isOk==1 ){
8635 char zBuf[100];
8636 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8637 oputf("%s\n", zBuf);
8639 }else
8641 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
8642 ShellState data;
8643 int doStats = 0;
8644 memcpy(&data, p, sizeof(data));
8645 data.showHeader = 0;
8646 data.cMode = data.mode = MODE_Semi;
8647 if( nArg==2 && optionMatch(azArg[1], "indent") ){
8648 data.cMode = data.mode = MODE_Pretty;
8649 nArg = 1;
8651 if( nArg!=1 ){
8652 eputz("Usage: .fullschema ?--indent?\n");
8653 rc = 1;
8654 goto meta_command_exit;
8656 open_db(p, 0);
8657 rc = sqlite3_exec(p->db,
8658 "SELECT sql FROM"
8659 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8660 " FROM sqlite_schema UNION ALL"
8661 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8662 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8663 "ORDER BY x",
8664 callback, &data, 0
8666 if( rc==SQLITE_OK ){
8667 sqlite3_stmt *pStmt;
8668 rc = sqlite3_prepare_v2(p->db,
8669 "SELECT rowid FROM sqlite_schema"
8670 " WHERE name GLOB 'sqlite_stat[134]'",
8671 -1, &pStmt, 0);
8672 if( rc==SQLITE_OK ){
8673 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8674 sqlite3_finalize(pStmt);
8677 if( doStats==0 ){
8678 oputz("/* No STAT tables available */\n");
8679 }else{
8680 oputz("ANALYZE sqlite_schema;\n");
8681 data.cMode = data.mode = MODE_Insert;
8682 data.zDestTable = "sqlite_stat1";
8683 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8684 data.zDestTable = "sqlite_stat4";
8685 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8686 oputz("ANALYZE sqlite_schema;\n");
8688 }else
8690 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
8691 if( nArg==2 ){
8692 p->showHeader = booleanValue(azArg[1]);
8693 p->shellFlgs |= SHFLG_HeaderSet;
8694 }else{
8695 eputz("Usage: .headers on|off\n");
8696 rc = 1;
8698 }else
8700 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
8701 if( nArg>=2 ){
8702 n = showHelp(p->out, azArg[1]);
8703 if( n==0 ){
8704 oputf("Nothing matches '%s'\n", azArg[1]);
8706 }else{
8707 showHelp(p->out, 0);
8709 }else
8711 #ifndef SQLITE_SHELL_FIDDLE
8712 if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
8713 char *zTable = 0; /* Insert data into this table */
8714 char *zSchema = 0; /* within this schema (may default to "main") */
8715 char *zFile = 0; /* Name of file to extra content from */
8716 sqlite3_stmt *pStmt = NULL; /* A statement */
8717 int nCol; /* Number of columns in the table */
8718 int nByte; /* Number of bytes in an SQL string */
8719 int i, j; /* Loop counters */
8720 int needCommit; /* True to COMMIT or ROLLBACK at end */
8721 int nSep; /* Number of bytes in p->colSeparator[] */
8722 char *zSql; /* An SQL statement */
8723 char *zFullTabName; /* Table name with schema if applicable */
8724 ImportCtx sCtx; /* Reader context */
8725 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8726 int eVerbose = 0; /* Larger for more console output */
8727 int nSkip = 0; /* Initial lines to skip */
8728 int useOutputMode = 1; /* Use output mode to determine separators */
8729 char *zCreate = 0; /* CREATE TABLE statement text */
8731 failIfSafeMode(p, "cannot run .import in safe mode");
8732 memset(&sCtx, 0, sizeof(sCtx));
8733 if( p->mode==MODE_Ascii ){
8734 xRead = ascii_read_one_field;
8735 }else{
8736 xRead = csv_read_one_field;
8738 rc = 1;
8739 for(i=1; i<nArg; i++){
8740 char *z = azArg[i];
8741 if( z[0]=='-' && z[1]=='-' ) z++;
8742 if( z[0]!='-' ){
8743 if( zFile==0 ){
8744 zFile = z;
8745 }else if( zTable==0 ){
8746 zTable = z;
8747 }else{
8748 oputf("ERROR: extra argument: \"%s\". Usage:\n", z);
8749 showHelp(p->out, "import");
8750 goto meta_command_exit;
8752 }else if( cli_strcmp(z,"-v")==0 ){
8753 eVerbose++;
8754 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
8755 zSchema = azArg[++i];
8756 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
8757 nSkip = integerValue(azArg[++i]);
8758 }else if( cli_strcmp(z,"-ascii")==0 ){
8759 sCtx.cColSep = SEP_Unit[0];
8760 sCtx.cRowSep = SEP_Record[0];
8761 xRead = ascii_read_one_field;
8762 useOutputMode = 0;
8763 }else if( cli_strcmp(z,"-csv")==0 ){
8764 sCtx.cColSep = ',';
8765 sCtx.cRowSep = '\n';
8766 xRead = csv_read_one_field;
8767 useOutputMode = 0;
8768 }else{
8769 oputf("ERROR: unknown option: \"%s\". Usage:\n", z);
8770 showHelp(p->out, "import");
8771 goto meta_command_exit;
8774 if( zTable==0 ){
8775 oputf("ERROR: missing %s argument. Usage:\n",
8776 zFile==0 ? "FILE" : "TABLE");
8777 showHelp(p->out, "import");
8778 goto meta_command_exit;
8780 seenInterrupt = 0;
8781 open_db(p, 0);
8782 if( useOutputMode ){
8783 /* If neither the --csv or --ascii options are specified, then set
8784 ** the column and row separator characters from the output mode. */
8785 nSep = strlen30(p->colSeparator);
8786 if( nSep==0 ){
8787 eputz("Error: non-null column separator required for import\n");
8788 goto meta_command_exit;
8790 if( nSep>1 ){
8791 eputz("Error: multi-character column separators not allowed"
8792 " for import\n");
8793 goto meta_command_exit;
8795 nSep = strlen30(p->rowSeparator);
8796 if( nSep==0 ){
8797 eputz("Error: non-null row separator required for import\n");
8798 goto meta_command_exit;
8800 if( nSep==2 && p->mode==MODE_Csv
8801 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
8803 /* When importing CSV (only), if the row separator is set to the
8804 ** default output row separator, change it to the default input
8805 ** row separator. This avoids having to maintain different input
8806 ** and output row separators. */
8807 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8808 nSep = strlen30(p->rowSeparator);
8810 if( nSep>1 ){
8811 eputz("Error: multi-character row separators not allowed"
8812 " for import\n");
8813 goto meta_command_exit;
8815 sCtx.cColSep = (u8)p->colSeparator[0];
8816 sCtx.cRowSep = (u8)p->rowSeparator[0];
8818 sCtx.zFile = zFile;
8819 sCtx.nLine = 1;
8820 if( sCtx.zFile[0]=='|' ){
8821 #ifdef SQLITE_OMIT_POPEN
8822 eputz("Error: pipes are not supported in this OS\n");
8823 goto meta_command_exit;
8824 #else
8825 sCtx.in = popen(sCtx.zFile+1, "r");
8826 sCtx.zFile = "<pipe>";
8827 sCtx.xCloser = pclose;
8828 #endif
8829 }else{
8830 sCtx.in = fopen(sCtx.zFile, "rb");
8831 sCtx.xCloser = fclose;
8833 if( sCtx.in==0 ){
8834 eputf("Error: cannot open \"%s\"\n", zFile);
8835 goto meta_command_exit;
8837 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8838 char zSep[2];
8839 zSep[1] = 0;
8840 zSep[0] = sCtx.cColSep;
8841 oputz("Column separator ");
8842 output_c_string(zSep);
8843 oputz(", row separator ");
8844 zSep[0] = sCtx.cRowSep;
8845 output_c_string(zSep);
8846 oputz("\n");
8848 sCtx.z = sqlite3_malloc64(120);
8849 if( sCtx.z==0 ){
8850 import_cleanup(&sCtx);
8851 shell_out_of_memory();
8853 /* Below, resources must be freed before exit. */
8854 while( (nSkip--)>0 ){
8855 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8857 if( zSchema!=0 ){
8858 zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8859 }else{
8860 zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8862 zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8863 if( zSql==0 || zFullTabName==0 ){
8864 import_cleanup(&sCtx);
8865 shell_out_of_memory();
8867 nByte = strlen30(zSql);
8868 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8869 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
8870 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8871 sqlite3 *dbCols = 0;
8872 char *zRenames = 0;
8873 char *zColDefs;
8874 zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
8875 while( xRead(&sCtx) ){
8876 zAutoColumn(sCtx.z, &dbCols, 0);
8877 if( sCtx.cTerm!=sCtx.cColSep ) break;
8879 zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8880 if( zRenames!=0 ){
8881 sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8882 "Columns renamed during .import %s due to duplicates:\n"
8883 "%s\n", sCtx.zFile, zRenames);
8884 sqlite3_free(zRenames);
8886 assert(dbCols==0);
8887 if( zColDefs==0 ){
8888 eputf("%s: empty file\n", sCtx.zFile);
8889 import_fail:
8890 sqlite3_free(zCreate);
8891 sqlite3_free(zSql);
8892 sqlite3_free(zFullTabName);
8893 import_cleanup(&sCtx);
8894 rc = 1;
8895 goto meta_command_exit;
8897 zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8898 if( eVerbose>=1 ){
8899 oputf("%s\n", zCreate);
8901 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8902 if( rc ){
8903 eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8904 goto import_fail;
8906 sqlite3_free(zCreate);
8907 zCreate = 0;
8908 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8910 if( rc ){
8911 if (pStmt) sqlite3_finalize(pStmt);
8912 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8913 goto import_fail;
8915 sqlite3_free(zSql);
8916 nCol = sqlite3_column_count(pStmt);
8917 sqlite3_finalize(pStmt);
8918 pStmt = 0;
8919 if( nCol==0 ) return 0; /* no columns, no error */
8920 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8921 if( zSql==0 ){
8922 import_cleanup(&sCtx);
8923 shell_out_of_memory();
8925 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
8926 j = strlen30(zSql);
8927 for(i=1; i<nCol; i++){
8928 zSql[j++] = ',';
8929 zSql[j++] = '?';
8931 zSql[j++] = ')';
8932 zSql[j] = 0;
8933 if( eVerbose>=2 ){
8934 oputf("Insert using: %s\n", zSql);
8936 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8937 if( rc ){
8938 eputf("Error: %s\n", sqlite3_errmsg(p->db));
8939 if (pStmt) sqlite3_finalize(pStmt);
8940 goto import_fail;
8942 sqlite3_free(zSql);
8943 sqlite3_free(zFullTabName);
8944 needCommit = sqlite3_get_autocommit(p->db);
8945 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8947 int startLine = sCtx.nLine;
8948 for(i=0; i<nCol; i++){
8949 char *z = xRead(&sCtx);
8951 ** Did we reach end-of-file before finding any columns?
8952 ** If so, stop instead of NULL filling the remaining columns.
8954 if( z==0 && i==0 ) break;
8956 ** Did we reach end-of-file OR end-of-line before finding any
8957 ** columns in ASCII mode? If so, stop instead of NULL filling
8958 ** the remaining columns.
8960 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8962 ** For CSV mode, per RFC 4180, accept EOF in lieu of final
8963 ** record terminator but only for last field of multi-field row.
8964 ** (If there are too few fields, it's not valid CSV anyway.)
8966 if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
8967 z = "";
8969 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8970 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8971 eputf("%s:%d: expected %d columns but found %d"
8972 " - filling the rest with NULL\n",
8973 sCtx.zFile, startLine, nCol, i+1);
8974 i += 2;
8975 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8978 if( sCtx.cTerm==sCtx.cColSep ){
8980 xRead(&sCtx);
8981 i++;
8982 }while( sCtx.cTerm==sCtx.cColSep );
8983 eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
8984 sCtx.zFile, startLine, nCol, i);
8986 if( i>=nCol ){
8987 sqlite3_step(pStmt);
8988 rc = sqlite3_reset(pStmt);
8989 if( rc!=SQLITE_OK ){
8990 eputf("%s:%d: INSERT failed: %s\n",
8991 sCtx.zFile, startLine, sqlite3_errmsg(p->db));
8992 sCtx.nErr++;
8993 }else{
8994 sCtx.nRow++;
8997 }while( sCtx.cTerm!=EOF );
8999 import_cleanup(&sCtx);
9000 sqlite3_finalize(pStmt);
9001 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9002 if( eVerbose>0 ){
9003 oputf("Added %d rows with %d errors using %d lines of input\n",
9004 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9006 }else
9007 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9009 #ifndef SQLITE_UNTESTABLE
9010 if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
9011 char *zSql;
9012 char *zCollist = 0;
9013 sqlite3_stmt *pStmt;
9014 int tnum = 0;
9015 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
9016 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9017 int i;
9018 if( !ShellHasFlag(p,SHFLG_TestingMode) ){
9019 eputf(".%s unavailable without --unsafe-testing\n",
9020 "imposter");
9021 rc = 1;
9022 goto meta_command_exit;
9024 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9025 eputz("Usage: .imposter INDEX IMPOSTER\n"
9026 " .imposter off\n");
9027 /* Also allowed, but not documented:
9029 ** .imposter TABLE IMPOSTER
9031 ** where TABLE is a WITHOUT ROWID table. In that case, the
9032 ** imposter is another WITHOUT ROWID table with the columns in
9033 ** storage order. */
9034 rc = 1;
9035 goto meta_command_exit;
9037 open_db(p, 0);
9038 if( nArg==2 ){
9039 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9040 goto meta_command_exit;
9042 zSql = sqlite3_mprintf(
9043 "SELECT rootpage, 0 FROM sqlite_schema"
9044 " WHERE name='%q' AND type='index'"
9045 "UNION ALL "
9046 "SELECT rootpage, 1 FROM sqlite_schema"
9047 " WHERE name='%q' AND type='table'"
9048 " AND sql LIKE '%%without%%rowid%%'",
9049 azArg[1], azArg[1]
9051 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9052 sqlite3_free(zSql);
9053 if( sqlite3_step(pStmt)==SQLITE_ROW ){
9054 tnum = sqlite3_column_int(pStmt, 0);
9055 isWO = sqlite3_column_int(pStmt, 1);
9057 sqlite3_finalize(pStmt);
9058 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9059 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9060 sqlite3_free(zSql);
9061 i = 0;
9062 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9063 char zLabel[20];
9064 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9065 i++;
9066 if( zCol==0 ){
9067 if( sqlite3_column_int(pStmt,1)==-1 ){
9068 zCol = "_ROWID_";
9069 }else{
9070 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9071 zCol = zLabel;
9074 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9075 lenPK = (int)strlen(zCollist);
9077 if( zCollist==0 ){
9078 zCollist = sqlite3_mprintf("\"%w\"", zCol);
9079 }else{
9080 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9083 sqlite3_finalize(pStmt);
9084 if( i==0 || tnum==0 ){
9085 eputf("no such index: \"%s\"\n", azArg[1]);
9086 rc = 1;
9087 sqlite3_free(zCollist);
9088 goto meta_command_exit;
9090 if( lenPK==0 ) lenPK = 100000;
9091 zSql = sqlite3_mprintf(
9092 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9093 azArg[2], zCollist, lenPK, zCollist);
9094 sqlite3_free(zCollist);
9095 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9096 if( rc==SQLITE_OK ){
9097 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9098 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9099 if( rc ){
9100 eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9101 }else{
9102 sputf(stdout, "%s;\n", zSql);
9103 sputf(stdout, "WARNING: writing to an imposter table will corrupt"
9104 " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
9106 }else{
9107 eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9108 rc = 1;
9110 sqlite3_free(zSql);
9111 }else
9112 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9114 #ifdef SQLITE_ENABLE_IOTRACE
9115 if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
9116 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9117 if( iotrace && iotrace!=stdout ) fclose(iotrace);
9118 iotrace = 0;
9119 if( nArg<2 ){
9120 sqlite3IoTrace = 0;
9121 }else if( cli_strcmp(azArg[1], "-")==0 ){
9122 sqlite3IoTrace = iotracePrintf;
9123 iotrace = stdout;
9124 }else{
9125 iotrace = fopen(azArg[1], "w");
9126 if( iotrace==0 ){
9127 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9128 sqlite3IoTrace = 0;
9129 rc = 1;
9130 }else{
9131 sqlite3IoTrace = iotracePrintf;
9134 }else
9135 #endif
9137 if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
9138 static const struct {
9139 const char *zLimitName; /* Name of a limit */
9140 int limitCode; /* Integer code for that limit */
9141 } aLimit[] = {
9142 { "length", SQLITE_LIMIT_LENGTH },
9143 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
9144 { "column", SQLITE_LIMIT_COLUMN },
9145 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
9146 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
9147 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
9148 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
9149 { "attached", SQLITE_LIMIT_ATTACHED },
9150 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
9151 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
9152 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
9153 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
9155 int i, n2;
9156 open_db(p, 0);
9157 if( nArg==1 ){
9158 for(i=0; i<ArraySize(aLimit); i++){
9159 sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
9160 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9162 }else if( nArg>3 ){
9163 eputz("Usage: .limit NAME ?NEW-VALUE?\n");
9164 rc = 1;
9165 goto meta_command_exit;
9166 }else{
9167 int iLimit = -1;
9168 n2 = strlen30(azArg[1]);
9169 for(i=0; i<ArraySize(aLimit); i++){
9170 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9171 if( iLimit<0 ){
9172 iLimit = i;
9173 }else{
9174 eputf("ambiguous limit: \"%s\"\n", azArg[1]);
9175 rc = 1;
9176 goto meta_command_exit;
9180 if( iLimit<0 ){
9181 eputf("unknown limit: \"%s\"\n"
9182 "enter \".limits\" with no arguments for a list.\n",
9183 azArg[1]);
9184 rc = 1;
9185 goto meta_command_exit;
9187 if( nArg==3 ){
9188 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9189 (int)integerValue(azArg[2]));
9191 sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
9192 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9194 }else
9196 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
9197 open_db(p, 0);
9198 lintDotCommand(p, azArg, nArg);
9199 }else
9201 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9202 if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
9203 const char *zFile, *zProc;
9204 char *zErrMsg = 0;
9205 failIfSafeMode(p, "cannot run .load in safe mode");
9206 if( nArg<2 || azArg[1][0]==0 ){
9207 /* Must have a non-empty FILE. (Will not load self.) */
9208 eputz("Usage: .load FILE ?ENTRYPOINT?\n");
9209 rc = 1;
9210 goto meta_command_exit;
9212 zFile = azArg[1];
9213 zProc = nArg>=3 ? azArg[2] : 0;
9214 open_db(p, 0);
9215 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9216 if( rc!=SQLITE_OK ){
9217 eputf("Error: %s\n", zErrMsg);
9218 sqlite3_free(zErrMsg);
9219 rc = 1;
9221 }else
9222 #endif
9224 if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
9225 if( nArg!=2 ){
9226 eputz("Usage: .log FILENAME\n");
9227 rc = 1;
9228 }else{
9229 const char *zFile = azArg[1];
9230 if( p->bSafeMode
9231 && cli_strcmp(zFile,"on")!=0
9232 && cli_strcmp(zFile,"off")!=0
9234 sputz(stdout, "cannot set .log to anything other"
9235 " than \"on\" or \"off\"\n");
9236 zFile = "off";
9238 output_file_close(p->pLog);
9239 if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
9240 p->pLog = output_file_open(zFile, 0);
9242 }else
9244 if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
9245 const char *zMode = 0;
9246 const char *zTabname = 0;
9247 int i, n2;
9248 ColModeOpts cmOpts = ColModeOpts_default;
9249 for(i=1; i<nArg; i++){
9250 const char *z = azArg[i];
9251 if( optionMatch(z,"wrap") && i+1<nArg ){
9252 cmOpts.iWrap = integerValue(azArg[++i]);
9253 }else if( optionMatch(z,"ww") ){
9254 cmOpts.bWordWrap = 1;
9255 }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9256 cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9257 }else if( optionMatch(z,"quote") ){
9258 cmOpts.bQuote = 1;
9259 }else if( optionMatch(z,"noquote") ){
9260 cmOpts.bQuote = 0;
9261 }else if( zMode==0 ){
9262 zMode = z;
9263 /* Apply defaults for qbox pseudo-mode. If that
9264 * overwrites already-set values, user was informed of this.
9266 if( cli_strcmp(z, "qbox")==0 ){
9267 ColModeOpts cmo = ColModeOpts_default_qbox;
9268 zMode = "box";
9269 cmOpts = cmo;
9271 }else if( zTabname==0 ){
9272 zTabname = z;
9273 }else if( z[0]=='-' ){
9274 eputf("unknown option: %s\n", z);
9275 eputz("options:\n"
9276 " --noquote\n"
9277 " --quote\n"
9278 " --wordwrap on/off\n"
9279 " --wrap N\n"
9280 " --ww\n");
9281 rc = 1;
9282 goto meta_command_exit;
9283 }else{
9284 eputf("extra argument: \"%s\"\n", z);
9285 rc = 1;
9286 goto meta_command_exit;
9289 if( zMode==0 ){
9290 if( p->mode==MODE_Column
9291 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9293 oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9294 modeDescr[p->mode], p->cmOpts.iWrap,
9295 p->cmOpts.bWordWrap ? "on" : "off",
9296 p->cmOpts.bQuote ? "" : "no");
9297 }else{
9298 oputf("current output mode: %s\n", modeDescr[p->mode]);
9300 zMode = modeDescr[p->mode];
9302 n2 = strlen30(zMode);
9303 if( cli_strncmp(zMode,"lines",n2)==0 ){
9304 p->mode = MODE_Line;
9305 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9306 }else if( cli_strncmp(zMode,"columns",n2)==0 ){
9307 p->mode = MODE_Column;
9308 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9309 p->showHeader = 1;
9311 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9312 p->cmOpts = cmOpts;
9313 }else if( cli_strncmp(zMode,"list",n2)==0 ){
9314 p->mode = MODE_List;
9315 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9316 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9317 }else if( cli_strncmp(zMode,"html",n2)==0 ){
9318 p->mode = MODE_Html;
9319 }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
9320 p->mode = MODE_Tcl;
9321 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9322 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9323 }else if( cli_strncmp(zMode,"csv",n2)==0 ){
9324 p->mode = MODE_Csv;
9325 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9326 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9327 }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
9328 p->mode = MODE_List;
9329 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9330 }else if( cli_strncmp(zMode,"insert",n2)==0 ){
9331 p->mode = MODE_Insert;
9332 set_table_name(p, zTabname ? zTabname : "table");
9333 }else if( cli_strncmp(zMode,"quote",n2)==0 ){
9334 p->mode = MODE_Quote;
9335 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9336 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9337 }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
9338 p->mode = MODE_Ascii;
9339 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9340 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9341 }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
9342 p->mode = MODE_Markdown;
9343 p->cmOpts = cmOpts;
9344 }else if( cli_strncmp(zMode,"table",n2)==0 ){
9345 p->mode = MODE_Table;
9346 p->cmOpts = cmOpts;
9347 }else if( cli_strncmp(zMode,"box",n2)==0 ){
9348 p->mode = MODE_Box;
9349 p->cmOpts = cmOpts;
9350 }else if( cli_strncmp(zMode,"count",n2)==0 ){
9351 p->mode = MODE_Count;
9352 }else if( cli_strncmp(zMode,"off",n2)==0 ){
9353 p->mode = MODE_Off;
9354 }else if( cli_strncmp(zMode,"json",n2)==0 ){
9355 p->mode = MODE_Json;
9356 }else{
9357 eputz("Error: mode should be one of: "
9358 "ascii box column csv html insert json line list markdown "
9359 "qbox quote table tabs tcl\n");
9360 rc = 1;
9362 p->cMode = p->mode;
9363 }else
9365 #ifndef SQLITE_SHELL_FIDDLE
9366 if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
9367 if( nArg!=2 ){
9368 eputz("Usage: .nonce NONCE\n");
9369 rc = 1;
9370 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
9371 eputf("line %d: incorrect nonce: \"%s\"\n",
9372 p->lineno, azArg[1]);
9373 exit(1);
9374 }else{
9375 p->bSafeMode = 0;
9376 return 0; /* Return immediately to bypass the safe mode reset
9377 ** at the end of this procedure */
9379 }else
9380 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9382 if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
9383 if( nArg==2 ){
9384 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9385 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9386 }else{
9387 eputz("Usage: .nullvalue STRING\n");
9388 rc = 1;
9390 }else
9392 if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
9393 const char *zFN = 0; /* Pointer to constant filename */
9394 char *zNewFilename = 0; /* Name of the database file to open */
9395 int iName = 1; /* Index in azArg[] of the filename */
9396 int newFlag = 0; /* True to delete file before opening */
9397 int openMode = SHELL_OPEN_UNSPEC;
9399 /* Check for command-line arguments */
9400 for(iName=1; iName<nArg; iName++){
9401 const char *z = azArg[iName];
9402 #ifndef SQLITE_SHELL_FIDDLE
9403 if( optionMatch(z,"new") ){
9404 newFlag = 1;
9405 #ifdef SQLITE_HAVE_ZLIB
9406 }else if( optionMatch(z, "zip") ){
9407 openMode = SHELL_OPEN_ZIPFILE;
9408 #endif
9409 }else if( optionMatch(z, "append") ){
9410 openMode = SHELL_OPEN_APPENDVFS;
9411 }else if( optionMatch(z, "readonly") ){
9412 openMode = SHELL_OPEN_READONLY;
9413 }else if( optionMatch(z, "nofollow") ){
9414 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9415 #ifndef SQLITE_OMIT_DESERIALIZE
9416 }else if( optionMatch(z, "deserialize") ){
9417 openMode = SHELL_OPEN_DESERIALIZE;
9418 }else if( optionMatch(z, "hexdb") ){
9419 openMode = SHELL_OPEN_HEXDB;
9420 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9421 p->szMax = integerValue(azArg[++iName]);
9422 #endif /* SQLITE_OMIT_DESERIALIZE */
9423 }else
9424 #endif /* !SQLITE_SHELL_FIDDLE */
9425 if( z[0]=='-' ){
9426 eputf("unknown option: %s\n", z);
9427 rc = 1;
9428 goto meta_command_exit;
9429 }else if( zFN ){
9430 eputf("extra argument: \"%s\"\n", z);
9431 rc = 1;
9432 goto meta_command_exit;
9433 }else{
9434 zFN = z;
9438 /* Close the existing database */
9439 session_close_all(p, -1);
9440 close_db(p->db);
9441 p->db = 0;
9442 p->pAuxDb->zDbFilename = 0;
9443 sqlite3_free(p->pAuxDb->zFreeOnClose);
9444 p->pAuxDb->zFreeOnClose = 0;
9445 p->openMode = openMode;
9446 p->openFlags = 0;
9447 p->szMax = 0;
9449 /* If a filename is specified, try to open it first */
9450 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9451 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9452 #ifndef SQLITE_SHELL_FIDDLE
9453 if( p->bSafeMode
9454 && p->openMode!=SHELL_OPEN_HEXDB
9455 && zFN
9456 && cli_strcmp(zFN,":memory:")!=0
9458 failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9460 #else
9461 /* WASM mode has its own sandboxed pseudo-filesystem. */
9462 #endif
9463 if( zFN ){
9464 zNewFilename = sqlite3_mprintf("%s", zFN);
9465 shell_check_oom(zNewFilename);
9466 }else{
9467 zNewFilename = 0;
9469 p->pAuxDb->zDbFilename = zNewFilename;
9470 open_db(p, OPEN_DB_KEEPALIVE);
9471 if( p->db==0 ){
9472 eputf("Error: cannot open '%s'\n", zNewFilename);
9473 sqlite3_free(zNewFilename);
9474 }else{
9475 p->pAuxDb->zFreeOnClose = zNewFilename;
9478 if( p->db==0 ){
9479 /* As a fall-back open a TEMP database */
9480 p->pAuxDb->zDbFilename = 0;
9481 open_db(p, 0);
9483 }else
9485 #ifndef SQLITE_SHELL_FIDDLE
9486 if( (c=='o'
9487 && (cli_strncmp(azArg[0], "output", n)==0
9488 || cli_strncmp(azArg[0], "once", n)==0))
9489 || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
9491 char *zFile = 0;
9492 int bTxtMode = 0;
9493 int i;
9494 int eMode = 0;
9495 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
9496 static const char *zBomUtf8 = "\xef\xbb\xbf";
9497 const char *zBom = 0;
9499 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9500 if( c=='e' ){
9501 eMode = 'x';
9502 bOnce = 2;
9503 }else if( cli_strncmp(azArg[0],"once",n)==0 ){
9504 bOnce = 1;
9506 for(i=1; i<nArg; i++){
9507 char *z = azArg[i];
9508 if( z[0]=='-' ){
9509 if( z[1]=='-' ) z++;
9510 if( cli_strcmp(z,"-bom")==0 ){
9511 zBom = zBomUtf8;
9512 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
9513 eMode = 'x'; /* spreadsheet */
9514 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
9515 eMode = 'e'; /* text editor */
9516 }else{
9517 oputf("ERROR: unknown option: \"%s\". Usage:\n", azArg[i]);
9518 showHelp(p->out, azArg[0]);
9519 rc = 1;
9520 goto meta_command_exit;
9522 }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9523 zFile = sqlite3_mprintf("%s", z);
9524 if( zFile && zFile[0]=='|' ){
9525 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9526 break;
9528 }else{
9529 oputf("ERROR: extra parameter: \"%s\". Usage:\n", azArg[i]);
9530 showHelp(p->out, azArg[0]);
9531 rc = 1;
9532 sqlite3_free(zFile);
9533 goto meta_command_exit;
9536 if( zFile==0 ){
9537 zFile = sqlite3_mprintf("stdout");
9539 if( bOnce ){
9540 p->outCount = 2;
9541 }else{
9542 p->outCount = 0;
9544 output_reset(p);
9545 #ifndef SQLITE_NOHAVE_SYSTEM
9546 if( eMode=='e' || eMode=='x' ){
9547 p->doXdgOpen = 1;
9548 outputModePush(p);
9549 if( eMode=='x' ){
9550 /* spreadsheet mode. Output as CSV. */
9551 newTempFile(p, "csv");
9552 ShellClearFlag(p, SHFLG_Echo);
9553 p->mode = MODE_Csv;
9554 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9555 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9556 }else{
9557 /* text editor mode */
9558 newTempFile(p, "txt");
9559 bTxtMode = 1;
9561 sqlite3_free(zFile);
9562 zFile = sqlite3_mprintf("%s", p->zTempFile);
9564 #endif /* SQLITE_NOHAVE_SYSTEM */
9565 shell_check_oom(zFile);
9566 if( zFile[0]=='|' ){
9567 #ifdef SQLITE_OMIT_POPEN
9568 eputz("Error: pipes are not supported in this OS\n");
9569 rc = 1;
9570 output_redir(p, stdout);
9571 #else
9572 FILE *pfPipe = popen(zFile + 1, "w");
9573 if( pfPipe==0 ){
9574 eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
9575 rc = 1;
9576 }else{
9577 output_redir(p, pfPipe);
9578 if( zBom ) oputz(zBom);
9579 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9581 #endif
9582 }else{
9583 FILE *pfFile = output_file_open(zFile, bTxtMode);
9584 if( pfFile==0 ){
9585 if( cli_strcmp(zFile,"off")!=0 ){
9586 eputf("Error: cannot write to \"%s\"\n", zFile);
9588 rc = 1;
9589 } else {
9590 output_redir(p, pfFile);
9591 if( zBom ) oputz(zBom);
9592 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9595 sqlite3_free(zFile);
9596 }else
9597 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9599 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
9600 open_db(p,0);
9601 if( nArg<=1 ) goto parameter_syntax_error;
9603 /* .parameter clear
9604 ** Clear all bind parameters by dropping the TEMP table that holds them.
9606 if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
9607 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9608 0, 0, 0);
9609 }else
9611 /* .parameter list
9612 ** List all bind parameters.
9614 if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
9615 sqlite3_stmt *pStmt = 0;
9616 int rx;
9617 int len = 0;
9618 rx = sqlite3_prepare_v2(p->db,
9619 "SELECT max(length(key)) "
9620 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9621 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9622 len = sqlite3_column_int(pStmt, 0);
9623 if( len>40 ) len = 40;
9625 sqlite3_finalize(pStmt);
9626 pStmt = 0;
9627 if( len ){
9628 rx = sqlite3_prepare_v2(p->db,
9629 "SELECT key, quote(value) "
9630 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9631 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9632 oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9633 sqlite3_column_text(pStmt,1));
9635 sqlite3_finalize(pStmt);
9637 }else
9639 /* .parameter init
9640 ** Make sure the TEMP table used to hold bind parameters exists.
9641 ** Create it if necessary.
9643 if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
9644 bind_table_init(p);
9645 }else
9647 /* .parameter set NAME VALUE
9648 ** Set or reset a bind parameter. NAME should be the full parameter
9649 ** name exactly as it appears in the query. (ex: $abc, @def). The
9650 ** VALUE can be in either SQL literal notation, or if not it will be
9651 ** understood to be a text string.
9653 if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
9654 int rx;
9655 char *zSql;
9656 sqlite3_stmt *pStmt;
9657 const char *zKey = azArg[2];
9658 const char *zValue = azArg[3];
9659 bind_table_init(p);
9660 zSql = sqlite3_mprintf(
9661 "REPLACE INTO temp.sqlite_parameters(key,value)"
9662 "VALUES(%Q,%s);", zKey, zValue);
9663 shell_check_oom(zSql);
9664 pStmt = 0;
9665 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9666 sqlite3_free(zSql);
9667 if( rx!=SQLITE_OK ){
9668 sqlite3_finalize(pStmt);
9669 pStmt = 0;
9670 zSql = sqlite3_mprintf(
9671 "REPLACE INTO temp.sqlite_parameters(key,value)"
9672 "VALUES(%Q,%Q);", zKey, zValue);
9673 shell_check_oom(zSql);
9674 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9675 sqlite3_free(zSql);
9676 if( rx!=SQLITE_OK ){
9677 oputf("Error: %s\n", sqlite3_errmsg(p->db));
9678 sqlite3_finalize(pStmt);
9679 pStmt = 0;
9680 rc = 1;
9683 sqlite3_step(pStmt);
9684 sqlite3_finalize(pStmt);
9685 }else
9687 /* .parameter unset NAME
9688 ** Remove the NAME binding from the parameter binding table, if it
9689 ** exists.
9691 if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
9692 char *zSql = sqlite3_mprintf(
9693 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9694 shell_check_oom(zSql);
9695 sqlite3_exec(p->db, zSql, 0, 0, 0);
9696 sqlite3_free(zSql);
9697 }else
9698 /* If no command name matches, show a syntax error */
9699 parameter_syntax_error:
9700 showHelp(p->out, "parameter");
9701 }else
9703 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
9704 int i;
9705 for(i=1; i<nArg; i++){
9706 if( i>1 ) oputz(" ");
9707 oputz(azArg[i]);
9709 oputz("\n");
9710 }else
9712 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9713 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
9714 int i;
9715 int nn = 0;
9716 p->flgProgress = 0;
9717 p->mxProgress = 0;
9718 p->nProgress = 0;
9719 for(i=1; i<nArg; i++){
9720 const char *z = azArg[i];
9721 if( z[0]=='-' ){
9722 z++;
9723 if( z[0]=='-' ) z++;
9724 if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
9725 p->flgProgress |= SHELL_PROGRESS_QUIET;
9726 continue;
9728 if( cli_strcmp(z,"reset")==0 ){
9729 p->flgProgress |= SHELL_PROGRESS_RESET;
9730 continue;
9732 if( cli_strcmp(z,"once")==0 ){
9733 p->flgProgress |= SHELL_PROGRESS_ONCE;
9734 continue;
9736 if( cli_strcmp(z,"limit")==0 ){
9737 if( i+1>=nArg ){
9738 eputz("Error: missing argument on --limit\n");
9739 rc = 1;
9740 goto meta_command_exit;
9741 }else{
9742 p->mxProgress = (int)integerValue(azArg[++i]);
9744 continue;
9746 eputf("Error: unknown option: \"%s\"\n", azArg[i]);
9747 rc = 1;
9748 goto meta_command_exit;
9749 }else{
9750 nn = (int)integerValue(z);
9753 open_db(p, 0);
9754 sqlite3_progress_handler(p->db, nn, progress_handler, p);
9755 }else
9756 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9758 if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
9759 if( nArg >= 2) {
9760 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9762 if( nArg >= 3) {
9763 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9765 }else
9767 #ifndef SQLITE_SHELL_FIDDLE
9768 if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
9769 rc = 2;
9770 }else
9771 #endif
9773 #ifndef SQLITE_SHELL_FIDDLE
9774 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
9775 FILE *inSaved = p->in;
9776 int savedLineno = p->lineno;
9777 failIfSafeMode(p, "cannot run .read in safe mode");
9778 if( nArg!=2 ){
9779 eputz("Usage: .read FILE\n");
9780 rc = 1;
9781 goto meta_command_exit;
9783 if( azArg[1][0]=='|' ){
9784 #ifdef SQLITE_OMIT_POPEN
9785 eputz("Error: pipes are not supported in this OS\n");
9786 rc = 1;
9787 p->out = stdout;
9788 #else
9789 p->in = popen(azArg[1]+1, "r");
9790 if( p->in==0 ){
9791 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9792 rc = 1;
9793 }else{
9794 rc = process_input(p);
9795 pclose(p->in);
9797 #endif
9798 }else if( (p->in = openChrSource(azArg[1]))==0 ){
9799 eputf("Error: cannot open \"%s\"\n", azArg[1]);
9800 rc = 1;
9801 }else{
9802 rc = process_input(p);
9803 fclose(p->in);
9805 p->in = inSaved;
9806 p->lineno = savedLineno;
9807 }else
9808 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9810 #ifndef SQLITE_SHELL_FIDDLE
9811 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
9812 const char *zSrcFile;
9813 const char *zDb;
9814 sqlite3 *pSrc;
9815 sqlite3_backup *pBackup;
9816 int nTimeout = 0;
9818 failIfSafeMode(p, "cannot run .restore in safe mode");
9819 if( nArg==2 ){
9820 zSrcFile = azArg[1];
9821 zDb = "main";
9822 }else if( nArg==3 ){
9823 zSrcFile = azArg[2];
9824 zDb = azArg[1];
9825 }else{
9826 eputz("Usage: .restore ?DB? FILE\n");
9827 rc = 1;
9828 goto meta_command_exit;
9830 rc = sqlite3_open(zSrcFile, &pSrc);
9831 if( rc!=SQLITE_OK ){
9832 eputf("Error: cannot open \"%s\"\n", zSrcFile);
9833 close_db(pSrc);
9834 return 1;
9836 open_db(p, 0);
9837 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9838 if( pBackup==0 ){
9839 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9840 close_db(pSrc);
9841 return 1;
9843 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9844 || rc==SQLITE_BUSY ){
9845 if( rc==SQLITE_BUSY ){
9846 if( nTimeout++ >= 3 ) break;
9847 sqlite3_sleep(100);
9850 sqlite3_backup_finish(pBackup);
9851 if( rc==SQLITE_DONE ){
9852 rc = 0;
9853 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9854 eputz("Error: source database is busy\n");
9855 rc = 1;
9856 }else{
9857 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9858 rc = 1;
9860 close_db(pSrc);
9861 }else
9862 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9864 if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
9865 if( nArg==2 ){
9866 if( cli_strcmp(azArg[1], "vm")==0 ){
9867 p->scanstatsOn = 3;
9868 }else
9869 if( cli_strcmp(azArg[1], "est")==0 ){
9870 p->scanstatsOn = 2;
9871 }else{
9872 p->scanstatsOn = (u8)booleanValue(azArg[1]);
9874 open_db(p, 0);
9875 sqlite3_db_config(
9876 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
9878 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9879 eputz("Warning: .scanstats not available in this build.\n");
9880 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
9881 if( p->scanstatsOn==3 ){
9882 eputz("Warning: \".scanstats vm\" not available in this build.\n");
9884 #endif
9885 }else{
9886 eputz("Usage: .scanstats on|off|est\n");
9887 rc = 1;
9889 }else
9891 if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
9892 ShellText sSelect;
9893 ShellState data;
9894 char *zErrMsg = 0;
9895 const char *zDiv = "(";
9896 const char *zName = 0;
9897 int iSchema = 0;
9898 int bDebug = 0;
9899 int bNoSystemTabs = 0;
9900 int ii;
9902 open_db(p, 0);
9903 memcpy(&data, p, sizeof(data));
9904 data.showHeader = 0;
9905 data.cMode = data.mode = MODE_Semi;
9906 initText(&sSelect);
9907 for(ii=1; ii<nArg; ii++){
9908 if( optionMatch(azArg[ii],"indent") ){
9909 data.cMode = data.mode = MODE_Pretty;
9910 }else if( optionMatch(azArg[ii],"debug") ){
9911 bDebug = 1;
9912 }else if( optionMatch(azArg[ii],"nosys") ){
9913 bNoSystemTabs = 1;
9914 }else if( azArg[ii][0]=='-' ){
9915 eputf("Unknown option: \"%s\"\n", azArg[ii]);
9916 rc = 1;
9917 goto meta_command_exit;
9918 }else if( zName==0 ){
9919 zName = azArg[ii];
9920 }else{
9921 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9922 rc = 1;
9923 goto meta_command_exit;
9926 if( zName!=0 ){
9927 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9928 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9929 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9930 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9931 if( isSchema ){
9932 char *new_argv[2], *new_colv[2];
9933 new_argv[0] = sqlite3_mprintf(
9934 "CREATE TABLE %s (\n"
9935 " type text,\n"
9936 " name text,\n"
9937 " tbl_name text,\n"
9938 " rootpage integer,\n"
9939 " sql text\n"
9940 ")", zName);
9941 shell_check_oom(new_argv[0]);
9942 new_argv[1] = 0;
9943 new_colv[0] = "sql";
9944 new_colv[1] = 0;
9945 callback(&data, 1, new_argv, new_colv);
9946 sqlite3_free(new_argv[0]);
9949 if( zDiv ){
9950 sqlite3_stmt *pStmt = 0;
9951 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9952 -1, &pStmt, 0);
9953 if( rc ){
9954 eputf("Error: %s\n", sqlite3_errmsg(p->db));
9955 sqlite3_finalize(pStmt);
9956 rc = 1;
9957 goto meta_command_exit;
9959 appendText(&sSelect, "SELECT sql FROM", 0);
9960 iSchema = 0;
9961 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9962 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9963 char zScNum[30];
9964 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9965 appendText(&sSelect, zDiv, 0);
9966 zDiv = " UNION ALL ";
9967 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9968 if( sqlite3_stricmp(zDb, "main")!=0 ){
9969 appendText(&sSelect, zDb, '\'');
9970 }else{
9971 appendText(&sSelect, "NULL", 0);
9973 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9974 appendText(&sSelect, zScNum, 0);
9975 appendText(&sSelect, " AS snum, ", 0);
9976 appendText(&sSelect, zDb, '\'');
9977 appendText(&sSelect, " AS sname FROM ", 0);
9978 appendText(&sSelect, zDb, quoteChar(zDb));
9979 appendText(&sSelect, ".sqlite_schema", 0);
9981 sqlite3_finalize(pStmt);
9982 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9983 if( zName ){
9984 appendText(&sSelect,
9985 " UNION ALL SELECT shell_module_schema(name),"
9986 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9989 #endif
9990 appendText(&sSelect, ") WHERE ", 0);
9991 if( zName ){
9992 char *zQarg = sqlite3_mprintf("%Q", zName);
9993 int bGlob;
9994 shell_check_oom(zQarg);
9995 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9996 strchr(zName, '[') != 0;
9997 if( strchr(zName, '.') ){
9998 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9999 }else{
10000 appendText(&sSelect, "lower(tbl_name)", 0);
10002 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10003 appendText(&sSelect, zQarg, 0);
10004 if( !bGlob ){
10005 appendText(&sSelect, " ESCAPE '\\' ", 0);
10007 appendText(&sSelect, " AND ", 0);
10008 sqlite3_free(zQarg);
10010 if( bNoSystemTabs ){
10011 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10013 appendText(&sSelect, "sql IS NOT NULL"
10014 " ORDER BY snum, rowid", 0);
10015 if( bDebug ){
10016 oputf("SQL: %s;\n", sSelect.z);
10017 }else{
10018 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10020 freeText(&sSelect);
10022 if( zErrMsg ){
10023 eputf("Error: %s\n", zErrMsg);
10024 sqlite3_free(zErrMsg);
10025 rc = 1;
10026 }else if( rc != SQLITE_OK ){
10027 eputz("Error: querying schema information\n");
10028 rc = 1;
10029 }else{
10030 rc = 0;
10032 }else
10034 if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
10035 || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0)
10037 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10038 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10039 }else
10041 #if defined(SQLITE_ENABLE_SESSION)
10042 if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
10043 struct AuxDb *pAuxDb = p->pAuxDb;
10044 OpenSession *pSession = &pAuxDb->aSession[0];
10045 char **azCmd = &azArg[1];
10046 int iSes = 0;
10047 int nCmd = nArg - 1;
10048 int i;
10049 if( nArg<=1 ) goto session_syntax_error;
10050 open_db(p, 0);
10051 if( nArg>=3 ){
10052 for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10053 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10055 if( iSes<pAuxDb->nSession ){
10056 pSession = &pAuxDb->aSession[iSes];
10057 azCmd++;
10058 nCmd--;
10059 }else{
10060 pSession = &pAuxDb->aSession[0];
10061 iSes = 0;
10065 /* .session attach TABLE
10066 ** Invoke the sqlite3session_attach() interface to attach a particular
10067 ** table so that it is never filtered.
10069 if( cli_strcmp(azCmd[0],"attach")==0 ){
10070 if( nCmd!=2 ) goto session_syntax_error;
10071 if( pSession->p==0 ){
10072 session_not_open:
10073 eputz("ERROR: No sessions are open\n");
10074 }else{
10075 rc = sqlite3session_attach(pSession->p, azCmd[1]);
10076 if( rc ){
10077 eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
10078 rc = 0;
10081 }else
10083 /* .session changeset FILE
10084 ** .session patchset FILE
10085 ** Write a changeset or patchset into a file. The file is overwritten.
10087 if( cli_strcmp(azCmd[0],"changeset")==0
10088 || cli_strcmp(azCmd[0],"patchset")==0
10090 FILE *out = 0;
10091 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10092 if( nCmd!=2 ) goto session_syntax_error;
10093 if( pSession->p==0 ) goto session_not_open;
10094 out = fopen(azCmd[1], "wb");
10095 if( out==0 ){
10096 eputf("ERROR: cannot open \"%s\" for writing\n",
10097 azCmd[1]);
10098 }else{
10099 int szChng;
10100 void *pChng;
10101 if( azCmd[0][0]=='c' ){
10102 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10103 }else{
10104 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10106 if( rc ){
10107 sputf(stdout, "Error: error code %d\n", rc);
10108 rc = 0;
10110 if( pChng
10111 && fwrite(pChng, szChng, 1, out)!=1 ){
10112 eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
10114 sqlite3_free(pChng);
10115 fclose(out);
10117 }else
10119 /* .session close
10120 ** Close the identified session
10122 if( cli_strcmp(azCmd[0], "close")==0 ){
10123 if( nCmd!=1 ) goto session_syntax_error;
10124 if( pAuxDb->nSession ){
10125 session_close(pSession);
10126 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10128 }else
10130 /* .session enable ?BOOLEAN?
10131 ** Query or set the enable flag
10133 if( cli_strcmp(azCmd[0], "enable")==0 ){
10134 int ii;
10135 if( nCmd>2 ) goto session_syntax_error;
10136 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10137 if( pAuxDb->nSession ){
10138 ii = sqlite3session_enable(pSession->p, ii);
10139 oputf("session %s enable flag = %d\n", pSession->zName, ii);
10141 }else
10143 /* .session filter GLOB ....
10144 ** Set a list of GLOB patterns of table names to be excluded.
10146 if( cli_strcmp(azCmd[0], "filter")==0 ){
10147 int ii, nByte;
10148 if( nCmd<2 ) goto session_syntax_error;
10149 if( pAuxDb->nSession ){
10150 for(ii=0; ii<pSession->nFilter; ii++){
10151 sqlite3_free(pSession->azFilter[ii]);
10153 sqlite3_free(pSession->azFilter);
10154 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10155 pSession->azFilter = sqlite3_malloc( nByte );
10156 shell_check_oom( pSession->azFilter );
10157 for(ii=1; ii<nCmd; ii++){
10158 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10159 shell_check_oom(x);
10161 pSession->nFilter = ii-1;
10163 }else
10165 /* .session indirect ?BOOLEAN?
10166 ** Query or set the indirect flag
10168 if( cli_strcmp(azCmd[0], "indirect")==0 ){
10169 int ii;
10170 if( nCmd>2 ) goto session_syntax_error;
10171 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10172 if( pAuxDb->nSession ){
10173 ii = sqlite3session_indirect(pSession->p, ii);
10174 oputf("session %s indirect flag = %d\n", pSession->zName, ii);
10176 }else
10178 /* .session isempty
10179 ** Determine if the session is empty
10181 if( cli_strcmp(azCmd[0], "isempty")==0 ){
10182 int ii;
10183 if( nCmd!=1 ) goto session_syntax_error;
10184 if( pAuxDb->nSession ){
10185 ii = sqlite3session_isempty(pSession->p);
10186 oputf("session %s isempty flag = %d\n", pSession->zName, ii);
10188 }else
10190 /* .session list
10191 ** List all currently open sessions
10193 if( cli_strcmp(azCmd[0],"list")==0 ){
10194 for(i=0; i<pAuxDb->nSession; i++){
10195 oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
10197 }else
10199 /* .session open DB NAME
10200 ** Open a new session called NAME on the attached database DB.
10201 ** DB is normally "main".
10203 if( cli_strcmp(azCmd[0],"open")==0 ){
10204 char *zName;
10205 if( nCmd!=3 ) goto session_syntax_error;
10206 zName = azCmd[2];
10207 if( zName[0]==0 ) goto session_syntax_error;
10208 for(i=0; i<pAuxDb->nSession; i++){
10209 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10210 eputf("Session \"%s\" already exists\n", zName);
10211 goto meta_command_exit;
10214 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10215 eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10216 goto meta_command_exit;
10218 pSession = &pAuxDb->aSession[pAuxDb->nSession];
10219 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10220 if( rc ){
10221 eputf("Cannot open session: error code=%d\n", rc);
10222 rc = 0;
10223 goto meta_command_exit;
10225 pSession->nFilter = 0;
10226 sqlite3session_table_filter(pSession->p, session_filter, pSession);
10227 pAuxDb->nSession++;
10228 pSession->zName = sqlite3_mprintf("%s", zName);
10229 shell_check_oom(pSession->zName);
10230 }else
10231 /* If no command name matches, show a syntax error */
10232 session_syntax_error:
10233 showHelp(p->out, "session");
10234 }else
10235 #endif
10237 #ifdef SQLITE_DEBUG
10238 /* Undocumented commands for internal testing. Subject to change
10239 ** without notice. */
10240 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
10241 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10242 int i, v;
10243 for(i=1; i<nArg; i++){
10244 v = booleanValue(azArg[i]);
10245 oputf("%s: %d 0x%x\n", azArg[i], v, v);
10248 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
10249 int i; sqlite3_int64 v;
10250 for(i=1; i<nArg; i++){
10251 char zBuf[200];
10252 v = integerValue(azArg[i]);
10253 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10254 oputz(zBuf);
10257 }else
10258 #endif
10260 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
10261 int bIsInit = 0; /* True to initialize the SELFTEST table */
10262 int bVerbose = 0; /* Verbose output */
10263 int bSelftestExists; /* True if SELFTEST already exists */
10264 int i, k; /* Loop counters */
10265 int nTest = 0; /* Number of tests runs */
10266 int nErr = 0; /* Number of errors seen */
10267 ShellText str; /* Answer for a query */
10268 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10270 open_db(p,0);
10271 for(i=1; i<nArg; i++){
10272 const char *z = azArg[i];
10273 if( z[0]=='-' && z[1]=='-' ) z++;
10274 if( cli_strcmp(z,"-init")==0 ){
10275 bIsInit = 1;
10276 }else
10277 if( cli_strcmp(z,"-v")==0 ){
10278 bVerbose++;
10279 }else
10281 eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
10282 eputz("Should be one of: --init -v\n");
10283 rc = 1;
10284 goto meta_command_exit;
10287 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10288 != SQLITE_OK ){
10289 bSelftestExists = 0;
10290 }else{
10291 bSelftestExists = 1;
10293 if( bIsInit ){
10294 createSelftestTable(p);
10295 bSelftestExists = 1;
10297 initText(&str);
10298 appendText(&str, "x", 0);
10299 for(k=bSelftestExists; k>=0; k--){
10300 if( k==1 ){
10301 rc = sqlite3_prepare_v2(p->db,
10302 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10303 -1, &pStmt, 0);
10304 }else{
10305 rc = sqlite3_prepare_v2(p->db,
10306 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10307 " (1,'run','PRAGMA integrity_check','ok')",
10308 -1, &pStmt, 0);
10310 if( rc ){
10311 eputz("Error querying the selftest table\n");
10312 rc = 1;
10313 sqlite3_finalize(pStmt);
10314 goto meta_command_exit;
10316 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10317 int tno = sqlite3_column_int(pStmt, 0);
10318 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10319 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10320 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10322 if( zOp==0 ) continue;
10323 if( zSql==0 ) continue;
10324 if( zAns==0 ) continue;
10325 k = 0;
10326 if( bVerbose>0 ){
10327 sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
10329 if( cli_strcmp(zOp,"memo")==0 ){
10330 oputf("%s\n", zSql);
10331 }else
10332 if( cli_strcmp(zOp,"run")==0 ){
10333 char *zErrMsg = 0;
10334 str.n = 0;
10335 str.z[0] = 0;
10336 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10337 nTest++;
10338 if( bVerbose ){
10339 oputf("Result: %s\n", str.z);
10341 if( rc || zErrMsg ){
10342 nErr++;
10343 rc = 1;
10344 oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10345 sqlite3_free(zErrMsg);
10346 }else if( cli_strcmp(zAns,str.z)!=0 ){
10347 nErr++;
10348 rc = 1;
10349 oputf("%d: Expected: [%s]\n", tno, zAns);
10350 oputf("%d: Got: [%s]\n", tno, str.z);
10353 else{
10354 eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10355 rc = 1;
10356 break;
10358 } /* End loop over rows of content from SELFTEST */
10359 sqlite3_finalize(pStmt);
10360 } /* End loop over k */
10361 freeText(&str);
10362 oputf("%d errors out of %d tests\n", nErr, nTest);
10363 }else
10365 if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
10366 if( nArg<2 || nArg>3 ){
10367 eputz("Usage: .separator COL ?ROW?\n");
10368 rc = 1;
10370 if( nArg>=2 ){
10371 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10372 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10374 if( nArg>=3 ){
10375 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10376 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10378 }else
10380 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
10381 const char *zLike = 0; /* Which table to checksum. 0 means everything */
10382 int i; /* Loop counter */
10383 int bSchema = 0; /* Also hash the schema */
10384 int bSeparate = 0; /* Hash each table separately */
10385 int iSize = 224; /* Hash algorithm to use */
10386 int bDebug = 0; /* Only show the query that would have run */
10387 sqlite3_stmt *pStmt; /* For querying tables names */
10388 char *zSql; /* SQL to be run */
10389 char *zSep; /* Separator */
10390 ShellText sSql; /* Complete SQL for the query to run the hash */
10391 ShellText sQuery; /* Set of queries used to read all content */
10392 open_db(p, 0);
10393 for(i=1; i<nArg; i++){
10394 const char *z = azArg[i];
10395 if( z[0]=='-' ){
10396 z++;
10397 if( z[0]=='-' ) z++;
10398 if( cli_strcmp(z,"schema")==0 ){
10399 bSchema = 1;
10400 }else
10401 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
10402 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
10404 iSize = atoi(&z[5]);
10405 }else
10406 if( cli_strcmp(z,"debug")==0 ){
10407 bDebug = 1;
10408 }else
10410 eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
10411 showHelp(p->out, azArg[0]);
10412 rc = 1;
10413 goto meta_command_exit;
10415 }else if( zLike ){
10416 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10417 rc = 1;
10418 goto meta_command_exit;
10419 }else{
10420 zLike = z;
10421 bSeparate = 1;
10422 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10425 if( bSchema ){
10426 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10427 " WHERE type='table' AND coalesce(rootpage,0)>1"
10428 " UNION ALL SELECT 'sqlite_schema'"
10429 " ORDER BY 1 collate nocase";
10430 }else{
10431 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10432 " WHERE type='table' AND coalesce(rootpage,0)>1"
10433 " AND name NOT LIKE 'sqlite_%'"
10434 " ORDER BY 1 collate nocase";
10436 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10437 initText(&sQuery);
10438 initText(&sSql);
10439 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10440 zSep = "VALUES(";
10441 while( SQLITE_ROW==sqlite3_step(pStmt) ){
10442 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10443 if( zTab==0 ) continue;
10444 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10445 if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
10446 appendText(&sQuery,"SELECT * FROM ", 0);
10447 appendText(&sQuery,zTab,'"');
10448 appendText(&sQuery," NOT INDEXED;", 0);
10449 }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
10450 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10451 " ORDER BY name;", 0);
10452 }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
10453 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10454 " ORDER BY name;", 0);
10455 }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
10456 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10457 " ORDER BY tbl,idx;", 0);
10458 }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
10459 appendText(&sQuery, "SELECT * FROM ", 0);
10460 appendText(&sQuery, zTab, 0);
10461 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10463 appendText(&sSql, zSep, 0);
10464 appendText(&sSql, sQuery.z, '\'');
10465 sQuery.n = 0;
10466 appendText(&sSql, ",", 0);
10467 appendText(&sSql, zTab, '\'');
10468 zSep = "),(";
10470 sqlite3_finalize(pStmt);
10471 if( bSeparate ){
10472 zSql = sqlite3_mprintf(
10473 "%s))"
10474 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10475 " FROM [sha3sum$query]",
10476 sSql.z, iSize);
10477 }else{
10478 zSql = sqlite3_mprintf(
10479 "%s))"
10480 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10481 " FROM [sha3sum$query]",
10482 sSql.z, iSize);
10484 shell_check_oom(zSql);
10485 freeText(&sQuery);
10486 freeText(&sSql);
10487 if( bDebug ){
10488 oputf("%s\n", zSql);
10489 }else{
10490 shell_exec(p, zSql, 0);
10492 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10494 int lrc;
10495 char *zRevText = /* Query for reversible to-blob-to-text check */
10496 "SELECT lower(name) as tname FROM sqlite_schema\n"
10497 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10498 "AND name NOT LIKE 'sqlite_%%'%s\n"
10499 "ORDER BY 1 collate nocase";
10500 zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
10501 zRevText = sqlite3_mprintf(
10502 /* lower-case query is first run, producing upper-case query. */
10503 "with tabcols as materialized(\n"
10504 "select tname, cname\n"
10505 "from ("
10506 " select printf('\"%%w\"',ss.tname) as tname,"
10507 " printf('\"%%w\"',ti.name) as cname\n"
10508 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10509 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10510 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10511 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10512 "FROM '||tname||' WHERE '\n"
10513 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10514 "|| ' AND typeof('||cname||')=''text'' ',\n"
10515 "' OR ') as query, tname from tabcols group by tname)"
10516 , zRevText);
10517 shell_check_oom(zRevText);
10518 if( bDebug ) oputf("%s\n", zRevText);
10519 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
10520 if( lrc!=SQLITE_OK ){
10521 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
10522 ** user does cruel and unnatural things like ".limit expr_depth 0". */
10523 rc = 1;
10524 }else{
10525 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
10526 lrc = SQLITE_ROW==sqlite3_step(pStmt);
10527 if( lrc ){
10528 const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
10529 sqlite3_stmt *pCheckStmt;
10530 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
10531 if( bDebug ) oputf("%s\n", zGenQuery);
10532 if( lrc!=SQLITE_OK ){
10533 rc = 1;
10534 }else{
10535 if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
10536 double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
10537 if( countIrreversible>0 ){
10538 int sz = (int)(countIrreversible + 0.5);
10539 eputf("Digest includes %d invalidly encoded text field%s.\n",
10540 sz, (sz>1)? "s": "");
10543 sqlite3_finalize(pCheckStmt);
10545 sqlite3_finalize(pStmt);
10548 if( rc ) eputz(".sha3sum failed.\n");
10549 sqlite3_free(zRevText);
10551 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10552 sqlite3_free(zSql);
10553 }else
10555 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10556 if( c=='s'
10557 && (cli_strncmp(azArg[0], "shell", n)==0
10558 || cli_strncmp(azArg[0],"system",n)==0)
10560 char *zCmd;
10561 int i, x;
10562 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10563 if( nArg<2 ){
10564 eputz("Usage: .system COMMAND\n");
10565 rc = 1;
10566 goto meta_command_exit;
10568 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10569 for(i=2; i<nArg && zCmd!=0; i++){
10570 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10571 zCmd, azArg[i]);
10573 consoleRestore();
10574 x = zCmd!=0 ? system(zCmd) : 1;
10575 consoleRenewSetup();
10576 sqlite3_free(zCmd);
10577 if( x ) eputf("System command returns %d\n", x);
10578 }else
10579 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10581 if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
10582 static const char *azBool[] = { "off", "on", "trigger", "full"};
10583 const char *zOut;
10584 int i;
10585 if( nArg!=1 ){
10586 eputz("Usage: .show\n");
10587 rc = 1;
10588 goto meta_command_exit;
10590 oputf("%12.12s: %s\n","echo",
10591 azBool[ShellHasFlag(p, SHFLG_Echo)]);
10592 oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10593 oputf("%12.12s: %s\n","explain",
10594 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10595 oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10596 if( p->mode==MODE_Column
10597 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10599 oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10600 modeDescr[p->mode], p->cmOpts.iWrap,
10601 p->cmOpts.bWordWrap ? "on" : "off",
10602 p->cmOpts.bQuote ? "" : "no");
10603 }else{
10604 oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
10606 oputf("%12.12s: ", "nullvalue");
10607 output_c_string(p->nullValue);
10608 oputz("\n");
10609 oputf("%12.12s: %s\n","output",
10610 strlen30(p->outfile) ? p->outfile : "stdout");
10611 oputf("%12.12s: ", "colseparator");
10612 output_c_string(p->colSeparator);
10613 oputz("\n");
10614 oputf("%12.12s: ", "rowseparator");
10615 output_c_string(p->rowSeparator);
10616 oputz("\n");
10617 switch( p->statsOn ){
10618 case 0: zOut = "off"; break;
10619 default: zOut = "on"; break;
10620 case 2: zOut = "stmt"; break;
10621 case 3: zOut = "vmstep"; break;
10623 oputf("%12.12s: %s\n","stats", zOut);
10624 oputf("%12.12s: ", "width");
10625 for (i=0;i<p->nWidth;i++) {
10626 oputf("%d ", p->colWidth[i]);
10628 oputz("\n");
10629 oputf("%12.12s: %s\n", "filename",
10630 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10631 }else
10633 if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
10634 if( nArg==2 ){
10635 if( cli_strcmp(azArg[1],"stmt")==0 ){
10636 p->statsOn = 2;
10637 }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
10638 p->statsOn = 3;
10639 }else{
10640 p->statsOn = (u8)booleanValue(azArg[1]);
10642 }else if( nArg==1 ){
10643 display_stats(p->db, p, 0);
10644 }else{
10645 eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
10646 rc = 1;
10648 }else
10650 if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
10651 || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
10652 || cli_strncmp(azArg[0], "indexes", n)==0) )
10654 sqlite3_stmt *pStmt;
10655 char **azResult;
10656 int nRow, nAlloc;
10657 int ii;
10658 ShellText s;
10659 initText(&s);
10660 open_db(p, 0);
10661 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10662 if( rc ){
10663 sqlite3_finalize(pStmt);
10664 return shellDatabaseError(p->db);
10667 if( nArg>2 && c=='i' ){
10668 /* It is an historical accident that the .indexes command shows an error
10669 ** when called with the wrong number of arguments whereas the .tables
10670 ** command does not. */
10671 eputz("Usage: .indexes ?LIKE-PATTERN?\n");
10672 rc = 1;
10673 sqlite3_finalize(pStmt);
10674 goto meta_command_exit;
10676 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10677 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10678 if( zDbName==0 ) continue;
10679 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10680 if( sqlite3_stricmp(zDbName, "main")==0 ){
10681 appendText(&s, "SELECT name FROM ", 0);
10682 }else{
10683 appendText(&s, "SELECT ", 0);
10684 appendText(&s, zDbName, '\'');
10685 appendText(&s, "||'.'||name FROM ", 0);
10687 appendText(&s, zDbName, '"');
10688 appendText(&s, ".sqlite_schema ", 0);
10689 if( c=='t' ){
10690 appendText(&s," WHERE type IN ('table','view')"
10691 " AND name NOT LIKE 'sqlite_%'"
10692 " AND name LIKE ?1", 0);
10693 }else{
10694 appendText(&s," WHERE type='index'"
10695 " AND tbl_name LIKE ?1", 0);
10698 rc = sqlite3_finalize(pStmt);
10699 if( rc==SQLITE_OK ){
10700 appendText(&s, " ORDER BY 1", 0);
10701 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10703 freeText(&s);
10704 if( rc ) return shellDatabaseError(p->db);
10706 /* Run the SQL statement prepared by the above block. Store the results
10707 ** as an array of nul-terminated strings in azResult[]. */
10708 nRow = nAlloc = 0;
10709 azResult = 0;
10710 if( nArg>1 ){
10711 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10712 }else{
10713 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10715 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10716 if( nRow>=nAlloc ){
10717 char **azNew;
10718 int n2 = nAlloc*2 + 10;
10719 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10720 shell_check_oom(azNew);
10721 nAlloc = n2;
10722 azResult = azNew;
10724 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10725 shell_check_oom(azResult[nRow]);
10726 nRow++;
10728 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10729 rc = shellDatabaseError(p->db);
10732 /* Pretty-print the contents of array azResult[] to the output */
10733 if( rc==0 && nRow>0 ){
10734 int len, maxlen = 0;
10735 int i, j;
10736 int nPrintCol, nPrintRow;
10737 for(i=0; i<nRow; i++){
10738 len = strlen30(azResult[i]);
10739 if( len>maxlen ) maxlen = len;
10741 nPrintCol = 80/(maxlen+2);
10742 if( nPrintCol<1 ) nPrintCol = 1;
10743 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10744 for(i=0; i<nPrintRow; i++){
10745 for(j=i; j<nRow; j+=nPrintRow){
10746 char *zSp = j<nPrintRow ? "" : " ";
10747 oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
10749 oputz("\n");
10753 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10754 sqlite3_free(azResult);
10755 }else
10757 #ifndef SQLITE_SHELL_FIDDLE
10758 /* Begin redirecting output to the file "testcase-out.txt" */
10759 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
10760 output_reset(p);
10761 p->out = output_file_open("testcase-out.txt", 0);
10762 if( p->out==0 ){
10763 eputz("Error: cannot open 'testcase-out.txt'\n");
10765 if( nArg>=2 ){
10766 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10767 }else{
10768 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10770 }else
10771 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10773 #ifndef SQLITE_UNTESTABLE
10774 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
10775 static const struct {
10776 const char *zCtrlName; /* Name of a test-control option */
10777 int ctrlCode; /* Integer code for that option */
10778 int unSafe; /* Not valid unless --unsafe-testing */
10779 const char *zUsage; /* Usage notes */
10780 } aCtrl[] = {
10781 {"always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
10782 {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
10783 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10784 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10785 {"byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
10786 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
10787 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10788 {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" },
10789 {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10790 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
10791 {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" },
10792 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
10793 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
10794 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
10795 #ifdef YYCOVERAGE
10796 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
10797 #endif
10798 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
10799 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
10800 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
10801 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
10802 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
10803 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
10804 {"tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
10805 {"uselongdouble", SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
10807 int testctrl = -1;
10808 int iCtrl = -1;
10809 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10810 int isOk = 0;
10811 int i, n2;
10812 const char *zCmd = 0;
10814 open_db(p, 0);
10815 zCmd = nArg>=2 ? azArg[1] : "help";
10817 /* The argument can optionally begin with "-" or "--" */
10818 if( zCmd[0]=='-' && zCmd[1] ){
10819 zCmd++;
10820 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10823 /* --help lists all test-controls */
10824 if( cli_strcmp(zCmd,"help")==0 ){
10825 oputz("Available test-controls:\n");
10826 for(i=0; i<ArraySize(aCtrl); i++){
10827 if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
10828 oputf(" .testctrl %s %s\n",
10829 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10831 rc = 1;
10832 goto meta_command_exit;
10835 /* convert testctrl text option to value. allow any unique prefix
10836 ** of the option name, or a numerical value. */
10837 n2 = strlen30(zCmd);
10838 for(i=0; i<ArraySize(aCtrl); i++){
10839 if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
10840 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10841 if( testctrl<0 ){
10842 testctrl = aCtrl[i].ctrlCode;
10843 iCtrl = i;
10844 }else{
10845 eputf("Error: ambiguous test-control: \"%s\"\n"
10846 "Use \".testctrl --help\" for help\n", zCmd);
10847 rc = 1;
10848 goto meta_command_exit;
10852 if( testctrl<0 ){
10853 eputf("Error: unknown test-control: %s\n"
10854 "Use \".testctrl --help\" for help\n", zCmd);
10855 }else{
10856 switch(testctrl){
10858 /* sqlite3_test_control(int, db, int) */
10859 case SQLITE_TESTCTRL_OPTIMIZATIONS:
10860 case SQLITE_TESTCTRL_FK_NO_ACTION:
10861 if( nArg==3 ){
10862 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10863 rc2 = sqlite3_test_control(testctrl, p->db, opt);
10864 isOk = 3;
10866 break;
10868 /* sqlite3_test_control(int) */
10869 case SQLITE_TESTCTRL_PRNG_SAVE:
10870 case SQLITE_TESTCTRL_PRNG_RESTORE:
10871 case SQLITE_TESTCTRL_BYTEORDER:
10872 if( nArg==2 ){
10873 rc2 = sqlite3_test_control(testctrl);
10874 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10876 break;
10878 /* sqlite3_test_control(int, uint) */
10879 case SQLITE_TESTCTRL_PENDING_BYTE:
10880 if( nArg==3 ){
10881 unsigned int opt = (unsigned int)integerValue(azArg[2]);
10882 rc2 = sqlite3_test_control(testctrl, opt);
10883 isOk = 3;
10885 break;
10887 /* sqlite3_test_control(int, int, sqlite3*) */
10888 case SQLITE_TESTCTRL_PRNG_SEED:
10889 if( nArg==3 || nArg==4 ){
10890 int ii = (int)integerValue(azArg[2]);
10891 sqlite3 *db;
10892 if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
10893 sqlite3_randomness(sizeof(ii),&ii);
10894 sputf(stdout, "-- random seed: %d\n", ii);
10896 if( nArg==3 ){
10897 db = 0;
10898 }else{
10899 db = p->db;
10900 /* Make sure the schema has been loaded */
10901 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10903 rc2 = sqlite3_test_control(testctrl, ii, db);
10904 isOk = 3;
10906 break;
10908 /* sqlite3_test_control(int, int) */
10909 case SQLITE_TESTCTRL_ASSERT:
10910 case SQLITE_TESTCTRL_ALWAYS:
10911 if( nArg==3 ){
10912 int opt = booleanValue(azArg[2]);
10913 rc2 = sqlite3_test_control(testctrl, opt);
10914 isOk = 1;
10916 break;
10918 /* sqlite3_test_control(int, int) */
10919 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10920 case SQLITE_TESTCTRL_NEVER_CORRUPT:
10921 if( nArg==3 ){
10922 int opt = booleanValue(azArg[2]);
10923 rc2 = sqlite3_test_control(testctrl, opt);
10924 isOk = 3;
10926 break;
10928 /* sqlite3_test_control(int, int) */
10929 case SQLITE_TESTCTRL_USELONGDOUBLE: {
10930 int opt = -1;
10931 if( nArg==3 ){
10932 if( cli_strcmp(azArg[2],"default")==0 ){
10933 opt = 2;
10934 }else{
10935 opt = booleanValue(azArg[2]);
10938 rc2 = sqlite3_test_control(testctrl, opt);
10939 isOk = 1;
10940 break;
10943 /* sqlite3_test_control(sqlite3*) */
10944 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10945 rc2 = sqlite3_test_control(testctrl, p->db);
10946 isOk = 3;
10947 break;
10949 case SQLITE_TESTCTRL_IMPOSTER:
10950 if( nArg==5 ){
10951 rc2 = sqlite3_test_control(testctrl, p->db,
10952 azArg[2],
10953 integerValue(azArg[3]),
10954 integerValue(azArg[4]));
10955 isOk = 3;
10957 break;
10959 case SQLITE_TESTCTRL_SEEK_COUNT: {
10960 u64 x = 0;
10961 rc2 = sqlite3_test_control(testctrl, p->db, &x);
10962 oputf("%llu\n", x);
10963 isOk = 3;
10964 break;
10967 #ifdef YYCOVERAGE
10968 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10969 if( nArg==2 ){
10970 sqlite3_test_control(testctrl, p->out);
10971 isOk = 3;
10973 break;
10975 #endif
10976 #ifdef SQLITE_DEBUG
10977 case SQLITE_TESTCTRL_TUNE: {
10978 if( nArg==4 ){
10979 int id = (int)integerValue(azArg[2]);
10980 int val = (int)integerValue(azArg[3]);
10981 sqlite3_test_control(testctrl, id, &val);
10982 isOk = 3;
10983 }else if( nArg==3 ){
10984 int id = (int)integerValue(azArg[2]);
10985 sqlite3_test_control(testctrl, -id, &rc2);
10986 isOk = 1;
10987 }else if( nArg==2 ){
10988 int id = 1;
10989 while(1){
10990 int val = 0;
10991 rc2 = sqlite3_test_control(testctrl, -id, &val);
10992 if( rc2!=SQLITE_OK ) break;
10993 if( id>1 ) oputz(" ");
10994 oputf("%d: %d", id, val);
10995 id++;
10997 if( id>1 ) oputz("\n");
10998 isOk = 3;
11000 break;
11002 #endif
11003 case SQLITE_TESTCTRL_SORTER_MMAP:
11004 if( nArg==3 ){
11005 int opt = (unsigned int)integerValue(azArg[2]);
11006 rc2 = sqlite3_test_control(testctrl, p->db, opt);
11007 isOk = 3;
11009 break;
11010 case SQLITE_TESTCTRL_JSON_SELFCHECK:
11011 if( nArg==2 ){
11012 rc2 = -1;
11013 isOk = 1;
11014 }else{
11015 rc2 = booleanValue(azArg[2]);
11016 isOk = 3;
11018 sqlite3_test_control(testctrl, &rc2);
11019 break;
11022 if( isOk==0 && iCtrl>=0 ){
11023 oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11024 rc = 1;
11025 }else if( isOk==1 ){
11026 oputf("%d\n", rc2);
11027 }else if( isOk==2 ){
11028 oputf("0x%08x\n", rc2);
11030 }else
11031 #endif /* !defined(SQLITE_UNTESTABLE) */
11033 if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
11034 open_db(p, 0);
11035 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11036 }else
11038 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
11039 if( nArg==2 ){
11040 enableTimer = booleanValue(azArg[1]);
11041 if( enableTimer && !HAS_TIMER ){
11042 eputz("Error: timer not available on this system.\n");
11043 enableTimer = 0;
11045 }else{
11046 eputz("Usage: .timer on|off\n");
11047 rc = 1;
11049 }else
11051 #ifndef SQLITE_OMIT_TRACE
11052 if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
11053 int mType = 0;
11054 int jj;
11055 open_db(p, 0);
11056 for(jj=1; jj<nArg; jj++){
11057 const char *z = azArg[jj];
11058 if( z[0]=='-' ){
11059 if( optionMatch(z, "expanded") ){
11060 p->eTraceType = SHELL_TRACE_EXPANDED;
11062 #ifdef SQLITE_ENABLE_NORMALIZE
11063 else if( optionMatch(z, "normalized") ){
11064 p->eTraceType = SHELL_TRACE_NORMALIZED;
11066 #endif
11067 else if( optionMatch(z, "plain") ){
11068 p->eTraceType = SHELL_TRACE_PLAIN;
11070 else if( optionMatch(z, "profile") ){
11071 mType |= SQLITE_TRACE_PROFILE;
11073 else if( optionMatch(z, "row") ){
11074 mType |= SQLITE_TRACE_ROW;
11076 else if( optionMatch(z, "stmt") ){
11077 mType |= SQLITE_TRACE_STMT;
11079 else if( optionMatch(z, "close") ){
11080 mType |= SQLITE_TRACE_CLOSE;
11082 else {
11083 eputf("Unknown option \"%s\" on \".trace\"\n", z);
11084 rc = 1;
11085 goto meta_command_exit;
11087 }else{
11088 output_file_close(p->traceOut);
11089 p->traceOut = output_file_open(z, 0);
11092 if( p->traceOut==0 ){
11093 sqlite3_trace_v2(p->db, 0, 0, 0);
11094 }else{
11095 if( mType==0 ) mType = SQLITE_TRACE_STMT;
11096 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11098 }else
11099 #endif /* !defined(SQLITE_OMIT_TRACE) */
11101 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11102 if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
11103 int ii;
11104 int lenOpt;
11105 char *zOpt;
11106 if( nArg<2 ){
11107 eputz("Usage: .unmodule [--allexcept] NAME ...\n");
11108 rc = 1;
11109 goto meta_command_exit;
11111 open_db(p, 0);
11112 zOpt = azArg[1];
11113 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11114 lenOpt = (int)strlen(zOpt);
11115 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11116 assert( azArg[nArg]==0 );
11117 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11118 }else{
11119 for(ii=1; ii<nArg; ii++){
11120 sqlite3_create_module(p->db, azArg[ii], 0, 0);
11123 }else
11124 #endif
11126 #if SQLITE_USER_AUTHENTICATION
11127 if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
11128 if( nArg<2 ){
11129 eputz("Usage: .user SUBCOMMAND ...\n");
11130 rc = 1;
11131 goto meta_command_exit;
11133 open_db(p, 0);
11134 if( cli_strcmp(azArg[1],"login")==0 ){
11135 if( nArg!=4 ){
11136 eputz("Usage: .user login USER PASSWORD\n");
11137 rc = 1;
11138 goto meta_command_exit;
11140 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11141 strlen30(azArg[3]));
11142 if( rc ){
11143 eputf("Authentication failed for user %s\n", azArg[2]);
11144 rc = 1;
11146 }else if( cli_strcmp(azArg[1],"add")==0 ){
11147 if( nArg!=5 ){
11148 eputz("Usage: .user add USER PASSWORD ISADMIN\n");
11149 rc = 1;
11150 goto meta_command_exit;
11152 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11153 booleanValue(azArg[4]));
11154 if( rc ){
11155 eputf("User-Add failed: %d\n", rc);
11156 rc = 1;
11158 }else if( cli_strcmp(azArg[1],"edit")==0 ){
11159 if( nArg!=5 ){
11160 eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
11161 rc = 1;
11162 goto meta_command_exit;
11164 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11165 booleanValue(azArg[4]));
11166 if( rc ){
11167 eputf("User-Edit failed: %d\n", rc);
11168 rc = 1;
11170 }else if( cli_strcmp(azArg[1],"delete")==0 ){
11171 if( nArg!=3 ){
11172 eputz("Usage: .user delete USER\n");
11173 rc = 1;
11174 goto meta_command_exit;
11176 rc = sqlite3_user_delete(p->db, azArg[2]);
11177 if( rc ){
11178 eputf("User-Delete failed: %d\n", rc);
11179 rc = 1;
11181 }else{
11182 eputz("Usage: .user login|add|edit|delete ...\n");
11183 rc = 1;
11184 goto meta_command_exit;
11186 }else
11187 #endif /* SQLITE_USER_AUTHENTICATION */
11189 if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
11190 char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
11191 oputf("SQLite %s %s\n" /*extra-version-info*/,
11192 sqlite3_libversion(), sqlite3_sourceid());
11193 /* BEGIN SQLCIPHER */
11194 #ifdef SQLITE_HAS_CODEC
11196 extern char* sqlcipher_version();
11197 char *sqlcipher_ver = sqlcipher_version();
11198 oputf("SQLCipher %s\n", sqlcipher_ver);
11199 sqlite3_free(sqlcipher_ver);
11201 #endif
11202 /* END SQLCIPHER */
11203 #if SQLITE_HAVE_ZLIB
11204 oputf("zlib version %s\n", zlibVersion());
11205 #endif
11206 #define CTIMEOPT_VAL_(opt) #opt
11207 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11208 #if defined(__clang__) && defined(__clang_major__)
11209 oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
11210 CTIMEOPT_VAL(__clang_minor__) "."
11211 CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
11212 #elif defined(_MSC_VER)
11213 oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
11214 #elif defined(__GNUC__) && defined(__VERSION__)
11215 oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
11216 #endif
11217 }else
11219 if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
11220 const char *zDbName = nArg==2 ? azArg[1] : "main";
11221 sqlite3_vfs *pVfs = 0;
11222 if( p->db ){
11223 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11224 if( pVfs ){
11225 oputf("vfs.zName = \"%s\"\n", pVfs->zName);
11226 oputf("vfs.iVersion = %d\n", pVfs->iVersion);
11227 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile);
11228 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
11231 }else
11233 if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
11234 sqlite3_vfs *pVfs;
11235 sqlite3_vfs *pCurrent = 0;
11236 if( p->db ){
11237 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11239 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11240 oputf("vfs.zName = \"%s\"%s\n", pVfs->zName,
11241 pVfs==pCurrent ? " <--- CURRENT" : "");
11242 oputf("vfs.iVersion = %d\n", pVfs->iVersion);
11243 oputf("vfs.szOsFile = %d\n", pVfs->szOsFile);
11244 oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
11245 if( pVfs->pNext ){
11246 oputz("-----------------------------------\n");
11249 }else
11251 if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
11252 const char *zDbName = nArg==2 ? azArg[1] : "main";
11253 char *zVfsName = 0;
11254 if( p->db ){
11255 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11256 if( zVfsName ){
11257 oputf("%s\n", zVfsName);
11258 sqlite3_free(zVfsName);
11261 }else
11263 if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
11264 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11265 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11266 }else
11268 if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
11269 int j;
11270 assert( nArg<=ArraySize(azArg) );
11271 p->nWidth = nArg-1;
11272 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11273 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11274 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11275 for(j=1; j<nArg; j++){
11276 p->colWidth[j-1] = (int)integerValue(azArg[j]);
11278 }else
11281 eputf("Error: unknown command or invalid arguments: "
11282 " \"%s\". Enter \".help\" for help\n", azArg[0]);
11283 rc = 1;
11286 meta_command_exit:
11287 if( p->outCount ){
11288 p->outCount--;
11289 if( p->outCount==0 ) output_reset(p);
11291 p->bSafeMode = p->bSafeModePersist;
11292 return rc;
11295 /* Line scan result and intermediate states (supporting scan resumption)
11297 #ifndef CHAR_BIT
11298 # define CHAR_BIT 8
11299 #endif
11300 typedef enum {
11301 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11302 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11303 QSS_Start = 0
11304 } QuickScanState;
11305 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11306 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11307 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11308 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11309 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11312 ** Scan line for classification to guide shell's handling.
11313 ** The scan is resumable for subsequent lines when prior
11314 ** return values are passed as the 2nd argument.
11316 static QuickScanState quickscan(char *zLine, QuickScanState qss,
11317 SCAN_TRACKER_REFTYPE pst){
11318 char cin;
11319 char cWait = (char)qss; /* intentional narrowing loss */
11320 if( cWait==0 ){
11321 PlainScan:
11322 assert( cWait==0 );
11323 while( (cin = *zLine++)!=0 ){
11324 if( IsSpace(cin) )
11325 continue;
11326 switch (cin){
11327 case '-':
11328 if( *zLine!='-' )
11329 break;
11330 while((cin = *++zLine)!=0 )
11331 if( cin=='\n')
11332 goto PlainScan;
11333 return qss;
11334 case ';':
11335 qss |= QSS_EndingSemi;
11336 continue;
11337 case '/':
11338 if( *zLine=='*' ){
11339 ++zLine;
11340 cWait = '*';
11341 CONTINUE_PROMPT_AWAITS(pst, "/*");
11342 qss = QSS_SETV(qss, cWait);
11343 goto TermScan;
11345 break;
11346 case '[':
11347 cin = ']';
11348 deliberate_fall_through;
11349 case '`': case '\'': case '"':
11350 cWait = cin;
11351 qss = QSS_HasDark | cWait;
11352 CONTINUE_PROMPT_AWAITC(pst, cin);
11353 goto TermScan;
11354 case '(':
11355 CONTINUE_PAREN_INCR(pst, 1);
11356 break;
11357 case ')':
11358 CONTINUE_PAREN_INCR(pst, -1);
11359 break;
11360 default:
11361 break;
11363 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11365 }else{
11366 TermScan:
11367 while( (cin = *zLine++)!=0 ){
11368 if( cin==cWait ){
11369 switch( cWait ){
11370 case '*':
11371 if( *zLine != '/' )
11372 continue;
11373 ++zLine;
11374 cWait = 0;
11375 CONTINUE_PROMPT_AWAITC(pst, 0);
11376 qss = QSS_SETV(qss, 0);
11377 goto PlainScan;
11378 case '`': case '\'': case '"':
11379 if(*zLine==cWait){
11380 /* Swallow doubled end-delimiter.*/
11381 ++zLine;
11382 continue;
11384 deliberate_fall_through;
11385 case ']':
11386 cWait = 0;
11387 CONTINUE_PROMPT_AWAITC(pst, 0);
11388 qss = QSS_SETV(qss, 0);
11389 goto PlainScan;
11390 default: assert(0);
11395 return qss;
11399 ** Return TRUE if the line typed in is an SQL command terminator other
11400 ** than a semi-colon. The SQL Server style "go" command is understood
11401 ** as is the Oracle "/".
11403 static int line_is_command_terminator(char *zLine){
11404 while( IsSpace(zLine[0]) ){ zLine++; };
11405 if( zLine[0]=='/' )
11406 zLine += 1; /* Oracle */
11407 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11408 zLine += 2; /* SQL Server */
11409 else
11410 return 0;
11411 return quickscan(zLine, QSS_Start, 0)==QSS_Start;
11415 ** The CLI needs a working sqlite3_complete() to work properly. So error
11416 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11418 #ifdef SQLITE_OMIT_COMPLETE
11419 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11420 #endif
11423 ** Return true if zSql is a complete SQL statement. Return false if it
11424 ** ends in the middle of a string literal or C-style comment.
11426 static int line_is_complete(char *zSql, int nSql){
11427 int rc;
11428 if( zSql==0 ) return 1;
11429 zSql[nSql] = ';';
11430 zSql[nSql+1] = 0;
11431 rc = sqlite3_complete(zSql);
11432 zSql[nSql] = 0;
11433 return rc;
11437 ** This function is called after processing each line of SQL in the
11438 ** runOneSqlLine() function. Its purpose is to detect scenarios where
11439 ** defensive mode should be automatically turned off. Specifically, when
11441 ** 1. The first line of input is "PRAGMA foreign_keys=OFF;",
11442 ** 2. The second line of input is "BEGIN TRANSACTION;",
11443 ** 3. The database is empty, and
11444 ** 4. The shell is not running in --safe mode.
11446 ** The implementation uses the ShellState.eRestoreState to maintain state:
11448 ** 0: Have not seen any SQL.
11449 ** 1: Have seen "PRAGMA foreign_keys=OFF;".
11450 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
11451 ** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
11452 ** 7: Nothing left to do. This function becomes a no-op.
11454 static int doAutoDetectRestore(ShellState *p, const char *zSql){
11455 int rc = SQLITE_OK;
11457 if( p->eRestoreState<7 ){
11458 switch( p->eRestoreState ){
11459 case 0: {
11460 const char *zExpect = "PRAGMA foreign_keys=OFF;";
11461 assert( strlen(zExpect)==24 );
11462 if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
11463 p->eRestoreState = 1;
11464 }else{
11465 p->eRestoreState = 7;
11467 break;
11470 case 1: {
11471 int bIsDump = 0;
11472 const char *zExpect = "BEGIN TRANSACTION;";
11473 assert( strlen(zExpect)==18 );
11474 if( memcmp(zSql, zExpect, 19)==0 ){
11475 /* Now check if the database is empty. */
11476 const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
11477 sqlite3_stmt *pStmt = 0;
11479 bIsDump = 1;
11480 shellPrepare(p->db, &rc, zQuery, &pStmt);
11481 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
11482 bIsDump = 0;
11484 shellFinalize(&rc, pStmt);
11486 if( bIsDump && rc==SQLITE_OK ){
11487 int bDefense = 0;
11488 int bDqsDdl = 0;
11489 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
11490 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
11491 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
11492 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
11493 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
11494 }else{
11495 p->eRestoreState = 7;
11497 break;
11500 default: {
11501 if( sqlite3_get_autocommit(p->db) ){
11502 if( (p->eRestoreState & 2) ){
11503 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
11505 if( (p->eRestoreState & 4) ){
11506 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
11508 p->eRestoreState = 7;
11510 break;
11515 return rc;
11519 ** Run a single line of SQL. Return the number of errors.
11521 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11522 int rc;
11523 char *zErrMsg = 0;
11525 open_db(p, 0);
11526 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11527 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11528 BEGIN_TIMER;
11529 rc = shell_exec(p, zSql, &zErrMsg);
11530 END_TIMER;
11531 if( rc || zErrMsg ){
11532 char zPrefix[100];
11533 const char *zErrorTail;
11534 const char *zErrorType;
11535 if( zErrMsg==0 ){
11536 zErrorType = "Error";
11537 zErrorTail = sqlite3_errmsg(p->db);
11538 }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
11539 zErrorType = "Parse error";
11540 zErrorTail = &zErrMsg[12];
11541 }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
11542 zErrorType = "Runtime error";
11543 zErrorTail = &zErrMsg[10];
11544 }else{
11545 zErrorType = "Error";
11546 zErrorTail = zErrMsg;
11548 if( in!=0 || !stdin_is_interactive ){
11549 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11550 "%s near line %d:", zErrorType, startline);
11551 }else{
11552 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11554 eputf("%s %s\n", zPrefix, zErrorTail);
11555 sqlite3_free(zErrMsg);
11556 zErrMsg = 0;
11557 return 1;
11558 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11559 char zLineBuf[2000];
11560 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11561 "changes: %lld total_changes: %lld",
11562 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11563 oputf("%s\n", zLineBuf);
11566 if( doAutoDetectRestore(p, zSql) ) return 1;
11567 return 0;
11570 static void echo_group_input(ShellState *p, const char *zDo){
11571 if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
11574 #ifdef SQLITE_SHELL_FIDDLE
11576 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11577 ** impl because we need the global shellState and cannot access it from that
11578 ** function without moving lots of code around (creating a larger/messier diff).
11580 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11581 /* Parse the next line from shellState.wasm.zInput. */
11582 const char *zBegin = shellState.wasm.zPos;
11583 const char *z = zBegin;
11584 char *zLine = 0;
11585 i64 nZ = 0;
11587 UNUSED_PARAMETER(in);
11588 UNUSED_PARAMETER(isContinuation);
11589 if(!z || !*z){
11590 return 0;
11592 while(*z && isspace(*z)) ++z;
11593 zBegin = z;
11594 for(; *z && '\n'!=*z; ++nZ, ++z){}
11595 if(nZ>0 && '\r'==zBegin[nZ-1]){
11596 --nZ;
11598 shellState.wasm.zPos = z;
11599 zLine = realloc(zPrior, nZ+1);
11600 shell_check_oom(zLine);
11601 memcpy(zLine, zBegin, nZ);
11602 zLine[nZ] = 0;
11603 return zLine;
11605 #endif /* SQLITE_SHELL_FIDDLE */
11608 ** Read input from *in and process it. If *in==0 then input
11609 ** is interactive - the user is typing it it. Otherwise, input
11610 ** is coming from a file or device. A prompt is issued and history
11611 ** is saved only if input is interactive. An interrupt signal will
11612 ** cause this routine to exit immediately, unless input is interactive.
11614 ** Return the number of errors.
11616 static int process_input(ShellState *p){
11617 char *zLine = 0; /* A single input line */
11618 char *zSql = 0; /* Accumulated SQL text */
11619 i64 nLine; /* Length of current line */
11620 i64 nSql = 0; /* Bytes of zSql[] used */
11621 i64 nAlloc = 0; /* Allocated zSql[] space */
11622 int rc; /* Error code */
11623 int errCnt = 0; /* Number of errors seen */
11624 i64 startline = 0; /* Line number for start of current input */
11625 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11627 if( p->inputNesting==MAX_INPUT_NESTING ){
11628 /* This will be more informative in a later version. */
11629 eputf("Input nesting limit (%d) reached at line %d."
11630 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11631 return 1;
11633 ++p->inputNesting;
11634 p->lineno = 0;
11635 CONTINUE_PROMPT_RESET;
11636 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11637 fflush(p->out);
11638 zLine = one_input_line(p->in, zLine, nSql>0);
11639 if( zLine==0 ){
11640 /* End of input */
11641 if( p->in==0 && stdin_is_interactive ) oputz("\n");
11642 break;
11644 if( seenInterrupt ){
11645 if( p->in!=0 ) break;
11646 seenInterrupt = 0;
11648 p->lineno++;
11649 if( QSS_INPLAIN(qss)
11650 && line_is_command_terminator(zLine)
11651 && line_is_complete(zSql, nSql) ){
11652 memcpy(zLine,";",2);
11654 qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
11655 if( QSS_PLAINWHITE(qss) && nSql==0 ){
11656 /* Just swallow single-line whitespace */
11657 echo_group_input(p, zLine);
11658 qss = QSS_Start;
11659 continue;
11661 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11662 CONTINUE_PROMPT_RESET;
11663 echo_group_input(p, zLine);
11664 if( zLine[0]=='.' ){
11665 rc = do_meta_command(zLine, p);
11666 if( rc==2 ){ /* exit requested */
11667 break;
11668 }else if( rc ){
11669 errCnt++;
11672 qss = QSS_Start;
11673 continue;
11675 /* No single-line dispositions remain; accumulate line(s). */
11676 nLine = strlen(zLine);
11677 if( nSql+nLine+2>=nAlloc ){
11678 /* Grow buffer by half-again increments when big. */
11679 nAlloc = nSql+(nSql>>1)+nLine+100;
11680 zSql = realloc(zSql, nAlloc);
11681 shell_check_oom(zSql);
11683 if( nSql==0 ){
11684 i64 i;
11685 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11686 assert( nAlloc>0 && zSql!=0 );
11687 memcpy(zSql, zLine+i, nLine+1-i);
11688 startline = p->lineno;
11689 nSql = nLine-i;
11690 }else{
11691 zSql[nSql++] = '\n';
11692 memcpy(zSql+nSql, zLine, nLine+1);
11693 nSql += nLine;
11695 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11696 echo_group_input(p, zSql);
11697 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11698 CONTINUE_PROMPT_RESET;
11699 nSql = 0;
11700 if( p->outCount ){
11701 output_reset(p);
11702 p->outCount = 0;
11703 }else{
11704 clearTempFile(p);
11706 p->bSafeMode = p->bSafeModePersist;
11707 qss = QSS_Start;
11708 }else if( nSql && QSS_PLAINWHITE(qss) ){
11709 echo_group_input(p, zSql);
11710 nSql = 0;
11711 qss = QSS_Start;
11714 if( nSql ){
11715 /* This may be incomplete. Let the SQL parser deal with that. */
11716 echo_group_input(p, zSql);
11717 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11718 CONTINUE_PROMPT_RESET;
11720 free(zSql);
11721 free(zLine);
11722 --p->inputNesting;
11723 return errCnt>0;
11727 ** Return a pathname which is the user's home directory. A
11728 ** 0 return indicates an error of some kind.
11730 static char *find_home_dir(int clearFlag){
11731 static char *home_dir = NULL;
11732 if( clearFlag ){
11733 free(home_dir);
11734 home_dir = 0;
11735 return 0;
11737 if( home_dir ) return home_dir;
11739 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11740 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11742 struct passwd *pwent;
11743 uid_t uid = getuid();
11744 if( (pwent=getpwuid(uid)) != NULL) {
11745 home_dir = pwent->pw_dir;
11748 #endif
11750 #if defined(_WIN32_WCE)
11751 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11753 home_dir = "/";
11754 #else
11756 #if defined(_WIN32) || defined(WIN32)
11757 if (!home_dir) {
11758 home_dir = getenv("USERPROFILE");
11760 #endif
11762 if (!home_dir) {
11763 home_dir = getenv("HOME");
11766 #if defined(_WIN32) || defined(WIN32)
11767 if (!home_dir) {
11768 char *zDrive, *zPath;
11769 int n;
11770 zDrive = getenv("HOMEDRIVE");
11771 zPath = getenv("HOMEPATH");
11772 if( zDrive && zPath ){
11773 n = strlen30(zDrive) + strlen30(zPath) + 1;
11774 home_dir = malloc( n );
11775 if( home_dir==0 ) return 0;
11776 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11777 return home_dir;
11779 home_dir = "c:\\";
11781 #endif
11783 #endif /* !_WIN32_WCE */
11785 if( home_dir ){
11786 i64 n = strlen(home_dir) + 1;
11787 char *z = malloc( n );
11788 if( z ) memcpy(z, home_dir, n);
11789 home_dir = z;
11792 return home_dir;
11796 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11797 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11798 ** the path to it, else return 0. The result is cached for
11799 ** subsequent calls.
11801 static const char *find_xdg_config(void){
11802 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11803 || defined(__RTP__) || defined(_WRS_KERNEL)
11804 return 0;
11805 #else
11806 static int alreadyTried = 0;
11807 static char *zConfig = 0;
11808 const char *zXdgHome;
11810 if( alreadyTried!=0 ){
11811 return zConfig;
11813 alreadyTried = 1;
11814 zXdgHome = getenv("XDG_CONFIG_HOME");
11815 if( zXdgHome==0 ){
11816 return 0;
11818 zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
11819 shell_check_oom(zConfig);
11820 if( access(zConfig,0)!=0 ){
11821 sqlite3_free(zConfig);
11822 zConfig = 0;
11824 return zConfig;
11825 #endif
11829 ** Read input from the file given by sqliterc_override. Or if that
11830 ** parameter is NULL, take input from the first of find_xdg_config()
11831 ** or ~/.sqliterc which is found.
11833 ** Returns the number of errors.
11835 static void process_sqliterc(
11836 ShellState *p, /* Configuration data */
11837 const char *sqliterc_override /* Name of config file. NULL to use default */
11839 char *home_dir = NULL;
11840 const char *sqliterc = sqliterc_override;
11841 char *zBuf = 0;
11842 FILE *inSaved = p->in;
11843 int savedLineno = p->lineno;
11845 if( sqliterc == NULL ){
11846 sqliterc = find_xdg_config();
11848 if( sqliterc == NULL ){
11849 home_dir = find_home_dir(0);
11850 if( home_dir==0 ){
11851 eputz("-- warning: cannot find home directory;"
11852 " cannot read ~/.sqliterc\n");
11853 return;
11855 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11856 shell_check_oom(zBuf);
11857 sqliterc = zBuf;
11859 p->in = fopen(sqliterc,"rb");
11860 if( p->in ){
11861 if( stdin_is_interactive ){
11862 eputf("-- Loading resources from %s\n", sqliterc);
11864 if( process_input(p) && bail_on_error ) exit(1);
11865 fclose(p->in);
11866 }else if( sqliterc_override!=0 ){
11867 eputf("cannot open: \"%s\"\n", sqliterc);
11868 if( bail_on_error ) exit(1);
11870 p->in = inSaved;
11871 p->lineno = savedLineno;
11872 sqlite3_free(zBuf);
11876 ** Show available command line options
11878 static const char zOptions[] =
11879 " -- treat no subsequent arguments as options\n"
11880 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11881 " -A ARGS... run \".archive ARGS\" and exit\n"
11882 #endif
11883 " -append append the database to the end of the file\n"
11884 " -ascii set output mode to 'ascii'\n"
11885 " -bail stop after hitting an error\n"
11886 " -batch force batch I/O\n"
11887 " -box set output mode to 'box'\n"
11888 " -column set output mode to 'column'\n"
11889 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11890 " -csv set output mode to 'csv'\n"
11891 #if !defined(SQLITE_OMIT_DESERIALIZE)
11892 " -deserialize open the database using sqlite3_deserialize()\n"
11893 #endif
11894 " -echo print inputs before execution\n"
11895 " -init FILENAME read/process named file\n"
11896 " -[no]header turn headers on or off\n"
11897 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11898 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11899 #endif
11900 " -help show this message\n"
11901 " -html set output mode to HTML\n"
11902 " -interactive force interactive I/O\n"
11903 " -json set output mode to 'json'\n"
11904 " -line set output mode to 'line'\n"
11905 " -list set output mode to 'list'\n"
11906 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11907 " -markdown set output mode to 'markdown'\n"
11908 #if !defined(SQLITE_OMIT_DESERIALIZE)
11909 " -maxsize N maximum size for a --deserialize database\n"
11910 #endif
11911 " -memtrace trace all memory allocations and deallocations\n"
11912 " -mmap N default mmap size set to N\n"
11913 #ifdef SQLITE_ENABLE_MULTIPLEX
11914 " -multiplex enable the multiplexor VFS\n"
11915 #endif
11916 " -newline SEP set output row separator. Default: '\\n'\n"
11917 " -nofollow refuse to open symbolic links to database files\n"
11918 " -nonce STRING set the safe-mode escape nonce\n"
11919 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11920 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11921 " -pcachetrace trace all page cache operations\n"
11922 " -quote set output mode to 'quote'\n"
11923 " -readonly open the database read-only\n"
11924 " -safe enable safe-mode\n"
11925 " -separator SEP set output column separator. Default: '|'\n"
11926 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11927 " -sorterref SIZE sorter references threshold size\n"
11928 #endif
11929 " -stats print memory stats before each finalize\n"
11930 " -table set output mode to 'table'\n"
11931 " -tabs set output mode to 'tabs'\n"
11932 " -unsafe-testing allow unsafe commands and modes for testing\n"
11933 " -version show SQLite version\n"
11934 " -vfs NAME use NAME as the default VFS\n"
11935 #ifdef SQLITE_ENABLE_VFSTRACE
11936 " -vfstrace enable tracing of all VFS calls\n"
11937 #endif
11938 #ifdef SQLITE_HAVE_ZLIB
11939 " -zip open the file as a ZIP Archive\n"
11940 #endif
11942 static void usage(int showDetail){
11943 eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
11944 "FILENAME is the name of an SQLite database. A new database is created\n"
11945 "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
11946 if( showDetail ){
11947 eputf("OPTIONS include:\n%s", zOptions);
11948 }else{
11949 eputz("Use the -help option for additional information\n");
11951 exit(1);
11955 ** Internal check: Verify that the SQLite is uninitialized. Print a
11956 ** error message if it is initialized.
11958 static void verify_uninitialized(void){
11959 if( sqlite3_config(-1)==SQLITE_MISUSE ){
11960 sputz(stdout, "WARNING: attempt to configure SQLite after"
11961 " initialization.\n");
11966 ** Initialize the state information in data
11968 static void main_init(ShellState *data) {
11969 memset(data, 0, sizeof(*data));
11970 data->normalMode = data->cMode = data->mode = MODE_List;
11971 data->autoExplain = 1;
11972 data->pAuxDb = &data->aAuxDb[0];
11973 memcpy(data->colSeparator,SEP_Column, 2);
11974 memcpy(data->rowSeparator,SEP_Row, 2);
11975 data->showHeader = 0;
11976 data->shellFlgs = SHFLG_Lookaside;
11977 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11978 #if !defined(SQLITE_SHELL_FIDDLE)
11979 verify_uninitialized();
11980 #endif
11981 sqlite3_config(SQLITE_CONFIG_URI, 1);
11982 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11983 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11984 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
11988 ** Output text to the console in a font that attracts extra attention.
11990 #if defined(_WIN32) || defined(WIN32)
11991 static void printBold(const char *zText){
11992 #if !SQLITE_OS_WINRT
11993 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11994 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11995 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11996 SetConsoleTextAttribute(out,
11997 FOREGROUND_RED|FOREGROUND_INTENSITY
11999 #endif
12000 sputz(stdout, zText);
12001 #if !SQLITE_OS_WINRT
12002 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
12003 #endif
12005 #else
12006 static void printBold(const char *zText){
12007 sputf(stdout, "\033[1m%s\033[0m", zText);
12009 #endif
12012 ** Get the argument to an --option. Throw an error and die if no argument
12013 ** is available.
12015 static char *cmdline_option_value(int argc, char **argv, int i){
12016 if( i==argc ){
12017 eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
12018 exit(1);
12020 return argv[i];
12023 static void sayAbnormalExit(void){
12024 if( seenInterrupt ) eputz("Program interrupted.\n");
12027 #ifndef SQLITE_SHELL_IS_UTF8
12028 # if (defined(_WIN32) || defined(WIN32)) \
12029 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12030 # define SQLITE_SHELL_IS_UTF8 (0)
12031 # else
12032 # define SQLITE_SHELL_IS_UTF8 (1)
12033 # endif
12034 #endif
12036 #ifdef SQLITE_SHELL_FIDDLE
12037 # define main fiddle_main
12038 #endif
12040 #if SQLITE_SHELL_IS_UTF8
12041 int SQLITE_CDECL main(int argc, char **argv){
12042 #else
12043 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12044 char **argv;
12045 #endif
12046 #ifdef SQLITE_DEBUG
12047 sqlite3_int64 mem_main_enter = 0;
12048 #endif
12049 char *zErrMsg = 0;
12050 #ifdef SQLITE_SHELL_FIDDLE
12051 # define data shellState
12052 #else
12053 ShellState data;
12054 StreamsAreConsole consStreams = SAC_NoConsole;
12055 #endif
12056 const char *zInitFile = 0;
12057 int i;
12058 int rc = 0;
12059 int warnInmemoryDb = 0;
12060 int readStdin = 1;
12061 int nCmd = 0;
12062 int nOptsEnd = argc;
12063 char **azCmd = 0;
12064 const char *zVfs = 0; /* Value of -vfs command-line option */
12065 #if !SQLITE_SHELL_IS_UTF8
12066 char **argvToFree = 0;
12067 int argcToFree = 0;
12068 #endif
12069 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12071 #ifdef SQLITE_SHELL_FIDDLE
12072 stdin_is_interactive = 0;
12073 stdout_is_console = 1;
12074 data.wasm.zDefaultDbName = "/fiddle.sqlite3";
12075 #else
12076 consStreams = consoleClassifySetup(stdin, stdout, stderr);
12077 stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
12078 stdout_is_console = (consStreams & SAC_OutConsole)!=0;
12079 atexit(consoleRestore);
12080 #endif
12081 atexit(sayAbnormalExit);
12082 #ifdef SQLITE_DEBUG
12083 mem_main_enter = sqlite3_memory_used();
12084 #endif
12085 #if !defined(_WIN32_WCE)
12086 if( getenv("SQLITE_DEBUG_BREAK") ){
12087 if( isatty(0) && isatty(2) ){
12088 eputf("attach debugger to process %d and press any key to continue.\n",
12089 GETPID());
12090 fgetc(stdin);
12091 }else{
12092 #if defined(_WIN32) || defined(WIN32)
12093 #if SQLITE_OS_WINRT
12094 __debugbreak();
12095 #else
12096 DebugBreak();
12097 #endif
12098 #elif defined(SIGTRAP)
12099 raise(SIGTRAP);
12100 #endif
12103 #endif
12104 /* Register a valid signal handler early, before much else is done. */
12105 #ifdef SIGINT
12106 signal(SIGINT, interrupt_handler);
12107 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12108 if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
12109 eputz("No ^C handler.\n");
12111 #endif
12113 #if USE_SYSTEM_SQLITE+0!=1
12114 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12115 eputf("SQLite header and source version mismatch\n%s\n%s\n",
12116 sqlite3_sourceid(), SQLITE_SOURCE_ID);
12117 exit(1);
12119 #endif
12120 main_init(&data);
12122 /* On Windows, we must translate command-line arguments into UTF-8.
12123 ** The SQLite memory allocator subsystem has to be enabled in order to
12124 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12125 ** subsequent sqlite3_config() calls will work. So copy all results into
12126 ** memory that does not come from the SQLite memory allocator.
12128 #if !SQLITE_SHELL_IS_UTF8
12129 sqlite3_initialize();
12130 argvToFree = malloc(sizeof(argv[0])*argc*2);
12131 shell_check_oom(argvToFree);
12132 argcToFree = argc;
12133 argv = argvToFree + argc;
12134 for(i=0; i<argc; i++){
12135 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12136 i64 n;
12137 shell_check_oom(z);
12138 n = strlen(z);
12139 argv[i] = malloc( n+1 );
12140 shell_check_oom(argv[i]);
12141 memcpy(argv[i], z, n+1);
12142 argvToFree[i] = argv[i];
12143 sqlite3_free(z);
12145 sqlite3_shutdown();
12146 #endif
12148 assert( argc>=1 && argv && argv[0] );
12149 Argv0 = argv[0];
12151 #ifdef SQLITE_SHELL_DBNAME_PROC
12153 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12154 ** of a C-function that will provide the name of the database file. Use
12155 ** this compile-time option to embed this shell program in larger
12156 ** applications. */
12157 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12158 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12159 warnInmemoryDb = 0;
12161 #endif
12163 /* Do an initial pass through the command-line argument to locate
12164 ** the name of the database file, the name of the initialization file,
12165 ** the size of the alternative malloc heap, options affecting commands
12166 ** or SQL run from the command line, and the first command to execute.
12168 #ifndef SQLITE_SHELL_FIDDLE
12169 verify_uninitialized();
12170 #endif
12171 for(i=1; i<argc; i++){
12172 char *z;
12173 z = argv[i];
12174 if( z[0]!='-' || i>nOptsEnd ){
12175 if( data.aAuxDb->zDbFilename==0 ){
12176 data.aAuxDb->zDbFilename = z;
12177 }else{
12178 /* Excess arguments are interpreted as SQL (or dot-commands) and
12179 ** mean that nothing is read from stdin */
12180 readStdin = 0;
12181 nCmd++;
12182 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12183 shell_check_oom(azCmd);
12184 azCmd[nCmd-1] = z;
12186 continue;
12188 if( z[1]=='-' ) z++;
12189 if( cli_strcmp(z, "-")==0 ){
12190 nOptsEnd = i;
12191 continue;
12192 }else if( cli_strcmp(z,"-separator")==0
12193 || cli_strcmp(z,"-nullvalue")==0
12194 || cli_strcmp(z,"-newline")==0
12195 || cli_strcmp(z,"-cmd")==0
12197 (void)cmdline_option_value(argc, argv, ++i);
12198 }else if( cli_strcmp(z,"-init")==0 ){
12199 zInitFile = cmdline_option_value(argc, argv, ++i);
12200 }else if( cli_strcmp(z,"-interactive")==0 ){
12201 }else if( cli_strcmp(z,"-batch")==0 ){
12202 /* Need to check for batch mode here to so we can avoid printing
12203 ** informational messages (like from process_sqliterc) before
12204 ** we do the actual processing of arguments later in a second pass.
12206 stdin_is_interactive = 0;
12207 }else if( cli_strcmp(z,"-utf8")==0 ){
12208 }else if( cli_strcmp(z,"-no-utf8")==0 ){
12209 }else if( cli_strcmp(z,"-heap")==0 ){
12210 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12211 const char *zSize;
12212 sqlite3_int64 szHeap;
12214 zSize = cmdline_option_value(argc, argv, ++i);
12215 szHeap = integerValue(zSize);
12216 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12217 verify_uninitialized();
12218 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12219 #else
12220 (void)cmdline_option_value(argc, argv, ++i);
12221 #endif
12222 }else if( cli_strcmp(z,"-pagecache")==0 ){
12223 sqlite3_int64 n, sz;
12224 sz = integerValue(cmdline_option_value(argc,argv,++i));
12225 if( sz>70000 ) sz = 70000;
12226 if( sz<0 ) sz = 0;
12227 n = integerValue(cmdline_option_value(argc,argv,++i));
12228 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12229 n = 0xffffffffffffLL/sz;
12231 verify_uninitialized();
12232 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12233 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12234 data.shellFlgs |= SHFLG_Pagecache;
12235 }else if( cli_strcmp(z,"-lookaside")==0 ){
12236 int n, sz;
12237 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12238 if( sz<0 ) sz = 0;
12239 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12240 if( n<0 ) n = 0;
12241 verify_uninitialized();
12242 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12243 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12244 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12245 int n;
12246 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12247 verify_uninitialized();
12248 switch( n ){
12249 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
12250 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
12251 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
12253 #ifdef SQLITE_ENABLE_VFSTRACE
12254 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12255 extern int vfstrace_register(
12256 const char *zTraceName,
12257 const char *zOldVfsName,
12258 int (*xOut)(const char*,void*),
12259 void *pOutArg,
12260 int makeDefault
12262 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12263 #endif
12264 #ifdef SQLITE_ENABLE_MULTIPLEX
12265 }else if( cli_strcmp(z,"-multiplex")==0 ){
12266 extern int sqlite3_multiplex_initialize(const char*,int);
12267 sqlite3_multiplex_initialize(0, 1);
12268 #endif
12269 }else if( cli_strcmp(z,"-mmap")==0 ){
12270 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12271 verify_uninitialized();
12272 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12273 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
12274 }else if( cli_strcmp(z,"-sorterref")==0 ){
12275 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12276 verify_uninitialized();
12277 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12278 #endif
12279 }else if( cli_strcmp(z,"-vfs")==0 ){
12280 zVfs = cmdline_option_value(argc, argv, ++i);
12281 #ifdef SQLITE_HAVE_ZLIB
12282 }else if( cli_strcmp(z,"-zip")==0 ){
12283 data.openMode = SHELL_OPEN_ZIPFILE;
12284 #endif
12285 }else if( cli_strcmp(z,"-append")==0 ){
12286 data.openMode = SHELL_OPEN_APPENDVFS;
12287 #ifndef SQLITE_OMIT_DESERIALIZE
12288 }else if( cli_strcmp(z,"-deserialize")==0 ){
12289 data.openMode = SHELL_OPEN_DESERIALIZE;
12290 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12291 data.szMax = integerValue(argv[++i]);
12292 #endif
12293 }else if( cli_strcmp(z,"-readonly")==0 ){
12294 data.openMode = SHELL_OPEN_READONLY;
12295 }else if( cli_strcmp(z,"-nofollow")==0 ){
12296 data.openFlags = SQLITE_OPEN_NOFOLLOW;
12297 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12298 }else if( cli_strncmp(z, "-A",2)==0 ){
12299 /* All remaining command-line arguments are passed to the ".archive"
12300 ** command, so ignore them */
12301 break;
12302 #endif
12303 }else if( cli_strcmp(z, "-memtrace")==0 ){
12304 sqlite3MemTraceActivate(stderr);
12305 }else if( cli_strcmp(z, "-pcachetrace")==0 ){
12306 sqlite3PcacheTraceActivate(stderr);
12307 }else if( cli_strcmp(z,"-bail")==0 ){
12308 bail_on_error = 1;
12309 }else if( cli_strcmp(z,"-nonce")==0 ){
12310 free(data.zNonce);
12311 data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
12312 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12313 ShellSetFlag(&data,SHFLG_TestingMode);
12314 }else if( cli_strcmp(z,"-safe")==0 ){
12315 /* no-op - catch this on the second pass */
12318 #ifndef SQLITE_SHELL_FIDDLE
12319 verify_uninitialized();
12320 #endif
12323 #ifdef SQLITE_SHELL_INIT_PROC
12325 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12326 ** of a C-function that will perform initialization actions on SQLite that
12327 ** occur just before or after sqlite3_initialize(). Use this compile-time
12328 ** option to embed this shell program in larger applications. */
12329 extern void SQLITE_SHELL_INIT_PROC(void);
12330 SQLITE_SHELL_INIT_PROC();
12332 #else
12333 /* All the sqlite3_config() calls have now been made. So it is safe
12334 ** to call sqlite3_initialize() and process any command line -vfs option. */
12335 sqlite3_initialize();
12336 #endif
12338 if( zVfs ){
12339 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12340 if( pVfs ){
12341 sqlite3_vfs_register(pVfs, 1);
12342 }else{
12343 eputf("no such VFS: \"%s\"\n", zVfs);
12344 exit(1);
12348 if( data.pAuxDb->zDbFilename==0 ){
12349 #ifndef SQLITE_OMIT_MEMORYDB
12350 data.pAuxDb->zDbFilename = ":memory:";
12351 warnInmemoryDb = argc==1;
12352 #else
12353 eputf("%s: Error: no database filename specified\n", Argv0);
12354 return 1;
12355 #endif
12357 data.out = stdout;
12358 #ifndef SQLITE_SHELL_FIDDLE
12359 sqlite3_appendvfs_init(0,0,0);
12360 #endif
12362 /* Go ahead and open the database file if it already exists. If the
12363 ** file does not exist, delay opening it. This prevents empty database
12364 ** files from being created if a user mistypes the database name argument
12365 ** to the sqlite command-line tool.
12367 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12368 open_db(&data, 0);
12371 /* Process the initialization file if there is one. If no -init option
12372 ** is given on the command line, look for a file named ~/.sqliterc and
12373 ** try to process it.
12375 process_sqliterc(&data,zInitFile);
12377 /* Make a second pass through the command-line argument and set
12378 ** options. This second pass is delayed until after the initialization
12379 ** file is processed so that the command-line arguments will override
12380 ** settings in the initialization file.
12382 for(i=1; i<argc; i++){
12383 char *z = argv[i];
12384 if( z[0]!='-' || i>=nOptsEnd ) continue;
12385 if( z[1]=='-' ){ z++; }
12386 if( cli_strcmp(z,"-init")==0 ){
12387 i++;
12388 }else if( cli_strcmp(z,"-html")==0 ){
12389 data.mode = MODE_Html;
12390 }else if( cli_strcmp(z,"-list")==0 ){
12391 data.mode = MODE_List;
12392 }else if( cli_strcmp(z,"-quote")==0 ){
12393 data.mode = MODE_Quote;
12394 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12395 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12396 }else if( cli_strcmp(z,"-line")==0 ){
12397 data.mode = MODE_Line;
12398 }else if( cli_strcmp(z,"-column")==0 ){
12399 data.mode = MODE_Column;
12400 }else if( cli_strcmp(z,"-json")==0 ){
12401 data.mode = MODE_Json;
12402 }else if( cli_strcmp(z,"-markdown")==0 ){
12403 data.mode = MODE_Markdown;
12404 }else if( cli_strcmp(z,"-table")==0 ){
12405 data.mode = MODE_Table;
12406 }else if( cli_strcmp(z,"-box")==0 ){
12407 data.mode = MODE_Box;
12408 }else if( cli_strcmp(z,"-csv")==0 ){
12409 data.mode = MODE_Csv;
12410 memcpy(data.colSeparator,",",2);
12411 #ifdef SQLITE_HAVE_ZLIB
12412 }else if( cli_strcmp(z,"-zip")==0 ){
12413 data.openMode = SHELL_OPEN_ZIPFILE;
12414 #endif
12415 }else if( cli_strcmp(z,"-append")==0 ){
12416 data.openMode = SHELL_OPEN_APPENDVFS;
12417 #ifndef SQLITE_OMIT_DESERIALIZE
12418 }else if( cli_strcmp(z,"-deserialize")==0 ){
12419 data.openMode = SHELL_OPEN_DESERIALIZE;
12420 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12421 data.szMax = integerValue(argv[++i]);
12422 #endif
12423 }else if( cli_strcmp(z,"-readonly")==0 ){
12424 data.openMode = SHELL_OPEN_READONLY;
12425 }else if( cli_strcmp(z,"-nofollow")==0 ){
12426 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12427 }else if( cli_strcmp(z,"-ascii")==0 ){
12428 data.mode = MODE_Ascii;
12429 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
12430 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
12431 }else if( cli_strcmp(z,"-tabs")==0 ){
12432 data.mode = MODE_List;
12433 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
12434 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
12435 }else if( cli_strcmp(z,"-separator")==0 ){
12436 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12437 "%s",cmdline_option_value(argc,argv,++i));
12438 }else if( cli_strcmp(z,"-newline")==0 ){
12439 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12440 "%s",cmdline_option_value(argc,argv,++i));
12441 }else if( cli_strcmp(z,"-nullvalue")==0 ){
12442 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12443 "%s",cmdline_option_value(argc,argv,++i));
12444 }else if( cli_strcmp(z,"-header")==0 ){
12445 data.showHeader = 1;
12446 ShellSetFlag(&data, SHFLG_HeaderSet);
12447 }else if( cli_strcmp(z,"-noheader")==0 ){
12448 data.showHeader = 0;
12449 ShellSetFlag(&data, SHFLG_HeaderSet);
12450 }else if( cli_strcmp(z,"-echo")==0 ){
12451 ShellSetFlag(&data, SHFLG_Echo);
12452 }else if( cli_strcmp(z,"-eqp")==0 ){
12453 data.autoEQP = AUTOEQP_on;
12454 }else if( cli_strcmp(z,"-eqpfull")==0 ){
12455 data.autoEQP = AUTOEQP_full;
12456 }else if( cli_strcmp(z,"-stats")==0 ){
12457 data.statsOn = 1;
12458 }else if( cli_strcmp(z,"-scanstats")==0 ){
12459 data.scanstatsOn = 1;
12460 }else if( cli_strcmp(z,"-backslash")==0 ){
12461 /* Undocumented command-line option: -backslash
12462 ** Causes C-style backslash escapes to be evaluated in SQL statements
12463 ** prior to sending the SQL into SQLite. Useful for injecting
12464 ** crazy bytes in the middle of SQL statements for testing and debugging.
12466 ShellSetFlag(&data, SHFLG_Backslash);
12467 }else if( cli_strcmp(z,"-bail")==0 ){
12468 /* No-op. The bail_on_error flag should already be set. */
12469 }else if( cli_strcmp(z,"-version")==0 ){
12470 /* BEGIN SQLCIPHER */
12471 #ifdef SQLITE_HAS_CODEC
12472 extern char* sqlcipher_version();
12473 char *sqlcipher_ver = sqlcipher_version();
12474 sputf(stdout, "%s %s (%d-bit)",
12475 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
12476 sputf(stdout, " (SQLCipher %s)\n", sqlcipher_ver);
12477 sqlite3_free(sqlcipher_ver);
12478 #else
12479 sputf(stdout, "%s %s (%d-bit)\n",
12480 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
12481 #endif
12482 /* END SQLCIPHER */
12483 return 0;
12484 }else if( cli_strcmp(z,"-interactive")==0 ){
12485 /* Need to check for interactive override here to so that it can
12486 ** affect console setup (for Windows only) and testing thereof.
12488 stdin_is_interactive = 1;
12489 }else if( cli_strcmp(z,"-batch")==0 ){
12490 /* already handled */
12491 }else if( cli_strcmp(z,"-utf8")==0 ){
12492 /* already handled */
12493 }else if( cli_strcmp(z,"-no-utf8")==0 ){
12494 /* already handled */
12495 }else if( cli_strcmp(z,"-heap")==0 ){
12496 i++;
12497 }else if( cli_strcmp(z,"-pagecache")==0 ){
12498 i+=2;
12499 }else if( cli_strcmp(z,"-lookaside")==0 ){
12500 i+=2;
12501 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12502 i+=2;
12503 }else if( cli_strcmp(z,"-nonce")==0 ){
12504 i += 2;
12505 }else if( cli_strcmp(z,"-mmap")==0 ){
12506 i++;
12507 }else if( cli_strcmp(z,"-memtrace")==0 ){
12508 i++;
12509 }else if( cli_strcmp(z,"-pcachetrace")==0 ){
12510 i++;
12511 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12512 }else if( cli_strcmp(z,"-sorterref")==0 ){
12513 i++;
12514 #endif
12515 }else if( cli_strcmp(z,"-vfs")==0 ){
12516 i++;
12517 #ifdef SQLITE_ENABLE_VFSTRACE
12518 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12519 i++;
12520 #endif
12521 #ifdef SQLITE_ENABLE_MULTIPLEX
12522 }else if( cli_strcmp(z,"-multiplex")==0 ){
12523 i++;
12524 #endif
12525 }else if( cli_strcmp(z,"-help")==0 ){
12526 usage(1);
12527 }else if( cli_strcmp(z,"-cmd")==0 ){
12528 /* Run commands that follow -cmd first and separately from commands
12529 ** that simply appear on the command-line. This seems goofy. It would
12530 ** be better if all commands ran in the order that they appear. But
12531 ** we retain the goofy behavior for historical compatibility. */
12532 if( i==argc-1 ) break;
12533 z = cmdline_option_value(argc,argv,++i);
12534 if( z[0]=='.' ){
12535 rc = do_meta_command(z, &data);
12536 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12537 }else{
12538 open_db(&data, 0);
12539 rc = shell_exec(&data, z, &zErrMsg);
12540 if( zErrMsg!=0 ){
12541 eputf("Error: %s\n", zErrMsg);
12542 if( bail_on_error ) return rc!=0 ? rc : 1;
12543 }else if( rc!=0 ){
12544 eputf("Error: unable to process SQL \"%s\"\n", z);
12545 if( bail_on_error ) return rc;
12548 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12549 }else if( cli_strncmp(z, "-A", 2)==0 ){
12550 if( nCmd>0 ){
12551 eputf("Error: cannot mix regular SQL or dot-commands"
12552 " with \"%s\"\n", z);
12553 return 1;
12555 open_db(&data, OPEN_DB_ZIPFILE);
12556 if( z[2] ){
12557 argv[i] = &z[2];
12558 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12559 }else{
12560 arDotCommand(&data, 1, argv+i, argc-i);
12562 readStdin = 0;
12563 break;
12564 #endif
12565 }else if( cli_strcmp(z,"-safe")==0 ){
12566 data.bSafeMode = data.bSafeModePersist = 1;
12567 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12568 /* Acted upon in first pass. */
12569 }else{
12570 eputf("%s: Error: unknown option: %s\n", Argv0, z);
12571 eputz("Use -help for a list of options.\n");
12572 return 1;
12574 data.cMode = data.mode;
12577 if( !readStdin ){
12578 /* Run all arguments that do not begin with '-' as if they were separate
12579 ** command-line inputs, except for the argToSkip argument which contains
12580 ** the database filename.
12582 for(i=0; i<nCmd; i++){
12583 if( azCmd[i][0]=='.' ){
12584 rc = do_meta_command(azCmd[i], &data);
12585 if( rc ){
12586 free(azCmd);
12587 return rc==2 ? 0 : rc;
12589 }else{
12590 open_db(&data, 0);
12591 echo_group_input(&data, azCmd[i]);
12592 rc = shell_exec(&data, azCmd[i], &zErrMsg);
12593 if( zErrMsg || rc ){
12594 if( zErrMsg!=0 ){
12595 eputf("Error: %s\n", zErrMsg);
12596 }else{
12597 eputf("Error: unable to process SQL: %s\n", azCmd[i]);
12599 sqlite3_free(zErrMsg);
12600 free(azCmd);
12601 return rc!=0 ? rc : 1;
12605 }else{
12606 /* Run commands received from standard input
12608 if( stdin_is_interactive ){
12609 char *zHome;
12610 char *zHistory;
12611 int nHistory;
12612 #if CIO_WIN_WC_XLATE
12613 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
12614 #else
12615 # define SHELL_CIO_CHAR_SET ""
12616 #endif
12617 /* BEGIN SQLCIPHER */
12618 #ifdef SQLITE_HAS_CODEC
12620 extern char* sqlcipher_version();
12621 char *sqlcipher_ver = sqlcipher_version();
12622 sputf(stdout, "SQLite version %s %.19s%s" /*extra-version-info*/
12623 " (SQLCipher %s)\n" /*sqlcipher version info*/
12624 "Enter \".help\" for usage hints.\n",
12625 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET, sqlcipher_ver);
12626 sqlite3_free(sqlcipher_ver);
12628 #else
12629 sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
12630 "Enter \".help\" for usage hints.\n",
12631 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
12632 #endif
12633 /* END SQLCIPHER */
12634 if( warnInmemoryDb ){
12635 sputz(stdout, "Connected to a ");
12636 printBold("transient in-memory database");
12637 sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
12638 " persistent database.\n");
12640 zHistory = getenv("SQLITE_HISTORY");
12641 if( zHistory ){
12642 zHistory = strdup(zHistory);
12643 }else if( (zHome = find_home_dir(0))!=0 ){
12644 nHistory = strlen30(zHome) + 20;
12645 if( (zHistory = malloc(nHistory))!=0 ){
12646 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12649 if( zHistory ){ shell_read_history(zHistory); }
12650 #if HAVE_READLINE || HAVE_EDITLINE
12651 rl_attempted_completion_function = readline_completion;
12652 #elif HAVE_LINENOISE
12653 linenoiseSetCompletionCallback(linenoise_completion);
12654 #endif
12655 data.in = 0;
12656 rc = process_input(&data);
12657 if( zHistory ){
12658 shell_stifle_history(2000);
12659 shell_write_history(zHistory);
12660 free(zHistory);
12662 }else{
12663 data.in = stdin;
12664 rc = process_input(&data);
12667 #ifndef SQLITE_SHELL_FIDDLE
12668 /* In WASM mode we have to leave the db state in place so that
12669 ** client code can "push" SQL into it after this call returns. */
12670 free(azCmd);
12671 set_table_name(&data, 0);
12672 if( data.db ){
12673 session_close_all(&data, -1);
12674 close_db(data.db);
12676 for(i=0; i<ArraySize(data.aAuxDb); i++){
12677 sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12678 if( data.aAuxDb[i].db ){
12679 session_close_all(&data, i);
12680 close_db(data.aAuxDb[i].db);
12683 find_home_dir(1);
12684 output_reset(&data);
12685 data.doXdgOpen = 0;
12686 clearTempFile(&data);
12687 #if !SQLITE_SHELL_IS_UTF8
12688 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12689 free(argvToFree);
12690 #endif
12691 free(data.colWidth);
12692 free(data.zNonce);
12693 /* Clear the global data structure so that valgrind will detect memory
12694 ** leaks */
12695 memset(&data, 0, sizeof(data));
12696 #ifdef SQLITE_DEBUG
12697 if( sqlite3_memory_used()>mem_main_enter ){
12698 eputf("Memory leaked: %u bytes\n",
12699 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12701 #endif
12702 #endif /* !SQLITE_SHELL_FIDDLE */
12703 return rc;
12707 #ifdef SQLITE_SHELL_FIDDLE
12708 /* Only for emcc experimentation purposes. */
12709 int fiddle_experiment(int a,int b){
12710 return a + b;
12714 ** Returns a pointer to the current DB handle.
12716 sqlite3 * fiddle_db_handle(){
12717 return globalDb;
12721 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12722 ** "main" is assumed. Returns 0 if no db with the given name is
12723 ** open.
12725 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12726 sqlite3_vfs * pVfs = 0;
12727 if(globalDb){
12728 sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12729 SQLITE_FCNTL_VFS_POINTER, &pVfs);
12731 return pVfs;
12734 /* Only for emcc experimentation purposes. */
12735 sqlite3 * fiddle_db_arg(sqlite3 *arg){
12736 printf("fiddle_db_arg(%p)\n", (const void*)arg);
12737 return arg;
12741 ** Intended to be called via a SharedWorker() while a separate
12742 ** SharedWorker() (which manages the wasm module) is performing work
12743 ** which should be interrupted. Unfortunately, SharedWorker is not
12744 ** portable enough to make real use of.
12746 void fiddle_interrupt(void){
12747 if( globalDb ) sqlite3_interrupt(globalDb);
12751 ** Returns the filename of the given db name, assuming "main" if
12752 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12754 const char * fiddle_db_filename(const char * zDbName){
12755 return globalDb
12756 ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12757 : NULL;
12761 ** Completely wipes out the contents of the currently-opened database
12762 ** but leaves its storage intact for reuse.
12764 void fiddle_reset_db(void){
12765 if( globalDb ){
12766 int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12767 if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12768 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12773 ** Uses the current database's VFS xRead to stream the db file's
12774 ** contents out to the given callback. The callback gets a single
12775 ** chunk of size n (its 2nd argument) on each call and must return 0
12776 ** on success, non-0 on error. This function returns 0 on success,
12777 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12778 ** code from the callback. Note that this is not thread-friendly: it
12779 ** expects that it will be the only thread reading the db file and
12780 ** takes no measures to ensure that is the case.
12782 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12783 sqlite3_int64 nSize = 0;
12784 sqlite3_int64 nPos = 0;
12785 sqlite3_file * pFile = 0;
12786 unsigned char buf[1024 * 8];
12787 int nBuf = (int)sizeof(buf);
12788 int rc = shellState.db
12789 ? sqlite3_file_control(shellState.db, "main",
12790 SQLITE_FCNTL_FILE_POINTER, &pFile)
12791 : SQLITE_NOTFOUND;
12792 if( rc ) return rc;
12793 rc = pFile->pMethods->xFileSize(pFile, &nSize);
12794 if( rc ) return rc;
12795 if(nSize % nBuf){
12796 /* DB size is not an even multiple of the buffer size. Reduce
12797 ** buffer size so that we do not unduly inflate the db size when
12798 ** exporting. */
12799 if(0 == nSize % 4096) nBuf = 4096;
12800 else if(0 == nSize % 2048) nBuf = 2048;
12801 else if(0 == nSize % 1024) nBuf = 1024;
12802 else nBuf = 512;
12804 for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12805 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12806 if(SQLITE_IOERR_SHORT_READ == rc){
12807 rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12809 if( 0==rc ) rc = xCallback(buf, nBuf);
12811 return rc;
12815 ** Trivial exportable function for emscripten. It processes zSql as if
12816 ** it were input to the sqlite3 shell and redirects all output to the
12817 ** wasm binding. fiddle_main() must have been called before this
12818 ** is called, or results are undefined.
12820 void fiddle_exec(const char * zSql){
12821 if(zSql && *zSql){
12822 if('.'==*zSql) puts(zSql);
12823 shellState.wasm.zInput = zSql;
12824 shellState.wasm.zPos = zSql;
12825 process_input(&shellState);
12826 shellState.wasm.zInput = shellState.wasm.zPos = 0;
12829 #endif /* SQLITE_SHELL_FIDDLE */