Snapshot of upstream SQLite 3.42.0
[sqlcipher.git] / src / shell.c.in
blob72e449840231c7623b881bb3ef1d66aa527d0f7d
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 #define WIN32_LEAN_AND_MEAN
232 #include <windows.h>
234 /* string conversion routines only needed on Win32 */
235 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
236 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
237 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
238 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
239 #endif
241 /* On Windows, we normally run with output mode of TEXT so that \n characters
242 ** are automatically translated into \r\n. However, this behavior needs
243 ** to be disabled in some cases (ex: when generating CSV output and when
244 ** rendering quoted strings that contain \n characters). The following
245 ** routines take care of that.
247 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
248 static void setBinaryMode(FILE *file, int isOutput){
249 if( isOutput ) fflush(file);
250 _setmode(_fileno(file), _O_BINARY);
252 static void setTextMode(FILE *file, int isOutput){
253 if( isOutput ) fflush(file);
254 _setmode(_fileno(file), _O_TEXT);
256 #else
257 # define setBinaryMode(X,Y)
258 # define setTextMode(X,Y)
259 #endif
261 /* True if the timer is enabled */
262 static int enableTimer = 0;
264 /* A version of strcmp() that works with NULL values */
265 static int cli_strcmp(const char *a, const char *b){
266 if( a==0 ) a = "";
267 if( b==0 ) b = "";
268 return strcmp(a,b);
270 static int cli_strncmp(const char *a, const char *b, size_t n){
271 if( a==0 ) a = "";
272 if( b==0 ) b = "";
273 return strncmp(a,b,n);
276 /* Return the current wall-clock time */
277 static sqlite3_int64 timeOfDay(void){
278 static sqlite3_vfs *clockVfs = 0;
279 sqlite3_int64 t;
280 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
281 if( clockVfs==0 ) return 0; /* Never actually happens */
282 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
283 clockVfs->xCurrentTimeInt64(clockVfs, &t);
284 }else{
285 double r;
286 clockVfs->xCurrentTime(clockVfs, &r);
287 t = (sqlite3_int64)(r*86400000.0);
289 return t;
292 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
293 #include <sys/time.h>
294 #include <sys/resource.h>
296 /* VxWorks does not support getrusage() as far as we can determine */
297 #if defined(_WRS_KERNEL) || defined(__RTP__)
298 struct rusage {
299 struct timeval ru_utime; /* user CPU time used */
300 struct timeval ru_stime; /* system CPU time used */
302 #define getrusage(A,B) memset(B,0,sizeof(*B))
303 #endif
305 /* Saved resource information for the beginning of an operation */
306 static struct rusage sBegin; /* CPU time at start */
307 static sqlite3_int64 iBegin; /* Wall-clock time at start */
310 ** Begin timing an operation
312 static void beginTimer(void){
313 if( enableTimer ){
314 getrusage(RUSAGE_SELF, &sBegin);
315 iBegin = timeOfDay();
319 /* Return the difference of two time_structs in seconds */
320 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
321 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
322 (double)(pEnd->tv_sec - pStart->tv_sec);
326 ** Print the timing results.
328 static void endTimer(void){
329 if( enableTimer ){
330 sqlite3_int64 iEnd = timeOfDay();
331 struct rusage sEnd;
332 getrusage(RUSAGE_SELF, &sEnd);
333 printf("Run Time: real %.3f user %f sys %f\n",
334 (iEnd - iBegin)*0.001,
335 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
336 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
340 #define BEGIN_TIMER beginTimer()
341 #define END_TIMER endTimer()
342 #define HAS_TIMER 1
344 #elif (defined(_WIN32) || defined(WIN32))
346 /* Saved resource information for the beginning of an operation */
347 static HANDLE hProcess;
348 static FILETIME ftKernelBegin;
349 static FILETIME ftUserBegin;
350 static sqlite3_int64 ftWallBegin;
351 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
352 LPFILETIME, LPFILETIME);
353 static GETPROCTIMES getProcessTimesAddr = NULL;
356 ** Check to see if we have timer support. Return 1 if necessary
357 ** support found (or found previously).
359 static int hasTimer(void){
360 if( getProcessTimesAddr ){
361 return 1;
362 } else {
363 #if !SQLITE_OS_WINRT
364 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
365 ** versions. See if the version we are running on has it, and if it
366 ** does, save off a pointer to it and the current process handle.
368 hProcess = GetCurrentProcess();
369 if( hProcess ){
370 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
371 if( NULL != hinstLib ){
372 getProcessTimesAddr =
373 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
374 if( NULL != getProcessTimesAddr ){
375 return 1;
377 FreeLibrary(hinstLib);
380 #endif
382 return 0;
386 ** Begin timing an operation
388 static void beginTimer(void){
389 if( enableTimer && getProcessTimesAddr ){
390 FILETIME ftCreation, ftExit;
391 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
392 &ftKernelBegin,&ftUserBegin);
393 ftWallBegin = timeOfDay();
397 /* Return the difference of two FILETIME structs in seconds */
398 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
399 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
400 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
401 return (double) ((i64End - i64Start) / 10000000.0);
405 ** Print the timing results.
407 static void endTimer(void){
408 if( enableTimer && getProcessTimesAddr){
409 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
410 sqlite3_int64 ftWallEnd = timeOfDay();
411 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
412 printf("Run Time: real %.3f user %f sys %f\n",
413 (ftWallEnd - ftWallBegin)*0.001,
414 timeDiff(&ftUserBegin, &ftUserEnd),
415 timeDiff(&ftKernelBegin, &ftKernelEnd));
419 #define BEGIN_TIMER beginTimer()
420 #define END_TIMER endTimer()
421 #define HAS_TIMER hasTimer()
423 #else
424 #define BEGIN_TIMER
425 #define END_TIMER
426 #define HAS_TIMER 0
427 #endif
430 ** Used to prevent warnings about unused parameters
432 #define UNUSED_PARAMETER(x) (void)(x)
435 ** Number of elements in an array
437 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
440 ** If the following flag is set, then command execution stops
441 ** at an error if we are not interactive.
443 static int bail_on_error = 0;
446 ** Treat stdin as an interactive input if the following variable
447 ** is true. Otherwise, assume stdin is connected to a file or pipe.
449 static int stdin_is_interactive = 1;
451 #if (defined(_WIN32) || defined(WIN32)) && SHELL_USE_LOCAL_GETLINE \
452 && !defined(SHELL_OMIT_WIN_UTF8)
453 # define SHELL_WIN_UTF8_OPT 1
454 #else
455 # define SHELL_WIN_UTF8_OPT 0
456 #endif
458 #if SHELL_WIN_UTF8_OPT
460 ** Setup console for UTF-8 input/output when following variable true.
462 static int console_utf8 = 0;
463 #endif
466 ** On Windows systems we have to know if standard output is a console
467 ** in order to translate UTF-8 into MBCS. The following variable is
468 ** true if translation is required.
470 static int stdout_is_console = 1;
473 ** The following is the open SQLite database. We make a pointer
474 ** to this database a static variable so that it can be accessed
475 ** by the SIGINT handler to interrupt database processing.
477 static sqlite3 *globalDb = 0;
480 ** True if an interrupt (Control-C) has been received.
482 static volatile int seenInterrupt = 0;
485 ** This is the name of our program. It is set in main(), used
486 ** in a number of other places, mostly for error messages.
488 static char *Argv0;
491 ** Prompt strings. Initialized in main. Settable with
492 ** .prompt main continue
494 #define PROMPT_LEN_MAX 20
495 /* First line prompt. default: "sqlite> " */
496 static char mainPrompt[PROMPT_LEN_MAX];
497 /* Continuation prompt. default: " ...> " */
498 static char continuePrompt[PROMPT_LEN_MAX];
500 /* This is variant of the standard-library strncpy() routine with the
501 ** one change that the destination string is always zero-terminated, even
502 ** if there is no zero-terminator in the first n-1 characters of the source
503 ** string.
505 static char *shell_strncpy(char *dest, const char *src, size_t n){
506 size_t i;
507 for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
508 dest[i] = 0;
509 return dest;
513 ** Optionally disable dynamic continuation prompt.
514 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
515 ** or open parentheses level if non-zero, or continuation prompt as set.
516 ** This facility interacts with the scanner and process_input() where the
517 ** below 5 macros are used.
519 #ifdef SQLITE_OMIT_DYNAPROMPT
520 # define CONTINUATION_PROMPT continuePrompt
521 # define CONTINUE_PROMPT_RESET
522 # define CONTINUE_PROMPT_AWAITS(p,s)
523 # define CONTINUE_PROMPT_AWAITC(p,c)
524 # define CONTINUE_PAREN_INCR(p,n)
525 # define CONTINUE_PROMPT_PSTATE 0
526 typedef void *t_NoDynaPrompt;
527 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
528 #else
529 # define CONTINUATION_PROMPT dynamicContinuePrompt()
530 # define CONTINUE_PROMPT_RESET \
531 do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
532 # define CONTINUE_PROMPT_AWAITS(p,s) \
533 if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
534 # define CONTINUE_PROMPT_AWAITC(p,c) \
535 if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
536 # define CONTINUE_PAREN_INCR(p,n) \
537 if(p && stdin_is_interactive) (trackParenLevel(p,n))
538 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
539 typedef struct DynaPrompt *t_DynaPromptRef;
540 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
542 static struct DynaPrompt {
543 char dynamicPrompt[PROMPT_LEN_MAX];
544 char acAwait[2];
545 int inParenLevel;
546 char *zScannerAwaits;
547 } dynPrompt = { {0}, {0}, 0, 0 };
549 /* Record parenthesis nesting level change, or force level to 0. */
550 static void trackParenLevel(struct DynaPrompt *p, int ni){
551 p->inParenLevel += ni;
552 if( ni==0 ) p->inParenLevel = 0;
553 p->zScannerAwaits = 0;
556 /* Record that a lexeme is opened, or closed with args==0. */
557 static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
558 if( s!=0 || c==0 ){
559 p->zScannerAwaits = s;
560 p->acAwait[0] = 0;
561 }else{
562 p->acAwait[0] = c;
563 p->zScannerAwaits = p->acAwait;
567 /* Upon demand, derive the continuation prompt to display. */
568 static char *dynamicContinuePrompt(void){
569 if( continuePrompt[0]==0
570 || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
571 return continuePrompt;
572 }else{
573 if( dynPrompt.zScannerAwaits ){
574 size_t ncp = strlen(continuePrompt);
575 size_t ndp = strlen(dynPrompt.zScannerAwaits);
576 if( ndp > ncp-3 ) return continuePrompt;
577 strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
578 while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
579 shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
580 PROMPT_LEN_MAX-4);
581 }else{
582 if( dynPrompt.inParenLevel>9 ){
583 shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
584 }else if( dynPrompt.inParenLevel<0 ){
585 shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
586 }else{
587 shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
588 dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
590 shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, PROMPT_LEN_MAX-4);
593 return dynPrompt.dynamicPrompt;
595 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
597 #if SHELL_WIN_UTF8_OPT
598 /* Following struct is used for -utf8 operation. */
599 static struct ConsoleState {
600 int stdinEof; /* EOF has been seen on console input */
601 int infsMode; /* Input file stream mode upon shell start */
602 UINT inCodePage; /* Input code page upon shell start */
603 UINT outCodePage; /* Output code page upon shell start */
604 HANDLE hConsoleIn; /* Console input handle */
605 DWORD consoleMode; /* Console mode upon shell start */
606 } conState = { 0, 0, 0, 0, INVALID_HANDLE_VALUE, 0 };
608 #ifndef _O_U16TEXT /* For build environments lacking this constant: */
609 # define _O_U16TEXT 0x20000
610 #endif
613 ** Prepare console, (if known to be a WIN32 console), for UTF-8
614 ** input (from either typing or suitable paste operations) and for
615 ** UTF-8 rendering. This may "fail" with a message to stderr, where
616 ** the preparation is not done and common "code page" issues occur.
618 static void console_prepare(void){
619 HANDLE hCI = GetStdHandle(STD_INPUT_HANDLE);
620 DWORD consoleMode = 0;
621 if( isatty(0) && GetFileType(hCI)==FILE_TYPE_CHAR
622 && GetConsoleMode( hCI, &consoleMode) ){
623 if( !IsValidCodePage(CP_UTF8) ){
624 fprintf(stderr, "Cannot use UTF-8 code page.\n");
625 console_utf8 = 0;
626 return;
628 conState.hConsoleIn = hCI;
629 conState.consoleMode = consoleMode;
630 conState.inCodePage = GetConsoleCP();
631 conState.outCodePage = GetConsoleOutputCP();
632 SetConsoleCP(CP_UTF8);
633 SetConsoleOutputCP(CP_UTF8);
634 consoleMode |= ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
635 SetConsoleMode(conState.hConsoleIn, consoleMode);
636 conState.infsMode = _setmode(_fileno(stdin), _O_U16TEXT);
637 console_utf8 = 1;
638 }else{
639 console_utf8 = 0;
644 ** Undo the effects of console_prepare(), if any.
646 static void SQLITE_CDECL console_restore(void){
647 if( console_utf8 && conState.inCodePage!=0
648 && conState.hConsoleIn!=INVALID_HANDLE_VALUE ){
649 _setmode(_fileno(stdin), conState.infsMode);
650 SetConsoleCP(conState.inCodePage);
651 SetConsoleOutputCP(conState.outCodePage);
652 SetConsoleMode(conState.hConsoleIn, conState.consoleMode);
653 /* Avoid multiple calls. */
654 conState.hConsoleIn = INVALID_HANDLE_VALUE;
655 conState.consoleMode = 0;
656 console_utf8 = 0;
661 ** Collect input like fgets(...) with special provisions for input
662 ** from the Windows console to get around its strange coding issues.
663 ** Defers to plain fgets() when input is not interactive or when the
664 ** startup option, -utf8, has not been provided or taken effect.
666 static char* utf8_fgets(char *buf, int ncmax, FILE *fin){
667 if( fin==0 ) fin = stdin;
668 if( fin==stdin && stdin_is_interactive && console_utf8 ){
669 # define SQLITE_IALIM 150
670 wchar_t wbuf[SQLITE_IALIM];
671 int lend = 0;
672 int noc = 0;
673 if( ncmax==0 || conState.stdinEof ) return 0;
674 buf[0] = 0;
675 while( noc<ncmax-7-1 && !lend ){
676 /* There is room for at least 2 more characters and a 0-terminator. */
677 int na = (ncmax > SQLITE_IALIM*4+1 + noc)
678 ? SQLITE_IALIM : (ncmax-1 - noc)/4;
679 # undef SQLITE_IALIM
680 DWORD nbr = 0;
681 BOOL bRC = ReadConsoleW(conState.hConsoleIn, wbuf, na, &nbr, 0);
682 if( !bRC || (noc==0 && nbr==0) ) return 0;
683 if( nbr > 0 ){
684 int nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
685 wbuf,nbr,0,0,0,0);
686 if( nmb !=0 && noc+nmb <= ncmax ){
687 int iseg = noc;
688 nmb = WideCharToMultiByte(CP_UTF8,WC_COMPOSITECHECK|WC_DEFAULTCHAR,
689 wbuf,nbr,buf+noc,nmb,0,0);
690 noc += nmb;
691 /* Fixup line-ends as coded by Windows for CR (or "Enter".)*/
692 if( noc > 0 ){
693 if( buf[noc-1]=='\n' ){
694 lend = 1;
695 if( noc > 1 && buf[noc-2]=='\r' ){
696 buf[noc-2] = '\n';
697 --noc;
701 /* Check for ^Z (anywhere in line) too. */
702 while( iseg < noc ){
703 if( buf[iseg]==0x1a ){
704 conState.stdinEof = 1;
705 noc = iseg; /* Chop ^Z and anything following. */
706 break;
708 ++iseg;
710 }else break; /* Drop apparent garbage in. (Could assert.) */
711 }else break;
713 /* If got nothing, (after ^Z chop), must be at end-of-file. */
714 if( noc == 0 ) return 0;
715 buf[noc] = 0;
716 return buf;
717 }else{
718 return fgets(buf, ncmax, fin);
722 # define fgets(b,n,f) utf8_fgets(b,n,f)
723 #endif /* SHELL_WIN_UTF8_OPT */
726 ** Render output like fprintf(). Except, if the output is going to the
727 ** console and if this is running on a Windows machine, and if the -utf8
728 ** option is unavailable or (available and inactive), translate the
729 ** output from UTF-8 into MBCS for output through 8-bit stdout stream.
730 ** (With -utf8 active, no translation is needed and must not be done.)
732 #if defined(_WIN32) || defined(WIN32)
733 void utf8_printf(FILE *out, const char *zFormat, ...){
734 va_list ap;
735 va_start(ap, zFormat);
736 if( stdout_is_console && (out==stdout || out==stderr)
737 # if SHELL_WIN_UTF8_OPT
738 && !console_utf8
739 # endif
741 char *z1 = sqlite3_vmprintf(zFormat, ap);
742 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
743 sqlite3_free(z1);
744 fputs(z2, out);
745 sqlite3_free(z2);
746 }else{
747 vfprintf(out, zFormat, ap);
749 va_end(ap);
751 #elif !defined(utf8_printf)
752 # define utf8_printf fprintf
753 #endif
756 ** Render output like fprintf(). This should not be used on anything that
757 ** includes string formatting (e.g. "%s").
759 #if !defined(raw_printf)
760 # define raw_printf fprintf
761 #endif
763 /* Indicate out-of-memory and exit. */
764 static void shell_out_of_memory(void){
765 raw_printf(stderr,"Error: out of memory\n");
766 exit(1);
769 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
770 ** out-of-memory error.
772 static void shell_check_oom(const void *p){
773 if( p==0 ) shell_out_of_memory();
777 ** Write I/O traces to the following stream.
779 #ifdef SQLITE_ENABLE_IOTRACE
780 static FILE *iotrace = 0;
781 #endif
784 ** This routine works like printf in that its first argument is a
785 ** format string and subsequent arguments are values to be substituted
786 ** in place of % fields. The result of formatting this string
787 ** is written to iotrace.
789 #ifdef SQLITE_ENABLE_IOTRACE
790 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
791 va_list ap;
792 char *z;
793 if( iotrace==0 ) return;
794 va_start(ap, zFormat);
795 z = sqlite3_vmprintf(zFormat, ap);
796 va_end(ap);
797 utf8_printf(iotrace, "%s", z);
798 sqlite3_free(z);
800 #endif
803 ** Output string zUtf to stream pOut as w characters. If w is negative,
804 ** then right-justify the text. W is the width in UTF-8 characters, not
805 ** in bytes. This is different from the %*.*s specification in printf
806 ** since with %*.*s the width is measured in bytes, not characters.
808 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
809 int i;
810 int n;
811 int aw = w<0 ? -w : w;
812 if( zUtf==0 ) zUtf = "";
813 for(i=n=0; zUtf[i]; i++){
814 if( (zUtf[i]&0xc0)!=0x80 ){
815 n++;
816 if( n==aw ){
817 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
818 break;
822 if( n>=aw ){
823 utf8_printf(pOut, "%.*s", i, zUtf);
824 }else if( w<0 ){
825 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
826 }else{
827 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
833 ** Determines if a string is a number of not.
835 static int isNumber(const char *z, int *realnum){
836 if( *z=='-' || *z=='+' ) z++;
837 if( !IsDigit(*z) ){
838 return 0;
840 z++;
841 if( realnum ) *realnum = 0;
842 while( IsDigit(*z) ){ z++; }
843 if( *z=='.' ){
844 z++;
845 if( !IsDigit(*z) ) return 0;
846 while( IsDigit(*z) ){ z++; }
847 if( realnum ) *realnum = 1;
849 if( *z=='e' || *z=='E' ){
850 z++;
851 if( *z=='+' || *z=='-' ) z++;
852 if( !IsDigit(*z) ) return 0;
853 while( IsDigit(*z) ){ z++; }
854 if( realnum ) *realnum = 1;
856 return *z==0;
860 ** Compute a string length that is limited to what can be stored in
861 ** lower 30 bits of a 32-bit signed integer.
863 static int strlen30(const char *z){
864 const char *z2 = z;
865 while( *z2 ){ z2++; }
866 return 0x3fffffff & (int)(z2 - z);
870 ** Return the length of a string in characters. Multibyte UTF8 characters
871 ** count as a single character.
873 static int strlenChar(const char *z){
874 int n = 0;
875 while( *z ){
876 if( (0xc0&*(z++))!=0x80 ) n++;
878 return n;
882 ** Return open FILE * if zFile exists, can be opened for read
883 ** and is an ordinary file or a character stream source.
884 ** Otherwise return 0.
886 static FILE * openChrSource(const char *zFile){
887 #ifdef _WIN32
888 struct _stat x = {0};
889 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
890 /* On Windows, open first, then check the stream nature. This order
891 ** is necessary because _stat() and sibs, when checking a named pipe,
892 ** effectively break the pipe as its supplier sees it. */
893 FILE *rv = fopen(zFile, "rb");
894 if( rv==0 ) return 0;
895 if( _fstat(_fileno(rv), &x) != 0
896 || !STAT_CHR_SRC(x.st_mode)){
897 fclose(rv);
898 rv = 0;
900 return rv;
901 #else
902 struct stat x = {0};
903 int rc = stat(zFile, &x);
904 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
905 if( rc!=0 ) return 0;
906 if( STAT_CHR_SRC(x.st_mode) ){
907 return fopen(zFile, "rb");
908 }else{
909 return 0;
911 #endif
912 #undef STAT_CHR_SRC
916 ** This routine reads a line of text from FILE in, stores
917 ** the text in memory obtained from malloc() and returns a pointer
918 ** to the text. NULL is returned at end of file, or if malloc()
919 ** fails.
921 ** If zLine is not NULL then it is a malloced buffer returned from
922 ** a previous call to this routine that may be reused.
924 static char *local_getline(char *zLine, FILE *in){
925 int nLine = zLine==0 ? 0 : 100;
926 int n = 0;
928 while( 1 ){
929 if( n+100>nLine ){
930 nLine = nLine*2 + 100;
931 zLine = realloc(zLine, nLine);
932 shell_check_oom(zLine);
934 if( fgets(&zLine[n], nLine - n, in)==0 ){
935 if( n==0 ){
936 free(zLine);
937 return 0;
939 zLine[n] = 0;
940 break;
942 while( zLine[n] ) n++;
943 if( n>0 && zLine[n-1]=='\n' ){
944 n--;
945 if( n>0 && zLine[n-1]=='\r' ) n--;
946 zLine[n] = 0;
947 break;
950 #if defined(_WIN32) || defined(WIN32)
951 /* For interactive input on Windows systems, without -utf8,
952 ** translate the multi-byte characterset characters into UTF-8.
953 ** This is the translation that predates the -utf8 option. */
954 if( stdin_is_interactive && in==stdin
955 # if SHELL_WIN_UTF8_OPT
956 && !console_utf8
957 # endif /* SHELL_WIN_UTF8_OPT */
959 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
960 if( zTrans ){
961 i64 nTrans = strlen(zTrans)+1;
962 if( nTrans>nLine ){
963 zLine = realloc(zLine, nTrans);
964 shell_check_oom(zLine);
966 memcpy(zLine, zTrans, nTrans);
967 sqlite3_free(zTrans);
970 #endif /* defined(_WIN32) || defined(WIN32) */
971 return zLine;
975 ** Retrieve a single line of input text.
977 ** If in==0 then read from standard input and prompt before each line.
978 ** If isContinuation is true, then a continuation prompt is appropriate.
979 ** If isContinuation is zero, then the main prompt should be used.
981 ** If zPrior is not NULL then it is a buffer from a prior call to this
982 ** routine that can be reused.
984 ** The result is stored in space obtained from malloc() and must either
985 ** be freed by the caller or else passed back into this routine via the
986 ** zPrior argument for reuse.
988 #ifndef SQLITE_SHELL_FIDDLE
989 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
990 char *zPrompt;
991 char *zResult;
992 if( in!=0 ){
993 zResult = local_getline(zPrior, in);
994 }else{
995 zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
996 #if SHELL_USE_LOCAL_GETLINE
997 printf("%s", zPrompt);
998 fflush(stdout);
1000 zResult = local_getline(zPrior, stdin);
1001 zPrior = 0;
1002 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1003 if( zResult==0 ) sqlite3_sleep(50);
1004 }while( zResult==0 && seenInterrupt>0 );
1005 #else
1006 free(zPrior);
1007 zResult = shell_readline(zPrompt);
1008 while( zResult==0 ){
1009 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1010 sqlite3_sleep(50);
1011 if( seenInterrupt==0 ) break;
1012 zResult = shell_readline("");
1014 if( zResult && *zResult ) shell_add_history(zResult);
1015 #endif
1017 return zResult;
1019 #endif /* !SQLITE_SHELL_FIDDLE */
1022 ** Return the value of a hexadecimal digit. Return -1 if the input
1023 ** is not a hex digit.
1025 static int hexDigitValue(char c){
1026 if( c>='0' && c<='9' ) return c - '0';
1027 if( c>='a' && c<='f' ) return c - 'a' + 10;
1028 if( c>='A' && c<='F' ) return c - 'A' + 10;
1029 return -1;
1033 ** Interpret zArg as an integer value, possibly with suffixes.
1035 static sqlite3_int64 integerValue(const char *zArg){
1036 sqlite3_int64 v = 0;
1037 static const struct { char *zSuffix; int iMult; } aMult[] = {
1038 { "KiB", 1024 },
1039 { "MiB", 1024*1024 },
1040 { "GiB", 1024*1024*1024 },
1041 { "KB", 1000 },
1042 { "MB", 1000000 },
1043 { "GB", 1000000000 },
1044 { "K", 1000 },
1045 { "M", 1000000 },
1046 { "G", 1000000000 },
1048 int i;
1049 int isNeg = 0;
1050 if( zArg[0]=='-' ){
1051 isNeg = 1;
1052 zArg++;
1053 }else if( zArg[0]=='+' ){
1054 zArg++;
1056 if( zArg[0]=='0' && zArg[1]=='x' ){
1057 int x;
1058 zArg += 2;
1059 while( (x = hexDigitValue(zArg[0]))>=0 ){
1060 v = (v<<4) + x;
1061 zArg++;
1063 }else{
1064 while( IsDigit(zArg[0]) ){
1065 v = v*10 + zArg[0] - '0';
1066 zArg++;
1069 for(i=0; i<ArraySize(aMult); i++){
1070 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1071 v *= aMult[i].iMult;
1072 break;
1075 return isNeg? -v : v;
1079 ** A variable length string to which one can append text.
1081 typedef struct ShellText ShellText;
1082 struct ShellText {
1083 char *z;
1084 int n;
1085 int nAlloc;
1089 ** Initialize and destroy a ShellText object
1091 static void initText(ShellText *p){
1092 memset(p, 0, sizeof(*p));
1094 static void freeText(ShellText *p){
1095 free(p->z);
1096 initText(p);
1099 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1100 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1101 ** added to zIn, and the result returned in memory obtained from malloc().
1102 ** zIn, if it was not NULL, is freed.
1104 ** If the third argument, quote, is not '\0', then it is used as a
1105 ** quote character for zAppend.
1107 static void appendText(ShellText *p, const char *zAppend, char quote){
1108 i64 len;
1109 i64 i;
1110 i64 nAppend = strlen30(zAppend);
1112 len = nAppend+p->n+1;
1113 if( quote ){
1114 len += 2;
1115 for(i=0; i<nAppend; i++){
1116 if( zAppend[i]==quote ) len++;
1120 if( p->z==0 || p->n+len>=p->nAlloc ){
1121 p->nAlloc = p->nAlloc*2 + len + 20;
1122 p->z = realloc(p->z, p->nAlloc);
1123 shell_check_oom(p->z);
1126 if( quote ){
1127 char *zCsr = p->z+p->n;
1128 *zCsr++ = quote;
1129 for(i=0; i<nAppend; i++){
1130 *zCsr++ = zAppend[i];
1131 if( zAppend[i]==quote ) *zCsr++ = quote;
1133 *zCsr++ = quote;
1134 p->n = (int)(zCsr - p->z);
1135 *zCsr = '\0';
1136 }else{
1137 memcpy(p->z+p->n, zAppend, nAppend);
1138 p->n += nAppend;
1139 p->z[p->n] = '\0';
1144 ** Attempt to determine if identifier zName needs to be quoted, either
1145 ** because it contains non-alphanumeric characters, or because it is an
1146 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
1147 ** that quoting is required.
1149 ** Return '"' if quoting is required. Return 0 if no quoting is required.
1151 static char quoteChar(const char *zName){
1152 int i;
1153 if( zName==0 ) return '"';
1154 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1155 for(i=0; zName[i]; i++){
1156 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1158 return sqlite3_keyword_check(zName, i) ? '"' : 0;
1162 ** Construct a fake object name and column list to describe the structure
1163 ** of the view, virtual table, or table valued function zSchema.zName.
1165 static char *shellFakeSchema(
1166 sqlite3 *db, /* The database connection containing the vtab */
1167 const char *zSchema, /* Schema of the database holding the vtab */
1168 const char *zName /* The name of the virtual table */
1170 sqlite3_stmt *pStmt = 0;
1171 char *zSql;
1172 ShellText s;
1173 char cQuote;
1174 char *zDiv = "(";
1175 int nRow = 0;
1177 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1178 zSchema ? zSchema : "main", zName);
1179 shell_check_oom(zSql);
1180 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1181 sqlite3_free(zSql);
1182 initText(&s);
1183 if( zSchema ){
1184 cQuote = quoteChar(zSchema);
1185 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
1186 appendText(&s, zSchema, cQuote);
1187 appendText(&s, ".", 0);
1189 cQuote = quoteChar(zName);
1190 appendText(&s, zName, cQuote);
1191 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1192 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
1193 nRow++;
1194 appendText(&s, zDiv, 0);
1195 zDiv = ",";
1196 if( zCol==0 ) zCol = "";
1197 cQuote = quoteChar(zCol);
1198 appendText(&s, zCol, cQuote);
1200 appendText(&s, ")", 0);
1201 sqlite3_finalize(pStmt);
1202 if( nRow==0 ){
1203 freeText(&s);
1204 s.z = 0;
1206 return s.z;
1210 ** SQL function: shell_module_schema(X)
1212 ** Return a fake schema for the table-valued function or eponymous virtual
1213 ** table X.
1215 static void shellModuleSchema(
1216 sqlite3_context *pCtx,
1217 int nVal,
1218 sqlite3_value **apVal
1220 const char *zName;
1221 char *zFake;
1222 UNUSED_PARAMETER(nVal);
1223 zName = (const char*)sqlite3_value_text(apVal[0]);
1224 zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
1225 if( zFake ){
1226 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
1227 -1, sqlite3_free);
1228 free(zFake);
1233 ** SQL function: shell_add_schema(S,X)
1235 ** Add the schema name X to the CREATE statement in S and return the result.
1236 ** Examples:
1238 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1240 ** Also works on
1242 ** CREATE INDEX
1243 ** CREATE UNIQUE INDEX
1244 ** CREATE VIEW
1245 ** CREATE TRIGGER
1246 ** CREATE VIRTUAL TABLE
1248 ** This UDF is used by the .schema command to insert the schema name of
1249 ** attached databases into the middle of the sqlite_schema.sql field.
1251 static void shellAddSchemaName(
1252 sqlite3_context *pCtx,
1253 int nVal,
1254 sqlite3_value **apVal
1256 static const char *aPrefix[] = {
1257 "TABLE",
1258 "INDEX",
1259 "UNIQUE INDEX",
1260 "VIEW",
1261 "TRIGGER",
1262 "VIRTUAL TABLE"
1264 int i = 0;
1265 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1266 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1267 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1268 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1269 UNUSED_PARAMETER(nVal);
1270 if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
1271 for(i=0; i<ArraySize(aPrefix); i++){
1272 int n = strlen30(aPrefix[i]);
1273 if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1274 char *z = 0;
1275 char *zFake = 0;
1276 if( zSchema ){
1277 char cQuote = quoteChar(zSchema);
1278 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1279 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1280 }else{
1281 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1284 if( zName
1285 && aPrefix[i][0]=='V'
1286 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1288 if( z==0 ){
1289 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1290 }else{
1291 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1293 free(zFake);
1295 if( z ){
1296 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1297 return;
1302 sqlite3_result_value(pCtx, apVal[0]);
1306 ** The source code for several run-time loadable extensions is inserted
1307 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1308 ** code, we need to override some macros to make the included program code
1309 ** work here in the middle of this regular program.
1311 #define SQLITE_EXTENSION_INIT1
1312 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1314 #if defined(_WIN32) && defined(_MSC_VER)
1315 INCLUDE test_windirent.h
1316 INCLUDE test_windirent.c
1317 #define dirent DIRENT
1318 #endif
1319 INCLUDE ../ext/misc/memtrace.c
1320 INCLUDE ../ext/misc/shathree.c
1321 INCLUDE ../ext/misc/uint.c
1322 INCLUDE ../ext/misc/decimal.c
1323 #undef sqlite3_base_init
1324 #define sqlite3_base_init sqlite3_base64_init
1325 INCLUDE ../ext/misc/base64.c
1326 #undef sqlite3_base_init
1327 #define sqlite3_base_init sqlite3_base85_init
1328 #define OMIT_BASE85_CHECKER
1329 INCLUDE ../ext/misc/base85.c
1330 INCLUDE ../ext/misc/ieee754.c
1331 INCLUDE ../ext/misc/series.c
1332 INCLUDE ../ext/misc/regexp.c
1333 #ifndef SQLITE_SHELL_FIDDLE
1334 INCLUDE ../ext/misc/fileio.c
1335 INCLUDE ../ext/misc/completion.c
1336 INCLUDE ../ext/misc/appendvfs.c
1337 #endif
1338 #ifdef SQLITE_HAVE_ZLIB
1339 INCLUDE ../ext/misc/zipfile.c
1340 INCLUDE ../ext/misc/sqlar.c
1341 #endif
1342 INCLUDE ../ext/expert/sqlite3expert.h
1343 INCLUDE ../ext/expert/sqlite3expert.c
1345 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1346 #define SQLITE_SHELL_HAVE_RECOVER 1
1347 #else
1348 #define SQLITE_SHELL_HAVE_RECOVER 0
1349 #endif
1350 #if SQLITE_SHELL_HAVE_RECOVER
1351 INCLUDE ../ext/recover/sqlite3recover.h
1352 # ifndef SQLITE_HAVE_SQLITE3R
1353 INCLUDE ../ext/recover/dbdata.c
1354 INCLUDE ../ext/recover/sqlite3recover.c
1355 # endif /* SQLITE_HAVE_SQLITE3R */
1356 #endif
1357 #ifdef SQLITE_SHELL_EXTSRC
1358 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1359 #endif
1361 #if defined(SQLITE_ENABLE_SESSION)
1363 ** State information for a single open session
1365 typedef struct OpenSession OpenSession;
1366 struct OpenSession {
1367 char *zName; /* Symbolic name for this session */
1368 int nFilter; /* Number of xFilter rejection GLOB patterns */
1369 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1370 sqlite3_session *p; /* The open session */
1372 #endif
1374 typedef struct ExpertInfo ExpertInfo;
1375 struct ExpertInfo {
1376 sqlite3expert *pExpert;
1377 int bVerbose;
1380 /* A single line in the EQP output */
1381 typedef struct EQPGraphRow EQPGraphRow;
1382 struct EQPGraphRow {
1383 int iEqpId; /* ID for this row */
1384 int iParentId; /* ID of the parent row */
1385 EQPGraphRow *pNext; /* Next row in sequence */
1386 char zText[1]; /* Text to display for this row */
1389 /* All EQP output is collected into an instance of the following */
1390 typedef struct EQPGraph EQPGraph;
1391 struct EQPGraph {
1392 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
1393 EQPGraphRow *pLast; /* Last element of the pRow list */
1394 char zPrefix[100]; /* Graph prefix */
1397 /* Parameters affecting columnar mode result display (defaulting together) */
1398 typedef struct ColModeOpts {
1399 int iWrap; /* In columnar modes, wrap lines reaching this limit */
1400 u8 bQuote; /* Quote results for .mode box and table */
1401 u8 bWordWrap; /* In columnar modes, wrap at word boundaries */
1402 } ColModeOpts;
1403 #define ColModeOpts_default { 60, 0, 0 }
1404 #define ColModeOpts_default_qbox { 60, 1, 0 }
1407 ** State information about the database connection is contained in an
1408 ** instance of the following structure.
1410 typedef struct ShellState ShellState;
1411 struct ShellState {
1412 sqlite3 *db; /* The database */
1413 u8 autoExplain; /* Automatically turn on .explain mode */
1414 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1415 u8 autoEQPtest; /* autoEQP is in test mode */
1416 u8 autoEQPtrace; /* autoEQP is in trace mode */
1417 u8 scanstatsOn; /* True to display scan stats before each finalize */
1418 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1419 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1420 u8 nEqpLevel; /* Depth of the EQP output graph */
1421 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1422 u8 bSafeMode; /* True to prohibit unsafe operations */
1423 u8 bSafeModePersist; /* The long-term value of bSafeMode */
1424 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
1425 unsigned statsOn; /* True to display memory stats before each finalize */
1426 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
1427 int inputNesting; /* Track nesting level of .read and other redirects */
1428 int outCount; /* Revert to stdout when reaching zero */
1429 int cnt; /* Number of records displayed so far */
1430 int lineno; /* Line number of last line read from in */
1431 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1432 FILE *in; /* Read commands from this stream */
1433 FILE *out; /* Write results here */
1434 FILE *traceOut; /* Output for sqlite3_trace() */
1435 int nErr; /* Number of errors seen */
1436 int mode; /* An output mode setting */
1437 int modePrior; /* Saved mode */
1438 int cMode; /* temporary output mode for the current query */
1439 int normalMode; /* Output mode before ".explain on" */
1440 int writableSchema; /* True if PRAGMA writable_schema=ON */
1441 int showHeader; /* True to show column names in List or Column mode */
1442 int nCheck; /* Number of ".check" commands run */
1443 unsigned nProgress; /* Number of progress callbacks encountered */
1444 unsigned mxProgress; /* Maximum progress callbacks before failing */
1445 unsigned flgProgress; /* Flags for the progress callback */
1446 unsigned shellFlgs; /* Various flags */
1447 unsigned priorShFlgs; /* Saved copy of flags */
1448 sqlite3_int64 szMax; /* --maxsize argument to .open */
1449 char *zDestTable; /* Name of destination table when MODE_Insert */
1450 char *zTempFile; /* Temporary file that might need deleting */
1451 char zTestcase[30]; /* Name of current test case */
1452 char colSeparator[20]; /* Column separator character for several modes */
1453 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1454 char colSepPrior[20]; /* Saved column separator */
1455 char rowSepPrior[20]; /* Saved row separator */
1456 int *colWidth; /* Requested width of each column in columnar modes */
1457 int *actualWidth; /* Actual width of each column */
1458 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */
1459 char nullValue[20]; /* The text to print when a NULL comes back from
1460 ** the database */
1461 char outfile[FILENAME_MAX]; /* Filename for *out */
1462 sqlite3_stmt *pStmt; /* Current statement if any. */
1463 FILE *pLog; /* Write log output here */
1464 struct AuxDb { /* Storage space for auxiliary database connections */
1465 sqlite3 *db; /* Connection pointer */
1466 const char *zDbFilename; /* Filename used to open the connection */
1467 char *zFreeOnClose; /* Free this memory allocation on close */
1468 #if defined(SQLITE_ENABLE_SESSION)
1469 int nSession; /* Number of active sessions */
1470 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1471 #endif
1472 } aAuxDb[5], /* Array of all database connections */
1473 *pAuxDb; /* Currently active database connection */
1474 int *aiIndent; /* Array of indents used in MODE_Explain */
1475 int nIndent; /* Size of array aiIndent[] */
1476 int iIndent; /* Index of current op in aiIndent[] */
1477 char *zNonce; /* Nonce for temporary safe-mode excapes */
1478 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
1479 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
1480 #ifdef SQLITE_SHELL_FIDDLE
1481 struct {
1482 const char * zInput; /* Input string from wasm/JS proxy */
1483 const char * zPos; /* Cursor pos into zInput */
1484 const char * zDefaultDbName; /* Default name for db file */
1485 } wasm;
1486 #endif
1489 #ifdef SQLITE_SHELL_FIDDLE
1490 static ShellState shellState;
1491 #endif
1494 /* Allowed values for ShellState.autoEQP
1496 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1497 #define AUTOEQP_on 1 /* Automatic EQP is on */
1498 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1499 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1501 /* Allowed values for ShellState.openMode
1503 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1504 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1505 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1506 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1507 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1508 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1509 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1511 /* Allowed values for ShellState.eTraceType
1513 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1514 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1515 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1517 /* Bits in the ShellState.flgProgress variable */
1518 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1519 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1520 ** callback limit is reached, and for each
1521 ** top-level SQL statement */
1522 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1525 ** These are the allowed shellFlgs values
1527 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1528 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1529 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1530 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1531 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1532 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1533 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1534 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1535 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1536 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1537 #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */
1540 ** Macros for testing and setting shellFlgs
1542 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1543 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1544 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1547 ** These are the allowed modes.
1549 #define MODE_Line 0 /* One column per line. Blank line between records */
1550 #define MODE_Column 1 /* One record per line in neat columns */
1551 #define MODE_List 2 /* One record per line with a separator */
1552 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1553 #define MODE_Html 4 /* Generate an XHTML table */
1554 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1555 #define MODE_Quote 6 /* Quote values as for SQL */
1556 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1557 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1558 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1559 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1560 #define MODE_Pretty 11 /* Pretty-print schemas */
1561 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1562 #define MODE_Json 13 /* Output JSON */
1563 #define MODE_Markdown 14 /* Markdown formatting */
1564 #define MODE_Table 15 /* MySQL-style table formatting */
1565 #define MODE_Box 16 /* Unicode box-drawing characters */
1566 #define MODE_Count 17 /* Output only a count of the rows of output */
1567 #define MODE_Off 18 /* No query output shown */
1569 static const char *modeDescr[] = {
1570 "line",
1571 "column",
1572 "list",
1573 "semi",
1574 "html",
1575 "insert",
1576 "quote",
1577 "tcl",
1578 "csv",
1579 "explain",
1580 "ascii",
1581 "prettyprint",
1582 "eqp",
1583 "json",
1584 "markdown",
1585 "table",
1586 "box",
1587 "count",
1588 "off"
1592 ** These are the column/row/line separators used by the various
1593 ** import/export modes.
1595 #define SEP_Column "|"
1596 #define SEP_Row "\n"
1597 #define SEP_Tab "\t"
1598 #define SEP_Space " "
1599 #define SEP_Comma ","
1600 #define SEP_CrLf "\r\n"
1601 #define SEP_Unit "\x1F"
1602 #define SEP_Record "\x1E"
1605 ** Limit input nesting via .read or any other input redirect.
1606 ** It's not too expensive, so a generous allowance can be made.
1608 #define MAX_INPUT_NESTING 25
1611 ** A callback for the sqlite3_log() interface.
1613 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1614 ShellState *p = (ShellState*)pArg;
1615 if( p->pLog==0 ) return;
1616 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1617 fflush(p->pLog);
1621 ** SQL function: shell_putsnl(X)
1623 ** Write the text X to the screen (or whatever output is being directed)
1624 ** adding a newline at the end, and then return X.
1626 static void shellPutsFunc(
1627 sqlite3_context *pCtx,
1628 int nVal,
1629 sqlite3_value **apVal
1631 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1632 (void)nVal;
1633 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1634 sqlite3_result_value(pCtx, apVal[0]);
1638 ** If in safe mode, print an error message described by the arguments
1639 ** and exit immediately.
1641 static void failIfSafeMode(
1642 ShellState *p,
1643 const char *zErrMsg,
1646 if( p->bSafeMode ){
1647 va_list ap;
1648 char *zMsg;
1649 va_start(ap, zErrMsg);
1650 zMsg = sqlite3_vmprintf(zErrMsg, ap);
1651 va_end(ap);
1652 raw_printf(stderr, "line %d: ", p->lineno);
1653 utf8_printf(stderr, "%s\n", zMsg);
1654 exit(1);
1659 ** SQL function: edit(VALUE)
1660 ** edit(VALUE,EDITOR)
1662 ** These steps:
1664 ** (1) Write VALUE into a temporary file.
1665 ** (2) Run program EDITOR on that temporary file.
1666 ** (3) Read the temporary file back and return its content as the result.
1667 ** (4) Delete the temporary file
1669 ** If the EDITOR argument is omitted, use the value in the VISUAL
1670 ** environment variable. If still there is no EDITOR, through an error.
1672 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1674 #ifndef SQLITE_NOHAVE_SYSTEM
1675 static void editFunc(
1676 sqlite3_context *context,
1677 int argc,
1678 sqlite3_value **argv
1680 const char *zEditor;
1681 char *zTempFile = 0;
1682 sqlite3 *db;
1683 char *zCmd = 0;
1684 int bBin;
1685 int rc;
1686 int hasCRNL = 0;
1687 FILE *f = 0;
1688 sqlite3_int64 sz;
1689 sqlite3_int64 x;
1690 unsigned char *p = 0;
1692 if( argc==2 ){
1693 zEditor = (const char*)sqlite3_value_text(argv[1]);
1694 }else{
1695 zEditor = getenv("VISUAL");
1697 if( zEditor==0 ){
1698 sqlite3_result_error(context, "no editor for edit()", -1);
1699 return;
1701 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1702 sqlite3_result_error(context, "NULL input to edit()", -1);
1703 return;
1705 db = sqlite3_context_db_handle(context);
1706 zTempFile = 0;
1707 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1708 if( zTempFile==0 ){
1709 sqlite3_uint64 r = 0;
1710 sqlite3_randomness(sizeof(r), &r);
1711 zTempFile = sqlite3_mprintf("temp%llx", r);
1712 if( zTempFile==0 ){
1713 sqlite3_result_error_nomem(context);
1714 return;
1717 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1718 /* When writing the file to be edited, do \n to \r\n conversions on systems
1719 ** that want \r\n line endings */
1720 f = fopen(zTempFile, bBin ? "wb" : "w");
1721 if( f==0 ){
1722 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1723 goto edit_func_end;
1725 sz = sqlite3_value_bytes(argv[0]);
1726 if( bBin ){
1727 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1728 }else{
1729 const char *z = (const char*)sqlite3_value_text(argv[0]);
1730 /* Remember whether or not the value originally contained \r\n */
1731 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1732 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1734 fclose(f);
1735 f = 0;
1736 if( x!=sz ){
1737 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1738 goto edit_func_end;
1740 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1741 if( zCmd==0 ){
1742 sqlite3_result_error_nomem(context);
1743 goto edit_func_end;
1745 rc = system(zCmd);
1746 sqlite3_free(zCmd);
1747 if( rc ){
1748 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1749 goto edit_func_end;
1751 f = fopen(zTempFile, "rb");
1752 if( f==0 ){
1753 sqlite3_result_error(context,
1754 "edit() cannot reopen temp file after edit", -1);
1755 goto edit_func_end;
1757 fseek(f, 0, SEEK_END);
1758 sz = ftell(f);
1759 rewind(f);
1760 p = sqlite3_malloc64( sz+1 );
1761 if( p==0 ){
1762 sqlite3_result_error_nomem(context);
1763 goto edit_func_end;
1765 x = fread(p, 1, (size_t)sz, f);
1766 fclose(f);
1767 f = 0;
1768 if( x!=sz ){
1769 sqlite3_result_error(context, "could not read back the whole file", -1);
1770 goto edit_func_end;
1772 if( bBin ){
1773 sqlite3_result_blob64(context, p, sz, sqlite3_free);
1774 }else{
1775 sqlite3_int64 i, j;
1776 if( hasCRNL ){
1777 /* If the original contains \r\n then do no conversions back to \n */
1778 }else{
1779 /* If the file did not originally contain \r\n then convert any new
1780 ** \r\n back into \n */
1781 p[sz] = 0;
1782 for(i=j=0; i<sz; i++){
1783 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1784 p[j++] = p[i];
1786 sz = j;
1787 p[sz] = 0;
1789 sqlite3_result_text64(context, (const char*)p, sz,
1790 sqlite3_free, SQLITE_UTF8);
1792 p = 0;
1794 edit_func_end:
1795 if( f ) fclose(f);
1796 unlink(zTempFile);
1797 sqlite3_free(zTempFile);
1798 sqlite3_free(p);
1800 #endif /* SQLITE_NOHAVE_SYSTEM */
1803 ** Save or restore the current output mode
1805 static void outputModePush(ShellState *p){
1806 p->modePrior = p->mode;
1807 p->priorShFlgs = p->shellFlgs;
1808 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1809 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1811 static void outputModePop(ShellState *p){
1812 p->mode = p->modePrior;
1813 p->shellFlgs = p->priorShFlgs;
1814 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1815 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1819 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1821 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1822 int i;
1823 unsigned char *aBlob = (unsigned char*)pBlob;
1825 char *zStr = sqlite3_malloc(nBlob*2 + 1);
1826 shell_check_oom(zStr);
1828 for(i=0; i<nBlob; i++){
1829 static const char aHex[] = {
1830 '0', '1', '2', '3', '4', '5', '6', '7',
1831 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1833 zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1834 zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1836 zStr[i*2] = '\0';
1838 raw_printf(out,"X'%s'", zStr);
1839 sqlite3_free(zStr);
1843 ** Find a string that is not found anywhere in z[]. Return a pointer
1844 ** to that string.
1846 ** Try to use zA and zB first. If both of those are already found in z[]
1847 ** then make up some string and store it in the buffer zBuf.
1849 static const char *unused_string(
1850 const char *z, /* Result must not appear anywhere in z */
1851 const char *zA, const char *zB, /* Try these first */
1852 char *zBuf /* Space to store a generated string */
1854 unsigned i = 0;
1855 if( strstr(z, zA)==0 ) return zA;
1856 if( strstr(z, zB)==0 ) return zB;
1858 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1859 }while( strstr(z,zBuf)!=0 );
1860 return zBuf;
1864 ** Output the given string as a quoted string using SQL quoting conventions.
1866 ** See also: output_quoted_escaped_string()
1868 static void output_quoted_string(FILE *out, const char *z){
1869 int i;
1870 char c;
1871 setBinaryMode(out, 1);
1872 if( z==0 ) return;
1873 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1874 if( c==0 ){
1875 utf8_printf(out,"'%s'",z);
1876 }else{
1877 raw_printf(out, "'");
1878 while( *z ){
1879 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1880 if( c=='\'' ) i++;
1881 if( i ){
1882 utf8_printf(out, "%.*s", i, z);
1883 z += i;
1885 if( c=='\'' ){
1886 raw_printf(out, "'");
1887 continue;
1889 if( c==0 ){
1890 break;
1892 z++;
1894 raw_printf(out, "'");
1896 setTextMode(out, 1);
1900 ** Output the given string as a quoted string using SQL quoting conventions.
1901 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1902 ** get corrupted by end-of-line translation facilities in some operating
1903 ** systems.
1905 ** This is like output_quoted_string() but with the addition of the \r\n
1906 ** escape mechanism.
1908 static void output_quoted_escaped_string(FILE *out, const char *z){
1909 int i;
1910 char c;
1911 setBinaryMode(out, 1);
1912 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1913 if( c==0 ){
1914 utf8_printf(out,"'%s'",z);
1915 }else{
1916 const char *zNL = 0;
1917 const char *zCR = 0;
1918 int nNL = 0;
1919 int nCR = 0;
1920 char zBuf1[20], zBuf2[20];
1921 for(i=0; z[i]; i++){
1922 if( z[i]=='\n' ) nNL++;
1923 if( z[i]=='\r' ) nCR++;
1925 if( nNL ){
1926 raw_printf(out, "replace(");
1927 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1929 if( nCR ){
1930 raw_printf(out, "replace(");
1931 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1933 raw_printf(out, "'");
1934 while( *z ){
1935 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1936 if( c=='\'' ) i++;
1937 if( i ){
1938 utf8_printf(out, "%.*s", i, z);
1939 z += i;
1941 if( c=='\'' ){
1942 raw_printf(out, "'");
1943 continue;
1945 if( c==0 ){
1946 break;
1948 z++;
1949 if( c=='\n' ){
1950 raw_printf(out, "%s", zNL);
1951 continue;
1953 raw_printf(out, "%s", zCR);
1955 raw_printf(out, "'");
1956 if( nCR ){
1957 raw_printf(out, ",'%s',char(13))", zCR);
1959 if( nNL ){
1960 raw_printf(out, ",'%s',char(10))", zNL);
1963 setTextMode(out, 1);
1967 ** Output the given string as a quoted according to C or TCL quoting rules.
1969 static void output_c_string(FILE *out, const char *z){
1970 unsigned int c;
1971 fputc('"', out);
1972 while( (c = *(z++))!=0 ){
1973 if( c=='\\' ){
1974 fputc(c, out);
1975 fputc(c, out);
1976 }else if( c=='"' ){
1977 fputc('\\', out);
1978 fputc('"', out);
1979 }else if( c=='\t' ){
1980 fputc('\\', out);
1981 fputc('t', out);
1982 }else if( c=='\n' ){
1983 fputc('\\', out);
1984 fputc('n', out);
1985 }else if( c=='\r' ){
1986 fputc('\\', out);
1987 fputc('r', out);
1988 }else if( !isprint(c&0xff) ){
1989 raw_printf(out, "\\%03o", c&0xff);
1990 }else{
1991 fputc(c, out);
1994 fputc('"', out);
1998 ** Output the given string as a quoted according to JSON quoting rules.
2000 static void output_json_string(FILE *out, const char *z, i64 n){
2001 unsigned int c;
2002 if( z==0 ) z = "";
2003 if( n<0 ) n = strlen(z);
2004 fputc('"', out);
2005 while( n-- ){
2006 c = *(z++);
2007 if( c=='\\' || c=='"' ){
2008 fputc('\\', out);
2009 fputc(c, out);
2010 }else if( c<=0x1f ){
2011 fputc('\\', out);
2012 if( c=='\b' ){
2013 fputc('b', out);
2014 }else if( c=='\f' ){
2015 fputc('f', out);
2016 }else if( c=='\n' ){
2017 fputc('n', out);
2018 }else if( c=='\r' ){
2019 fputc('r', out);
2020 }else if( c=='\t' ){
2021 fputc('t', out);
2022 }else{
2023 raw_printf(out, "u%04x",c);
2025 }else{
2026 fputc(c, out);
2029 fputc('"', out);
2033 ** Output the given string with characters that are special to
2034 ** HTML escaped.
2036 static void output_html_string(FILE *out, const char *z){
2037 int i;
2038 if( z==0 ) z = "";
2039 while( *z ){
2040 for(i=0; z[i]
2041 && z[i]!='<'
2042 && z[i]!='&'
2043 && z[i]!='>'
2044 && z[i]!='\"'
2045 && z[i]!='\'';
2046 i++){}
2047 if( i>0 ){
2048 utf8_printf(out,"%.*s",i,z);
2050 if( z[i]=='<' ){
2051 raw_printf(out,"&lt;");
2052 }else if( z[i]=='&' ){
2053 raw_printf(out,"&amp;");
2054 }else if( z[i]=='>' ){
2055 raw_printf(out,"&gt;");
2056 }else if( z[i]=='\"' ){
2057 raw_printf(out,"&quot;");
2058 }else if( z[i]=='\'' ){
2059 raw_printf(out,"&#39;");
2060 }else{
2061 break;
2063 z += i + 1;
2068 ** If a field contains any character identified by a 1 in the following
2069 ** array, then the string must be quoted for CSV.
2071 static const char needCsvQuote[] = {
2072 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2073 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2074 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2075 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2076 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2077 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2078 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2079 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2082 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2083 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2084 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2085 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2086 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2087 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2091 ** Output a single term of CSV. Actually, p->colSeparator is used for
2092 ** the separator, which may or may not be a comma. p->nullValue is
2093 ** the null value. Strings are quoted if necessary. The separator
2094 ** is only issued if bSep is true.
2096 static void output_csv(ShellState *p, const char *z, int bSep){
2097 FILE *out = p->out;
2098 if( z==0 ){
2099 utf8_printf(out,"%s",p->nullValue);
2100 }else{
2101 unsigned i;
2102 for(i=0; z[i]; i++){
2103 if( needCsvQuote[((unsigned char*)z)[i]] ){
2104 i = 0;
2105 break;
2108 if( i==0 || strstr(z, p->colSeparator)!=0 ){
2109 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
2110 shell_check_oom(zQuoted);
2111 utf8_printf(out, "%s", zQuoted);
2112 sqlite3_free(zQuoted);
2113 }else{
2114 utf8_printf(out, "%s", z);
2117 if( bSep ){
2118 utf8_printf(p->out, "%s", p->colSeparator);
2123 ** This routine runs when the user presses Ctrl-C
2125 static void interrupt_handler(int NotUsed){
2126 UNUSED_PARAMETER(NotUsed);
2127 if( ++seenInterrupt>1 ) exit(1);
2128 if( globalDb ) sqlite3_interrupt(globalDb);
2131 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
2133 ** This routine runs for console events (e.g. Ctrl-C) on Win32
2135 static BOOL WINAPI ConsoleCtrlHandler(
2136 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
2138 if( dwCtrlType==CTRL_C_EVENT ){
2139 interrupt_handler(0);
2140 return TRUE;
2142 return FALSE;
2144 #endif
2146 #ifndef SQLITE_OMIT_AUTHORIZATION
2148 ** This authorizer runs in safe mode.
2150 static int safeModeAuth(
2151 void *pClientData,
2152 int op,
2153 const char *zA1,
2154 const char *zA2,
2155 const char *zA3,
2156 const char *zA4
2158 ShellState *p = (ShellState*)pClientData;
2159 static const char *azProhibitedFunctions[] = {
2160 "edit",
2161 "fts3_tokenizer",
2162 "load_extension",
2163 "readfile",
2164 "writefile",
2165 "zipfile",
2166 "zipfile_cds",
2168 UNUSED_PARAMETER(zA1);
2169 UNUSED_PARAMETER(zA3);
2170 UNUSED_PARAMETER(zA4);
2171 switch( op ){
2172 case SQLITE_ATTACH: {
2173 #ifndef SQLITE_SHELL_FIDDLE
2174 /* In WASM builds the filesystem is a virtual sandbox, so
2175 ** there's no harm in using ATTACH. */
2176 failIfSafeMode(p, "cannot run ATTACH in safe mode");
2177 #endif
2178 break;
2180 case SQLITE_FUNCTION: {
2181 int i;
2182 for(i=0; i<ArraySize(azProhibitedFunctions); i++){
2183 if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
2184 failIfSafeMode(p, "cannot use the %s() function in safe mode",
2185 azProhibitedFunctions[i]);
2188 break;
2191 return SQLITE_OK;
2195 ** When the ".auth ON" is set, the following authorizer callback is
2196 ** invoked. It always returns SQLITE_OK.
2198 static int shellAuth(
2199 void *pClientData,
2200 int op,
2201 const char *zA1,
2202 const char *zA2,
2203 const char *zA3,
2204 const char *zA4
2206 ShellState *p = (ShellState*)pClientData;
2207 static const char *azAction[] = { 0,
2208 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2209 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2210 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2211 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2212 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2213 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2214 "PRAGMA", "READ", "SELECT",
2215 "TRANSACTION", "UPDATE", "ATTACH",
2216 "DETACH", "ALTER_TABLE", "REINDEX",
2217 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2218 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2220 int i;
2221 const char *az[4];
2222 az[0] = zA1;
2223 az[1] = zA2;
2224 az[2] = zA3;
2225 az[3] = zA4;
2226 utf8_printf(p->out, "authorizer: %s", azAction[op]);
2227 for(i=0; i<4; i++){
2228 raw_printf(p->out, " ");
2229 if( az[i] ){
2230 output_c_string(p->out, az[i]);
2231 }else{
2232 raw_printf(p->out, "NULL");
2235 raw_printf(p->out, "\n");
2236 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
2237 return SQLITE_OK;
2239 #endif
2242 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2244 ** This routine converts some CREATE TABLE statements for shadow tables
2245 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2247 ** If the schema statement in z[] contains a start-of-comment and if
2248 ** sqlite3_complete() returns false, try to terminate the comment before
2249 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2251 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
2252 char *zToFree = 0;
2253 if( z==0 ) return;
2254 if( zTail==0 ) return;
2255 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
2256 const char *zOrig = z;
2257 static const char *azTerm[] = { "", "*/", "\n" };
2258 int i;
2259 for(i=0; i<ArraySize(azTerm); i++){
2260 char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
2261 shell_check_oom(zNew);
2262 if( sqlite3_complete(zNew) ){
2263 size_t n = strlen(zNew);
2264 zNew[n-1] = 0;
2265 zToFree = zNew;
2266 z = zNew;
2267 break;
2269 sqlite3_free(zNew);
2272 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
2273 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
2274 }else{
2275 utf8_printf(out, "%s%s", z, zTail);
2277 sqlite3_free(zToFree);
2279 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
2280 char c = z[n];
2281 z[n] = 0;
2282 printSchemaLine(out, z, zTail);
2283 z[n] = c;
2287 ** Return true if string z[] has nothing but whitespace and comments to the
2288 ** end of the first line.
2290 static int wsToEol(const char *z){
2291 int i;
2292 for(i=0; z[i]; i++){
2293 if( z[i]=='\n' ) return 1;
2294 if( IsSpace(z[i]) ) continue;
2295 if( z[i]=='-' && z[i+1]=='-' ) return 1;
2296 return 0;
2298 return 1;
2302 ** Add a new entry to the EXPLAIN QUERY PLAN data
2304 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
2305 EQPGraphRow *pNew;
2306 i64 nText;
2307 if( zText==0 ) return;
2308 nText = strlen(zText);
2309 if( p->autoEQPtest ){
2310 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
2312 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
2313 shell_check_oom(pNew);
2314 pNew->iEqpId = iEqpId;
2315 pNew->iParentId = p2;
2316 memcpy(pNew->zText, zText, nText+1);
2317 pNew->pNext = 0;
2318 if( p->sGraph.pLast ){
2319 p->sGraph.pLast->pNext = pNew;
2320 }else{
2321 p->sGraph.pRow = pNew;
2323 p->sGraph.pLast = pNew;
2327 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2328 ** in p->sGraph.
2330 static void eqp_reset(ShellState *p){
2331 EQPGraphRow *pRow, *pNext;
2332 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2333 pNext = pRow->pNext;
2334 sqlite3_free(pRow);
2336 memset(&p->sGraph, 0, sizeof(p->sGraph));
2339 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2340 ** pOld, or return the first such line if pOld is NULL
2342 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2343 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2344 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2345 return pRow;
2348 /* Render a single level of the graph that has iEqpId as its parent. Called
2349 ** recursively to render sublevels.
2351 static void eqp_render_level(ShellState *p, int iEqpId){
2352 EQPGraphRow *pRow, *pNext;
2353 i64 n = strlen(p->sGraph.zPrefix);
2354 char *z;
2355 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2356 pNext = eqp_next_row(p, iEqpId, pRow);
2357 z = pRow->zText;
2358 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2359 pNext ? "|--" : "`--", z);
2360 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
2361 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
2362 eqp_render_level(p, pRow->iEqpId);
2363 p->sGraph.zPrefix[n] = 0;
2369 ** Display and reset the EXPLAIN QUERY PLAN data
2371 static void eqp_render(ShellState *p, i64 nCycle){
2372 EQPGraphRow *pRow = p->sGraph.pRow;
2373 if( pRow ){
2374 if( pRow->zText[0]=='-' ){
2375 if( pRow->pNext==0 ){
2376 eqp_reset(p);
2377 return;
2379 utf8_printf(p->out, "%s\n", pRow->zText+3);
2380 p->sGraph.pRow = pRow->pNext;
2381 sqlite3_free(pRow);
2382 }else if( nCycle>0 ){
2383 utf8_printf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
2384 }else{
2385 utf8_printf(p->out, "QUERY PLAN\n");
2387 p->sGraph.zPrefix[0] = 0;
2388 eqp_render_level(p, 0);
2389 eqp_reset(p);
2393 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2395 ** Progress handler callback.
2397 static int progress_handler(void *pClientData) {
2398 ShellState *p = (ShellState*)pClientData;
2399 p->nProgress++;
2400 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2401 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2402 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2403 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2404 return 1;
2406 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2407 raw_printf(p->out, "Progress %u\n", p->nProgress);
2409 return 0;
2411 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2414 ** Print N dashes
2416 static void print_dashes(FILE *out, int N){
2417 const char zDash[] = "--------------------------------------------------";
2418 const int nDash = sizeof(zDash) - 1;
2419 while( N>nDash ){
2420 fputs(zDash, out);
2421 N -= nDash;
2423 raw_printf(out, "%.*s", N, zDash);
2427 ** Print a markdown or table-style row separator using ascii-art
2429 static void print_row_separator(
2430 ShellState *p,
2431 int nArg,
2432 const char *zSep
2434 int i;
2435 if( nArg>0 ){
2436 fputs(zSep, p->out);
2437 print_dashes(p->out, p->actualWidth[0]+2);
2438 for(i=1; i<nArg; i++){
2439 fputs(zSep, p->out);
2440 print_dashes(p->out, p->actualWidth[i]+2);
2442 fputs(zSep, p->out);
2444 fputs("\n", p->out);
2448 ** This is the callback routine that the shell
2449 ** invokes for each row of a query result.
2451 static int shell_callback(
2452 void *pArg,
2453 int nArg, /* Number of result columns */
2454 char **azArg, /* Text of each result column */
2455 char **azCol, /* Column names */
2456 int *aiType /* Column types. Might be NULL */
2458 int i;
2459 ShellState *p = (ShellState*)pArg;
2461 if( azArg==0 ) return 0;
2462 switch( p->cMode ){
2463 case MODE_Count:
2464 case MODE_Off: {
2465 break;
2467 case MODE_Line: {
2468 int w = 5;
2469 if( azArg==0 ) break;
2470 for(i=0; i<nArg; i++){
2471 int len = strlen30(azCol[i] ? azCol[i] : "");
2472 if( len>w ) w = len;
2474 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2475 for(i=0; i<nArg; i++){
2476 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2477 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2479 break;
2481 case MODE_Explain: {
2482 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2483 if( nArg>ArraySize(aExplainWidth) ){
2484 nArg = ArraySize(aExplainWidth);
2486 if( p->cnt++==0 ){
2487 for(i=0; i<nArg; i++){
2488 int w = aExplainWidth[i];
2489 utf8_width_print(p->out, w, azCol[i]);
2490 fputs(i==nArg-1 ? "\n" : " ", p->out);
2492 for(i=0; i<nArg; i++){
2493 int w = aExplainWidth[i];
2494 print_dashes(p->out, w);
2495 fputs(i==nArg-1 ? "\n" : " ", p->out);
2498 if( azArg==0 ) break;
2499 for(i=0; i<nArg; i++){
2500 int w = aExplainWidth[i];
2501 if( i==nArg-1 ) w = 0;
2502 if( azArg[i] && strlenChar(azArg[i])>w ){
2503 w = strlenChar(azArg[i]);
2505 if( i==1 && p->aiIndent && p->pStmt ){
2506 if( p->iIndent<p->nIndent ){
2507 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2509 p->iIndent++;
2511 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2512 fputs(i==nArg-1 ? "\n" : " ", p->out);
2514 break;
2516 case MODE_Semi: { /* .schema and .fullschema output */
2517 printSchemaLine(p->out, azArg[0], ";\n");
2518 break;
2520 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2521 char *z;
2522 int j;
2523 int nParen = 0;
2524 char cEnd = 0;
2525 char c;
2526 int nLine = 0;
2527 assert( nArg==1 );
2528 if( azArg[0]==0 ) break;
2529 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2530 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2532 utf8_printf(p->out, "%s;\n", azArg[0]);
2533 break;
2535 z = sqlite3_mprintf("%s", azArg[0]);
2536 shell_check_oom(z);
2537 j = 0;
2538 for(i=0; IsSpace(z[i]); i++){}
2539 for(; (c = z[i])!=0; i++){
2540 if( IsSpace(c) ){
2541 if( z[j-1]=='\r' ) z[j-1] = '\n';
2542 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2543 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2544 j--;
2546 z[j++] = c;
2548 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2549 z[j] = 0;
2550 if( strlen30(z)>=79 ){
2551 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2552 if( c==cEnd ){
2553 cEnd = 0;
2554 }else if( c=='"' || c=='\'' || c=='`' ){
2555 cEnd = c;
2556 }else if( c=='[' ){
2557 cEnd = ']';
2558 }else if( c=='-' && z[i+1]=='-' ){
2559 cEnd = '\n';
2560 }else if( c=='(' ){
2561 nParen++;
2562 }else if( c==')' ){
2563 nParen--;
2564 if( nLine>0 && nParen==0 && j>0 ){
2565 printSchemaLineN(p->out, z, j, "\n");
2566 j = 0;
2569 z[j++] = c;
2570 if( nParen==1 && cEnd==0
2571 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2573 if( c=='\n' ) j--;
2574 printSchemaLineN(p->out, z, j, "\n ");
2575 j = 0;
2576 nLine++;
2577 while( IsSpace(z[i+1]) ){ i++; }
2580 z[j] = 0;
2582 printSchemaLine(p->out, z, ";\n");
2583 sqlite3_free(z);
2584 break;
2586 case MODE_List: {
2587 if( p->cnt++==0 && p->showHeader ){
2588 for(i=0; i<nArg; i++){
2589 utf8_printf(p->out,"%s%s",azCol[i],
2590 i==nArg-1 ? p->rowSeparator : p->colSeparator);
2593 if( azArg==0 ) break;
2594 for(i=0; i<nArg; i++){
2595 char *z = azArg[i];
2596 if( z==0 ) z = p->nullValue;
2597 utf8_printf(p->out, "%s", z);
2598 if( i<nArg-1 ){
2599 utf8_printf(p->out, "%s", p->colSeparator);
2600 }else{
2601 utf8_printf(p->out, "%s", p->rowSeparator);
2604 break;
2606 case MODE_Html: {
2607 if( p->cnt++==0 && p->showHeader ){
2608 raw_printf(p->out,"<TR>");
2609 for(i=0; i<nArg; i++){
2610 raw_printf(p->out,"<TH>");
2611 output_html_string(p->out, azCol[i]);
2612 raw_printf(p->out,"</TH>\n");
2614 raw_printf(p->out,"</TR>\n");
2616 if( azArg==0 ) break;
2617 raw_printf(p->out,"<TR>");
2618 for(i=0; i<nArg; i++){
2619 raw_printf(p->out,"<TD>");
2620 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2621 raw_printf(p->out,"</TD>\n");
2623 raw_printf(p->out,"</TR>\n");
2624 break;
2626 case MODE_Tcl: {
2627 if( p->cnt++==0 && p->showHeader ){
2628 for(i=0; i<nArg; i++){
2629 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2630 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2632 utf8_printf(p->out, "%s", p->rowSeparator);
2634 if( azArg==0 ) break;
2635 for(i=0; i<nArg; i++){
2636 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2637 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2639 utf8_printf(p->out, "%s", p->rowSeparator);
2640 break;
2642 case MODE_Csv: {
2643 setBinaryMode(p->out, 1);
2644 if( p->cnt++==0 && p->showHeader ){
2645 for(i=0; i<nArg; i++){
2646 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2648 utf8_printf(p->out, "%s", p->rowSeparator);
2650 if( nArg>0 ){
2651 for(i=0; i<nArg; i++){
2652 output_csv(p, azArg[i], i<nArg-1);
2654 utf8_printf(p->out, "%s", p->rowSeparator);
2656 setTextMode(p->out, 1);
2657 break;
2659 case MODE_Insert: {
2660 if( azArg==0 ) break;
2661 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2662 if( p->showHeader ){
2663 raw_printf(p->out,"(");
2664 for(i=0; i<nArg; i++){
2665 if( i>0 ) raw_printf(p->out, ",");
2666 if( quoteChar(azCol[i]) ){
2667 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2668 shell_check_oom(z);
2669 utf8_printf(p->out, "%s", z);
2670 sqlite3_free(z);
2671 }else{
2672 raw_printf(p->out, "%s", azCol[i]);
2675 raw_printf(p->out,")");
2677 p->cnt++;
2678 for(i=0; i<nArg; i++){
2679 raw_printf(p->out, i>0 ? "," : " VALUES(");
2680 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2681 utf8_printf(p->out,"NULL");
2682 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2683 if( ShellHasFlag(p, SHFLG_Newlines) ){
2684 output_quoted_string(p->out, azArg[i]);
2685 }else{
2686 output_quoted_escaped_string(p->out, azArg[i]);
2688 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2689 utf8_printf(p->out,"%s", azArg[i]);
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 raw_printf(p->out, "9.0e+999");
2697 }else if( ur==0xfff0000000000000LL ){
2698 raw_printf(p->out, "-9.0e+999");
2699 }else{
2700 sqlite3_int64 ir = (sqlite3_int64)r;
2701 if( r==(double)ir ){
2702 sqlite3_snprintf(50,z,"%lld.0", ir);
2703 }else{
2704 sqlite3_snprintf(50,z,"%!.20g", r);
2706 raw_printf(p->out, "%s", z);
2708 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2709 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2710 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2711 output_hex_blob(p->out, pBlob, nBlob);
2712 }else if( isNumber(azArg[i], 0) ){
2713 utf8_printf(p->out,"%s", azArg[i]);
2714 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2715 output_quoted_string(p->out, azArg[i]);
2716 }else{
2717 output_quoted_escaped_string(p->out, azArg[i]);
2720 raw_printf(p->out,");\n");
2721 break;
2723 case MODE_Json: {
2724 if( azArg==0 ) break;
2725 if( p->cnt==0 ){
2726 fputs("[{", p->out);
2727 }else{
2728 fputs(",\n{", p->out);
2730 p->cnt++;
2731 for(i=0; i<nArg; i++){
2732 output_json_string(p->out, azCol[i], -1);
2733 putc(':', p->out);
2734 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2735 fputs("null",p->out);
2736 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2737 char z[50];
2738 double r = sqlite3_column_double(p->pStmt, i);
2739 sqlite3_uint64 ur;
2740 memcpy(&ur,&r,sizeof(r));
2741 if( ur==0x7ff0000000000000LL ){
2742 raw_printf(p->out, "9.0e+999");
2743 }else if( ur==0xfff0000000000000LL ){
2744 raw_printf(p->out, "-9.0e+999");
2745 }else{
2746 sqlite3_snprintf(50,z,"%!.20g", r);
2747 raw_printf(p->out, "%s", z);
2749 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2750 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2751 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2752 output_json_string(p->out, pBlob, nBlob);
2753 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2754 output_json_string(p->out, azArg[i], -1);
2755 }else{
2756 utf8_printf(p->out,"%s", azArg[i]);
2758 if( i<nArg-1 ){
2759 putc(',', p->out);
2762 putc('}', p->out);
2763 break;
2765 case MODE_Quote: {
2766 if( azArg==0 ) break;
2767 if( p->cnt==0 && p->showHeader ){
2768 for(i=0; i<nArg; i++){
2769 if( i>0 ) fputs(p->colSeparator, p->out);
2770 output_quoted_string(p->out, azCol[i]);
2772 fputs(p->rowSeparator, p->out);
2774 p->cnt++;
2775 for(i=0; i<nArg; i++){
2776 if( i>0 ) fputs(p->colSeparator, p->out);
2777 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2778 utf8_printf(p->out,"NULL");
2779 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2780 output_quoted_string(p->out, azArg[i]);
2781 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2782 utf8_printf(p->out,"%s", azArg[i]);
2783 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2784 char z[50];
2785 double r = sqlite3_column_double(p->pStmt, i);
2786 sqlite3_snprintf(50,z,"%!.20g", r);
2787 raw_printf(p->out, "%s", z);
2788 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2789 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2790 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2791 output_hex_blob(p->out, pBlob, nBlob);
2792 }else if( isNumber(azArg[i], 0) ){
2793 utf8_printf(p->out,"%s", azArg[i]);
2794 }else{
2795 output_quoted_string(p->out, azArg[i]);
2798 fputs(p->rowSeparator, p->out);
2799 break;
2801 case MODE_Ascii: {
2802 if( p->cnt++==0 && p->showHeader ){
2803 for(i=0; i<nArg; i++){
2804 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2805 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2807 utf8_printf(p->out, "%s", p->rowSeparator);
2809 if( azArg==0 ) break;
2810 for(i=0; i<nArg; i++){
2811 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2812 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2814 utf8_printf(p->out, "%s", p->rowSeparator);
2815 break;
2817 case MODE_EQP: {
2818 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2819 break;
2822 return 0;
2826 ** This is the callback routine that the SQLite library
2827 ** invokes for each row of a query result.
2829 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2830 /* since we don't have type info, call the shell_callback with a NULL value */
2831 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2835 ** This is the callback routine from sqlite3_exec() that appends all
2836 ** output onto the end of a ShellText object.
2838 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2839 ShellText *p = (ShellText*)pArg;
2840 int i;
2841 UNUSED_PARAMETER(az);
2842 if( azArg==0 ) return 0;
2843 if( p->n ) appendText(p, "|", 0);
2844 for(i=0; i<nArg; i++){
2845 if( i ) appendText(p, ",", 0);
2846 if( azArg[i] ) appendText(p, azArg[i], 0);
2848 return 0;
2852 ** Generate an appropriate SELFTEST table in the main database.
2854 static void createSelftestTable(ShellState *p){
2855 char *zErrMsg = 0;
2856 sqlite3_exec(p->db,
2857 "SAVEPOINT selftest_init;\n"
2858 "CREATE TABLE IF NOT EXISTS selftest(\n"
2859 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2860 " op TEXT,\n" /* Operator: memo run */
2861 " cmd TEXT,\n" /* Command text */
2862 " ans TEXT\n" /* Desired answer */
2863 ");"
2864 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2865 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2866 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2867 " 'memo','Tests generated by --init');\n"
2868 "INSERT INTO [_shell$self]\n"
2869 " SELECT 'run',\n"
2870 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2871 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2872 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2873 "FROM sqlite_schema ORDER BY 2',224));\n"
2874 "INSERT INTO [_shell$self]\n"
2875 " SELECT 'run',"
2876 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2877 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2878 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2879 " FROM (\n"
2880 " SELECT name FROM sqlite_schema\n"
2881 " WHERE type='table'\n"
2882 " AND name<>'selftest'\n"
2883 " AND coalesce(rootpage,0)>0\n"
2884 " )\n"
2885 " ORDER BY name;\n"
2886 "INSERT INTO [_shell$self]\n"
2887 " VALUES('run','PRAGMA integrity_check','ok');\n"
2888 "INSERT INTO selftest(tno,op,cmd,ans)"
2889 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2890 "DROP TABLE [_shell$self];"
2891 ,0,0,&zErrMsg);
2892 if( zErrMsg ){
2893 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2894 sqlite3_free(zErrMsg);
2896 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2901 ** Set the destination table field of the ShellState structure to
2902 ** the name of the table given. Escape any quote characters in the
2903 ** table name.
2905 static void set_table_name(ShellState *p, const char *zName){
2906 int i, n;
2907 char cQuote;
2908 char *z;
2910 if( p->zDestTable ){
2911 free(p->zDestTable);
2912 p->zDestTable = 0;
2914 if( zName==0 ) return;
2915 cQuote = quoteChar(zName);
2916 n = strlen30(zName);
2917 if( cQuote ) n += n+2;
2918 z = p->zDestTable = malloc( n+1 );
2919 shell_check_oom(z);
2920 n = 0;
2921 if( cQuote ) z[n++] = cQuote;
2922 for(i=0; zName[i]; i++){
2923 z[n++] = zName[i];
2924 if( zName[i]==cQuote ) z[n++] = cQuote;
2926 if( cQuote ) z[n++] = cQuote;
2927 z[n] = 0;
2931 ** Maybe construct two lines of text that point out the position of a
2932 ** syntax error. Return a pointer to the text, in memory obtained from
2933 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2934 ** specific token that we can point to, return an empty string.
2936 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2937 ** and should be released by the caller invoking sqlite3_free().
2939 static char *shell_error_context(const char *zSql, sqlite3 *db){
2940 int iOffset;
2941 size_t len;
2942 char *zCode;
2943 char *zMsg;
2944 int i;
2945 if( db==0
2946 || zSql==0
2947 || (iOffset = sqlite3_error_offset(db))<0
2948 || iOffset>=(int)strlen(zSql)
2950 return sqlite3_mprintf("");
2952 while( iOffset>50 ){
2953 iOffset--;
2954 zSql++;
2955 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2957 len = strlen(zSql);
2958 if( len>78 ){
2959 len = 78;
2960 while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
2962 zCode = sqlite3_mprintf("%.*s", len, zSql);
2963 shell_check_oom(zCode);
2964 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2965 if( iOffset<25 ){
2966 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,"");
2967 }else{
2968 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,"");
2970 return zMsg;
2975 ** Execute a query statement that will generate SQL output. Print
2976 ** the result columns, comma-separated, on a line and then add a
2977 ** semicolon terminator to the end of that line.
2979 ** If the number of columns is 1 and that column contains text "--"
2980 ** then write the semicolon on a separate line. That way, if a
2981 ** "--" comment occurs at the end of the statement, the comment
2982 ** won't consume the semicolon terminator.
2984 static int run_table_dump_query(
2985 ShellState *p, /* Query context */
2986 const char *zSelect /* SELECT statement to extract content */
2988 sqlite3_stmt *pSelect;
2989 int rc;
2990 int nResult;
2991 int i;
2992 const char *z;
2993 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2994 if( rc!=SQLITE_OK || !pSelect ){
2995 char *zContext = shell_error_context(zSelect, p->db);
2996 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2997 sqlite3_errmsg(p->db), zContext);
2998 sqlite3_free(zContext);
2999 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
3000 return rc;
3002 rc = sqlite3_step(pSelect);
3003 nResult = sqlite3_column_count(pSelect);
3004 while( rc==SQLITE_ROW ){
3005 z = (const char*)sqlite3_column_text(pSelect, 0);
3006 utf8_printf(p->out, "%s", z);
3007 for(i=1; i<nResult; i++){
3008 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
3010 if( z==0 ) z = "";
3011 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
3012 if( z[0] ){
3013 raw_printf(p->out, "\n;\n");
3014 }else{
3015 raw_printf(p->out, ";\n");
3017 rc = sqlite3_step(pSelect);
3019 rc = sqlite3_finalize(pSelect);
3020 if( rc!=SQLITE_OK ){
3021 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
3022 sqlite3_errmsg(p->db));
3023 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
3025 return rc;
3029 ** Allocate space and save off string indicating current error.
3031 static char *save_err_msg(
3032 sqlite3 *db, /* Database to query */
3033 const char *zPhase, /* When the error occcurs */
3034 int rc, /* Error code returned from API */
3035 const char *zSql /* SQL string, or NULL */
3037 char *zErr;
3038 char *zContext;
3039 sqlite3_str *pStr = sqlite3_str_new(0);
3040 sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
3041 if( rc>1 ){
3042 sqlite3_str_appendf(pStr, " (%d)", rc);
3044 zContext = shell_error_context(zSql, db);
3045 if( zContext ){
3046 sqlite3_str_appendall(pStr, zContext);
3047 sqlite3_free(zContext);
3049 zErr = sqlite3_str_finish(pStr);
3050 shell_check_oom(zErr);
3051 return zErr;
3054 #ifdef __linux__
3056 ** Attempt to display I/O stats on Linux using /proc/PID/io
3058 static void displayLinuxIoStats(FILE *out){
3059 FILE *in;
3060 char z[200];
3061 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
3062 in = fopen(z, "rb");
3063 if( in==0 ) return;
3064 while( fgets(z, sizeof(z), in)!=0 ){
3065 static const struct {
3066 const char *zPattern;
3067 const char *zDesc;
3068 } aTrans[] = {
3069 { "rchar: ", "Bytes received by read():" },
3070 { "wchar: ", "Bytes sent to write():" },
3071 { "syscr: ", "Read() system calls:" },
3072 { "syscw: ", "Write() system calls:" },
3073 { "read_bytes: ", "Bytes read from storage:" },
3074 { "write_bytes: ", "Bytes written to storage:" },
3075 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
3077 int i;
3078 for(i=0; i<ArraySize(aTrans); i++){
3079 int n = strlen30(aTrans[i].zPattern);
3080 if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
3081 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
3082 break;
3086 fclose(in);
3088 #endif
3091 ** Display a single line of status using 64-bit values.
3093 static void displayStatLine(
3094 ShellState *p, /* The shell context */
3095 char *zLabel, /* Label for this one line */
3096 char *zFormat, /* Format for the result */
3097 int iStatusCtrl, /* Which status to display */
3098 int bReset /* True to reset the stats */
3100 sqlite3_int64 iCur = -1;
3101 sqlite3_int64 iHiwtr = -1;
3102 int i, nPercent;
3103 char zLine[200];
3104 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
3105 for(i=0, nPercent=0; zFormat[i]; i++){
3106 if( zFormat[i]=='%' ) nPercent++;
3108 if( nPercent>1 ){
3109 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
3110 }else{
3111 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
3113 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
3117 ** Display memory stats.
3119 static int display_stats(
3120 sqlite3 *db, /* Database to query */
3121 ShellState *pArg, /* Pointer to ShellState */
3122 int bReset /* True to reset the stats */
3124 int iCur;
3125 int iHiwtr;
3126 FILE *out;
3127 if( pArg==0 || pArg->out==0 ) return 0;
3128 out = pArg->out;
3130 if( pArg->pStmt && pArg->statsOn==2 ){
3131 int nCol, i, x;
3132 sqlite3_stmt *pStmt = pArg->pStmt;
3133 char z[100];
3134 nCol = sqlite3_column_count(pStmt);
3135 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
3136 for(i=0; i<nCol; i++){
3137 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
3138 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
3139 #ifndef SQLITE_OMIT_DECLTYPE
3140 sqlite3_snprintf(30, z+x, "declared type:");
3141 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
3142 #endif
3143 #ifdef SQLITE_ENABLE_COLUMN_METADATA
3144 sqlite3_snprintf(30, z+x, "database name:");
3145 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
3146 sqlite3_snprintf(30, z+x, "table name:");
3147 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
3148 sqlite3_snprintf(30, z+x, "origin name:");
3149 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
3150 #endif
3154 if( pArg->statsOn==3 ){
3155 if( pArg->pStmt ){
3156 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
3157 raw_printf(pArg->out, "VM-steps: %d\n", iCur);
3159 return 0;
3162 displayStatLine(pArg, "Memory Used:",
3163 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
3164 displayStatLine(pArg, "Number of Outstanding Allocations:",
3165 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
3166 if( pArg->shellFlgs & SHFLG_Pagecache ){
3167 displayStatLine(pArg, "Number of Pcache Pages Used:",
3168 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
3170 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
3171 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
3172 displayStatLine(pArg, "Largest Allocation:",
3173 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
3174 displayStatLine(pArg, "Largest Pcache Allocation:",
3175 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
3176 #ifdef YYTRACKMAXSTACKDEPTH
3177 displayStatLine(pArg, "Deepest Parser Stack:",
3178 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
3179 #endif
3181 if( db ){
3182 if( pArg->shellFlgs & SHFLG_Lookaside ){
3183 iHiwtr = iCur = -1;
3184 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
3185 &iCur, &iHiwtr, bReset);
3186 raw_printf(pArg->out,
3187 "Lookaside Slots Used: %d (max %d)\n",
3188 iCur, iHiwtr);
3189 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
3190 &iCur, &iHiwtr, bReset);
3191 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
3192 iHiwtr);
3193 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
3194 &iCur, &iHiwtr, bReset);
3195 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
3196 iHiwtr);
3197 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
3198 &iCur, &iHiwtr, bReset);
3199 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
3200 iHiwtr);
3202 iHiwtr = iCur = -1;
3203 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
3204 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
3205 iCur);
3206 iHiwtr = iCur = -1;
3207 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
3208 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
3209 iHiwtr = iCur = -1;
3210 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
3211 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
3212 iHiwtr = iCur = -1;
3213 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
3214 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
3215 iHiwtr = iCur = -1;
3216 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
3217 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
3218 iHiwtr = iCur = -1;
3219 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
3220 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
3221 iCur);
3222 iHiwtr = iCur = -1;
3223 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
3224 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
3225 iCur);
3228 if( pArg->pStmt ){
3229 int iHit, iMiss;
3230 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
3231 bReset);
3232 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
3233 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
3234 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
3235 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
3236 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
3237 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
3238 bReset);
3239 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
3240 bReset);
3241 if( iHit || iMiss ){
3242 raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n",
3243 iHit, iHit+iMiss);
3245 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
3246 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
3247 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
3248 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
3249 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
3250 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
3251 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
3252 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
3255 #ifdef __linux__
3256 displayLinuxIoStats(pArg->out);
3257 #endif
3259 /* Do not remove this machine readable comment: extra-stats-output-here */
3261 return 0;
3265 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3266 static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
3267 int iPid = 0;
3268 int ret = 1;
3269 sqlite3_stmt_scanstatus_v2(p, iEntry,
3270 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3272 while( iPid!=0 ){
3273 int ii;
3274 for(ii=0; 1; ii++){
3275 int iId;
3276 int res;
3277 res = sqlite3_stmt_scanstatus_v2(p, ii,
3278 SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
3280 if( res ) break;
3281 if( iId==iPid ){
3282 sqlite3_stmt_scanstatus_v2(p, ii,
3283 SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
3287 ret++;
3289 return ret;
3291 #endif
3294 ** Display scan stats.
3296 static void display_scanstats(
3297 sqlite3 *db, /* Database to query */
3298 ShellState *pArg /* Pointer to ShellState */
3300 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3301 UNUSED_PARAMETER(db);
3302 UNUSED_PARAMETER(pArg);
3303 #else
3304 static const int f = SQLITE_SCANSTAT_COMPLEX;
3305 sqlite3_stmt *p = pArg->pStmt;
3306 int ii = 0;
3307 i64 nTotal = 0;
3308 int nWidth = 0;
3309 eqp_reset(pArg);
3311 for(ii=0; 1; ii++){
3312 const char *z = 0;
3313 int n = 0;
3314 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
3315 break;
3317 n = strlen(z) + scanStatsHeight(p, ii)*3;
3318 if( n>nWidth ) nWidth = n;
3320 nWidth += 4;
3322 sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
3323 for(ii=0; 1; ii++){
3324 i64 nLoop = 0;
3325 i64 nRow = 0;
3326 i64 nCycle = 0;
3327 int iId = 0;
3328 int iPid = 0;
3329 const char *z = 0;
3330 const char *zName = 0;
3331 char *zText = 0;
3332 double rEst = 0.0;
3334 if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
3335 break;
3337 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
3338 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
3339 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
3340 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
3341 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
3342 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
3343 sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
3345 zText = sqlite3_mprintf("%s", z);
3346 if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
3347 char *z = 0;
3348 if( nCycle>=0 && nTotal>0 ){
3349 z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
3350 nCycle, ((nCycle*100)+nTotal/2) / nTotal
3353 if( nLoop>=0 ){
3354 z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
3356 if( nRow>=0 ){
3357 z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
3360 if( zName && pArg->scanstatsOn>1 ){
3361 double rpl = (double)nRow / (double)nLoop;
3362 z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
3365 zText = sqlite3_mprintf(
3366 "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
3370 eqp_append(pArg, iId, iPid, zText);
3371 sqlite3_free(zText);
3374 eqp_render(pArg, nTotal);
3375 #endif
3379 ** Parameter azArray points to a zero-terminated array of strings. zStr
3380 ** points to a single nul-terminated string. Return non-zero if zStr
3381 ** is equal, according to strcmp(), to any of the strings in the array.
3382 ** Otherwise, return zero.
3384 static int str_in_array(const char *zStr, const char **azArray){
3385 int i;
3386 for(i=0; azArray[i]; i++){
3387 if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
3389 return 0;
3393 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3394 ** and populate the ShellState.aiIndent[] array with the number of
3395 ** spaces each opcode should be indented before it is output.
3397 ** The indenting rules are:
3399 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3400 ** all opcodes that occur between the p2 jump destination and the opcode
3401 ** itself by 2 spaces.
3403 ** * Do the previous for "Return" instructions for when P2 is positive.
3404 ** See tag-20220407a in wherecode.c and vdbe.c.
3406 ** * For each "Goto", if the jump destination is earlier in the program
3407 ** and ends on one of:
3408 ** Yield SeekGt SeekLt RowSetRead Rewind
3409 ** or if the P1 parameter is one instead of zero,
3410 ** then indent all opcodes between the earlier instruction
3411 ** and "Goto" by 2 spaces.
3413 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3414 const char *zSql; /* The text of the SQL statement */
3415 const char *z; /* Used to check if this is an EXPLAIN */
3416 int *abYield = 0; /* True if op is an OP_Yield */
3417 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
3418 int iOp; /* Index of operation in p->aiIndent[] */
3420 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3421 "Return", 0 };
3422 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3423 "Rewind", 0 };
3424 const char *azGoto[] = { "Goto", 0 };
3426 /* Try to figure out if this is really an EXPLAIN statement. If this
3427 ** cannot be verified, return early. */
3428 if( sqlite3_column_count(pSql)!=8 ){
3429 p->cMode = p->mode;
3430 return;
3432 zSql = sqlite3_sql(pSql);
3433 if( zSql==0 ) return;
3434 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3435 if( sqlite3_strnicmp(z, "explain", 7) ){
3436 p->cMode = p->mode;
3437 return;
3440 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3441 int i;
3442 int iAddr = sqlite3_column_int(pSql, 0);
3443 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3445 /* Set p2 to the P2 field of the current opcode. Then, assuming that
3446 ** p2 is an instruction address, set variable p2op to the index of that
3447 ** instruction in the aiIndent[] array. p2 and p2op may be different if
3448 ** the current instruction is part of a sub-program generated by an
3449 ** SQL trigger or foreign key. */
3450 int p2 = sqlite3_column_int(pSql, 3);
3451 int p2op = (p2 + (iOp-iAddr));
3453 /* Grow the p->aiIndent array as required */
3454 if( iOp>=nAlloc ){
3455 if( iOp==0 ){
3456 /* Do further verfication that this is explain output. Abort if
3457 ** it is not */
3458 static const char *explainCols[] = {
3459 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3460 int jj;
3461 for(jj=0; jj<ArraySize(explainCols); jj++){
3462 if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3463 p->cMode = p->mode;
3464 sqlite3_reset(pSql);
3465 return;
3469 nAlloc += 100;
3470 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3471 shell_check_oom(p->aiIndent);
3472 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3473 shell_check_oom(abYield);
3475 abYield[iOp] = str_in_array(zOp, azYield);
3476 p->aiIndent[iOp] = 0;
3477 p->nIndent = iOp+1;
3479 if( str_in_array(zOp, azNext) && p2op>0 ){
3480 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3482 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3483 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3485 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3489 p->iIndent = 0;
3490 sqlite3_free(abYield);
3491 sqlite3_reset(pSql);
3495 ** Free the array allocated by explain_data_prepare().
3497 static void explain_data_delete(ShellState *p){
3498 sqlite3_free(p->aiIndent);
3499 p->aiIndent = 0;
3500 p->nIndent = 0;
3501 p->iIndent = 0;
3505 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3507 static unsigned int savedSelectTrace;
3508 static unsigned int savedWhereTrace;
3509 static void disable_debug_trace_modes(void){
3510 unsigned int zero = 0;
3511 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3512 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3513 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3514 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3516 static void restore_debug_trace_modes(void){
3517 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3518 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3521 /* Create the TEMP table used to store parameter bindings */
3522 static void bind_table_init(ShellState *p){
3523 int wrSchema = 0;
3524 int defensiveMode = 0;
3525 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3526 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3527 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3528 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3529 sqlite3_exec(p->db,
3530 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3531 " key TEXT PRIMARY KEY,\n"
3532 " value\n"
3533 ") WITHOUT ROWID;",
3534 0, 0, 0);
3535 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3536 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3540 ** Bind parameters on a prepared statement.
3542 ** Parameter bindings are taken from a TEMP table of the form:
3544 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3545 ** WITHOUT ROWID;
3547 ** No bindings occur if this table does not exist. The name of the table
3548 ** begins with "sqlite_" so that it will not collide with ordinary application
3549 ** tables. The table must be in the TEMP schema.
3551 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3552 int nVar;
3553 int i;
3554 int rc;
3555 sqlite3_stmt *pQ = 0;
3557 nVar = sqlite3_bind_parameter_count(pStmt);
3558 if( nVar==0 ) return; /* Nothing to do */
3559 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3560 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3561 rc = SQLITE_NOTFOUND;
3562 pQ = 0;
3563 }else{
3564 rc = sqlite3_prepare_v2(pArg->db,
3565 "SELECT value FROM temp.sqlite_parameters"
3566 " WHERE key=?1", -1, &pQ, 0);
3568 for(i=1; i<=nVar; i++){
3569 char zNum[30];
3570 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3571 if( zVar==0 ){
3572 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3573 zVar = zNum;
3575 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3576 if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
3577 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3578 #ifdef NAN
3579 }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
3580 sqlite3_bind_double(pStmt, i, NAN);
3581 #endif
3582 #ifdef INFINITY
3583 }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
3584 sqlite3_bind_double(pStmt, i, INFINITY);
3585 #endif
3586 }else{
3587 sqlite3_bind_null(pStmt, i);
3589 sqlite3_reset(pQ);
3591 sqlite3_finalize(pQ);
3595 ** UTF8 box-drawing characters. Imagine box lines like this:
3597 ** 1
3598 ** |
3599 ** 4 --+-- 2
3600 ** |
3601 ** 3
3603 ** Each box characters has between 2 and 4 of the lines leading from
3604 ** the center. The characters are here identified by the numbers of
3605 ** their corresponding lines.
3607 #define BOX_24 "\342\224\200" /* U+2500 --- */
3608 #define BOX_13 "\342\224\202" /* U+2502 | */
3609 #define BOX_23 "\342\224\214" /* U+250c ,- */
3610 #define BOX_34 "\342\224\220" /* U+2510 -, */
3611 #define BOX_12 "\342\224\224" /* U+2514 '- */
3612 #define BOX_14 "\342\224\230" /* U+2518 -' */
3613 #define BOX_123 "\342\224\234" /* U+251c |- */
3614 #define BOX_134 "\342\224\244" /* U+2524 -| */
3615 #define BOX_234 "\342\224\254" /* U+252c -,- */
3616 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3617 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3619 /* Draw horizontal line N characters long using unicode box
3620 ** characters
3622 static void print_box_line(FILE *out, int N){
3623 const char zDash[] =
3624 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3625 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3626 const int nDash = sizeof(zDash) - 1;
3627 N *= 3;
3628 while( N>nDash ){
3629 utf8_printf(out, zDash);
3630 N -= nDash;
3632 utf8_printf(out, "%.*s", N, zDash);
3636 ** Draw a horizontal separator for a MODE_Box table.
3638 static void print_box_row_separator(
3639 ShellState *p,
3640 int nArg,
3641 const char *zSep1,
3642 const char *zSep2,
3643 const char *zSep3
3645 int i;
3646 if( nArg>0 ){
3647 utf8_printf(p->out, "%s", zSep1);
3648 print_box_line(p->out, p->actualWidth[0]+2);
3649 for(i=1; i<nArg; i++){
3650 utf8_printf(p->out, "%s", zSep2);
3651 print_box_line(p->out, p->actualWidth[i]+2);
3653 utf8_printf(p->out, "%s", zSep3);
3655 fputs("\n", p->out);
3659 ** z[] is a line of text that is to be displayed the .mode box or table or
3660 ** similar tabular formats. z[] might contain control characters such
3661 ** as \n, \t, \f, or \r.
3663 ** Compute characters to display on the first line of z[]. Stop at the
3664 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3665 ** from malloc()) of that first line, which caller should free sometime.
3666 ** Write anything to display on the next line into *pzTail. If this is
3667 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3669 static char *translateForDisplayAndDup(
3670 const unsigned char *z, /* Input text to be transformed */
3671 const unsigned char **pzTail, /* OUT: Tail of the input for next line */
3672 int mxWidth, /* Max width. 0 means no limit */
3673 u8 bWordWrap /* If true, avoid breaking mid-word */
3675 int i; /* Input bytes consumed */
3676 int j; /* Output bytes generated */
3677 int k; /* Input bytes to be displayed */
3678 int n; /* Output column number */
3679 unsigned char *zOut; /* Output text */
3681 if( z==0 ){
3682 *pzTail = 0;
3683 return 0;
3685 if( mxWidth<0 ) mxWidth = -mxWidth;
3686 if( mxWidth==0 ) mxWidth = 1000000;
3687 i = j = n = 0;
3688 while( n<mxWidth ){
3689 if( z[i]>=' ' ){
3690 n++;
3691 do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3692 continue;
3694 if( z[i]=='\t' ){
3696 n++;
3697 j++;
3698 }while( (n&7)!=0 && n<mxWidth );
3699 i++;
3700 continue;
3702 break;
3704 if( n>=mxWidth && bWordWrap ){
3705 /* Perhaps try to back up to a better place to break the line */
3706 for(k=i; k>i/2; k--){
3707 if( isspace(z[k-1]) ) break;
3709 if( k<=i/2 ){
3710 for(k=i; k>i/2; k--){
3711 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3714 if( k<=i/2 ){
3715 k = i;
3716 }else{
3717 i = k;
3718 while( z[i]==' ' ) i++;
3720 }else{
3721 k = i;
3723 if( n>=mxWidth && z[i]>=' ' ){
3724 *pzTail = &z[i];
3725 }else if( z[i]=='\r' && z[i+1]=='\n' ){
3726 *pzTail = z[i+2] ? &z[i+2] : 0;
3727 }else if( z[i]==0 || z[i+1]==0 ){
3728 *pzTail = 0;
3729 }else{
3730 *pzTail = &z[i+1];
3732 zOut = malloc( j+1 );
3733 shell_check_oom(zOut);
3734 i = j = n = 0;
3735 while( i<k ){
3736 if( z[i]>=' ' ){
3737 n++;
3738 do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3739 continue;
3741 if( z[i]=='\t' ){
3743 n++;
3744 zOut[j++] = ' ';
3745 }while( (n&7)!=0 && n<mxWidth );
3746 i++;
3747 continue;
3749 break;
3751 zOut[j] = 0;
3752 return (char*)zOut;
3755 /* Extract the value of the i-th current column for pStmt as an SQL literal
3756 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3757 ** the caller.
3759 static char *quoted_column(sqlite3_stmt *pStmt, int i){
3760 switch( sqlite3_column_type(pStmt, i) ){
3761 case SQLITE_NULL: {
3762 return sqlite3_mprintf("NULL");
3764 case SQLITE_INTEGER:
3765 case SQLITE_FLOAT: {
3766 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3768 case SQLITE_TEXT: {
3769 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3771 case SQLITE_BLOB: {
3772 int j;
3773 sqlite3_str *pStr = sqlite3_str_new(0);
3774 const unsigned char *a = sqlite3_column_blob(pStmt,i);
3775 int n = sqlite3_column_bytes(pStmt,i);
3776 sqlite3_str_append(pStr, "x'", 2);
3777 for(j=0; j<n; j++){
3778 sqlite3_str_appendf(pStr, "%02x", a[j]);
3780 sqlite3_str_append(pStr, "'", 1);
3781 return sqlite3_str_finish(pStr);
3784 return 0; /* Not reached */
3788 ** Run a prepared statement and output the result in one of the
3789 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3790 ** or MODE_Box.
3792 ** This is different from ordinary exec_prepared_stmt() in that
3793 ** it has to run the entire query and gather the results into memory
3794 ** first, in order to determine column widths, before providing
3795 ** any output.
3797 static void exec_prepared_stmt_columnar(
3798 ShellState *p, /* Pointer to ShellState */
3799 sqlite3_stmt *pStmt /* Statment to run */
3801 sqlite3_int64 nRow = 0;
3802 int nColumn = 0;
3803 char **azData = 0;
3804 sqlite3_int64 nAlloc = 0;
3805 char *abRowDiv = 0;
3806 const unsigned char *uz;
3807 const char *z;
3808 char **azQuoted = 0;
3809 int rc;
3810 sqlite3_int64 i, nData;
3811 int j, nTotal, w, n;
3812 const char *colSep = 0;
3813 const char *rowSep = 0;
3814 const unsigned char **azNextLine = 0;
3815 int bNextLine = 0;
3816 int bMultiLineRowExists = 0;
3817 int bw = p->cmOpts.bWordWrap;
3818 const char *zEmpty = "";
3819 const char *zShowNull = p->nullValue;
3821 rc = sqlite3_step(pStmt);
3822 if( rc!=SQLITE_ROW ) return;
3823 nColumn = sqlite3_column_count(pStmt);
3824 nAlloc = nColumn*4;
3825 if( nAlloc<=0 ) nAlloc = 1;
3826 azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3827 shell_check_oom(azData);
3828 azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3829 shell_check_oom(azNextLine);
3830 memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3831 if( p->cmOpts.bQuote ){
3832 azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3833 shell_check_oom(azQuoted);
3834 memset(azQuoted, 0, nColumn*sizeof(char*) );
3836 abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3837 shell_check_oom(abRowDiv);
3838 if( nColumn>p->nWidth ){
3839 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3840 shell_check_oom(p->colWidth);
3841 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3842 p->nWidth = nColumn;
3843 p->actualWidth = &p->colWidth[nColumn];
3845 memset(p->actualWidth, 0, nColumn*sizeof(int));
3846 for(i=0; i<nColumn; i++){
3847 w = p->colWidth[i];
3848 if( w<0 ) w = -w;
3849 p->actualWidth[i] = w;
3851 for(i=0; i<nColumn; i++){
3852 const unsigned char *zNotUsed;
3853 int wx = p->colWidth[i];
3854 if( wx==0 ){
3855 wx = p->cmOpts.iWrap;
3857 if( wx<0 ) wx = -wx;
3858 uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3859 if( uz==0 ) uz = (u8*)"";
3860 azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3863 int useNextLine = bNextLine;
3864 bNextLine = 0;
3865 if( (nRow+2)*nColumn >= nAlloc ){
3866 nAlloc *= 2;
3867 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3868 shell_check_oom(azData);
3869 abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3870 shell_check_oom(abRowDiv);
3872 abRowDiv[nRow] = 1;
3873 nRow++;
3874 for(i=0; i<nColumn; i++){
3875 int wx = p->colWidth[i];
3876 if( wx==0 ){
3877 wx = p->cmOpts.iWrap;
3879 if( wx<0 ) wx = -wx;
3880 if( useNextLine ){
3881 uz = azNextLine[i];
3882 if( uz==0 ) uz = (u8*)zEmpty;
3883 }else if( p->cmOpts.bQuote ){
3884 sqlite3_free(azQuoted[i]);
3885 azQuoted[i] = quoted_column(pStmt,i);
3886 uz = (const unsigned char*)azQuoted[i];
3887 }else{
3888 uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3889 if( uz==0 ) uz = (u8*)zShowNull;
3891 azData[nRow*nColumn + i]
3892 = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3893 if( azNextLine[i] ){
3894 bNextLine = 1;
3895 abRowDiv[nRow-1] = 0;
3896 bMultiLineRowExists = 1;
3899 }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3900 nTotal = nColumn*(nRow+1);
3901 for(i=0; i<nTotal; i++){
3902 z = azData[i];
3903 if( z==0 ) z = (char*)zEmpty;
3904 n = strlenChar(z);
3905 j = i%nColumn;
3906 if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3908 if( seenInterrupt ) goto columnar_end;
3909 if( nColumn==0 ) goto columnar_end;
3910 switch( p->cMode ){
3911 case MODE_Column: {
3912 colSep = " ";
3913 rowSep = "\n";
3914 if( p->showHeader ){
3915 for(i=0; i<nColumn; i++){
3916 w = p->actualWidth[i];
3917 if( p->colWidth[i]<0 ) w = -w;
3918 utf8_width_print(p->out, w, azData[i]);
3919 fputs(i==nColumn-1?"\n":" ", p->out);
3921 for(i=0; i<nColumn; i++){
3922 print_dashes(p->out, p->actualWidth[i]);
3923 fputs(i==nColumn-1?"\n":" ", p->out);
3926 break;
3928 case MODE_Table: {
3929 colSep = " | ";
3930 rowSep = " |\n";
3931 print_row_separator(p, nColumn, "+");
3932 fputs("| ", p->out);
3933 for(i=0; i<nColumn; i++){
3934 w = p->actualWidth[i];
3935 n = strlenChar(azData[i]);
3936 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3937 fputs(i==nColumn-1?" |\n":" | ", p->out);
3939 print_row_separator(p, nColumn, "+");
3940 break;
3942 case MODE_Markdown: {
3943 colSep = " | ";
3944 rowSep = " |\n";
3945 fputs("| ", p->out);
3946 for(i=0; i<nColumn; i++){
3947 w = p->actualWidth[i];
3948 n = strlenChar(azData[i]);
3949 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3950 fputs(i==nColumn-1?" |\n":" | ", p->out);
3952 print_row_separator(p, nColumn, "|");
3953 break;
3955 case MODE_Box: {
3956 colSep = " " BOX_13 " ";
3957 rowSep = " " BOX_13 "\n";
3958 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3959 utf8_printf(p->out, BOX_13 " ");
3960 for(i=0; i<nColumn; i++){
3961 w = p->actualWidth[i];
3962 n = strlenChar(azData[i]);
3963 utf8_printf(p->out, "%*s%s%*s%s",
3964 (w-n)/2, "", azData[i], (w-n+1)/2, "",
3965 i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3967 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3968 break;
3971 for(i=nColumn, j=0; i<nTotal; i++, j++){
3972 if( j==0 && p->cMode!=MODE_Column ){
3973 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3975 z = azData[i];
3976 if( z==0 ) z = p->nullValue;
3977 w = p->actualWidth[j];
3978 if( p->colWidth[j]<0 ) w = -w;
3979 utf8_width_print(p->out, w, z);
3980 if( j==nColumn-1 ){
3981 utf8_printf(p->out, "%s", rowSep);
3982 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3983 if( p->cMode==MODE_Table ){
3984 print_row_separator(p, nColumn, "+");
3985 }else if( p->cMode==MODE_Box ){
3986 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3987 }else if( p->cMode==MODE_Column ){
3988 raw_printf(p->out, "\n");
3991 j = -1;
3992 if( seenInterrupt ) goto columnar_end;
3993 }else{
3994 utf8_printf(p->out, "%s", colSep);
3997 if( p->cMode==MODE_Table ){
3998 print_row_separator(p, nColumn, "+");
3999 }else if( p->cMode==MODE_Box ){
4000 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
4002 columnar_end:
4003 if( seenInterrupt ){
4004 utf8_printf(p->out, "Interrupt\n");
4006 nData = (nRow+1)*nColumn;
4007 for(i=0; i<nData; i++){
4008 z = azData[i];
4009 if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
4011 sqlite3_free(azData);
4012 sqlite3_free((void*)azNextLine);
4013 sqlite3_free(abRowDiv);
4014 if( azQuoted ){
4015 for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
4016 sqlite3_free(azQuoted);
4021 ** Run a prepared statement
4023 static void exec_prepared_stmt(
4024 ShellState *pArg, /* Pointer to ShellState */
4025 sqlite3_stmt *pStmt /* Statment to run */
4027 int rc;
4028 sqlite3_uint64 nRow = 0;
4030 if( pArg->cMode==MODE_Column
4031 || pArg->cMode==MODE_Table
4032 || pArg->cMode==MODE_Box
4033 || pArg->cMode==MODE_Markdown
4035 exec_prepared_stmt_columnar(pArg, pStmt);
4036 return;
4039 /* perform the first step. this will tell us if we
4040 ** have a result set or not and how wide it is.
4042 rc = sqlite3_step(pStmt);
4043 /* if we have a result set... */
4044 if( SQLITE_ROW == rc ){
4045 /* allocate space for col name ptr, value ptr, and type */
4046 int nCol = sqlite3_column_count(pStmt);
4047 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
4048 if( !pData ){
4049 shell_out_of_memory();
4050 }else{
4051 char **azCols = (char **)pData; /* Names of result columns */
4052 char **azVals = &azCols[nCol]; /* Results */
4053 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
4054 int i, x;
4055 assert(sizeof(int) <= sizeof(char *));
4056 /* save off ptrs to column names */
4057 for(i=0; i<nCol; i++){
4058 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
4061 nRow++;
4062 /* extract the data and data types */
4063 for(i=0; i<nCol; i++){
4064 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
4065 if( x==SQLITE_BLOB
4066 && pArg
4067 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
4069 azVals[i] = "";
4070 }else{
4071 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
4073 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
4074 rc = SQLITE_NOMEM;
4075 break; /* from for */
4077 } /* end for */
4079 /* if data and types extracted successfully... */
4080 if( SQLITE_ROW == rc ){
4081 /* call the supplied callback with the result row data */
4082 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
4083 rc = SQLITE_ABORT;
4084 }else{
4085 rc = sqlite3_step(pStmt);
4088 } while( SQLITE_ROW == rc );
4089 sqlite3_free(pData);
4090 if( pArg->cMode==MODE_Json ){
4091 fputs("]\n", pArg->out);
4092 }else if( pArg->cMode==MODE_Count ){
4093 char zBuf[200];
4094 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
4095 nRow, nRow!=1 ? "s" : "");
4096 printf("%s", zBuf);
4102 #ifndef SQLITE_OMIT_VIRTUALTABLE
4104 ** This function is called to process SQL if the previous shell command
4105 ** was ".expert". It passes the SQL in the second argument directly to
4106 ** the sqlite3expert object.
4108 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4109 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4110 ** an English language error message. It is the responsibility of the
4111 ** caller to eventually free this buffer using sqlite3_free().
4113 static int expertHandleSQL(
4114 ShellState *pState,
4115 const char *zSql,
4116 char **pzErr
4118 assert( pState->expert.pExpert );
4119 assert( pzErr==0 || *pzErr==0 );
4120 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
4124 ** This function is called either to silently clean up the object
4125 ** created by the ".expert" command (if bCancel==1), or to generate a
4126 ** report from it and then clean it up (if bCancel==0).
4128 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4129 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4130 ** an English language error message. It is the responsibility of the
4131 ** caller to eventually free this buffer using sqlite3_free().
4133 static int expertFinish(
4134 ShellState *pState,
4135 int bCancel,
4136 char **pzErr
4138 int rc = SQLITE_OK;
4139 sqlite3expert *p = pState->expert.pExpert;
4140 assert( p );
4141 assert( bCancel || pzErr==0 || *pzErr==0 );
4142 if( bCancel==0 ){
4143 FILE *out = pState->out;
4144 int bVerbose = pState->expert.bVerbose;
4146 rc = sqlite3_expert_analyze(p, pzErr);
4147 if( rc==SQLITE_OK ){
4148 int nQuery = sqlite3_expert_count(p);
4149 int i;
4151 if( bVerbose ){
4152 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
4153 raw_printf(out, "-- Candidates -----------------------------\n");
4154 raw_printf(out, "%s\n", zCand);
4156 for(i=0; i<nQuery; i++){
4157 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
4158 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
4159 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
4160 if( zIdx==0 ) zIdx = "(no new indexes)\n";
4161 if( bVerbose ){
4162 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
4163 raw_printf(out, "%s\n\n", zSql);
4165 raw_printf(out, "%s\n", zIdx);
4166 raw_printf(out, "%s\n", zEQP);
4170 sqlite3_expert_destroy(p);
4171 pState->expert.pExpert = 0;
4172 return rc;
4176 ** Implementation of ".expert" dot command.
4178 static int expertDotCommand(
4179 ShellState *pState, /* Current shell tool state */
4180 char **azArg, /* Array of arguments passed to dot command */
4181 int nArg /* Number of entries in azArg[] */
4183 int rc = SQLITE_OK;
4184 char *zErr = 0;
4185 int i;
4186 int iSample = 0;
4188 assert( pState->expert.pExpert==0 );
4189 memset(&pState->expert, 0, sizeof(ExpertInfo));
4191 for(i=1; rc==SQLITE_OK && i<nArg; i++){
4192 char *z = azArg[i];
4193 int n;
4194 if( z[0]=='-' && z[1]=='-' ) z++;
4195 n = strlen30(z);
4196 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
4197 pState->expert.bVerbose = 1;
4199 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
4200 if( i==(nArg-1) ){
4201 raw_printf(stderr, "option requires an argument: %s\n", z);
4202 rc = SQLITE_ERROR;
4203 }else{
4204 iSample = (int)integerValue(azArg[++i]);
4205 if( iSample<0 || iSample>100 ){
4206 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
4207 rc = SQLITE_ERROR;
4211 else{
4212 raw_printf(stderr, "unknown option: %s\n", z);
4213 rc = SQLITE_ERROR;
4217 if( rc==SQLITE_OK ){
4218 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
4219 if( pState->expert.pExpert==0 ){
4220 raw_printf(stderr, "sqlite3_expert_new: %s\n",
4221 zErr ? zErr : "out of memory");
4222 rc = SQLITE_ERROR;
4223 }else{
4224 sqlite3_expert_config(
4225 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
4229 sqlite3_free(zErr);
4231 return rc;
4233 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4236 ** Execute a statement or set of statements. Print
4237 ** any result rows/columns depending on the current mode
4238 ** set via the supplied callback.
4240 ** This is very similar to SQLite's built-in sqlite3_exec()
4241 ** function except it takes a slightly different callback
4242 ** and callback data argument.
4244 static int shell_exec(
4245 ShellState *pArg, /* Pointer to ShellState */
4246 const char *zSql, /* SQL to be evaluated */
4247 char **pzErrMsg /* Error msg written here */
4249 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
4250 int rc = SQLITE_OK; /* Return Code */
4251 int rc2;
4252 const char *zLeftover; /* Tail of unprocessed SQL */
4253 sqlite3 *db = pArg->db;
4255 if( pzErrMsg ){
4256 *pzErrMsg = NULL;
4259 #ifndef SQLITE_OMIT_VIRTUALTABLE
4260 if( pArg->expert.pExpert ){
4261 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
4262 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
4264 #endif
4266 while( zSql[0] && (SQLITE_OK == rc) ){
4267 static const char *zStmtSql;
4268 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
4269 if( SQLITE_OK != rc ){
4270 if( pzErrMsg ){
4271 *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
4273 }else{
4274 if( !pStmt ){
4275 /* this happens for a comment or white-space */
4276 zSql = zLeftover;
4277 while( IsSpace(zSql[0]) ) zSql++;
4278 continue;
4280 zStmtSql = sqlite3_sql(pStmt);
4281 if( zStmtSql==0 ) zStmtSql = "";
4282 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
4284 /* save off the prepared statment handle and reset row count */
4285 if( pArg ){
4286 pArg->pStmt = pStmt;
4287 pArg->cnt = 0;
4290 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4291 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
4292 sqlite3_stmt *pExplain;
4293 char *zEQP;
4294 int triggerEQP = 0;
4295 disable_debug_trace_modes();
4296 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
4297 if( pArg->autoEQP>=AUTOEQP_trigger ){
4298 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
4300 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
4301 shell_check_oom(zEQP);
4302 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4303 if( rc==SQLITE_OK ){
4304 while( sqlite3_step(pExplain)==SQLITE_ROW ){
4305 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
4306 int iEqpId = sqlite3_column_int(pExplain, 0);
4307 int iParentId = sqlite3_column_int(pExplain, 1);
4308 if( zEQPLine==0 ) zEQPLine = "";
4309 if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
4310 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
4312 eqp_render(pArg, 0);
4314 sqlite3_finalize(pExplain);
4315 sqlite3_free(zEQP);
4316 if( pArg->autoEQP>=AUTOEQP_full ){
4317 /* Also do an EXPLAIN for ".eqp full" mode */
4318 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
4319 shell_check_oom(zEQP);
4320 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4321 if( rc==SQLITE_OK ){
4322 pArg->cMode = MODE_Explain;
4323 explain_data_prepare(pArg, pExplain);
4324 exec_prepared_stmt(pArg, pExplain);
4325 explain_data_delete(pArg);
4327 sqlite3_finalize(pExplain);
4328 sqlite3_free(zEQP);
4330 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
4331 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
4332 /* Reprepare pStmt before reactiving trace modes */
4333 sqlite3_finalize(pStmt);
4334 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
4335 if( pArg ) pArg->pStmt = pStmt;
4337 restore_debug_trace_modes();
4340 if( pArg ){
4341 pArg->cMode = pArg->mode;
4342 if( pArg->autoExplain ){
4343 if( sqlite3_stmt_isexplain(pStmt)==1 ){
4344 pArg->cMode = MODE_Explain;
4346 if( sqlite3_stmt_isexplain(pStmt)==2 ){
4347 pArg->cMode = MODE_EQP;
4351 /* If the shell is currently in ".explain" mode, gather the extra
4352 ** data required to add indents to the output.*/
4353 if( pArg->cMode==MODE_Explain ){
4354 explain_data_prepare(pArg, pStmt);
4358 bind_prepared_stmt(pArg, pStmt);
4359 exec_prepared_stmt(pArg, pStmt);
4360 explain_data_delete(pArg);
4361 eqp_render(pArg, 0);
4363 /* print usage stats if stats on */
4364 if( pArg && pArg->statsOn ){
4365 display_stats(db, pArg, 0);
4368 /* print loop-counters if required */
4369 if( pArg && pArg->scanstatsOn ){
4370 display_scanstats(db, pArg);
4373 /* Finalize the statement just executed. If this fails, save a
4374 ** copy of the error message. Otherwise, set zSql to point to the
4375 ** next statement to execute. */
4376 rc2 = sqlite3_finalize(pStmt);
4377 if( rc!=SQLITE_NOMEM ) rc = rc2;
4378 if( rc==SQLITE_OK ){
4379 zSql = zLeftover;
4380 while( IsSpace(zSql[0]) ) zSql++;
4381 }else if( pzErrMsg ){
4382 *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
4385 /* clear saved stmt handle */
4386 if( pArg ){
4387 pArg->pStmt = NULL;
4390 } /* end while */
4392 return rc;
4396 ** Release memory previously allocated by tableColumnList().
4398 static void freeColumnList(char **azCol){
4399 int i;
4400 for(i=1; azCol[i]; i++){
4401 sqlite3_free(azCol[i]);
4403 /* azCol[0] is a static string */
4404 sqlite3_free(azCol);
4408 ** Return a list of pointers to strings which are the names of all
4409 ** columns in table zTab. The memory to hold the names is dynamically
4410 ** allocated and must be released by the caller using a subsequent call
4411 ** to freeColumnList().
4413 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4414 ** value that needs to be preserved, then azCol[0] is filled in with the
4415 ** name of the rowid column.
4417 ** The first regular column in the table is azCol[1]. The list is terminated
4418 ** by an entry with azCol[i]==0.
4420 static char **tableColumnList(ShellState *p, const char *zTab){
4421 char **azCol = 0;
4422 sqlite3_stmt *pStmt;
4423 char *zSql;
4424 int nCol = 0;
4425 int nAlloc = 0;
4426 int nPK = 0; /* Number of PRIMARY KEY columns seen */
4427 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
4428 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4429 int rc;
4431 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4432 shell_check_oom(zSql);
4433 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4434 sqlite3_free(zSql);
4435 if( rc ) return 0;
4436 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4437 if( nCol>=nAlloc-2 ){
4438 nAlloc = nAlloc*2 + nCol + 10;
4439 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4440 shell_check_oom(azCol);
4442 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4443 shell_check_oom(azCol[nCol]);
4444 if( sqlite3_column_int(pStmt, 5) ){
4445 nPK++;
4446 if( nPK==1
4447 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4448 "INTEGER")==0
4450 isIPK = 1;
4451 }else{
4452 isIPK = 0;
4456 sqlite3_finalize(pStmt);
4457 if( azCol==0 ) return 0;
4458 azCol[0] = 0;
4459 azCol[nCol+1] = 0;
4461 /* The decision of whether or not a rowid really needs to be preserved
4462 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4463 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4464 ** rowids on tables where the rowid is inaccessible because there are other
4465 ** columns in the table named "rowid", "_rowid_", and "oid".
4467 if( preserveRowid && isIPK ){
4468 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4469 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
4470 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4471 ** ROWID aliases. To distinguish these cases, check to see if
4472 ** there is a "pk" entry in "PRAGMA index_list". There will be
4473 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4475 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4476 " WHERE origin='pk'", zTab);
4477 shell_check_oom(zSql);
4478 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4479 sqlite3_free(zSql);
4480 if( rc ){
4481 freeColumnList(azCol);
4482 return 0;
4484 rc = sqlite3_step(pStmt);
4485 sqlite3_finalize(pStmt);
4486 preserveRowid = rc==SQLITE_ROW;
4488 if( preserveRowid ){
4489 /* Only preserve the rowid if we can find a name to use for the
4490 ** rowid */
4491 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4492 int i, j;
4493 for(j=0; j<3; j++){
4494 for(i=1; i<=nCol; i++){
4495 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4497 if( i>nCol ){
4498 /* At this point, we know that azRowid[j] is not the name of any
4499 ** ordinary column in the table. Verify that azRowid[j] is a valid
4500 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4501 ** tables will fail this last check */
4502 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4503 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4504 break;
4508 return azCol;
4512 ** Toggle the reverse_unordered_selects setting.
4514 static void toggleSelectOrder(sqlite3 *db){
4515 sqlite3_stmt *pStmt = 0;
4516 int iSetting = 0;
4517 char zStmt[100];
4518 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4519 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4520 iSetting = sqlite3_column_int(pStmt, 0);
4522 sqlite3_finalize(pStmt);
4523 sqlite3_snprintf(sizeof(zStmt), zStmt,
4524 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4525 sqlite3_exec(db, zStmt, 0, 0, 0);
4529 ** This is a different callback routine used for dumping the database.
4530 ** Each row received by this callback consists of a table name,
4531 ** the table type ("index" or "table") and SQL to create the table.
4532 ** This routine should print text sufficient to recreate the table.
4534 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4535 int rc;
4536 const char *zTable;
4537 const char *zType;
4538 const char *zSql;
4539 ShellState *p = (ShellState *)pArg;
4540 int dataOnly;
4541 int noSys;
4543 UNUSED_PARAMETER(azNotUsed);
4544 if( nArg!=3 || azArg==0 ) return 0;
4545 zTable = azArg[0];
4546 zType = azArg[1];
4547 zSql = azArg[2];
4548 if( zTable==0 ) return 0;
4549 if( zType==0 ) return 0;
4550 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4551 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4553 if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4554 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4555 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4556 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4557 }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
4558 return 0;
4559 }else if( dataOnly ){
4560 /* no-op */
4561 }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4562 char *zIns;
4563 if( !p->writableSchema ){
4564 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4565 p->writableSchema = 1;
4567 zIns = sqlite3_mprintf(
4568 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4569 "VALUES('table','%q','%q',0,'%q');",
4570 zTable, zTable, zSql);
4571 shell_check_oom(zIns);
4572 utf8_printf(p->out, "%s\n", zIns);
4573 sqlite3_free(zIns);
4574 return 0;
4575 }else{
4576 printSchemaLine(p->out, zSql, ";\n");
4579 if( cli_strcmp(zType, "table")==0 ){
4580 ShellText sSelect;
4581 ShellText sTable;
4582 char **azCol;
4583 int i;
4584 char *savedDestTable;
4585 int savedMode;
4587 azCol = tableColumnList(p, zTable);
4588 if( azCol==0 ){
4589 p->nErr++;
4590 return 0;
4593 /* Always quote the table name, even if it appears to be pure ascii,
4594 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4595 initText(&sTable);
4596 appendText(&sTable, zTable, quoteChar(zTable));
4597 /* If preserving the rowid, add a column list after the table name.
4598 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4599 ** instead of the usual "INSERT INTO tab VALUES(...)".
4601 if( azCol[0] ){
4602 appendText(&sTable, "(", 0);
4603 appendText(&sTable, azCol[0], 0);
4604 for(i=1; azCol[i]; i++){
4605 appendText(&sTable, ",", 0);
4606 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4608 appendText(&sTable, ")", 0);
4611 /* Build an appropriate SELECT statement */
4612 initText(&sSelect);
4613 appendText(&sSelect, "SELECT ", 0);
4614 if( azCol[0] ){
4615 appendText(&sSelect, azCol[0], 0);
4616 appendText(&sSelect, ",", 0);
4618 for(i=1; azCol[i]; i++){
4619 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4620 if( azCol[i+1] ){
4621 appendText(&sSelect, ",", 0);
4624 freeColumnList(azCol);
4625 appendText(&sSelect, " FROM ", 0);
4626 appendText(&sSelect, zTable, quoteChar(zTable));
4628 savedDestTable = p->zDestTable;
4629 savedMode = p->mode;
4630 p->zDestTable = sTable.z;
4631 p->mode = p->cMode = MODE_Insert;
4632 rc = shell_exec(p, sSelect.z, 0);
4633 if( (rc&0xff)==SQLITE_CORRUPT ){
4634 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4635 toggleSelectOrder(p->db);
4636 shell_exec(p, sSelect.z, 0);
4637 toggleSelectOrder(p->db);
4639 p->zDestTable = savedDestTable;
4640 p->mode = savedMode;
4641 freeText(&sTable);
4642 freeText(&sSelect);
4643 if( rc ) p->nErr++;
4645 return 0;
4649 ** Run zQuery. Use dump_callback() as the callback routine so that
4650 ** the contents of the query are output as SQL statements.
4652 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4653 ** "ORDER BY rowid DESC" to the end.
4655 static int run_schema_dump_query(
4656 ShellState *p,
4657 const char *zQuery
4659 int rc;
4660 char *zErr = 0;
4661 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4662 if( rc==SQLITE_CORRUPT ){
4663 char *zQ2;
4664 int len = strlen30(zQuery);
4665 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4666 if( zErr ){
4667 utf8_printf(p->out, "/****** %s ******/\n", zErr);
4668 sqlite3_free(zErr);
4669 zErr = 0;
4671 zQ2 = malloc( len+100 );
4672 if( zQ2==0 ) return rc;
4673 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4674 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4675 if( rc ){
4676 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4677 }else{
4678 rc = SQLITE_CORRUPT;
4680 sqlite3_free(zErr);
4681 free(zQ2);
4683 return rc;
4687 ** Text of help messages.
4689 ** The help text for each individual command begins with a line that starts
4690 ** with ".". Subsequent lines are supplemental information.
4692 ** There must be two or more spaces between the end of the command and the
4693 ** start of the description of what that command does.
4695 static const char *(azHelp[]) = {
4696 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4697 && !defined(SQLITE_SHELL_FIDDLE)
4698 ".archive ... Manage SQL archives",
4699 " Each command must have exactly one of the following options:",
4700 " -c, --create Create a new archive",
4701 " -u, --update Add or update files with changed mtime",
4702 " -i, --insert Like -u but always add even if unchanged",
4703 " -r, --remove Remove files from archive",
4704 " -t, --list List contents of archive",
4705 " -x, --extract Extract files from archive",
4706 " Optional arguments:",
4707 " -v, --verbose Print each filename as it is processed",
4708 " -f FILE, --file FILE Use archive FILE (default is current db)",
4709 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4710 " -C DIR, --directory DIR Read/extract files from directory DIR",
4711 " -g, --glob Use glob matching for names in archive",
4712 " -n, --dryrun Show the SQL that would have occurred",
4713 " Examples:",
4714 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4715 " .ar -tf ARCHIVE # List members of ARCHIVE",
4716 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4717 " See also:",
4718 " http://sqlite.org/cli.html#sqlite_archive_support",
4719 #endif
4720 #ifndef SQLITE_OMIT_AUTHORIZATION
4721 ".auth ON|OFF Show authorizer callbacks",
4722 #endif
4723 #ifndef SQLITE_SHELL_FIDDLE
4724 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4725 " Options:",
4726 " --append Use the appendvfs",
4727 " --async Write to FILE without journal and fsync()",
4728 #endif
4729 ".bail on|off Stop after hitting an error. Default OFF",
4730 ".binary on|off Turn binary output on or off. Default OFF",
4731 #ifndef SQLITE_SHELL_FIDDLE
4732 ".cd DIRECTORY Change the working directory to DIRECTORY",
4733 #endif
4734 ".changes on|off Show number of rows changed by SQL",
4735 #ifndef SQLITE_SHELL_FIDDLE
4736 ".check GLOB Fail if output since .testcase does not match",
4737 ".clone NEWDB Clone data into NEWDB from the existing database",
4738 #endif
4739 ".connection [close] [#] Open or close an auxiliary database connection",
4740 ".databases List names and files of attached databases",
4741 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4742 #if SQLITE_SHELL_HAVE_RECOVER
4743 ".dbinfo ?DB? Show status information about the database",
4744 #endif
4745 ".dump ?OBJECTS? Render database content as SQL",
4746 " Options:",
4747 " --data-only Output only INSERT statements",
4748 " --newlines Allow unescaped newline characters in output",
4749 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4750 " --preserve-rowids Include ROWID values in the output",
4751 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4752 " Additional LIKE patterns can be given in subsequent arguments",
4753 ".echo on|off Turn command echo on or off",
4754 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4755 " Other Modes:",
4756 #ifdef SQLITE_DEBUG
4757 " test Show raw EXPLAIN QUERY PLAN output",
4758 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4759 #endif
4760 " trigger Like \"full\" but also show trigger bytecode",
4761 #ifndef SQLITE_SHELL_FIDDLE
4762 ".excel Display the output of next command in spreadsheet",
4763 " --bom Put a UTF8 byte-order mark on intermediate file",
4764 #endif
4765 #ifndef SQLITE_SHELL_FIDDLE
4766 ".exit ?CODE? Exit this program with return-code CODE",
4767 #endif
4768 ".expert EXPERIMENTAL. Suggest indexes for queries",
4769 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4770 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4771 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4772 " --help Show CMD details",
4773 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4774 ".headers on|off Turn display of headers on or off",
4775 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4776 #ifndef SQLITE_SHELL_FIDDLE
4777 ".import FILE TABLE Import data from FILE into TABLE",
4778 " Options:",
4779 " --ascii Use \\037 and \\036 as column and row separators",
4780 " --csv Use , and \\n as column and row separators",
4781 " --skip N Skip the first N rows of input",
4782 " --schema S Target table to be S.TABLE",
4783 " -v \"Verbose\" - increase auxiliary output",
4784 " Notes:",
4785 " * If TABLE does not exist, it is created. The first row of input",
4786 " determines the column names.",
4787 " * If neither --csv or --ascii are used, the input mode is derived",
4788 " from the \".mode\" output mode",
4789 " * If FILE begins with \"|\" then it is a command that generates the",
4790 " input text.",
4791 #endif
4792 #ifndef SQLITE_OMIT_TEST_CONTROL
4793 ",imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4794 #endif
4795 ".indexes ?TABLE? Show names of indexes",
4796 " If TABLE is specified, only show indexes for",
4797 " tables matching TABLE using the LIKE operator.",
4798 #ifdef SQLITE_ENABLE_IOTRACE
4799 ",iotrace FILE Enable I/O diagnostic logging to FILE",
4800 #endif
4801 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4802 ".lint OPTIONS Report potential schema issues.",
4803 " Options:",
4804 " fkey-indexes Find missing foreign key indexes",
4805 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4806 ".load FILE ?ENTRY? Load an extension library",
4807 #endif
4808 #if !defined(SQLITE_SHELL_FIDDLE)
4809 ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout",
4810 #else
4811 ".log on|off Turn logging on or off.",
4812 #endif
4813 ".mode MODE ?OPTIONS? Set output mode",
4814 " MODE is one of:",
4815 " ascii Columns/rows delimited by 0x1F and 0x1E",
4816 " box Tables using unicode box-drawing characters",
4817 " csv Comma-separated values",
4818 " column Output in columns. (See .width)",
4819 " html HTML <table> code",
4820 " insert SQL insert statements for TABLE",
4821 " json Results in a JSON array",
4822 " line One value per line",
4823 " list Values delimited by \"|\"",
4824 " markdown Markdown table format",
4825 " qbox Shorthand for \"box --wrap 60 --quote\"",
4826 " quote Escape answers as for SQL",
4827 " table ASCII-art table",
4828 " tabs Tab-separated values",
4829 " tcl TCL list elements",
4830 " OPTIONS: (for columnar modes or insert mode):",
4831 " --wrap N Wrap output lines to no longer than N characters",
4832 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4833 " --ww Shorthand for \"--wordwrap 1\"",
4834 " --quote Quote output text as SQL literals",
4835 " --noquote Do not quote output text",
4836 " TABLE The name of SQL table used for \"insert\" mode",
4837 #ifndef SQLITE_SHELL_FIDDLE
4838 ".nonce STRING Suspend safe mode for one command if nonce matches",
4839 #endif
4840 ".nullvalue STRING Use STRING in place of NULL values",
4841 #ifndef SQLITE_SHELL_FIDDLE
4842 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4843 " If FILE begins with '|' then open as a pipe",
4844 " --bom Put a UTF8 byte-order mark at the beginning",
4845 " -e Send output to the system text editor",
4846 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4847 /* Note that .open is (partially) available in WASM builds but is
4848 ** currently only intended to be used by the fiddle tool, not
4849 ** end users, so is "undocumented." */
4850 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4851 " Options:",
4852 " --append Use appendvfs to append database to the end of FILE",
4853 #endif
4854 #ifndef SQLITE_OMIT_DESERIALIZE
4855 " --deserialize Load into memory using sqlite3_deserialize()",
4856 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4857 " --maxsize N Maximum size for --hexdb or --deserialized database",
4858 #endif
4859 " --new Initialize FILE to an empty database",
4860 " --nofollow Do not follow symbolic links",
4861 " --readonly Open FILE readonly",
4862 " --zip FILE is a ZIP archive",
4863 #ifndef SQLITE_SHELL_FIDDLE
4864 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4865 " If FILE begins with '|' then open it as a pipe.",
4866 " Options:",
4867 " --bom Prefix output with a UTF8 byte-order mark",
4868 " -e Send output to the system text editor",
4869 " -x Send output as CSV to a spreadsheet",
4870 #endif
4871 ".parameter CMD ... Manage SQL parameter bindings",
4872 " clear Erase all bindings",
4873 " init Initialize the TEMP table that holds bindings",
4874 " list List the current parameter bindings",
4875 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4876 " PARAMETER should start with one of: $ : @ ?",
4877 " unset PARAMETER Remove PARAMETER from the binding table",
4878 ".print STRING... Print literal STRING",
4879 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4880 ".progress N Invoke progress handler after every N opcodes",
4881 " --limit N Interrupt after N progress callbacks",
4882 " --once Do no more than one progress interrupt",
4883 " --quiet|-q No output except at interrupts",
4884 " --reset Reset the count for each input and interrupt",
4885 #endif
4886 ".prompt MAIN CONTINUE Replace the standard prompts",
4887 #ifndef SQLITE_SHELL_FIDDLE
4888 ".quit Stop interpreting input stream, exit if primary.",
4889 ".read FILE Read input from FILE or command output",
4890 " If FILE begins with \"|\", it is a command that generates the input.",
4891 #endif
4892 #if SQLITE_SHELL_HAVE_RECOVER
4893 ".recover Recover as much data as possible from corrupt db.",
4894 " --ignore-freelist Ignore pages that appear to be on db freelist",
4895 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4896 " --no-rowids Do not attempt to recover rowid values",
4897 " that are not also INTEGER PRIMARY KEYs",
4898 #endif
4899 #ifndef SQLITE_SHELL_FIDDLE
4900 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4901 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4902 #endif
4903 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4904 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4905 " Options:",
4906 " --indent Try to pretty-print the schema",
4907 " --nosys Omit objects whose names start with \"sqlite_\"",
4908 ",selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4909 " Options:",
4910 " --init Create a new SELFTEST table",
4911 " -v Verbose output",
4912 ".separator COL ?ROW? Change the column and row separators",
4913 #if defined(SQLITE_ENABLE_SESSION)
4914 ".session ?NAME? CMD ... Create or control sessions",
4915 " Subcommands:",
4916 " attach TABLE Attach TABLE",
4917 " changeset FILE Write a changeset into FILE",
4918 " close Close one session",
4919 " enable ?BOOLEAN? Set or query the enable bit",
4920 " filter GLOB... Reject tables matching GLOBs",
4921 " indirect ?BOOLEAN? Mark or query the indirect status",
4922 " isempty Query whether the session is empty",
4923 " list List currently open session names",
4924 " open DB NAME Open a new session on DB",
4925 " patchset FILE Write a patchset into FILE",
4926 " If ?NAME? is omitted, the first defined session is used.",
4927 #endif
4928 ".sha3sum ... Compute a SHA3 hash of database content",
4929 " Options:",
4930 " --schema Also hash the sqlite_schema table",
4931 " --sha3-224 Use the sha3-224 algorithm",
4932 " --sha3-256 Use the sha3-256 algorithm (default)",
4933 " --sha3-384 Use the sha3-384 algorithm",
4934 " --sha3-512 Use the sha3-512 algorithm",
4935 " Any other argument is a LIKE pattern for tables to hash",
4936 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4937 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4938 #endif
4939 ".show Show the current values for various settings",
4940 ".stats ?ARG? Show stats or turn stats on or off",
4941 " off Turn off automatic stat display",
4942 " on Turn on automatic stat display",
4943 " stmt Show statement stats",
4944 " vmstep Show the virtual machine step count only",
4945 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4946 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4947 #endif
4948 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4949 #ifndef SQLITE_SHELL_FIDDLE
4950 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
4951 #endif
4952 ",testctrl CMD ... Run various sqlite3_test_control() operations",
4953 " Run \".testctrl\" with no arguments for details",
4954 ".timeout MS Try opening locked tables for MS milliseconds",
4955 ".timer on|off Turn SQL timer on or off",
4956 #ifndef SQLITE_OMIT_TRACE
4957 ".trace ?OPTIONS? Output each SQL statement as it is run",
4958 " FILE Send output to FILE",
4959 " stdout Send output to stdout",
4960 " stderr Send output to stderr",
4961 " off Disable tracing",
4962 " --expanded Expand query parameters",
4963 #ifdef SQLITE_ENABLE_NORMALIZE
4964 " --normalized Normal the SQL statements",
4965 #endif
4966 " --plain Show SQL as it is input",
4967 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4968 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4969 " --row Trace each row (SQLITE_TRACE_ROW)",
4970 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4971 #endif /* SQLITE_OMIT_TRACE */
4972 #ifdef SQLITE_DEBUG
4973 ".unmodule NAME ... Unregister virtual table modules",
4974 " --allexcept Unregister everything except those named",
4975 #endif
4976 ".version Show source, library and compiler versions",
4977 ".vfsinfo ?AUX? Information about the top-level VFS",
4978 ".vfslist List all available VFSes",
4979 ".vfsname ?AUX? Print the name of the VFS stack",
4980 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4981 " Negative values right-justify",
4985 ** Output help text.
4987 ** zPattern describes the set of commands for which help text is provided.
4988 ** If zPattern is NULL, then show all commands, but only give a one-line
4989 ** description of each.
4991 ** Return the number of matches.
4993 static int showHelp(FILE *out, const char *zPattern){
4994 int i = 0;
4995 int j = 0;
4996 int n = 0;
4997 char *zPat;
4998 if( zPattern==0
4999 || zPattern[0]=='0'
5000 || cli_strcmp(zPattern,"-a")==0
5001 || cli_strcmp(zPattern,"-all")==0
5002 || cli_strcmp(zPattern,"--all")==0
5004 enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
5005 enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
5006 /* Show all or most commands
5007 ** *zPattern==0 => summary of documented commands only
5008 ** *zPattern=='0' => whole help for undocumented commands
5009 ** Otherwise => whole help for documented commands
5011 enum HelpWanted hw = HW_SummaryOnly;
5012 enum HelpHave hh = HH_More;
5013 if( zPattern!=0 ){
5014 hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
5016 for(i=0; i<ArraySize(azHelp); i++){
5017 switch( azHelp[i][0] ){
5018 case ',':
5019 hh = HH_Summary|HH_Undoc;
5020 break;
5021 case '.':
5022 hh = HH_Summary;
5023 break;
5024 default:
5025 hh &= ~HH_Summary;
5026 break;
5028 if( ((hw^hh)&HH_Undoc)==0 ){
5029 if( (hh&HH_Summary)!=0 ){
5030 utf8_printf(out, ".%s\n", azHelp[i]+1);
5031 ++n;
5032 }else if( (hw&HW_SummaryOnly)==0 ){
5033 utf8_printf(out, "%s\n", azHelp[i]);
5037 }else{
5038 /* Seek documented commands for which zPattern is an exact prefix */
5039 zPat = sqlite3_mprintf(".%s*", zPattern);
5040 shell_check_oom(zPat);
5041 for(i=0; i<ArraySize(azHelp); i++){
5042 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
5043 utf8_printf(out, "%s\n", azHelp[i]);
5044 j = i+1;
5045 n++;
5048 sqlite3_free(zPat);
5049 if( n ){
5050 if( n==1 ){
5051 /* when zPattern is a prefix of exactly one command, then include
5052 ** the details of that command, which should begin at offset j */
5053 while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
5054 utf8_printf(out, "%s\n", azHelp[j]);
5055 j++;
5058 return n;
5060 /* Look for documented commands that contain zPattern anywhere.
5061 ** Show complete text of all documented commands that match. */
5062 zPat = sqlite3_mprintf("%%%s%%", zPattern);
5063 shell_check_oom(zPat);
5064 for(i=0; i<ArraySize(azHelp); i++){
5065 if( azHelp[i][0]==',' ){
5066 while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
5067 continue;
5069 if( azHelp[i][0]=='.' ) j = i;
5070 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
5071 utf8_printf(out, "%s\n", azHelp[j]);
5072 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
5073 j++;
5074 utf8_printf(out, "%s\n", azHelp[j]);
5076 i = j;
5077 n++;
5080 sqlite3_free(zPat);
5082 return n;
5085 /* Forward reference */
5086 static int process_input(ShellState *p);
5089 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
5090 ** and return a pointer to the buffer. The caller is responsible for freeing
5091 ** the memory.
5093 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
5094 ** read.
5096 ** For convenience, a nul-terminator byte is always appended to the data read
5097 ** from the file before the buffer is returned. This byte is not included in
5098 ** the final value of (*pnByte), if applicable.
5100 ** NULL is returned if any error is encountered. The final value of *pnByte
5101 ** is undefined in this case.
5103 static char *readFile(const char *zName, int *pnByte){
5104 FILE *in = fopen(zName, "rb");
5105 long nIn;
5106 size_t nRead;
5107 char *pBuf;
5108 int rc;
5109 if( in==0 ) return 0;
5110 rc = fseek(in, 0, SEEK_END);
5111 if( rc!=0 ){
5112 raw_printf(stderr, "Error: '%s' not seekable\n", zName);
5113 fclose(in);
5114 return 0;
5116 nIn = ftell(in);
5117 rewind(in);
5118 pBuf = sqlite3_malloc64( nIn+1 );
5119 if( pBuf==0 ){
5120 raw_printf(stderr, "Error: out of memory\n");
5121 fclose(in);
5122 return 0;
5124 nRead = fread(pBuf, nIn, 1, in);
5125 fclose(in);
5126 if( nRead!=1 ){
5127 sqlite3_free(pBuf);
5128 raw_printf(stderr, "Error: cannot read '%s'\n", zName);
5129 return 0;
5131 pBuf[nIn] = 0;
5132 if( pnByte ) *pnByte = nIn;
5133 return pBuf;
5136 #if defined(SQLITE_ENABLE_SESSION)
5138 ** Close a single OpenSession object and release all of its associated
5139 ** resources.
5141 static void session_close(OpenSession *pSession){
5142 int i;
5143 sqlite3session_delete(pSession->p);
5144 sqlite3_free(pSession->zName);
5145 for(i=0; i<pSession->nFilter; i++){
5146 sqlite3_free(pSession->azFilter[i]);
5148 sqlite3_free(pSession->azFilter);
5149 memset(pSession, 0, sizeof(OpenSession));
5151 #endif
5154 ** Close all OpenSession objects and release all associated resources.
5156 #if defined(SQLITE_ENABLE_SESSION)
5157 static void session_close_all(ShellState *p, int i){
5158 int j;
5159 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
5160 for(j=0; j<pAuxDb->nSession; j++){
5161 session_close(&pAuxDb->aSession[j]);
5163 pAuxDb->nSession = 0;
5165 #else
5166 # define session_close_all(X,Y)
5167 #endif
5170 ** Implementation of the xFilter function for an open session. Omit
5171 ** any tables named by ".session filter" but let all other table through.
5173 #if defined(SQLITE_ENABLE_SESSION)
5174 static int session_filter(void *pCtx, const char *zTab){
5175 OpenSession *pSession = (OpenSession*)pCtx;
5176 int i;
5177 for(i=0; i<pSession->nFilter; i++){
5178 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
5180 return 1;
5182 #endif
5185 ** Try to deduce the type of file for zName based on its content. Return
5186 ** one of the SHELL_OPEN_* constants.
5188 ** If the file does not exist or is empty but its name looks like a ZIP
5189 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
5190 ** Otherwise, assume an ordinary database regardless of the filename if
5191 ** the type cannot be determined from content.
5193 int deduceDatabaseType(const char *zName, int dfltZip){
5194 FILE *f = fopen(zName, "rb");
5195 size_t n;
5196 int rc = SHELL_OPEN_UNSPEC;
5197 char zBuf[100];
5198 if( f==0 ){
5199 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5200 return SHELL_OPEN_ZIPFILE;
5201 }else{
5202 return SHELL_OPEN_NORMAL;
5205 n = fread(zBuf, 16, 1, f);
5206 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
5207 fclose(f);
5208 return SHELL_OPEN_NORMAL;
5210 fseek(f, -25, SEEK_END);
5211 n = fread(zBuf, 25, 1, f);
5212 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
5213 rc = SHELL_OPEN_APPENDVFS;
5214 }else{
5215 fseek(f, -22, SEEK_END);
5216 n = fread(zBuf, 22, 1, f);
5217 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
5218 && zBuf[3]==0x06 ){
5219 rc = SHELL_OPEN_ZIPFILE;
5220 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
5221 rc = SHELL_OPEN_ZIPFILE;
5224 fclose(f);
5225 return rc;
5228 #ifndef SQLITE_OMIT_DESERIALIZE
5230 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5231 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5232 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5234 static unsigned char *readHexDb(ShellState *p, int *pnData){
5235 unsigned char *a = 0;
5236 int nLine;
5237 int n = 0;
5238 int pgsz = 0;
5239 int iOffset = 0;
5240 int j, k;
5241 int rc;
5242 FILE *in;
5243 const char *zDbFilename = p->pAuxDb->zDbFilename;
5244 unsigned int x[16];
5245 char zLine[1000];
5246 if( zDbFilename ){
5247 in = fopen(zDbFilename, "r");
5248 if( in==0 ){
5249 utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
5250 return 0;
5252 nLine = 0;
5253 }else{
5254 in = p->in;
5255 nLine = p->lineno;
5256 if( in==0 ) in = stdin;
5258 *pnData = 0;
5259 nLine++;
5260 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
5261 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
5262 if( rc!=2 ) goto readHexDb_error;
5263 if( n<0 ) goto readHexDb_error;
5264 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
5265 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
5266 a = sqlite3_malloc( n ? n : 1 );
5267 shell_check_oom(a);
5268 memset(a, 0, n);
5269 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
5270 utf8_printf(stderr, "invalid pagesize\n");
5271 goto readHexDb_error;
5273 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
5274 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
5275 if( rc==2 ){
5276 iOffset = k;
5277 continue;
5279 if( cli_strncmp(zLine, "| end ", 6)==0 ){
5280 break;
5282 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5283 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
5284 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
5285 if( rc==17 ){
5286 k = iOffset+j;
5287 if( k+16<=n && k>=0 ){
5288 int ii;
5289 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
5293 *pnData = n;
5294 if( in!=p->in ){
5295 fclose(in);
5296 }else{
5297 p->lineno = nLine;
5299 return a;
5301 readHexDb_error:
5302 if( in!=p->in ){
5303 fclose(in);
5304 }else{
5305 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
5306 nLine++;
5307 if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
5309 p->lineno = nLine;
5311 sqlite3_free(a);
5312 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
5313 return 0;
5315 #endif /* SQLITE_OMIT_DESERIALIZE */
5318 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5320 static void shellUSleepFunc(
5321 sqlite3_context *context,
5322 int argcUnused,
5323 sqlite3_value **argv
5325 int sleep = sqlite3_value_int(argv[0]);
5326 (void)argcUnused;
5327 sqlite3_sleep(sleep/1000);
5328 sqlite3_result_int(context, sleep);
5331 /* Flags for open_db().
5333 ** The default behavior of open_db() is to exit(1) if the database fails to
5334 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5335 ** but still returns without calling exit.
5337 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5338 ** ZIP archive if the file does not exist or is empty and its name matches
5339 ** the *.zip pattern.
5341 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5342 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5345 ** Make sure the database is open. If it is not, then open it. If
5346 ** the database fails to open, print an error message and exit.
5348 static void open_db(ShellState *p, int openFlags){
5349 if( p->db==0 ){
5350 const char *zDbFilename = p->pAuxDb->zDbFilename;
5351 if( p->openMode==SHELL_OPEN_UNSPEC ){
5352 if( zDbFilename==0 || zDbFilename[0]==0 ){
5353 p->openMode = SHELL_OPEN_NORMAL;
5354 }else{
5355 p->openMode = (u8)deduceDatabaseType(zDbFilename,
5356 (openFlags & OPEN_DB_ZIPFILE)!=0);
5359 switch( p->openMode ){
5360 case SHELL_OPEN_APPENDVFS: {
5361 sqlite3_open_v2(zDbFilename, &p->db,
5362 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5363 break;
5365 case SHELL_OPEN_HEXDB:
5366 case SHELL_OPEN_DESERIALIZE: {
5367 sqlite3_open(0, &p->db);
5368 break;
5370 case SHELL_OPEN_ZIPFILE: {
5371 sqlite3_open(":memory:", &p->db);
5372 break;
5374 case SHELL_OPEN_READONLY: {
5375 sqlite3_open_v2(zDbFilename, &p->db,
5376 SQLITE_OPEN_READONLY|p->openFlags, 0);
5377 break;
5379 case SHELL_OPEN_UNSPEC:
5380 case SHELL_OPEN_NORMAL: {
5381 sqlite3_open_v2(zDbFilename, &p->db,
5382 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5383 break;
5386 globalDb = p->db;
5387 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5388 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5389 zDbFilename, sqlite3_errmsg(p->db));
5390 if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
5391 exit(1);
5393 sqlite3_close(p->db);
5394 sqlite3_open(":memory:", &p->db);
5395 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5396 utf8_printf(stderr,
5397 "Also: unable to open substitute in-memory database.\n"
5399 exit(1);
5400 }else{
5401 utf8_printf(stderr,
5402 "Notice: using substitute in-memory database instead of \"%s\"\n",
5403 zDbFilename);
5406 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
5408 /* Reflect the use or absence of --unsafe-testing invocation. */
5410 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
5411 sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
5412 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
5415 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5416 sqlite3_enable_load_extension(p->db, 1);
5417 #endif
5418 sqlite3_shathree_init(p->db, 0, 0);
5419 sqlite3_uint_init(p->db, 0, 0);
5420 sqlite3_decimal_init(p->db, 0, 0);
5421 sqlite3_base64_init(p->db, 0, 0);
5422 sqlite3_base85_init(p->db, 0, 0);
5423 sqlite3_regexp_init(p->db, 0, 0);
5424 sqlite3_ieee_init(p->db, 0, 0);
5425 sqlite3_series_init(p->db, 0, 0);
5426 #ifndef SQLITE_SHELL_FIDDLE
5427 sqlite3_fileio_init(p->db, 0, 0);
5428 sqlite3_completion_init(p->db, 0, 0);
5429 #endif
5430 #ifdef SQLITE_HAVE_ZLIB
5431 if( !p->bSafeModePersist ){
5432 sqlite3_zipfile_init(p->db, 0, 0);
5433 sqlite3_sqlar_init(p->db, 0, 0);
5435 #endif
5436 #ifdef SQLITE_SHELL_EXTFUNCS
5437 /* Create a preprocessing mechanism for extensions to make
5438 * their own provisions for being built into the shell.
5439 * This is a short-span macro. See further below for usage.
5441 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5442 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5443 /* Let custom-included extensions get their ..._init() called.
5444 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5445 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5446 * inititialization routine to be called.
5449 int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
5450 /* Let custom-included extensions expose their functionality.
5451 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5452 * the SQL functions, virtual tables, collating sequences or
5453 * VFS's implemented by the extension to be registered.
5455 if( irc==SQLITE_OK
5456 || irc==SQLITE_OK_LOAD_PERMANENTLY ){
5457 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
5459 #undef SHELL_SUB_MACRO
5460 #undef SHELL_SUBMACRO
5462 #endif
5464 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5465 shellAddSchemaName, 0, 0);
5466 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5467 shellModuleSchema, 0, 0);
5468 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5469 shellPutsFunc, 0, 0);
5470 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5471 shellUSleepFunc, 0, 0);
5472 #ifndef SQLITE_NOHAVE_SYSTEM
5473 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5474 editFunc, 0, 0);
5475 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5476 editFunc, 0, 0);
5477 #endif
5479 if( p->openMode==SHELL_OPEN_ZIPFILE ){
5480 char *zSql = sqlite3_mprintf(
5481 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5482 shell_check_oom(zSql);
5483 sqlite3_exec(p->db, zSql, 0, 0, 0);
5484 sqlite3_free(zSql);
5486 #ifndef SQLITE_OMIT_DESERIALIZE
5487 else
5488 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5489 int rc;
5490 int nData = 0;
5491 unsigned char *aData;
5492 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5493 aData = (unsigned char*)readFile(zDbFilename, &nData);
5494 }else{
5495 aData = readHexDb(p, &nData);
5497 if( aData==0 ){
5498 return;
5500 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5501 SQLITE_DESERIALIZE_RESIZEABLE |
5502 SQLITE_DESERIALIZE_FREEONCLOSE);
5503 if( rc ){
5504 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5506 if( p->szMax>0 ){
5507 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5510 #endif
5512 if( p->db!=0 ){
5513 if( p->bSafeModePersist ){
5514 sqlite3_set_authorizer(p->db, safeModeAuth, p);
5516 sqlite3_db_config(
5517 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
5523 ** Attempt to close the databaes connection. Report errors.
5525 void close_db(sqlite3 *db){
5526 int rc = sqlite3_close(db);
5527 if( rc ){
5528 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5529 rc, sqlite3_errmsg(db));
5533 #if HAVE_READLINE || HAVE_EDITLINE
5535 ** Readline completion callbacks
5537 static char *readline_completion_generator(const char *text, int state){
5538 static sqlite3_stmt *pStmt = 0;
5539 char *zRet;
5540 if( state==0 ){
5541 char *zSql;
5542 sqlite3_finalize(pStmt);
5543 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5544 " FROM completion(%Q) ORDER BY 1", text);
5545 shell_check_oom(zSql);
5546 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5547 sqlite3_free(zSql);
5549 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5550 const char *z = (const char*)sqlite3_column_text(pStmt,0);
5551 zRet = z ? strdup(z) : 0;
5552 }else{
5553 sqlite3_finalize(pStmt);
5554 pStmt = 0;
5555 zRet = 0;
5557 return zRet;
5559 static char **readline_completion(const char *zText, int iStart, int iEnd){
5560 (void)iStart;
5561 (void)iEnd;
5562 rl_attempted_completion_over = 1;
5563 return rl_completion_matches(zText, readline_completion_generator);
5566 #elif HAVE_LINENOISE
5568 ** Linenoise completion callback
5570 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5571 i64 nLine = strlen(zLine);
5572 i64 i, iStart;
5573 sqlite3_stmt *pStmt = 0;
5574 char *zSql;
5575 char zBuf[1000];
5577 if( nLine>(i64)sizeof(zBuf)-30 ) return;
5578 if( zLine[0]=='.' || zLine[0]=='#') return;
5579 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5580 if( i==nLine-1 ) return;
5581 iStart = i+1;
5582 memcpy(zBuf, zLine, iStart);
5583 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5584 " FROM completion(%Q,%Q) ORDER BY 1",
5585 &zLine[iStart], zLine);
5586 shell_check_oom(zSql);
5587 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5588 sqlite3_free(zSql);
5589 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5590 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5591 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5592 int nCompletion = sqlite3_column_bytes(pStmt, 0);
5593 if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
5594 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5595 linenoiseAddCompletion(lc, zBuf);
5598 sqlite3_finalize(pStmt);
5600 #endif
5603 ** Do C-language style dequoting.
5605 ** \a -> alarm
5606 ** \b -> backspace
5607 ** \t -> tab
5608 ** \n -> newline
5609 ** \v -> vertical tab
5610 ** \f -> form feed
5611 ** \r -> carriage return
5612 ** \s -> space
5613 ** \" -> "
5614 ** \' -> '
5615 ** \\ -> backslash
5616 ** \NNN -> ascii character NNN in octal
5617 ** \xHH -> ascii character HH in hexadecimal
5619 static void resolve_backslashes(char *z){
5620 int i, j;
5621 char c;
5622 while( *z && *z!='\\' ) z++;
5623 for(i=j=0; (c = z[i])!=0; i++, j++){
5624 if( c=='\\' && z[i+1]!=0 ){
5625 c = z[++i];
5626 if( c=='a' ){
5627 c = '\a';
5628 }else if( c=='b' ){
5629 c = '\b';
5630 }else if( c=='t' ){
5631 c = '\t';
5632 }else if( c=='n' ){
5633 c = '\n';
5634 }else if( c=='v' ){
5635 c = '\v';
5636 }else if( c=='f' ){
5637 c = '\f';
5638 }else if( c=='r' ){
5639 c = '\r';
5640 }else if( c=='"' ){
5641 c = '"';
5642 }else if( c=='\'' ){
5643 c = '\'';
5644 }else if( c=='\\' ){
5645 c = '\\';
5646 }else if( c=='x' ){
5647 int nhd = 0, hdv;
5648 u8 hv = 0;
5649 while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
5650 hv = (u8)((hv<<4)|hdv);
5651 ++nhd;
5653 i += nhd;
5654 c = (u8)hv;
5655 }else if( c>='0' && c<='7' ){
5656 c -= '0';
5657 if( z[i+1]>='0' && z[i+1]<='7' ){
5658 i++;
5659 c = (c<<3) + z[i] - '0';
5660 if( z[i+1]>='0' && z[i+1]<='7' ){
5661 i++;
5662 c = (c<<3) + z[i] - '0';
5667 z[j] = c;
5669 if( j<i ) z[j] = 0;
5673 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5674 ** for TRUE and FALSE. Return the integer value if appropriate.
5676 static int booleanValue(const char *zArg){
5677 int i;
5678 if( zArg[0]=='0' && zArg[1]=='x' ){
5679 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5680 }else{
5681 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5683 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5684 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5685 return 1;
5687 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5688 return 0;
5690 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5691 zArg);
5692 return 0;
5696 ** Set or clear a shell flag according to a boolean value.
5698 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5699 if( booleanValue(zArg) ){
5700 ShellSetFlag(p, mFlag);
5701 }else{
5702 ShellClearFlag(p, mFlag);
5707 ** Close an output file, assuming it is not stderr or stdout
5709 static void output_file_close(FILE *f){
5710 if( f && f!=stdout && f!=stderr ) fclose(f);
5714 ** Try to open an output file. The names "stdout" and "stderr" are
5715 ** recognized and do the right thing. NULL is returned if the output
5716 ** filename is "off".
5718 static FILE *output_file_open(const char *zFile, int bTextMode){
5719 FILE *f;
5720 if( cli_strcmp(zFile,"stdout")==0 ){
5721 f = stdout;
5722 }else if( cli_strcmp(zFile, "stderr")==0 ){
5723 f = stderr;
5724 }else if( cli_strcmp(zFile, "off")==0 ){
5725 f = 0;
5726 }else{
5727 f = fopen(zFile, bTextMode ? "w" : "wb");
5728 if( f==0 ){
5729 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5732 return f;
5735 #ifndef SQLITE_OMIT_TRACE
5737 ** A routine for handling output from sqlite3_trace().
5739 static int sql_trace_callback(
5740 unsigned mType, /* The trace type */
5741 void *pArg, /* The ShellState pointer */
5742 void *pP, /* Usually a pointer to sqlite_stmt */
5743 void *pX /* Auxiliary output */
5745 ShellState *p = (ShellState*)pArg;
5746 sqlite3_stmt *pStmt;
5747 const char *zSql;
5748 i64 nSql;
5749 if( p->traceOut==0 ) return 0;
5750 if( mType==SQLITE_TRACE_CLOSE ){
5751 utf8_printf(p->traceOut, "-- closing database connection\n");
5752 return 0;
5754 if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
5755 zSql = (const char*)pX;
5756 }else{
5757 pStmt = (sqlite3_stmt*)pP;
5758 switch( p->eTraceType ){
5759 case SHELL_TRACE_EXPANDED: {
5760 zSql = sqlite3_expanded_sql(pStmt);
5761 break;
5763 #ifdef SQLITE_ENABLE_NORMALIZE
5764 case SHELL_TRACE_NORMALIZED: {
5765 zSql = sqlite3_normalized_sql(pStmt);
5766 break;
5768 #endif
5769 default: {
5770 zSql = sqlite3_sql(pStmt);
5771 break;
5775 if( zSql==0 ) return 0;
5776 nSql = strlen(zSql);
5777 if( nSql>1000000000 ) nSql = 1000000000;
5778 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5779 switch( mType ){
5780 case SQLITE_TRACE_ROW:
5781 case SQLITE_TRACE_STMT: {
5782 utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5783 break;
5785 case SQLITE_TRACE_PROFILE: {
5786 sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
5787 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5788 break;
5791 return 0;
5793 #endif
5796 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5797 ** a useful spot to set a debugger breakpoint.
5799 ** This routine does not do anything practical. The code are there simply
5800 ** to prevent the compiler from optimizing this routine out.
5802 static void test_breakpoint(void){
5803 static unsigned int nCall = 0;
5804 if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
5808 ** An object used to read a CSV and other files for import.
5810 typedef struct ImportCtx ImportCtx;
5811 struct ImportCtx {
5812 const char *zFile; /* Name of the input file */
5813 FILE *in; /* Read the CSV text from this input stream */
5814 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */
5815 char *z; /* Accumulated text for a field */
5816 int n; /* Number of bytes in z */
5817 int nAlloc; /* Space allocated for z[] */
5818 int nLine; /* Current line number */
5819 int nRow; /* Number of rows imported */
5820 int nErr; /* Number of errors encountered */
5821 int bNotFirst; /* True if one or more bytes already read */
5822 int cTerm; /* Character that terminated the most recent field */
5823 int cColSep; /* The column separator character. (Usually ",") */
5824 int cRowSep; /* The row separator character. (Usually "\n") */
5827 /* Clean up resourced used by an ImportCtx */
5828 static void import_cleanup(ImportCtx *p){
5829 if( p->in!=0 && p->xCloser!=0 ){
5830 p->xCloser(p->in);
5831 p->in = 0;
5833 sqlite3_free(p->z);
5834 p->z = 0;
5837 /* Append a single byte to z[] */
5838 static void import_append_char(ImportCtx *p, int c){
5839 if( p->n+1>=p->nAlloc ){
5840 p->nAlloc += p->nAlloc + 100;
5841 p->z = sqlite3_realloc64(p->z, p->nAlloc);
5842 shell_check_oom(p->z);
5844 p->z[p->n++] = (char)c;
5847 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5848 ** with the option of having a separator other than ",".
5850 ** + Input comes from p->in.
5851 ** + Store results in p->z of length p->n. Space to hold p->z comes
5852 ** from sqlite3_malloc64().
5853 ** + Use p->cSep as the column separator. The default is ",".
5854 ** + Use p->rSep as the row separator. The default is "\n".
5855 ** + Keep track of the line number in p->nLine.
5856 ** + Store the character that terminates the field in p->cTerm. Store
5857 ** EOF on end-of-file.
5858 ** + Report syntax errors on stderr
5860 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5861 int c;
5862 int cSep = (u8)p->cColSep;
5863 int rSep = (u8)p->cRowSep;
5864 p->n = 0;
5865 c = fgetc(p->in);
5866 if( c==EOF || seenInterrupt ){
5867 p->cTerm = EOF;
5868 return 0;
5870 if( c=='"' ){
5871 int pc, ppc;
5872 int startLine = p->nLine;
5873 int cQuote = c;
5874 pc = ppc = 0;
5875 while( 1 ){
5876 c = fgetc(p->in);
5877 if( c==rSep ) p->nLine++;
5878 if( c==cQuote ){
5879 if( pc==cQuote ){
5880 pc = 0;
5881 continue;
5884 if( (c==cSep && pc==cQuote)
5885 || (c==rSep && pc==cQuote)
5886 || (c==rSep && pc=='\r' && ppc==cQuote)
5887 || (c==EOF && pc==cQuote)
5889 do{ p->n--; }while( p->z[p->n]!=cQuote );
5890 p->cTerm = c;
5891 break;
5893 if( pc==cQuote && c!='\r' ){
5894 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5895 p->zFile, p->nLine, cQuote);
5897 if( c==EOF ){
5898 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5899 p->zFile, startLine, cQuote);
5900 p->cTerm = c;
5901 break;
5903 import_append_char(p, c);
5904 ppc = pc;
5905 pc = c;
5907 }else{
5908 /* If this is the first field being parsed and it begins with the
5909 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5910 if( (c&0xff)==0xef && p->bNotFirst==0 ){
5911 import_append_char(p, c);
5912 c = fgetc(p->in);
5913 if( (c&0xff)==0xbb ){
5914 import_append_char(p, c);
5915 c = fgetc(p->in);
5916 if( (c&0xff)==0xbf ){
5917 p->bNotFirst = 1;
5918 p->n = 0;
5919 return csv_read_one_field(p);
5923 while( c!=EOF && c!=cSep && c!=rSep ){
5924 import_append_char(p, c);
5925 c = fgetc(p->in);
5927 if( c==rSep ){
5928 p->nLine++;
5929 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5931 p->cTerm = c;
5933 if( p->z ) p->z[p->n] = 0;
5934 p->bNotFirst = 1;
5935 return p->z;
5938 /* Read a single field of ASCII delimited text.
5940 ** + Input comes from p->in.
5941 ** + Store results in p->z of length p->n. Space to hold p->z comes
5942 ** from sqlite3_malloc64().
5943 ** + Use p->cSep as the column separator. The default is "\x1F".
5944 ** + Use p->rSep as the row separator. The default is "\x1E".
5945 ** + Keep track of the row number in p->nLine.
5946 ** + Store the character that terminates the field in p->cTerm. Store
5947 ** EOF on end-of-file.
5948 ** + Report syntax errors on stderr
5950 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5951 int c;
5952 int cSep = (u8)p->cColSep;
5953 int rSep = (u8)p->cRowSep;
5954 p->n = 0;
5955 c = fgetc(p->in);
5956 if( c==EOF || seenInterrupt ){
5957 p->cTerm = EOF;
5958 return 0;
5960 while( c!=EOF && c!=cSep && c!=rSep ){
5961 import_append_char(p, c);
5962 c = fgetc(p->in);
5964 if( c==rSep ){
5965 p->nLine++;
5967 p->cTerm = c;
5968 if( p->z ) p->z[p->n] = 0;
5969 return p->z;
5973 ** Try to transfer data for table zTable. If an error is seen while
5974 ** moving forward, try to go backwards. The backwards movement won't
5975 ** work for WITHOUT ROWID tables.
5977 static void tryToCloneData(
5978 ShellState *p,
5979 sqlite3 *newDb,
5980 const char *zTable
5982 sqlite3_stmt *pQuery = 0;
5983 sqlite3_stmt *pInsert = 0;
5984 char *zQuery = 0;
5985 char *zInsert = 0;
5986 int rc;
5987 int i, j, n;
5988 int nTable = strlen30(zTable);
5989 int k = 0;
5990 int cnt = 0;
5991 const int spinRate = 10000;
5993 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5994 shell_check_oom(zQuery);
5995 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5996 if( rc ){
5997 utf8_printf(stderr, "Error %d: %s on [%s]\n",
5998 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5999 zQuery);
6000 goto end_data_xfer;
6002 n = sqlite3_column_count(pQuery);
6003 zInsert = sqlite3_malloc64(200 + nTable + n*3);
6004 shell_check_oom(zInsert);
6005 sqlite3_snprintf(200+nTable,zInsert,
6006 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
6007 i = strlen30(zInsert);
6008 for(j=1; j<n; j++){
6009 memcpy(zInsert+i, ",?", 2);
6010 i += 2;
6012 memcpy(zInsert+i, ");", 3);
6013 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
6014 if( rc ){
6015 utf8_printf(stderr, "Error %d: %s on [%s]\n",
6016 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
6017 zQuery);
6018 goto end_data_xfer;
6020 for(k=0; k<2; k++){
6021 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
6022 for(i=0; i<n; i++){
6023 switch( sqlite3_column_type(pQuery, i) ){
6024 case SQLITE_NULL: {
6025 sqlite3_bind_null(pInsert, i+1);
6026 break;
6028 case SQLITE_INTEGER: {
6029 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
6030 break;
6032 case SQLITE_FLOAT: {
6033 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
6034 break;
6036 case SQLITE_TEXT: {
6037 sqlite3_bind_text(pInsert, i+1,
6038 (const char*)sqlite3_column_text(pQuery,i),
6039 -1, SQLITE_STATIC);
6040 break;
6042 case SQLITE_BLOB: {
6043 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
6044 sqlite3_column_bytes(pQuery,i),
6045 SQLITE_STATIC);
6046 break;
6049 } /* End for */
6050 rc = sqlite3_step(pInsert);
6051 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
6052 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
6053 sqlite3_errmsg(newDb));
6055 sqlite3_reset(pInsert);
6056 cnt++;
6057 if( (cnt%spinRate)==0 ){
6058 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
6059 fflush(stdout);
6061 } /* End while */
6062 if( rc==SQLITE_DONE ) break;
6063 sqlite3_finalize(pQuery);
6064 sqlite3_free(zQuery);
6065 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
6066 zTable);
6067 shell_check_oom(zQuery);
6068 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6069 if( rc ){
6070 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
6071 break;
6073 } /* End for(k=0...) */
6075 end_data_xfer:
6076 sqlite3_finalize(pQuery);
6077 sqlite3_finalize(pInsert);
6078 sqlite3_free(zQuery);
6079 sqlite3_free(zInsert);
6084 ** Try to transfer all rows of the schema that match zWhere. For
6085 ** each row, invoke xForEach() on the object defined by that row.
6086 ** If an error is encountered while moving forward through the
6087 ** sqlite_schema table, try again moving backwards.
6089 static void tryToCloneSchema(
6090 ShellState *p,
6091 sqlite3 *newDb,
6092 const char *zWhere,
6093 void (*xForEach)(ShellState*,sqlite3*,const char*)
6095 sqlite3_stmt *pQuery = 0;
6096 char *zQuery = 0;
6097 int rc;
6098 const unsigned char *zName;
6099 const unsigned char *zSql;
6100 char *zErrMsg = 0;
6102 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6103 " WHERE %s ORDER BY rowid ASC", zWhere);
6104 shell_check_oom(zQuery);
6105 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6106 if( rc ){
6107 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
6108 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
6109 zQuery);
6110 goto end_schema_xfer;
6112 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
6113 zName = sqlite3_column_text(pQuery, 0);
6114 zSql = sqlite3_column_text(pQuery, 1);
6115 if( zName==0 || zSql==0 ) continue;
6116 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
6117 printf("%s... ", zName); fflush(stdout);
6118 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6119 if( zErrMsg ){
6120 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6121 sqlite3_free(zErrMsg);
6122 zErrMsg = 0;
6125 if( xForEach ){
6126 xForEach(p, newDb, (const char*)zName);
6128 printf("done\n");
6130 if( rc!=SQLITE_DONE ){
6131 sqlite3_finalize(pQuery);
6132 sqlite3_free(zQuery);
6133 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6134 " WHERE %s ORDER BY rowid DESC", zWhere);
6135 shell_check_oom(zQuery);
6136 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
6137 if( rc ){
6138 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
6139 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
6140 zQuery);
6141 goto end_schema_xfer;
6143 while( sqlite3_step(pQuery)==SQLITE_ROW ){
6144 zName = sqlite3_column_text(pQuery, 0);
6145 zSql = sqlite3_column_text(pQuery, 1);
6146 if( zName==0 || zSql==0 ) continue;
6147 if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
6148 printf("%s... ", zName); fflush(stdout);
6149 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
6150 if( zErrMsg ){
6151 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
6152 sqlite3_free(zErrMsg);
6153 zErrMsg = 0;
6155 if( xForEach ){
6156 xForEach(p, newDb, (const char*)zName);
6158 printf("done\n");
6161 end_schema_xfer:
6162 sqlite3_finalize(pQuery);
6163 sqlite3_free(zQuery);
6167 ** Open a new database file named "zNewDb". Try to recover as much information
6168 ** as possible out of the main database (which might be corrupt) and write it
6169 ** into zNewDb.
6171 static void tryToClone(ShellState *p, const char *zNewDb){
6172 int rc;
6173 sqlite3 *newDb = 0;
6174 if( access(zNewDb,0)==0 ){
6175 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
6176 return;
6178 rc = sqlite3_open(zNewDb, &newDb);
6179 if( rc ){
6180 utf8_printf(stderr, "Cannot create output database: %s\n",
6181 sqlite3_errmsg(newDb));
6182 }else{
6183 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
6184 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
6185 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
6186 tryToCloneSchema(p, newDb, "type!='table'", 0);
6187 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
6188 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6190 close_db(newDb);
6194 ** Change the output file back to stdout.
6196 ** If the p->doXdgOpen flag is set, that means the output was being
6197 ** redirected to a temporary file named by p->zTempFile. In that case,
6198 ** launch start/open/xdg-open on that temporary file.
6200 static void output_reset(ShellState *p){
6201 if( p->outfile[0]=='|' ){
6202 #ifndef SQLITE_OMIT_POPEN
6203 pclose(p->out);
6204 #endif
6205 }else{
6206 output_file_close(p->out);
6207 #ifndef SQLITE_NOHAVE_SYSTEM
6208 if( p->doXdgOpen ){
6209 const char *zXdgOpenCmd =
6210 #if defined(_WIN32)
6211 "start";
6212 #elif defined(__APPLE__)
6213 "open";
6214 #else
6215 "xdg-open";
6216 #endif
6217 char *zCmd;
6218 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
6219 if( system(zCmd) ){
6220 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
6221 }else{
6222 /* Give the start/open/xdg-open command some time to get
6223 ** going before we continue, and potential delete the
6224 ** p->zTempFile data file out from under it */
6225 sqlite3_sleep(2000);
6227 sqlite3_free(zCmd);
6228 outputModePop(p);
6229 p->doXdgOpen = 0;
6231 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6233 p->outfile[0] = 0;
6234 p->out = stdout;
6238 ** Run an SQL command and return the single integer result.
6240 static int db_int(sqlite3 *db, const char *zSql){
6241 sqlite3_stmt *pStmt;
6242 int res = 0;
6243 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
6244 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
6245 res = sqlite3_column_int(pStmt,0);
6247 sqlite3_finalize(pStmt);
6248 return res;
6251 #if SQLITE_SHELL_HAVE_RECOVER
6253 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6255 static unsigned int get2byteInt(unsigned char *a){
6256 return (a[0]<<8) + a[1];
6258 static unsigned int get4byteInt(unsigned char *a){
6259 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
6263 ** Implementation of the ".dbinfo" command.
6265 ** Return 1 on error, 2 to exit, and 0 otherwise.
6267 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
6268 static const struct { const char *zName; int ofst; } aField[] = {
6269 { "file change counter:", 24 },
6270 { "database page count:", 28 },
6271 { "freelist page count:", 36 },
6272 { "schema cookie:", 40 },
6273 { "schema format:", 44 },
6274 { "default cache size:", 48 },
6275 { "autovacuum top root:", 52 },
6276 { "incremental vacuum:", 64 },
6277 { "text encoding:", 56 },
6278 { "user version:", 60 },
6279 { "application id:", 68 },
6280 { "software version:", 96 },
6282 static const struct { const char *zName; const char *zSql; } aQuery[] = {
6283 { "number of tables:",
6284 "SELECT count(*) FROM %s WHERE type='table'" },
6285 { "number of indexes:",
6286 "SELECT count(*) FROM %s WHERE type='index'" },
6287 { "number of triggers:",
6288 "SELECT count(*) FROM %s WHERE type='trigger'" },
6289 { "number of views:",
6290 "SELECT count(*) FROM %s WHERE type='view'" },
6291 { "schema size:",
6292 "SELECT total(length(sql)) FROM %s" },
6294 int i, rc;
6295 unsigned iDataVersion;
6296 char *zSchemaTab;
6297 char *zDb = nArg>=2 ? azArg[1] : "main";
6298 sqlite3_stmt *pStmt = 0;
6299 unsigned char aHdr[100];
6300 open_db(p, 0);
6301 if( p->db==0 ) return 1;
6302 rc = sqlite3_prepare_v2(p->db,
6303 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6304 -1, &pStmt, 0);
6305 if( rc ){
6306 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
6307 sqlite3_finalize(pStmt);
6308 return 1;
6310 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
6311 if( sqlite3_step(pStmt)==SQLITE_ROW
6312 && sqlite3_column_bytes(pStmt,0)>100
6314 const u8 *pb = sqlite3_column_blob(pStmt,0);
6315 shell_check_oom(pb);
6316 memcpy(aHdr, pb, 100);
6317 sqlite3_finalize(pStmt);
6318 }else{
6319 raw_printf(stderr, "unable to read database header\n");
6320 sqlite3_finalize(pStmt);
6321 return 1;
6323 i = get2byteInt(aHdr+16);
6324 if( i==1 ) i = 65536;
6325 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
6326 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
6327 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
6328 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
6329 for(i=0; i<ArraySize(aField); i++){
6330 int ofst = aField[i].ofst;
6331 unsigned int val = get4byteInt(aHdr + ofst);
6332 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
6333 switch( ofst ){
6334 case 56: {
6335 if( val==1 ) raw_printf(p->out, " (utf8)");
6336 if( val==2 ) raw_printf(p->out, " (utf16le)");
6337 if( val==3 ) raw_printf(p->out, " (utf16be)");
6340 raw_printf(p->out, "\n");
6342 if( zDb==0 ){
6343 zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
6344 }else if( cli_strcmp(zDb,"temp")==0 ){
6345 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
6346 }else{
6347 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
6349 for(i=0; i<ArraySize(aQuery); i++){
6350 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
6351 int val = db_int(p->db, zSql);
6352 sqlite3_free(zSql);
6353 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
6355 sqlite3_free(zSchemaTab);
6356 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
6357 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
6358 return 0;
6360 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6363 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6365 static int shellDatabaseError(sqlite3 *db){
6366 const char *zErr = sqlite3_errmsg(db);
6367 utf8_printf(stderr, "Error: %s\n", zErr);
6368 return 1;
6372 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6373 ** if they match and FALSE (0) if they do not match.
6375 ** Globbing rules:
6377 ** '*' Matches any sequence of zero or more characters.
6379 ** '?' Matches exactly one character.
6381 ** [...] Matches one character from the enclosed list of
6382 ** characters.
6384 ** [^...] Matches one character not in the enclosed list.
6386 ** '#' Matches any sequence of one or more digits with an
6387 ** optional + or - sign in front
6389 ** ' ' Any span of whitespace matches any other span of
6390 ** whitespace.
6392 ** Extra whitespace at the end of z[] is ignored.
6394 static int testcase_glob(const char *zGlob, const char *z){
6395 int c, c2;
6396 int invert;
6397 int seen;
6399 while( (c = (*(zGlob++)))!=0 ){
6400 if( IsSpace(c) ){
6401 if( !IsSpace(*z) ) return 0;
6402 while( IsSpace(*zGlob) ) zGlob++;
6403 while( IsSpace(*z) ) z++;
6404 }else if( c=='*' ){
6405 while( (c=(*(zGlob++))) == '*' || c=='?' ){
6406 if( c=='?' && (*(z++))==0 ) return 0;
6408 if( c==0 ){
6409 return 1;
6410 }else if( c=='[' ){
6411 while( *z && testcase_glob(zGlob-1,z)==0 ){
6412 z++;
6414 return (*z)!=0;
6416 while( (c2 = (*(z++)))!=0 ){
6417 while( c2!=c ){
6418 c2 = *(z++);
6419 if( c2==0 ) return 0;
6421 if( testcase_glob(zGlob,z) ) return 1;
6423 return 0;
6424 }else if( c=='?' ){
6425 if( (*(z++))==0 ) return 0;
6426 }else if( c=='[' ){
6427 int prior_c = 0;
6428 seen = 0;
6429 invert = 0;
6430 c = *(z++);
6431 if( c==0 ) return 0;
6432 c2 = *(zGlob++);
6433 if( c2=='^' ){
6434 invert = 1;
6435 c2 = *(zGlob++);
6437 if( c2==']' ){
6438 if( c==']' ) seen = 1;
6439 c2 = *(zGlob++);
6441 while( c2 && c2!=']' ){
6442 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6443 c2 = *(zGlob++);
6444 if( c>=prior_c && c<=c2 ) seen = 1;
6445 prior_c = 0;
6446 }else{
6447 if( c==c2 ){
6448 seen = 1;
6450 prior_c = c2;
6452 c2 = *(zGlob++);
6454 if( c2==0 || (seen ^ invert)==0 ) return 0;
6455 }else if( c=='#' ){
6456 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6457 if( !IsDigit(z[0]) ) return 0;
6458 z++;
6459 while( IsDigit(z[0]) ){ z++; }
6460 }else{
6461 if( c!=(*(z++)) ) return 0;
6464 while( IsSpace(*z) ){ z++; }
6465 return *z==0;
6470 ** Compare the string as a command-line option with either one or two
6471 ** initial "-" characters.
6473 static int optionMatch(const char *zStr, const char *zOpt){
6474 if( zStr[0]!='-' ) return 0;
6475 zStr++;
6476 if( zStr[0]=='-' ) zStr++;
6477 return cli_strcmp(zStr, zOpt)==0;
6481 ** Delete a file.
6483 int shellDeleteFile(const char *zFilename){
6484 int rc;
6485 #ifdef _WIN32
6486 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6487 rc = _wunlink(z);
6488 sqlite3_free(z);
6489 #else
6490 rc = unlink(zFilename);
6491 #endif
6492 return rc;
6496 ** Try to delete the temporary file (if there is one) and free the
6497 ** memory used to hold the name of the temp file.
6499 static void clearTempFile(ShellState *p){
6500 if( p->zTempFile==0 ) return;
6501 if( p->doXdgOpen ) return;
6502 if( shellDeleteFile(p->zTempFile) ) return;
6503 sqlite3_free(p->zTempFile);
6504 p->zTempFile = 0;
6508 ** Create a new temp file name with the given suffix.
6510 static void newTempFile(ShellState *p, const char *zSuffix){
6511 clearTempFile(p);
6512 sqlite3_free(p->zTempFile);
6513 p->zTempFile = 0;
6514 if( p->db ){
6515 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6517 if( p->zTempFile==0 ){
6518 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6519 ** will not work and we will need to fallback to guessing */
6520 char *zTemp;
6521 sqlite3_uint64 r;
6522 sqlite3_randomness(sizeof(r), &r);
6523 zTemp = getenv("TEMP");
6524 if( zTemp==0 ) zTemp = getenv("TMP");
6525 if( zTemp==0 ){
6526 #ifdef _WIN32
6527 zTemp = "\\tmp";
6528 #else
6529 zTemp = "/tmp";
6530 #endif
6532 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6533 }else{
6534 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6536 shell_check_oom(p->zTempFile);
6541 ** The implementation of SQL scalar function fkey_collate_clause(), used
6542 ** by the ".lint fkey-indexes" command. This scalar function is always
6543 ** called with four arguments - the parent table name, the parent column name,
6544 ** the child table name and the child column name.
6546 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6548 ** If either of the named tables or columns do not exist, this function
6549 ** returns an empty string. An empty string is also returned if both tables
6550 ** and columns exist but have the same default collation sequence. Or,
6551 ** if both exist but the default collation sequences are different, this
6552 ** function returns the string " COLLATE <parent-collation>", where
6553 ** <parent-collation> is the default collation sequence of the parent column.
6555 static void shellFkeyCollateClause(
6556 sqlite3_context *pCtx,
6557 int nVal,
6558 sqlite3_value **apVal
6560 sqlite3 *db = sqlite3_context_db_handle(pCtx);
6561 const char *zParent;
6562 const char *zParentCol;
6563 const char *zParentSeq;
6564 const char *zChild;
6565 const char *zChildCol;
6566 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
6567 int rc;
6569 assert( nVal==4 );
6570 zParent = (const char*)sqlite3_value_text(apVal[0]);
6571 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6572 zChild = (const char*)sqlite3_value_text(apVal[2]);
6573 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6575 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6576 rc = sqlite3_table_column_metadata(
6577 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6579 if( rc==SQLITE_OK ){
6580 rc = sqlite3_table_column_metadata(
6581 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6585 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6586 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6587 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6588 sqlite3_free(z);
6594 ** The implementation of dot-command ".lint fkey-indexes".
6596 static int lintFkeyIndexes(
6597 ShellState *pState, /* Current shell tool state */
6598 char **azArg, /* Array of arguments passed to dot command */
6599 int nArg /* Number of entries in azArg[] */
6601 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
6602 FILE *out = pState->out; /* Stream to write non-error output to */
6603 int bVerbose = 0; /* If -verbose is present */
6604 int bGroupByParent = 0; /* If -groupbyparent is present */
6605 int i; /* To iterate through azArg[] */
6606 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
6607 int rc; /* Return code */
6608 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
6611 ** This SELECT statement returns one row for each foreign key constraint
6612 ** in the schema of the main database. The column values are:
6614 ** 0. The text of an SQL statement similar to:
6616 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6618 ** This SELECT is similar to the one that the foreign keys implementation
6619 ** needs to run internally on child tables. If there is an index that can
6620 ** be used to optimize this query, then it can also be used by the FK
6621 ** implementation to optimize DELETE or UPDATE statements on the parent
6622 ** table.
6624 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6625 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6626 ** contains an index that can be used to optimize the query.
6628 ** 2. Human readable text that describes the child table and columns. e.g.
6630 ** "child_table(child_key1, child_key2)"
6632 ** 3. Human readable text that describes the parent table and columns. e.g.
6634 ** "parent_table(parent_key1, parent_key2)"
6636 ** 4. A full CREATE INDEX statement for an index that could be used to
6637 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6639 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6641 ** 5. The name of the parent table.
6643 ** These six values are used by the C logic below to generate the report.
6645 const char *zSql =
6646 "SELECT "
6647 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6648 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6649 " || fkey_collate_clause("
6650 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6651 ", "
6652 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6653 " || group_concat('*=?', ' AND ') || ')'"
6654 ", "
6655 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6656 ", "
6657 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6658 ", "
6659 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6660 " || ' ON ' || quote(s.name) || '('"
6661 " || group_concat(quote(f.[from]) ||"
6662 " fkey_collate_clause("
6663 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6664 " || ');'"
6665 ", "
6666 " f.[table] "
6667 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6668 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6669 "GROUP BY s.name, f.id "
6670 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6672 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6674 for(i=2; i<nArg; i++){
6675 int n = strlen30(azArg[i]);
6676 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6677 bVerbose = 1;
6679 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6680 bGroupByParent = 1;
6681 zIndent = " ";
6683 else{
6684 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6685 azArg[0], azArg[1]
6687 return SQLITE_ERROR;
6691 /* Register the fkey_collate_clause() SQL function */
6692 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6693 0, shellFkeyCollateClause, 0, 0
6697 if( rc==SQLITE_OK ){
6698 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6700 if( rc==SQLITE_OK ){
6701 sqlite3_bind_int(pSql, 1, bGroupByParent);
6704 if( rc==SQLITE_OK ){
6705 int rc2;
6706 char *zPrev = 0;
6707 while( SQLITE_ROW==sqlite3_step(pSql) ){
6708 int res = -1;
6709 sqlite3_stmt *pExplain = 0;
6710 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6711 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6712 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6713 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6714 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6715 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6717 if( zEQP==0 ) continue;
6718 if( zGlob==0 ) continue;
6719 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6720 if( rc!=SQLITE_OK ) break;
6721 if( SQLITE_ROW==sqlite3_step(pExplain) ){
6722 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6723 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan)
6724 || 0==sqlite3_strglob(zGlobIPK, zPlan));
6726 rc = sqlite3_finalize(pExplain);
6727 if( rc!=SQLITE_OK ) break;
6729 if( res<0 ){
6730 raw_printf(stderr, "Error: internal error");
6731 break;
6732 }else{
6733 if( bGroupByParent
6734 && (bVerbose || res==0)
6735 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6737 raw_printf(out, "-- Parent table %s\n", zParent);
6738 sqlite3_free(zPrev);
6739 zPrev = sqlite3_mprintf("%s", zParent);
6742 if( res==0 ){
6743 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6744 }else if( bVerbose ){
6745 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6746 zIndent, zFrom, zTarget
6751 sqlite3_free(zPrev);
6753 if( rc!=SQLITE_OK ){
6754 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6757 rc2 = sqlite3_finalize(pSql);
6758 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6759 rc = rc2;
6760 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6762 }else{
6763 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6766 return rc;
6770 ** Implementation of ".lint" dot command.
6772 static int lintDotCommand(
6773 ShellState *pState, /* Current shell tool state */
6774 char **azArg, /* Array of arguments passed to dot command */
6775 int nArg /* Number of entries in azArg[] */
6777 int n;
6778 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6779 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6780 return lintFkeyIndexes(pState, azArg, nArg);
6782 usage:
6783 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6784 raw_printf(stderr, "Where sub-commands are:\n");
6785 raw_printf(stderr, " fkey-indexes\n");
6786 return SQLITE_ERROR;
6789 #if !defined SQLITE_OMIT_VIRTUALTABLE
6790 static void shellPrepare(
6791 sqlite3 *db,
6792 int *pRc,
6793 const char *zSql,
6794 sqlite3_stmt **ppStmt
6796 *ppStmt = 0;
6797 if( *pRc==SQLITE_OK ){
6798 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6799 if( rc!=SQLITE_OK ){
6800 raw_printf(stderr, "sql error: %s (%d)\n",
6801 sqlite3_errmsg(db), sqlite3_errcode(db)
6803 *pRc = rc;
6809 ** Create a prepared statement using printf-style arguments for the SQL.
6811 ** This routine is could be marked "static". But it is not always used,
6812 ** depending on compile-time options. By omitting the "static", we avoid
6813 ** nuisance compiler warnings about "defined but not used".
6815 void shellPreparePrintf(
6816 sqlite3 *db,
6817 int *pRc,
6818 sqlite3_stmt **ppStmt,
6819 const char *zFmt,
6822 *ppStmt = 0;
6823 if( *pRc==SQLITE_OK ){
6824 va_list ap;
6825 char *z;
6826 va_start(ap, zFmt);
6827 z = sqlite3_vmprintf(zFmt, ap);
6828 va_end(ap);
6829 if( z==0 ){
6830 *pRc = SQLITE_NOMEM;
6831 }else{
6832 shellPrepare(db, pRc, z, ppStmt);
6833 sqlite3_free(z);
6838 /* Finalize the prepared statement created using shellPreparePrintf().
6840 ** This routine is could be marked "static". But it is not always used,
6841 ** depending on compile-time options. By omitting the "static", we avoid
6842 ** nuisance compiler warnings about "defined but not used".
6844 void shellFinalize(
6845 int *pRc,
6846 sqlite3_stmt *pStmt
6848 if( pStmt ){
6849 sqlite3 *db = sqlite3_db_handle(pStmt);
6850 int rc = sqlite3_finalize(pStmt);
6851 if( *pRc==SQLITE_OK ){
6852 if( rc!=SQLITE_OK ){
6853 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6855 *pRc = rc;
6860 /* Reset the prepared statement created using shellPreparePrintf().
6862 ** This routine is could be marked "static". But it is not always used,
6863 ** depending on compile-time options. By omitting the "static", we avoid
6864 ** nuisance compiler warnings about "defined but not used".
6866 void shellReset(
6867 int *pRc,
6868 sqlite3_stmt *pStmt
6870 int rc = sqlite3_reset(pStmt);
6871 if( *pRc==SQLITE_OK ){
6872 if( rc!=SQLITE_OK ){
6873 sqlite3 *db = sqlite3_db_handle(pStmt);
6874 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6876 *pRc = rc;
6879 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6881 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6882 /******************************************************************************
6883 ** The ".archive" or ".ar" command.
6886 ** Structure representing a single ".ar" command.
6888 typedef struct ArCommand ArCommand;
6889 struct ArCommand {
6890 u8 eCmd; /* An AR_CMD_* value */
6891 u8 bVerbose; /* True if --verbose */
6892 u8 bZip; /* True if the archive is a ZIP */
6893 u8 bDryRun; /* True if --dry-run */
6894 u8 bAppend; /* True if --append */
6895 u8 bGlob; /* True if --glob */
6896 u8 fromCmdLine; /* Run from -A instead of .archive */
6897 int nArg; /* Number of command arguments */
6898 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
6899 const char *zFile; /* --file argument, or NULL */
6900 const char *zDir; /* --directory argument, or NULL */
6901 char **azArg; /* Array of command arguments */
6902 ShellState *p; /* Shell state */
6903 sqlite3 *db; /* Database containing the archive */
6907 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6909 static int arUsage(FILE *f){
6910 showHelp(f,"archive");
6911 return SQLITE_ERROR;
6915 ** Print an error message for the .ar command to stderr and return
6916 ** SQLITE_ERROR.
6918 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6919 va_list ap;
6920 char *z;
6921 va_start(ap, zFmt);
6922 z = sqlite3_vmprintf(zFmt, ap);
6923 va_end(ap);
6924 utf8_printf(stderr, "Error: %s\n", z);
6925 if( pAr->fromCmdLine ){
6926 utf8_printf(stderr, "Use \"-A\" for more help\n");
6927 }else{
6928 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6930 sqlite3_free(z);
6931 return SQLITE_ERROR;
6935 ** Values for ArCommand.eCmd.
6937 #define AR_CMD_CREATE 1
6938 #define AR_CMD_UPDATE 2
6939 #define AR_CMD_INSERT 3
6940 #define AR_CMD_EXTRACT 4
6941 #define AR_CMD_LIST 5
6942 #define AR_CMD_HELP 6
6943 #define AR_CMD_REMOVE 7
6946 ** Other (non-command) switches.
6948 #define AR_SWITCH_VERBOSE 8
6949 #define AR_SWITCH_FILE 9
6950 #define AR_SWITCH_DIRECTORY 10
6951 #define AR_SWITCH_APPEND 11
6952 #define AR_SWITCH_DRYRUN 12
6953 #define AR_SWITCH_GLOB 13
6955 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6956 switch( eSwitch ){
6957 case AR_CMD_CREATE:
6958 case AR_CMD_EXTRACT:
6959 case AR_CMD_LIST:
6960 case AR_CMD_REMOVE:
6961 case AR_CMD_UPDATE:
6962 case AR_CMD_INSERT:
6963 case AR_CMD_HELP:
6964 if( pAr->eCmd ){
6965 return arErrorMsg(pAr, "multiple command options");
6967 pAr->eCmd = eSwitch;
6968 break;
6970 case AR_SWITCH_DRYRUN:
6971 pAr->bDryRun = 1;
6972 break;
6973 case AR_SWITCH_GLOB:
6974 pAr->bGlob = 1;
6975 break;
6976 case AR_SWITCH_VERBOSE:
6977 pAr->bVerbose = 1;
6978 break;
6979 case AR_SWITCH_APPEND:
6980 pAr->bAppend = 1;
6981 deliberate_fall_through;
6982 case AR_SWITCH_FILE:
6983 pAr->zFile = zArg;
6984 break;
6985 case AR_SWITCH_DIRECTORY:
6986 pAr->zDir = zArg;
6987 break;
6990 return SQLITE_OK;
6994 ** Parse the command line for an ".ar" command. The results are written into
6995 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6996 ** successfully, otherwise an error message is written to stderr and
6997 ** SQLITE_ERROR returned.
6999 static int arParseCommand(
7000 char **azArg, /* Array of arguments passed to dot command */
7001 int nArg, /* Number of entries in azArg[] */
7002 ArCommand *pAr /* Populate this object */
7004 struct ArSwitch {
7005 const char *zLong;
7006 char cShort;
7007 u8 eSwitch;
7008 u8 bArg;
7009 } aSwitch[] = {
7010 { "create", 'c', AR_CMD_CREATE, 0 },
7011 { "extract", 'x', AR_CMD_EXTRACT, 0 },
7012 { "insert", 'i', AR_CMD_INSERT, 0 },
7013 { "list", 't', AR_CMD_LIST, 0 },
7014 { "remove", 'r', AR_CMD_REMOVE, 0 },
7015 { "update", 'u', AR_CMD_UPDATE, 0 },
7016 { "help", 'h', AR_CMD_HELP, 0 },
7017 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
7018 { "file", 'f', AR_SWITCH_FILE, 1 },
7019 { "append", 'a', AR_SWITCH_APPEND, 1 },
7020 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
7021 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
7022 { "glob", 'g', AR_SWITCH_GLOB, 0 },
7024 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
7025 struct ArSwitch *pEnd = &aSwitch[nSwitch];
7027 if( nArg<=1 ){
7028 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
7029 return arUsage(stderr);
7030 }else{
7031 char *z = azArg[1];
7032 if( z[0]!='-' ){
7033 /* Traditional style [tar] invocation */
7034 int i;
7035 int iArg = 2;
7036 for(i=0; z[i]; i++){
7037 const char *zArg = 0;
7038 struct ArSwitch *pOpt;
7039 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7040 if( z[i]==pOpt->cShort ) break;
7042 if( pOpt==pEnd ){
7043 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
7045 if( pOpt->bArg ){
7046 if( iArg>=nArg ){
7047 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
7049 zArg = azArg[iArg++];
7051 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7053 pAr->nArg = nArg-iArg;
7054 if( pAr->nArg>0 ){
7055 pAr->azArg = &azArg[iArg];
7057 }else{
7058 /* Non-traditional invocation */
7059 int iArg;
7060 for(iArg=1; iArg<nArg; iArg++){
7061 int n;
7062 z = azArg[iArg];
7063 if( z[0]!='-' ){
7064 /* All remaining command line words are command arguments. */
7065 pAr->azArg = &azArg[iArg];
7066 pAr->nArg = nArg-iArg;
7067 break;
7069 n = strlen30(z);
7071 if( z[1]!='-' ){
7072 int i;
7073 /* One or more short options */
7074 for(i=1; i<n; i++){
7075 const char *zArg = 0;
7076 struct ArSwitch *pOpt;
7077 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7078 if( z[i]==pOpt->cShort ) break;
7080 if( pOpt==pEnd ){
7081 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
7083 if( pOpt->bArg ){
7084 if( i<(n-1) ){
7085 zArg = &z[i+1];
7086 i = n;
7087 }else{
7088 if( iArg>=(nArg-1) ){
7089 return arErrorMsg(pAr, "option requires an argument: %c",
7090 z[i]);
7092 zArg = azArg[++iArg];
7095 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
7097 }else if( z[2]=='\0' ){
7098 /* A -- option, indicating that all remaining command line words
7099 ** are command arguments. */
7100 pAr->azArg = &azArg[iArg+1];
7101 pAr->nArg = nArg-iArg-1;
7102 break;
7103 }else{
7104 /* A long option */
7105 const char *zArg = 0; /* Argument for option, if any */
7106 struct ArSwitch *pMatch = 0; /* Matching option */
7107 struct ArSwitch *pOpt; /* Iterator */
7108 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
7109 const char *zLong = pOpt->zLong;
7110 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
7111 if( pMatch ){
7112 return arErrorMsg(pAr, "ambiguous option: %s",z);
7113 }else{
7114 pMatch = pOpt;
7119 if( pMatch==0 ){
7120 return arErrorMsg(pAr, "unrecognized option: %s", z);
7122 if( pMatch->bArg ){
7123 if( iArg>=(nArg-1) ){
7124 return arErrorMsg(pAr, "option requires an argument: %s", z);
7126 zArg = azArg[++iArg];
7128 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
7133 if( pAr->eCmd==0 ){
7134 utf8_printf(stderr, "Required argument missing. Usage:\n");
7135 return arUsage(stderr);
7137 return SQLITE_OK;
7141 ** This function assumes that all arguments within the ArCommand.azArg[]
7142 ** array refer to archive members, as for the --extract, --list or --remove
7143 ** commands. It checks that each of them are "present". If any specified
7144 ** file is not present in the archive, an error is printed to stderr and an
7145 ** error code returned. Otherwise, if all specified arguments are present
7146 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7147 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7148 ** when pAr->bGlob is true.
7150 ** This function strips any trailing '/' characters from each argument.
7151 ** This is consistent with the way the [tar] command seems to work on
7152 ** Linux.
7154 static int arCheckEntries(ArCommand *pAr){
7155 int rc = SQLITE_OK;
7156 if( pAr->nArg ){
7157 int i, j;
7158 sqlite3_stmt *pTest = 0;
7159 const char *zSel = (pAr->bGlob)
7160 ? "SELECT name FROM %s WHERE glob($name,name)"
7161 : "SELECT name FROM %s WHERE name=$name";
7163 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
7164 j = sqlite3_bind_parameter_index(pTest, "$name");
7165 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7166 char *z = pAr->azArg[i];
7167 int n = strlen30(z);
7168 int bOk = 0;
7169 while( n>0 && z[n-1]=='/' ) n--;
7170 z[n] = '\0';
7171 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
7172 if( SQLITE_ROW==sqlite3_step(pTest) ){
7173 bOk = 1;
7175 shellReset(&rc, pTest);
7176 if( rc==SQLITE_OK && bOk==0 ){
7177 utf8_printf(stderr, "not found in archive: %s\n", z);
7178 rc = SQLITE_ERROR;
7181 shellFinalize(&rc, pTest);
7183 return rc;
7187 ** Format a WHERE clause that can be used against the "sqlar" table to
7188 ** identify all archive members that match the command arguments held
7189 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7190 ** The caller is responsible for eventually calling sqlite3_free() on
7191 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7192 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7194 static void arWhereClause(
7195 int *pRc,
7196 ArCommand *pAr,
7197 char **pzWhere /* OUT: New WHERE clause */
7199 char *zWhere = 0;
7200 const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
7201 if( *pRc==SQLITE_OK ){
7202 if( pAr->nArg==0 ){
7203 zWhere = sqlite3_mprintf("1");
7204 }else{
7205 int i;
7206 const char *zSep = "";
7207 for(i=0; i<pAr->nArg; i++){
7208 const char *z = pAr->azArg[i];
7209 zWhere = sqlite3_mprintf(
7210 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7211 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
7213 if( zWhere==0 ){
7214 *pRc = SQLITE_NOMEM;
7215 break;
7217 zSep = " OR ";
7221 *pzWhere = zWhere;
7225 ** Implementation of .ar "lisT" command.
7227 static int arListCommand(ArCommand *pAr){
7228 const char *zSql = "SELECT %s FROM %s WHERE %s";
7229 const char *azCols[] = {
7230 "name",
7231 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7234 char *zWhere = 0;
7235 sqlite3_stmt *pSql = 0;
7236 int rc;
7238 rc = arCheckEntries(pAr);
7239 arWhereClause(&rc, pAr, &zWhere);
7241 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
7242 pAr->zSrcTable, zWhere);
7243 if( pAr->bDryRun ){
7244 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
7245 }else{
7246 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7247 if( pAr->bVerbose ){
7248 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
7249 sqlite3_column_text(pSql, 0),
7250 sqlite3_column_int(pSql, 1),
7251 sqlite3_column_text(pSql, 2),
7252 sqlite3_column_text(pSql, 3)
7254 }else{
7255 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
7259 shellFinalize(&rc, pSql);
7260 sqlite3_free(zWhere);
7261 return rc;
7266 ** Implementation of .ar "Remove" command.
7268 static int arRemoveCommand(ArCommand *pAr){
7269 int rc = 0;
7270 char *zSql = 0;
7271 char *zWhere = 0;
7273 if( pAr->nArg ){
7274 /* Verify that args actually exist within the archive before proceeding.
7275 ** And formulate a WHERE clause to match them. */
7276 rc = arCheckEntries(pAr);
7277 arWhereClause(&rc, pAr, &zWhere);
7279 if( rc==SQLITE_OK ){
7280 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7281 pAr->zSrcTable, zWhere);
7282 if( pAr->bDryRun ){
7283 utf8_printf(pAr->p->out, "%s\n", zSql);
7284 }else{
7285 char *zErr = 0;
7286 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
7287 if( rc==SQLITE_OK ){
7288 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7289 if( rc!=SQLITE_OK ){
7290 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7291 }else{
7292 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
7295 if( zErr ){
7296 utf8_printf(stdout, "ERROR: %s\n", zErr);
7297 sqlite3_free(zErr);
7301 sqlite3_free(zWhere);
7302 sqlite3_free(zSql);
7303 return rc;
7307 ** Implementation of .ar "eXtract" command.
7309 static int arExtractCommand(ArCommand *pAr){
7310 const char *zSql1 =
7311 "SELECT "
7312 " ($dir || name),"
7313 " writefile(($dir || name), %s, mode, mtime) "
7314 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7315 " AND name NOT GLOB '*..[/\\]*'";
7317 const char *azExtraArg[] = {
7318 "sqlar_uncompress(data, sz)",
7319 "data"
7322 sqlite3_stmt *pSql = 0;
7323 int rc = SQLITE_OK;
7324 char *zDir = 0;
7325 char *zWhere = 0;
7326 int i, j;
7328 /* If arguments are specified, check that they actually exist within
7329 ** the archive before proceeding. And formulate a WHERE clause to
7330 ** match them. */
7331 rc = arCheckEntries(pAr);
7332 arWhereClause(&rc, pAr, &zWhere);
7334 if( rc==SQLITE_OK ){
7335 if( pAr->zDir ){
7336 zDir = sqlite3_mprintf("%s/", pAr->zDir);
7337 }else{
7338 zDir = sqlite3_mprintf("");
7340 if( zDir==0 ) rc = SQLITE_NOMEM;
7343 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
7344 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
7347 if( rc==SQLITE_OK ){
7348 j = sqlite3_bind_parameter_index(pSql, "$dir");
7349 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
7351 /* Run the SELECT statement twice. The first time, writefile() is called
7352 ** for all archive members that should be extracted. The second time,
7353 ** only for the directories. This is because the timestamps for
7354 ** extracted directories must be reset after they are populated (as
7355 ** populating them changes the timestamp). */
7356 for(i=0; i<2; i++){
7357 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
7358 sqlite3_bind_int(pSql, j, i);
7359 if( pAr->bDryRun ){
7360 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
7361 }else{
7362 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7363 if( i==0 && pAr->bVerbose ){
7364 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
7368 shellReset(&rc, pSql);
7370 shellFinalize(&rc, pSql);
7373 sqlite3_free(zDir);
7374 sqlite3_free(zWhere);
7375 return rc;
7379 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7381 static int arExecSql(ArCommand *pAr, const char *zSql){
7382 int rc;
7383 if( pAr->bDryRun ){
7384 utf8_printf(pAr->p->out, "%s\n", zSql);
7385 rc = SQLITE_OK;
7386 }else{
7387 char *zErr = 0;
7388 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7389 if( zErr ){
7390 utf8_printf(stdout, "ERROR: %s\n", zErr);
7391 sqlite3_free(zErr);
7394 return rc;
7399 ** Implementation of .ar "create", "insert", and "update" commands.
7401 ** create -> Create a new SQL archive
7402 ** insert -> Insert or reinsert all files listed
7403 ** update -> Insert files that have changed or that were not
7404 ** previously in the archive
7406 ** Create the "sqlar" table in the database if it does not already exist.
7407 ** Then add each file in the azFile[] array to the archive. Directories
7408 ** are added recursively. If argument bVerbose is non-zero, a message is
7409 ** printed on stdout for each file archived.
7411 ** The create command is the same as update, except that it drops
7412 ** any existing "sqlar" table before beginning. The "insert" command
7413 ** always overwrites every file named on the command-line, where as
7414 ** "update" only overwrites if the size or mtime or mode has changed.
7416 static int arCreateOrUpdateCommand(
7417 ArCommand *pAr, /* Command arguments and options */
7418 int bUpdate, /* true for a --create. */
7419 int bOnlyIfChanged /* Only update if file has changed */
7421 const char *zCreate =
7422 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7423 " name TEXT PRIMARY KEY, -- name of the file\n"
7424 " mode INT, -- access permissions\n"
7425 " mtime INT, -- last modification time\n"
7426 " sz INT, -- original file size\n"
7427 " data BLOB -- compressed content\n"
7428 ")";
7429 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7430 const char *zInsertFmt[2] = {
7431 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7432 " SELECT\n"
7433 " %s,\n"
7434 " mode,\n"
7435 " mtime,\n"
7436 " CASE substr(lsmode(mode),1,1)\n"
7437 " WHEN '-' THEN length(data)\n"
7438 " WHEN 'd' THEN 0\n"
7439 " ELSE -1 END,\n"
7440 " sqlar_compress(data)\n"
7441 " FROM fsdir(%Q,%Q) AS disk\n"
7442 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7444 "REPLACE INTO %s(name,mode,mtime,data)\n"
7445 " SELECT\n"
7446 " %s,\n"
7447 " mode,\n"
7448 " mtime,\n"
7449 " data\n"
7450 " FROM fsdir(%Q,%Q) AS disk\n"
7451 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7453 int i; /* For iterating through azFile[] */
7454 int rc; /* Return code */
7455 const char *zTab = 0; /* SQL table into which to insert */
7456 char *zSql;
7457 char zTemp[50];
7458 char *zExists = 0;
7460 arExecSql(pAr, "PRAGMA page_size=512");
7461 rc = arExecSql(pAr, "SAVEPOINT ar;");
7462 if( rc!=SQLITE_OK ) return rc;
7463 zTemp[0] = 0;
7464 if( pAr->bZip ){
7465 /* Initialize the zipfile virtual table, if necessary */
7466 if( pAr->zFile ){
7467 sqlite3_uint64 r;
7468 sqlite3_randomness(sizeof(r),&r);
7469 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7470 zTab = zTemp;
7471 zSql = sqlite3_mprintf(
7472 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7473 zTab, pAr->zFile
7475 rc = arExecSql(pAr, zSql);
7476 sqlite3_free(zSql);
7477 }else{
7478 zTab = "zip";
7480 }else{
7481 /* Initialize the table for an SQLAR */
7482 zTab = "sqlar";
7483 if( bUpdate==0 ){
7484 rc = arExecSql(pAr, zDrop);
7485 if( rc!=SQLITE_OK ) goto end_ar_transaction;
7487 rc = arExecSql(pAr, zCreate);
7489 if( bOnlyIfChanged ){
7490 zExists = sqlite3_mprintf(
7491 " AND NOT EXISTS("
7492 "SELECT 1 FROM %s AS mem"
7493 " WHERE mem.name=disk.name"
7494 " AND mem.mtime=disk.mtime"
7495 " AND mem.mode=disk.mode)", zTab);
7496 }else{
7497 zExists = sqlite3_mprintf("");
7499 if( zExists==0 ) rc = SQLITE_NOMEM;
7500 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7501 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7502 pAr->bVerbose ? "shell_putsnl(name)" : "name",
7503 pAr->azArg[i], pAr->zDir, zExists);
7504 rc = arExecSql(pAr, zSql2);
7505 sqlite3_free(zSql2);
7507 end_ar_transaction:
7508 if( rc!=SQLITE_OK ){
7509 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7510 }else{
7511 rc = arExecSql(pAr, "RELEASE ar;");
7512 if( pAr->bZip && pAr->zFile ){
7513 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7514 arExecSql(pAr, zSql);
7515 sqlite3_free(zSql);
7518 sqlite3_free(zExists);
7519 return rc;
7523 ** Implementation of ".ar" dot command.
7525 static int arDotCommand(
7526 ShellState *pState, /* Current shell tool state */
7527 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
7528 char **azArg, /* Array of arguments passed to dot command */
7529 int nArg /* Number of entries in azArg[] */
7531 ArCommand cmd;
7532 int rc;
7533 memset(&cmd, 0, sizeof(cmd));
7534 cmd.fromCmdLine = fromCmdLine;
7535 rc = arParseCommand(azArg, nArg, &cmd);
7536 if( rc==SQLITE_OK ){
7537 int eDbType = SHELL_OPEN_UNSPEC;
7538 cmd.p = pState;
7539 cmd.db = pState->db;
7540 if( cmd.zFile ){
7541 eDbType = deduceDatabaseType(cmd.zFile, 1);
7542 }else{
7543 eDbType = pState->openMode;
7545 if( eDbType==SHELL_OPEN_ZIPFILE ){
7546 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7547 if( cmd.zFile==0 ){
7548 cmd.zSrcTable = sqlite3_mprintf("zip");
7549 }else{
7550 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7553 cmd.bZip = 1;
7554 }else if( cmd.zFile ){
7555 int flags;
7556 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7557 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7558 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7559 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7560 }else{
7561 flags = SQLITE_OPEN_READONLY;
7563 cmd.db = 0;
7564 if( cmd.bDryRun ){
7565 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7566 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7568 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7569 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7570 if( rc!=SQLITE_OK ){
7571 utf8_printf(stderr, "cannot open file: %s (%s)\n",
7572 cmd.zFile, sqlite3_errmsg(cmd.db)
7574 goto end_ar_command;
7576 sqlite3_fileio_init(cmd.db, 0, 0);
7577 sqlite3_sqlar_init(cmd.db, 0, 0);
7578 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7579 shellPutsFunc, 0, 0);
7582 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7583 if( cmd.eCmd!=AR_CMD_CREATE
7584 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7586 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7587 rc = SQLITE_ERROR;
7588 goto end_ar_command;
7590 cmd.zSrcTable = sqlite3_mprintf("sqlar");
7593 switch( cmd.eCmd ){
7594 case AR_CMD_CREATE:
7595 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7596 break;
7598 case AR_CMD_EXTRACT:
7599 rc = arExtractCommand(&cmd);
7600 break;
7602 case AR_CMD_LIST:
7603 rc = arListCommand(&cmd);
7604 break;
7606 case AR_CMD_HELP:
7607 arUsage(pState->out);
7608 break;
7610 case AR_CMD_INSERT:
7611 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7612 break;
7614 case AR_CMD_REMOVE:
7615 rc = arRemoveCommand(&cmd);
7616 break;
7618 default:
7619 assert( cmd.eCmd==AR_CMD_UPDATE );
7620 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7621 break;
7624 end_ar_command:
7625 if( cmd.db!=pState->db ){
7626 close_db(cmd.db);
7628 sqlite3_free(cmd.zSrcTable);
7630 return rc;
7632 /* End of the ".archive" or ".ar" command logic
7633 *******************************************************************************/
7634 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7636 #if SQLITE_SHELL_HAVE_RECOVER
7639 ** This function is used as a callback by the recover extension. Simply
7640 ** print the supplied SQL statement to stdout.
7642 static int recoverSqlCb(void *pCtx, const char *zSql){
7643 ShellState *pState = (ShellState*)pCtx;
7644 utf8_printf(pState->out, "%s;\n", zSql);
7645 return SQLITE_OK;
7649 ** This function is called to recover data from the database. A script
7650 ** to construct a new database containing all recovered data is output
7651 ** on stream pState->out.
7653 static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7654 int rc = SQLITE_OK;
7655 const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */
7656 const char *zLAF = "lost_and_found";
7657 int bFreelist = 1; /* 0 if --ignore-freelist is specified */
7658 int bRowids = 1; /* 0 if --no-rowids */
7659 sqlite3_recover *p = 0;
7660 int i = 0;
7662 for(i=1; i<nArg; i++){
7663 char *z = azArg[i];
7664 int n;
7665 if( z[0]=='-' && z[1]=='-' ) z++;
7666 n = strlen30(z);
7667 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
7668 bFreelist = 0;
7669 }else
7670 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7671 /* This option determines the name of the ATTACH-ed database used
7672 ** internally by the recovery extension. The default is "" which
7673 ** means to use a temporary database that is automatically deleted
7674 ** when closed. This option is undocumented and might disappear at
7675 ** any moment. */
7676 i++;
7677 zRecoveryDb = azArg[i];
7678 }else
7679 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7680 i++;
7681 zLAF = azArg[i];
7682 }else
7683 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7684 bRowids = 0;
7686 else{
7687 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7688 showHelp(pState->out, azArg[0]);
7689 return 1;
7693 p = sqlite3_recover_init_sql(
7694 pState->db, "main", recoverSqlCb, (void*)pState
7697 sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */
7698 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7699 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7700 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7702 sqlite3_recover_run(p);
7703 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7704 const char *zErr = sqlite3_recover_errmsg(p);
7705 int errCode = sqlite3_recover_errcode(p);
7706 raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
7708 rc = sqlite3_recover_finish(p);
7709 return rc;
7711 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7715 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7716 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7717 * close db and set it to 0, and return the columns spec, to later
7718 * be sqlite3_free()'ed by the caller.
7719 * The return is 0 when either:
7720 * (a) The db was not initialized and zCol==0 (There are no columns.)
7721 * (b) zCol!=0 (Column was added, db initialized as needed.)
7722 * The 3rd argument, pRenamed, references an out parameter. If the
7723 * pointer is non-zero, its referent will be set to a summary of renames
7724 * done if renaming was necessary, or set to 0 if none was done. The out
7725 * string (if any) must be sqlite3_free()'ed by the caller.
7727 #ifdef SHELL_DEBUG
7728 #define rc_err_oom_die(rc) \
7729 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7730 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7731 fprintf(stderr,"E:%d\n",rc), assert(0)
7732 #else
7733 static void rc_err_oom_die(int rc){
7734 if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7735 assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7737 #endif
7739 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7740 static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7741 #else /* Otherwise, memory is faster/better for the transient DB. */
7742 static const char *zCOL_DB = ":memory:";
7743 #endif
7745 /* Define character (as C string) to separate generated column ordinal
7746 * from protected part of incoming column names. This defaults to "_"
7747 * so that incoming column identifiers that did not need not be quoted
7748 * remain usable without being quoted. It must be one character.
7750 #ifndef SHELL_AUTOCOLUMN_SEP
7751 # define AUTOCOLUMN_SEP "_"
7752 #else
7753 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7754 #endif
7756 static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7757 /* Queries and D{D,M}L used here */
7758 static const char * const zTabMake = "\
7759 CREATE TABLE ColNames(\
7760 cpos INTEGER PRIMARY KEY,\
7761 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7762 CREATE VIEW RepeatedNames AS \
7763 SELECT DISTINCT t.name FROM ColNames t \
7764 WHERE t.name COLLATE NOCASE IN (\
7765 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7768 static const char * const zTabFill = "\
7769 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7770 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7772 static const char * const zHasDupes = "\
7773 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7774 <count(name) FROM ColNames\
7776 #ifdef SHELL_COLUMN_RENAME_CLEAN
7777 static const char * const zDedoctor = "\
7778 UPDATE ColNames SET chop=iif(\
7779 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7780 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7781 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7785 #endif
7786 static const char * const zSetReps = "\
7787 UPDATE ColNames AS t SET reps=\
7788 (SELECT count(*) FROM ColNames d \
7789 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7790 COLLATE NOCASE\
7793 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7794 static const char * const zColDigits = "\
7795 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7797 #else
7798 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7799 static const char * const zColDigits = "\
7800 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7801 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7802 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7804 #endif
7805 static const char * const zRenameRank =
7806 #ifdef SHELL_COLUMN_RENAME_CLEAN
7807 "UPDATE ColNames AS t SET suff="
7808 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7809 #else /* ...RENAME_MINIMAL_ONE_PASS */
7810 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7811 " SELECT 0 AS nlz"
7812 " UNION"
7813 " SELECT nlz+1 AS nlz FROM Lzn"
7814 " WHERE EXISTS("
7815 " SELECT 1"
7816 " FROM ColNames t, ColNames o"
7817 " WHERE"
7818 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7819 " printf('%s"AUTOCOLUMN_SEP"%s',"
7820 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7821 " t.name"
7822 " )"
7823 " ="
7824 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7825 " printf('%s"AUTOCOLUMN_SEP"%s',"
7826 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7827 " o.name"
7828 " )"
7829 " COLLATE NOCASE"
7830 " AND o.cpos<>t.cpos"
7831 " GROUP BY t.cpos"
7832 " )"
7833 ") UPDATE Colnames AS t SET"
7834 " chop = 0," /* No chopping, never touch incoming names. */
7835 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7836 " printf('"AUTOCOLUMN_SEP"%s', substring("
7837 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7838 " ''"
7839 " )"
7840 #endif
7842 static const char * const zCollectVar = "\
7843 SELECT\
7844 '('||x'0a'\
7845 || group_concat(\
7846 cname||' TEXT',\
7847 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7848 ||')' AS ColsSpec \
7849 FROM (\
7850 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7851 FROM ColNames ORDER BY cpos\
7853 static const char * const zRenamesDone =
7854 "SELECT group_concat("
7855 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7856 " ','||x'0a')"
7857 "FROM ColNames WHERE suff<>'' OR chop!=0"
7859 int rc;
7860 sqlite3_stmt *pStmt = 0;
7861 assert(pDb!=0);
7862 if( zColNew ){
7863 /* Add initial or additional column. Init db if necessary. */
7864 if( *pDb==0 ){
7865 if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7866 #ifdef SHELL_COLFIX_DB
7867 if(*zCOL_DB!=':')
7868 sqlite3_exec(*pDb,"drop table if exists ColNames;"
7869 "drop view if exists RepeatedNames;",0,0,0);
7870 #endif
7871 rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7872 rc_err_oom_die(rc);
7874 assert(*pDb!=0);
7875 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7876 rc_err_oom_die(rc);
7877 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7878 rc_err_oom_die(rc);
7879 rc = sqlite3_step(pStmt);
7880 rc_err_oom_die(rc);
7881 sqlite3_finalize(pStmt);
7882 return 0;
7883 }else if( *pDb==0 ){
7884 return 0;
7885 }else{
7886 /* Formulate the columns spec, close the DB, zero *pDb. */
7887 char *zColsSpec = 0;
7888 int hasDupes = db_int(*pDb, zHasDupes);
7889 int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7890 if( hasDupes ){
7891 #ifdef SHELL_COLUMN_RENAME_CLEAN
7892 rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7893 rc_err_oom_die(rc);
7894 #endif
7895 rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7896 rc_err_oom_die(rc);
7897 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7898 rc_err_oom_die(rc);
7899 sqlite3_bind_int(pStmt, 1, nDigits);
7900 rc = sqlite3_step(pStmt);
7901 sqlite3_finalize(pStmt);
7902 if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
7904 assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7905 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7906 rc_err_oom_die(rc);
7907 rc = sqlite3_step(pStmt);
7908 if( rc==SQLITE_ROW ){
7909 zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7910 }else{
7911 zColsSpec = 0;
7913 if( pzRenamed!=0 ){
7914 if( !hasDupes ) *pzRenamed = 0;
7915 else{
7916 sqlite3_finalize(pStmt);
7917 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7918 && SQLITE_ROW==sqlite3_step(pStmt) ){
7919 *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7920 }else
7921 *pzRenamed = 0;
7924 sqlite3_finalize(pStmt);
7925 sqlite3_close(*pDb);
7926 *pDb = 0;
7927 return zColsSpec;
7932 ** If an input line begins with "." then invoke this routine to
7933 ** process that line.
7935 ** Return 1 on error, 2 to exit, and 0 otherwise.
7937 static int do_meta_command(char *zLine, ShellState *p){
7938 int h = 1;
7939 int nArg = 0;
7940 int n, c;
7941 int rc = 0;
7942 char *azArg[52];
7944 #ifndef SQLITE_OMIT_VIRTUALTABLE
7945 if( p->expert.pExpert ){
7946 expertFinish(p, 1, 0);
7948 #endif
7950 /* Parse the input line into tokens.
7952 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7953 while( IsSpace(zLine[h]) ){ h++; }
7954 if( zLine[h]==0 ) break;
7955 if( zLine[h]=='\'' || zLine[h]=='"' ){
7956 int delim = zLine[h++];
7957 azArg[nArg++] = &zLine[h];
7958 while( zLine[h] && zLine[h]!=delim ){
7959 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7960 h++;
7962 if( zLine[h]==delim ){
7963 zLine[h++] = 0;
7965 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7966 }else{
7967 azArg[nArg++] = &zLine[h];
7968 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7969 if( zLine[h] ) zLine[h++] = 0;
7970 resolve_backslashes(azArg[nArg-1]);
7973 azArg[nArg] = 0;
7975 /* Process the input line.
7977 if( nArg==0 ) return 0; /* no tokens, no error */
7978 n = strlen30(azArg[0]);
7979 c = azArg[0][0];
7980 clearTempFile(p);
7982 #ifndef SQLITE_OMIT_AUTHORIZATION
7983 if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
7984 if( nArg!=2 ){
7985 raw_printf(stderr, "Usage: .auth ON|OFF\n");
7986 rc = 1;
7987 goto meta_command_exit;
7989 open_db(p, 0);
7990 if( booleanValue(azArg[1]) ){
7991 sqlite3_set_authorizer(p->db, shellAuth, p);
7992 }else if( p->bSafeModePersist ){
7993 sqlite3_set_authorizer(p->db, safeModeAuth, p);
7994 }else{
7995 sqlite3_set_authorizer(p->db, 0, 0);
7997 }else
7998 #endif
8000 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8001 && !defined(SQLITE_SHELL_FIDDLE)
8002 if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
8003 open_db(p, 0);
8004 failIfSafeMode(p, "cannot run .archive in safe mode");
8005 rc = arDotCommand(p, 0, azArg, nArg);
8006 }else
8007 #endif
8009 #ifndef SQLITE_SHELL_FIDDLE
8010 if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
8011 || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
8013 const char *zDestFile = 0;
8014 const char *zDb = 0;
8015 sqlite3 *pDest;
8016 sqlite3_backup *pBackup;
8017 int j;
8018 int bAsync = 0;
8019 const char *zVfs = 0;
8020 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8021 for(j=1; j<nArg; j++){
8022 const char *z = azArg[j];
8023 if( z[0]=='-' ){
8024 if( z[1]=='-' ) z++;
8025 if( cli_strcmp(z, "-append")==0 ){
8026 zVfs = "apndvfs";
8027 }else
8028 if( cli_strcmp(z, "-async")==0 ){
8029 bAsync = 1;
8030 }else
8032 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8033 return 1;
8035 }else if( zDestFile==0 ){
8036 zDestFile = azArg[j];
8037 }else if( zDb==0 ){
8038 zDb = zDestFile;
8039 zDestFile = azArg[j];
8040 }else{
8041 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8042 return 1;
8045 if( zDestFile==0 ){
8046 raw_printf(stderr, "missing FILENAME argument on .backup\n");
8047 return 1;
8049 if( zDb==0 ) zDb = "main";
8050 rc = sqlite3_open_v2(zDestFile, &pDest,
8051 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8052 if( rc!=SQLITE_OK ){
8053 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8054 close_db(pDest);
8055 return 1;
8057 if( bAsync ){
8058 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8059 0, 0, 0);
8061 open_db(p, 0);
8062 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8063 if( pBackup==0 ){
8064 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8065 close_db(pDest);
8066 return 1;
8068 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8069 sqlite3_backup_finish(pBackup);
8070 if( rc==SQLITE_DONE ){
8071 rc = 0;
8072 }else{
8073 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8074 rc = 1;
8076 close_db(pDest);
8077 }else
8078 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8080 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
8081 if( nArg==2 ){
8082 bail_on_error = booleanValue(azArg[1]);
8083 }else{
8084 raw_printf(stderr, "Usage: .bail on|off\n");
8085 rc = 1;
8087 }else
8089 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
8090 if( nArg==2 ){
8091 if( booleanValue(azArg[1]) ){
8092 setBinaryMode(p->out, 1);
8093 }else{
8094 setTextMode(p->out, 1);
8096 }else{
8097 raw_printf(stderr, "Usage: .binary on|off\n");
8098 rc = 1;
8100 }else
8102 /* The undocumented ".breakpoint" command causes a call to the no-op
8103 ** routine named test_breakpoint().
8105 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
8106 test_breakpoint();
8107 }else
8109 #ifndef SQLITE_SHELL_FIDDLE
8110 if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
8111 failIfSafeMode(p, "cannot run .cd in safe mode");
8112 if( nArg==2 ){
8113 #if defined(_WIN32) || defined(WIN32)
8114 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8115 rc = !SetCurrentDirectoryW(z);
8116 sqlite3_free(z);
8117 #else
8118 rc = chdir(azArg[1]);
8119 #endif
8120 if( rc ){
8121 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8122 rc = 1;
8124 }else{
8125 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8126 rc = 1;
8128 }else
8129 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8131 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
8132 if( nArg==2 ){
8133 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8134 }else{
8135 raw_printf(stderr, "Usage: .changes on|off\n");
8136 rc = 1;
8138 }else
8140 #ifndef SQLITE_SHELL_FIDDLE
8141 /* Cancel output redirection, if it is currently set (by .testcase)
8142 ** Then read the content of the testcase-out.txt file and compare against
8143 ** azArg[1]. If there are differences, report an error and exit.
8145 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
8146 char *zRes = 0;
8147 output_reset(p);
8148 if( nArg!=2 ){
8149 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8150 rc = 2;
8151 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8152 rc = 2;
8153 }else if( testcase_glob(azArg[1],zRes)==0 ){
8154 utf8_printf(stderr,
8155 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8156 p->zTestcase, azArg[1], zRes);
8157 rc = 1;
8158 }else{
8159 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8160 p->nCheck++;
8162 sqlite3_free(zRes);
8163 }else
8164 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8166 #ifndef SQLITE_SHELL_FIDDLE
8167 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
8168 failIfSafeMode(p, "cannot run .clone in safe mode");
8169 if( nArg==2 ){
8170 tryToClone(p, azArg[1]);
8171 }else{
8172 raw_printf(stderr, "Usage: .clone FILENAME\n");
8173 rc = 1;
8175 }else
8176 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8178 if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
8179 if( nArg==1 ){
8180 /* List available connections */
8181 int i;
8182 for(i=0; i<ArraySize(p->aAuxDb); i++){
8183 const char *zFile = p->aAuxDb[i].zDbFilename;
8184 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8185 zFile = "(not open)";
8186 }else if( zFile==0 ){
8187 zFile = "(memory)";
8188 }else if( zFile[0]==0 ){
8189 zFile = "(temporary-file)";
8191 if( p->pAuxDb == &p->aAuxDb[i] ){
8192 utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8193 }else if( p->aAuxDb[i].db!=0 ){
8194 utf8_printf(stdout, " %d: %s\n", i, zFile);
8197 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8198 int i = azArg[1][0] - '0';
8199 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8200 p->pAuxDb->db = p->db;
8201 p->pAuxDb = &p->aAuxDb[i];
8202 globalDb = p->db = p->pAuxDb->db;
8203 p->pAuxDb->db = 0;
8205 }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
8206 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8207 int i = azArg[2][0] - '0';
8208 if( i<0 || i>=ArraySize(p->aAuxDb) ){
8209 /* No-op */
8210 }else if( p->pAuxDb == &p->aAuxDb[i] ){
8211 raw_printf(stderr, "cannot close the active database connection\n");
8212 rc = 1;
8213 }else if( p->aAuxDb[i].db ){
8214 session_close_all(p, i);
8215 close_db(p->aAuxDb[i].db);
8216 p->aAuxDb[i].db = 0;
8218 }else{
8219 raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8220 rc = 1;
8222 }else
8224 if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
8225 char **azName = 0;
8226 int nName = 0;
8227 sqlite3_stmt *pStmt;
8228 int i;
8229 open_db(p, 0);
8230 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8231 if( rc ){
8232 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8233 rc = 1;
8234 }else{
8235 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8236 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8237 const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8238 if( zSchema==0 || zFile==0 ) continue;
8239 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8240 shell_check_oom(azName);
8241 azName[nName*2] = strdup(zSchema);
8242 azName[nName*2+1] = strdup(zFile);
8243 nName++;
8246 sqlite3_finalize(pStmt);
8247 for(i=0; i<nName; i++){
8248 int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8249 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8250 const char *z = azName[i*2+1];
8251 utf8_printf(p->out, "%s: %s %s%s\n",
8252 azName[i*2],
8253 z && z[0] ? z : "\"\"",
8254 bRdonly ? "r/o" : "r/w",
8255 eTxn==SQLITE_TXN_NONE ? "" :
8256 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8257 free(azName[i*2]);
8258 free(azName[i*2+1]);
8260 sqlite3_free(azName);
8261 }else
8263 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
8264 static const struct DbConfigChoices {
8265 const char *zName;
8266 int op;
8267 } aDbConfig[] = {
8268 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
8269 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
8270 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
8271 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
8272 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
8273 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
8274 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
8275 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8276 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
8277 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT },
8278 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8279 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
8280 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
8281 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER },
8282 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS },
8283 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
8284 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA },
8285 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
8287 int ii, v;
8288 open_db(p, 0);
8289 for(ii=0; ii<ArraySize(aDbConfig); ii++){
8290 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8291 if( nArg>=3 ){
8292 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8294 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8295 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8296 if( nArg>1 ) break;
8298 if( nArg>1 && ii==ArraySize(aDbConfig) ){
8299 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8300 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8302 }else
8304 #if SQLITE_SHELL_HAVE_RECOVER
8305 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
8306 rc = shell_dbinfo_command(p, nArg, azArg);
8307 }else
8309 if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
8310 open_db(p, 0);
8311 rc = recoverDatabaseCmd(p, nArg, azArg);
8312 }else
8313 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8315 if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
8316 char *zLike = 0;
8317 char *zSql;
8318 int i;
8319 int savedShowHeader = p->showHeader;
8320 int savedShellFlags = p->shellFlgs;
8321 ShellClearFlag(p,
8322 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8323 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8324 for(i=1; i<nArg; i++){
8325 if( azArg[i][0]=='-' ){
8326 const char *z = azArg[i]+1;
8327 if( z[0]=='-' ) z++;
8328 if( cli_strcmp(z,"preserve-rowids")==0 ){
8329 #ifdef SQLITE_OMIT_VIRTUALTABLE
8330 raw_printf(stderr, "The --preserve-rowids option is not compatible"
8331 " with SQLITE_OMIT_VIRTUALTABLE\n");
8332 rc = 1;
8333 sqlite3_free(zLike);
8334 goto meta_command_exit;
8335 #else
8336 ShellSetFlag(p, SHFLG_PreserveRowid);
8337 #endif
8338 }else
8339 if( cli_strcmp(z,"newlines")==0 ){
8340 ShellSetFlag(p, SHFLG_Newlines);
8341 }else
8342 if( cli_strcmp(z,"data-only")==0 ){
8343 ShellSetFlag(p, SHFLG_DumpDataOnly);
8344 }else
8345 if( cli_strcmp(z,"nosys")==0 ){
8346 ShellSetFlag(p, SHFLG_DumpNoSys);
8347 }else
8349 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8350 rc = 1;
8351 sqlite3_free(zLike);
8352 goto meta_command_exit;
8354 }else{
8355 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8356 ** only dump data for tables for which either the table name matches
8357 ** the LIKE pattern, or the table appears to be a shadow table of
8358 ** a virtual table for which the name matches the LIKE pattern.
8360 char *zExpr = sqlite3_mprintf(
8361 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8362 " SELECT 1 FROM sqlite_schema WHERE "
8363 " name LIKE %Q ESCAPE '\\' AND"
8364 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8365 " substr(o.name, 1, length(name)+1) == (name||'_')"
8366 ")", azArg[i], azArg[i]
8369 if( zLike ){
8370 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8371 }else{
8372 zLike = zExpr;
8377 open_db(p, 0);
8379 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8380 /* When playing back a "dump", the content might appear in an order
8381 ** which causes immediate foreign key constraints to be violated.
8382 ** So disable foreign-key constraint enforcement to prevent problems. */
8383 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8384 raw_printf(p->out, "BEGIN TRANSACTION;\n");
8386 p->writableSchema = 0;
8387 p->showHeader = 0;
8388 /* Set writable_schema=ON since doing so forces SQLite to initialize
8389 ** as much of the schema as it can even if the sqlite_schema table is
8390 ** corrupt. */
8391 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8392 p->nErr = 0;
8393 if( zLike==0 ) zLike = sqlite3_mprintf("true");
8394 zSql = sqlite3_mprintf(
8395 "SELECT name, type, sql FROM sqlite_schema AS o "
8396 "WHERE (%s) AND type=='table'"
8397 " AND sql NOT NULL"
8398 " ORDER BY tbl_name='sqlite_sequence', rowid",
8399 zLike
8401 run_schema_dump_query(p,zSql);
8402 sqlite3_free(zSql);
8403 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8404 zSql = sqlite3_mprintf(
8405 "SELECT sql FROM sqlite_schema AS o "
8406 "WHERE (%s) AND sql NOT NULL"
8407 " AND type IN ('index','trigger','view')",
8408 zLike
8410 run_table_dump_query(p, zSql);
8411 sqlite3_free(zSql);
8413 sqlite3_free(zLike);
8414 if( p->writableSchema ){
8415 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8416 p->writableSchema = 0;
8418 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8419 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8420 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8421 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8423 p->showHeader = savedShowHeader;
8424 p->shellFlgs = savedShellFlags;
8425 }else
8427 if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
8428 if( nArg==2 ){
8429 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8430 }else{
8431 raw_printf(stderr, "Usage: .echo on|off\n");
8432 rc = 1;
8434 }else
8436 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
8437 if( nArg==2 ){
8438 p->autoEQPtest = 0;
8439 if( p->autoEQPtrace ){
8440 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8441 p->autoEQPtrace = 0;
8443 if( cli_strcmp(azArg[1],"full")==0 ){
8444 p->autoEQP = AUTOEQP_full;
8445 }else if( cli_strcmp(azArg[1],"trigger")==0 ){
8446 p->autoEQP = AUTOEQP_trigger;
8447 #ifdef SQLITE_DEBUG
8448 }else if( cli_strcmp(azArg[1],"test")==0 ){
8449 p->autoEQP = AUTOEQP_on;
8450 p->autoEQPtest = 1;
8451 }else if( cli_strcmp(azArg[1],"trace")==0 ){
8452 p->autoEQP = AUTOEQP_full;
8453 p->autoEQPtrace = 1;
8454 open_db(p, 0);
8455 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8456 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8457 #endif
8458 }else{
8459 p->autoEQP = (u8)booleanValue(azArg[1]);
8461 }else{
8462 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8463 rc = 1;
8465 }else
8467 #ifndef SQLITE_SHELL_FIDDLE
8468 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
8469 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8470 rc = 2;
8471 }else
8472 #endif
8474 /* The ".explain" command is automatic now. It is largely pointless. It
8475 ** retained purely for backwards compatibility */
8476 if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
8477 int val = 1;
8478 if( nArg>=2 ){
8479 if( cli_strcmp(azArg[1],"auto")==0 ){
8480 val = 99;
8481 }else{
8482 val = booleanValue(azArg[1]);
8485 if( val==1 && p->mode!=MODE_Explain ){
8486 p->normalMode = p->mode;
8487 p->mode = MODE_Explain;
8488 p->autoExplain = 0;
8489 }else if( val==0 ){
8490 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8491 p->autoExplain = 0;
8492 }else if( val==99 ){
8493 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8494 p->autoExplain = 1;
8496 }else
8498 #ifndef SQLITE_OMIT_VIRTUALTABLE
8499 if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
8500 if( p->bSafeMode ){
8501 raw_printf(stderr,
8502 "Cannot run experimental commands such as \"%s\" in safe mode\n",
8503 azArg[0]);
8504 rc = 1;
8505 }else{
8506 open_db(p, 0);
8507 expertDotCommand(p, azArg, nArg);
8509 }else
8510 #endif
8512 if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
8513 static const struct {
8514 const char *zCtrlName; /* Name of a test-control option */
8515 int ctrlCode; /* Integer code for that option */
8516 const char *zUsage; /* Usage notes */
8517 } aCtrl[] = {
8518 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
8519 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" },
8520 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
8521 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
8522 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
8523 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8524 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
8525 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" },
8526 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
8527 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
8528 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8530 int filectrl = -1;
8531 int iCtrl = -1;
8532 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
8533 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
8534 int n2, i;
8535 const char *zCmd = 0;
8536 const char *zSchema = 0;
8538 open_db(p, 0);
8539 zCmd = nArg>=2 ? azArg[1] : "help";
8541 if( zCmd[0]=='-'
8542 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
8543 && nArg>=4
8545 zSchema = azArg[2];
8546 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8547 nArg -= 2;
8548 zCmd = azArg[1];
8551 /* The argument can optionally begin with "-" or "--" */
8552 if( zCmd[0]=='-' && zCmd[1] ){
8553 zCmd++;
8554 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8557 /* --help lists all file-controls */
8558 if( cli_strcmp(zCmd,"help")==0 ){
8559 utf8_printf(p->out, "Available file-controls:\n");
8560 for(i=0; i<ArraySize(aCtrl); i++){
8561 utf8_printf(p->out, " .filectrl %s %s\n",
8562 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8564 rc = 1;
8565 goto meta_command_exit;
8568 /* convert filectrl text option to value. allow any unique prefix
8569 ** of the option name, or a numerical value. */
8570 n2 = strlen30(zCmd);
8571 for(i=0; i<ArraySize(aCtrl); i++){
8572 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8573 if( filectrl<0 ){
8574 filectrl = aCtrl[i].ctrlCode;
8575 iCtrl = i;
8576 }else{
8577 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8578 "Use \".filectrl --help\" for help\n", zCmd);
8579 rc = 1;
8580 goto meta_command_exit;
8584 if( filectrl<0 ){
8585 utf8_printf(stderr,"Error: unknown file-control: %s\n"
8586 "Use \".filectrl --help\" for help\n", zCmd);
8587 }else{
8588 switch(filectrl){
8589 case SQLITE_FCNTL_SIZE_LIMIT: {
8590 if( nArg!=2 && nArg!=3 ) break;
8591 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8592 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8593 isOk = 1;
8594 break;
8596 case SQLITE_FCNTL_LOCK_TIMEOUT:
8597 case SQLITE_FCNTL_CHUNK_SIZE: {
8598 int x;
8599 if( nArg!=3 ) break;
8600 x = (int)integerValue(azArg[2]);
8601 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8602 isOk = 2;
8603 break;
8605 case SQLITE_FCNTL_PERSIST_WAL:
8606 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8607 int x;
8608 if( nArg!=2 && nArg!=3 ) break;
8609 x = nArg==3 ? booleanValue(azArg[2]) : -1;
8610 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8611 iRes = x;
8612 isOk = 1;
8613 break;
8615 case SQLITE_FCNTL_DATA_VERSION:
8616 case SQLITE_FCNTL_HAS_MOVED: {
8617 int x;
8618 if( nArg!=2 ) break;
8619 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8620 iRes = x;
8621 isOk = 1;
8622 break;
8624 case SQLITE_FCNTL_TEMPFILENAME: {
8625 char *z = 0;
8626 if( nArg!=2 ) break;
8627 sqlite3_file_control(p->db, zSchema, filectrl, &z);
8628 if( z ){
8629 utf8_printf(p->out, "%s\n", z);
8630 sqlite3_free(z);
8632 isOk = 2;
8633 break;
8635 case SQLITE_FCNTL_RESERVE_BYTES: {
8636 int x;
8637 if( nArg>=3 ){
8638 x = atoi(azArg[2]);
8639 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8641 x = -1;
8642 sqlite3_file_control(p->db, zSchema, filectrl, &x);
8643 utf8_printf(p->out,"%d\n", x);
8644 isOk = 2;
8645 break;
8649 if( isOk==0 && iCtrl>=0 ){
8650 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8651 rc = 1;
8652 }else if( isOk==1 ){
8653 char zBuf[100];
8654 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8655 raw_printf(p->out, "%s\n", zBuf);
8657 }else
8659 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
8660 ShellState data;
8661 int doStats = 0;
8662 memcpy(&data, p, sizeof(data));
8663 data.showHeader = 0;
8664 data.cMode = data.mode = MODE_Semi;
8665 if( nArg==2 && optionMatch(azArg[1], "indent") ){
8666 data.cMode = data.mode = MODE_Pretty;
8667 nArg = 1;
8669 if( nArg!=1 ){
8670 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8671 rc = 1;
8672 goto meta_command_exit;
8674 open_db(p, 0);
8675 rc = sqlite3_exec(p->db,
8676 "SELECT sql FROM"
8677 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8678 " FROM sqlite_schema UNION ALL"
8679 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8680 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8681 "ORDER BY x",
8682 callback, &data, 0
8684 if( rc==SQLITE_OK ){
8685 sqlite3_stmt *pStmt;
8686 rc = sqlite3_prepare_v2(p->db,
8687 "SELECT rowid FROM sqlite_schema"
8688 " WHERE name GLOB 'sqlite_stat[134]'",
8689 -1, &pStmt, 0);
8690 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8691 sqlite3_finalize(pStmt);
8693 if( doStats==0 ){
8694 raw_printf(p->out, "/* No STAT tables available */\n");
8695 }else{
8696 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8697 data.cMode = data.mode = MODE_Insert;
8698 data.zDestTable = "sqlite_stat1";
8699 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8700 data.zDestTable = "sqlite_stat4";
8701 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8702 raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8704 }else
8706 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
8707 if( nArg==2 ){
8708 p->showHeader = booleanValue(azArg[1]);
8709 p->shellFlgs |= SHFLG_HeaderSet;
8710 }else{
8711 raw_printf(stderr, "Usage: .headers on|off\n");
8712 rc = 1;
8714 }else
8716 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
8717 if( nArg>=2 ){
8718 n = showHelp(p->out, azArg[1]);
8719 if( n==0 ){
8720 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8722 }else{
8723 showHelp(p->out, 0);
8725 }else
8727 #ifndef SQLITE_SHELL_FIDDLE
8728 if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
8729 char *zTable = 0; /* Insert data into this table */
8730 char *zSchema = 0; /* within this schema (may default to "main") */
8731 char *zFile = 0; /* Name of file to extra content from */
8732 sqlite3_stmt *pStmt = NULL; /* A statement */
8733 int nCol; /* Number of columns in the table */
8734 int nByte; /* Number of bytes in an SQL string */
8735 int i, j; /* Loop counters */
8736 int needCommit; /* True to COMMIT or ROLLBACK at end */
8737 int nSep; /* Number of bytes in p->colSeparator[] */
8738 char *zSql; /* An SQL statement */
8739 char *zFullTabName; /* Table name with schema if applicable */
8740 ImportCtx sCtx; /* Reader context */
8741 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8742 int eVerbose = 0; /* Larger for more console output */
8743 int nSkip = 0; /* Initial lines to skip */
8744 int useOutputMode = 1; /* Use output mode to determine separators */
8745 char *zCreate = 0; /* CREATE TABLE statement text */
8747 failIfSafeMode(p, "cannot run .import in safe mode");
8748 memset(&sCtx, 0, sizeof(sCtx));
8749 if( p->mode==MODE_Ascii ){
8750 xRead = ascii_read_one_field;
8751 }else{
8752 xRead = csv_read_one_field;
8754 rc = 1;
8755 for(i=1; i<nArg; i++){
8756 char *z = azArg[i];
8757 if( z[0]=='-' && z[1]=='-' ) z++;
8758 if( z[0]!='-' ){
8759 if( zFile==0 ){
8760 zFile = z;
8761 }else if( zTable==0 ){
8762 zTable = z;
8763 }else{
8764 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z);
8765 showHelp(p->out, "import");
8766 goto meta_command_exit;
8768 }else if( cli_strcmp(z,"-v")==0 ){
8769 eVerbose++;
8770 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
8771 zSchema = azArg[++i];
8772 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
8773 nSkip = integerValue(azArg[++i]);
8774 }else if( cli_strcmp(z,"-ascii")==0 ){
8775 sCtx.cColSep = SEP_Unit[0];
8776 sCtx.cRowSep = SEP_Record[0];
8777 xRead = ascii_read_one_field;
8778 useOutputMode = 0;
8779 }else if( cli_strcmp(z,"-csv")==0 ){
8780 sCtx.cColSep = ',';
8781 sCtx.cRowSep = '\n';
8782 xRead = csv_read_one_field;
8783 useOutputMode = 0;
8784 }else{
8785 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z);
8786 showHelp(p->out, "import");
8787 goto meta_command_exit;
8790 if( zTable==0 ){
8791 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8792 zFile==0 ? "FILE" : "TABLE");
8793 showHelp(p->out, "import");
8794 goto meta_command_exit;
8796 seenInterrupt = 0;
8797 open_db(p, 0);
8798 if( useOutputMode ){
8799 /* If neither the --csv or --ascii options are specified, then set
8800 ** the column and row separator characters from the output mode. */
8801 nSep = strlen30(p->colSeparator);
8802 if( nSep==0 ){
8803 raw_printf(stderr,
8804 "Error: non-null column separator required for import\n");
8805 goto meta_command_exit;
8807 if( nSep>1 ){
8808 raw_printf(stderr,
8809 "Error: multi-character column separators not allowed"
8810 " for import\n");
8811 goto meta_command_exit;
8813 nSep = strlen30(p->rowSeparator);
8814 if( nSep==0 ){
8815 raw_printf(stderr,
8816 "Error: non-null row separator required for import\n");
8817 goto meta_command_exit;
8819 if( nSep==2 && p->mode==MODE_Csv
8820 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
8822 /* When importing CSV (only), if the row separator is set to the
8823 ** default output row separator, change it to the default input
8824 ** row separator. This avoids having to maintain different input
8825 ** and output row separators. */
8826 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8827 nSep = strlen30(p->rowSeparator);
8829 if( nSep>1 ){
8830 raw_printf(stderr, "Error: multi-character row separators not allowed"
8831 " for import\n");
8832 goto meta_command_exit;
8834 sCtx.cColSep = (u8)p->colSeparator[0];
8835 sCtx.cRowSep = (u8)p->rowSeparator[0];
8837 sCtx.zFile = zFile;
8838 sCtx.nLine = 1;
8839 if( sCtx.zFile[0]=='|' ){
8840 #ifdef SQLITE_OMIT_POPEN
8841 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8842 goto meta_command_exit;
8843 #else
8844 sCtx.in = popen(sCtx.zFile+1, "r");
8845 sCtx.zFile = "<pipe>";
8846 sCtx.xCloser = pclose;
8847 #endif
8848 }else{
8849 sCtx.in = fopen(sCtx.zFile, "rb");
8850 sCtx.xCloser = fclose;
8852 if( sCtx.in==0 ){
8853 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8854 goto meta_command_exit;
8856 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8857 char zSep[2];
8858 zSep[1] = 0;
8859 zSep[0] = sCtx.cColSep;
8860 utf8_printf(p->out, "Column separator ");
8861 output_c_string(p->out, zSep);
8862 utf8_printf(p->out, ", row separator ");
8863 zSep[0] = sCtx.cRowSep;
8864 output_c_string(p->out, zSep);
8865 utf8_printf(p->out, "\n");
8867 sCtx.z = sqlite3_malloc64(120);
8868 if( sCtx.z==0 ){
8869 import_cleanup(&sCtx);
8870 shell_out_of_memory();
8872 /* Below, resources must be freed before exit. */
8873 while( (nSkip--)>0 ){
8874 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8876 if( zSchema!=0 ){
8877 zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8878 }else{
8879 zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8881 zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8882 if( zSql==0 || zFullTabName==0 ){
8883 import_cleanup(&sCtx);
8884 shell_out_of_memory();
8886 nByte = strlen30(zSql);
8887 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8888 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
8889 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8890 sqlite3 *dbCols = 0;
8891 char *zRenames = 0;
8892 char *zColDefs;
8893 zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
8894 while( xRead(&sCtx) ){
8895 zAutoColumn(sCtx.z, &dbCols, 0);
8896 if( sCtx.cTerm!=sCtx.cColSep ) break;
8898 zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8899 if( zRenames!=0 ){
8900 utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8901 "Columns renamed during .import %s due to duplicates:\n"
8902 "%s\n", sCtx.zFile, zRenames);
8903 sqlite3_free(zRenames);
8905 assert(dbCols==0);
8906 if( zColDefs==0 ){
8907 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8908 import_fail:
8909 sqlite3_free(zCreate);
8910 sqlite3_free(zSql);
8911 sqlite3_free(zFullTabName);
8912 import_cleanup(&sCtx);
8913 rc = 1;
8914 goto meta_command_exit;
8916 zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8917 if( eVerbose>=1 ){
8918 utf8_printf(p->out, "%s\n", zCreate);
8920 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8921 if( rc ){
8922 utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8923 goto import_fail;
8925 sqlite3_free(zCreate);
8926 zCreate = 0;
8927 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8929 if( rc ){
8930 if (pStmt) sqlite3_finalize(pStmt);
8931 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8932 goto import_fail;
8934 sqlite3_free(zSql);
8935 nCol = sqlite3_column_count(pStmt);
8936 sqlite3_finalize(pStmt);
8937 pStmt = 0;
8938 if( nCol==0 ) return 0; /* no columns, no error */
8939 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8940 if( zSql==0 ){
8941 import_cleanup(&sCtx);
8942 shell_out_of_memory();
8944 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
8945 j = strlen30(zSql);
8946 for(i=1; i<nCol; i++){
8947 zSql[j++] = ',';
8948 zSql[j++] = '?';
8950 zSql[j++] = ')';
8951 zSql[j] = 0;
8952 if( eVerbose>=2 ){
8953 utf8_printf(p->out, "Insert using: %s\n", zSql);
8955 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8956 if( rc ){
8957 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8958 if (pStmt) sqlite3_finalize(pStmt);
8959 goto import_fail;
8961 sqlite3_free(zSql);
8962 sqlite3_free(zFullTabName);
8963 needCommit = sqlite3_get_autocommit(p->db);
8964 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8966 int startLine = sCtx.nLine;
8967 for(i=0; i<nCol; i++){
8968 char *z = xRead(&sCtx);
8970 ** Did we reach end-of-file before finding any columns?
8971 ** If so, stop instead of NULL filling the remaining columns.
8973 if( z==0 && i==0 ) break;
8975 ** Did we reach end-of-file OR end-of-line before finding any
8976 ** columns in ASCII mode? If so, stop instead of NULL filling
8977 ** the remaining columns.
8979 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8980 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8981 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8982 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8983 "filling the rest with NULL\n",
8984 sCtx.zFile, startLine, nCol, i+1);
8985 i += 2;
8986 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8989 if( sCtx.cTerm==sCtx.cColSep ){
8991 xRead(&sCtx);
8992 i++;
8993 }while( sCtx.cTerm==sCtx.cColSep );
8994 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8995 "extras ignored\n",
8996 sCtx.zFile, startLine, nCol, i);
8998 if( i>=nCol ){
8999 sqlite3_step(pStmt);
9000 rc = sqlite3_reset(pStmt);
9001 if( rc!=SQLITE_OK ){
9002 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9003 startLine, sqlite3_errmsg(p->db));
9004 sCtx.nErr++;
9005 }else{
9006 sCtx.nRow++;
9009 }while( sCtx.cTerm!=EOF );
9011 import_cleanup(&sCtx);
9012 sqlite3_finalize(pStmt);
9013 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9014 if( eVerbose>0 ){
9015 utf8_printf(p->out,
9016 "Added %d rows with %d errors using %d lines of input\n",
9017 sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9019 }else
9020 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9022 #ifndef SQLITE_UNTESTABLE
9023 if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
9024 char *zSql;
9025 char *zCollist = 0;
9026 sqlite3_stmt *pStmt;
9027 int tnum = 0;
9028 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
9029 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9030 int i;
9031 if( !ShellHasFlag(p,SHFLG_TestingMode) ){
9032 utf8_printf(stderr, ".%s unavailable without --unsafe-testing\n",
9033 "imposter");
9034 rc = 1;
9035 goto meta_command_exit;
9037 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9038 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9039 " .imposter off\n");
9040 /* Also allowed, but not documented:
9042 ** .imposter TABLE IMPOSTER
9044 ** where TABLE is a WITHOUT ROWID table. In that case, the
9045 ** imposter is another WITHOUT ROWID table with the columns in
9046 ** storage order. */
9047 rc = 1;
9048 goto meta_command_exit;
9050 open_db(p, 0);
9051 if( nArg==2 ){
9052 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9053 goto meta_command_exit;
9055 zSql = sqlite3_mprintf(
9056 "SELECT rootpage, 0 FROM sqlite_schema"
9057 " WHERE name='%q' AND type='index'"
9058 "UNION ALL "
9059 "SELECT rootpage, 1 FROM sqlite_schema"
9060 " WHERE name='%q' AND type='table'"
9061 " AND sql LIKE '%%without%%rowid%%'",
9062 azArg[1], azArg[1]
9064 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9065 sqlite3_free(zSql);
9066 if( sqlite3_step(pStmt)==SQLITE_ROW ){
9067 tnum = sqlite3_column_int(pStmt, 0);
9068 isWO = sqlite3_column_int(pStmt, 1);
9070 sqlite3_finalize(pStmt);
9071 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9072 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9073 sqlite3_free(zSql);
9074 i = 0;
9075 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9076 char zLabel[20];
9077 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9078 i++;
9079 if( zCol==0 ){
9080 if( sqlite3_column_int(pStmt,1)==-1 ){
9081 zCol = "_ROWID_";
9082 }else{
9083 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9084 zCol = zLabel;
9087 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9088 lenPK = (int)strlen(zCollist);
9090 if( zCollist==0 ){
9091 zCollist = sqlite3_mprintf("\"%w\"", zCol);
9092 }else{
9093 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9096 sqlite3_finalize(pStmt);
9097 if( i==0 || tnum==0 ){
9098 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9099 rc = 1;
9100 sqlite3_free(zCollist);
9101 goto meta_command_exit;
9103 if( lenPK==0 ) lenPK = 100000;
9104 zSql = sqlite3_mprintf(
9105 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9106 azArg[2], zCollist, lenPK, zCollist);
9107 sqlite3_free(zCollist);
9108 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9109 if( rc==SQLITE_OK ){
9110 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9111 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9112 if( rc ){
9113 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9114 }else{
9115 utf8_printf(stdout, "%s;\n", zSql);
9116 raw_printf(stdout,
9117 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9118 azArg[1], isWO ? "table" : "index"
9121 }else{
9122 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9123 rc = 1;
9125 sqlite3_free(zSql);
9126 }else
9127 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9129 #ifdef SQLITE_ENABLE_IOTRACE
9130 if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
9131 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9132 if( iotrace && iotrace!=stdout ) fclose(iotrace);
9133 iotrace = 0;
9134 if( nArg<2 ){
9135 sqlite3IoTrace = 0;
9136 }else if( cli_strcmp(azArg[1], "-")==0 ){
9137 sqlite3IoTrace = iotracePrintf;
9138 iotrace = stdout;
9139 }else{
9140 iotrace = fopen(azArg[1], "w");
9141 if( iotrace==0 ){
9142 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9143 sqlite3IoTrace = 0;
9144 rc = 1;
9145 }else{
9146 sqlite3IoTrace = iotracePrintf;
9149 }else
9150 #endif
9152 if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
9153 static const struct {
9154 const char *zLimitName; /* Name of a limit */
9155 int limitCode; /* Integer code for that limit */
9156 } aLimit[] = {
9157 { "length", SQLITE_LIMIT_LENGTH },
9158 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
9159 { "column", SQLITE_LIMIT_COLUMN },
9160 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
9161 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
9162 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
9163 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
9164 { "attached", SQLITE_LIMIT_ATTACHED },
9165 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
9166 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
9167 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
9168 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
9170 int i, n2;
9171 open_db(p, 0);
9172 if( nArg==1 ){
9173 for(i=0; i<ArraySize(aLimit); i++){
9174 printf("%20s %d\n", aLimit[i].zLimitName,
9175 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9177 }else if( nArg>3 ){
9178 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9179 rc = 1;
9180 goto meta_command_exit;
9181 }else{
9182 int iLimit = -1;
9183 n2 = strlen30(azArg[1]);
9184 for(i=0; i<ArraySize(aLimit); i++){
9185 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9186 if( iLimit<0 ){
9187 iLimit = i;
9188 }else{
9189 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9190 rc = 1;
9191 goto meta_command_exit;
9195 if( iLimit<0 ){
9196 utf8_printf(stderr, "unknown limit: \"%s\"\n"
9197 "enter \".limits\" with no arguments for a list.\n",
9198 azArg[1]);
9199 rc = 1;
9200 goto meta_command_exit;
9202 if( nArg==3 ){
9203 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9204 (int)integerValue(azArg[2]));
9206 printf("%20s %d\n", aLimit[iLimit].zLimitName,
9207 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9209 }else
9211 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
9212 open_db(p, 0);
9213 lintDotCommand(p, azArg, nArg);
9214 }else
9216 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9217 if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
9218 const char *zFile, *zProc;
9219 char *zErrMsg = 0;
9220 failIfSafeMode(p, "cannot run .load in safe mode");
9221 if( nArg<2 || azArg[1][0]==0 ){
9222 /* Must have a non-empty FILE. (Will not load self.) */
9223 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9224 rc = 1;
9225 goto meta_command_exit;
9227 zFile = azArg[1];
9228 zProc = nArg>=3 ? azArg[2] : 0;
9229 open_db(p, 0);
9230 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9231 if( rc!=SQLITE_OK ){
9232 utf8_printf(stderr, "Error: %s\n", zErrMsg);
9233 sqlite3_free(zErrMsg);
9234 rc = 1;
9236 }else
9237 #endif
9239 if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
9240 if( nArg!=2 ){
9241 raw_printf(stderr, "Usage: .log FILENAME\n");
9242 rc = 1;
9243 }else{
9244 const char *zFile = azArg[1];
9245 if( p->bSafeMode
9246 && cli_strcmp(zFile,"on")!=0
9247 && cli_strcmp(zFile,"off")!=0
9249 raw_printf(stdout, "cannot set .log to anything other "
9250 "than \"on\" or \"off\"\n");
9251 zFile = "off";
9253 output_file_close(p->pLog);
9254 if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
9255 p->pLog = output_file_open(zFile, 0);
9257 }else
9259 if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
9260 const char *zMode = 0;
9261 const char *zTabname = 0;
9262 int i, n2;
9263 ColModeOpts cmOpts = ColModeOpts_default;
9264 for(i=1; i<nArg; i++){
9265 const char *z = azArg[i];
9266 if( optionMatch(z,"wrap") && i+1<nArg ){
9267 cmOpts.iWrap = integerValue(azArg[++i]);
9268 }else if( optionMatch(z,"ww") ){
9269 cmOpts.bWordWrap = 1;
9270 }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9271 cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9272 }else if( optionMatch(z,"quote") ){
9273 cmOpts.bQuote = 1;
9274 }else if( optionMatch(z,"noquote") ){
9275 cmOpts.bQuote = 0;
9276 }else if( zMode==0 ){
9277 zMode = z;
9278 /* Apply defaults for qbox pseudo-mode. If that
9279 * overwrites already-set values, user was informed of this.
9281 if( cli_strcmp(z, "qbox")==0 ){
9282 ColModeOpts cmo = ColModeOpts_default_qbox;
9283 zMode = "box";
9284 cmOpts = cmo;
9286 }else if( zTabname==0 ){
9287 zTabname = z;
9288 }else if( z[0]=='-' ){
9289 utf8_printf(stderr, "unknown option: %s\n", z);
9290 utf8_printf(stderr, "options:\n"
9291 " --noquote\n"
9292 " --quote\n"
9293 " --wordwrap on/off\n"
9294 " --wrap N\n"
9295 " --ww\n");
9296 rc = 1;
9297 goto meta_command_exit;
9298 }else{
9299 utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9300 rc = 1;
9301 goto meta_command_exit;
9304 if( zMode==0 ){
9305 if( p->mode==MODE_Column
9306 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9308 raw_printf
9309 (p->out,
9310 "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9311 modeDescr[p->mode], p->cmOpts.iWrap,
9312 p->cmOpts.bWordWrap ? "on" : "off",
9313 p->cmOpts.bQuote ? "" : "no");
9314 }else{
9315 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9317 zMode = modeDescr[p->mode];
9319 n2 = strlen30(zMode);
9320 if( cli_strncmp(zMode,"lines",n2)==0 ){
9321 p->mode = MODE_Line;
9322 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9323 }else if( cli_strncmp(zMode,"columns",n2)==0 ){
9324 p->mode = MODE_Column;
9325 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9326 p->showHeader = 1;
9328 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9329 p->cmOpts = cmOpts;
9330 }else if( cli_strncmp(zMode,"list",n2)==0 ){
9331 p->mode = MODE_List;
9332 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9333 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9334 }else if( cli_strncmp(zMode,"html",n2)==0 ){
9335 p->mode = MODE_Html;
9336 }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
9337 p->mode = MODE_Tcl;
9338 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9339 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9340 }else if( cli_strncmp(zMode,"csv",n2)==0 ){
9341 p->mode = MODE_Csv;
9342 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9343 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9344 }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
9345 p->mode = MODE_List;
9346 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9347 }else if( cli_strncmp(zMode,"insert",n2)==0 ){
9348 p->mode = MODE_Insert;
9349 set_table_name(p, zTabname ? zTabname : "table");
9350 }else if( cli_strncmp(zMode,"quote",n2)==0 ){
9351 p->mode = MODE_Quote;
9352 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9353 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9354 }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
9355 p->mode = MODE_Ascii;
9356 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9357 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9358 }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
9359 p->mode = MODE_Markdown;
9360 p->cmOpts = cmOpts;
9361 }else if( cli_strncmp(zMode,"table",n2)==0 ){
9362 p->mode = MODE_Table;
9363 p->cmOpts = cmOpts;
9364 }else if( cli_strncmp(zMode,"box",n2)==0 ){
9365 p->mode = MODE_Box;
9366 p->cmOpts = cmOpts;
9367 }else if( cli_strncmp(zMode,"count",n2)==0 ){
9368 p->mode = MODE_Count;
9369 }else if( cli_strncmp(zMode,"off",n2)==0 ){
9370 p->mode = MODE_Off;
9371 }else if( cli_strncmp(zMode,"json",n2)==0 ){
9372 p->mode = MODE_Json;
9373 }else{
9374 raw_printf(stderr, "Error: mode should be one of: "
9375 "ascii box column csv html insert json line list markdown "
9376 "qbox quote table tabs tcl\n");
9377 rc = 1;
9379 p->cMode = p->mode;
9380 }else
9382 #ifndef SQLITE_SHELL_FIDDLE
9383 if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
9384 if( nArg!=2 ){
9385 raw_printf(stderr, "Usage: .nonce NONCE\n");
9386 rc = 1;
9387 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
9388 raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9389 p->lineno, azArg[1]);
9390 exit(1);
9391 }else{
9392 p->bSafeMode = 0;
9393 return 0; /* Return immediately to bypass the safe mode reset
9394 ** at the end of this procedure */
9396 }else
9397 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9399 if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
9400 if( nArg==2 ){
9401 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9402 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9403 }else{
9404 raw_printf(stderr, "Usage: .nullvalue STRING\n");
9405 rc = 1;
9407 }else
9409 if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
9410 const char *zFN = 0; /* Pointer to constant filename */
9411 char *zNewFilename = 0; /* Name of the database file to open */
9412 int iName = 1; /* Index in azArg[] of the filename */
9413 int newFlag = 0; /* True to delete file before opening */
9414 int openMode = SHELL_OPEN_UNSPEC;
9416 /* Check for command-line arguments */
9417 for(iName=1; iName<nArg; iName++){
9418 const char *z = azArg[iName];
9419 #ifndef SQLITE_SHELL_FIDDLE
9420 if( optionMatch(z,"new") ){
9421 newFlag = 1;
9422 #ifdef SQLITE_HAVE_ZLIB
9423 }else if( optionMatch(z, "zip") ){
9424 openMode = SHELL_OPEN_ZIPFILE;
9425 #endif
9426 }else if( optionMatch(z, "append") ){
9427 openMode = SHELL_OPEN_APPENDVFS;
9428 }else if( optionMatch(z, "readonly") ){
9429 openMode = SHELL_OPEN_READONLY;
9430 }else if( optionMatch(z, "nofollow") ){
9431 p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9432 #ifndef SQLITE_OMIT_DESERIALIZE
9433 }else if( optionMatch(z, "deserialize") ){
9434 openMode = SHELL_OPEN_DESERIALIZE;
9435 }else if( optionMatch(z, "hexdb") ){
9436 openMode = SHELL_OPEN_HEXDB;
9437 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9438 p->szMax = integerValue(azArg[++iName]);
9439 #endif /* SQLITE_OMIT_DESERIALIZE */
9440 }else
9441 #endif /* !SQLITE_SHELL_FIDDLE */
9442 if( z[0]=='-' ){
9443 utf8_printf(stderr, "unknown option: %s\n", z);
9444 rc = 1;
9445 goto meta_command_exit;
9446 }else if( zFN ){
9447 utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9448 rc = 1;
9449 goto meta_command_exit;
9450 }else{
9451 zFN = z;
9455 /* Close the existing database */
9456 session_close_all(p, -1);
9457 close_db(p->db);
9458 p->db = 0;
9459 p->pAuxDb->zDbFilename = 0;
9460 sqlite3_free(p->pAuxDb->zFreeOnClose);
9461 p->pAuxDb->zFreeOnClose = 0;
9462 p->openMode = openMode;
9463 p->openFlags = 0;
9464 p->szMax = 0;
9466 /* If a filename is specified, try to open it first */
9467 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9468 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9469 #ifndef SQLITE_SHELL_FIDDLE
9470 if( p->bSafeMode
9471 && p->openMode!=SHELL_OPEN_HEXDB
9472 && zFN
9473 && cli_strcmp(zFN,":memory:")!=0
9475 failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9477 #else
9478 /* WASM mode has its own sandboxed pseudo-filesystem. */
9479 #endif
9480 if( zFN ){
9481 zNewFilename = sqlite3_mprintf("%s", zFN);
9482 shell_check_oom(zNewFilename);
9483 }else{
9484 zNewFilename = 0;
9486 p->pAuxDb->zDbFilename = zNewFilename;
9487 open_db(p, OPEN_DB_KEEPALIVE);
9488 if( p->db==0 ){
9489 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9490 sqlite3_free(zNewFilename);
9491 }else{
9492 p->pAuxDb->zFreeOnClose = zNewFilename;
9495 if( p->db==0 ){
9496 /* As a fall-back open a TEMP database */
9497 p->pAuxDb->zDbFilename = 0;
9498 open_db(p, 0);
9500 }else
9502 #ifndef SQLITE_SHELL_FIDDLE
9503 if( (c=='o'
9504 && (cli_strncmp(azArg[0], "output", n)==0
9505 || cli_strncmp(azArg[0], "once", n)==0))
9506 || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
9508 char *zFile = 0;
9509 int bTxtMode = 0;
9510 int i;
9511 int eMode = 0;
9512 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */
9513 unsigned char zBOM[4]; /* Byte-order mark to using if --bom is present */
9515 zBOM[0] = 0;
9516 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9517 if( c=='e' ){
9518 eMode = 'x';
9519 bOnce = 2;
9520 }else if( cli_strncmp(azArg[0],"once",n)==0 ){
9521 bOnce = 1;
9523 for(i=1; i<nArg; i++){
9524 char *z = azArg[i];
9525 if( z[0]=='-' ){
9526 if( z[1]=='-' ) z++;
9527 if( cli_strcmp(z,"-bom")==0 ){
9528 zBOM[0] = 0xef;
9529 zBOM[1] = 0xbb;
9530 zBOM[2] = 0xbf;
9531 zBOM[3] = 0;
9532 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
9533 eMode = 'x'; /* spreadsheet */
9534 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
9535 eMode = 'e'; /* text editor */
9536 }else{
9537 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n",
9538 azArg[i]);
9539 showHelp(p->out, azArg[0]);
9540 rc = 1;
9541 goto meta_command_exit;
9543 }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9544 zFile = sqlite3_mprintf("%s", z);
9545 if( zFile && zFile[0]=='|' ){
9546 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9547 break;
9549 }else{
9550 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n",
9551 azArg[i]);
9552 showHelp(p->out, azArg[0]);
9553 rc = 1;
9554 sqlite3_free(zFile);
9555 goto meta_command_exit;
9558 if( zFile==0 ){
9559 zFile = sqlite3_mprintf("stdout");
9561 if( bOnce ){
9562 p->outCount = 2;
9563 }else{
9564 p->outCount = 0;
9566 output_reset(p);
9567 #ifndef SQLITE_NOHAVE_SYSTEM
9568 if( eMode=='e' || eMode=='x' ){
9569 p->doXdgOpen = 1;
9570 outputModePush(p);
9571 if( eMode=='x' ){
9572 /* spreadsheet mode. Output as CSV. */
9573 newTempFile(p, "csv");
9574 ShellClearFlag(p, SHFLG_Echo);
9575 p->mode = MODE_Csv;
9576 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9577 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9578 }else{
9579 /* text editor mode */
9580 newTempFile(p, "txt");
9581 bTxtMode = 1;
9583 sqlite3_free(zFile);
9584 zFile = sqlite3_mprintf("%s", p->zTempFile);
9586 #endif /* SQLITE_NOHAVE_SYSTEM */
9587 shell_check_oom(zFile);
9588 if( zFile[0]=='|' ){
9589 #ifdef SQLITE_OMIT_POPEN
9590 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9591 rc = 1;
9592 p->out = stdout;
9593 #else
9594 p->out = popen(zFile + 1, "w");
9595 if( p->out==0 ){
9596 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9597 p->out = stdout;
9598 rc = 1;
9599 }else{
9600 if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9601 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9603 #endif
9604 }else{
9605 p->out = output_file_open(zFile, bTxtMode);
9606 if( p->out==0 ){
9607 if( cli_strcmp(zFile,"off")!=0 ){
9608 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9610 p->out = stdout;
9611 rc = 1;
9612 } else {
9613 if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9614 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9617 sqlite3_free(zFile);
9618 }else
9619 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9621 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
9622 open_db(p,0);
9623 if( nArg<=1 ) goto parameter_syntax_error;
9625 /* .parameter clear
9626 ** Clear all bind parameters by dropping the TEMP table that holds them.
9628 if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
9629 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9630 0, 0, 0);
9631 }else
9633 /* .parameter list
9634 ** List all bind parameters.
9636 if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
9637 sqlite3_stmt *pStmt = 0;
9638 int rx;
9639 int len = 0;
9640 rx = sqlite3_prepare_v2(p->db,
9641 "SELECT max(length(key)) "
9642 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9643 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9644 len = sqlite3_column_int(pStmt, 0);
9645 if( len>40 ) len = 40;
9647 sqlite3_finalize(pStmt);
9648 pStmt = 0;
9649 if( len ){
9650 rx = sqlite3_prepare_v2(p->db,
9651 "SELECT key, quote(value) "
9652 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9653 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9654 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9655 sqlite3_column_text(pStmt,1));
9657 sqlite3_finalize(pStmt);
9659 }else
9661 /* .parameter init
9662 ** Make sure the TEMP table used to hold bind parameters exists.
9663 ** Create it if necessary.
9665 if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
9666 bind_table_init(p);
9667 }else
9669 /* .parameter set NAME VALUE
9670 ** Set or reset a bind parameter. NAME should be the full parameter
9671 ** name exactly as it appears in the query. (ex: $abc, @def). The
9672 ** VALUE can be in either SQL literal notation, or if not it will be
9673 ** understood to be a text string.
9675 if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
9676 int rx;
9677 char *zSql;
9678 sqlite3_stmt *pStmt;
9679 const char *zKey = azArg[2];
9680 const char *zValue = azArg[3];
9681 bind_table_init(p);
9682 zSql = sqlite3_mprintf(
9683 "REPLACE INTO temp.sqlite_parameters(key,value)"
9684 "VALUES(%Q,%s);", zKey, zValue);
9685 shell_check_oom(zSql);
9686 pStmt = 0;
9687 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9688 sqlite3_free(zSql);
9689 if( rx!=SQLITE_OK ){
9690 sqlite3_finalize(pStmt);
9691 pStmt = 0;
9692 zSql = sqlite3_mprintf(
9693 "REPLACE INTO temp.sqlite_parameters(key,value)"
9694 "VALUES(%Q,%Q);", zKey, zValue);
9695 shell_check_oom(zSql);
9696 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9697 sqlite3_free(zSql);
9698 if( rx!=SQLITE_OK ){
9699 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9700 sqlite3_finalize(pStmt);
9701 pStmt = 0;
9702 rc = 1;
9705 sqlite3_step(pStmt);
9706 sqlite3_finalize(pStmt);
9707 }else
9709 /* .parameter unset NAME
9710 ** Remove the NAME binding from the parameter binding table, if it
9711 ** exists.
9713 if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
9714 char *zSql = sqlite3_mprintf(
9715 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9716 shell_check_oom(zSql);
9717 sqlite3_exec(p->db, zSql, 0, 0, 0);
9718 sqlite3_free(zSql);
9719 }else
9720 /* If no command name matches, show a syntax error */
9721 parameter_syntax_error:
9722 showHelp(p->out, "parameter");
9723 }else
9725 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
9726 int i;
9727 for(i=1; i<nArg; i++){
9728 if( i>1 ) raw_printf(p->out, " ");
9729 utf8_printf(p->out, "%s", azArg[i]);
9731 raw_printf(p->out, "\n");
9732 }else
9734 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9735 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
9736 int i;
9737 int nn = 0;
9738 p->flgProgress = 0;
9739 p->mxProgress = 0;
9740 p->nProgress = 0;
9741 for(i=1; i<nArg; i++){
9742 const char *z = azArg[i];
9743 if( z[0]=='-' ){
9744 z++;
9745 if( z[0]=='-' ) z++;
9746 if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
9747 p->flgProgress |= SHELL_PROGRESS_QUIET;
9748 continue;
9750 if( cli_strcmp(z,"reset")==0 ){
9751 p->flgProgress |= SHELL_PROGRESS_RESET;
9752 continue;
9754 if( cli_strcmp(z,"once")==0 ){
9755 p->flgProgress |= SHELL_PROGRESS_ONCE;
9756 continue;
9758 if( cli_strcmp(z,"limit")==0 ){
9759 if( i+1>=nArg ){
9760 utf8_printf(stderr, "Error: missing argument on --limit\n");
9761 rc = 1;
9762 goto meta_command_exit;
9763 }else{
9764 p->mxProgress = (int)integerValue(azArg[++i]);
9766 continue;
9768 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9769 rc = 1;
9770 goto meta_command_exit;
9771 }else{
9772 nn = (int)integerValue(z);
9775 open_db(p, 0);
9776 sqlite3_progress_handler(p->db, nn, progress_handler, p);
9777 }else
9778 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9780 if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
9781 if( nArg >= 2) {
9782 shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9784 if( nArg >= 3) {
9785 shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9787 }else
9789 #ifndef SQLITE_SHELL_FIDDLE
9790 if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
9791 rc = 2;
9792 }else
9793 #endif
9795 #ifndef SQLITE_SHELL_FIDDLE
9796 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
9797 FILE *inSaved = p->in;
9798 int savedLineno = p->lineno;
9799 failIfSafeMode(p, "cannot run .read in safe mode");
9800 if( nArg!=2 ){
9801 raw_printf(stderr, "Usage: .read FILE\n");
9802 rc = 1;
9803 goto meta_command_exit;
9805 if( azArg[1][0]=='|' ){
9806 #ifdef SQLITE_OMIT_POPEN
9807 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9808 rc = 1;
9809 p->out = stdout;
9810 #else
9811 p->in = popen(azArg[1]+1, "r");
9812 if( p->in==0 ){
9813 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9814 rc = 1;
9815 }else{
9816 rc = process_input(p);
9817 pclose(p->in);
9819 #endif
9820 }else if( (p->in = openChrSource(azArg[1]))==0 ){
9821 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9822 rc = 1;
9823 }else{
9824 rc = process_input(p);
9825 fclose(p->in);
9827 p->in = inSaved;
9828 p->lineno = savedLineno;
9829 }else
9830 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9832 #ifndef SQLITE_SHELL_FIDDLE
9833 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
9834 const char *zSrcFile;
9835 const char *zDb;
9836 sqlite3 *pSrc;
9837 sqlite3_backup *pBackup;
9838 int nTimeout = 0;
9840 failIfSafeMode(p, "cannot run .restore in safe mode");
9841 if( nArg==2 ){
9842 zSrcFile = azArg[1];
9843 zDb = "main";
9844 }else if( nArg==3 ){
9845 zSrcFile = azArg[2];
9846 zDb = azArg[1];
9847 }else{
9848 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9849 rc = 1;
9850 goto meta_command_exit;
9852 rc = sqlite3_open(zSrcFile, &pSrc);
9853 if( rc!=SQLITE_OK ){
9854 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9855 close_db(pSrc);
9856 return 1;
9858 open_db(p, 0);
9859 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9860 if( pBackup==0 ){
9861 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9862 close_db(pSrc);
9863 return 1;
9865 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9866 || rc==SQLITE_BUSY ){
9867 if( rc==SQLITE_BUSY ){
9868 if( nTimeout++ >= 3 ) break;
9869 sqlite3_sleep(100);
9872 sqlite3_backup_finish(pBackup);
9873 if( rc==SQLITE_DONE ){
9874 rc = 0;
9875 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9876 raw_printf(stderr, "Error: source database is busy\n");
9877 rc = 1;
9878 }else{
9879 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9880 rc = 1;
9882 close_db(pSrc);
9883 }else
9884 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9886 if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
9887 if( nArg==2 ){
9888 if( cli_strcmp(azArg[1], "est")==0 ){
9889 p->scanstatsOn = 2;
9890 }else{
9891 p->scanstatsOn = (u8)booleanValue(azArg[1]);
9893 open_db(p, 0);
9894 sqlite3_db_config(
9895 p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
9897 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9898 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9899 #endif
9900 }else{
9901 raw_printf(stderr, "Usage: .scanstats on|off|est\n");
9902 rc = 1;
9904 }else
9906 if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
9907 ShellText sSelect;
9908 ShellState data;
9909 char *zErrMsg = 0;
9910 const char *zDiv = "(";
9911 const char *zName = 0;
9912 int iSchema = 0;
9913 int bDebug = 0;
9914 int bNoSystemTabs = 0;
9915 int ii;
9917 open_db(p, 0);
9918 memcpy(&data, p, sizeof(data));
9919 data.showHeader = 0;
9920 data.cMode = data.mode = MODE_Semi;
9921 initText(&sSelect);
9922 for(ii=1; ii<nArg; ii++){
9923 if( optionMatch(azArg[ii],"indent") ){
9924 data.cMode = data.mode = MODE_Pretty;
9925 }else if( optionMatch(azArg[ii],"debug") ){
9926 bDebug = 1;
9927 }else if( optionMatch(azArg[ii],"nosys") ){
9928 bNoSystemTabs = 1;
9929 }else if( azArg[ii][0]=='-' ){
9930 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9931 rc = 1;
9932 goto meta_command_exit;
9933 }else if( zName==0 ){
9934 zName = azArg[ii];
9935 }else{
9936 raw_printf(stderr,
9937 "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9938 rc = 1;
9939 goto meta_command_exit;
9942 if( zName!=0 ){
9943 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9944 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9945 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9946 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9947 if( isSchema ){
9948 char *new_argv[2], *new_colv[2];
9949 new_argv[0] = sqlite3_mprintf(
9950 "CREATE TABLE %s (\n"
9951 " type text,\n"
9952 " name text,\n"
9953 " tbl_name text,\n"
9954 " rootpage integer,\n"
9955 " sql text\n"
9956 ")", zName);
9957 shell_check_oom(new_argv[0]);
9958 new_argv[1] = 0;
9959 new_colv[0] = "sql";
9960 new_colv[1] = 0;
9961 callback(&data, 1, new_argv, new_colv);
9962 sqlite3_free(new_argv[0]);
9965 if( zDiv ){
9966 sqlite3_stmt *pStmt = 0;
9967 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9968 -1, &pStmt, 0);
9969 if( rc ){
9970 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9971 sqlite3_finalize(pStmt);
9972 rc = 1;
9973 goto meta_command_exit;
9975 appendText(&sSelect, "SELECT sql FROM", 0);
9976 iSchema = 0;
9977 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9978 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9979 char zScNum[30];
9980 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9981 appendText(&sSelect, zDiv, 0);
9982 zDiv = " UNION ALL ";
9983 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9984 if( sqlite3_stricmp(zDb, "main")!=0 ){
9985 appendText(&sSelect, zDb, '\'');
9986 }else{
9987 appendText(&sSelect, "NULL", 0);
9989 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9990 appendText(&sSelect, zScNum, 0);
9991 appendText(&sSelect, " AS snum, ", 0);
9992 appendText(&sSelect, zDb, '\'');
9993 appendText(&sSelect, " AS sname FROM ", 0);
9994 appendText(&sSelect, zDb, quoteChar(zDb));
9995 appendText(&sSelect, ".sqlite_schema", 0);
9997 sqlite3_finalize(pStmt);
9998 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9999 if( zName ){
10000 appendText(&sSelect,
10001 " UNION ALL SELECT shell_module_schema(name),"
10002 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10005 #endif
10006 appendText(&sSelect, ") WHERE ", 0);
10007 if( zName ){
10008 char *zQarg = sqlite3_mprintf("%Q", zName);
10009 int bGlob;
10010 shell_check_oom(zQarg);
10011 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10012 strchr(zName, '[') != 0;
10013 if( strchr(zName, '.') ){
10014 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10015 }else{
10016 appendText(&sSelect, "lower(tbl_name)", 0);
10018 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10019 appendText(&sSelect, zQarg, 0);
10020 if( !bGlob ){
10021 appendText(&sSelect, " ESCAPE '\\' ", 0);
10023 appendText(&sSelect, " AND ", 0);
10024 sqlite3_free(zQarg);
10026 if( bNoSystemTabs ){
10027 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10029 appendText(&sSelect, "sql IS NOT NULL"
10030 " ORDER BY snum, rowid", 0);
10031 if( bDebug ){
10032 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10033 }else{
10034 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10036 freeText(&sSelect);
10038 if( zErrMsg ){
10039 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10040 sqlite3_free(zErrMsg);
10041 rc = 1;
10042 }else if( rc != SQLITE_OK ){
10043 raw_printf(stderr,"Error: querying schema information\n");
10044 rc = 1;
10045 }else{
10046 rc = 0;
10048 }else
10050 if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
10051 || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0)
10053 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10054 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10055 }else
10057 #if defined(SQLITE_ENABLE_SESSION)
10058 if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
10059 struct AuxDb *pAuxDb = p->pAuxDb;
10060 OpenSession *pSession = &pAuxDb->aSession[0];
10061 char **azCmd = &azArg[1];
10062 int iSes = 0;
10063 int nCmd = nArg - 1;
10064 int i;
10065 if( nArg<=1 ) goto session_syntax_error;
10066 open_db(p, 0);
10067 if( nArg>=3 ){
10068 for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10069 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10071 if( iSes<pAuxDb->nSession ){
10072 pSession = &pAuxDb->aSession[iSes];
10073 azCmd++;
10074 nCmd--;
10075 }else{
10076 pSession = &pAuxDb->aSession[0];
10077 iSes = 0;
10081 /* .session attach TABLE
10082 ** Invoke the sqlite3session_attach() interface to attach a particular
10083 ** table so that it is never filtered.
10085 if( cli_strcmp(azCmd[0],"attach")==0 ){
10086 if( nCmd!=2 ) goto session_syntax_error;
10087 if( pSession->p==0 ){
10088 session_not_open:
10089 raw_printf(stderr, "ERROR: No sessions are open\n");
10090 }else{
10091 rc = sqlite3session_attach(pSession->p, azCmd[1]);
10092 if( rc ){
10093 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10094 rc = 0;
10097 }else
10099 /* .session changeset FILE
10100 ** .session patchset FILE
10101 ** Write a changeset or patchset into a file. The file is overwritten.
10103 if( cli_strcmp(azCmd[0],"changeset")==0
10104 || cli_strcmp(azCmd[0],"patchset")==0
10106 FILE *out = 0;
10107 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10108 if( nCmd!=2 ) goto session_syntax_error;
10109 if( pSession->p==0 ) goto session_not_open;
10110 out = fopen(azCmd[1], "wb");
10111 if( out==0 ){
10112 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10113 azCmd[1]);
10114 }else{
10115 int szChng;
10116 void *pChng;
10117 if( azCmd[0][0]=='c' ){
10118 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10119 }else{
10120 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10122 if( rc ){
10123 printf("Error: error code %d\n", rc);
10124 rc = 0;
10126 if( pChng
10127 && fwrite(pChng, szChng, 1, out)!=1 ){
10128 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10129 szChng);
10131 sqlite3_free(pChng);
10132 fclose(out);
10134 }else
10136 /* .session close
10137 ** Close the identified session
10139 if( cli_strcmp(azCmd[0], "close")==0 ){
10140 if( nCmd!=1 ) goto session_syntax_error;
10141 if( pAuxDb->nSession ){
10142 session_close(pSession);
10143 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10145 }else
10147 /* .session enable ?BOOLEAN?
10148 ** Query or set the enable flag
10150 if( cli_strcmp(azCmd[0], "enable")==0 ){
10151 int ii;
10152 if( nCmd>2 ) goto session_syntax_error;
10153 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10154 if( pAuxDb->nSession ){
10155 ii = sqlite3session_enable(pSession->p, ii);
10156 utf8_printf(p->out, "session %s enable flag = %d\n",
10157 pSession->zName, ii);
10159 }else
10161 /* .session filter GLOB ....
10162 ** Set a list of GLOB patterns of table names to be excluded.
10164 if( cli_strcmp(azCmd[0], "filter")==0 ){
10165 int ii, nByte;
10166 if( nCmd<2 ) goto session_syntax_error;
10167 if( pAuxDb->nSession ){
10168 for(ii=0; ii<pSession->nFilter; ii++){
10169 sqlite3_free(pSession->azFilter[ii]);
10171 sqlite3_free(pSession->azFilter);
10172 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10173 pSession->azFilter = sqlite3_malloc( nByte );
10174 if( pSession->azFilter==0 ){
10175 raw_printf(stderr, "Error: out or memory\n");
10176 exit(1);
10178 for(ii=1; ii<nCmd; ii++){
10179 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10180 shell_check_oom(x);
10182 pSession->nFilter = ii-1;
10184 }else
10186 /* .session indirect ?BOOLEAN?
10187 ** Query or set the indirect flag
10189 if( cli_strcmp(azCmd[0], "indirect")==0 ){
10190 int ii;
10191 if( nCmd>2 ) goto session_syntax_error;
10192 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10193 if( pAuxDb->nSession ){
10194 ii = sqlite3session_indirect(pSession->p, ii);
10195 utf8_printf(p->out, "session %s indirect flag = %d\n",
10196 pSession->zName, ii);
10198 }else
10200 /* .session isempty
10201 ** Determine if the session is empty
10203 if( cli_strcmp(azCmd[0], "isempty")==0 ){
10204 int ii;
10205 if( nCmd!=1 ) goto session_syntax_error;
10206 if( pAuxDb->nSession ){
10207 ii = sqlite3session_isempty(pSession->p);
10208 utf8_printf(p->out, "session %s isempty flag = %d\n",
10209 pSession->zName, ii);
10211 }else
10213 /* .session list
10214 ** List all currently open sessions
10216 if( cli_strcmp(azCmd[0],"list")==0 ){
10217 for(i=0; i<pAuxDb->nSession; i++){
10218 utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10220 }else
10222 /* .session open DB NAME
10223 ** Open a new session called NAME on the attached database DB.
10224 ** DB is normally "main".
10226 if( cli_strcmp(azCmd[0],"open")==0 ){
10227 char *zName;
10228 if( nCmd!=3 ) goto session_syntax_error;
10229 zName = azCmd[2];
10230 if( zName[0]==0 ) goto session_syntax_error;
10231 for(i=0; i<pAuxDb->nSession; i++){
10232 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10233 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10234 goto meta_command_exit;
10237 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10238 raw_printf(stderr,
10239 "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10240 goto meta_command_exit;
10242 pSession = &pAuxDb->aSession[pAuxDb->nSession];
10243 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10244 if( rc ){
10245 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10246 rc = 0;
10247 goto meta_command_exit;
10249 pSession->nFilter = 0;
10250 sqlite3session_table_filter(pSession->p, session_filter, pSession);
10251 pAuxDb->nSession++;
10252 pSession->zName = sqlite3_mprintf("%s", zName);
10253 shell_check_oom(pSession->zName);
10254 }else
10255 /* If no command name matches, show a syntax error */
10256 session_syntax_error:
10257 showHelp(p->out, "session");
10258 }else
10259 #endif
10261 #ifdef SQLITE_DEBUG
10262 /* Undocumented commands for internal testing. Subject to change
10263 ** without notice. */
10264 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
10265 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10266 int i, v;
10267 for(i=1; i<nArg; i++){
10268 v = booleanValue(azArg[i]);
10269 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10272 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
10273 int i; sqlite3_int64 v;
10274 for(i=1; i<nArg; i++){
10275 char zBuf[200];
10276 v = integerValue(azArg[i]);
10277 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10278 utf8_printf(p->out, "%s", zBuf);
10281 }else
10282 #endif
10284 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
10285 int bIsInit = 0; /* True to initialize the SELFTEST table */
10286 int bVerbose = 0; /* Verbose output */
10287 int bSelftestExists; /* True if SELFTEST already exists */
10288 int i, k; /* Loop counters */
10289 int nTest = 0; /* Number of tests runs */
10290 int nErr = 0; /* Number of errors seen */
10291 ShellText str; /* Answer for a query */
10292 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10294 open_db(p,0);
10295 for(i=1; i<nArg; i++){
10296 const char *z = azArg[i];
10297 if( z[0]=='-' && z[1]=='-' ) z++;
10298 if( cli_strcmp(z,"-init")==0 ){
10299 bIsInit = 1;
10300 }else
10301 if( cli_strcmp(z,"-v")==0 ){
10302 bVerbose++;
10303 }else
10305 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10306 azArg[i], azArg[0]);
10307 raw_printf(stderr, "Should be one of: --init -v\n");
10308 rc = 1;
10309 goto meta_command_exit;
10312 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10313 != SQLITE_OK ){
10314 bSelftestExists = 0;
10315 }else{
10316 bSelftestExists = 1;
10318 if( bIsInit ){
10319 createSelftestTable(p);
10320 bSelftestExists = 1;
10322 initText(&str);
10323 appendText(&str, "x", 0);
10324 for(k=bSelftestExists; k>=0; k--){
10325 if( k==1 ){
10326 rc = sqlite3_prepare_v2(p->db,
10327 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10328 -1, &pStmt, 0);
10329 }else{
10330 rc = sqlite3_prepare_v2(p->db,
10331 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10332 " (1,'run','PRAGMA integrity_check','ok')",
10333 -1, &pStmt, 0);
10335 if( rc ){
10336 raw_printf(stderr, "Error querying the selftest table\n");
10337 rc = 1;
10338 sqlite3_finalize(pStmt);
10339 goto meta_command_exit;
10341 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10342 int tno = sqlite3_column_int(pStmt, 0);
10343 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10344 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10345 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10347 if( zOp==0 ) continue;
10348 if( zSql==0 ) continue;
10349 if( zAns==0 ) continue;
10350 k = 0;
10351 if( bVerbose>0 ){
10352 printf("%d: %s %s\n", tno, zOp, zSql);
10354 if( cli_strcmp(zOp,"memo")==0 ){
10355 utf8_printf(p->out, "%s\n", zSql);
10356 }else
10357 if( cli_strcmp(zOp,"run")==0 ){
10358 char *zErrMsg = 0;
10359 str.n = 0;
10360 str.z[0] = 0;
10361 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10362 nTest++;
10363 if( bVerbose ){
10364 utf8_printf(p->out, "Result: %s\n", str.z);
10366 if( rc || zErrMsg ){
10367 nErr++;
10368 rc = 1;
10369 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10370 sqlite3_free(zErrMsg);
10371 }else if( cli_strcmp(zAns,str.z)!=0 ){
10372 nErr++;
10373 rc = 1;
10374 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10375 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
10377 }else
10379 utf8_printf(stderr,
10380 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10381 rc = 1;
10382 break;
10384 } /* End loop over rows of content from SELFTEST */
10385 sqlite3_finalize(pStmt);
10386 } /* End loop over k */
10387 freeText(&str);
10388 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10389 }else
10391 if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
10392 if( nArg<2 || nArg>3 ){
10393 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10394 rc = 1;
10396 if( nArg>=2 ){
10397 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10398 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10400 if( nArg>=3 ){
10401 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10402 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10404 }else
10406 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
10407 const char *zLike = 0; /* Which table to checksum. 0 means everything */
10408 int i; /* Loop counter */
10409 int bSchema = 0; /* Also hash the schema */
10410 int bSeparate = 0; /* Hash each table separately */
10411 int iSize = 224; /* Hash algorithm to use */
10412 int bDebug = 0; /* Only show the query that would have run */
10413 sqlite3_stmt *pStmt; /* For querying tables names */
10414 char *zSql; /* SQL to be run */
10415 char *zSep; /* Separator */
10416 ShellText sSql; /* Complete SQL for the query to run the hash */
10417 ShellText sQuery; /* Set of queries used to read all content */
10418 open_db(p, 0);
10419 for(i=1; i<nArg; i++){
10420 const char *z = azArg[i];
10421 if( z[0]=='-' ){
10422 z++;
10423 if( z[0]=='-' ) z++;
10424 if( cli_strcmp(z,"schema")==0 ){
10425 bSchema = 1;
10426 }else
10427 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
10428 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
10430 iSize = atoi(&z[5]);
10431 }else
10432 if( cli_strcmp(z,"debug")==0 ){
10433 bDebug = 1;
10434 }else
10436 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10437 azArg[i], azArg[0]);
10438 showHelp(p->out, azArg[0]);
10439 rc = 1;
10440 goto meta_command_exit;
10442 }else if( zLike ){
10443 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10444 rc = 1;
10445 goto meta_command_exit;
10446 }else{
10447 zLike = z;
10448 bSeparate = 1;
10449 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10452 if( bSchema ){
10453 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10454 " WHERE type='table' AND coalesce(rootpage,0)>1"
10455 " UNION ALL SELECT 'sqlite_schema'"
10456 " ORDER BY 1 collate nocase";
10457 }else{
10458 zSql = "SELECT lower(name) as tname FROM sqlite_schema"
10459 " WHERE type='table' AND coalesce(rootpage,0)>1"
10460 " AND name NOT LIKE 'sqlite_%'"
10461 " ORDER BY 1 collate nocase";
10463 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10464 initText(&sQuery);
10465 initText(&sSql);
10466 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10467 zSep = "VALUES(";
10468 while( SQLITE_ROW==sqlite3_step(pStmt) ){
10469 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10470 if( zTab==0 ) continue;
10471 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10472 if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
10473 appendText(&sQuery,"SELECT * FROM ", 0);
10474 appendText(&sQuery,zTab,'"');
10475 appendText(&sQuery," NOT INDEXED;", 0);
10476 }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
10477 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10478 " ORDER BY name;", 0);
10479 }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
10480 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10481 " ORDER BY name;", 0);
10482 }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
10483 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10484 " ORDER BY tbl,idx;", 0);
10485 }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
10486 appendText(&sQuery, "SELECT * FROM ", 0);
10487 appendText(&sQuery, zTab, 0);
10488 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10490 appendText(&sSql, zSep, 0);
10491 appendText(&sSql, sQuery.z, '\'');
10492 sQuery.n = 0;
10493 appendText(&sSql, ",", 0);
10494 appendText(&sSql, zTab, '\'');
10495 zSep = "),(";
10497 sqlite3_finalize(pStmt);
10498 if( bSeparate ){
10499 zSql = sqlite3_mprintf(
10500 "%s))"
10501 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10502 " FROM [sha3sum$query]",
10503 sSql.z, iSize);
10504 }else{
10505 zSql = sqlite3_mprintf(
10506 "%s))"
10507 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10508 " FROM [sha3sum$query]",
10509 sSql.z, iSize);
10511 shell_check_oom(zSql);
10512 freeText(&sQuery);
10513 freeText(&sSql);
10514 if( bDebug ){
10515 utf8_printf(p->out, "%s\n", zSql);
10516 }else{
10517 shell_exec(p, zSql, 0);
10519 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10521 int lrc;
10522 char *zRevText = /* Query for reversible to-blob-to-text check */
10523 "SELECT lower(name) as tname FROM sqlite_schema\n"
10524 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10525 "AND name NOT LIKE 'sqlite_%%'%s\n"
10526 "ORDER BY 1 collate nocase";
10527 zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
10528 zRevText = sqlite3_mprintf(
10529 /* lower-case query is first run, producing upper-case query. */
10530 "with tabcols as materialized(\n"
10531 "select tname, cname\n"
10532 "from ("
10533 " select ss.tname as tname, ti.name as cname\n"
10534 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10535 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10536 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10537 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10538 "FROM '||tname||' WHERE '\n"
10539 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10540 "|| ' AND typeof('||cname||')=''text'' ',\n"
10541 "' OR ') as query, tname from tabcols group by tname)"
10542 , zRevText);
10543 shell_check_oom(zRevText);
10544 if( bDebug ) utf8_printf(p->out, "%s\n", zRevText);
10545 lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
10546 if( lrc!=SQLITE_OK ){
10547 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
10548 ** user does cruel and unnatural things like ".limit expr_depth 0". */
10549 rc = 1;
10550 }else{
10551 if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
10552 lrc = SQLITE_ROW==sqlite3_step(pStmt);
10553 if( lrc ){
10554 const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
10555 sqlite3_stmt *pCheckStmt;
10556 lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
10557 if( bDebug ) utf8_printf(p->out, "%s\n", zGenQuery);
10558 if( lrc!=SQLITE_OK ){
10559 rc = 1;
10560 }else{
10561 if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
10562 double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
10563 if( countIrreversible>0 ){
10564 int sz = (int)(countIrreversible + 0.5);
10565 utf8_printf(stderr,
10566 "Digest includes %d invalidly encoded text field%s.\n",
10567 sz, (sz>1)? "s": "");
10570 sqlite3_finalize(pCheckStmt);
10572 sqlite3_finalize(pStmt);
10575 if( rc ) utf8_printf(stderr, ".sha3sum failed.\n");
10576 sqlite3_free(zRevText);
10578 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10579 sqlite3_free(zSql);
10580 }else
10582 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10583 if( c=='s'
10584 && (cli_strncmp(azArg[0], "shell", n)==0
10585 || cli_strncmp(azArg[0],"system",n)==0)
10587 char *zCmd;
10588 int i, x;
10589 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10590 if( nArg<2 ){
10591 raw_printf(stderr, "Usage: .system COMMAND\n");
10592 rc = 1;
10593 goto meta_command_exit;
10595 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10596 for(i=2; i<nArg && zCmd!=0; i++){
10597 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10598 zCmd, azArg[i]);
10600 x = zCmd!=0 ? system(zCmd) : 1;
10601 sqlite3_free(zCmd);
10602 if( x ) raw_printf(stderr, "System command returns %d\n", x);
10603 }else
10604 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10606 if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
10607 static const char *azBool[] = { "off", "on", "trigger", "full"};
10608 const char *zOut;
10609 int i;
10610 if( nArg!=1 ){
10611 raw_printf(stderr, "Usage: .show\n");
10612 rc = 1;
10613 goto meta_command_exit;
10615 utf8_printf(p->out, "%12.12s: %s\n","echo",
10616 azBool[ShellHasFlag(p, SHFLG_Echo)]);
10617 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10618 utf8_printf(p->out, "%12.12s: %s\n","explain",
10619 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10620 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10621 if( p->mode==MODE_Column
10622 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10624 utf8_printf
10625 (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10626 modeDescr[p->mode], p->cmOpts.iWrap,
10627 p->cmOpts.bWordWrap ? "on" : "off",
10628 p->cmOpts.bQuote ? "" : "no");
10629 }else{
10630 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10632 utf8_printf(p->out, "%12.12s: ", "nullvalue");
10633 output_c_string(p->out, p->nullValue);
10634 raw_printf(p->out, "\n");
10635 utf8_printf(p->out,"%12.12s: %s\n","output",
10636 strlen30(p->outfile) ? p->outfile : "stdout");
10637 utf8_printf(p->out,"%12.12s: ", "colseparator");
10638 output_c_string(p->out, p->colSeparator);
10639 raw_printf(p->out, "\n");
10640 utf8_printf(p->out,"%12.12s: ", "rowseparator");
10641 output_c_string(p->out, p->rowSeparator);
10642 raw_printf(p->out, "\n");
10643 switch( p->statsOn ){
10644 case 0: zOut = "off"; break;
10645 default: zOut = "on"; break;
10646 case 2: zOut = "stmt"; break;
10647 case 3: zOut = "vmstep"; break;
10649 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10650 utf8_printf(p->out, "%12.12s: ", "width");
10651 for (i=0;i<p->nWidth;i++) {
10652 raw_printf(p->out, "%d ", p->colWidth[i]);
10654 raw_printf(p->out, "\n");
10655 utf8_printf(p->out, "%12.12s: %s\n", "filename",
10656 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10657 }else
10659 if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
10660 if( nArg==2 ){
10661 if( cli_strcmp(azArg[1],"stmt")==0 ){
10662 p->statsOn = 2;
10663 }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
10664 p->statsOn = 3;
10665 }else{
10666 p->statsOn = (u8)booleanValue(azArg[1]);
10668 }else if( nArg==1 ){
10669 display_stats(p->db, p, 0);
10670 }else{
10671 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10672 rc = 1;
10674 }else
10676 if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
10677 || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
10678 || cli_strncmp(azArg[0], "indexes", n)==0) )
10680 sqlite3_stmt *pStmt;
10681 char **azResult;
10682 int nRow, nAlloc;
10683 int ii;
10684 ShellText s;
10685 initText(&s);
10686 open_db(p, 0);
10687 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10688 if( rc ){
10689 sqlite3_finalize(pStmt);
10690 return shellDatabaseError(p->db);
10693 if( nArg>2 && c=='i' ){
10694 /* It is an historical accident that the .indexes command shows an error
10695 ** when called with the wrong number of arguments whereas the .tables
10696 ** command does not. */
10697 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10698 rc = 1;
10699 sqlite3_finalize(pStmt);
10700 goto meta_command_exit;
10702 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10703 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10704 if( zDbName==0 ) continue;
10705 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10706 if( sqlite3_stricmp(zDbName, "main")==0 ){
10707 appendText(&s, "SELECT name FROM ", 0);
10708 }else{
10709 appendText(&s, "SELECT ", 0);
10710 appendText(&s, zDbName, '\'');
10711 appendText(&s, "||'.'||name FROM ", 0);
10713 appendText(&s, zDbName, '"');
10714 appendText(&s, ".sqlite_schema ", 0);
10715 if( c=='t' ){
10716 appendText(&s," WHERE type IN ('table','view')"
10717 " AND name NOT LIKE 'sqlite_%'"
10718 " AND name LIKE ?1", 0);
10719 }else{
10720 appendText(&s," WHERE type='index'"
10721 " AND tbl_name LIKE ?1", 0);
10724 rc = sqlite3_finalize(pStmt);
10725 if( rc==SQLITE_OK ){
10726 appendText(&s, " ORDER BY 1", 0);
10727 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10729 freeText(&s);
10730 if( rc ) return shellDatabaseError(p->db);
10732 /* Run the SQL statement prepared by the above block. Store the results
10733 ** as an array of nul-terminated strings in azResult[]. */
10734 nRow = nAlloc = 0;
10735 azResult = 0;
10736 if( nArg>1 ){
10737 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10738 }else{
10739 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10741 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10742 if( nRow>=nAlloc ){
10743 char **azNew;
10744 int n2 = nAlloc*2 + 10;
10745 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10746 shell_check_oom(azNew);
10747 nAlloc = n2;
10748 azResult = azNew;
10750 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10751 shell_check_oom(azResult[nRow]);
10752 nRow++;
10754 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10755 rc = shellDatabaseError(p->db);
10758 /* Pretty-print the contents of array azResult[] to the output */
10759 if( rc==0 && nRow>0 ){
10760 int len, maxlen = 0;
10761 int i, j;
10762 int nPrintCol, nPrintRow;
10763 for(i=0; i<nRow; i++){
10764 len = strlen30(azResult[i]);
10765 if( len>maxlen ) maxlen = len;
10767 nPrintCol = 80/(maxlen+2);
10768 if( nPrintCol<1 ) nPrintCol = 1;
10769 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10770 for(i=0; i<nPrintRow; i++){
10771 for(j=i; j<nRow; j+=nPrintRow){
10772 char *zSp = j<nPrintRow ? "" : " ";
10773 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10774 azResult[j] ? azResult[j]:"");
10776 raw_printf(p->out, "\n");
10780 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10781 sqlite3_free(azResult);
10782 }else
10784 #ifndef SQLITE_SHELL_FIDDLE
10785 /* Begin redirecting output to the file "testcase-out.txt" */
10786 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
10787 output_reset(p);
10788 p->out = output_file_open("testcase-out.txt", 0);
10789 if( p->out==0 ){
10790 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10792 if( nArg>=2 ){
10793 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10794 }else{
10795 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10797 }else
10798 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10800 #ifndef SQLITE_UNTESTABLE
10801 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
10802 static const struct {
10803 const char *zCtrlName; /* Name of a test-control option */
10804 int ctrlCode; /* Integer code for that option */
10805 int unSafe; /* Not valid for --safe mode */
10806 const char *zUsage; /* Usage notes */
10807 } aCtrl[] = {
10808 {"always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" },
10809 {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" },
10810 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10811 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10812 {"byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" },
10813 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
10814 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10815 {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10816 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
10817 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
10818 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
10819 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
10820 #ifdef YYCOVERAGE
10821 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
10822 #endif
10823 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " },
10824 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" },
10825 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" },
10826 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" },
10827 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" },
10828 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" },
10829 {"tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" },
10831 int testctrl = -1;
10832 int iCtrl = -1;
10833 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10834 int isOk = 0;
10835 int i, n2;
10836 const char *zCmd = 0;
10838 if( !ShellHasFlag(p,SHFLG_TestingMode) ){
10839 utf8_printf(stderr, ".%s unavailable without --unsafe-testing\n",
10840 "testctrl");
10841 rc = 1;
10842 goto meta_command_exit;
10844 open_db(p, 0);
10845 zCmd = nArg>=2 ? azArg[1] : "help";
10847 /* The argument can optionally begin with "-" or "--" */
10848 if( zCmd[0]=='-' && zCmd[1] ){
10849 zCmd++;
10850 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10853 /* --help lists all test-controls */
10854 if( cli_strcmp(zCmd,"help")==0 ){
10855 utf8_printf(p->out, "Available test-controls:\n");
10856 for(i=0; i<ArraySize(aCtrl); i++){
10857 utf8_printf(p->out, " .testctrl %s %s\n",
10858 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10860 rc = 1;
10861 goto meta_command_exit;
10864 /* convert testctrl text option to value. allow any unique prefix
10865 ** of the option name, or a numerical value. */
10866 n2 = strlen30(zCmd);
10867 for(i=0; i<ArraySize(aCtrl); i++){
10868 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10869 if( testctrl<0 ){
10870 testctrl = aCtrl[i].ctrlCode;
10871 iCtrl = i;
10872 }else{
10873 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10874 "Use \".testctrl --help\" for help\n", zCmd);
10875 rc = 1;
10876 goto meta_command_exit;
10880 if( testctrl<0 ){
10881 utf8_printf(stderr,"Error: unknown test-control: %s\n"
10882 "Use \".testctrl --help\" for help\n", zCmd);
10883 }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10884 utf8_printf(stderr,
10885 "line %d: \".testctrl %s\" may not be used in safe mode\n",
10886 p->lineno, aCtrl[iCtrl].zCtrlName);
10887 exit(1);
10888 }else{
10889 switch(testctrl){
10891 /* sqlite3_test_control(int, db, int) */
10892 case SQLITE_TESTCTRL_OPTIMIZATIONS:
10893 if( nArg==3 ){
10894 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10895 rc2 = sqlite3_test_control(testctrl, p->db, opt);
10896 isOk = 3;
10898 break;
10900 /* sqlite3_test_control(int) */
10901 case SQLITE_TESTCTRL_PRNG_SAVE:
10902 case SQLITE_TESTCTRL_PRNG_RESTORE:
10903 case SQLITE_TESTCTRL_BYTEORDER:
10904 if( nArg==2 ){
10905 rc2 = sqlite3_test_control(testctrl);
10906 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10908 break;
10910 /* sqlite3_test_control(int, uint) */
10911 case SQLITE_TESTCTRL_PENDING_BYTE:
10912 if( nArg==3 ){
10913 unsigned int opt = (unsigned int)integerValue(azArg[2]);
10914 rc2 = sqlite3_test_control(testctrl, opt);
10915 isOk = 3;
10917 break;
10919 /* sqlite3_test_control(int, int, sqlite3*) */
10920 case SQLITE_TESTCTRL_PRNG_SEED:
10921 if( nArg==3 || nArg==4 ){
10922 int ii = (int)integerValue(azArg[2]);
10923 sqlite3 *db;
10924 if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
10925 sqlite3_randomness(sizeof(ii),&ii);
10926 printf("-- random seed: %d\n", ii);
10928 if( nArg==3 ){
10929 db = 0;
10930 }else{
10931 db = p->db;
10932 /* Make sure the schema has been loaded */
10933 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10935 rc2 = sqlite3_test_control(testctrl, ii, db);
10936 isOk = 3;
10938 break;
10940 /* sqlite3_test_control(int, int) */
10941 case SQLITE_TESTCTRL_ASSERT:
10942 case SQLITE_TESTCTRL_ALWAYS:
10943 if( nArg==3 ){
10944 int opt = booleanValue(azArg[2]);
10945 rc2 = sqlite3_test_control(testctrl, opt);
10946 isOk = 1;
10948 break;
10950 /* sqlite3_test_control(int, int) */
10951 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10952 case SQLITE_TESTCTRL_NEVER_CORRUPT:
10953 if( nArg==3 ){
10954 int opt = booleanValue(azArg[2]);
10955 rc2 = sqlite3_test_control(testctrl, opt);
10956 isOk = 3;
10958 break;
10960 /* sqlite3_test_control(sqlite3*) */
10961 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10962 rc2 = sqlite3_test_control(testctrl, p->db);
10963 isOk = 3;
10964 break;
10966 case SQLITE_TESTCTRL_IMPOSTER:
10967 if( nArg==5 ){
10968 rc2 = sqlite3_test_control(testctrl, p->db,
10969 azArg[2],
10970 integerValue(azArg[3]),
10971 integerValue(azArg[4]));
10972 isOk = 3;
10974 break;
10976 case SQLITE_TESTCTRL_SEEK_COUNT: {
10977 u64 x = 0;
10978 rc2 = sqlite3_test_control(testctrl, p->db, &x);
10979 utf8_printf(p->out, "%llu\n", x);
10980 isOk = 3;
10981 break;
10984 #ifdef YYCOVERAGE
10985 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10986 if( nArg==2 ){
10987 sqlite3_test_control(testctrl, p->out);
10988 isOk = 3;
10990 break;
10992 #endif
10993 #ifdef SQLITE_DEBUG
10994 case SQLITE_TESTCTRL_TUNE: {
10995 if( nArg==4 ){
10996 int id = (int)integerValue(azArg[2]);
10997 int val = (int)integerValue(azArg[3]);
10998 sqlite3_test_control(testctrl, id, &val);
10999 isOk = 3;
11000 }else if( nArg==3 ){
11001 int id = (int)integerValue(azArg[2]);
11002 sqlite3_test_control(testctrl, -id, &rc2);
11003 isOk = 1;
11004 }else if( nArg==2 ){
11005 int id = 1;
11006 while(1){
11007 int val = 0;
11008 rc2 = sqlite3_test_control(testctrl, -id, &val);
11009 if( rc2!=SQLITE_OK ) break;
11010 if( id>1 ) utf8_printf(p->out, " ");
11011 utf8_printf(p->out, "%d: %d", id, val);
11012 id++;
11014 if( id>1 ) utf8_printf(p->out, "\n");
11015 isOk = 3;
11017 break;
11019 #endif
11020 case SQLITE_TESTCTRL_SORTER_MMAP:
11021 if( nArg==3 ){
11022 int opt = (unsigned int)integerValue(azArg[2]);
11023 rc2 = sqlite3_test_control(testctrl, p->db, opt);
11024 isOk = 3;
11026 break;
11029 if( isOk==0 && iCtrl>=0 ){
11030 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11031 rc = 1;
11032 }else if( isOk==1 ){
11033 raw_printf(p->out, "%d\n", rc2);
11034 }else if( isOk==2 ){
11035 raw_printf(p->out, "0x%08x\n", rc2);
11037 }else
11038 #endif /* !defined(SQLITE_UNTESTABLE) */
11040 if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
11041 open_db(p, 0);
11042 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11043 }else
11045 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
11046 if( nArg==2 ){
11047 enableTimer = booleanValue(azArg[1]);
11048 if( enableTimer && !HAS_TIMER ){
11049 raw_printf(stderr, "Error: timer not available on this system.\n");
11050 enableTimer = 0;
11052 }else{
11053 raw_printf(stderr, "Usage: .timer on|off\n");
11054 rc = 1;
11056 }else
11058 #ifndef SQLITE_OMIT_TRACE
11059 if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
11060 int mType = 0;
11061 int jj;
11062 open_db(p, 0);
11063 for(jj=1; jj<nArg; jj++){
11064 const char *z = azArg[jj];
11065 if( z[0]=='-' ){
11066 if( optionMatch(z, "expanded") ){
11067 p->eTraceType = SHELL_TRACE_EXPANDED;
11069 #ifdef SQLITE_ENABLE_NORMALIZE
11070 else if( optionMatch(z, "normalized") ){
11071 p->eTraceType = SHELL_TRACE_NORMALIZED;
11073 #endif
11074 else if( optionMatch(z, "plain") ){
11075 p->eTraceType = SHELL_TRACE_PLAIN;
11077 else if( optionMatch(z, "profile") ){
11078 mType |= SQLITE_TRACE_PROFILE;
11080 else if( optionMatch(z, "row") ){
11081 mType |= SQLITE_TRACE_ROW;
11083 else if( optionMatch(z, "stmt") ){
11084 mType |= SQLITE_TRACE_STMT;
11086 else if( optionMatch(z, "close") ){
11087 mType |= SQLITE_TRACE_CLOSE;
11089 else {
11090 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11091 rc = 1;
11092 goto meta_command_exit;
11094 }else{
11095 output_file_close(p->traceOut);
11096 p->traceOut = output_file_open(z, 0);
11099 if( p->traceOut==0 ){
11100 sqlite3_trace_v2(p->db, 0, 0, 0);
11101 }else{
11102 if( mType==0 ) mType = SQLITE_TRACE_STMT;
11103 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11105 }else
11106 #endif /* !defined(SQLITE_OMIT_TRACE) */
11108 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11109 if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
11110 int ii;
11111 int lenOpt;
11112 char *zOpt;
11113 if( nArg<2 ){
11114 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11115 rc = 1;
11116 goto meta_command_exit;
11118 open_db(p, 0);
11119 zOpt = azArg[1];
11120 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11121 lenOpt = (int)strlen(zOpt);
11122 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11123 assert( azArg[nArg]==0 );
11124 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11125 }else{
11126 for(ii=1; ii<nArg; ii++){
11127 sqlite3_create_module(p->db, azArg[ii], 0, 0);
11130 }else
11131 #endif
11133 #if SQLITE_USER_AUTHENTICATION
11134 if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
11135 if( nArg<2 ){
11136 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11137 rc = 1;
11138 goto meta_command_exit;
11140 open_db(p, 0);
11141 if( cli_strcmp(azArg[1],"login")==0 ){
11142 if( nArg!=4 ){
11143 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11144 rc = 1;
11145 goto meta_command_exit;
11147 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11148 strlen30(azArg[3]));
11149 if( rc ){
11150 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11151 rc = 1;
11153 }else if( cli_strcmp(azArg[1],"add")==0 ){
11154 if( nArg!=5 ){
11155 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11156 rc = 1;
11157 goto meta_command_exit;
11159 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11160 booleanValue(azArg[4]));
11161 if( rc ){
11162 raw_printf(stderr, "User-Add failed: %d\n", rc);
11163 rc = 1;
11165 }else if( cli_strcmp(azArg[1],"edit")==0 ){
11166 if( nArg!=5 ){
11167 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11168 rc = 1;
11169 goto meta_command_exit;
11171 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11172 booleanValue(azArg[4]));
11173 if( rc ){
11174 raw_printf(stderr, "User-Edit failed: %d\n", rc);
11175 rc = 1;
11177 }else if( cli_strcmp(azArg[1],"delete")==0 ){
11178 if( nArg!=3 ){
11179 raw_printf(stderr, "Usage: .user delete USER\n");
11180 rc = 1;
11181 goto meta_command_exit;
11183 rc = sqlite3_user_delete(p->db, azArg[2]);
11184 if( rc ){
11185 raw_printf(stderr, "User-Delete failed: %d\n", rc);
11186 rc = 1;
11188 }else{
11189 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11190 rc = 1;
11191 goto meta_command_exit;
11193 }else
11194 #endif /* SQLITE_USER_AUTHENTICATION */
11196 if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
11197 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11198 sqlite3_libversion(), sqlite3_sourceid());
11199 #if SQLITE_HAVE_ZLIB
11200 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11201 #endif
11202 #define CTIMEOPT_VAL_(opt) #opt
11203 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11204 #if defined(__clang__) && defined(__clang_major__)
11205 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11206 CTIMEOPT_VAL(__clang_minor__) "."
11207 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11208 #elif defined(_MSC_VER)
11209 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11210 #elif defined(__GNUC__) && defined(__VERSION__)
11211 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11212 #endif
11213 }else
11215 if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
11216 const char *zDbName = nArg==2 ? azArg[1] : "main";
11217 sqlite3_vfs *pVfs = 0;
11218 if( p->db ){
11219 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11220 if( pVfs ){
11221 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
11222 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
11223 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
11224 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11227 }else
11229 if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
11230 sqlite3_vfs *pVfs;
11231 sqlite3_vfs *pCurrent = 0;
11232 if( p->db ){
11233 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11235 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11236 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
11237 pVfs==pCurrent ? " <--- CURRENT" : "");
11238 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
11239 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
11240 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11241 if( pVfs->pNext ){
11242 raw_printf(p->out, "-----------------------------------\n");
11245 }else
11247 if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
11248 const char *zDbName = nArg==2 ? azArg[1] : "main";
11249 char *zVfsName = 0;
11250 if( p->db ){
11251 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11252 if( zVfsName ){
11253 utf8_printf(p->out, "%s\n", zVfsName);
11254 sqlite3_free(zVfsName);
11257 }else
11259 if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
11260 unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11261 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11262 }else
11264 if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
11265 int j;
11266 assert( nArg<=ArraySize(azArg) );
11267 p->nWidth = nArg-1;
11268 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11269 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11270 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11271 for(j=1; j<nArg; j++){
11272 p->colWidth[j-1] = (int)integerValue(azArg[j]);
11274 }else
11277 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11278 " \"%s\". Enter \".help\" for help\n", azArg[0]);
11279 rc = 1;
11282 meta_command_exit:
11283 if( p->outCount ){
11284 p->outCount--;
11285 if( p->outCount==0 ) output_reset(p);
11287 p->bSafeMode = p->bSafeModePersist;
11288 return rc;
11291 /* Line scan result and intermediate states (supporting scan resumption)
11293 #ifndef CHAR_BIT
11294 # define CHAR_BIT 8
11295 #endif
11296 typedef enum {
11297 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11298 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11299 QSS_Start = 0
11300 } QuickScanState;
11301 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11302 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11303 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11304 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11305 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11308 ** Scan line for classification to guide shell's handling.
11309 ** The scan is resumable for subsequent lines when prior
11310 ** return values are passed as the 2nd argument.
11312 static QuickScanState quickscan(char *zLine, QuickScanState qss,
11313 SCAN_TRACKER_REFTYPE pst){
11314 char cin;
11315 char cWait = (char)qss; /* intentional narrowing loss */
11316 if( cWait==0 ){
11317 PlainScan:
11318 assert( cWait==0 );
11319 while( (cin = *zLine++)!=0 ){
11320 if( IsSpace(cin) )
11321 continue;
11322 switch (cin){
11323 case '-':
11324 if( *zLine!='-' )
11325 break;
11326 while((cin = *++zLine)!=0 )
11327 if( cin=='\n')
11328 goto PlainScan;
11329 return qss;
11330 case ';':
11331 qss |= QSS_EndingSemi;
11332 continue;
11333 case '/':
11334 if( *zLine=='*' ){
11335 ++zLine;
11336 cWait = '*';
11337 CONTINUE_PROMPT_AWAITS(pst, "/*");
11338 qss = QSS_SETV(qss, cWait);
11339 goto TermScan;
11341 break;
11342 case '[':
11343 cin = ']';
11344 deliberate_fall_through;
11345 case '`': case '\'': case '"':
11346 cWait = cin;
11347 qss = QSS_HasDark | cWait;
11348 CONTINUE_PROMPT_AWAITC(pst, cin);
11349 goto TermScan;
11350 case '(':
11351 CONTINUE_PAREN_INCR(pst, 1);
11352 break;
11353 case ')':
11354 CONTINUE_PAREN_INCR(pst, -1);
11355 break;
11356 default:
11357 break;
11359 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11361 }else{
11362 TermScan:
11363 while( (cin = *zLine++)!=0 ){
11364 if( cin==cWait ){
11365 switch( cWait ){
11366 case '*':
11367 if( *zLine != '/' )
11368 continue;
11369 ++zLine;
11370 cWait = 0;
11371 CONTINUE_PROMPT_AWAITC(pst, 0);
11372 qss = QSS_SETV(qss, 0);
11373 goto PlainScan;
11374 case '`': case '\'': case '"':
11375 if(*zLine==cWait){
11376 /* Swallow doubled end-delimiter.*/
11377 ++zLine;
11378 continue;
11380 deliberate_fall_through;
11381 case ']':
11382 cWait = 0;
11383 CONTINUE_PROMPT_AWAITC(pst, 0);
11384 qss = QSS_SETV(qss, 0);
11385 goto PlainScan;
11386 default: assert(0);
11391 return qss;
11395 ** Return TRUE if the line typed in is an SQL command terminator other
11396 ** than a semi-colon. The SQL Server style "go" command is understood
11397 ** as is the Oracle "/".
11399 static int line_is_command_terminator(char *zLine){
11400 while( IsSpace(zLine[0]) ){ zLine++; };
11401 if( zLine[0]=='/' )
11402 zLine += 1; /* Oracle */
11403 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11404 zLine += 2; /* SQL Server */
11405 else
11406 return 0;
11407 return quickscan(zLine, QSS_Start, 0)==QSS_Start;
11411 ** The CLI needs a working sqlite3_complete() to work properly. So error
11412 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11414 #ifdef SQLITE_OMIT_COMPLETE
11415 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11416 #endif
11419 ** Return true if zSql is a complete SQL statement. Return false if it
11420 ** ends in the middle of a string literal or C-style comment.
11422 static int line_is_complete(char *zSql, int nSql){
11423 int rc;
11424 if( zSql==0 ) return 1;
11425 zSql[nSql] = ';';
11426 zSql[nSql+1] = 0;
11427 rc = sqlite3_complete(zSql);
11428 zSql[nSql] = 0;
11429 return rc;
11433 ** Run a single line of SQL. Return the number of errors.
11435 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11436 int rc;
11437 char *zErrMsg = 0;
11439 open_db(p, 0);
11440 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11441 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11442 BEGIN_TIMER;
11443 rc = shell_exec(p, zSql, &zErrMsg);
11444 END_TIMER;
11445 if( rc || zErrMsg ){
11446 char zPrefix[100];
11447 const char *zErrorTail;
11448 const char *zErrorType;
11449 if( zErrMsg==0 ){
11450 zErrorType = "Error";
11451 zErrorTail = sqlite3_errmsg(p->db);
11452 }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
11453 zErrorType = "Parse error";
11454 zErrorTail = &zErrMsg[12];
11455 }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
11456 zErrorType = "Runtime error";
11457 zErrorTail = &zErrMsg[10];
11458 }else{
11459 zErrorType = "Error";
11460 zErrorTail = zErrMsg;
11462 if( in!=0 || !stdin_is_interactive ){
11463 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11464 "%s near line %d:", zErrorType, startline);
11465 }else{
11466 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11468 utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11469 sqlite3_free(zErrMsg);
11470 zErrMsg = 0;
11471 return 1;
11472 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11473 char zLineBuf[2000];
11474 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11475 "changes: %lld total_changes: %lld",
11476 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11477 raw_printf(p->out, "%s\n", zLineBuf);
11479 return 0;
11482 static void echo_group_input(ShellState *p, const char *zDo){
11483 if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11486 #ifdef SQLITE_SHELL_FIDDLE
11488 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11489 ** impl because we need the global shellState and cannot access it from that
11490 ** function without moving lots of code around (creating a larger/messier diff).
11492 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11493 /* Parse the next line from shellState.wasm.zInput. */
11494 const char *zBegin = shellState.wasm.zPos;
11495 const char *z = zBegin;
11496 char *zLine = 0;
11497 i64 nZ = 0;
11499 UNUSED_PARAMETER(in);
11500 UNUSED_PARAMETER(isContinuation);
11501 if(!z || !*z){
11502 return 0;
11504 while(*z && isspace(*z)) ++z;
11505 zBegin = z;
11506 for(; *z && '\n'!=*z; ++nZ, ++z){}
11507 if(nZ>0 && '\r'==zBegin[nZ-1]){
11508 --nZ;
11510 shellState.wasm.zPos = z;
11511 zLine = realloc(zPrior, nZ+1);
11512 shell_check_oom(zLine);
11513 memcpy(zLine, zBegin, nZ);
11514 zLine[nZ] = 0;
11515 return zLine;
11517 #endif /* SQLITE_SHELL_FIDDLE */
11520 ** Read input from *in and process it. If *in==0 then input
11521 ** is interactive - the user is typing it it. Otherwise, input
11522 ** is coming from a file or device. A prompt is issued and history
11523 ** is saved only if input is interactive. An interrupt signal will
11524 ** cause this routine to exit immediately, unless input is interactive.
11526 ** Return the number of errors.
11528 static int process_input(ShellState *p){
11529 char *zLine = 0; /* A single input line */
11530 char *zSql = 0; /* Accumulated SQL text */
11531 i64 nLine; /* Length of current line */
11532 i64 nSql = 0; /* Bytes of zSql[] used */
11533 i64 nAlloc = 0; /* Allocated zSql[] space */
11534 int rc; /* Error code */
11535 int errCnt = 0; /* Number of errors seen */
11536 i64 startline = 0; /* Line number for start of current input */
11537 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11539 if( p->inputNesting==MAX_INPUT_NESTING ){
11540 /* This will be more informative in a later version. */
11541 utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11542 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11543 return 1;
11545 ++p->inputNesting;
11546 p->lineno = 0;
11547 CONTINUE_PROMPT_RESET;
11548 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11549 fflush(p->out);
11550 zLine = one_input_line(p->in, zLine, nSql>0);
11551 if( zLine==0 ){
11552 /* End of input */
11553 if( p->in==0 && stdin_is_interactive ) printf("\n");
11554 break;
11556 if( seenInterrupt ){
11557 if( p->in!=0 ) break;
11558 seenInterrupt = 0;
11560 p->lineno++;
11561 if( QSS_INPLAIN(qss)
11562 && line_is_command_terminator(zLine)
11563 && line_is_complete(zSql, nSql) ){
11564 memcpy(zLine,";",2);
11566 qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
11567 if( QSS_PLAINWHITE(qss) && nSql==0 ){
11568 /* Just swallow single-line whitespace */
11569 echo_group_input(p, zLine);
11570 qss = QSS_Start;
11571 continue;
11573 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11574 CONTINUE_PROMPT_RESET;
11575 echo_group_input(p, zLine);
11576 if( zLine[0]=='.' ){
11577 rc = do_meta_command(zLine, p);
11578 if( rc==2 ){ /* exit requested */
11579 break;
11580 }else if( rc ){
11581 errCnt++;
11584 qss = QSS_Start;
11585 continue;
11587 /* No single-line dispositions remain; accumulate line(s). */
11588 nLine = strlen(zLine);
11589 if( nSql+nLine+2>=nAlloc ){
11590 /* Grow buffer by half-again increments when big. */
11591 nAlloc = nSql+(nSql>>1)+nLine+100;
11592 zSql = realloc(zSql, nAlloc);
11593 shell_check_oom(zSql);
11595 if( nSql==0 ){
11596 i64 i;
11597 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11598 assert( nAlloc>0 && zSql!=0 );
11599 memcpy(zSql, zLine+i, nLine+1-i);
11600 startline = p->lineno;
11601 nSql = nLine-i;
11602 }else{
11603 zSql[nSql++] = '\n';
11604 memcpy(zSql+nSql, zLine, nLine+1);
11605 nSql += nLine;
11607 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11608 echo_group_input(p, zSql);
11609 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11610 CONTINUE_PROMPT_RESET;
11611 nSql = 0;
11612 if( p->outCount ){
11613 output_reset(p);
11614 p->outCount = 0;
11615 }else{
11616 clearTempFile(p);
11618 p->bSafeMode = p->bSafeModePersist;
11619 qss = QSS_Start;
11620 }else if( nSql && QSS_PLAINWHITE(qss) ){
11621 echo_group_input(p, zSql);
11622 nSql = 0;
11623 qss = QSS_Start;
11626 if( nSql ){
11627 /* This may be incomplete. Let the SQL parser deal with that. */
11628 echo_group_input(p, zSql);
11629 errCnt += runOneSqlLine(p, zSql, p->in, startline);
11630 CONTINUE_PROMPT_RESET;
11632 free(zSql);
11633 free(zLine);
11634 --p->inputNesting;
11635 return errCnt>0;
11639 ** Return a pathname which is the user's home directory. A
11640 ** 0 return indicates an error of some kind.
11642 static char *find_home_dir(int clearFlag){
11643 static char *home_dir = NULL;
11644 if( clearFlag ){
11645 free(home_dir);
11646 home_dir = 0;
11647 return 0;
11649 if( home_dir ) return home_dir;
11651 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11652 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11654 struct passwd *pwent;
11655 uid_t uid = getuid();
11656 if( (pwent=getpwuid(uid)) != NULL) {
11657 home_dir = pwent->pw_dir;
11660 #endif
11662 #if defined(_WIN32_WCE)
11663 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11665 home_dir = "/";
11666 #else
11668 #if defined(_WIN32) || defined(WIN32)
11669 if (!home_dir) {
11670 home_dir = getenv("USERPROFILE");
11672 #endif
11674 if (!home_dir) {
11675 home_dir = getenv("HOME");
11678 #if defined(_WIN32) || defined(WIN32)
11679 if (!home_dir) {
11680 char *zDrive, *zPath;
11681 int n;
11682 zDrive = getenv("HOMEDRIVE");
11683 zPath = getenv("HOMEPATH");
11684 if( zDrive && zPath ){
11685 n = strlen30(zDrive) + strlen30(zPath) + 1;
11686 home_dir = malloc( n );
11687 if( home_dir==0 ) return 0;
11688 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11689 return home_dir;
11691 home_dir = "c:\\";
11693 #endif
11695 #endif /* !_WIN32_WCE */
11697 if( home_dir ){
11698 i64 n = strlen(home_dir) + 1;
11699 char *z = malloc( n );
11700 if( z ) memcpy(z, home_dir, n);
11701 home_dir = z;
11704 return home_dir;
11708 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11709 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11710 ** the path to it, else return 0. The result is cached for
11711 ** subsequent calls.
11713 static const char *find_xdg_config(void){
11714 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11715 || defined(__RTP__) || defined(_WRS_KERNEL)
11716 return 0;
11717 #else
11718 static int alreadyTried = 0;
11719 static char *zConfig = 0;
11720 const char *zXdgHome;
11722 if( alreadyTried!=0 ){
11723 return zConfig;
11725 alreadyTried = 1;
11726 zXdgHome = getenv("XDG_CONFIG_HOME");
11727 if( zXdgHome==0 ){
11728 return 0;
11730 zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
11731 shell_check_oom(zConfig);
11732 if( access(zConfig,0)!=0 ){
11733 sqlite3_free(zConfig);
11734 zConfig = 0;
11736 return zConfig;
11737 #endif
11741 ** Read input from the file given by sqliterc_override. Or if that
11742 ** parameter is NULL, take input from the first of find_xdg_config()
11743 ** or ~/.sqliterc which is found.
11745 ** Returns the number of errors.
11747 static void process_sqliterc(
11748 ShellState *p, /* Configuration data */
11749 const char *sqliterc_override /* Name of config file. NULL to use default */
11751 char *home_dir = NULL;
11752 const char *sqliterc = sqliterc_override;
11753 char *zBuf = 0;
11754 FILE *inSaved = p->in;
11755 int savedLineno = p->lineno;
11757 if( sqliterc == NULL ){
11758 sqliterc = find_xdg_config();
11760 if( sqliterc == NULL ){
11761 home_dir = find_home_dir(0);
11762 if( home_dir==0 ){
11763 raw_printf(stderr, "-- warning: cannot find home directory;"
11764 " cannot read ~/.sqliterc\n");
11765 return;
11767 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11768 shell_check_oom(zBuf);
11769 sqliterc = zBuf;
11771 p->in = fopen(sqliterc,"rb");
11772 if( p->in ){
11773 if( stdin_is_interactive ){
11774 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11776 if( process_input(p) && bail_on_error ) exit(1);
11777 fclose(p->in);
11778 }else if( sqliterc_override!=0 ){
11779 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11780 if( bail_on_error ) exit(1);
11782 p->in = inSaved;
11783 p->lineno = savedLineno;
11784 sqlite3_free(zBuf);
11788 ** Show available command line options
11790 static const char zOptions[] =
11791 " -- treat no subsequent arguments as options\n"
11792 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11793 " -A ARGS... run \".archive ARGS\" and exit\n"
11794 #endif
11795 " -append append the database to the end of the file\n"
11796 " -ascii set output mode to 'ascii'\n"
11797 " -bail stop after hitting an error\n"
11798 " -batch force batch I/O\n"
11799 " -box set output mode to 'box'\n"
11800 " -column set output mode to 'column'\n"
11801 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11802 " -csv set output mode to 'csv'\n"
11803 #if !defined(SQLITE_OMIT_DESERIALIZE)
11804 " -deserialize open the database using sqlite3_deserialize()\n"
11805 #endif
11806 " -echo print inputs before execution\n"
11807 " -init FILENAME read/process named file\n"
11808 " -[no]header turn headers on or off\n"
11809 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11810 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11811 #endif
11812 " -help show this message\n"
11813 " -html set output mode to HTML\n"
11814 " -interactive force interactive I/O\n"
11815 " -json set output mode to 'json'\n"
11816 " -line set output mode to 'line'\n"
11817 " -list set output mode to 'list'\n"
11818 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11819 " -markdown set output mode to 'markdown'\n"
11820 #if !defined(SQLITE_OMIT_DESERIALIZE)
11821 " -maxsize N maximum size for a --deserialize database\n"
11822 #endif
11823 " -memtrace trace all memory allocations and deallocations\n"
11824 " -mmap N default mmap size set to N\n"
11825 #ifdef SQLITE_ENABLE_MULTIPLEX
11826 " -multiplex enable the multiplexor VFS\n"
11827 #endif
11828 " -newline SEP set output row separator. Default: '\\n'\n"
11829 " -nofollow refuse to open symbolic links to database files\n"
11830 " -nonce STRING set the safe-mode escape nonce\n"
11831 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11832 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11833 " -quote set output mode to 'quote'\n"
11834 " -readonly open the database read-only\n"
11835 " -safe enable safe-mode\n"
11836 " -separator SEP set output column separator. Default: '|'\n"
11837 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11838 " -sorterref SIZE sorter references threshold size\n"
11839 #endif
11840 " -stats print memory stats before each finalize\n"
11841 " -table set output mode to 'table'\n"
11842 " -tabs set output mode to 'tabs'\n"
11843 " -unsafe-testing allow unsafe commands and modes for testing\n"
11844 #if SHELL_WIN_UTF8_OPT
11845 " -utf8 setup interactive console code page for UTF-8\n"
11846 #endif
11847 " -version show SQLite version\n"
11848 " -vfs NAME use NAME as the default VFS\n"
11849 #ifdef SQLITE_ENABLE_VFSTRACE
11850 " -vfstrace enable tracing of all VFS calls\n"
11851 #endif
11852 #ifdef SQLITE_HAVE_ZLIB
11853 " -zip open the file as a ZIP Archive\n"
11854 #endif
11856 static void usage(int showDetail){
11857 utf8_printf(stderr,
11858 "Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
11859 "FILENAME is the name of an SQLite database. A new database is created\n"
11860 "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
11861 if( showDetail ){
11862 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11863 }else{
11864 raw_printf(stderr, "Use the -help option for additional information\n");
11866 exit(1);
11870 ** Internal check: Verify that the SQLite is uninitialized. Print a
11871 ** error message if it is initialized.
11873 static void verify_uninitialized(void){
11874 if( sqlite3_config(-1)==SQLITE_MISUSE ){
11875 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11876 " initialization.\n");
11881 ** Initialize the state information in data
11883 static void main_init(ShellState *data) {
11884 memset(data, 0, sizeof(*data));
11885 data->normalMode = data->cMode = data->mode = MODE_List;
11886 data->autoExplain = 1;
11887 data->pAuxDb = &data->aAuxDb[0];
11888 memcpy(data->colSeparator,SEP_Column, 2);
11889 memcpy(data->rowSeparator,SEP_Row, 2);
11890 data->showHeader = 0;
11891 data->shellFlgs = SHFLG_Lookaside;
11892 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11893 #if !defined(SQLITE_SHELL_FIDDLE)
11894 verify_uninitialized();
11895 #endif
11896 sqlite3_config(SQLITE_CONFIG_URI, 1);
11897 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11898 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11899 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
11903 ** Output text to the console in a font that attracts extra attention.
11905 #ifdef _WIN32
11906 static void printBold(const char *zText){
11907 #if !SQLITE_OS_WINRT
11908 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11909 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11910 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11911 SetConsoleTextAttribute(out,
11912 FOREGROUND_RED|FOREGROUND_INTENSITY
11914 #endif
11915 printf("%s", zText);
11916 #if !SQLITE_OS_WINRT
11917 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11918 #endif
11920 #else
11921 static void printBold(const char *zText){
11922 printf("\033[1m%s\033[0m", zText);
11924 #endif
11927 ** Get the argument to an --option. Throw an error and die if no argument
11928 ** is available.
11930 static char *cmdline_option_value(int argc, char **argv, int i){
11931 if( i==argc ){
11932 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11933 argv[0], argv[argc-1]);
11934 exit(1);
11936 return argv[i];
11939 static void sayAbnormalExit(void){
11940 if( seenInterrupt ) fprintf(stderr, "Program interrupted.\n");
11943 #ifndef SQLITE_SHELL_IS_UTF8
11944 # if (defined(_WIN32) || defined(WIN32)) \
11945 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11946 # define SQLITE_SHELL_IS_UTF8 (0)
11947 # else
11948 # define SQLITE_SHELL_IS_UTF8 (1)
11949 # endif
11950 #endif
11952 #ifdef SQLITE_SHELL_FIDDLE
11953 # define main fiddle_main
11954 #endif
11956 #if SQLITE_SHELL_IS_UTF8
11957 int SQLITE_CDECL main(int argc, char **argv){
11958 #else
11959 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11960 char **argv;
11961 #endif
11962 #ifdef SQLITE_DEBUG
11963 sqlite3_int64 mem_main_enter = 0;
11964 #endif
11965 char *zErrMsg = 0;
11966 #ifdef SQLITE_SHELL_FIDDLE
11967 # define data shellState
11968 #else
11969 ShellState data;
11970 #endif
11971 const char *zInitFile = 0;
11972 int i;
11973 int rc = 0;
11974 int warnInmemoryDb = 0;
11975 int readStdin = 1;
11976 int nCmd = 0;
11977 int nOptsEnd = argc;
11978 char **azCmd = 0;
11979 const char *zVfs = 0; /* Value of -vfs command-line option */
11980 #if !SQLITE_SHELL_IS_UTF8
11981 char **argvToFree = 0;
11982 int argcToFree = 0;
11983 #endif
11984 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11986 #ifdef SQLITE_SHELL_FIDDLE
11987 stdin_is_interactive = 0;
11988 stdout_is_console = 1;
11989 data.wasm.zDefaultDbName = "/fiddle.sqlite3";
11990 #else
11991 stdin_is_interactive = isatty(0);
11992 stdout_is_console = isatty(1);
11993 #endif
11994 #if SHELL_WIN_UTF8_OPT
11995 atexit(console_restore); /* Needs revision for CLI as library call */
11996 #endif
11997 atexit(sayAbnormalExit);
11998 #ifdef SQLITE_DEBUG
11999 mem_main_enter = sqlite3_memory_used();
12000 #endif
12001 #if !defined(_WIN32_WCE)
12002 if( getenv("SQLITE_DEBUG_BREAK") ){
12003 if( isatty(0) && isatty(2) ){
12004 fprintf(stderr,
12005 "attach debugger to process %d and press any key to continue.\n",
12006 GETPID());
12007 fgetc(stdin);
12008 }else{
12009 #if defined(_WIN32) || defined(WIN32)
12010 #if SQLITE_OS_WINRT
12011 __debugbreak();
12012 #else
12013 DebugBreak();
12014 #endif
12015 #elif defined(SIGTRAP)
12016 raise(SIGTRAP);
12017 #endif
12020 #endif
12021 /* Register a valid signal handler early, before much else is done. */
12022 #ifdef SIGINT
12023 signal(SIGINT, interrupt_handler);
12024 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12025 if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
12026 fprintf(stderr, "No ^C handler.\n");
12028 #endif
12030 #if USE_SYSTEM_SQLITE+0!=1
12031 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12032 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12033 sqlite3_sourceid(), SQLITE_SOURCE_ID);
12034 exit(1);
12036 #endif
12037 main_init(&data);
12039 /* On Windows, we must translate command-line arguments into UTF-8.
12040 ** The SQLite memory allocator subsystem has to be enabled in order to
12041 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12042 ** subsequent sqlite3_config() calls will work. So copy all results into
12043 ** memory that does not come from the SQLite memory allocator.
12045 #if !SQLITE_SHELL_IS_UTF8
12046 sqlite3_initialize();
12047 argvToFree = malloc(sizeof(argv[0])*argc*2);
12048 shell_check_oom(argvToFree);
12049 argcToFree = argc;
12050 argv = argvToFree + argc;
12051 for(i=0; i<argc; i++){
12052 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12053 i64 n;
12054 shell_check_oom(z);
12055 n = strlen(z);
12056 argv[i] = malloc( n+1 );
12057 shell_check_oom(argv[i]);
12058 memcpy(argv[i], z, n+1);
12059 argvToFree[i] = argv[i];
12060 sqlite3_free(z);
12062 sqlite3_shutdown();
12063 #endif
12065 assert( argc>=1 && argv && argv[0] );
12066 Argv0 = argv[0];
12068 #ifdef SQLITE_SHELL_DBNAME_PROC
12070 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12071 ** of a C-function that will provide the name of the database file. Use
12072 ** this compile-time option to embed this shell program in larger
12073 ** applications. */
12074 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12075 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12076 warnInmemoryDb = 0;
12078 #endif
12080 /* Do an initial pass through the command-line argument to locate
12081 ** the name of the database file, the name of the initialization file,
12082 ** the size of the alternative malloc heap,
12083 ** and the first command to execute.
12085 #ifndef SQLITE_SHELL_FIDDLE
12086 verify_uninitialized();
12087 #endif
12088 for(i=1; i<argc; i++){
12089 char *z;
12090 z = argv[i];
12091 if( z[0]!='-' || i>nOptsEnd ){
12092 if( data.aAuxDb->zDbFilename==0 ){
12093 data.aAuxDb->zDbFilename = z;
12094 }else{
12095 /* Excesss arguments are interpreted as SQL (or dot-commands) and
12096 ** mean that nothing is read from stdin */
12097 readStdin = 0;
12098 nCmd++;
12099 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12100 shell_check_oom(azCmd);
12101 azCmd[nCmd-1] = z;
12103 continue;
12105 if( z[1]=='-' ) z++;
12106 if( cli_strcmp(z, "-")==0 ){
12107 nOptsEnd = i;
12108 continue;
12109 }else if( cli_strcmp(z,"-separator")==0
12110 || cli_strcmp(z,"-nullvalue")==0
12111 || cli_strcmp(z,"-newline")==0
12112 || cli_strcmp(z,"-cmd")==0
12114 (void)cmdline_option_value(argc, argv, ++i);
12115 }else if( cli_strcmp(z,"-init")==0 ){
12116 zInitFile = cmdline_option_value(argc, argv, ++i);
12117 }else if( cli_strcmp(z,"-batch")==0 ){
12118 /* Need to check for batch mode here to so we can avoid printing
12119 ** informational messages (like from process_sqliterc) before
12120 ** we do the actual processing of arguments later in a second pass.
12122 stdin_is_interactive = 0;
12123 }else if( cli_strcmp(z,"-heap")==0 ){
12124 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12125 const char *zSize;
12126 sqlite3_int64 szHeap;
12128 zSize = cmdline_option_value(argc, argv, ++i);
12129 szHeap = integerValue(zSize);
12130 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12131 verify_uninitialized();
12132 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12133 #else
12134 (void)cmdline_option_value(argc, argv, ++i);
12135 #endif
12136 }else if( cli_strcmp(z,"-pagecache")==0 ){
12137 sqlite3_int64 n, sz;
12138 sz = integerValue(cmdline_option_value(argc,argv,++i));
12139 if( sz>70000 ) sz = 70000;
12140 if( sz<0 ) sz = 0;
12141 n = integerValue(cmdline_option_value(argc,argv,++i));
12142 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12143 n = 0xffffffffffffLL/sz;
12145 verify_uninitialized();
12146 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12147 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12148 data.shellFlgs |= SHFLG_Pagecache;
12149 }else if( cli_strcmp(z,"-lookaside")==0 ){
12150 int n, sz;
12151 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12152 if( sz<0 ) sz = 0;
12153 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12154 if( n<0 ) n = 0;
12155 verify_uninitialized();
12156 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12157 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12158 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12159 int n;
12160 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12161 verify_uninitialized();
12162 switch( n ){
12163 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break;
12164 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break;
12165 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break;
12167 #ifdef SQLITE_ENABLE_VFSTRACE
12168 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12169 extern int vfstrace_register(
12170 const char *zTraceName,
12171 const char *zOldVfsName,
12172 int (*xOut)(const char*,void*),
12173 void *pOutArg,
12174 int makeDefault
12176 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12177 #endif
12178 #ifdef SQLITE_ENABLE_MULTIPLEX
12179 }else if( cli_strcmp(z,"-multiplex")==0 ){
12180 extern int sqlite3_multiple_initialize(const char*,int);
12181 sqlite3_multiplex_initialize(0, 1);
12182 #endif
12183 }else if( cli_strcmp(z,"-mmap")==0 ){
12184 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12185 verify_uninitialized();
12186 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12187 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
12188 }else if( cli_strcmp(z,"-sorterref")==0 ){
12189 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12190 verify_uninitialized();
12191 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12192 #endif
12193 }else if( cli_strcmp(z,"-vfs")==0 ){
12194 zVfs = cmdline_option_value(argc, argv, ++i);
12195 #ifdef SQLITE_HAVE_ZLIB
12196 }else if( cli_strcmp(z,"-zip")==0 ){
12197 data.openMode = SHELL_OPEN_ZIPFILE;
12198 #endif
12199 }else if( cli_strcmp(z,"-append")==0 ){
12200 data.openMode = SHELL_OPEN_APPENDVFS;
12201 #ifndef SQLITE_OMIT_DESERIALIZE
12202 }else if( cli_strcmp(z,"-deserialize")==0 ){
12203 data.openMode = SHELL_OPEN_DESERIALIZE;
12204 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12205 data.szMax = integerValue(argv[++i]);
12206 #endif
12207 }else if( cli_strcmp(z,"-readonly")==0 ){
12208 data.openMode = SHELL_OPEN_READONLY;
12209 }else if( cli_strcmp(z,"-nofollow")==0 ){
12210 data.openFlags = SQLITE_OPEN_NOFOLLOW;
12211 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12212 }else if( cli_strncmp(z, "-A",2)==0 ){
12213 /* All remaining command-line arguments are passed to the ".archive"
12214 ** command, so ignore them */
12215 break;
12216 #endif
12217 }else if( cli_strcmp(z, "-memtrace")==0 ){
12218 sqlite3MemTraceActivate(stderr);
12219 }else if( cli_strcmp(z,"-bail")==0 ){
12220 bail_on_error = 1;
12221 }else if( cli_strcmp(z,"-nonce")==0 ){
12222 free(data.zNonce);
12223 data.zNonce = strdup(argv[++i]);
12224 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12225 ShellSetFlag(&data,SHFLG_TestingMode);
12226 }else if( cli_strcmp(z,"-safe")==0 ){
12227 /* no-op - catch this on the second pass */
12230 #ifndef SQLITE_SHELL_FIDDLE
12231 verify_uninitialized();
12232 #endif
12235 #ifdef SQLITE_SHELL_INIT_PROC
12237 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12238 ** of a C-function that will perform initialization actions on SQLite that
12239 ** occur just before or after sqlite3_initialize(). Use this compile-time
12240 ** option to embed this shell program in larger applications. */
12241 extern void SQLITE_SHELL_INIT_PROC(void);
12242 SQLITE_SHELL_INIT_PROC();
12244 #else
12245 /* All the sqlite3_config() calls have now been made. So it is safe
12246 ** to call sqlite3_initialize() and process any command line -vfs option. */
12247 sqlite3_initialize();
12248 #endif
12250 if( zVfs ){
12251 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12252 if( pVfs ){
12253 sqlite3_vfs_register(pVfs, 1);
12254 }else{
12255 utf8_printf(stderr, "no such VFS: \"%s\"\n", zVfs);
12256 exit(1);
12260 if( data.pAuxDb->zDbFilename==0 ){
12261 #ifndef SQLITE_OMIT_MEMORYDB
12262 data.pAuxDb->zDbFilename = ":memory:";
12263 warnInmemoryDb = argc==1;
12264 #else
12265 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12266 return 1;
12267 #endif
12269 data.out = stdout;
12270 #ifndef SQLITE_SHELL_FIDDLE
12271 sqlite3_appendvfs_init(0,0,0);
12272 #endif
12274 /* Go ahead and open the database file if it already exists. If the
12275 ** file does not exist, delay opening it. This prevents empty database
12276 ** files from being created if a user mistypes the database name argument
12277 ** to the sqlite command-line tool.
12279 if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12280 open_db(&data, 0);
12283 /* Process the initialization file if there is one. If no -init option
12284 ** is given on the command line, look for a file named ~/.sqliterc and
12285 ** try to process it.
12287 process_sqliterc(&data,zInitFile);
12289 /* Make a second pass through the command-line argument and set
12290 ** options. This second pass is delayed until after the initialization
12291 ** file is processed so that the command-line arguments will override
12292 ** settings in the initialization file.
12294 for(i=1; i<argc; i++){
12295 char *z = argv[i];
12296 if( z[0]!='-' || i>=nOptsEnd ) continue;
12297 if( z[1]=='-' ){ z++; }
12298 if( cli_strcmp(z,"-init")==0 ){
12299 i++;
12300 }else if( cli_strcmp(z,"-html")==0 ){
12301 data.mode = MODE_Html;
12302 }else if( cli_strcmp(z,"-list")==0 ){
12303 data.mode = MODE_List;
12304 }else if( cli_strcmp(z,"-quote")==0 ){
12305 data.mode = MODE_Quote;
12306 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12307 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12308 }else if( cli_strcmp(z,"-line")==0 ){
12309 data.mode = MODE_Line;
12310 }else if( cli_strcmp(z,"-column")==0 ){
12311 data.mode = MODE_Column;
12312 }else if( cli_strcmp(z,"-json")==0 ){
12313 data.mode = MODE_Json;
12314 }else if( cli_strcmp(z,"-markdown")==0 ){
12315 data.mode = MODE_Markdown;
12316 }else if( cli_strcmp(z,"-table")==0 ){
12317 data.mode = MODE_Table;
12318 }else if( cli_strcmp(z,"-box")==0 ){
12319 data.mode = MODE_Box;
12320 }else if( cli_strcmp(z,"-csv")==0 ){
12321 data.mode = MODE_Csv;
12322 memcpy(data.colSeparator,",",2);
12323 #ifdef SQLITE_HAVE_ZLIB
12324 }else if( cli_strcmp(z,"-zip")==0 ){
12325 data.openMode = SHELL_OPEN_ZIPFILE;
12326 #endif
12327 }else if( cli_strcmp(z,"-append")==0 ){
12328 data.openMode = SHELL_OPEN_APPENDVFS;
12329 #ifndef SQLITE_OMIT_DESERIALIZE
12330 }else if( cli_strcmp(z,"-deserialize")==0 ){
12331 data.openMode = SHELL_OPEN_DESERIALIZE;
12332 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
12333 data.szMax = integerValue(argv[++i]);
12334 #endif
12335 }else if( cli_strcmp(z,"-readonly")==0 ){
12336 data.openMode = SHELL_OPEN_READONLY;
12337 }else if( cli_strcmp(z,"-nofollow")==0 ){
12338 data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12339 }else if( cli_strcmp(z,"-ascii")==0 ){
12340 data.mode = MODE_Ascii;
12341 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
12342 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
12343 }else if( cli_strcmp(z,"-tabs")==0 ){
12344 data.mode = MODE_List;
12345 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
12346 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
12347 }else if( cli_strcmp(z,"-separator")==0 ){
12348 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12349 "%s",cmdline_option_value(argc,argv,++i));
12350 }else if( cli_strcmp(z,"-newline")==0 ){
12351 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12352 "%s",cmdline_option_value(argc,argv,++i));
12353 }else if( cli_strcmp(z,"-nullvalue")==0 ){
12354 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12355 "%s",cmdline_option_value(argc,argv,++i));
12356 }else if( cli_strcmp(z,"-header")==0 ){
12357 data.showHeader = 1;
12358 ShellSetFlag(&data, SHFLG_HeaderSet);
12359 }else if( cli_strcmp(z,"-noheader")==0 ){
12360 data.showHeader = 0;
12361 ShellSetFlag(&data, SHFLG_HeaderSet);
12362 }else if( cli_strcmp(z,"-echo")==0 ){
12363 ShellSetFlag(&data, SHFLG_Echo);
12364 }else if( cli_strcmp(z,"-eqp")==0 ){
12365 data.autoEQP = AUTOEQP_on;
12366 }else if( cli_strcmp(z,"-eqpfull")==0 ){
12367 data.autoEQP = AUTOEQP_full;
12368 }else if( cli_strcmp(z,"-stats")==0 ){
12369 data.statsOn = 1;
12370 }else if( cli_strcmp(z,"-scanstats")==0 ){
12371 data.scanstatsOn = 1;
12372 }else if( cli_strcmp(z,"-backslash")==0 ){
12373 /* Undocumented command-line option: -backslash
12374 ** Causes C-style backslash escapes to be evaluated in SQL statements
12375 ** prior to sending the SQL into SQLite. Useful for injecting
12376 ** crazy bytes in the middle of SQL statements for testing and debugging.
12378 ShellSetFlag(&data, SHFLG_Backslash);
12379 }else if( cli_strcmp(z,"-bail")==0 ){
12380 /* No-op. The bail_on_error flag should already be set. */
12381 }else if( cli_strcmp(z,"-version")==0 ){
12382 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12383 return 0;
12384 }else if( cli_strcmp(z,"-interactive")==0 ){
12385 stdin_is_interactive = 1;
12386 }else if( cli_strcmp(z,"-batch")==0 ){
12387 stdin_is_interactive = 0;
12388 }else if( cli_strcmp(z,"-utf8")==0 ){
12389 #if SHELL_WIN_UTF8_OPT
12390 console_utf8 = 1;
12391 #endif /* SHELL_WIN_UTF8_OPT */
12392 }else if( cli_strcmp(z,"-heap")==0 ){
12393 i++;
12394 }else if( cli_strcmp(z,"-pagecache")==0 ){
12395 i+=2;
12396 }else if( cli_strcmp(z,"-lookaside")==0 ){
12397 i+=2;
12398 }else if( cli_strcmp(z,"-threadsafe")==0 ){
12399 i+=2;
12400 }else if( cli_strcmp(z,"-nonce")==0 ){
12401 i += 2;
12402 }else if( cli_strcmp(z,"-mmap")==0 ){
12403 i++;
12404 }else if( cli_strcmp(z,"-memtrace")==0 ){
12405 i++;
12406 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12407 }else if( cli_strcmp(z,"-sorterref")==0 ){
12408 i++;
12409 #endif
12410 }else if( cli_strcmp(z,"-vfs")==0 ){
12411 i++;
12412 #ifdef SQLITE_ENABLE_VFSTRACE
12413 }else if( cli_strcmp(z,"-vfstrace")==0 ){
12414 i++;
12415 #endif
12416 #ifdef SQLITE_ENABLE_MULTIPLEX
12417 }else if( cli_strcmp(z,"-multiplex")==0 ){
12418 i++;
12419 #endif
12420 }else if( cli_strcmp(z,"-help")==0 ){
12421 usage(1);
12422 }else if( cli_strcmp(z,"-cmd")==0 ){
12423 /* Run commands that follow -cmd first and separately from commands
12424 ** that simply appear on the command-line. This seems goofy. It would
12425 ** be better if all commands ran in the order that they appear. But
12426 ** we retain the goofy behavior for historical compatibility. */
12427 if( i==argc-1 ) break;
12428 z = cmdline_option_value(argc,argv,++i);
12429 if( z[0]=='.' ){
12430 rc = do_meta_command(z, &data);
12431 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12432 }else{
12433 open_db(&data, 0);
12434 rc = shell_exec(&data, z, &zErrMsg);
12435 if( zErrMsg!=0 ){
12436 utf8_printf(stderr,"Error: %s\n", zErrMsg);
12437 if( bail_on_error ) return rc!=0 ? rc : 1;
12438 }else if( rc!=0 ){
12439 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12440 if( bail_on_error ) return rc;
12443 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12444 }else if( cli_strncmp(z, "-A", 2)==0 ){
12445 if( nCmd>0 ){
12446 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12447 " with \"%s\"\n", z);
12448 return 1;
12450 open_db(&data, OPEN_DB_ZIPFILE);
12451 if( z[2] ){
12452 argv[i] = &z[2];
12453 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12454 }else{
12455 arDotCommand(&data, 1, argv+i, argc-i);
12457 readStdin = 0;
12458 break;
12459 #endif
12460 }else if( cli_strcmp(z,"-safe")==0 ){
12461 data.bSafeMode = data.bSafeModePersist = 1;
12462 }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
12463 /* Acted upon in first pass. */
12464 }else{
12465 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12466 raw_printf(stderr,"Use -help for a list of options.\n");
12467 return 1;
12469 data.cMode = data.mode;
12471 #if SHELL_WIN_UTF8_OPT
12472 if( console_utf8 && stdin_is_interactive ){
12473 console_prepare();
12474 }else{
12475 setBinaryMode(stdin, 0);
12476 console_utf8 = 0;
12478 #endif
12480 if( !readStdin ){
12481 /* Run all arguments that do not begin with '-' as if they were separate
12482 ** command-line inputs, except for the argToSkip argument which contains
12483 ** the database filename.
12485 for(i=0; i<nCmd; i++){
12486 if( azCmd[i][0]=='.' ){
12487 rc = do_meta_command(azCmd[i], &data);
12488 if( rc ){
12489 free(azCmd);
12490 return rc==2 ? 0 : rc;
12492 }else{
12493 open_db(&data, 0);
12494 echo_group_input(&data, azCmd[i]);
12495 rc = shell_exec(&data, azCmd[i], &zErrMsg);
12496 if( zErrMsg || rc ){
12497 if( zErrMsg!=0 ){
12498 utf8_printf(stderr,"Error: %s\n", zErrMsg);
12499 }else{
12500 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12502 sqlite3_free(zErrMsg);
12503 free(azCmd);
12504 return rc!=0 ? rc : 1;
12508 }else{
12509 /* Run commands received from standard input
12511 if( stdin_is_interactive ){
12512 char *zHome;
12513 char *zHistory;
12514 int nHistory;
12515 printf(
12516 "SQLite version %s %.19s\n" /*extra-version-info*/
12517 "Enter \".help\" for usage hints.\n",
12518 sqlite3_libversion(), sqlite3_sourceid()
12520 if( warnInmemoryDb ){
12521 printf("Connected to a ");
12522 printBold("transient in-memory database");
12523 printf(".\nUse \".open FILENAME\" to reopen on a "
12524 "persistent database.\n");
12526 zHistory = getenv("SQLITE_HISTORY");
12527 if( zHistory ){
12528 zHistory = strdup(zHistory);
12529 }else if( (zHome = find_home_dir(0))!=0 ){
12530 nHistory = strlen30(zHome) + 20;
12531 if( (zHistory = malloc(nHistory))!=0 ){
12532 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12535 if( zHistory ){ shell_read_history(zHistory); }
12536 #if HAVE_READLINE || HAVE_EDITLINE
12537 rl_attempted_completion_function = readline_completion;
12538 #elif HAVE_LINENOISE
12539 linenoiseSetCompletionCallback(linenoise_completion);
12540 #endif
12541 data.in = 0;
12542 rc = process_input(&data);
12543 if( zHistory ){
12544 shell_stifle_history(2000);
12545 shell_write_history(zHistory);
12546 free(zHistory);
12548 }else{
12549 data.in = stdin;
12550 rc = process_input(&data);
12553 #ifndef SQLITE_SHELL_FIDDLE
12554 /* In WASM mode we have to leave the db state in place so that
12555 ** client code can "push" SQL into it after this call returns. */
12556 free(azCmd);
12557 set_table_name(&data, 0);
12558 if( data.db ){
12559 session_close_all(&data, -1);
12560 close_db(data.db);
12562 for(i=0; i<ArraySize(data.aAuxDb); i++){
12563 sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12564 if( data.aAuxDb[i].db ){
12565 session_close_all(&data, i);
12566 close_db(data.aAuxDb[i].db);
12569 find_home_dir(1);
12570 output_reset(&data);
12571 data.doXdgOpen = 0;
12572 clearTempFile(&data);
12573 #if !SQLITE_SHELL_IS_UTF8
12574 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12575 free(argvToFree);
12576 #endif
12577 free(data.colWidth);
12578 free(data.zNonce);
12579 /* Clear the global data structure so that valgrind will detect memory
12580 ** leaks */
12581 memset(&data, 0, sizeof(data));
12582 #ifdef SQLITE_DEBUG
12583 if( sqlite3_memory_used()>mem_main_enter ){
12584 utf8_printf(stderr, "Memory leaked: %u bytes\n",
12585 (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12587 #endif
12588 #endif /* !SQLITE_SHELL_FIDDLE */
12589 return rc;
12593 #ifdef SQLITE_SHELL_FIDDLE
12594 /* Only for emcc experimentation purposes. */
12595 int fiddle_experiment(int a,int b){
12596 return a + b;
12600 ** Returns a pointer to the current DB handle.
12602 sqlite3 * fiddle_db_handle(){
12603 return globalDb;
12607 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12608 ** "main" is assumed. Returns 0 if no db with the given name is
12609 ** open.
12611 sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12612 sqlite3_vfs * pVfs = 0;
12613 if(globalDb){
12614 sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12615 SQLITE_FCNTL_VFS_POINTER, &pVfs);
12617 return pVfs;
12620 /* Only for emcc experimentation purposes. */
12621 sqlite3 * fiddle_db_arg(sqlite3 *arg){
12622 printf("fiddle_db_arg(%p)\n", (const void*)arg);
12623 return arg;
12627 ** Intended to be called via a SharedWorker() while a separate
12628 ** SharedWorker() (which manages the wasm module) is performing work
12629 ** which should be interrupted. Unfortunately, SharedWorker is not
12630 ** portable enough to make real use of.
12632 void fiddle_interrupt(void){
12633 if( globalDb ) sqlite3_interrupt(globalDb);
12637 ** Returns the filename of the given db name, assuming "main" if
12638 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12640 const char * fiddle_db_filename(const char * zDbName){
12641 return globalDb
12642 ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12643 : NULL;
12647 ** Completely wipes out the contents of the currently-opened database
12648 ** but leaves its storage intact for reuse.
12650 void fiddle_reset_db(void){
12651 if( globalDb ){
12652 int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12653 if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12654 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12659 ** Uses the current database's VFS xRead to stream the db file's
12660 ** contents out to the given callback. The callback gets a single
12661 ** chunk of size n (its 2nd argument) on each call and must return 0
12662 ** on success, non-0 on error. This function returns 0 on success,
12663 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12664 ** code from the callback. Note that this is not thread-friendly: it
12665 ** expects that it will be the only thread reading the db file and
12666 ** takes no measures to ensure that is the case.
12668 int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12669 sqlite3_int64 nSize = 0;
12670 sqlite3_int64 nPos = 0;
12671 sqlite3_file * pFile = 0;
12672 unsigned char buf[1024 * 8];
12673 int nBuf = (int)sizeof(buf);
12674 int rc = shellState.db
12675 ? sqlite3_file_control(shellState.db, "main",
12676 SQLITE_FCNTL_FILE_POINTER, &pFile)
12677 : SQLITE_NOTFOUND;
12678 if( rc ) return rc;
12679 rc = pFile->pMethods->xFileSize(pFile, &nSize);
12680 if( rc ) return rc;
12681 if(nSize % nBuf){
12682 /* DB size is not an even multiple of the buffer size. Reduce
12683 ** buffer size so that we do not unduly inflate the db size when
12684 ** exporting. */
12685 if(0 == nSize % 4096) nBuf = 4096;
12686 else if(0 == nSize % 2048) nBuf = 2048;
12687 else if(0 == nSize % 1024) nBuf = 1024;
12688 else nBuf = 512;
12690 for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12691 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12692 if(SQLITE_IOERR_SHORT_READ == rc){
12693 rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12695 if( 0==rc ) rc = xCallback(buf, nBuf);
12697 return rc;
12701 ** Trivial exportable function for emscripten. It processes zSql as if
12702 ** it were input to the sqlite3 shell and redirects all output to the
12703 ** wasm binding. fiddle_main() must have been called before this
12704 ** is called, or results are undefined.
12706 void fiddle_exec(const char * zSql){
12707 if(zSql && *zSql){
12708 if('.'==*zSql) puts(zSql);
12709 shellState.wasm.zInput = zSql;
12710 shellState.wasm.zPos = zSql;
12711 process_input(&shellState);
12712 shellState.wasm.zInput = shellState.wasm.zPos = 0;
12715 #endif /* SQLITE_SHELL_FIDDLE */