4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
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)
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
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
52 ** Warning pragmas copied from msvc.h in the core.
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
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
87 # define _LARGEFILE_SOURCE 1
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
104 typedef sqlite3_int64 i64
;
105 typedef sqlite3_uint64 u64
;
106 typedef unsigned char u8
;
107 #if SQLITE_USER_AUTHENTICATION
108 # include "sqlite3userauth.h"
113 #if !defined(_WIN32) && !defined(WIN32)
115 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
119 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
122 # define GETPID getpid
123 # if defined(__MINGW32__)
124 # define DIRENT dirent
126 # define S_ISLNK(mode) (0)
130 # define GETPID (int)GetCurrentProcessId
132 #include <sys/types.h>
133 #include <sys/stat.h>
136 # include <readline/readline.h>
137 # include <readline/history.h>
141 # include <editline/readline.h>
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)
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)
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
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));
175 # define deliberate_fall_through
179 #if defined(_WIN32) || defined(WIN32)
181 # define SQLITE_OMIT_POPEN 1
185 # define isatty(h) _isatty(h)
187 # define access(f,m) _access((f),(m))
190 # define unlink _unlink
193 # define strdup _strdup
196 # define popen _popen
198 # define pclose _pclose
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*);
210 # define SQLITE_OMIT_POPEN 1
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.
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)
231 #undef WIN32_LEAN_AND_MEAN
232 #define WIN32_LEAN_AND_MEAN
235 /* string conversion routines only needed on Win32 */
236 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
237 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
240 /* Use console I/O package as a direct INCLUDE. */
241 #define SQLITE_INTERNAL_LINKAGE static
243 #ifdef SQLITE_SHELL_FIDDLE
244 /* Deselect most features from the console I/O package for Fiddle. */
245 # define SQLITE_CIO_NO_REDIRECT
246 # define SQLITE_CIO_NO_CLASSIFY
247 # define SQLITE_CIO_NO_TRANSLATE
248 # define SQLITE_CIO_NO_SETMODE
250 INCLUDE
../ext
/consio
/console_io
.h
251 INCLUDE
../ext
/consio
/console_io
.c
253 #ifndef SQLITE_SHELL_FIDDLE
255 /* From here onward, fgets() is redirected to the console_io library. */
256 # define fgets(b,n,f) fGetsUtf8(b,n,f)
258 * Define macros for emitting output text in various ways:
259 * sputz(s, z) => emit 0-terminated string z to given stream s
260 * sputf(s, f, ...) => emit varargs per format f to given stream s
261 * oputz(z) => emit 0-terminated string z to default stream
262 * oputf(f, ...) => emit varargs per format f to default stream
263 * eputz(z) => emit 0-terminated string z to error stream
264 * eputf(f, ...) => emit varargs per format f to error stream
265 * oputb(b, n) => emit char buffer b[0..n-1] to default stream
267 * Note that the default stream is whatever has been last set via:
268 * setOutputStream(FILE *pf)
269 * This is normally the stream that CLI normal output goes to.
270 * For the stand-alone CLI, it is stdout with no .output redirect.
272 # define sputz(s,z) fPutsUtf8(z,s)
273 # define sputf fPrintfUtf8
274 # define oputz(z) oPutsUtf8(z)
275 # define oputf oPrintfUtf8
276 # define eputz(z) ePutsUtf8(z)
277 # define eputf ePrintfUtf8
278 # define oputb(buf,na) oPutbUtf8(buf,na)
281 /* For Fiddle, all console handling and emit redirection is omitted. */
282 # define sputz(fp,z) fputs(z,fp)
283 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
284 # define oputz(z) fputs(z,stdout)
285 # define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
286 # define eputz(z) fputs(z,stderr)
287 # define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
288 # define oputb(buf,na) fwrite(buf,1,na,stdout)
291 /* True if the timer is enabled */
292 static int enableTimer
= 0;
294 /* A version of strcmp() that works with NULL values */
295 static int cli_strcmp(const char *a
, const char *b
){
300 static int cli_strncmp(const char *a
, const char *b
, size_t n
){
303 return strncmp(a
,b
,n
);
306 /* Return the current wall-clock time */
307 static sqlite3_int64
timeOfDay(void){
308 static sqlite3_vfs
*clockVfs
= 0;
310 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
311 if( clockVfs
==0 ) return 0; /* Never actually happens */
312 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
313 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
316 clockVfs
->xCurrentTime(clockVfs
, &r
);
317 t
= (sqlite3_int64
)(r
*86400000.0);
322 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
323 #include <sys/time.h>
324 #include <sys/resource.h>
326 /* VxWorks does not support getrusage() as far as we can determine */
327 #if defined(_WRS_KERNEL) || defined(__RTP__)
329 struct timeval ru_utime
; /* user CPU time used */
330 struct timeval ru_stime
; /* system CPU time used */
332 #define getrusage(A,B) memset(B,0,sizeof(*B))
335 /* Saved resource information for the beginning of an operation */
336 static struct rusage sBegin
; /* CPU time at start */
337 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
340 ** Begin timing an operation
342 static void beginTimer(void){
344 getrusage(RUSAGE_SELF
, &sBegin
);
345 iBegin
= timeOfDay();
349 /* Return the difference of two time_structs in seconds */
350 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
351 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
352 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
356 ** Print the timing results.
358 static void endTimer(void){
360 sqlite3_int64 iEnd
= timeOfDay();
362 getrusage(RUSAGE_SELF
, &sEnd
);
363 sputf(stdout
, "Run Time: real %.3f user %f sys %f\n",
364 (iEnd
- iBegin
)*0.001,
365 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
366 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
370 #define BEGIN_TIMER beginTimer()
371 #define END_TIMER endTimer()
374 #elif (defined(_WIN32) || defined(WIN32))
376 /* Saved resource information for the beginning of an operation */
377 static HANDLE hProcess
;
378 static FILETIME ftKernelBegin
;
379 static FILETIME ftUserBegin
;
380 static sqlite3_int64 ftWallBegin
;
381 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
382 LPFILETIME
, LPFILETIME
);
383 static GETPROCTIMES getProcessTimesAddr
= NULL
;
386 ** Check to see if we have timer support. Return 1 if necessary
387 ** support found (or found previously).
389 static int hasTimer(void){
390 if( getProcessTimesAddr
){
394 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
395 ** versions. See if the version we are running on has it, and if it
396 ** does, save off a pointer to it and the current process handle.
398 hProcess
= GetCurrentProcess();
400 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
401 if( NULL
!= hinstLib
){
402 getProcessTimesAddr
=
403 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
404 if( NULL
!= getProcessTimesAddr
){
407 FreeLibrary(hinstLib
);
416 ** Begin timing an operation
418 static void beginTimer(void){
419 if( enableTimer
&& getProcessTimesAddr
){
420 FILETIME ftCreation
, ftExit
;
421 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
422 &ftKernelBegin
,&ftUserBegin
);
423 ftWallBegin
= timeOfDay();
427 /* Return the difference of two FILETIME structs in seconds */
428 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
429 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
430 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
431 return (double) ((i64End
- i64Start
) / 10000000.0);
435 ** Print the timing results.
437 static void endTimer(void){
438 if( enableTimer
&& getProcessTimesAddr
){
439 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
440 sqlite3_int64 ftWallEnd
= timeOfDay();
441 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
442 sputf(stdout
, "Run Time: real %.3f user %f sys %f\n",
443 (ftWallEnd
- ftWallBegin
)*0.001,
444 timeDiff(&ftUserBegin
, &ftUserEnd
),
445 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
449 #define BEGIN_TIMER beginTimer()
450 #define END_TIMER endTimer()
451 #define HAS_TIMER hasTimer()
460 ** Used to prevent warnings about unused parameters
462 #define UNUSED_PARAMETER(x) (void)(x)
465 ** Number of elements in an array
467 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
470 ** If the following flag is set, then command execution stops
471 ** at an error if we are not interactive.
473 static int bail_on_error
= 0;
476 ** Treat stdin as an interactive input if the following variable
477 ** is true. Otherwise, assume stdin is connected to a file or pipe.
479 static int stdin_is_interactive
= 1;
482 ** On Windows systems we need to know if standard output is a console
483 ** in order to show that UTF-16 translation is done in the sign-on
484 ** banner. The following variable is true if it is the console.
486 static int stdout_is_console
= 1;
489 ** The following is the open SQLite database. We make a pointer
490 ** to this database a static variable so that it can be accessed
491 ** by the SIGINT handler to interrupt database processing.
493 static sqlite3
*globalDb
= 0;
496 ** True if an interrupt (Control-C) has been received.
498 static volatile int seenInterrupt
= 0;
501 ** This is the name of our program. It is set in main(), used
502 ** in a number of other places, mostly for error messages.
507 ** Prompt strings. Initialized in main. Settable with
508 ** .prompt main continue
510 #define PROMPT_LEN_MAX 20
511 /* First line prompt. default: "sqlite> " */
512 static char mainPrompt
[PROMPT_LEN_MAX
];
513 /* Continuation prompt. default: " ...> " */
514 static char continuePrompt
[PROMPT_LEN_MAX
];
516 /* This is variant of the standard-library strncpy() routine with the
517 ** one change that the destination string is always zero-terminated, even
518 ** if there is no zero-terminator in the first n-1 characters of the source
521 static char *shell_strncpy(char *dest
, const char *src
, size_t n
){
523 for(i
=0; i
<n
-1 && src
[i
]!=0; i
++) dest
[i
] = src
[i
];
529 ** Optionally disable dynamic continuation prompt.
530 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
531 ** or open parentheses level if non-zero, or continuation prompt as set.
532 ** This facility interacts with the scanner and process_input() where the
533 ** below 5 macros are used.
535 #ifdef SQLITE_OMIT_DYNAPROMPT
536 # define CONTINUATION_PROMPT continuePrompt
537 # define CONTINUE_PROMPT_RESET
538 # define CONTINUE_PROMPT_AWAITS(p,s)
539 # define CONTINUE_PROMPT_AWAITC(p,c)
540 # define CONTINUE_PAREN_INCR(p,n)
541 # define CONTINUE_PROMPT_PSTATE 0
542 typedef void *t_NoDynaPrompt
;
543 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
545 # define CONTINUATION_PROMPT dynamicContinuePrompt()
546 # define CONTINUE_PROMPT_RESET \
547 do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
548 # define CONTINUE_PROMPT_AWAITS(p,s) \
549 if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
550 # define CONTINUE_PROMPT_AWAITC(p,c) \
551 if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
552 # define CONTINUE_PAREN_INCR(p,n) \
553 if(p && stdin_is_interactive) (trackParenLevel(p,n))
554 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
555 typedef struct DynaPrompt
*t_DynaPromptRef
;
556 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
558 static struct DynaPrompt
{
559 char dynamicPrompt
[PROMPT_LEN_MAX
];
562 char *zScannerAwaits
;
563 } dynPrompt
= { {0}, {0}, 0, 0 };
565 /* Record parenthesis nesting level change, or force level to 0. */
566 static void trackParenLevel(struct DynaPrompt
*p
, int ni
){
567 p
->inParenLevel
+= ni
;
568 if( ni
==0 ) p
->inParenLevel
= 0;
569 p
->zScannerAwaits
= 0;
572 /* Record that a lexeme is opened, or closed with args==0. */
573 static void setLexemeOpen(struct DynaPrompt
*p
, char *s
, char c
){
575 p
->zScannerAwaits
= s
;
579 p
->zScannerAwaits
= p
->acAwait
;
583 /* Upon demand, derive the continuation prompt to display. */
584 static char *dynamicContinuePrompt(void){
585 if( continuePrompt
[0]==0
586 || (dynPrompt
.zScannerAwaits
==0 && dynPrompt
.inParenLevel
== 0) ){
587 return continuePrompt
;
589 if( dynPrompt
.zScannerAwaits
){
590 size_t ncp
= strlen(continuePrompt
);
591 size_t ndp
= strlen(dynPrompt
.zScannerAwaits
);
592 if( ndp
> ncp
-3 ) return continuePrompt
;
593 strcpy(dynPrompt
.dynamicPrompt
, dynPrompt
.zScannerAwaits
);
594 while( ndp
<3 ) dynPrompt
.dynamicPrompt
[ndp
++] = ' ';
595 shell_strncpy(dynPrompt
.dynamicPrompt
+3, continuePrompt
+3,
598 if( dynPrompt
.inParenLevel
>9 ){
599 shell_strncpy(dynPrompt
.dynamicPrompt
, "(..", 4);
600 }else if( dynPrompt
.inParenLevel
<0 ){
601 shell_strncpy(dynPrompt
.dynamicPrompt
, ")x!", 4);
603 shell_strncpy(dynPrompt
.dynamicPrompt
, "(x.", 4);
604 dynPrompt
.dynamicPrompt
[2] = (char)('0'+dynPrompt
.inParenLevel
);
606 shell_strncpy(dynPrompt
.dynamicPrompt
+3, continuePrompt
+3,
610 return dynPrompt
.dynamicPrompt
;
612 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
614 /* Indicate out-of-memory and exit. */
615 static void shell_out_of_memory(void){
616 eputz("Error: out of memory\n");
620 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
621 ** out-of-memory error.
623 static void shell_check_oom(const void *p
){
624 if( p
==0 ) shell_out_of_memory();
628 ** Write I/O traces to the following stream.
630 #ifdef SQLITE_ENABLE_IOTRACE
631 static FILE *iotrace
= 0;
635 ** This routine works like printf in that its first argument is a
636 ** format string and subsequent arguments are values to be substituted
637 ** in place of % fields. The result of formatting this string
638 ** is written to iotrace.
640 #ifdef SQLITE_ENABLE_IOTRACE
641 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
644 if( iotrace
==0 ) return;
645 va_start(ap
, zFormat
);
646 z
= sqlite3_vmprintf(zFormat
, ap
);
648 sputf(iotrace
, "%s", z
);
654 ** Output string zUtf to Out stream as w characters. If w is negative,
655 ** then right-justify the text. W is the width in UTF-8 characters, not
656 ** in bytes. This is different from the %*.*s specification in printf
657 ** since with %*.*s the width is measured in bytes, not characters.
659 static void utf8_width_print(int w
, const char *zUtf
){
662 int aw
= w
<0 ? -w
: w
;
663 if( zUtf
==0 ) zUtf
= "";
664 for(i
=n
=0; zUtf
[i
]; i
++){
665 if( (zUtf
[i
]&0xc0)!=0x80 ){
668 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
674 oputf("%.*s", i
, zUtf
);
676 oputf("%*s%s", aw
-n
, "", zUtf
);
678 oputf("%s%*s", zUtf
, aw
-n
, "");
684 ** Determines if a string is a number of not.
686 static int isNumber(const char *z
, int *realnum
){
687 if( *z
=='-' || *z
=='+' ) z
++;
692 if( realnum
) *realnum
= 0;
693 while( IsDigit(*z
) ){ z
++; }
696 if( !IsDigit(*z
) ) return 0;
697 while( IsDigit(*z
) ){ z
++; }
698 if( realnum
) *realnum
= 1;
700 if( *z
=='e' || *z
=='E' ){
702 if( *z
=='+' || *z
=='-' ) z
++;
703 if( !IsDigit(*z
) ) return 0;
704 while( IsDigit(*z
) ){ z
++; }
705 if( realnum
) *realnum
= 1;
711 ** Compute a string length that is limited to what can be stored in
712 ** lower 30 bits of a 32-bit signed integer.
714 static int strlen30(const char *z
){
716 while( *z2
){ z2
++; }
717 return 0x3fffffff & (int)(z2
- z
);
721 ** Return the length of a string in characters. Multibyte UTF8 characters
722 ** count as a single character.
724 static int strlenChar(const char *z
){
727 if( (0xc0&*(z
++))!=0x80 ) n
++;
733 ** Return open FILE * if zFile exists, can be opened for read
734 ** and is an ordinary file or a character stream source.
735 ** Otherwise return 0.
737 static FILE * openChrSource(const char *zFile
){
738 #if defined(_WIN32) || defined(WIN32)
739 struct __stat64 x
= {0};
740 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
741 /* On Windows, open first, then check the stream nature. This order
742 ** is necessary because _stat() and sibs, when checking a named pipe,
743 ** effectively break the pipe as its supplier sees it. */
744 FILE *rv
= fopen(zFile
, "rb");
745 if( rv
==0 ) return 0;
746 if( _fstat64(_fileno(rv
), &x
) != 0
747 || !STAT_CHR_SRC(x
.st_mode
)){
754 int rc
= stat(zFile
, &x
);
755 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
756 if( rc
!=0 ) return 0;
757 if( STAT_CHR_SRC(x
.st_mode
) ){
758 return fopen(zFile
, "rb");
767 ** This routine reads a line of text from FILE in, stores
768 ** the text in memory obtained from malloc() and returns a pointer
769 ** to the text. NULL is returned at end of file, or if malloc()
772 ** If zLine is not NULL then it is a malloced buffer returned from
773 ** a previous call to this routine that may be reused.
775 static char *local_getline(char *zLine
, FILE *in
){
776 int nLine
= zLine
==0 ? 0 : 100;
781 nLine
= nLine
*2 + 100;
782 zLine
= realloc(zLine
, nLine
);
783 shell_check_oom(zLine
);
785 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
793 while( zLine
[n
] ) n
++;
794 if( n
>0 && zLine
[n
-1]=='\n' ){
796 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
805 ** Retrieve a single line of input text.
807 ** If in==0 then read from standard input and prompt before each line.
808 ** If isContinuation is true, then a continuation prompt is appropriate.
809 ** If isContinuation is zero, then the main prompt should be used.
811 ** If zPrior is not NULL then it is a buffer from a prior call to this
812 ** routine that can be reused.
814 ** The result is stored in space obtained from malloc() and must either
815 ** be freed by the caller or else passed back into this routine via the
816 ** zPrior argument for reuse.
818 #ifndef SQLITE_SHELL_FIDDLE
819 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
823 zResult
= local_getline(zPrior
, in
);
825 zPrompt
= isContinuation
? CONTINUATION_PROMPT
: mainPrompt
;
826 #if SHELL_USE_LOCAL_GETLINE
827 sputz(stdout
, zPrompt
);
830 zResult
= local_getline(zPrior
, stdin
);
832 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
833 if( zResult
==0 ) sqlite3_sleep(50);
834 }while( zResult
==0 && seenInterrupt
>0 );
837 zResult
= shell_readline(zPrompt
);
839 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
841 if( seenInterrupt
==0 ) break;
842 zResult
= shell_readline("");
844 if( zResult
&& *zResult
) shell_add_history(zResult
);
849 #endif /* !SQLITE_SHELL_FIDDLE */
852 ** Return the value of a hexadecimal digit. Return -1 if the input
853 ** is not a hex digit.
855 static int hexDigitValue(char c
){
856 if( c
>='0' && c
<='9' ) return c
- '0';
857 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
858 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
863 ** Interpret zArg as an integer value, possibly with suffixes.
865 static sqlite3_int64
integerValue(const char *zArg
){
867 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
869 { "MiB", 1024*1024 },
870 { "GiB", 1024*1024*1024 },
873 { "GB", 1000000000 },
883 }else if( zArg
[0]=='+' ){
886 if( zArg
[0]=='0' && zArg
[1]=='x' ){
889 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
894 while( IsDigit(zArg
[0]) ){
895 v
= v
*10 + zArg
[0] - '0';
899 for(i
=0; i
<ArraySize(aMult
); i
++){
900 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
905 return isNeg
? -v
: v
;
909 ** A variable length string to which one can append text.
911 typedef struct ShellText ShellText
;
919 ** Initialize and destroy a ShellText object
921 static void initText(ShellText
*p
){
922 memset(p
, 0, sizeof(*p
));
924 static void freeText(ShellText
*p
){
929 /* zIn is either a pointer to a NULL-terminated string in memory obtained
930 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
931 ** added to zIn, and the result returned in memory obtained from malloc().
932 ** zIn, if it was not NULL, is freed.
934 ** If the third argument, quote, is not '\0', then it is used as a
935 ** quote character for zAppend.
937 static void appendText(ShellText
*p
, const char *zAppend
, char quote
){
940 i64 nAppend
= strlen30(zAppend
);
942 len
= nAppend
+p
->n
+1;
945 for(i
=0; i
<nAppend
; i
++){
946 if( zAppend
[i
]==quote
) len
++;
950 if( p
->z
==0 || p
->n
+len
>=p
->nAlloc
){
951 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
952 p
->z
= realloc(p
->z
, p
->nAlloc
);
953 shell_check_oom(p
->z
);
957 char *zCsr
= p
->z
+p
->n
;
959 for(i
=0; i
<nAppend
; i
++){
960 *zCsr
++ = zAppend
[i
];
961 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
964 p
->n
= (int)(zCsr
- p
->z
);
967 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
974 ** Attempt to determine if identifier zName needs to be quoted, either
975 ** because it contains non-alphanumeric characters, or because it is an
976 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
977 ** that quoting is required.
979 ** Return '"' if quoting is required. Return 0 if no quoting is required.
981 static char quoteChar(const char *zName
){
983 if( zName
==0 ) return '"';
984 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
985 for(i
=0; zName
[i
]; i
++){
986 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
988 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
992 ** Construct a fake object name and column list to describe the structure
993 ** of the view, virtual table, or table valued function zSchema.zName.
995 static char *shellFakeSchema(
996 sqlite3
*db
, /* The database connection containing the vtab */
997 const char *zSchema
, /* Schema of the database holding the vtab */
998 const char *zName
/* The name of the virtual table */
1000 sqlite3_stmt
*pStmt
= 0;
1007 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1008 zSchema
? zSchema
: "main", zName
);
1009 shell_check_oom(zSql
);
1010 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
1014 cQuote
= quoteChar(zSchema
);
1015 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
1016 appendText(&s
, zSchema
, cQuote
);
1017 appendText(&s
, ".", 0);
1019 cQuote
= quoteChar(zName
);
1020 appendText(&s
, zName
, cQuote
);
1021 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
1022 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
1024 appendText(&s
, zDiv
, 0);
1026 if( zCol
==0 ) zCol
= "";
1027 cQuote
= quoteChar(zCol
);
1028 appendText(&s
, zCol
, cQuote
);
1030 appendText(&s
, ")", 0);
1031 sqlite3_finalize(pStmt
);
1040 ** SQL function: strtod(X)
1042 ** Use the C-library strtod() function to convert string X into a double.
1043 ** Used for comparing the accuracy of SQLite's internal text-to-float conversion
1044 ** routines against the C-library.
1046 static void shellStrtod(
1047 sqlite3_context
*pCtx
,
1049 sqlite3_value
**apVal
1051 char *z
= (char*)sqlite3_value_text(apVal
[0]);
1052 UNUSED_PARAMETER(nVal
);
1054 sqlite3_result_double(pCtx
, strtod(z
,0));
1058 ** SQL function: dtostr(X)
1060 ** Use the C-library printf() function to convert real value X into a string.
1061 ** Used for comparing the accuracy of SQLite's internal float-to-text conversion
1062 ** routines against the C-library.
1064 static void shellDtostr(
1065 sqlite3_context
*pCtx
,
1067 sqlite3_value
**apVal
1069 double r
= sqlite3_value_double(apVal
[0]);
1070 int n
= nVal
>=2 ? sqlite3_value_int(apVal
[1]) : 26;
1073 if( n
>350 ) n
= 350;
1074 sqlite3_snprintf(sizeof(z
), z
, "%#+.*e", n
, r
);
1075 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
1080 ** SQL function: shell_module_schema(X)
1082 ** Return a fake schema for the table-valued function or eponymous virtual
1085 static void shellModuleSchema(
1086 sqlite3_context
*pCtx
,
1088 sqlite3_value
**apVal
1092 UNUSED_PARAMETER(nVal
);
1093 zName
= (const char*)sqlite3_value_text(apVal
[0]);
1094 zFake
= zName
? shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
) : 0;
1096 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
1103 ** SQL function: shell_add_schema(S,X)
1105 ** Add the schema name X to the CREATE statement in S and return the result.
1108 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1113 ** CREATE UNIQUE INDEX
1116 ** CREATE VIRTUAL TABLE
1118 ** This UDF is used by the .schema command to insert the schema name of
1119 ** attached databases into the middle of the sqlite_schema.sql field.
1121 static void shellAddSchemaName(
1122 sqlite3_context
*pCtx
,
1124 sqlite3_value
**apVal
1126 static const char *aPrefix
[] = {
1135 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
1136 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
1137 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
1138 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
1139 UNUSED_PARAMETER(nVal
);
1140 if( zIn
!=0 && cli_strncmp(zIn
, "CREATE ", 7)==0 ){
1141 for(i
=0; i
<ArraySize(aPrefix
); i
++){
1142 int n
= strlen30(aPrefix
[i
]);
1143 if( cli_strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
1147 char cQuote
= quoteChar(zSchema
);
1148 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
1149 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1151 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1155 && aPrefix
[i
][0]=='V'
1156 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
1159 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
1161 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
1166 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
1172 sqlite3_result_value(pCtx
, apVal
[0]);
1176 ** The source code for several run-time loadable extensions is inserted
1177 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1178 ** code, we need to override some macros to make the included program code
1179 ** work here in the middle of this regular program.
1181 #define SQLITE_EXTENSION_INIT1
1182 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1184 #if defined(_WIN32) && defined(_MSC_VER)
1185 INCLUDE test_windirent
.h
1186 INCLUDE test_windirent
.c
1187 #define dirent DIRENT
1189 INCLUDE
../ext
/misc
/memtrace
.c
1190 INCLUDE
../ext
/misc
/pcachetrace
.c
1191 INCLUDE
../ext
/misc
/shathree
.c
1192 INCLUDE
../ext
/misc
/uint
.c
1193 INCLUDE
../ext
/misc
/decimal
.c
1194 #undef sqlite3_base_init
1195 #define sqlite3_base_init sqlite3_base64_init
1196 INCLUDE
../ext
/misc
/base64
.c
1197 #undef sqlite3_base_init
1198 #define sqlite3_base_init sqlite3_base85_init
1199 #define OMIT_BASE85_CHECKER
1200 INCLUDE
../ext
/misc
/base85
.c
1201 INCLUDE
../ext
/misc
/ieee754
.c
1202 INCLUDE
../ext
/misc
/series
.c
1203 INCLUDE
../ext
/misc
/regexp
.c
1204 #ifndef SQLITE_SHELL_FIDDLE
1205 INCLUDE
../ext
/misc
/fileio
.c
1206 INCLUDE
../ext
/misc
/completion
.c
1207 INCLUDE
../ext
/misc
/appendvfs
.c
1209 #ifdef SQLITE_HAVE_ZLIB
1210 INCLUDE
../ext
/misc
/zipfile
.c
1211 INCLUDE
../ext
/misc
/sqlar
.c
1213 INCLUDE
../ext
/expert
/sqlite3expert
.h
1214 INCLUDE
../ext
/expert
/sqlite3expert
.c
1216 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1217 #define SQLITE_SHELL_HAVE_RECOVER 1
1219 #define SQLITE_SHELL_HAVE_RECOVER 0
1221 #if SQLITE_SHELL_HAVE_RECOVER
1222 INCLUDE
../ext
/recover
/sqlite3recover
.h
1223 # ifndef SQLITE_HAVE_SQLITE3R
1224 INCLUDE
../ext
/recover
/dbdata
.c
1225 INCLUDE
../ext
/recover
/sqlite3recover
.c
1226 # endif /* SQLITE_HAVE_SQLITE3R */
1228 #ifdef SQLITE_SHELL_EXTSRC
1229 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1232 #if defined(SQLITE_ENABLE_SESSION)
1234 ** State information for a single open session
1236 typedef struct OpenSession OpenSession
;
1237 struct OpenSession
{
1238 char *zName
; /* Symbolic name for this session */
1239 int nFilter
; /* Number of xFilter rejection GLOB patterns */
1240 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
1241 sqlite3_session
*p
; /* The open session */
1245 typedef struct ExpertInfo ExpertInfo
;
1247 sqlite3expert
*pExpert
;
1251 /* A single line in the EQP output */
1252 typedef struct EQPGraphRow EQPGraphRow
;
1253 struct EQPGraphRow
{
1254 int iEqpId
; /* ID for this row */
1255 int iParentId
; /* ID of the parent row */
1256 EQPGraphRow
*pNext
; /* Next row in sequence */
1257 char zText
[1]; /* Text to display for this row */
1260 /* All EQP output is collected into an instance of the following */
1261 typedef struct EQPGraph EQPGraph
;
1263 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
1264 EQPGraphRow
*pLast
; /* Last element of the pRow list */
1265 char zPrefix
[100]; /* Graph prefix */
1268 /* Parameters affecting columnar mode result display (defaulting together) */
1269 typedef struct ColModeOpts
{
1270 int iWrap
; /* In columnar modes, wrap lines reaching this limit */
1271 u8 bQuote
; /* Quote results for .mode box and table */
1272 u8 bWordWrap
; /* In columnar modes, wrap at word boundaries */
1274 #define ColModeOpts_default { 60, 0, 0 }
1275 #define ColModeOpts_default_qbox { 60, 1, 0 }
1278 ** State information about the database connection is contained in an
1279 ** instance of the following structure.
1281 typedef struct ShellState ShellState
;
1283 sqlite3
*db
; /* The database */
1284 u8 autoExplain
; /* Automatically turn on .explain mode */
1285 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
1286 u8 autoEQPtest
; /* autoEQP is in test mode */
1287 u8 autoEQPtrace
; /* autoEQP is in trace mode */
1288 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1289 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1290 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1291 u8 nEqpLevel
; /* Depth of the EQP output graph */
1292 u8 eTraceType
; /* SHELL_TRACE_* value for type of trace */
1293 u8 bSafeMode
; /* True to prohibit unsafe operations */
1294 u8 bSafeModePersist
; /* The long-term value of bSafeMode */
1295 u8 eRestoreState
; /* See comments above doAutoDetectRestore() */
1296 ColModeOpts cmOpts
; /* Option values affecting columnar mode output */
1297 unsigned statsOn
; /* True to display memory stats before each finalize */
1298 unsigned mEqpLines
; /* Mask of vertical lines in the EQP output graph */
1299 int inputNesting
; /* Track nesting level of .read and other redirects */
1300 int outCount
; /* Revert to stdout when reaching zero */
1301 int cnt
; /* Number of records displayed so far */
1302 int lineno
; /* Line number of last line read from in */
1303 int openFlags
; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1304 FILE *in
; /* Read commands from this stream */
1305 FILE *out
; /* Write results here */
1306 FILE *traceOut
; /* Output for sqlite3_trace() */
1307 int nErr
; /* Number of errors seen */
1308 int mode
; /* An output mode setting */
1309 int modePrior
; /* Saved mode */
1310 int cMode
; /* temporary output mode for the current query */
1311 int normalMode
; /* Output mode before ".explain on" */
1312 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1313 int showHeader
; /* True to show column names in List or Column mode */
1314 int nCheck
; /* Number of ".check" commands run */
1315 unsigned nProgress
; /* Number of progress callbacks encountered */
1316 unsigned mxProgress
; /* Maximum progress callbacks before failing */
1317 unsigned flgProgress
; /* Flags for the progress callback */
1318 unsigned shellFlgs
; /* Various flags */
1319 unsigned priorShFlgs
; /* Saved copy of flags */
1320 sqlite3_int64 szMax
; /* --maxsize argument to .open */
1321 char *zDestTable
; /* Name of destination table when MODE_Insert */
1322 char *zTempFile
; /* Temporary file that might need deleting */
1323 char zTestcase
[30]; /* Name of current test case */
1324 char colSeparator
[20]; /* Column separator character for several modes */
1325 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1326 char colSepPrior
[20]; /* Saved column separator */
1327 char rowSepPrior
[20]; /* Saved row separator */
1328 int *colWidth
; /* Requested width of each column in columnar modes */
1329 int *actualWidth
; /* Actual width of each column */
1330 int nWidth
; /* Number of slots in colWidth[] and actualWidth[] */
1331 char nullValue
[20]; /* The text to print when a NULL comes back from
1333 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1334 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1335 FILE *pLog
; /* Write log output here */
1336 struct AuxDb
{ /* Storage space for auxiliary database connections */
1337 sqlite3
*db
; /* Connection pointer */
1338 const char *zDbFilename
; /* Filename used to open the connection */
1339 char *zFreeOnClose
; /* Free this memory allocation on close */
1340 #if defined(SQLITE_ENABLE_SESSION)
1341 int nSession
; /* Number of active sessions */
1342 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1344 } aAuxDb
[5], /* Array of all database connections */
1345 *pAuxDb
; /* Currently active database connection */
1346 int *aiIndent
; /* Array of indents used in MODE_Explain */
1347 int nIndent
; /* Size of array aiIndent[] */
1348 int iIndent
; /* Index of current op in aiIndent[] */
1349 char *zNonce
; /* Nonce for temporary safe-mode escapes */
1350 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1351 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1352 #ifdef SQLITE_SHELL_FIDDLE
1354 const char * zInput
; /* Input string from wasm/JS proxy */
1355 const char * zPos
; /* Cursor pos into zInput */
1356 const char * zDefaultDbName
; /* Default name for db file */
1361 #ifdef SQLITE_SHELL_FIDDLE
1362 static ShellState shellState
;
1366 /* Allowed values for ShellState.autoEQP
1368 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1369 #define AUTOEQP_on 1 /* Automatic EQP is on */
1370 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1371 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1373 /* Allowed values for ShellState.openMode
1375 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1376 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1377 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1378 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1379 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1380 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1381 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1383 /* Allowed values for ShellState.eTraceType
1385 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1386 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1387 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1389 /* Bits in the ShellState.flgProgress variable */
1390 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1391 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress
1392 ** callback limit is reached, and for each
1393 ** top-level SQL statement */
1394 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1397 ** These are the allowed shellFlgs values
1399 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1400 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1401 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1402 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1403 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1404 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1405 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1406 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1407 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1408 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1409 #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */
1412 ** Macros for testing and setting shellFlgs
1414 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1415 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1416 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1419 ** These are the allowed modes.
1421 #define MODE_Line 0 /* One column per line. Blank line between records */
1422 #define MODE_Column 1 /* One record per line in neat columns */
1423 #define MODE_List 2 /* One record per line with a separator */
1424 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1425 #define MODE_Html 4 /* Generate an XHTML table */
1426 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1427 #define MODE_Quote 6 /* Quote values as for SQL */
1428 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1429 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1430 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1431 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1432 #define MODE_Pretty 11 /* Pretty-print schemas */
1433 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1434 #define MODE_Json 13 /* Output JSON */
1435 #define MODE_Markdown 14 /* Markdown formatting */
1436 #define MODE_Table 15 /* MySQL-style table formatting */
1437 #define MODE_Box 16 /* Unicode box-drawing characters */
1438 #define MODE_Count 17 /* Output only a count of the rows of output */
1439 #define MODE_Off 18 /* No query output shown */
1440 #define MODE_ScanExp 19 /* Like MODE_Explain, but for ".scanstats vm" */
1442 static const char *modeDescr
[] = {
1465 ** These are the column/row/line separators used by the various
1466 ** import/export modes.
1468 #define SEP_Column "|"
1469 #define SEP_Row "\n"
1470 #define SEP_Tab "\t"
1471 #define SEP_Space " "
1472 #define SEP_Comma ","
1473 #define SEP_CrLf "\r\n"
1474 #define SEP_Unit "\x1F"
1475 #define SEP_Record "\x1E"
1478 ** Limit input nesting via .read or any other input redirect.
1479 ** It's not too expensive, so a generous allowance can be made.
1481 #define MAX_INPUT_NESTING 25
1484 ** A callback for the sqlite3_log() interface.
1486 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1487 ShellState
*p
= (ShellState
*)pArg
;
1488 if( p
->pLog
==0 ) return;
1489 sputf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1494 ** SQL function: shell_putsnl(X)
1496 ** Write the text X to the screen (or whatever output is being directed)
1497 ** adding a newline at the end, and then return X.
1499 static void shellPutsFunc(
1500 sqlite3_context
*pCtx
,
1502 sqlite3_value
**apVal
1504 /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
1506 oputf("%s\n", sqlite3_value_text(apVal
[0]));
1507 sqlite3_result_value(pCtx
, apVal
[0]);
1511 ** If in safe mode, print an error message described by the arguments
1512 ** and exit immediately.
1514 static void failIfSafeMode(
1516 const char *zErrMsg
,
1522 va_start(ap
, zErrMsg
);
1523 zMsg
= sqlite3_vmprintf(zErrMsg
, ap
);
1525 eputf("line %d: %s\n", p
->lineno
, zMsg
);
1531 ** SQL function: edit(VALUE)
1532 ** edit(VALUE,EDITOR)
1536 ** (1) Write VALUE into a temporary file.
1537 ** (2) Run program EDITOR on that temporary file.
1538 ** (3) Read the temporary file back and return its content as the result.
1539 ** (4) Delete the temporary file
1541 ** If the EDITOR argument is omitted, use the value in the VISUAL
1542 ** environment variable. If still there is no EDITOR, through an error.
1544 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1546 #ifndef SQLITE_NOHAVE_SYSTEM
1547 static void editFunc(
1548 sqlite3_context
*context
,
1550 sqlite3_value
**argv
1552 const char *zEditor
;
1553 char *zTempFile
= 0;
1562 unsigned char *p
= 0;
1565 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1567 zEditor
= getenv("VISUAL");
1570 sqlite3_result_error(context
, "no editor for edit()", -1);
1573 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1574 sqlite3_result_error(context
, "NULL input to edit()", -1);
1577 db
= sqlite3_context_db_handle(context
);
1579 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1581 sqlite3_uint64 r
= 0;
1582 sqlite3_randomness(sizeof(r
), &r
);
1583 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1585 sqlite3_result_error_nomem(context
);
1589 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1590 /* When writing the file to be edited, do \n to \r\n conversions on systems
1591 ** that want \r\n line endings */
1592 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1594 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1597 sz
= sqlite3_value_bytes(argv
[0]);
1599 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, (size_t)sz
, f
);
1601 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
1602 /* Remember whether or not the value originally contained \r\n */
1603 if( z
&& strstr(z
,"\r\n")!=0 ) hasCRNL
= 1;
1604 x
= fwrite(sqlite3_value_text(argv
[0]), 1, (size_t)sz
, f
);
1609 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1612 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1614 sqlite3_result_error_nomem(context
);
1620 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1623 f
= fopen(zTempFile
, "rb");
1625 sqlite3_result_error(context
,
1626 "edit() cannot reopen temp file after edit", -1);
1629 fseek(f
, 0, SEEK_END
);
1632 p
= sqlite3_malloc64( sz
+1 );
1634 sqlite3_result_error_nomem(context
);
1637 x
= fread(p
, 1, (size_t)sz
, f
);
1641 sqlite3_result_error(context
, "could not read back the whole file", -1);
1645 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1649 /* If the original contains \r\n then do no conversions back to \n */
1651 /* If the file did not originally contain \r\n then convert any new
1652 ** \r\n back into \n */
1654 for(i
=j
=0; i
<sz
; i
++){
1655 if( p
[i
]=='\r' && p
[i
+1]=='\n' ) i
++;
1661 sqlite3_result_text64(context
, (const char*)p
, sz
,
1662 sqlite3_free
, SQLITE_UTF8
);
1669 sqlite3_free(zTempFile
);
1672 #endif /* SQLITE_NOHAVE_SYSTEM */
1675 ** Save or restore the current output mode
1677 static void outputModePush(ShellState
*p
){
1678 p
->modePrior
= p
->mode
;
1679 p
->priorShFlgs
= p
->shellFlgs
;
1680 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1681 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1683 static void outputModePop(ShellState
*p
){
1684 p
->mode
= p
->modePrior
;
1685 p
->shellFlgs
= p
->priorShFlgs
;
1686 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1687 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1691 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1693 static void output_hex_blob(const void *pBlob
, int nBlob
){
1695 unsigned char *aBlob
= (unsigned char*)pBlob
;
1697 char *zStr
= sqlite3_malloc(nBlob
*2 + 1);
1698 shell_check_oom(zStr
);
1700 for(i
=0; i
<nBlob
; i
++){
1701 static const char aHex
[] = {
1702 '0', '1', '2', '3', '4', '5', '6', '7',
1703 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1705 zStr
[i
*2] = aHex
[ (aBlob
[i
] >> 4) ];
1706 zStr
[i
*2+1] = aHex
[ (aBlob
[i
] & 0x0F) ];
1710 oputf("X'%s'", zStr
);
1715 ** Find a string that is not found anywhere in z[]. Return a pointer
1718 ** Try to use zA and zB first. If both of those are already found in z[]
1719 ** then make up some string and store it in the buffer zBuf.
1721 static const char *unused_string(
1722 const char *z
, /* Result must not appear anywhere in z */
1723 const char *zA
, const char *zB
, /* Try these first */
1724 char *zBuf
/* Space to store a generated string */
1727 if( strstr(z
, zA
)==0 ) return zA
;
1728 if( strstr(z
, zB
)==0 ) return zB
;
1730 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1731 }while( strstr(z
,zBuf
)!=0 );
1736 ** Output the given string as a quoted string using SQL quoting conventions.
1738 ** See also: output_quoted_escaped_string()
1740 static void output_quoted_string(const char *z
){
1743 #ifndef SQLITE_SHELL_FIDDLE
1744 FILE *pfO
= setOutputStream(invalidFileStream
);
1745 setBinaryMode(pfO
, 1);
1748 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1754 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1757 oputf("%.*s", i
, z
);
1771 #ifndef SQLITE_SHELL_FIDDLE
1772 setTextMode(pfO
, 1);
1774 setTextMode(stdout
, 1);
1779 ** Output the given string as a quoted string using SQL quoting conventions.
1780 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1781 ** get corrupted by end-of-line translation facilities in some operating
1784 ** This is like output_quoted_string() but with the addition of the \r\n
1785 ** escape mechanism.
1787 static void output_quoted_escaped_string(const char *z
){
1790 #ifndef SQLITE_SHELL_FIDDLE
1791 FILE *pfO
= setOutputStream(invalidFileStream
);
1792 setBinaryMode(pfO
, 1);
1794 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1798 const char *zNL
= 0;
1799 const char *zCR
= 0;
1802 char zBuf1
[20], zBuf2
[20];
1803 for(i
=0; z
[i
]; i
++){
1804 if( z
[i
]=='\n' ) nNL
++;
1805 if( z
[i
]=='\r' ) nCR
++;
1809 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1813 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1817 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1820 oputf("%.*s", i
, z
);
1839 oputf(",'%s',char(13))", zCR
);
1842 oputf(",'%s',char(10))", zNL
);
1845 #ifndef SQLITE_SHELL_FIDDLE
1846 setTextMode(pfO
, 1);
1848 setTextMode(stdout
, 1);
1853 ** Find earliest of chars within s specified in zAny.
1854 ** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
1856 static const char *anyOfInStr(const char *s
, const char *zAny
, size_t ns
){
1857 const char *pcFirst
= 0;
1858 if( ns
== ~(size_t)0 ) ns
= strlen(s
);
1860 const char *pc
= (const char*)memchr(s
, *zAny
&0xff, ns
);
1870 ** Output the given string as a quoted according to C or TCL quoting rules.
1872 static void output_c_string(const char *z
){
1874 static const char *zq
= "\"";
1875 static long ctrlMask
= ~0L;
1876 static const char *zDQBSRO
= "\"\\\x7f"; /* double-quote, backslash, rubout */
1877 char ace
[3] = "\\?";
1881 const char *pcDQBSRO
= anyOfInStr(z
, zDQBSRO
, ~(size_t)0);
1882 const char *pcPast
= zSkipValidUtf8(z
, INT_MAX
, ctrlMask
);
1883 const char *pcEnd
= (pcDQBSRO
&& pcDQBSRO
< pcPast
)? pcDQBSRO
: pcPast
;
1884 if( pcEnd
> z
) oputb(z
, (int)(pcEnd
-z
));
1885 if( (c
= *pcEnd
)==0 ) break;
1888 case '\\': case '"':
1891 case '\t': cbsSay
= 't'; break;
1892 case '\n': cbsSay
= 'n'; break;
1893 case '\r': cbsSay
= 'r'; break;
1894 case '\f': cbsSay
= 'f'; break;
1895 default: cbsSay
= 0; break;
1900 }else if( !isprint(c
&0xff) ){
1901 oputf("\\%03o", c
&0xff);
1912 ** Output the given string as a quoted according to JSON quoting rules.
1914 static void output_json_string(const char *z
, i64 n
){
1916 static const char *zq
= "\"";
1917 static long ctrlMask
= ~0L;
1918 static const char *zDQBS
= "\"\\";
1919 const char *pcLimit
;
1920 char ace
[3] = "\\?";
1924 pcLimit
= z
+ ((n
<0)? strlen(z
) : (size_t)n
);
1926 while( z
< pcLimit
){
1927 const char *pcDQBS
= anyOfInStr(z
, zDQBS
, pcLimit
-z
);
1928 const char *pcPast
= zSkipValidUtf8(z
, (int)(pcLimit
-z
), ctrlMask
);
1929 const char *pcEnd
= (pcDQBS
&& pcDQBS
< pcPast
)? pcDQBS
: pcPast
;
1931 oputb(z
, (int)(pcEnd
-z
));
1934 if( z
>= pcLimit
) break;
1937 case '"': case '\\':
1940 case '\b': cbsSay
= 'b'; break;
1941 case '\f': cbsSay
= 'f'; break;
1942 case '\n': cbsSay
= 'n'; break;
1943 case '\r': cbsSay
= 'r'; break;
1944 case '\t': cbsSay
= 't'; break;
1945 default: cbsSay
= 0; break;
1950 }else if( c
<=0x1f ){
1961 ** Output the given string with characters that are special to
1964 static void output_html_string(const char *z
){
1980 }else if( z
[i
]=='&' ){
1982 }else if( z
[i
]=='>' ){
1984 }else if( z
[i
]=='\"' ){
1986 }else if( z
[i
]=='\'' ){
1996 ** If a field contains any character identified by a 1 in the following
1997 ** array, then the string must be quoted for CSV.
1999 static const char needCsvQuote
[] = {
2000 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2001 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2002 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2003 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2004 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2005 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2006 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2007 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2008 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2009 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2010 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2011 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2012 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2013 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2014 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2015 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2019 ** Output a single term of CSV. Actually, p->colSeparator is used for
2020 ** the separator, which may or may not be a comma. p->nullValue is
2021 ** the null value. Strings are quoted if necessary. The separator
2022 ** is only issued if bSep is true.
2024 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
2026 oputf("%s",p
->nullValue
);
2029 for(i
=0; z
[i
]; i
++){
2030 if( needCsvQuote
[((unsigned char*)z
)[i
]] ){
2035 if( i
==0 || strstr(z
, p
->colSeparator
)!=0 ){
2036 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
2037 shell_check_oom(zQuoted
);
2039 sqlite3_free(zQuoted
);
2045 oputz(p
->colSeparator
);
2050 ** This routine runs when the user presses Ctrl-C
2052 static void interrupt_handler(int NotUsed
){
2053 UNUSED_PARAMETER(NotUsed
);
2054 if( ++seenInterrupt
>1 ) exit(1);
2055 if( globalDb
) sqlite3_interrupt(globalDb
);
2058 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
2060 ** This routine runs for console events (e.g. Ctrl-C) on Win32
2062 static BOOL WINAPI
ConsoleCtrlHandler(
2063 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
2065 if( dwCtrlType
==CTRL_C_EVENT
){
2066 interrupt_handler(0);
2073 #ifndef SQLITE_OMIT_AUTHORIZATION
2075 ** This authorizer runs in safe mode.
2077 static int safeModeAuth(
2085 ShellState
*p
= (ShellState
*)pClientData
;
2086 static const char *azProhibitedFunctions
[] = {
2095 UNUSED_PARAMETER(zA1
);
2096 UNUSED_PARAMETER(zA3
);
2097 UNUSED_PARAMETER(zA4
);
2099 case SQLITE_ATTACH
: {
2100 #ifndef SQLITE_SHELL_FIDDLE
2101 /* In WASM builds the filesystem is a virtual sandbox, so
2102 ** there's no harm in using ATTACH. */
2103 failIfSafeMode(p
, "cannot run ATTACH in safe mode");
2107 case SQLITE_FUNCTION
: {
2109 for(i
=0; i
<ArraySize(azProhibitedFunctions
); i
++){
2110 if( sqlite3_stricmp(zA2
, azProhibitedFunctions
[i
])==0 ){
2111 failIfSafeMode(p
, "cannot use the %s() function in safe mode",
2112 azProhibitedFunctions
[i
]);
2122 ** When the ".auth ON" is set, the following authorizer callback is
2123 ** invoked. It always returns SQLITE_OK.
2125 static int shellAuth(
2133 ShellState
*p
= (ShellState
*)pClientData
;
2134 static const char *azAction
[] = { 0,
2135 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2136 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2137 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2138 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2139 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2140 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2141 "PRAGMA", "READ", "SELECT",
2142 "TRANSACTION", "UPDATE", "ATTACH",
2143 "DETACH", "ALTER_TABLE", "REINDEX",
2144 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2145 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2153 oputf("authorizer: %s", azAction
[op
]);
2157 output_c_string(az
[i
]);
2163 if( p
->bSafeMode
) (void)safeModeAuth(pClientData
, op
, zA1
, zA2
, zA3
, zA4
);
2169 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2171 ** This routine converts some CREATE TABLE statements for shadow tables
2172 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2174 ** If the schema statement in z[] contains a start-of-comment and if
2175 ** sqlite3_complete() returns false, try to terminate the comment before
2176 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2178 static void printSchemaLine(const char *z
, const char *zTail
){
2181 if( zTail
==0 ) return;
2182 if( zTail
[0]==';' && (strstr(z
, "/*")!=0 || strstr(z
,"--")!=0) ){
2183 const char *zOrig
= z
;
2184 static const char *azTerm
[] = { "", "*/", "\n" };
2186 for(i
=0; i
<ArraySize(azTerm
); i
++){
2187 char *zNew
= sqlite3_mprintf("%s%s;", zOrig
, azTerm
[i
]);
2188 shell_check_oom(zNew
);
2189 if( sqlite3_complete(zNew
) ){
2190 size_t n
= strlen(zNew
);
2199 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
2200 oputf("CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
2202 oputf("%s%s", z
, zTail
);
2204 sqlite3_free(zToFree
);
2206 static void printSchemaLineN(char *z
, int n
, const char *zTail
){
2209 printSchemaLine(z
, zTail
);
2214 ** Return true if string z[] has nothing but whitespace and comments to the
2215 ** end of the first line.
2217 static int wsToEol(const char *z
){
2219 for(i
=0; z
[i
]; i
++){
2220 if( z
[i
]=='\n' ) return 1;
2221 if( IsSpace(z
[i
]) ) continue;
2222 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
2229 ** Add a new entry to the EXPLAIN QUERY PLAN data
2231 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
2234 if( zText
==0 ) return;
2235 nText
= strlen(zText
);
2236 if( p
->autoEQPtest
){
2237 oputf("%d,%d,%s\n", iEqpId
, p2
, zText
);
2239 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
2240 shell_check_oom(pNew
);
2241 pNew
->iEqpId
= iEqpId
;
2242 pNew
->iParentId
= p2
;
2243 memcpy(pNew
->zText
, zText
, nText
+1);
2245 if( p
->sGraph
.pLast
){
2246 p
->sGraph
.pLast
->pNext
= pNew
;
2248 p
->sGraph
.pRow
= pNew
;
2250 p
->sGraph
.pLast
= pNew
;
2254 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2257 static void eqp_reset(ShellState
*p
){
2258 EQPGraphRow
*pRow
, *pNext
;
2259 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
2260 pNext
= pRow
->pNext
;
2263 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
2266 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2267 ** pOld, or return the first such line if pOld is NULL
2269 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
2270 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
2271 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
2275 /* Render a single level of the graph that has iEqpId as its parent. Called
2276 ** recursively to render sublevels.
2278 static void eqp_render_level(ShellState
*p
, int iEqpId
){
2279 EQPGraphRow
*pRow
, *pNext
;
2280 i64 n
= strlen(p
->sGraph
.zPrefix
);
2282 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
2283 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
2285 oputf("%s%s%s\n", p
->sGraph
.zPrefix
, pNext
? "|--" : "`--", z
);
2286 if( n
<(i64
)sizeof(p
->sGraph
.zPrefix
)-7 ){
2287 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
2288 eqp_render_level(p
, pRow
->iEqpId
);
2289 p
->sGraph
.zPrefix
[n
] = 0;
2295 ** Display and reset the EXPLAIN QUERY PLAN data
2297 static void eqp_render(ShellState
*p
, i64 nCycle
){
2298 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
2300 if( pRow
->zText
[0]=='-' ){
2301 if( pRow
->pNext
==0 ){
2305 oputf("%s\n", pRow
->zText
+3);
2306 p
->sGraph
.pRow
= pRow
->pNext
;
2308 }else if( nCycle
>0 ){
2309 oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle
);
2311 oputz("QUERY PLAN\n");
2313 p
->sGraph
.zPrefix
[0] = 0;
2314 eqp_render_level(p
, 0);
2319 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2321 ** Progress handler callback.
2323 static int progress_handler(void *pClientData
) {
2324 ShellState
*p
= (ShellState
*)pClientData
;
2326 if( p
->nProgress
>=p
->mxProgress
&& p
->mxProgress
>0 ){
2327 oputf("Progress limit reached (%u)\n", p
->nProgress
);
2328 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
2329 if( p
->flgProgress
& SHELL_PROGRESS_ONCE
) p
->mxProgress
= 0;
2332 if( (p
->flgProgress
& SHELL_PROGRESS_QUIET
)==0 ){
2333 oputf("Progress %u\n", p
->nProgress
);
2337 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2342 static void print_dashes(int N
){
2343 const char zDash
[] = "--------------------------------------------------";
2344 const int nDash
= sizeof(zDash
) - 1;
2349 oputf("%.*s", N
, zDash
);
2353 ** Print a markdown or table-style row separator using ascii-art
2355 static void print_row_separator(
2363 print_dashes(p
->actualWidth
[0]+2);
2364 for(i
=1; i
<nArg
; i
++){
2366 print_dashes(p
->actualWidth
[i
]+2);
2374 ** This is the callback routine that the shell
2375 ** invokes for each row of a query result.
2377 static int shell_callback(
2379 int nArg
, /* Number of result columns */
2380 char **azArg
, /* Text of each result column */
2381 char **azCol
, /* Column names */
2382 int *aiType
/* Column types. Might be NULL */
2385 ShellState
*p
= (ShellState
*)pArg
;
2387 if( azArg
==0 ) return 0;
2395 if( azArg
==0 ) break;
2396 for(i
=0; i
<nArg
; i
++){
2397 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
2398 if( len
>w
) w
= len
;
2400 if( p
->cnt
++>0 ) oputz(p
->rowSeparator
);
2401 for(i
=0; i
<nArg
; i
++){
2402 oputf("%*s = %s%s", w
, azCol
[i
],
2403 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
2408 case MODE_Explain
: {
2409 static const int aExplainWidth
[] = {4, 13, 4, 4, 4, 13, 2, 13};
2410 static const int aExplainMap
[] = {0, 1, 2, 3, 4, 5, 6, 7 };
2411 static const int aScanExpWidth
[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
2412 static const int aScanExpMap
[] = {0, 9, 8, 1, 2, 3, 4, 5, 6, 7 };
2414 const int *aWidth
= aExplainWidth
;
2415 const int *aMap
= aExplainMap
;
2416 int nWidth
= ArraySize(aExplainWidth
);
2419 if( p
->cMode
==MODE_ScanExp
){
2420 aWidth
= aScanExpWidth
;
2422 nWidth
= ArraySize(aScanExpWidth
);
2425 if( nArg
>nWidth
) nArg
= nWidth
;
2427 /* If this is the first row seen, print out the headers */
2429 for(i
=0; i
<nArg
; i
++){
2430 utf8_width_print(aWidth
[i
], azCol
[ aMap
[i
] ]);
2431 oputz(i
==nArg
-1 ? "\n" : " ");
2433 for(i
=0; i
<nArg
; i
++){
2434 print_dashes(aWidth
[i
]);
2435 oputz(i
==nArg
-1 ? "\n" : " ");
2439 /* If there is no data, exit early. */
2440 if( azArg
==0 ) break;
2442 for(i
=0; i
<nArg
; i
++){
2443 const char *zSep
= " ";
2445 const char *zVal
= azArg
[ aMap
[i
] ];
2446 if( i
==nArg
-1 ) w
= 0;
2447 if( zVal
&& strlenChar(zVal
)>w
){
2448 w
= strlenChar(zVal
);
2451 if( i
==iIndent
&& p
->aiIndent
&& p
->pStmt
){
2452 if( p
->iIndent
<p
->nIndent
){
2453 oputf("%*.s", p
->aiIndent
[p
->iIndent
], "");
2457 utf8_width_print(w
, zVal
? zVal
: p
->nullValue
);
2458 oputz(i
==nArg
-1 ? "\n" : zSep
);
2462 case MODE_Semi
: { /* .schema and .fullschema output */
2463 printSchemaLine(azArg
[0], ";\n");
2466 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
2474 if( azArg
[0]==0 ) break;
2475 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
2476 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
2478 oputf("%s;\n", azArg
[0]);
2481 z
= sqlite3_mprintf("%s", azArg
[0]);
2484 for(i
=0; IsSpace(z
[i
]); i
++){}
2485 for(; (c
= z
[i
])!=0; i
++){
2487 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
2488 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
2489 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
2494 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
2496 if( strlen30(z
)>=79 ){
2497 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy from z[i] back to z[j] */
2500 }else if( c
=='"' || c
=='\'' || c
=='`' ){
2504 }else if( c
=='-' && z
[i
+1]=='-' ){
2510 if( nLine
>0 && nParen
==0 && j
>0 ){
2511 printSchemaLineN(z
, j
, "\n");
2516 if( nParen
==1 && cEnd
==0
2517 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
2520 printSchemaLineN(z
, j
, "\n ");
2523 while( IsSpace(z
[i
+1]) ){ i
++; }
2528 printSchemaLine(z
, ";\n");
2533 if( p
->cnt
++==0 && p
->showHeader
){
2534 for(i
=0; i
<nArg
; i
++){
2535 oputf("%s%s",azCol
[i
], i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
2538 if( azArg
==0 ) break;
2539 for(i
=0; i
<nArg
; i
++){
2541 if( z
==0 ) z
= p
->nullValue
;
2543 oputz((i
<nArg
-1)? p
->colSeparator
: p
->rowSeparator
);
2548 if( p
->cnt
++==0 && p
->showHeader
){
2550 for(i
=0; i
<nArg
; i
++){
2552 output_html_string(azCol
[i
]);
2557 if( azArg
==0 ) break;
2559 for(i
=0; i
<nArg
; i
++){
2561 output_html_string(azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2568 if( p
->cnt
++==0 && p
->showHeader
){
2569 for(i
=0; i
<nArg
; i
++){
2570 output_c_string(azCol
[i
] ? azCol
[i
] : "");
2571 if(i
<nArg
-1) oputz(p
->colSeparator
);
2573 oputz(p
->rowSeparator
);
2575 if( azArg
==0 ) break;
2576 for(i
=0; i
<nArg
; i
++){
2577 output_c_string(azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2578 if(i
<nArg
-1) oputz(p
->colSeparator
);
2580 oputz(p
->rowSeparator
);
2584 setBinaryMode(p
->out
, 1);
2585 if( p
->cnt
++==0 && p
->showHeader
){
2586 for(i
=0; i
<nArg
; i
++){
2587 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
2589 oputz(p
->rowSeparator
);
2592 for(i
=0; i
<nArg
; i
++){
2593 output_csv(p
, azArg
[i
], i
<nArg
-1);
2595 oputz(p
->rowSeparator
);
2597 setTextMode(p
->out
, 1);
2601 if( azArg
==0 ) break;
2602 oputf("INSERT INTO %s",p
->zDestTable
);
2603 if( p
->showHeader
){
2605 for(i
=0; i
<nArg
; i
++){
2606 if( i
>0 ) oputz(",");
2607 if( quoteChar(azCol
[i
]) ){
2608 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2613 oputf("%s", azCol
[i
]);
2619 for(i
=0; i
<nArg
; i
++){
2620 oputz(i
>0 ? "," : " VALUES(");
2621 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2623 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2624 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2625 output_quoted_string(azArg
[i
]);
2627 output_quoted_escaped_string(azArg
[i
]);
2629 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2631 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2633 double r
= sqlite3_column_double(p
->pStmt
, i
);
2635 memcpy(&ur
,&r
,sizeof(r
));
2636 if( ur
==0x7ff0000000000000LL
){
2638 }else if( ur
==0xfff0000000000000LL
){
2641 sqlite3_int64 ir
= (sqlite3_int64
)r
;
2642 if( r
==(double)ir
){
2643 sqlite3_snprintf(50,z
,"%lld.0", ir
);
2645 sqlite3_snprintf(50,z
,"%!.20g", r
);
2649 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2650 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2651 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2652 output_hex_blob(pBlob
, nBlob
);
2653 }else if( isNumber(azArg
[i
], 0) ){
2655 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2656 output_quoted_string(azArg
[i
]);
2658 output_quoted_escaped_string(azArg
[i
]);
2665 if( azArg
==0 ) break;
2667 fputs("[{", p
->out
);
2669 fputs(",\n{", p
->out
);
2672 for(i
=0; i
<nArg
; i
++){
2673 output_json_string(azCol
[i
], -1);
2675 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2677 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2679 double r
= sqlite3_column_double(p
->pStmt
, i
);
2681 memcpy(&ur
,&r
,sizeof(r
));
2682 if( ur
==0x7ff0000000000000LL
){
2684 }else if( ur
==0xfff0000000000000LL
){
2687 sqlite3_snprintf(50,z
,"%!.20g", r
);
2690 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2691 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2692 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2693 output_json_string(pBlob
, nBlob
);
2694 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2695 output_json_string(azArg
[i
], -1);
2707 if( azArg
==0 ) break;
2708 if( p
->cnt
==0 && p
->showHeader
){
2709 for(i
=0; i
<nArg
; i
++){
2710 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2711 output_quoted_string(azCol
[i
]);
2713 fputs(p
->rowSeparator
, p
->out
);
2716 for(i
=0; i
<nArg
; i
++){
2717 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2718 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2720 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2721 output_quoted_string(azArg
[i
]);
2722 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2724 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2726 double r
= sqlite3_column_double(p
->pStmt
, i
);
2727 sqlite3_snprintf(50,z
,"%!.20g", r
);
2729 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2730 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2731 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2732 output_hex_blob(pBlob
, nBlob
);
2733 }else if( isNumber(azArg
[i
], 0) ){
2736 output_quoted_string(azArg
[i
]);
2739 fputs(p
->rowSeparator
, p
->out
);
2743 if( p
->cnt
++==0 && p
->showHeader
){
2744 for(i
=0; i
<nArg
; i
++){
2745 if( i
>0 ) oputz(p
->colSeparator
);
2746 oputz(azCol
[i
] ? azCol
[i
] : "");
2748 oputz(p
->rowSeparator
);
2750 if( azArg
==0 ) break;
2751 for(i
=0; i
<nArg
; i
++){
2752 if( i
>0 ) oputz(p
->colSeparator
);
2753 oputz(azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2755 oputz(p
->rowSeparator
);
2759 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2767 ** This is the callback routine that the SQLite library
2768 ** invokes for each row of a query result.
2770 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2771 /* since we don't have type info, call the shell_callback with a NULL value */
2772 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2776 ** This is the callback routine from sqlite3_exec() that appends all
2777 ** output onto the end of a ShellText object.
2779 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2780 ShellText
*p
= (ShellText
*)pArg
;
2782 UNUSED_PARAMETER(az
);
2783 if( azArg
==0 ) return 0;
2784 if( p
->n
) appendText(p
, "|", 0);
2785 for(i
=0; i
<nArg
; i
++){
2786 if( i
) appendText(p
, ",", 0);
2787 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2793 ** Generate an appropriate SELFTEST table in the main database.
2795 static void createSelftestTable(ShellState
*p
){
2798 "SAVEPOINT selftest_init;\n"
2799 "CREATE TABLE IF NOT EXISTS selftest(\n"
2800 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2801 " op TEXT,\n" /* Operator: memo run */
2802 " cmd TEXT,\n" /* Command text */
2803 " ans TEXT\n" /* Desired answer */
2805 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2806 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2807 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2808 " 'memo','Tests generated by --init');\n"
2809 "INSERT INTO [_shell$self]\n"
2811 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2812 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2813 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2814 "FROM sqlite_schema ORDER BY 2',224));\n"
2815 "INSERT INTO [_shell$self]\n"
2817 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2818 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2819 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2821 " SELECT name FROM sqlite_schema\n"
2822 " WHERE type='table'\n"
2823 " AND name<>'selftest'\n"
2824 " AND coalesce(rootpage,0)>0\n"
2827 "INSERT INTO [_shell$self]\n"
2828 " VALUES('run','PRAGMA integrity_check','ok');\n"
2829 "INSERT INTO selftest(tno,op,cmd,ans)"
2830 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2831 "DROP TABLE [_shell$self];"
2834 eputf("SELFTEST initialization failure: %s\n", zErrMsg
);
2835 sqlite3_free(zErrMsg
);
2837 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2842 ** Set the destination table field of the ShellState structure to
2843 ** the name of the table given. Escape any quote characters in the
2846 static void set_table_name(ShellState
*p
, const char *zName
){
2851 if( p
->zDestTable
){
2852 free(p
->zDestTable
);
2855 if( zName
==0 ) return;
2856 cQuote
= quoteChar(zName
);
2857 n
= strlen30(zName
);
2858 if( cQuote
) n
+= n
+2;
2859 z
= p
->zDestTable
= malloc( n
+1 );
2862 if( cQuote
) z
[n
++] = cQuote
;
2863 for(i
=0; zName
[i
]; i
++){
2865 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2867 if( cQuote
) z
[n
++] = cQuote
;
2872 ** Maybe construct two lines of text that point out the position of a
2873 ** syntax error. Return a pointer to the text, in memory obtained from
2874 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2875 ** specific token that we can point to, return an empty string.
2877 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2878 ** and should be released by the caller invoking sqlite3_free().
2880 static char *shell_error_context(const char *zSql
, sqlite3
*db
){
2888 || (iOffset
= sqlite3_error_offset(db
))<0
2889 || iOffset
>=(int)strlen(zSql
)
2891 return sqlite3_mprintf("");
2893 while( iOffset
>50 ){
2896 while( (zSql
[0]&0xc0)==0x80 ){ zSql
++; iOffset
--; }
2901 while( len
>0 && (zSql
[len
]&0xc0)==0x80 ) len
--;
2903 zCode
= sqlite3_mprintf("%.*s", len
, zSql
);
2904 shell_check_oom(zCode
);
2905 for(i
=0; zCode
[i
]; i
++){ if( IsSpace(zSql
[i
]) ) zCode
[i
] = ' '; }
2907 zMsg
= sqlite3_mprintf("\n %z\n %*s^--- error here", zCode
,iOffset
,"");
2909 zMsg
= sqlite3_mprintf("\n %z\n %*serror here ---^", zCode
,iOffset
-14,"");
2916 ** Execute a query statement that will generate SQL output. Print
2917 ** the result columns, comma-separated, on a line and then add a
2918 ** semicolon terminator to the end of that line.
2920 ** If the number of columns is 1 and that column contains text "--"
2921 ** then write the semicolon on a separate line. That way, if a
2922 ** "--" comment occurs at the end of the statement, the comment
2923 ** won't consume the semicolon terminator.
2925 static int run_table_dump_query(
2926 ShellState
*p
, /* Query context */
2927 const char *zSelect
/* SELECT statement to extract content */
2929 sqlite3_stmt
*pSelect
;
2934 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2935 if( rc
!=SQLITE_OK
|| !pSelect
){
2936 char *zContext
= shell_error_context(zSelect
, p
->db
);
2937 oputf("/**** ERROR: (%d) %s *****/\n%s",
2938 rc
, sqlite3_errmsg(p
->db
), zContext
);
2939 sqlite3_free(zContext
);
2940 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2943 rc
= sqlite3_step(pSelect
);
2944 nResult
= sqlite3_column_count(pSelect
);
2945 while( rc
==SQLITE_ROW
){
2946 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2948 for(i
=1; i
<nResult
; i
++){
2949 oputf(",%s", sqlite3_column_text(pSelect
, i
));
2952 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2958 rc
= sqlite3_step(pSelect
);
2960 rc
= sqlite3_finalize(pSelect
);
2961 if( rc
!=SQLITE_OK
){
2962 oputf("/**** ERROR: (%d) %s *****/\n", rc
, sqlite3_errmsg(p
->db
));
2963 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2969 ** Allocate space and save off string indicating current error.
2971 static char *save_err_msg(
2972 sqlite3
*db
, /* Database to query */
2973 const char *zPhase
, /* When the error occurs */
2974 int rc
, /* Error code returned from API */
2975 const char *zSql
/* SQL string, or NULL */
2979 sqlite3_str
*pStr
= sqlite3_str_new(0);
2980 sqlite3_str_appendf(pStr
, "%s, %s", zPhase
, sqlite3_errmsg(db
));
2982 sqlite3_str_appendf(pStr
, " (%d)", rc
);
2984 zContext
= shell_error_context(zSql
, db
);
2986 sqlite3_str_appendall(pStr
, zContext
);
2987 sqlite3_free(zContext
);
2989 zErr
= sqlite3_str_finish(pStr
);
2990 shell_check_oom(zErr
);
2996 ** Attempt to display I/O stats on Linux using /proc/PID/io
2998 static void displayLinuxIoStats(void){
3001 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
3002 in
= fopen(z
, "rb");
3004 while( fgets(z
, sizeof(z
), in
)!=0 ){
3005 static const struct {
3006 const char *zPattern
;
3009 { "rchar: ", "Bytes received by read():" },
3010 { "wchar: ", "Bytes sent to write():" },
3011 { "syscr: ", "Read() system calls:" },
3012 { "syscw: ", "Write() system calls:" },
3013 { "read_bytes: ", "Bytes read from storage:" },
3014 { "write_bytes: ", "Bytes written to storage:" },
3015 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
3018 for(i
=0; i
<ArraySize(aTrans
); i
++){
3019 int n
= strlen30(aTrans
[i
].zPattern
);
3020 if( cli_strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
3021 oputf("%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
3031 ** Display a single line of status using 64-bit values.
3033 static void displayStatLine(
3034 char *zLabel
, /* Label for this one line */
3035 char *zFormat
, /* Format for the result */
3036 int iStatusCtrl
, /* Which status to display */
3037 int bReset
/* True to reset the stats */
3039 sqlite3_int64 iCur
= -1;
3040 sqlite3_int64 iHiwtr
= -1;
3043 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
3044 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
3045 if( zFormat
[i
]=='%' ) nPercent
++;
3048 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
3050 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
3052 oputf("%-36s %s\n", zLabel
, zLine
);
3056 ** Display memory stats.
3058 static int display_stats(
3059 sqlite3
*db
, /* Database to query */
3060 ShellState
*pArg
, /* Pointer to ShellState */
3061 int bReset
/* True to reset the stats */
3065 if( pArg
==0 || pArg
->out
==0 ) return 0;
3067 if( pArg
->pStmt
&& pArg
->statsOn
==2 ){
3069 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
3071 nCol
= sqlite3_column_count(pStmt
);
3072 oputf("%-36s %d\n", "Number of output columns:", nCol
);
3073 for(i
=0; i
<nCol
; i
++){
3074 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
3075 oputf("%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
3076 #ifndef SQLITE_OMIT_DECLTYPE
3077 sqlite3_snprintf(30, z
+x
, "declared type:");
3078 oputf("%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
3080 #ifdef SQLITE_ENABLE_COLUMN_METADATA
3081 sqlite3_snprintf(30, z
+x
, "database name:");
3082 oputf("%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
3083 sqlite3_snprintf(30, z
+x
, "table name:");
3084 oputf("%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
3085 sqlite3_snprintf(30, z
+x
, "origin name:");
3086 oputf("%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
3091 if( pArg
->statsOn
==3 ){
3093 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
,bReset
);
3094 oputf("VM-steps: %d\n", iCur
);
3099 displayStatLine("Memory Used:",
3100 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
3101 displayStatLine("Number of Outstanding Allocations:",
3102 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
3103 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
3104 displayStatLine("Number of Pcache Pages Used:",
3105 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
3107 displayStatLine("Number of Pcache Overflow Bytes:",
3108 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
3109 displayStatLine("Largest Allocation:",
3110 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
3111 displayStatLine("Largest Pcache Allocation:",
3112 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
3113 #ifdef YYTRACKMAXSTACKDEPTH
3114 displayStatLine("Deepest Parser Stack:",
3115 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
3119 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
3121 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
3122 &iCur
, &iHiwtr
, bReset
);
3123 oputf("Lookaside Slots Used: %d (max %d)\n", iCur
, iHiwtr
);
3124 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
3125 &iCur
, &iHiwtr
, bReset
);
3126 oputf("Successful lookaside attempts: %d\n", iHiwtr
);
3127 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
3128 &iCur
, &iHiwtr
, bReset
);
3129 oputf("Lookaside failures due to size: %d\n", iHiwtr
);
3130 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
3131 &iCur
, &iHiwtr
, bReset
);
3132 oputf("Lookaside failures due to OOM: %d\n", iHiwtr
);
3135 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
3136 oputf("Pager Heap Usage: %d bytes\n", iCur
);
3138 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
3139 oputf("Page cache hits: %d\n", iCur
);
3141 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
3142 oputf("Page cache misses: %d\n", iCur
);
3144 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
3145 oputf("Page cache writes: %d\n", iCur
);
3147 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
3148 oputf("Page cache spills: %d\n", iCur
);
3150 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
3151 oputf("Schema Heap Usage: %d bytes\n", iCur
);
3153 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
3154 oputf("Statement Heap/Lookaside Usage: %d bytes\n", iCur
);
3159 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
3161 oputf("Fullscan Steps: %d\n", iCur
);
3162 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
3163 oputf("Sort Operations: %d\n", iCur
);
3164 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
3165 oputf("Autoindex Inserts: %d\n", iCur
);
3166 iHit
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_HIT
,
3168 iMiss
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_MISS
,
3170 if( iHit
|| iMiss
){
3171 oputf("Bloom filter bypass taken: %d/%d\n", iHit
, iHit
+iMiss
);
3173 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
3174 oputf("Virtual Machine Steps: %d\n", iCur
);
3175 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
,bReset
);
3176 oputf("Reprepare operations: %d\n", iCur
);
3177 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
3178 oputf("Number of times run: %d\n", iCur
);
3179 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
3180 oputf("Memory used by prepared stmt: %d\n", iCur
);
3184 displayLinuxIoStats();
3187 /* Do not remove this machine readable comment: extra-stats-output-here */
3193 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3194 static int scanStatsHeight(sqlite3_stmt
*p
, int iEntry
){
3197 sqlite3_stmt_scanstatus_v2(p
, iEntry
,
3198 SQLITE_SCANSTAT_SELECTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iPid
3205 res
= sqlite3_stmt_scanstatus_v2(p
, ii
,
3206 SQLITE_SCANSTAT_SELECTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iId
3210 sqlite3_stmt_scanstatus_v2(p
, ii
,
3211 SQLITE_SCANSTAT_PARENTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iPid
3221 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3222 static void display_explain_scanstats(
3223 sqlite3
*db
, /* Database to query */
3224 ShellState
*pArg
/* Pointer to ShellState */
3226 static const int f
= SQLITE_SCANSTAT_COMPLEX
;
3227 sqlite3_stmt
*p
= pArg
->pStmt
;
3236 if( sqlite3_stmt_scanstatus_v2(p
,ii
,SQLITE_SCANSTAT_EXPLAIN
,f
,(void*)&z
) ){
3239 n
= (int)strlen(z
) + scanStatsHeight(p
, ii
)*3;
3240 if( n
>nWidth
) nWidth
= n
;
3244 sqlite3_stmt_scanstatus_v2(p
, -1, SQLITE_SCANSTAT_NCYCLE
, f
, (void*)&nTotal
);
3252 const char *zName
= 0;
3256 if( sqlite3_stmt_scanstatus_v2(p
,ii
,SQLITE_SCANSTAT_EXPLAIN
,f
,(void*)&zo
) ){
3259 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_EST
,f
,(void*)&rEst
);
3260 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NLOOP
,f
,(void*)&nLoop
);
3261 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NVISIT
,f
,(void*)&nRow
);
3262 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NCYCLE
,f
,(void*)&nCycle
);
3263 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_SELECTID
,f
,(void*)&iId
);
3264 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_PARENTID
,f
,(void*)&iPid
);
3265 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NAME
,f
,(void*)&zName
);
3267 zText
= sqlite3_mprintf("%s", zo
);
3268 if( nCycle
>=0 || nLoop
>=0 || nRow
>=0 ){
3270 if( nCycle
>=0 && nTotal
>0 ){
3271 z
= sqlite3_mprintf("%zcycles=%lld [%d%%]", z
,
3272 nCycle
, ((nCycle
*100)+nTotal
/2) / nTotal
3276 z
= sqlite3_mprintf("%z%sloops=%lld", z
, z
? " " : "", nLoop
);
3279 z
= sqlite3_mprintf("%z%srows=%lld", z
, z
? " " : "", nRow
);
3282 if( zName
&& pArg
->scanstatsOn
>1 ){
3283 double rpl
= (double)nRow
/ (double)nLoop
;
3284 z
= sqlite3_mprintf("%z rpl=%.1f est=%.1f", z
, rpl
, rEst
);
3287 zText
= sqlite3_mprintf(
3288 "% *z (%z)", -1*(nWidth
-scanStatsHeight(p
, ii
)*3), zText
, z
3292 eqp_append(pArg
, iId
, iPid
, zText
);
3293 sqlite3_free(zText
);
3296 eqp_render(pArg
, nTotal
);
3302 ** Parameter azArray points to a zero-terminated array of strings. zStr
3303 ** points to a single nul-terminated string. Return non-zero if zStr
3304 ** is equal, according to strcmp(), to any of the strings in the array.
3305 ** Otherwise, return zero.
3307 static int str_in_array(const char *zStr
, const char **azArray
){
3309 for(i
=0; azArray
[i
]; i
++){
3310 if( 0==cli_strcmp(zStr
, azArray
[i
]) ) return 1;
3316 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3317 ** and populate the ShellState.aiIndent[] array with the number of
3318 ** spaces each opcode should be indented before it is output.
3320 ** The indenting rules are:
3322 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3323 ** all opcodes that occur between the p2 jump destination and the opcode
3324 ** itself by 2 spaces.
3326 ** * Do the previous for "Return" instructions for when P2 is positive.
3327 ** See tag-20220407a in wherecode.c and vdbe.c.
3329 ** * For each "Goto", if the jump destination is earlier in the program
3330 ** and ends on one of:
3331 ** Yield SeekGt SeekLt RowSetRead Rewind
3332 ** or if the P1 parameter is one instead of zero,
3333 ** then indent all opcodes between the earlier instruction
3334 ** and "Goto" by 2 spaces.
3336 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
3337 int *abYield
= 0; /* True if op is an OP_Yield */
3338 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
3339 int iOp
; /* Index of operation in p->aiIndent[] */
3341 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3343 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3345 const char *azGoto
[] = { "Goto", 0 };
3347 /* The caller guarantees that the leftmost 4 columns of the statement
3348 ** passed to this function are equivalent to the leftmost 4 columns
3349 ** of EXPLAIN statement output. In practice the statement may be
3350 ** an EXPLAIN, or it may be a query on the bytecode() virtual table. */
3351 assert( sqlite3_column_count(pSql
)>=4 );
3352 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql
, 0), "addr" ) );
3353 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql
, 1), "opcode" ) );
3354 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql
, 2), "p1" ) );
3355 assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql
, 3), "p2" ) );
3357 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
3359 int iAddr
= sqlite3_column_int(pSql
, 0);
3360 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
3361 int p1
= sqlite3_column_int(pSql
, 2);
3362 int p2
= sqlite3_column_int(pSql
, 3);
3364 /* Assuming that p2 is an instruction address, set variable p2op to the
3365 ** index of that instruction in the aiIndent[] array. p2 and p2op may be
3366 ** different if the current instruction is part of a sub-program generated
3367 ** by an SQL trigger or foreign key. */
3368 int p2op
= (p2
+ (iOp
-iAddr
));
3370 /* Grow the p->aiIndent array as required */
3373 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
3374 shell_check_oom(p
->aiIndent
);
3375 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
3376 shell_check_oom(abYield
);
3379 abYield
[iOp
] = str_in_array(zOp
, azYield
);
3380 p
->aiIndent
[iOp
] = 0;
3382 if( str_in_array(zOp
, azNext
) && p2op
>0 ){
3383 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3385 if( str_in_array(zOp
, azGoto
) && p2op
<iOp
&& (abYield
[p2op
] || p1
) ){
3386 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3391 sqlite3_free(abYield
);
3392 sqlite3_reset(pSql
);
3396 ** Free the array allocated by explain_data_prepare().
3398 static void explain_data_delete(ShellState
*p
){
3399 sqlite3_free(p
->aiIndent
);
3405 static void exec_prepared_stmt(ShellState
*, sqlite3_stmt
*);
3408 ** Display scan stats.
3410 static void display_scanstats(
3411 sqlite3
*db
, /* Database to query */
3412 ShellState
*pArg
/* Pointer to ShellState */
3414 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3415 UNUSED_PARAMETER(db
);
3416 UNUSED_PARAMETER(pArg
);
3418 if( pArg
->scanstatsOn
==3 ){
3420 " SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
3421 " round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
3422 " FROM bytecode(?)";
3425 sqlite3_stmt
*pStmt
= 0;
3426 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
3427 if( rc
==SQLITE_OK
){
3428 sqlite3_stmt
*pSave
= pArg
->pStmt
;
3429 pArg
->pStmt
= pStmt
;
3430 sqlite3_bind_pointer(pStmt
, 1, pSave
, "stmt-pointer", 0);
3433 pArg
->cMode
= MODE_ScanExp
;
3434 explain_data_prepare(pArg
, pStmt
);
3435 exec_prepared_stmt(pArg
, pStmt
);
3436 explain_data_delete(pArg
);
3438 sqlite3_finalize(pStmt
);
3439 pArg
->pStmt
= pSave
;
3442 display_explain_scanstats(db
, pArg
);
3448 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3450 static unsigned int savedSelectTrace
;
3451 static unsigned int savedWhereTrace
;
3452 static void disable_debug_trace_modes(void){
3453 unsigned int zero
= 0;
3454 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 0, &savedSelectTrace
);
3455 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &zero
);
3456 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 2, &savedWhereTrace
);
3457 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &zero
);
3459 static void restore_debug_trace_modes(void){
3460 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &savedSelectTrace
);
3461 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &savedWhereTrace
);
3464 /* Create the TEMP table used to store parameter bindings */
3465 static void bind_table_init(ShellState
*p
){
3467 int defensiveMode
= 0;
3468 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, -1, &defensiveMode
);
3469 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, 0, 0);
3470 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, -1, &wrSchema
);
3471 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, 1, 0);
3473 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3474 " key TEXT PRIMARY KEY,\n"
3478 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, wrSchema
, 0);
3479 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, defensiveMode
, 0);
3483 ** Bind parameters on a prepared statement.
3485 ** Parameter bindings are taken from a TEMP table of the form:
3487 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3490 ** No bindings occur if this table does not exist. The name of the table
3491 ** begins with "sqlite_" so that it will not collide with ordinary application
3492 ** tables. The table must be in the TEMP schema.
3494 static void bind_prepared_stmt(ShellState
*pArg
, sqlite3_stmt
*pStmt
){
3498 sqlite3_stmt
*pQ
= 0;
3500 nVar
= sqlite3_bind_parameter_count(pStmt
);
3501 if( nVar
==0 ) return; /* Nothing to do */
3502 if( sqlite3_table_column_metadata(pArg
->db
, "TEMP", "sqlite_parameters",
3503 "key", 0, 0, 0, 0, 0)!=SQLITE_OK
){
3504 rc
= SQLITE_NOTFOUND
;
3507 rc
= sqlite3_prepare_v2(pArg
->db
,
3508 "SELECT value FROM temp.sqlite_parameters"
3509 " WHERE key=?1", -1, &pQ
, 0);
3511 for(i
=1; i
<=nVar
; i
++){
3513 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
3515 sqlite3_snprintf(sizeof(zNum
),zNum
,"?%d",i
);
3518 sqlite3_bind_text(pQ
, 1, zVar
, -1, SQLITE_STATIC
);
3519 if( rc
==SQLITE_OK
&& pQ
&& sqlite3_step(pQ
)==SQLITE_ROW
){
3520 sqlite3_bind_value(pStmt
, i
, sqlite3_column_value(pQ
, 0));
3522 }else if( sqlite3_strlike("_NAN", zVar
, 0)==0 ){
3523 sqlite3_bind_double(pStmt
, i
, NAN
);
3526 }else if( sqlite3_strlike("_INF", zVar
, 0)==0 ){
3527 sqlite3_bind_double(pStmt
, i
, INFINITY
);
3530 sqlite3_bind_null(pStmt
, i
);
3534 sqlite3_finalize(pQ
);
3538 ** UTF8 box-drawing characters. Imagine box lines like this:
3546 ** Each box characters has between 2 and 4 of the lines leading from
3547 ** the center. The characters are here identified by the numbers of
3548 ** their corresponding lines.
3550 #define BOX_24 "\342\224\200" /* U+2500 --- */
3551 #define BOX_13 "\342\224\202" /* U+2502 | */
3552 #define BOX_23 "\342\224\214" /* U+250c ,- */
3553 #define BOX_34 "\342\224\220" /* U+2510 -, */
3554 #define BOX_12 "\342\224\224" /* U+2514 '- */
3555 #define BOX_14 "\342\224\230" /* U+2518 -' */
3556 #define BOX_123 "\342\224\234" /* U+251c |- */
3557 #define BOX_134 "\342\224\244" /* U+2524 -| */
3558 #define BOX_234 "\342\224\254" /* U+252c -,- */
3559 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3560 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3562 /* Draw horizontal line N characters long using unicode box
3565 static void print_box_line(int N
){
3566 const char zDash
[] =
3567 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3568 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
;
3569 const int nDash
= sizeof(zDash
) - 1;
3575 oputf("%.*s", N
, zDash
);
3579 ** Draw a horizontal separator for a MODE_Box table.
3581 static void print_box_row_separator(
3591 print_box_line(p
->actualWidth
[0]+2);
3592 for(i
=1; i
<nArg
; i
++){
3594 print_box_line(p
->actualWidth
[i
]+2);
3602 ** z[] is a line of text that is to be displayed the .mode box or table or
3603 ** similar tabular formats. z[] might contain control characters such
3604 ** as \n, \t, \f, or \r.
3606 ** Compute characters to display on the first line of z[]. Stop at the
3607 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3608 ** from malloc()) of that first line, which caller should free sometime.
3609 ** Write anything to display on the next line into *pzTail. If this is
3610 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3612 static char *translateForDisplayAndDup(
3613 const unsigned char *z
, /* Input text to be transformed */
3614 const unsigned char **pzTail
, /* OUT: Tail of the input for next line */
3615 int mxWidth
, /* Max width. 0 means no limit */
3616 u8 bWordWrap
/* If true, avoid breaking mid-word */
3618 int i
; /* Input bytes consumed */
3619 int j
; /* Output bytes generated */
3620 int k
; /* Input bytes to be displayed */
3621 int n
; /* Output column number */
3622 unsigned char *zOut
; /* Output text */
3628 if( mxWidth
<0 ) mxWidth
= -mxWidth
;
3629 if( mxWidth
==0 ) mxWidth
= 1000000;
3634 do{ i
++; j
++; }while( (z
[i
]&0xc0)==0x80 );
3641 }while( (n
&7)!=0 && n
<mxWidth
);
3647 if( n
>=mxWidth
&& bWordWrap
){
3648 /* Perhaps try to back up to a better place to break the line */
3649 for(k
=i
; k
>i
/2; k
--){
3650 if( isspace(z
[k
-1]) ) break;
3653 for(k
=i
; k
>i
/2; k
--){
3654 if( isalnum(z
[k
-1])!=isalnum(z
[k
]) && (z
[k
]&0xc0)!=0x80 ) break;
3661 while( z
[i
]==' ' ) i
++;
3666 if( n
>=mxWidth
&& z
[i
]>=' ' ){
3668 }else if( z
[i
]=='\r' && z
[i
+1]=='\n' ){
3669 *pzTail
= z
[i
+2] ? &z
[i
+2] : 0;
3670 }else if( z
[i
]==0 || z
[i
+1]==0 ){
3675 zOut
= malloc( j
+1 );
3676 shell_check_oom(zOut
);
3681 do{ zOut
[j
++] = z
[i
++]; }while( (z
[i
]&0xc0)==0x80 );
3688 }while( (n
&7)!=0 && n
<mxWidth
);
3698 /* Extract the value of the i-th current column for pStmt as an SQL literal
3699 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3702 static char *quoted_column(sqlite3_stmt
*pStmt
, int i
){
3703 switch( sqlite3_column_type(pStmt
, i
) ){
3705 return sqlite3_mprintf("NULL");
3707 case SQLITE_INTEGER
:
3708 case SQLITE_FLOAT
: {
3709 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt
,i
));
3712 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt
,i
));
3716 sqlite3_str
*pStr
= sqlite3_str_new(0);
3717 const unsigned char *a
= sqlite3_column_blob(pStmt
,i
);
3718 int n
= sqlite3_column_bytes(pStmt
,i
);
3719 sqlite3_str_append(pStr
, "x'", 2);
3721 sqlite3_str_appendf(pStr
, "%02x", a
[j
]);
3723 sqlite3_str_append(pStr
, "'", 1);
3724 return sqlite3_str_finish(pStr
);
3727 return 0; /* Not reached */
3731 ** Run a prepared statement and output the result in one of the
3732 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3735 ** This is different from ordinary exec_prepared_stmt() in that
3736 ** it has to run the entire query and gather the results into memory
3737 ** first, in order to determine column widths, before providing
3740 static void exec_prepared_stmt_columnar(
3741 ShellState
*p
, /* Pointer to ShellState */
3742 sqlite3_stmt
*pStmt
/* Statement to run */
3744 sqlite3_int64 nRow
= 0;
3747 sqlite3_int64 nAlloc
= 0;
3749 const unsigned char *uz
;
3751 char **azQuoted
= 0;
3753 sqlite3_int64 i
, nData
;
3754 int j
, nTotal
, w
, n
;
3755 const char *colSep
= 0;
3756 const char *rowSep
= 0;
3757 const unsigned char **azNextLine
= 0;
3759 int bMultiLineRowExists
= 0;
3760 int bw
= p
->cmOpts
.bWordWrap
;
3761 const char *zEmpty
= "";
3762 const char *zShowNull
= p
->nullValue
;
3764 rc
= sqlite3_step(pStmt
);
3765 if( rc
!=SQLITE_ROW
) return;
3766 nColumn
= sqlite3_column_count(pStmt
);
3767 if( nColumn
==0 ) goto columnar_end
;
3769 if( nAlloc
<=0 ) nAlloc
= 1;
3770 azData
= sqlite3_malloc64( nAlloc
*sizeof(char*) );
3771 shell_check_oom(azData
);
3772 azNextLine
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3773 shell_check_oom(azNextLine
);
3774 memset((void*)azNextLine
, 0, nColumn
*sizeof(char*) );
3775 if( p
->cmOpts
.bQuote
){
3776 azQuoted
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3777 shell_check_oom(azQuoted
);
3778 memset(azQuoted
, 0, nColumn
*sizeof(char*) );
3780 abRowDiv
= sqlite3_malloc64( nAlloc
/nColumn
);
3781 shell_check_oom(abRowDiv
);
3782 if( nColumn
>p
->nWidth
){
3783 p
->colWidth
= realloc(p
->colWidth
, (nColumn
+1)*2*sizeof(int));
3784 shell_check_oom(p
->colWidth
);
3785 for(i
=p
->nWidth
; i
<nColumn
; i
++) p
->colWidth
[i
] = 0;
3786 p
->nWidth
= nColumn
;
3787 p
->actualWidth
= &p
->colWidth
[nColumn
];
3789 memset(p
->actualWidth
, 0, nColumn
*sizeof(int));
3790 for(i
=0; i
<nColumn
; i
++){
3793 p
->actualWidth
[i
] = w
;
3795 for(i
=0; i
<nColumn
; i
++){
3796 const unsigned char *zNotUsed
;
3797 int wx
= p
->colWidth
[i
];
3799 wx
= p
->cmOpts
.iWrap
;
3801 if( wx
<0 ) wx
= -wx
;
3802 uz
= (const unsigned char*)sqlite3_column_name(pStmt
,i
);
3803 if( uz
==0 ) uz
= (u8
*)"";
3804 azData
[i
] = translateForDisplayAndDup(uz
, &zNotUsed
, wx
, bw
);
3807 int useNextLine
= bNextLine
;
3809 if( (nRow
+2)*nColumn
>= nAlloc
){
3811 azData
= sqlite3_realloc64(azData
, nAlloc
*sizeof(char*));
3812 shell_check_oom(azData
);
3813 abRowDiv
= sqlite3_realloc64(abRowDiv
, nAlloc
/nColumn
);
3814 shell_check_oom(abRowDiv
);
3818 for(i
=0; i
<nColumn
; i
++){
3819 int wx
= p
->colWidth
[i
];
3821 wx
= p
->cmOpts
.iWrap
;
3823 if( wx
<0 ) wx
= -wx
;
3826 if( uz
==0 ) uz
= (u8
*)zEmpty
;
3827 }else if( p
->cmOpts
.bQuote
){
3828 sqlite3_free(azQuoted
[i
]);
3829 azQuoted
[i
] = quoted_column(pStmt
,i
);
3830 uz
= (const unsigned char*)azQuoted
[i
];
3832 uz
= (const unsigned char*)sqlite3_column_text(pStmt
,i
);
3833 if( uz
==0 ) uz
= (u8
*)zShowNull
;
3835 azData
[nRow
*nColumn
+ i
]
3836 = translateForDisplayAndDup(uz
, &azNextLine
[i
], wx
, bw
);
3837 if( azNextLine
[i
] ){
3839 abRowDiv
[nRow
-1] = 0;
3840 bMultiLineRowExists
= 1;
3843 }while( bNextLine
|| sqlite3_step(pStmt
)==SQLITE_ROW
);
3844 nTotal
= nColumn
*(nRow
+1);
3845 for(i
=0; i
<nTotal
; i
++){
3847 if( z
==0 ) z
= (char*)zEmpty
;
3850 if( n
>p
->actualWidth
[j
] ) p
->actualWidth
[j
] = n
;
3852 if( seenInterrupt
) goto columnar_end
;
3857 if( p
->showHeader
){
3858 for(i
=0; i
<nColumn
; i
++){
3859 w
= p
->actualWidth
[i
];
3860 if( p
->colWidth
[i
]<0 ) w
= -w
;
3861 utf8_width_print(w
, azData
[i
]);
3862 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3864 for(i
=0; i
<nColumn
; i
++){
3865 print_dashes(p
->actualWidth
[i
]);
3866 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3874 print_row_separator(p
, nColumn
, "+");
3875 fputs("| ", p
->out
);
3876 for(i
=0; i
<nColumn
; i
++){
3877 w
= p
->actualWidth
[i
];
3878 n
= strlenChar(azData
[i
]);
3879 oputf("%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3880 oputz(i
==nColumn
-1?" |\n":" | ");
3882 print_row_separator(p
, nColumn
, "+");
3885 case MODE_Markdown
: {
3888 fputs("| ", p
->out
);
3889 for(i
=0; i
<nColumn
; i
++){
3890 w
= p
->actualWidth
[i
];
3891 n
= strlenChar(azData
[i
]);
3892 oputf("%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3893 oputz(i
==nColumn
-1?" |\n":" | ");
3895 print_row_separator(p
, nColumn
, "|");
3899 colSep
= " " BOX_13
" ";
3900 rowSep
= " " BOX_13
"\n";
3901 print_box_row_separator(p
, nColumn
, BOX_23
, BOX_234
, BOX_34
);
3903 for(i
=0; i
<nColumn
; i
++){
3904 w
= p
->actualWidth
[i
];
3905 n
= strlenChar(azData
[i
]);
3907 (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "",
3908 i
==nColumn
-1?" "BOX_13
"\n":" "BOX_13
" ");
3910 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3914 for(i
=nColumn
, j
=0; i
<nTotal
; i
++, j
++){
3915 if( j
==0 && p
->cMode
!=MODE_Column
){
3916 oputz(p
->cMode
==MODE_Box
?BOX_13
" ":"| ");
3919 if( z
==0 ) z
= p
->nullValue
;
3920 w
= p
->actualWidth
[j
];
3921 if( p
->colWidth
[j
]<0 ) w
= -w
;
3922 utf8_width_print(w
, z
);
3925 if( bMultiLineRowExists
&& abRowDiv
[i
/nColumn
-1] && i
+1<nTotal
){
3926 if( p
->cMode
==MODE_Table
){
3927 print_row_separator(p
, nColumn
, "+");
3928 }else if( p
->cMode
==MODE_Box
){
3929 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3930 }else if( p
->cMode
==MODE_Column
){
3935 if( seenInterrupt
) goto columnar_end
;
3940 if( p
->cMode
==MODE_Table
){
3941 print_row_separator(p
, nColumn
, "+");
3942 }else if( p
->cMode
==MODE_Box
){
3943 print_box_row_separator(p
, nColumn
, BOX_12
, BOX_124
, BOX_14
);
3946 if( seenInterrupt
){
3947 oputz("Interrupt\n");
3949 nData
= (nRow
+1)*nColumn
;
3950 for(i
=0; i
<nData
; i
++){
3952 if( z
!=zEmpty
&& z
!=zShowNull
) free(azData
[i
]);
3954 sqlite3_free(azData
);
3955 sqlite3_free((void*)azNextLine
);
3956 sqlite3_free(abRowDiv
);
3958 for(i
=0; i
<nColumn
; i
++) sqlite3_free(azQuoted
[i
]);
3959 sqlite3_free(azQuoted
);
3964 ** Run a prepared statement
3966 static void exec_prepared_stmt(
3967 ShellState
*pArg
, /* Pointer to ShellState */
3968 sqlite3_stmt
*pStmt
/* Statement to run */
3971 sqlite3_uint64 nRow
= 0;
3973 if( pArg
->cMode
==MODE_Column
3974 || pArg
->cMode
==MODE_Table
3975 || pArg
->cMode
==MODE_Box
3976 || pArg
->cMode
==MODE_Markdown
3978 exec_prepared_stmt_columnar(pArg
, pStmt
);
3982 /* perform the first step. this will tell us if we
3983 ** have a result set or not and how wide it is.
3985 rc
= sqlite3_step(pStmt
);
3986 /* if we have a result set... */
3987 if( SQLITE_ROW
== rc
){
3988 /* allocate space for col name ptr, value ptr, and type */
3989 int nCol
= sqlite3_column_count(pStmt
);
3990 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
3992 shell_out_of_memory();
3994 char **azCols
= (char **)pData
; /* Names of result columns */
3995 char **azVals
= &azCols
[nCol
]; /* Results */
3996 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
3998 assert(sizeof(int) <= sizeof(char *));
3999 /* save off ptrs to column names */
4000 for(i
=0; i
<nCol
; i
++){
4001 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
4005 /* extract the data and data types */
4006 for(i
=0; i
<nCol
; i
++){
4007 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
4010 && (pArg
->cMode
==MODE_Insert
|| pArg
->cMode
==MODE_Quote
)
4014 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
4016 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
4018 break; /* from for */
4022 /* if data and types extracted successfully... */
4023 if( SQLITE_ROW
== rc
){
4024 /* call the supplied callback with the result row data */
4025 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
4028 rc
= sqlite3_step(pStmt
);
4031 } while( SQLITE_ROW
== rc
);
4032 sqlite3_free(pData
);
4033 if( pArg
->cMode
==MODE_Json
){
4034 fputs("]\n", pArg
->out
);
4035 }else if( pArg
->cMode
==MODE_Count
){
4037 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%llu row%s\n",
4038 nRow
, nRow
!=1 ? "s" : "");
4045 #ifndef SQLITE_OMIT_VIRTUALTABLE
4047 ** This function is called to process SQL if the previous shell command
4048 ** was ".expert". It passes the SQL in the second argument directly to
4049 ** the sqlite3expert object.
4051 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4052 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4053 ** an English language error message. It is the responsibility of the
4054 ** caller to eventually free this buffer using sqlite3_free().
4056 static int expertHandleSQL(
4061 assert( pState
->expert
.pExpert
);
4062 assert( pzErr
==0 || *pzErr
==0 );
4063 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
4067 ** This function is called either to silently clean up the object
4068 ** created by the ".expert" command (if bCancel==1), or to generate a
4069 ** report from it and then clean it up (if bCancel==0).
4071 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4072 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4073 ** an English language error message. It is the responsibility of the
4074 ** caller to eventually free this buffer using sqlite3_free().
4076 static int expertFinish(
4082 sqlite3expert
*p
= pState
->expert
.pExpert
;
4084 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
4086 int bVerbose
= pState
->expert
.bVerbose
;
4088 rc
= sqlite3_expert_analyze(p
, pzErr
);
4089 if( rc
==SQLITE_OK
){
4090 int nQuery
= sqlite3_expert_count(p
);
4094 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
4095 oputz("-- Candidates -----------------------------\n");
4096 oputf("%s\n", zCand
);
4098 for(i
=0; i
<nQuery
; i
++){
4099 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
4100 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
4101 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
4102 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
4104 oputf("-- Query %d --------------------------------\n",i
+1);
4105 oputf("%s\n\n", zSql
);
4107 oputf("%s\n", zIdx
);
4108 oputf("%s\n", zEQP
);
4112 sqlite3_expert_destroy(p
);
4113 pState
->expert
.pExpert
= 0;
4118 ** Implementation of ".expert" dot command.
4120 static int expertDotCommand(
4121 ShellState
*pState
, /* Current shell tool state */
4122 char **azArg
, /* Array of arguments passed to dot command */
4123 int nArg
/* Number of entries in azArg[] */
4130 assert( pState
->expert
.pExpert
==0 );
4131 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
4133 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
4136 if( z
[0]=='-' && z
[1]=='-' ) z
++;
4138 if( n
>=2 && 0==cli_strncmp(z
, "-verbose", n
) ){
4139 pState
->expert
.bVerbose
= 1;
4141 else if( n
>=2 && 0==cli_strncmp(z
, "-sample", n
) ){
4143 eputf("option requires an argument: %s\n", z
);
4146 iSample
= (int)integerValue(azArg
[++i
]);
4147 if( iSample
<0 || iSample
>100 ){
4148 eputf("value out of range: %s\n", azArg
[i
]);
4154 eputf("unknown option: %s\n", z
);
4159 if( rc
==SQLITE_OK
){
4160 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
4161 if( pState
->expert
.pExpert
==0 ){
4162 eputf("sqlite3_expert_new: %s\n", zErr
? zErr
: "out of memory");
4165 sqlite3_expert_config(
4166 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
4174 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4177 ** Execute a statement or set of statements. Print
4178 ** any result rows/columns depending on the current mode
4179 ** set via the supplied callback.
4181 ** This is very similar to SQLite's built-in sqlite3_exec()
4182 ** function except it takes a slightly different callback
4183 ** and callback data argument.
4185 static int shell_exec(
4186 ShellState
*pArg
, /* Pointer to ShellState */
4187 const char *zSql
, /* SQL to be evaluated */
4188 char **pzErrMsg
/* Error msg written here */
4190 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
4191 int rc
= SQLITE_OK
; /* Return Code */
4193 const char *zLeftover
; /* Tail of unprocessed SQL */
4194 sqlite3
*db
= pArg
->db
;
4200 #ifndef SQLITE_OMIT_VIRTUALTABLE
4201 if( pArg
->expert
.pExpert
){
4202 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
4203 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
4207 while( zSql
[0] && (SQLITE_OK
== rc
) ){
4208 static const char *zStmtSql
;
4209 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
4210 if( SQLITE_OK
!= rc
){
4212 *pzErrMsg
= save_err_msg(db
, "in prepare", rc
, zSql
);
4216 /* this happens for a comment or white-space */
4218 while( IsSpace(zSql
[0]) ) zSql
++;
4221 zStmtSql
= sqlite3_sql(pStmt
);
4222 if( zStmtSql
==0 ) zStmtSql
= "";
4223 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
4225 /* save off the prepared statement handle and reset row count */
4227 pArg
->pStmt
= pStmt
;
4231 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4232 if( pArg
&& pArg
->autoEQP
&& sqlite3_stmt_isexplain(pStmt
)==0 ){
4233 sqlite3_stmt
*pExplain
;
4235 disable_debug_trace_modes();
4236 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
4237 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
4238 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
4241 sqlite3_reset(pExplain
);
4242 rc
= sqlite3_stmt_explain(pExplain
, 2);
4243 if( rc
==SQLITE_OK
){
4244 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
4245 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
4246 int iEqpId
= sqlite3_column_int(pExplain
, 0);
4247 int iParentId
= sqlite3_column_int(pExplain
, 1);
4248 if( zEQPLine
==0 ) zEQPLine
= "";
4249 if( zEQPLine
[0]=='-' ) eqp_render(pArg
, 0);
4250 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
4252 eqp_render(pArg
, 0);
4254 if( pArg
->autoEQP
>=AUTOEQP_full
){
4255 /* Also do an EXPLAIN for ".eqp full" mode */
4256 sqlite3_reset(pExplain
);
4257 rc
= sqlite3_stmt_explain(pExplain
, 1);
4258 if( rc
==SQLITE_OK
){
4259 pArg
->cMode
= MODE_Explain
;
4260 assert( sqlite3_stmt_isexplain(pExplain
)==1 );
4261 explain_data_prepare(pArg
, pExplain
);
4262 exec_prepared_stmt(pArg
, pExplain
);
4263 explain_data_delete(pArg
);
4266 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
4267 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
4269 sqlite3_reset(pStmt
);
4270 sqlite3_stmt_explain(pStmt
, 0);
4271 restore_debug_trace_modes();
4275 int bIsExplain
= (sqlite3_stmt_isexplain(pStmt
)==1);
4276 pArg
->cMode
= pArg
->mode
;
4277 if( pArg
->autoExplain
){
4279 pArg
->cMode
= MODE_Explain
;
4281 if( sqlite3_stmt_isexplain(pStmt
)==2 ){
4282 pArg
->cMode
= MODE_EQP
;
4286 /* If the shell is currently in ".explain" mode, gather the extra
4287 ** data required to add indents to the output.*/
4288 if( pArg
->cMode
==MODE_Explain
&& bIsExplain
){
4289 explain_data_prepare(pArg
, pStmt
);
4293 bind_prepared_stmt(pArg
, pStmt
);
4294 exec_prepared_stmt(pArg
, pStmt
);
4295 explain_data_delete(pArg
);
4296 eqp_render(pArg
, 0);
4298 /* print usage stats if stats on */
4299 if( pArg
&& pArg
->statsOn
){
4300 display_stats(db
, pArg
, 0);
4303 /* print loop-counters if required */
4304 if( pArg
&& pArg
->scanstatsOn
){
4305 display_scanstats(db
, pArg
);
4308 /* Finalize the statement just executed. If this fails, save a
4309 ** copy of the error message. Otherwise, set zSql to point to the
4310 ** next statement to execute. */
4311 rc2
= sqlite3_finalize(pStmt
);
4312 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
4313 if( rc
==SQLITE_OK
){
4315 while( IsSpace(zSql
[0]) ) zSql
++;
4316 }else if( pzErrMsg
){
4317 *pzErrMsg
= save_err_msg(db
, "stepping", rc
, 0);
4320 /* clear saved stmt handle */
4331 ** Release memory previously allocated by tableColumnList().
4333 static void freeColumnList(char **azCol
){
4335 for(i
=1; azCol
[i
]; i
++){
4336 sqlite3_free(azCol
[i
]);
4338 /* azCol[0] is a static string */
4339 sqlite3_free(azCol
);
4343 ** Return a list of pointers to strings which are the names of all
4344 ** columns in table zTab. The memory to hold the names is dynamically
4345 ** allocated and must be released by the caller using a subsequent call
4346 ** to freeColumnList().
4348 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4349 ** value that needs to be preserved, then azCol[0] is filled in with the
4350 ** name of the rowid column.
4352 ** The first regular column in the table is azCol[1]. The list is terminated
4353 ** by an entry with azCol[i]==0.
4355 static char **tableColumnList(ShellState
*p
, const char *zTab
){
4357 sqlite3_stmt
*pStmt
;
4361 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
4362 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
4363 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
4366 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
4367 shell_check_oom(zSql
);
4368 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4371 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4372 if( nCol
>=nAlloc
-2 ){
4373 nAlloc
= nAlloc
*2 + nCol
+ 10;
4374 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
4375 shell_check_oom(azCol
);
4377 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
4378 shell_check_oom(azCol
[nCol
]);
4379 if( sqlite3_column_int(pStmt
, 5) ){
4382 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
4391 sqlite3_finalize(pStmt
);
4392 if( azCol
==0 ) return 0;
4396 /* The decision of whether or not a rowid really needs to be preserved
4397 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4398 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4399 ** rowids on tables where the rowid is inaccessible because there are other
4400 ** columns in the table named "rowid", "_rowid_", and "oid".
4402 if( preserveRowid
&& isIPK
){
4403 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4404 ** might be an alias for the ROWID. But it might also be a WITHOUT ROWID
4405 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4406 ** ROWID aliases. To distinguish these cases, check to see if
4407 ** there is a "pk" entry in "PRAGMA index_list". There will be
4408 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4410 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4411 " WHERE origin='pk'", zTab
);
4412 shell_check_oom(zSql
);
4413 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4416 freeColumnList(azCol
);
4419 rc
= sqlite3_step(pStmt
);
4420 sqlite3_finalize(pStmt
);
4421 preserveRowid
= rc
==SQLITE_ROW
;
4423 if( preserveRowid
){
4424 /* Only preserve the rowid if we can find a name to use for the
4426 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
4429 for(i
=1; i
<=nCol
; i
++){
4430 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
4433 /* At this point, we know that azRowid[j] is not the name of any
4434 ** ordinary column in the table. Verify that azRowid[j] is a valid
4435 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4436 ** tables will fail this last check */
4437 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
4438 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
4447 ** Toggle the reverse_unordered_selects setting.
4449 static void toggleSelectOrder(sqlite3
*db
){
4450 sqlite3_stmt
*pStmt
= 0;
4453 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
4454 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
4455 iSetting
= sqlite3_column_int(pStmt
, 0);
4457 sqlite3_finalize(pStmt
);
4458 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
4459 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
4460 sqlite3_exec(db
, zStmt
, 0, 0, 0);
4464 ** This is a different callback routine used for dumping the database.
4465 ** Each row received by this callback consists of a table name,
4466 ** the table type ("index" or "table") and SQL to create the table.
4467 ** This routine should print text sufficient to recreate the table.
4469 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
4474 ShellState
*p
= (ShellState
*)pArg
;
4478 UNUSED_PARAMETER(azNotUsed
);
4479 if( nArg
!=3 || azArg
==0 ) return 0;
4483 if( zTable
==0 ) return 0;
4484 if( zType
==0 ) return 0;
4485 dataOnly
= (p
->shellFlgs
& SHFLG_DumpDataOnly
)!=0;
4486 noSys
= (p
->shellFlgs
& SHFLG_DumpNoSys
)!=0;
4488 if( cli_strcmp(zTable
, "sqlite_sequence")==0 && !noSys
){
4489 if( !dataOnly
) oputz("DELETE FROM sqlite_sequence;\n");
4490 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 && !noSys
){
4491 if( !dataOnly
) oputz("ANALYZE sqlite_schema;\n");
4492 }else if( cli_strncmp(zTable
, "sqlite_", 7)==0 ){
4494 }else if( dataOnly
){
4496 }else if( cli_strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
4498 if( !p
->writableSchema
){
4499 oputz("PRAGMA writable_schema=ON;\n");
4500 p
->writableSchema
= 1;
4502 zIns
= sqlite3_mprintf(
4503 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4504 "VALUES('table','%q','%q',0,'%q');",
4505 zTable
, zTable
, zSql
);
4506 shell_check_oom(zIns
);
4507 oputf("%s\n", zIns
);
4511 printSchemaLine(zSql
, ";\n");
4514 if( cli_strcmp(zType
, "table")==0 ){
4519 char *savedDestTable
;
4522 azCol
= tableColumnList(p
, zTable
);
4528 /* Always quote the table name, even if it appears to be pure ascii,
4529 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4531 appendText(&sTable
, zTable
, quoteChar(zTable
));
4532 /* If preserving the rowid, add a column list after the table name.
4533 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4534 ** instead of the usual "INSERT INTO tab VALUES(...)".
4537 appendText(&sTable
, "(", 0);
4538 appendText(&sTable
, azCol
[0], 0);
4539 for(i
=1; azCol
[i
]; i
++){
4540 appendText(&sTable
, ",", 0);
4541 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
4543 appendText(&sTable
, ")", 0);
4546 /* Build an appropriate SELECT statement */
4548 appendText(&sSelect
, "SELECT ", 0);
4550 appendText(&sSelect
, azCol
[0], 0);
4551 appendText(&sSelect
, ",", 0);
4553 for(i
=1; azCol
[i
]; i
++){
4554 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
4556 appendText(&sSelect
, ",", 0);
4559 freeColumnList(azCol
);
4560 appendText(&sSelect
, " FROM ", 0);
4561 appendText(&sSelect
, zTable
, quoteChar(zTable
));
4563 savedDestTable
= p
->zDestTable
;
4564 savedMode
= p
->mode
;
4565 p
->zDestTable
= sTable
.z
;
4566 p
->mode
= p
->cMode
= MODE_Insert
;
4567 rc
= shell_exec(p
, sSelect
.z
, 0);
4568 if( (rc
&0xff)==SQLITE_CORRUPT
){
4569 oputz("/****** CORRUPTION ERROR *******/\n");
4570 toggleSelectOrder(p
->db
);
4571 shell_exec(p
, sSelect
.z
, 0);
4572 toggleSelectOrder(p
->db
);
4574 p
->zDestTable
= savedDestTable
;
4575 p
->mode
= savedMode
;
4584 ** Run zQuery. Use dump_callback() as the callback routine so that
4585 ** the contents of the query are output as SQL statements.
4587 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4588 ** "ORDER BY rowid DESC" to the end.
4590 static int run_schema_dump_query(
4596 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
4597 if( rc
==SQLITE_CORRUPT
){
4599 int len
= strlen30(zQuery
);
4600 oputz("/****** CORRUPTION ERROR *******/\n");
4602 oputf("/****** %s ******/\n", zErr
);
4606 zQ2
= malloc( len
+100 );
4607 if( zQ2
==0 ) return rc
;
4608 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
4609 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
4611 oputf("/****** ERROR: %s ******/\n", zErr
);
4613 rc
= SQLITE_CORRUPT
;
4622 ** Text of help messages.
4624 ** The help text for each individual command begins with a line that starts
4625 ** with ".". Subsequent lines are supplemental information.
4627 ** There must be two or more spaces between the end of the command and the
4628 ** start of the description of what that command does.
4630 static const char *(azHelp
[]) = {
4631 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4632 && !defined(SQLITE_SHELL_FIDDLE)
4633 ".archive ... Manage SQL archives",
4634 " Each command must have exactly one of the following options:",
4635 " -c, --create Create a new archive",
4636 " -u, --update Add or update files with changed mtime",
4637 " -i, --insert Like -u but always add even if unchanged",
4638 " -r, --remove Remove files from archive",
4639 " -t, --list List contents of archive",
4640 " -x, --extract Extract files from archive",
4641 " Optional arguments:",
4642 " -v, --verbose Print each filename as it is processed",
4643 " -f FILE, --file FILE Use archive FILE (default is current db)",
4644 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4645 " -C DIR, --directory DIR Read/extract files from directory DIR",
4646 " -g, --glob Use glob matching for names in archive",
4647 " -n, --dryrun Show the SQL that would have occurred",
4649 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4650 " .ar -tf ARCHIVE # List members of ARCHIVE",
4651 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4653 " http://sqlite.org/cli.html#sqlite_archive_support",
4655 #ifndef SQLITE_OMIT_AUTHORIZATION
4656 ".auth ON|OFF Show authorizer callbacks",
4658 #ifndef SQLITE_SHELL_FIDDLE
4659 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4661 " --append Use the appendvfs",
4662 " --async Write to FILE without journal and fsync()",
4664 ".bail on|off Stop after hitting an error. Default OFF",
4665 #ifndef SQLITE_SHELL_FIDDLE
4666 ".cd DIRECTORY Change the working directory to DIRECTORY",
4668 ".changes on|off Show number of rows changed by SQL",
4669 #ifndef SQLITE_SHELL_FIDDLE
4670 ".check GLOB Fail if output since .testcase does not match",
4671 ".clone NEWDB Clone data into NEWDB from the existing database",
4673 ".connection [close] [#] Open or close an auxiliary database connection",
4674 #if defined(_WIN32) || defined(WIN32)
4675 ".crnl on|off Translate \\n to \\r\\n. Default ON",
4677 ".databases List names and files of attached databases",
4678 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4679 #if SQLITE_SHELL_HAVE_RECOVER
4680 ".dbinfo ?DB? Show status information about the database",
4682 ".dump ?OBJECTS? Render database content as SQL",
4684 " --data-only Output only INSERT statements",
4685 " --newlines Allow unescaped newline characters in output",
4686 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4687 " --preserve-rowids Include ROWID values in the output",
4688 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4689 " Additional LIKE patterns can be given in subsequent arguments",
4690 ".echo on|off Turn command echo on or off",
4691 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4694 " test Show raw EXPLAIN QUERY PLAN output",
4695 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4697 " trigger Like \"full\" but also show trigger bytecode",
4698 #ifndef SQLITE_SHELL_FIDDLE
4699 ".excel Display the output of next command in spreadsheet",
4700 " --bom Put a UTF8 byte-order mark on intermediate file",
4702 #ifndef SQLITE_SHELL_FIDDLE
4703 ".exit ?CODE? Exit this program with return-code CODE",
4705 ".expert EXPERIMENTAL. Suggest indexes for queries",
4706 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4707 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4708 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4709 " --help Show CMD details",
4710 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4711 ".headers on|off Turn display of headers on or off",
4712 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4713 #ifndef SQLITE_SHELL_FIDDLE
4714 ".import FILE TABLE Import data from FILE into TABLE",
4716 " --ascii Use \\037 and \\036 as column and row separators",
4717 " --csv Use , and \\n as column and row separators",
4718 " --skip N Skip the first N rows of input",
4719 " --schema S Target table to be S.TABLE",
4720 " -v \"Verbose\" - increase auxiliary output",
4722 " * If TABLE does not exist, it is created. The first row of input",
4723 " determines the column names.",
4724 " * If neither --csv or --ascii are used, the input mode is derived",
4725 " from the \".mode\" output mode",
4726 " * If FILE begins with \"|\" then it is a command that generates the",
4729 #ifndef SQLITE_OMIT_TEST_CONTROL
4730 ",imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4732 ".indexes ?TABLE? Show names of indexes",
4733 " If TABLE is specified, only show indexes for",
4734 " tables matching TABLE using the LIKE operator.",
4735 #ifdef SQLITE_ENABLE_IOTRACE
4736 ",iotrace FILE Enable I/O diagnostic logging to FILE",
4738 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4739 ".lint OPTIONS Report potential schema issues.",
4741 " fkey-indexes Find missing foreign key indexes",
4742 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4743 ".load FILE ?ENTRY? Load an extension library",
4745 #if !defined(SQLITE_SHELL_FIDDLE)
4746 ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout",
4748 ".log on|off Turn logging on or off.",
4750 ".mode MODE ?OPTIONS? Set output mode",
4752 " ascii Columns/rows delimited by 0x1F and 0x1E",
4753 " box Tables using unicode box-drawing characters",
4754 " csv Comma-separated values",
4755 " column Output in columns. (See .width)",
4756 " html HTML <table> code",
4757 " insert SQL insert statements for TABLE",
4758 " json Results in a JSON array",
4759 " line One value per line",
4760 " list Values delimited by \"|\"",
4761 " markdown Markdown table format",
4762 " qbox Shorthand for \"box --wrap 60 --quote\"",
4763 " quote Escape answers as for SQL",
4764 " table ASCII-art table",
4765 " tabs Tab-separated values",
4766 " tcl TCL list elements",
4767 " OPTIONS: (for columnar modes or insert mode):",
4768 " --wrap N Wrap output lines to no longer than N characters",
4769 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4770 " --ww Shorthand for \"--wordwrap 1\"",
4771 " --quote Quote output text as SQL literals",
4772 " --noquote Do not quote output text",
4773 " TABLE The name of SQL table used for \"insert\" mode",
4774 #ifndef SQLITE_SHELL_FIDDLE
4775 ".nonce STRING Suspend safe mode for one command if nonce matches",
4777 ".nullvalue STRING Use STRING in place of NULL values",
4778 #ifndef SQLITE_SHELL_FIDDLE
4779 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4780 " If FILE begins with '|' then open as a pipe",
4781 " --bom Put a UTF8 byte-order mark at the beginning",
4782 " -e Send output to the system text editor",
4783 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4784 /* Note that .open is (partially) available in WASM builds but is
4785 ** currently only intended to be used by the fiddle tool, not
4786 ** end users, so is "undocumented." */
4787 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4789 " --append Use appendvfs to append database to the end of FILE",
4791 #ifndef SQLITE_OMIT_DESERIALIZE
4792 " --deserialize Load into memory using sqlite3_deserialize()",
4793 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4794 " --maxsize N Maximum size for --hexdb or --deserialized database",
4796 " --new Initialize FILE to an empty database",
4797 " --nofollow Do not follow symbolic links",
4798 " --readonly Open FILE readonly",
4799 " --zip FILE is a ZIP archive",
4800 #ifndef SQLITE_SHELL_FIDDLE
4801 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4802 " If FILE begins with '|' then open it as a pipe.",
4804 " --bom Prefix output with a UTF8 byte-order mark",
4805 " -e Send output to the system text editor",
4806 " -x Send output as CSV to a spreadsheet",
4808 ".parameter CMD ... Manage SQL parameter bindings",
4809 " clear Erase all bindings",
4810 " init Initialize the TEMP table that holds bindings",
4811 " list List the current parameter bindings",
4812 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4813 " PARAMETER should start with one of: $ : @ ?",
4814 " unset PARAMETER Remove PARAMETER from the binding table",
4815 ".print STRING... Print literal STRING",
4816 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4817 ".progress N Invoke progress handler after every N opcodes",
4818 " --limit N Interrupt after N progress callbacks",
4819 " --once Do no more than one progress interrupt",
4820 " --quiet|-q No output except at interrupts",
4821 " --reset Reset the count for each input and interrupt",
4823 ".prompt MAIN CONTINUE Replace the standard prompts",
4824 #ifndef SQLITE_SHELL_FIDDLE
4825 ".quit Stop interpreting input stream, exit if primary.",
4826 ".read FILE Read input from FILE or command output",
4827 " If FILE begins with \"|\", it is a command that generates the input.",
4829 #if SQLITE_SHELL_HAVE_RECOVER
4830 ".recover Recover as much data as possible from corrupt db.",
4831 " --ignore-freelist Ignore pages that appear to be on db freelist",
4832 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4833 " --no-rowids Do not attempt to recover rowid values",
4834 " that are not also INTEGER PRIMARY KEYs",
4836 #ifndef SQLITE_SHELL_FIDDLE
4837 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4838 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4840 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4841 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4843 " --indent Try to pretty-print the schema",
4844 " --nosys Omit objects whose names start with \"sqlite_\"",
4845 ",selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4847 " --init Create a new SELFTEST table",
4848 " -v Verbose output",
4849 ".separator COL ?ROW? Change the column and row separators",
4850 #if defined(SQLITE_ENABLE_SESSION)
4851 ".session ?NAME? CMD ... Create or control sessions",
4853 " attach TABLE Attach TABLE",
4854 " changeset FILE Write a changeset into FILE",
4855 " close Close one session",
4856 " enable ?BOOLEAN? Set or query the enable bit",
4857 " filter GLOB... Reject tables matching GLOBs",
4858 " indirect ?BOOLEAN? Mark or query the indirect status",
4859 " isempty Query whether the session is empty",
4860 " list List currently open session names",
4861 " open DB NAME Open a new session on DB",
4862 " patchset FILE Write a patchset into FILE",
4863 " If ?NAME? is omitted, the first defined session is used.",
4865 ".sha3sum ... Compute a SHA3 hash of database content",
4867 " --schema Also hash the sqlite_schema table",
4868 " --sha3-224 Use the sha3-224 algorithm",
4869 " --sha3-256 Use the sha3-256 algorithm (default)",
4870 " --sha3-384 Use the sha3-384 algorithm",
4871 " --sha3-512 Use the sha3-512 algorithm",
4872 " Any other argument is a LIKE pattern for tables to hash",
4873 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4874 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4876 ".show Show the current values for various settings",
4877 ".stats ?ARG? Show stats or turn stats on or off",
4878 " off Turn off automatic stat display",
4879 " on Turn on automatic stat display",
4880 " stmt Show statement stats",
4881 " vmstep Show the virtual machine step count only",
4882 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4883 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4885 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4886 #ifndef SQLITE_SHELL_FIDDLE
4887 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
4889 ",testctrl CMD ... Run various sqlite3_test_control() operations",
4890 " Run \".testctrl\" with no arguments for details",
4891 ".timeout MS Try opening locked tables for MS milliseconds",
4892 ".timer on|off Turn SQL timer on or off",
4893 #ifndef SQLITE_OMIT_TRACE
4894 ".trace ?OPTIONS? Output each SQL statement as it is run",
4895 " FILE Send output to FILE",
4896 " stdout Send output to stdout",
4897 " stderr Send output to stderr",
4898 " off Disable tracing",
4899 " --expanded Expand query parameters",
4900 #ifdef SQLITE_ENABLE_NORMALIZE
4901 " --normalized Normal the SQL statements",
4903 " --plain Show SQL as it is input",
4904 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4905 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4906 " --row Trace each row (SQLITE_TRACE_ROW)",
4907 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4908 #endif /* SQLITE_OMIT_TRACE */
4910 ".unmodule NAME ... Unregister virtual table modules",
4911 " --allexcept Unregister everything except those named",
4913 ".version Show source, library and compiler versions",
4914 ".vfsinfo ?AUX? Information about the top-level VFS",
4915 ".vfslist List all available VFSes",
4916 ".vfsname ?AUX? Print the name of the VFS stack",
4917 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4918 " Negative values right-justify",
4922 ** Output help text.
4924 ** zPattern describes the set of commands for which help text is provided.
4925 ** If zPattern is NULL, then show all commands, but only give a one-line
4926 ** description of each.
4928 ** Return the number of matches.
4930 static int showHelp(FILE *out
, const char *zPattern
){
4937 || cli_strcmp(zPattern
,"-a")==0
4938 || cli_strcmp(zPattern
,"-all")==0
4939 || cli_strcmp(zPattern
,"--all")==0
4941 enum HelpWanted
{ HW_NoCull
= 0, HW_SummaryOnly
= 1, HW_Undoc
= 2 };
4942 enum HelpHave
{ HH_Undoc
= 2, HH_Summary
= 1, HH_More
= 0 };
4943 /* Show all or most commands
4944 ** *zPattern==0 => summary of documented commands only
4945 ** *zPattern=='0' => whole help for undocumented commands
4946 ** Otherwise => whole help for documented commands
4948 enum HelpWanted hw
= HW_SummaryOnly
;
4949 enum HelpHave hh
= HH_More
;
4951 hw
= (*zPattern
=='0')? HW_NoCull
|HW_Undoc
: HW_NoCull
;
4953 for(i
=0; i
<ArraySize(azHelp
); i
++){
4954 switch( azHelp
[i
][0] ){
4956 hh
= HH_Summary
|HH_Undoc
;
4965 if( ((hw
^hh
)&HH_Undoc
)==0 ){
4966 if( (hh
&HH_Summary
)!=0 ){
4967 sputf(out
, ".%s\n", azHelp
[i
]+1);
4969 }else if( (hw
&HW_SummaryOnly
)==0 ){
4970 sputf(out
, "%s\n", azHelp
[i
]);
4975 /* Seek documented commands for which zPattern is an exact prefix */
4976 zPat
= sqlite3_mprintf(".%s*", zPattern
);
4977 shell_check_oom(zPat
);
4978 for(i
=0; i
<ArraySize(azHelp
); i
++){
4979 if( sqlite3_strglob(zPat
, azHelp
[i
])==0 ){
4980 sputf(out
, "%s\n", azHelp
[i
]);
4988 /* when zPattern is a prefix of exactly one command, then include
4989 ** the details of that command, which should begin at offset j */
4990 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
][0]==' ' ){
4991 sputf(out
, "%s\n", azHelp
[j
]);
4997 /* Look for documented commands that contain zPattern anywhere.
4998 ** Show complete text of all documented commands that match. */
4999 zPat
= sqlite3_mprintf("%%%s%%", zPattern
);
5000 shell_check_oom(zPat
);
5001 for(i
=0; i
<ArraySize(azHelp
); i
++){
5002 if( azHelp
[i
][0]==',' ){
5003 while( i
<ArraySize(azHelp
)-1 && azHelp
[i
+1][0]==' ' ) ++i
;
5006 if( azHelp
[i
][0]=='.' ) j
= i
;
5007 if( sqlite3_strlike(zPat
, azHelp
[i
], 0)==0 ){
5008 sputf(out
, "%s\n", azHelp
[j
]);
5009 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
+1][0]==' ' ){
5011 sputf(out
, "%s\n", azHelp
[j
]);
5022 /* Forward reference */
5023 static int process_input(ShellState
*p
);
5026 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
5027 ** and return a pointer to the buffer. The caller is responsible for freeing
5030 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
5033 ** For convenience, a nul-terminator byte is always appended to the data read
5034 ** from the file before the buffer is returned. This byte is not included in
5035 ** the final value of (*pnByte), if applicable.
5037 ** NULL is returned if any error is encountered. The final value of *pnByte
5038 ** is undefined in this case.
5040 static char *readFile(const char *zName
, int *pnByte
){
5041 FILE *in
= fopen(zName
, "rb");
5046 if( in
==0 ) return 0;
5047 rc
= fseek(in
, 0, SEEK_END
);
5049 eputf("Error: '%s' not seekable\n", zName
);
5055 pBuf
= sqlite3_malloc64( nIn
+1 );
5057 eputz("Error: out of memory\n");
5061 nRead
= fread(pBuf
, nIn
, 1, in
);
5065 eputf("Error: cannot read '%s'\n", zName
);
5069 if( pnByte
) *pnByte
= nIn
;
5073 #if defined(SQLITE_ENABLE_SESSION)
5075 ** Close a single OpenSession object and release all of its associated
5078 static void session_close(OpenSession
*pSession
){
5080 sqlite3session_delete(pSession
->p
);
5081 sqlite3_free(pSession
->zName
);
5082 for(i
=0; i
<pSession
->nFilter
; i
++){
5083 sqlite3_free(pSession
->azFilter
[i
]);
5085 sqlite3_free(pSession
->azFilter
);
5086 memset(pSession
, 0, sizeof(OpenSession
));
5091 ** Close all OpenSession objects and release all associated resources.
5093 #if defined(SQLITE_ENABLE_SESSION)
5094 static void session_close_all(ShellState
*p
, int i
){
5096 struct AuxDb
*pAuxDb
= i
<0 ? p
->pAuxDb
: &p
->aAuxDb
[i
];
5097 for(j
=0; j
<pAuxDb
->nSession
; j
++){
5098 session_close(&pAuxDb
->aSession
[j
]);
5100 pAuxDb
->nSession
= 0;
5103 # define session_close_all(X,Y)
5107 ** Implementation of the xFilter function for an open session. Omit
5108 ** any tables named by ".session filter" but let all other table through.
5110 #if defined(SQLITE_ENABLE_SESSION)
5111 static int session_filter(void *pCtx
, const char *zTab
){
5112 OpenSession
*pSession
= (OpenSession
*)pCtx
;
5114 for(i
=0; i
<pSession
->nFilter
; i
++){
5115 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
5122 ** Try to deduce the type of file for zName based on its content. Return
5123 ** one of the SHELL_OPEN_* constants.
5125 ** If the file does not exist or is empty but its name looks like a ZIP
5126 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
5127 ** Otherwise, assume an ordinary database regardless of the filename if
5128 ** the type cannot be determined from content.
5130 int deduceDatabaseType(const char *zName
, int dfltZip
){
5131 FILE *f
= fopen(zName
, "rb");
5133 int rc
= SHELL_OPEN_UNSPEC
;
5136 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
5137 return SHELL_OPEN_ZIPFILE
;
5139 return SHELL_OPEN_NORMAL
;
5142 n
= fread(zBuf
, 16, 1, f
);
5143 if( n
==1 && memcmp(zBuf
, "SQLite format 3", 16)==0 ){
5145 return SHELL_OPEN_NORMAL
;
5147 fseek(f
, -25, SEEK_END
);
5148 n
= fread(zBuf
, 25, 1, f
);
5149 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
5150 rc
= SHELL_OPEN_APPENDVFS
;
5152 fseek(f
, -22, SEEK_END
);
5153 n
= fread(zBuf
, 22, 1, f
);
5154 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
5156 rc
= SHELL_OPEN_ZIPFILE
;
5157 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
5158 rc
= SHELL_OPEN_ZIPFILE
;
5165 #ifndef SQLITE_OMIT_DESERIALIZE
5167 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5168 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5169 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5171 static unsigned char *readHexDb(ShellState
*p
, int *pnData
){
5172 unsigned char *a
= 0;
5180 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5184 in
= fopen(zDbFilename
, "r");
5186 eputf("cannot open \"%s\" for reading\n", zDbFilename
);
5193 if( in
==0 ) in
= stdin
;
5197 if( fgets(zLine
, sizeof(zLine
), in
)==0 ) goto readHexDb_error
;
5198 rc
= sscanf(zLine
, "| size %d pagesize %d", &n
, &pgsz
);
5199 if( rc
!=2 ) goto readHexDb_error
;
5200 if( n
<0 ) goto readHexDb_error
;
5201 if( pgsz
<512 || pgsz
>65536 || (pgsz
&(pgsz
-1))!=0 ) goto readHexDb_error
;
5202 n
= (n
+pgsz
-1)&~(pgsz
-1); /* Round n up to the next multiple of pgsz */
5203 a
= sqlite3_malloc( n
? n
: 1 );
5206 if( pgsz
<512 || pgsz
>65536 || (pgsz
& (pgsz
-1))!=0 ){
5207 eputz("invalid pagesize\n");
5208 goto readHexDb_error
;
5210 for(nLine
++; fgets(zLine
, sizeof(zLine
), in
)!=0; nLine
++){
5211 rc
= sscanf(zLine
, "| page %d offset %d", &j
, &k
);
5216 if( cli_strncmp(zLine
, "| end ", 6)==0 ){
5219 rc
= sscanf(zLine
,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5220 &j
, &x
[0], &x
[1], &x
[2], &x
[3], &x
[4], &x
[5], &x
[6], &x
[7],
5221 &x
[8], &x
[9], &x
[10], &x
[11], &x
[12], &x
[13], &x
[14], &x
[15]);
5224 if( k
+16<=n
&& k
>=0 ){
5226 for(ii
=0; ii
<16; ii
++) a
[k
+ii
] = x
[ii
]&0xff;
5242 while( fgets(zLine
, sizeof(zLine
), p
->in
)!=0 ){
5244 if(cli_strncmp(zLine
, "| end ", 6)==0 ) break;
5249 eputf("Error on line %d of --hexdb input\n", nLine
);
5252 #endif /* SQLITE_OMIT_DESERIALIZE */
5255 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5257 static void shellUSleepFunc(
5258 sqlite3_context
*context
,
5260 sqlite3_value
**argv
5262 int sleep
= sqlite3_value_int(argv
[0]);
5264 sqlite3_sleep(sleep
/1000);
5265 sqlite3_result_int(context
, sleep
);
5268 /* Flags for open_db().
5270 ** The default behavior of open_db() is to exit(1) if the database fails to
5271 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5272 ** but still returns without calling exit.
5274 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5275 ** ZIP archive if the file does not exist or is empty and its name matches
5276 ** the *.zip pattern.
5278 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5279 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5282 ** Make sure the database is open. If it is not, then open it. If
5283 ** the database fails to open, print an error message and exit.
5285 static void open_db(ShellState
*p
, int openFlags
){
5287 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5288 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
5289 if( zDbFilename
==0 || zDbFilename
[0]==0 ){
5290 p
->openMode
= SHELL_OPEN_NORMAL
;
5292 p
->openMode
= (u8
)deduceDatabaseType(zDbFilename
,
5293 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
5296 switch( p
->openMode
){
5297 case SHELL_OPEN_APPENDVFS
: {
5298 sqlite3_open_v2(zDbFilename
, &p
->db
,
5299 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, "apndvfs");
5302 case SHELL_OPEN_HEXDB
:
5303 case SHELL_OPEN_DESERIALIZE
: {
5304 sqlite3_open(0, &p
->db
);
5307 case SHELL_OPEN_ZIPFILE
: {
5308 sqlite3_open(":memory:", &p
->db
);
5311 case SHELL_OPEN_READONLY
: {
5312 sqlite3_open_v2(zDbFilename
, &p
->db
,
5313 SQLITE_OPEN_READONLY
|p
->openFlags
, 0);
5316 case SHELL_OPEN_UNSPEC
:
5317 case SHELL_OPEN_NORMAL
: {
5318 sqlite3_open_v2(zDbFilename
, &p
->db
,
5319 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, 0);
5323 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
5324 eputf("Error: unable to open database \"%s\": %s\n",
5325 zDbFilename
, sqlite3_errmsg(p
->db
));
5326 if( (openFlags
& OPEN_DB_KEEPALIVE
)==0 ){
5329 sqlite3_close(p
->db
);
5330 sqlite3_open(":memory:", &p
->db
);
5331 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
5332 eputz("Also: unable to open substitute in-memory database.\n");
5335 eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
5340 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_STMT_SCANSTATUS
, (int)0, (int*)0);
5342 /* Reflect the use or absence of --unsafe-testing invocation. */
5344 int testmode_on
= ShellHasFlag(p
,SHFLG_TestingMode
);
5345 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_TRUSTED_SCHEMA
, testmode_on
,0);
5346 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, !testmode_on
,0);
5349 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5350 sqlite3_enable_load_extension(p
->db
, 1);
5352 sqlite3_shathree_init(p
->db
, 0, 0);
5353 sqlite3_uint_init(p
->db
, 0, 0);
5354 sqlite3_decimal_init(p
->db
, 0, 0);
5355 sqlite3_base64_init(p
->db
, 0, 0);
5356 sqlite3_base85_init(p
->db
, 0, 0);
5357 sqlite3_regexp_init(p
->db
, 0, 0);
5358 sqlite3_ieee_init(p
->db
, 0, 0);
5359 sqlite3_series_init(p
->db
, 0, 0);
5360 #ifndef SQLITE_SHELL_FIDDLE
5361 sqlite3_fileio_init(p
->db
, 0, 0);
5362 sqlite3_completion_init(p
->db
, 0, 0);
5364 #ifdef SQLITE_HAVE_ZLIB
5365 if( !p
->bSafeModePersist
){
5366 sqlite3_zipfile_init(p
->db
, 0, 0);
5367 sqlite3_sqlar_init(p
->db
, 0, 0);
5370 #ifdef SQLITE_SHELL_EXTFUNCS
5371 /* Create a preprocessing mechanism for extensions to make
5372 * their own provisions for being built into the shell.
5373 * This is a short-span macro. See further below for usage.
5375 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5376 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5377 /* Let custom-included extensions get their ..._init() called.
5378 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5379 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5380 * initialization routine to be called.
5383 int irc
= SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS
, INIT
)(p
->db
);
5384 /* Let custom-included extensions expose their functionality.
5385 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5386 * the SQL functions, virtual tables, collating sequences or
5387 * VFS's implemented by the extension to be registered.
5390 || irc
==SQLITE_OK_LOAD_PERMANENTLY
){
5391 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS
, EXPOSE
)(p
->db
, 0);
5393 #undef SHELL_SUB_MACRO
5394 #undef SHELL_SUBMACRO
5398 sqlite3_create_function(p
->db
, "strtod", 1, SQLITE_UTF8
, 0,
5400 sqlite3_create_function(p
->db
, "dtostr", 1, SQLITE_UTF8
, 0,
5402 sqlite3_create_function(p
->db
, "dtostr", 2, SQLITE_UTF8
, 0,
5404 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
5405 shellAddSchemaName
, 0, 0);
5406 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
5407 shellModuleSchema
, 0, 0);
5408 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
5409 shellPutsFunc
, 0, 0);
5410 sqlite3_create_function(p
->db
, "usleep",1,SQLITE_UTF8
,0,
5411 shellUSleepFunc
, 0, 0);
5412 #ifndef SQLITE_NOHAVE_SYSTEM
5413 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
5415 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
5419 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
5420 char *zSql
= sqlite3_mprintf(
5421 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename
);
5422 shell_check_oom(zSql
);
5423 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
5426 #ifndef SQLITE_OMIT_DESERIALIZE
5428 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
|| p
->openMode
==SHELL_OPEN_HEXDB
){
5431 unsigned char *aData
;
5432 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
){
5433 aData
= (unsigned char*)readFile(zDbFilename
, &nData
);
5435 aData
= readHexDb(p
, &nData
);
5440 rc
= sqlite3_deserialize(p
->db
, "main", aData
, nData
, nData
,
5441 SQLITE_DESERIALIZE_RESIZEABLE
|
5442 SQLITE_DESERIALIZE_FREEONCLOSE
);
5444 eputf("Error: sqlite3_deserialize() returns %d\n", rc
);
5447 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_SIZE_LIMIT
, &p
->szMax
);
5453 if( p
->bSafeModePersist
){
5454 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
5457 p
->db
, SQLITE_DBCONFIG_STMT_SCANSTATUS
, p
->scanstatsOn
, (int*)0
5463 ** Attempt to close the database connection. Report errors.
5465 void close_db(sqlite3
*db
){
5466 int rc
= sqlite3_close(db
);
5468 eputf("Error: sqlite3_close() returns %d: %s\n", rc
, sqlite3_errmsg(db
));
5472 #if HAVE_READLINE || HAVE_EDITLINE
5474 ** Readline completion callbacks
5476 static char *readline_completion_generator(const char *text
, int state
){
5477 static sqlite3_stmt
*pStmt
= 0;
5481 sqlite3_finalize(pStmt
);
5482 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5483 " FROM completion(%Q) ORDER BY 1", text
);
5484 shell_check_oom(zSql
);
5485 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5488 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
5489 const char *z
= (const char*)sqlite3_column_text(pStmt
,0);
5490 zRet
= z
? strdup(z
) : 0;
5492 sqlite3_finalize(pStmt
);
5498 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
5501 rl_attempted_completion_over
= 1;
5502 return rl_completion_matches(zText
, readline_completion_generator
);
5505 #elif HAVE_LINENOISE
5507 ** Linenoise completion callback
5509 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
5510 i64 nLine
= strlen(zLine
);
5512 sqlite3_stmt
*pStmt
= 0;
5516 if( nLine
>(i64
)sizeof(zBuf
)-30 ) return;
5517 if( zLine
[0]=='.' || zLine
[0]=='#') return;
5518 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
5519 if( i
==nLine
-1 ) return;
5521 memcpy(zBuf
, zLine
, iStart
);
5522 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5523 " FROM completion(%Q,%Q) ORDER BY 1",
5524 &zLine
[iStart
], zLine
);
5525 shell_check_oom(zSql
);
5526 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5528 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5529 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5530 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
5531 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
5532 if( iStart
+nCompletion
< (i64
)sizeof(zBuf
)-1 && zCompletion
){
5533 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
5534 linenoiseAddCompletion(lc
, zBuf
);
5537 sqlite3_finalize(pStmt
);
5542 ** Do C-language style dequoting.
5548 ** \v -> vertical tab
5550 ** \r -> carriage return
5555 ** \NNN -> ascii character NNN in octal
5556 ** \xHH -> ascii character HH in hexadecimal
5558 static void resolve_backslashes(char *z
){
5561 while( *z
&& *z
!='\\' ) z
++;
5562 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
5563 if( c
=='\\' && z
[i
+1]!=0 ){
5581 }else if( c
=='\'' ){
5583 }else if( c
=='\\' ){
5588 while( nhd
<2 && (c
=z
[i
+1+nhd
])!=0 && (hdv
=hexDigitValue(c
))>=0 ){
5589 hv
= (u8
)((hv
<<4)|hdv
);
5594 }else if( c
>='0' && c
<='7' ){
5596 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5598 c
= (c
<<3) + z
[i
] - '0';
5599 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5601 c
= (c
<<3) + z
[i
] - '0';
5612 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5613 ** for TRUE and FALSE. Return the integer value if appropriate.
5615 static int booleanValue(const char *zArg
){
5617 if( zArg
[0]=='0' && zArg
[1]=='x' ){
5618 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
5620 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
5622 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
5623 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
5626 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
5629 eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg
);
5634 ** Set or clear a shell flag according to a boolean value.
5636 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
5637 if( booleanValue(zArg
) ){
5638 ShellSetFlag(p
, mFlag
);
5640 ShellClearFlag(p
, mFlag
);
5645 ** Close an output file, assuming it is not stderr or stdout
5647 static void output_file_close(FILE *f
){
5648 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
5652 ** Try to open an output file. The names "stdout" and "stderr" are
5653 ** recognized and do the right thing. NULL is returned if the output
5654 ** filename is "off".
5656 static FILE *output_file_open(const char *zFile
, int bTextMode
){
5658 if( cli_strcmp(zFile
,"stdout")==0 ){
5660 }else if( cli_strcmp(zFile
, "stderr")==0 ){
5662 }else if( cli_strcmp(zFile
, "off")==0 ){
5665 f
= fopen(zFile
, bTextMode
? "w" : "wb");
5667 eputf("Error: cannot open \"%s\"\n", zFile
);
5673 #ifndef SQLITE_OMIT_TRACE
5675 ** A routine for handling output from sqlite3_trace().
5677 static int sql_trace_callback(
5678 unsigned mType
, /* The trace type */
5679 void *pArg
, /* The ShellState pointer */
5680 void *pP
, /* Usually a pointer to sqlite_stmt */
5681 void *pX
/* Auxiliary output */
5683 ShellState
*p
= (ShellState
*)pArg
;
5684 sqlite3_stmt
*pStmt
;
5687 if( p
->traceOut
==0 ) return 0;
5688 if( mType
==SQLITE_TRACE_CLOSE
){
5689 sputz(p
->traceOut
, "-- closing database connection\n");
5692 if( mType
!=SQLITE_TRACE_ROW
&& pX
!=0 && ((const char*)pX
)[0]=='-' ){
5693 zSql
= (const char*)pX
;
5695 pStmt
= (sqlite3_stmt
*)pP
;
5696 switch( p
->eTraceType
){
5697 case SHELL_TRACE_EXPANDED
: {
5698 zSql
= sqlite3_expanded_sql(pStmt
);
5701 #ifdef SQLITE_ENABLE_NORMALIZE
5702 case SHELL_TRACE_NORMALIZED
: {
5703 zSql
= sqlite3_normalized_sql(pStmt
);
5708 zSql
= sqlite3_sql(pStmt
);
5713 if( zSql
==0 ) return 0;
5714 nSql
= strlen(zSql
);
5715 if( nSql
>1000000000 ) nSql
= 1000000000;
5716 while( nSql
>0 && zSql
[nSql
-1]==';' ){ nSql
--; }
5718 case SQLITE_TRACE_ROW
:
5719 case SQLITE_TRACE_STMT
: {
5720 sputf(p
->traceOut
, "%.*s;\n", (int)nSql
, zSql
);
5723 case SQLITE_TRACE_PROFILE
: {
5724 sqlite3_int64 nNanosec
= pX
? *(sqlite3_int64
*)pX
: 0;
5725 sputf(p
->traceOut
, "%.*s; -- %lld ns\n", (int)nSql
, zSql
, nNanosec
);
5734 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5735 ** a useful spot to set a debugger breakpoint.
5737 ** This routine does not do anything practical. The code are there simply
5738 ** to prevent the compiler from optimizing this routine out.
5740 static void test_breakpoint(void){
5741 static unsigned int nCall
= 0;
5742 if( (nCall
++)==0xffffffff ) printf("Many .breakpoints have run\n");
5746 ** An object used to read a CSV and other files for import.
5748 typedef struct ImportCtx ImportCtx
;
5750 const char *zFile
; /* Name of the input file */
5751 FILE *in
; /* Read the CSV text from this input stream */
5752 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close in */
5753 char *z
; /* Accumulated text for a field */
5754 int n
; /* Number of bytes in z */
5755 int nAlloc
; /* Space allocated for z[] */
5756 int nLine
; /* Current line number */
5757 int nRow
; /* Number of rows imported */
5758 int nErr
; /* Number of errors encountered */
5759 int bNotFirst
; /* True if one or more bytes already read */
5760 int cTerm
; /* Character that terminated the most recent field */
5761 int cColSep
; /* The column separator character. (Usually ",") */
5762 int cRowSep
; /* The row separator character. (Usually "\n") */
5765 /* Clean up resourced used by an ImportCtx */
5766 static void import_cleanup(ImportCtx
*p
){
5767 if( p
->in
!=0 && p
->xCloser
!=0 ){
5775 /* Append a single byte to z[] */
5776 static void import_append_char(ImportCtx
*p
, int c
){
5777 if( p
->n
+1>=p
->nAlloc
){
5778 p
->nAlloc
+= p
->nAlloc
+ 100;
5779 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
5780 shell_check_oom(p
->z
);
5782 p
->z
[p
->n
++] = (char)c
;
5785 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5786 ** with the option of having a separator other than ",".
5788 ** + Input comes from p->in.
5789 ** + Store results in p->z of length p->n. Space to hold p->z comes
5790 ** from sqlite3_malloc64().
5791 ** + Use p->cSep as the column separator. The default is ",".
5792 ** + Use p->rSep as the row separator. The default is "\n".
5793 ** + Keep track of the line number in p->nLine.
5794 ** + Store the character that terminates the field in p->cTerm. Store
5795 ** EOF on end-of-file.
5796 ** + Report syntax errors on stderr
5798 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
5800 int cSep
= (u8
)p
->cColSep
;
5801 int rSep
= (u8
)p
->cRowSep
;
5804 if( c
==EOF
|| seenInterrupt
){
5810 int startLine
= p
->nLine
;
5815 if( c
==rSep
) p
->nLine
++;
5822 if( (c
==cSep
&& pc
==cQuote
)
5823 || (c
==rSep
&& pc
==cQuote
)
5824 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
5825 || (c
==EOF
&& pc
==cQuote
)
5827 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
5831 if( pc
==cQuote
&& c
!='\r' ){
5832 eputf("%s:%d: unescaped %c character\n", p
->zFile
, p
->nLine
, cQuote
);
5835 eputf("%s:%d: unterminated %c-quoted field\n",
5836 p
->zFile
, startLine
, cQuote
);
5840 import_append_char(p
, c
);
5845 /* If this is the first field being parsed and it begins with the
5846 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5847 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
5848 import_append_char(p
, c
);
5850 if( (c
&0xff)==0xbb ){
5851 import_append_char(p
, c
);
5853 if( (c
&0xff)==0xbf ){
5856 return csv_read_one_field(p
);
5860 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5861 import_append_char(p
, c
);
5866 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
5870 if( p
->z
) p
->z
[p
->n
] = 0;
5875 /* Read a single field of ASCII delimited text.
5877 ** + Input comes from p->in.
5878 ** + Store results in p->z of length p->n. Space to hold p->z comes
5879 ** from sqlite3_malloc64().
5880 ** + Use p->cSep as the column separator. The default is "\x1F".
5881 ** + Use p->rSep as the row separator. The default is "\x1E".
5882 ** + Keep track of the row number in p->nLine.
5883 ** + Store the character that terminates the field in p->cTerm. Store
5884 ** EOF on end-of-file.
5885 ** + Report syntax errors on stderr
5887 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
5889 int cSep
= (u8
)p
->cColSep
;
5890 int rSep
= (u8
)p
->cRowSep
;
5893 if( c
==EOF
|| seenInterrupt
){
5897 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5898 import_append_char(p
, c
);
5905 if( p
->z
) p
->z
[p
->n
] = 0;
5910 ** Try to transfer data for table zTable. If an error is seen while
5911 ** moving forward, try to go backwards. The backwards movement won't
5912 ** work for WITHOUT ROWID tables.
5914 static void tryToCloneData(
5919 sqlite3_stmt
*pQuery
= 0;
5920 sqlite3_stmt
*pInsert
= 0;
5925 int nTable
= strlen30(zTable
);
5928 const int spinRate
= 10000;
5930 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
5931 shell_check_oom(zQuery
);
5932 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5934 eputf("Error %d: %s on [%s]\n",
5935 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
), zQuery
);
5938 n
= sqlite3_column_count(pQuery
);
5939 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
5940 shell_check_oom(zInsert
);
5941 sqlite3_snprintf(200+nTable
,zInsert
,
5942 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
5943 i
= strlen30(zInsert
);
5945 memcpy(zInsert
+i
, ",?", 2);
5948 memcpy(zInsert
+i
, ");", 3);
5949 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
5951 eputf("Error %d: %s on [%s]\n",
5952 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
), zInsert
);
5956 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
5958 switch( sqlite3_column_type(pQuery
, i
) ){
5960 sqlite3_bind_null(pInsert
, i
+1);
5963 case SQLITE_INTEGER
: {
5964 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
5967 case SQLITE_FLOAT
: {
5968 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
5972 sqlite3_bind_text(pInsert
, i
+1,
5973 (const char*)sqlite3_column_text(pQuery
,i
),
5978 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
5979 sqlite3_column_bytes(pQuery
,i
),
5985 rc
= sqlite3_step(pInsert
);
5986 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
5987 eputf("Error %d: %s\n",
5988 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
));
5990 sqlite3_reset(pInsert
);
5992 if( (cnt
%spinRate
)==0 ){
5993 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
5997 if( rc
==SQLITE_DONE
) break;
5998 sqlite3_finalize(pQuery
);
5999 sqlite3_free(zQuery
);
6000 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
6002 shell_check_oom(zQuery
);
6003 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6005 eputf("Warning: cannot step \"%s\" backwards", zTable
);
6008 } /* End for(k=0...) */
6011 sqlite3_finalize(pQuery
);
6012 sqlite3_finalize(pInsert
);
6013 sqlite3_free(zQuery
);
6014 sqlite3_free(zInsert
);
6019 ** Try to transfer all rows of the schema that match zWhere. For
6020 ** each row, invoke xForEach() on the object defined by that row.
6021 ** If an error is encountered while moving forward through the
6022 ** sqlite_schema table, try again moving backwards.
6024 static void tryToCloneSchema(
6028 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
6030 sqlite3_stmt
*pQuery
= 0;
6033 const unsigned char *zName
;
6034 const unsigned char *zSql
;
6037 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6038 " WHERE %s ORDER BY rowid ASC", zWhere
);
6039 shell_check_oom(zQuery
);
6040 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6042 eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p
->db
),
6043 sqlite3_errmsg(p
->db
), zQuery
);
6044 goto end_schema_xfer
;
6046 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
6047 zName
= sqlite3_column_text(pQuery
, 0);
6048 zSql
= sqlite3_column_text(pQuery
, 1);
6049 if( zName
==0 || zSql
==0 ) continue;
6050 if( sqlite3_stricmp((char*)zName
, "sqlite_sequence")!=0 ){
6051 sputf(stdout
, "%s... ", zName
); fflush(stdout
);
6052 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
6054 eputf("Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
6055 sqlite3_free(zErrMsg
);
6060 xForEach(p
, newDb
, (const char*)zName
);
6062 sputz(stdout
, "done\n");
6064 if( rc
!=SQLITE_DONE
){
6065 sqlite3_finalize(pQuery
);
6066 sqlite3_free(zQuery
);
6067 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6068 " WHERE %s ORDER BY rowid DESC", zWhere
);
6069 shell_check_oom(zQuery
);
6070 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6072 eputf("Error: (%d) %s on [%s]\n",
6073 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
), zQuery
);
6074 goto end_schema_xfer
;
6076 while( sqlite3_step(pQuery
)==SQLITE_ROW
){
6077 zName
= sqlite3_column_text(pQuery
, 0);
6078 zSql
= sqlite3_column_text(pQuery
, 1);
6079 if( zName
==0 || zSql
==0 ) continue;
6080 if( sqlite3_stricmp((char*)zName
, "sqlite_sequence")==0 ) continue;
6081 sputf(stdout
, "%s... ", zName
); fflush(stdout
);
6082 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
6084 eputf("Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
6085 sqlite3_free(zErrMsg
);
6089 xForEach(p
, newDb
, (const char*)zName
);
6091 sputz(stdout
, "done\n");
6095 sqlite3_finalize(pQuery
);
6096 sqlite3_free(zQuery
);
6100 ** Open a new database file named "zNewDb". Try to recover as much information
6101 ** as possible out of the main database (which might be corrupt) and write it
6104 static void tryToClone(ShellState
*p
, const char *zNewDb
){
6107 if( access(zNewDb
,0)==0 ){
6108 eputf("File \"%s\" already exists.\n", zNewDb
);
6111 rc
= sqlite3_open(zNewDb
, &newDb
);
6113 eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb
));
6115 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
6116 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
6117 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
6118 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
6119 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
6120 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6125 #ifndef SQLITE_SHELL_FIDDLE
6127 ** Change the output stream (file or pipe or console) to something else.
6129 static void output_redir(ShellState
*p
, FILE *pfNew
){
6130 if( p
->out
!= stdout
) eputz("Output already redirected.\n");
6133 setOutputStream(pfNew
);
6138 ** Change the output file back to stdout.
6140 ** If the p->doXdgOpen flag is set, that means the output was being
6141 ** redirected to a temporary file named by p->zTempFile. In that case,
6142 ** launch start/open/xdg-open on that temporary file.
6144 static void output_reset(ShellState
*p
){
6145 if( p
->outfile
[0]=='|' ){
6146 #ifndef SQLITE_OMIT_POPEN
6150 output_file_close(p
->out
);
6151 #ifndef SQLITE_NOHAVE_SYSTEM
6153 const char *zXdgOpenCmd
=
6156 #elif defined(__APPLE__)
6162 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
6164 eputf("Failed: [%s]\n", zCmd
);
6166 /* Give the start/open/xdg-open command some time to get
6167 ** going before we continue, and potential delete the
6168 ** p->zTempFile data file out from under it */
6169 sqlite3_sleep(2000);
6175 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6179 setOutputStream(stdout
);
6182 # define output_redir(SS,pfO)
6183 # define output_reset(SS)
6187 ** Run an SQL command and return the single integer result.
6189 static int db_int(sqlite3
*db
, const char *zSql
){
6190 sqlite3_stmt
*pStmt
;
6192 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
6193 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
6194 res
= sqlite3_column_int(pStmt
,0);
6196 sqlite3_finalize(pStmt
);
6200 #if SQLITE_SHELL_HAVE_RECOVER
6202 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6204 static unsigned int get2byteInt(unsigned char *a
){
6205 return (a
[0]<<8) + a
[1];
6207 static unsigned int get4byteInt(unsigned char *a
){
6208 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
6212 ** Implementation of the ".dbinfo" command.
6214 ** Return 1 on error, 2 to exit, and 0 otherwise.
6216 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
6217 static const struct { const char *zName
; int ofst
; } aField
[] = {
6218 { "file change counter:", 24 },
6219 { "database page count:", 28 },
6220 { "freelist page count:", 36 },
6221 { "schema cookie:", 40 },
6222 { "schema format:", 44 },
6223 { "default cache size:", 48 },
6224 { "autovacuum top root:", 52 },
6225 { "incremental vacuum:", 64 },
6226 { "text encoding:", 56 },
6227 { "user version:", 60 },
6228 { "application id:", 68 },
6229 { "software version:", 96 },
6231 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
6232 { "number of tables:",
6233 "SELECT count(*) FROM %s WHERE type='table'" },
6234 { "number of indexes:",
6235 "SELECT count(*) FROM %s WHERE type='index'" },
6236 { "number of triggers:",
6237 "SELECT count(*) FROM %s WHERE type='trigger'" },
6238 { "number of views:",
6239 "SELECT count(*) FROM %s WHERE type='view'" },
6241 "SELECT total(length(sql)) FROM %s" },
6244 unsigned iDataVersion
;
6246 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
6247 sqlite3_stmt
*pStmt
= 0;
6248 unsigned char aHdr
[100];
6250 if( p
->db
==0 ) return 1;
6251 rc
= sqlite3_prepare_v2(p
->db
,
6252 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6255 eputf("error: %s\n", sqlite3_errmsg(p
->db
));
6256 sqlite3_finalize(pStmt
);
6259 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
6260 if( sqlite3_step(pStmt
)==SQLITE_ROW
6261 && sqlite3_column_bytes(pStmt
,0)>100
6263 const u8
*pb
= sqlite3_column_blob(pStmt
,0);
6264 shell_check_oom(pb
);
6265 memcpy(aHdr
, pb
, 100);
6266 sqlite3_finalize(pStmt
);
6268 eputz("unable to read database header\n");
6269 sqlite3_finalize(pStmt
);
6272 i
= get2byteInt(aHdr
+16);
6273 if( i
==1 ) i
= 65536;
6274 oputf("%-20s %d\n", "database page size:", i
);
6275 oputf("%-20s %d\n", "write format:", aHdr
[18]);
6276 oputf("%-20s %d\n", "read format:", aHdr
[19]);
6277 oputf("%-20s %d\n", "reserved bytes:", aHdr
[20]);
6278 for(i
=0; i
<ArraySize(aField
); i
++){
6279 int ofst
= aField
[i
].ofst
;
6280 unsigned int val
= get4byteInt(aHdr
+ ofst
);
6281 oputf("%-20s %u", aField
[i
].zName
, val
);
6284 if( val
==1 ) oputz(" (utf8)");
6285 if( val
==2 ) oputz(" (utf16le)");
6286 if( val
==3 ) oputz(" (utf16be)");
6292 zSchemaTab
= sqlite3_mprintf("main.sqlite_schema");
6293 }else if( cli_strcmp(zDb
,"temp")==0 ){
6294 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_schema");
6296 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_schema", zDb
);
6298 for(i
=0; i
<ArraySize(aQuery
); i
++){
6299 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
6300 int val
= db_int(p
->db
, zSql
);
6302 oputf("%-20s %d\n", aQuery
[i
].zName
, val
);
6304 sqlite3_free(zSchemaTab
);
6305 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_DATA_VERSION
, &iDataVersion
);
6306 oputf("%-20s %u\n", "data version", iDataVersion
);
6309 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6312 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6314 static int shellDatabaseError(sqlite3
*db
){
6315 const char *zErr
= sqlite3_errmsg(db
);
6316 eputf("Error: %s\n", zErr
);
6321 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6322 ** if they match and FALSE (0) if they do not match.
6326 ** '*' Matches any sequence of zero or more characters.
6328 ** '?' Matches exactly one character.
6330 ** [...] Matches one character from the enclosed list of
6333 ** [^...] Matches one character not in the enclosed list.
6335 ** '#' Matches any sequence of one or more digits with an
6336 ** optional + or - sign in front
6338 ** ' ' Any span of whitespace matches any other span of
6341 ** Extra whitespace at the end of z[] is ignored.
6343 static int testcase_glob(const char *zGlob
, const char *z
){
6348 while( (c
= (*(zGlob
++)))!=0 ){
6350 if( !IsSpace(*z
) ) return 0;
6351 while( IsSpace(*zGlob
) ) zGlob
++;
6352 while( IsSpace(*z
) ) z
++;
6354 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
6355 if( c
=='?' && (*(z
++))==0 ) return 0;
6360 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
6365 while( (c2
= (*(z
++)))!=0 ){
6368 if( c2
==0 ) return 0;
6370 if( testcase_glob(zGlob
,z
) ) return 1;
6374 if( (*(z
++))==0 ) return 0;
6380 if( c
==0 ) return 0;
6387 if( c
==']' ) seen
= 1;
6390 while( c2
&& c2
!=']' ){
6391 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
6393 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
6403 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
6405 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
6406 if( !IsDigit(z
[0]) ) return 0;
6408 while( IsDigit(z
[0]) ){ z
++; }
6410 if( c
!=(*(z
++)) ) return 0;
6413 while( IsSpace(*z
) ){ z
++; }
6419 ** Compare the string as a command-line option with either one or two
6420 ** initial "-" characters.
6422 static int optionMatch(const char *zStr
, const char *zOpt
){
6423 if( zStr
[0]!='-' ) return 0;
6425 if( zStr
[0]=='-' ) zStr
++;
6426 return cli_strcmp(zStr
, zOpt
)==0;
6432 int shellDeleteFile(const char *zFilename
){
6435 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
6439 rc
= unlink(zFilename
);
6445 ** Try to delete the temporary file (if there is one) and free the
6446 ** memory used to hold the name of the temp file.
6448 static void clearTempFile(ShellState
*p
){
6449 if( p
->zTempFile
==0 ) return;
6450 if( p
->doXdgOpen
) return;
6451 if( shellDeleteFile(p
->zTempFile
) ) return;
6452 sqlite3_free(p
->zTempFile
);
6457 ** Create a new temp file name with the given suffix.
6459 static void newTempFile(ShellState
*p
, const char *zSuffix
){
6461 sqlite3_free(p
->zTempFile
);
6464 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
6466 if( p
->zTempFile
==0 ){
6467 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6468 ** will not work and we will need to fallback to guessing */
6471 sqlite3_randomness(sizeof(r
), &r
);
6472 zTemp
= getenv("TEMP");
6473 if( zTemp
==0 ) zTemp
= getenv("TMP");
6481 p
->zTempFile
= sqlite3_mprintf("%s/temp%llx.%s", zTemp
, r
, zSuffix
);
6483 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
6485 shell_check_oom(p
->zTempFile
);
6490 ** The implementation of SQL scalar function fkey_collate_clause(), used
6491 ** by the ".lint fkey-indexes" command. This scalar function is always
6492 ** called with four arguments - the parent table name, the parent column name,
6493 ** the child table name and the child column name.
6495 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6497 ** If either of the named tables or columns do not exist, this function
6498 ** returns an empty string. An empty string is also returned if both tables
6499 ** and columns exist but have the same default collation sequence. Or,
6500 ** if both exist but the default collation sequences are different, this
6501 ** function returns the string " COLLATE <parent-collation>", where
6502 ** <parent-collation> is the default collation sequence of the parent column.
6504 static void shellFkeyCollateClause(
6505 sqlite3_context
*pCtx
,
6507 sqlite3_value
**apVal
6509 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
6510 const char *zParent
;
6511 const char *zParentCol
;
6512 const char *zParentSeq
;
6514 const char *zChildCol
;
6515 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
6519 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
6520 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
6521 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
6522 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
6524 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
6525 rc
= sqlite3_table_column_metadata(
6526 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
6528 if( rc
==SQLITE_OK
){
6529 rc
= sqlite3_table_column_metadata(
6530 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
6534 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
6535 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
6536 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
6543 ** The implementation of dot-command ".lint fkey-indexes".
6545 static int lintFkeyIndexes(
6546 ShellState
*pState
, /* Current shell tool state */
6547 char **azArg
, /* Array of arguments passed to dot command */
6548 int nArg
/* Number of entries in azArg[] */
6550 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
6551 int bVerbose
= 0; /* If -verbose is present */
6552 int bGroupByParent
= 0; /* If -groupbyparent is present */
6553 int i
; /* To iterate through azArg[] */
6554 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
6555 int rc
; /* Return code */
6556 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
6559 ** This SELECT statement returns one row for each foreign key constraint
6560 ** in the schema of the main database. The column values are:
6562 ** 0. The text of an SQL statement similar to:
6564 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6566 ** This SELECT is similar to the one that the foreign keys implementation
6567 ** needs to run internally on child tables. If there is an index that can
6568 ** be used to optimize this query, then it can also be used by the FK
6569 ** implementation to optimize DELETE or UPDATE statements on the parent
6572 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6573 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6574 ** contains an index that can be used to optimize the query.
6576 ** 2. Human readable text that describes the child table and columns. e.g.
6578 ** "child_table(child_key1, child_key2)"
6580 ** 3. Human readable text that describes the parent table and columns. e.g.
6582 ** "parent_table(parent_key1, parent_key2)"
6584 ** 4. A full CREATE INDEX statement for an index that could be used to
6585 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6587 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6589 ** 5. The name of the parent table.
6591 ** These six values are used by the C logic below to generate the report.
6595 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6596 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6597 " || fkey_collate_clause("
6598 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6600 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6601 " || group_concat('*=?', ' AND ') || ')'"
6603 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6605 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6607 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6608 " || ' ON ' || quote(s.name) || '('"
6609 " || group_concat(quote(f.[from]) ||"
6610 " fkey_collate_clause("
6611 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6615 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6616 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6617 "GROUP BY s.name, f.id "
6618 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6620 const char *zGlobIPK
= "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6622 for(i
=2; i
<nArg
; i
++){
6623 int n
= strlen30(azArg
[i
]);
6624 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
6627 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
6632 eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg
[0], azArg
[1]);
6633 return SQLITE_ERROR
;
6637 /* Register the fkey_collate_clause() SQL function */
6638 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
6639 0, shellFkeyCollateClause
, 0, 0
6643 if( rc
==SQLITE_OK
){
6644 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
6646 if( rc
==SQLITE_OK
){
6647 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
6650 if( rc
==SQLITE_OK
){
6653 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
6655 sqlite3_stmt
*pExplain
= 0;
6656 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
6657 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
6658 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
6659 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
6660 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
6661 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
6663 if( zEQP
==0 ) continue;
6664 if( zGlob
==0 ) continue;
6665 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
6666 if( rc
!=SQLITE_OK
) break;
6667 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
6668 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
6669 res
= zPlan
!=0 && ( 0==sqlite3_strglob(zGlob
, zPlan
)
6670 || 0==sqlite3_strglob(zGlobIPK
, zPlan
));
6672 rc
= sqlite3_finalize(pExplain
);
6673 if( rc
!=SQLITE_OK
) break;
6676 eputz("Error: internal error");
6680 && (bVerbose
|| res
==0)
6681 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
6683 oputf("-- Parent table %s\n", zParent
);
6684 sqlite3_free(zPrev
);
6685 zPrev
= sqlite3_mprintf("%s", zParent
);
6689 oputf("%s%s --> %s\n", zIndent
, zCI
, zTarget
);
6690 }else if( bVerbose
){
6691 oputf("%s/* no extra indexes required for %s -> %s */\n",
6692 zIndent
, zFrom
, zTarget
6697 sqlite3_free(zPrev
);
6699 if( rc
!=SQLITE_OK
){
6700 eputf("%s\n", sqlite3_errmsg(db
));
6703 rc2
= sqlite3_finalize(pSql
);
6704 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
6706 eputf("%s\n", sqlite3_errmsg(db
));
6709 eputf("%s\n", sqlite3_errmsg(db
));
6716 ** Implementation of ".lint" dot command.
6718 static int lintDotCommand(
6719 ShellState
*pState
, /* Current shell tool state */
6720 char **azArg
, /* Array of arguments passed to dot command */
6721 int nArg
/* Number of entries in azArg[] */
6724 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
6725 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
6726 return lintFkeyIndexes(pState
, azArg
, nArg
);
6729 eputf("Usage %s sub-command ?switches...?\n", azArg
[0]);
6730 eputz("Where sub-commands are:\n");
6731 eputz(" fkey-indexes\n");
6732 return SQLITE_ERROR
;
6735 static void shellPrepare(
6739 sqlite3_stmt
**ppStmt
6742 if( *pRc
==SQLITE_OK
){
6743 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
6744 if( rc
!=SQLITE_OK
){
6745 eputf("sql error: %s (%d)\n", sqlite3_errmsg(db
), sqlite3_errcode(db
));
6752 ** Create a prepared statement using printf-style arguments for the SQL.
6754 static void shellPreparePrintf(
6757 sqlite3_stmt
**ppStmt
,
6762 if( *pRc
==SQLITE_OK
){
6766 z
= sqlite3_vmprintf(zFmt
, ap
);
6769 *pRc
= SQLITE_NOMEM
;
6771 shellPrepare(db
, pRc
, z
, ppStmt
);
6778 ** Finalize the prepared statement created using shellPreparePrintf().
6780 static void shellFinalize(
6785 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6786 int rc
= sqlite3_finalize(pStmt
);
6787 if( *pRc
==SQLITE_OK
){
6788 if( rc
!=SQLITE_OK
){
6789 eputf("SQL error: %s\n", sqlite3_errmsg(db
));
6796 #if !defined SQLITE_OMIT_VIRTUALTABLE
6797 /* Reset the prepared statement created using shellPreparePrintf().
6799 ** This routine is could be marked "static". But it is not always used,
6800 ** depending on compile-time options. By omitting the "static", we avoid
6801 ** nuisance compiler warnings about "defined but not used".
6807 int rc
= sqlite3_reset(pStmt
);
6808 if( *pRc
==SQLITE_OK
){
6809 if( rc
!=SQLITE_OK
){
6810 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6811 eputf("SQL error: %s\n", sqlite3_errmsg(db
));
6816 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6818 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6819 /******************************************************************************
6820 ** The ".archive" or ".ar" command.
6823 ** Structure representing a single ".ar" command.
6825 typedef struct ArCommand ArCommand
;
6827 u8 eCmd
; /* An AR_CMD_* value */
6828 u8 bVerbose
; /* True if --verbose */
6829 u8 bZip
; /* True if the archive is a ZIP */
6830 u8 bDryRun
; /* True if --dry-run */
6831 u8 bAppend
; /* True if --append */
6832 u8 bGlob
; /* True if --glob */
6833 u8 fromCmdLine
; /* Run from -A instead of .archive */
6834 int nArg
; /* Number of command arguments */
6835 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
6836 const char *zFile
; /* --file argument, or NULL */
6837 const char *zDir
; /* --directory argument, or NULL */
6838 char **azArg
; /* Array of command arguments */
6839 ShellState
*p
; /* Shell state */
6840 sqlite3
*db
; /* Database containing the archive */
6844 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6846 static int arUsage(FILE *f
){
6847 showHelp(f
,"archive");
6848 return SQLITE_ERROR
;
6852 ** Print an error message for the .ar command to stderr and return
6855 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
6859 z
= sqlite3_vmprintf(zFmt
, ap
);
6861 eputf("Error: %s\n", z
);
6862 if( pAr
->fromCmdLine
){
6863 eputz("Use \"-A\" for more help\n");
6865 eputz("Use \".archive --help\" for more help\n");
6868 return SQLITE_ERROR
;
6872 ** Values for ArCommand.eCmd.
6874 #define AR_CMD_CREATE 1
6875 #define AR_CMD_UPDATE 2
6876 #define AR_CMD_INSERT 3
6877 #define AR_CMD_EXTRACT 4
6878 #define AR_CMD_LIST 5
6879 #define AR_CMD_HELP 6
6880 #define AR_CMD_REMOVE 7
6883 ** Other (non-command) switches.
6885 #define AR_SWITCH_VERBOSE 8
6886 #define AR_SWITCH_FILE 9
6887 #define AR_SWITCH_DIRECTORY 10
6888 #define AR_SWITCH_APPEND 11
6889 #define AR_SWITCH_DRYRUN 12
6890 #define AR_SWITCH_GLOB 13
6892 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
6895 case AR_CMD_EXTRACT
:
6902 return arErrorMsg(pAr
, "multiple command options");
6904 pAr
->eCmd
= eSwitch
;
6907 case AR_SWITCH_DRYRUN
:
6910 case AR_SWITCH_GLOB
:
6913 case AR_SWITCH_VERBOSE
:
6916 case AR_SWITCH_APPEND
:
6918 deliberate_fall_through
;
6919 case AR_SWITCH_FILE
:
6922 case AR_SWITCH_DIRECTORY
:
6931 ** Parse the command line for an ".ar" command. The results are written into
6932 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6933 ** successfully, otherwise an error message is written to stderr and
6934 ** SQLITE_ERROR returned.
6936 static int arParseCommand(
6937 char **azArg
, /* Array of arguments passed to dot command */
6938 int nArg
, /* Number of entries in azArg[] */
6939 ArCommand
*pAr
/* Populate this object */
6947 { "create", 'c', AR_CMD_CREATE
, 0 },
6948 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
6949 { "insert", 'i', AR_CMD_INSERT
, 0 },
6950 { "list", 't', AR_CMD_LIST
, 0 },
6951 { "remove", 'r', AR_CMD_REMOVE
, 0 },
6952 { "update", 'u', AR_CMD_UPDATE
, 0 },
6953 { "help", 'h', AR_CMD_HELP
, 0 },
6954 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
6955 { "file", 'f', AR_SWITCH_FILE
, 1 },
6956 { "append", 'a', AR_SWITCH_APPEND
, 1 },
6957 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
6958 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
6959 { "glob", 'g', AR_SWITCH_GLOB
, 0 },
6961 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
6962 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
6965 eputz("Wrong number of arguments. Usage:\n");
6966 return arUsage(stderr
);
6970 /* Traditional style [tar] invocation */
6973 for(i
=0; z
[i
]; i
++){
6974 const char *zArg
= 0;
6975 struct ArSwitch
*pOpt
;
6976 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
6977 if( z
[i
]==pOpt
->cShort
) break;
6980 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
6984 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
6986 zArg
= azArg
[iArg
++];
6988 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
6990 pAr
->nArg
= nArg
-iArg
;
6992 pAr
->azArg
= &azArg
[iArg
];
6995 /* Non-traditional invocation */
6997 for(iArg
=1; iArg
<nArg
; iArg
++){
7001 /* All remaining command line words are command arguments. */
7002 pAr
->azArg
= &azArg
[iArg
];
7003 pAr
->nArg
= nArg
-iArg
;
7010 /* One or more short options */
7012 const char *zArg
= 0;
7013 struct ArSwitch
*pOpt
;
7014 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
7015 if( z
[i
]==pOpt
->cShort
) break;
7018 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
7025 if( iArg
>=(nArg
-1) ){
7026 return arErrorMsg(pAr
, "option requires an argument: %c",
7029 zArg
= azArg
[++iArg
];
7032 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
7034 }else if( z
[2]=='\0' ){
7035 /* A -- option, indicating that all remaining command line words
7036 ** are command arguments. */
7037 pAr
->azArg
= &azArg
[iArg
+1];
7038 pAr
->nArg
= nArg
-iArg
-1;
7042 const char *zArg
= 0; /* Argument for option, if any */
7043 struct ArSwitch
*pMatch
= 0; /* Matching option */
7044 struct ArSwitch
*pOpt
; /* Iterator */
7045 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
7046 const char *zLong
= pOpt
->zLong
;
7047 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
7049 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
7057 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
7060 if( iArg
>=(nArg
-1) ){
7061 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
7063 zArg
= azArg
[++iArg
];
7065 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
7071 eputz("Required argument missing. Usage:\n");
7072 return arUsage(stderr
);
7078 ** This function assumes that all arguments within the ArCommand.azArg[]
7079 ** array refer to archive members, as for the --extract, --list or --remove
7080 ** commands. It checks that each of them are "present". If any specified
7081 ** file is not present in the archive, an error is printed to stderr and an
7082 ** error code returned. Otherwise, if all specified arguments are present
7083 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7084 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7085 ** when pAr->bGlob is true.
7087 ** This function strips any trailing '/' characters from each argument.
7088 ** This is consistent with the way the [tar] command seems to work on
7091 static int arCheckEntries(ArCommand
*pAr
){
7095 sqlite3_stmt
*pTest
= 0;
7096 const char *zSel
= (pAr
->bGlob
)
7097 ? "SELECT name FROM %s WHERE glob($name,name)"
7098 : "SELECT name FROM %s WHERE name=$name";
7100 shellPreparePrintf(pAr
->db
, &rc
, &pTest
, zSel
, pAr
->zSrcTable
);
7101 j
= sqlite3_bind_parameter_index(pTest
, "$name");
7102 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7103 char *z
= pAr
->azArg
[i
];
7104 int n
= strlen30(z
);
7106 while( n
>0 && z
[n
-1]=='/' ) n
--;
7108 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
7109 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
7112 shellReset(&rc
, pTest
);
7113 if( rc
==SQLITE_OK
&& bOk
==0 ){
7114 eputf("not found in archive: %s\n", z
);
7118 shellFinalize(&rc
, pTest
);
7124 ** Format a WHERE clause that can be used against the "sqlar" table to
7125 ** identify all archive members that match the command arguments held
7126 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7127 ** The caller is responsible for eventually calling sqlite3_free() on
7128 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7129 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7131 static void arWhereClause(
7134 char **pzWhere
/* OUT: New WHERE clause */
7137 const char *zSameOp
= (pAr
->bGlob
)? "GLOB" : "=";
7138 if( *pRc
==SQLITE_OK
){
7140 zWhere
= sqlite3_mprintf("1");
7143 const char *zSep
= "";
7144 for(i
=0; i
<pAr
->nArg
; i
++){
7145 const char *z
= pAr
->azArg
[i
];
7146 zWhere
= sqlite3_mprintf(
7147 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7148 zWhere
, zSep
, zSameOp
, z
, strlen30(z
)+1, zSameOp
, z
7151 *pRc
= SQLITE_NOMEM
;
7162 ** Implementation of .ar "lisT" command.
7164 static int arListCommand(ArCommand
*pAr
){
7165 const char *zSql
= "SELECT %s FROM %s WHERE %s";
7166 const char *azCols
[] = {
7168 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7172 sqlite3_stmt
*pSql
= 0;
7175 rc
= arCheckEntries(pAr
);
7176 arWhereClause(&rc
, pAr
, &zWhere
);
7178 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
7179 pAr
->zSrcTable
, zWhere
);
7181 oputf("%s\n", sqlite3_sql(pSql
));
7183 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7184 if( pAr
->bVerbose
){
7185 oputf("%s % 10d %s %s\n",
7186 sqlite3_column_text(pSql
, 0), sqlite3_column_int(pSql
, 1),
7187 sqlite3_column_text(pSql
, 2),sqlite3_column_text(pSql
, 3));
7189 oputf("%s\n", sqlite3_column_text(pSql
, 0));
7193 shellFinalize(&rc
, pSql
);
7194 sqlite3_free(zWhere
);
7199 ** Implementation of .ar "Remove" command.
7201 static int arRemoveCommand(ArCommand
*pAr
){
7207 /* Verify that args actually exist within the archive before proceeding.
7208 ** And formulate a WHERE clause to match them. */
7209 rc
= arCheckEntries(pAr
);
7210 arWhereClause(&rc
, pAr
, &zWhere
);
7212 if( rc
==SQLITE_OK
){
7213 zSql
= sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7214 pAr
->zSrcTable
, zWhere
);
7216 oputf("%s\n", zSql
);
7219 rc
= sqlite3_exec(pAr
->db
, "SAVEPOINT ar;", 0, 0, 0);
7220 if( rc
==SQLITE_OK
){
7221 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7222 if( rc
!=SQLITE_OK
){
7223 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7225 rc
= sqlite3_exec(pAr
->db
, "RELEASE ar;", 0, 0, 0);
7229 sputf(stdout
, "ERROR: %s\n", zErr
); /* stdout? */
7234 sqlite3_free(zWhere
);
7240 ** Implementation of .ar "eXtract" command.
7242 static int arExtractCommand(ArCommand
*pAr
){
7246 " writefile(($dir || name), %s, mode, mtime) "
7247 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7248 " AND name NOT GLOB '*..[/\\]*'";
7250 const char *azExtraArg
[] = {
7251 "sqlar_uncompress(data, sz)",
7255 sqlite3_stmt
*pSql
= 0;
7261 /* If arguments are specified, check that they actually exist within
7262 ** the archive before proceeding. And formulate a WHERE clause to
7264 rc
= arCheckEntries(pAr
);
7265 arWhereClause(&rc
, pAr
, &zWhere
);
7267 if( rc
==SQLITE_OK
){
7269 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
7271 zDir
= sqlite3_mprintf("");
7273 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
7276 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
7277 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
7280 if( rc
==SQLITE_OK
){
7281 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
7282 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
7284 /* Run the SELECT statement twice. The first time, writefile() is called
7285 ** for all archive members that should be extracted. The second time,
7286 ** only for the directories. This is because the timestamps for
7287 ** extracted directories must be reset after they are populated (as
7288 ** populating them changes the timestamp). */
7290 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
7291 sqlite3_bind_int(pSql
, j
, i
);
7293 oputf("%s\n", sqlite3_sql(pSql
));
7295 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7296 if( i
==0 && pAr
->bVerbose
){
7297 oputf("%s\n", sqlite3_column_text(pSql
, 0));
7301 shellReset(&rc
, pSql
);
7303 shellFinalize(&rc
, pSql
);
7307 sqlite3_free(zWhere
);
7312 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7314 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
7317 oputf("%s\n", zSql
);
7321 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7323 sputf(stdout
, "ERROR: %s\n", zErr
);
7332 ** Implementation of .ar "create", "insert", and "update" commands.
7334 ** create -> Create a new SQL archive
7335 ** insert -> Insert or reinsert all files listed
7336 ** update -> Insert files that have changed or that were not
7337 ** previously in the archive
7339 ** Create the "sqlar" table in the database if it does not already exist.
7340 ** Then add each file in the azFile[] array to the archive. Directories
7341 ** are added recursively. If argument bVerbose is non-zero, a message is
7342 ** printed on stdout for each file archived.
7344 ** The create command is the same as update, except that it drops
7345 ** any existing "sqlar" table before beginning. The "insert" command
7346 ** always overwrites every file named on the command-line, where as
7347 ** "update" only overwrites if the size or mtime or mode has changed.
7349 static int arCreateOrUpdateCommand(
7350 ArCommand
*pAr
, /* Command arguments and options */
7351 int bUpdate
, /* true for a --create. */
7352 int bOnlyIfChanged
/* Only update if file has changed */
7354 const char *zCreate
=
7355 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7356 " name TEXT PRIMARY KEY, -- name of the file\n"
7357 " mode INT, -- access permissions\n"
7358 " mtime INT, -- last modification time\n"
7359 " sz INT, -- original file size\n"
7360 " data BLOB -- compressed content\n"
7362 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
7363 const char *zInsertFmt
[2] = {
7364 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7369 " CASE substr(lsmode(mode),1,1)\n"
7370 " WHEN '-' THEN length(data)\n"
7371 " WHEN 'd' THEN 0\n"
7373 " sqlar_compress(data)\n"
7374 " FROM fsdir(%Q,%Q) AS disk\n"
7375 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7377 "REPLACE INTO %s(name,mode,mtime,data)\n"
7383 " FROM fsdir(%Q,%Q) AS disk\n"
7384 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7386 int i
; /* For iterating through azFile[] */
7387 int rc
; /* Return code */
7388 const char *zTab
= 0; /* SQL table into which to insert */
7393 arExecSql(pAr
, "PRAGMA page_size=512");
7394 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
7395 if( rc
!=SQLITE_OK
) return rc
;
7398 /* Initialize the zipfile virtual table, if necessary */
7401 sqlite3_randomness(sizeof(r
),&r
);
7402 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
7404 zSql
= sqlite3_mprintf(
7405 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7408 rc
= arExecSql(pAr
, zSql
);
7414 /* Initialize the table for an SQLAR */
7417 rc
= arExecSql(pAr
, zDrop
);
7418 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
7420 rc
= arExecSql(pAr
, zCreate
);
7422 if( bOnlyIfChanged
){
7423 zExists
= sqlite3_mprintf(
7425 "SELECT 1 FROM %s AS mem"
7426 " WHERE mem.name=disk.name"
7427 " AND mem.mtime=disk.mtime"
7428 " AND mem.mode=disk.mode)", zTab
);
7430 zExists
= sqlite3_mprintf("");
7432 if( zExists
==0 ) rc
= SQLITE_NOMEM
;
7433 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7434 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
7435 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
7436 pAr
->azArg
[i
], pAr
->zDir
, zExists
);
7437 rc
= arExecSql(pAr
, zSql2
);
7438 sqlite3_free(zSql2
);
7441 if( rc
!=SQLITE_OK
){
7442 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7444 rc
= arExecSql(pAr
, "RELEASE ar;");
7445 if( pAr
->bZip
&& pAr
->zFile
){
7446 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
7447 arExecSql(pAr
, zSql
);
7451 sqlite3_free(zExists
);
7456 ** Implementation of ".ar" dot command.
7458 static int arDotCommand(
7459 ShellState
*pState
, /* Current shell tool state */
7460 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
7461 char **azArg
, /* Array of arguments passed to dot command */
7462 int nArg
/* Number of entries in azArg[] */
7466 memset(&cmd
, 0, sizeof(cmd
));
7467 cmd
.fromCmdLine
= fromCmdLine
;
7468 rc
= arParseCommand(azArg
, nArg
, &cmd
);
7469 if( rc
==SQLITE_OK
){
7470 int eDbType
= SHELL_OPEN_UNSPEC
;
7472 cmd
.db
= pState
->db
;
7474 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
7476 eDbType
= pState
->openMode
;
7478 if( eDbType
==SHELL_OPEN_ZIPFILE
){
7479 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
7481 cmd
.zSrcTable
= sqlite3_mprintf("zip");
7483 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
7487 }else if( cmd
.zFile
){
7489 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
7490 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_INSERT
7491 || cmd
.eCmd
==AR_CMD_REMOVE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
7492 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
7494 flags
= SQLITE_OPEN_READONLY
;
7498 oputf("-- open database '%s'%s\n", cmd
.zFile
,
7499 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
7501 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
7502 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
7503 if( rc
!=SQLITE_OK
){
7504 eputf("cannot open file: %s (%s)\n", cmd
.zFile
, sqlite3_errmsg(cmd
.db
));
7505 goto end_ar_command
;
7507 sqlite3_fileio_init(cmd
.db
, 0, 0);
7508 sqlite3_sqlar_init(cmd
.db
, 0, 0);
7509 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
7510 shellPutsFunc
, 0, 0);
7513 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
7514 if( cmd
.eCmd
!=AR_CMD_CREATE
7515 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
7517 eputz("database does not contain an 'sqlar' table\n");
7519 goto end_ar_command
;
7521 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
7526 rc
= arCreateOrUpdateCommand(&cmd
, 0, 0);
7529 case AR_CMD_EXTRACT
:
7530 rc
= arExtractCommand(&cmd
);
7534 rc
= arListCommand(&cmd
);
7538 arUsage(pState
->out
);
7542 rc
= arCreateOrUpdateCommand(&cmd
, 1, 0);
7546 rc
= arRemoveCommand(&cmd
);
7550 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
7551 rc
= arCreateOrUpdateCommand(&cmd
, 1, 1);
7556 if( cmd
.db
!=pState
->db
){
7559 sqlite3_free(cmd
.zSrcTable
);
7563 /* End of the ".archive" or ".ar" command logic
7564 *******************************************************************************/
7565 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7567 #if SQLITE_SHELL_HAVE_RECOVER
7570 ** This function is used as a callback by the recover extension. Simply
7571 ** print the supplied SQL statement to stdout.
7573 static int recoverSqlCb(void *pCtx
, const char *zSql
){
7574 ShellState
*pState
= (ShellState
*)pCtx
;
7575 sputf(pState
->out
, "%s;\n", zSql
);
7580 ** This function is called to recover data from the database. A script
7581 ** to construct a new database containing all recovered data is output
7582 ** on stream pState->out.
7584 static int recoverDatabaseCmd(ShellState
*pState
, int nArg
, char **azArg
){
7586 const char *zRecoveryDb
= ""; /* Name of "recovery" database. Debug only */
7587 const char *zLAF
= "lost_and_found";
7588 int bFreelist
= 1; /* 0 if --ignore-freelist is specified */
7589 int bRowids
= 1; /* 0 if --no-rowids */
7590 sqlite3_recover
*p
= 0;
7593 for(i
=1; i
<nArg
; i
++){
7596 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7598 if( n
<=17 && memcmp("-ignore-freelist", z
, n
)==0 ){
7601 if( n
<=12 && memcmp("-recovery-db", z
, n
)==0 && i
<(nArg
-1) ){
7602 /* This option determines the name of the ATTACH-ed database used
7603 ** internally by the recovery extension. The default is "" which
7604 ** means to use a temporary database that is automatically deleted
7605 ** when closed. This option is undocumented and might disappear at
7608 zRecoveryDb
= azArg
[i
];
7610 if( n
<=15 && memcmp("-lost-and-found", z
, n
)==0 && i
<(nArg
-1) ){
7614 if( n
<=10 && memcmp("-no-rowids", z
, n
)==0 ){
7618 eputf("unexpected option: %s\n", azArg
[i
]);
7619 showHelp(pState
->out
, azArg
[0]);
7624 p
= sqlite3_recover_init_sql(
7625 pState
->db
, "main", recoverSqlCb
, (void*)pState
7628 sqlite3_recover_config(p
, 789, (void*)zRecoveryDb
); /* Debug use only */
7629 sqlite3_recover_config(p
, SQLITE_RECOVER_LOST_AND_FOUND
, (void*)zLAF
);
7630 sqlite3_recover_config(p
, SQLITE_RECOVER_ROWIDS
, (void*)&bRowids
);
7631 sqlite3_recover_config(p
, SQLITE_RECOVER_FREELIST_CORRUPT
,(void*)&bFreelist
);
7633 sqlite3_recover_run(p
);
7634 if( sqlite3_recover_errcode(p
)!=SQLITE_OK
){
7635 const char *zErr
= sqlite3_recover_errmsg(p
);
7636 int errCode
= sqlite3_recover_errcode(p
);
7637 eputf("sql error: %s (%d)\n", zErr
, errCode
);
7639 rc
= sqlite3_recover_finish(p
);
7642 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7646 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7647 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7648 * close db and set it to 0, and return the columns spec, to later
7649 * be sqlite3_free()'ed by the caller.
7650 * The return is 0 when either:
7651 * (a) The db was not initialized and zCol==0 (There are no columns.)
7652 * (b) zCol!=0 (Column was added, db initialized as needed.)
7653 * The 3rd argument, pRenamed, references an out parameter. If the
7654 * pointer is non-zero, its referent will be set to a summary of renames
7655 * done if renaming was necessary, or set to 0 if none was done. The out
7656 * string (if any) must be sqlite3_free()'ed by the caller.
7659 #define rc_err_oom_die(rc) \
7660 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7661 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7662 eputf("E:%d\n",rc), assert(0)
7664 static void rc_err_oom_die(int rc
){
7665 if( rc
==SQLITE_NOMEM
) shell_check_oom(0);
7666 assert(rc
==SQLITE_OK
||rc
==SQLITE_DONE
);
7670 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7671 static char zCOL_DB
[] = SHELL_STRINGIFY(SHELL_COLFIX_DB
);
7672 #else /* Otherwise, memory is faster/better for the transient DB. */
7673 static const char *zCOL_DB
= ":memory:";
7676 /* Define character (as C string) to separate generated column ordinal
7677 * from protected part of incoming column names. This defaults to "_"
7678 * so that incoming column identifiers that did not need not be quoted
7679 * remain usable without being quoted. It must be one character.
7681 #ifndef SHELL_AUTOCOLUMN_SEP
7682 # define AUTOCOLUMN_SEP "_"
7684 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7687 static char *zAutoColumn(const char *zColNew
, sqlite3
**pDb
, char **pzRenamed
){
7688 /* Queries and D{D,M}L used here */
7689 static const char * const zTabMake
= "\
7690 CREATE TABLE ColNames(\
7691 cpos INTEGER PRIMARY KEY,\
7692 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7693 CREATE VIEW RepeatedNames AS \
7694 SELECT DISTINCT t.name FROM ColNames t \
7695 WHERE t.name COLLATE NOCASE IN (\
7696 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7699 static const char * const zTabFill
= "\
7700 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7701 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7703 static const char * const zHasDupes
= "\
7704 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7705 <count(name) FROM ColNames\
7707 #ifdef SHELL_COLUMN_RENAME_CLEAN
7708 static const char * const zDedoctor
= "\
7709 UPDATE ColNames SET chop=iif(\
7710 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7711 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP
"'),\
7712 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP
"0123456789')),\
7717 static const char * const zSetReps
= "\
7718 UPDATE ColNames AS t SET reps=\
7719 (SELECT count(*) FROM ColNames d \
7720 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7724 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7725 static const char * const zColDigits
= "\
7726 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7729 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7730 static const char * const zColDigits
= "\
7731 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7732 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7733 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7736 static const char * const zRenameRank
=
7737 #ifdef SHELL_COLUMN_RENAME_CLEAN
7738 "UPDATE ColNames AS t SET suff="
7739 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP
"', $1, cpos), '')"
7740 #else /* ...RENAME_MINIMAL_ONE_PASS */
7741 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7744 " SELECT nlz+1 AS nlz FROM Lzn"
7747 " FROM ColNames t, ColNames o"
7749 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7750 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7751 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7755 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7756 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7757 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7761 " AND o.cpos<>t.cpos"
7764 ") UPDATE Colnames AS t SET"
7765 " chop = 0," /* No chopping, never touch incoming names. */
7766 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7767 " printf('"AUTOCOLUMN_SEP
"%s', substring("
7768 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7773 static const char * const zCollectVar
= "\
7778 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7781 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7782 FROM ColNames ORDER BY cpos\
7784 static const char * const zRenamesDone
=
7785 "SELECT group_concat("
7786 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7788 "FROM ColNames WHERE suff<>'' OR chop!=0"
7791 sqlite3_stmt
*pStmt
= 0;
7794 /* Add initial or additional column. Init db if necessary. */
7796 if( SQLITE_OK
!=sqlite3_open(zCOL_DB
, pDb
) ) return 0;
7797 #ifdef SHELL_COLFIX_DB
7799 sqlite3_exec(*pDb
,"drop table if exists ColNames;"
7800 "drop view if exists RepeatedNames;",0,0,0);
7802 #undef SHELL_COLFIX_DB
7803 rc
= sqlite3_exec(*pDb
, zTabMake
, 0, 0, 0);
7807 rc
= sqlite3_prepare_v2(*pDb
, zTabFill
, -1, &pStmt
, 0);
7809 rc
= sqlite3_bind_text(pStmt
, 1, zColNew
, -1, 0);
7811 rc
= sqlite3_step(pStmt
);
7813 sqlite3_finalize(pStmt
);
7815 }else if( *pDb
==0 ){
7818 /* Formulate the columns spec, close the DB, zero *pDb. */
7819 char *zColsSpec
= 0;
7820 int hasDupes
= db_int(*pDb
, zHasDupes
);
7821 int nDigits
= (hasDupes
)? db_int(*pDb
, zColDigits
) : 0;
7823 #ifdef SHELL_COLUMN_RENAME_CLEAN
7824 rc
= sqlite3_exec(*pDb
, zDedoctor
, 0, 0, 0);
7827 rc
= sqlite3_exec(*pDb
, zSetReps
, 0, 0, 0);
7829 rc
= sqlite3_prepare_v2(*pDb
, zRenameRank
, -1, &pStmt
, 0);
7831 sqlite3_bind_int(pStmt
, 1, nDigits
);
7832 rc
= sqlite3_step(pStmt
);
7833 sqlite3_finalize(pStmt
);
7834 if( rc
!=SQLITE_DONE
) rc_err_oom_die(SQLITE_NOMEM
);
7836 assert(db_int(*pDb
, zHasDupes
)==0); /* Consider: remove this */
7837 rc
= sqlite3_prepare_v2(*pDb
, zCollectVar
, -1, &pStmt
, 0);
7839 rc
= sqlite3_step(pStmt
);
7840 if( rc
==SQLITE_ROW
){
7841 zColsSpec
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7846 if( !hasDupes
) *pzRenamed
= 0;
7848 sqlite3_finalize(pStmt
);
7849 if( SQLITE_OK
==sqlite3_prepare_v2(*pDb
, zRenamesDone
, -1, &pStmt
, 0)
7850 && SQLITE_ROW
==sqlite3_step(pStmt
) ){
7851 *pzRenamed
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7856 sqlite3_finalize(pStmt
);
7857 sqlite3_close(*pDb
);
7864 ** Check if the sqlite_schema table contains one or more virtual tables. If
7865 ** parameter zLike is not NULL, then it is an SQL expression that the
7866 ** sqlite_schema row must also match. If one or more such rows are found,
7867 ** print the following warning to the output:
7869 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
7871 static int outputDumpWarning(ShellState
*p
, const char *zLike
){
7873 sqlite3_stmt
*pStmt
= 0;
7874 shellPreparePrintf(p
->db
, &rc
, &pStmt
,
7875 "SELECT 1 FROM sqlite_schema o WHERE "
7876 "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike
? zLike
: "true"
7878 if( rc
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
7879 oputz("/* WARNING: "
7880 "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
7883 shellFinalize(&rc
, pStmt
);
7888 ** If an input line begins with "." then invoke this routine to
7889 ** process that line.
7891 ** Return 1 on error, 2 to exit, and 0 otherwise.
7893 static int do_meta_command(char *zLine
, ShellState
*p
){
7900 #ifndef SQLITE_OMIT_VIRTUALTABLE
7901 if( p
->expert
.pExpert
){
7902 expertFinish(p
, 1, 0);
7906 /* Parse the input line into tokens.
7908 while( zLine
[h
] && nArg
<ArraySize(azArg
)-1 ){
7909 while( IsSpace(zLine
[h
]) ){ h
++; }
7910 if( zLine
[h
]==0 ) break;
7911 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
7912 int delim
= zLine
[h
++];
7913 azArg
[nArg
++] = &zLine
[h
];
7914 while( zLine
[h
] && zLine
[h
]!=delim
){
7915 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
7918 if( zLine
[h
]==delim
){
7921 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
7923 azArg
[nArg
++] = &zLine
[h
];
7924 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
7925 if( zLine
[h
] ) zLine
[h
++] = 0;
7930 /* Process the input line.
7932 if( nArg
==0 ) return 0; /* no tokens, no error */
7933 n
= strlen30(azArg
[0]);
7937 #ifndef SQLITE_OMIT_AUTHORIZATION
7938 if( c
=='a' && cli_strncmp(azArg
[0], "auth", n
)==0 ){
7940 eputz("Usage: .auth ON|OFF\n");
7942 goto meta_command_exit
;
7945 if( booleanValue(azArg
[1]) ){
7946 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
7947 }else if( p
->bSafeModePersist
){
7948 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
7950 sqlite3_set_authorizer(p
->db
, 0, 0);
7955 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7956 && !defined(SQLITE_SHELL_FIDDLE)
7957 if( c
=='a' && cli_strncmp(azArg
[0], "archive", n
)==0 ){
7959 failIfSafeMode(p
, "cannot run .archive in safe mode");
7960 rc
= arDotCommand(p
, 0, azArg
, nArg
);
7964 #ifndef SQLITE_SHELL_FIDDLE
7965 if( (c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "backup", n
)==0)
7966 || (c
=='s' && n
>=3 && cli_strncmp(azArg
[0], "save", n
)==0)
7968 const char *zDestFile
= 0;
7969 const char *zDb
= 0;
7971 sqlite3_backup
*pBackup
;
7974 const char *zVfs
= 0;
7975 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
7976 for(j
=1; j
<nArg
; j
++){
7977 const char *z
= azArg
[j
];
7979 if( z
[1]=='-' ) z
++;
7980 if( cli_strcmp(z
, "-append")==0 ){
7983 if( cli_strcmp(z
, "-async")==0 ){
7987 eputf("unknown option: %s\n", azArg
[j
]);
7990 }else if( zDestFile
==0 ){
7991 zDestFile
= azArg
[j
];
7994 zDestFile
= azArg
[j
];
7996 eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8001 eputz("missing FILENAME argument on .backup\n");
8004 if( zDb
==0 ) zDb
= "main";
8005 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
8006 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
8007 if( rc
!=SQLITE_OK
){
8008 eputf("Error: cannot open \"%s\"\n", zDestFile
);
8013 sqlite3_exec(pDest
, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8017 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
8019 eputf("Error: %s\n", sqlite3_errmsg(pDest
));
8023 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
8024 sqlite3_backup_finish(pBackup
);
8025 if( rc
==SQLITE_DONE
){
8028 eputf("Error: %s\n", sqlite3_errmsg(pDest
));
8033 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8035 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "bail", n
)==0 ){
8037 bail_on_error
= booleanValue(azArg
[1]);
8039 eputz("Usage: .bail on|off\n");
8044 /* Undocumented. Legacy only. See "crnl" below */
8045 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "binary", n
)==0 ){
8047 if( booleanValue(azArg
[1]) ){
8048 setBinaryMode(p
->out
, 1);
8050 setTextMode(p
->out
, 1);
8053 eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
8054 "Usage: .binary on|off\n");
8059 /* The undocumented ".breakpoint" command causes a call to the no-op
8060 ** routine named test_breakpoint().
8062 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "breakpoint", n
)==0 ){
8066 #ifndef SQLITE_SHELL_FIDDLE
8067 if( c
=='c' && cli_strcmp(azArg
[0],"cd")==0 ){
8068 failIfSafeMode(p
, "cannot run .cd in safe mode");
8070 #if defined(_WIN32) || defined(WIN32)
8071 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
8072 rc
= !SetCurrentDirectoryW(z
);
8075 rc
= chdir(azArg
[1]);
8078 eputf("Cannot change to directory \"%s\"\n", azArg
[1]);
8082 eputz("Usage: .cd DIRECTORY\n");
8086 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8088 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "changes", n
)==0 ){
8090 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
8092 eputz("Usage: .changes on|off\n");
8097 #ifndef SQLITE_SHELL_FIDDLE
8098 /* Cancel output redirection, if it is currently set (by .testcase)
8099 ** Then read the content of the testcase-out.txt file and compare against
8100 ** azArg[1]. If there are differences, report an error and exit.
8102 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "check", n
)==0 ){
8106 eputz("Usage: .check GLOB-PATTERN\n");
8108 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
8110 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
8111 eputf("testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8112 p
->zTestcase
, azArg
[1], zRes
);
8115 oputf("testcase-%s ok\n", p
->zTestcase
);
8120 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8122 #ifndef SQLITE_SHELL_FIDDLE
8123 if( c
=='c' && cli_strncmp(azArg
[0], "clone", n
)==0 ){
8124 failIfSafeMode(p
, "cannot run .clone in safe mode");
8126 tryToClone(p
, azArg
[1]);
8128 eputz("Usage: .clone FILENAME\n");
8132 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8134 if( c
=='c' && cli_strncmp(azArg
[0], "connection", n
)==0 ){
8136 /* List available connections */
8138 for(i
=0; i
<ArraySize(p
->aAuxDb
); i
++){
8139 const char *zFile
= p
->aAuxDb
[i
].zDbFilename
;
8140 if( p
->aAuxDb
[i
].db
==0 && p
->pAuxDb
!=&p
->aAuxDb
[i
] ){
8141 zFile
= "(not open)";
8142 }else if( zFile
==0 ){
8144 }else if( zFile
[0]==0 ){
8145 zFile
= "(temporary-file)";
8147 if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
8148 sputf(stdout
, "ACTIVE %d: %s\n", i
, zFile
);
8149 }else if( p
->aAuxDb
[i
].db
!=0 ){
8150 sputf(stdout
, " %d: %s\n", i
, zFile
);
8153 }else if( nArg
==2 && IsDigit(azArg
[1][0]) && azArg
[1][1]==0 ){
8154 int i
= azArg
[1][0] - '0';
8155 if( p
->pAuxDb
!= &p
->aAuxDb
[i
] && i
>=0 && i
<ArraySize(p
->aAuxDb
) ){
8156 p
->pAuxDb
->db
= p
->db
;
8157 p
->pAuxDb
= &p
->aAuxDb
[i
];
8158 globalDb
= p
->db
= p
->pAuxDb
->db
;
8161 }else if( nArg
==3 && cli_strcmp(azArg
[1], "close")==0
8162 && IsDigit(azArg
[2][0]) && azArg
[2][1]==0 ){
8163 int i
= azArg
[2][0] - '0';
8164 if( i
<0 || i
>=ArraySize(p
->aAuxDb
) ){
8166 }else if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
8167 eputz("cannot close the active database connection\n");
8169 }else if( p
->aAuxDb
[i
].db
){
8170 session_close_all(p
, i
);
8171 close_db(p
->aAuxDb
[i
].db
);
8172 p
->aAuxDb
[i
].db
= 0;
8175 eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
8180 if( c
=='c' && n
==4 && cli_strncmp(azArg
[0], "crnl", n
)==0 ){
8182 if( booleanValue(azArg
[1]) ){
8183 setTextMode(p
->out
, 1);
8185 setBinaryMode(p
->out
, 1);
8188 #if !defined(_WIN32) && !defined(WIN32)
8189 eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
8191 eputz("Usage: .crnl on|off\n");
8196 if( c
=='d' && n
>1 && cli_strncmp(azArg
[0], "databases", n
)==0 ){
8199 sqlite3_stmt
*pStmt
;
8202 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
8204 eputf("Error: %s\n", sqlite3_errmsg(p
->db
));
8207 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
8208 const char *zSchema
= (const char *)sqlite3_column_text(pStmt
,1);
8209 const char *zFile
= (const char*)sqlite3_column_text(pStmt
,2);
8210 if( zSchema
==0 || zFile
==0 ) continue;
8211 azName
= sqlite3_realloc(azName
, (nName
+1)*2*sizeof(char*));
8212 shell_check_oom(azName
);
8213 azName
[nName
*2] = strdup(zSchema
);
8214 azName
[nName
*2+1] = strdup(zFile
);
8218 sqlite3_finalize(pStmt
);
8219 for(i
=0; i
<nName
; i
++){
8220 int eTxn
= sqlite3_txn_state(p
->db
, azName
[i
*2]);
8221 int bRdonly
= sqlite3_db_readonly(p
->db
, azName
[i
*2]);
8222 const char *z
= azName
[i
*2+1];
8223 oputf("%s: %s %s%s\n",
8224 azName
[i
*2], z
&& z
[0] ? z
: "\"\"", bRdonly
? "r/o" : "r/w",
8225 eTxn
==SQLITE_TXN_NONE
? "" :
8226 eTxn
==SQLITE_TXN_READ
? " read-txn" : " write-txn");
8228 free(azName
[i
*2+1]);
8230 sqlite3_free(azName
);
8233 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbconfig", n
)==0 ){
8234 static const struct DbConfigChoices
{
8238 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
8239 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
8240 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
8241 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
8242 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
8243 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
8244 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
8245 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
8246 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
8247 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
8248 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
8249 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
8250 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
8251 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER
},
8252 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS
},
8253 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
8254 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
8255 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
8259 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
8260 if( nArg
>1 && cli_strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
8262 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
8264 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
8265 oputf("%19s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
8268 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
8269 eputf("Error: unknown dbconfig \"%s\"\n", azArg
[1]);
8270 eputz("Enter \".dbconfig\" with no arguments for a list\n");
8274 #if SQLITE_SHELL_HAVE_RECOVER
8275 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbinfo", n
)==0 ){
8276 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
8279 if( c
=='r' && cli_strncmp(azArg
[0], "recover", n
)==0 ){
8281 rc
= recoverDatabaseCmd(p
, nArg
, azArg
);
8283 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8285 if( c
=='d' && cli_strncmp(azArg
[0], "dump", n
)==0 ){
8289 int savedShowHeader
= p
->showHeader
;
8290 int savedShellFlags
= p
->shellFlgs
;
8292 SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
8293 |SHFLG_DumpDataOnly
|SHFLG_DumpNoSys
);
8294 for(i
=1; i
<nArg
; i
++){
8295 if( azArg
[i
][0]=='-' ){
8296 const char *z
= azArg
[i
]+1;
8297 if( z
[0]=='-' ) z
++;
8298 if( cli_strcmp(z
,"preserve-rowids")==0 ){
8299 #ifdef SQLITE_OMIT_VIRTUALTABLE
8300 eputz("The --preserve-rowids option is not compatible"
8301 " with SQLITE_OMIT_VIRTUALTABLE\n");
8303 sqlite3_free(zLike
);
8304 goto meta_command_exit
;
8306 ShellSetFlag(p
, SHFLG_PreserveRowid
);
8309 if( cli_strcmp(z
,"newlines")==0 ){
8310 ShellSetFlag(p
, SHFLG_Newlines
);
8312 if( cli_strcmp(z
,"data-only")==0 ){
8313 ShellSetFlag(p
, SHFLG_DumpDataOnly
);
8315 if( cli_strcmp(z
,"nosys")==0 ){
8316 ShellSetFlag(p
, SHFLG_DumpNoSys
);
8319 eputf("Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
8321 sqlite3_free(zLike
);
8322 goto meta_command_exit
;
8325 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8326 ** only dump data for tables for which either the table name matches
8327 ** the LIKE pattern, or the table appears to be a shadow table of
8328 ** a virtual table for which the name matches the LIKE pattern.
8330 char *zExpr
= sqlite3_mprintf(
8331 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8332 " SELECT 1 FROM sqlite_schema WHERE "
8333 " name LIKE %Q ESCAPE '\\' AND"
8334 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8335 " substr(o.name, 1, length(name)+1) == (name||'_')"
8336 ")", azArg
[i
], azArg
[i
]
8340 zLike
= sqlite3_mprintf("%z OR %z", zLike
, zExpr
);
8349 outputDumpWarning(p
, zLike
);
8350 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8351 /* When playing back a "dump", the content might appear in an order
8352 ** which causes immediate foreign key constraints to be violated.
8353 ** So disable foreign-key constraint enforcement to prevent problems. */
8354 oputz("PRAGMA foreign_keys=OFF;\n");
8355 oputz("BEGIN TRANSACTION;\n");
8357 p
->writableSchema
= 0;
8359 /* Set writable_schema=ON since doing so forces SQLite to initialize
8360 ** as much of the schema as it can even if the sqlite_schema table is
8362 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8364 if( zLike
==0 ) zLike
= sqlite3_mprintf("true");
8365 zSql
= sqlite3_mprintf(
8366 "SELECT name, type, sql FROM sqlite_schema AS o "
8367 "WHERE (%s) AND type=='table'"
8369 " ORDER BY tbl_name='sqlite_sequence', rowid",
8372 run_schema_dump_query(p
,zSql
);
8374 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8375 zSql
= sqlite3_mprintf(
8376 "SELECT sql FROM sqlite_schema AS o "
8377 "WHERE (%s) AND sql NOT NULL"
8378 " AND type IN ('index','trigger','view')",
8381 run_table_dump_query(p
, zSql
);
8384 sqlite3_free(zLike
);
8385 if( p
->writableSchema
){
8386 oputz("PRAGMA writable_schema=OFF;\n");
8387 p
->writableSchema
= 0;
8389 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8390 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
8391 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8392 oputz(p
->nErr
?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8394 p
->showHeader
= savedShowHeader
;
8395 p
->shellFlgs
= savedShellFlags
;
8398 if( c
=='e' && cli_strncmp(azArg
[0], "echo", n
)==0 ){
8400 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
8402 eputz("Usage: .echo on|off\n");
8407 if( c
=='e' && cli_strncmp(azArg
[0], "eqp", n
)==0 ){
8410 if( p
->autoEQPtrace
){
8411 if( p
->db
) sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8412 p
->autoEQPtrace
= 0;
8414 if( cli_strcmp(azArg
[1],"full")==0 ){
8415 p
->autoEQP
= AUTOEQP_full
;
8416 }else if( cli_strcmp(azArg
[1],"trigger")==0 ){
8417 p
->autoEQP
= AUTOEQP_trigger
;
8419 }else if( cli_strcmp(azArg
[1],"test")==0 ){
8420 p
->autoEQP
= AUTOEQP_on
;
8422 }else if( cli_strcmp(azArg
[1],"trace")==0 ){
8423 p
->autoEQP
= AUTOEQP_full
;
8424 p
->autoEQPtrace
= 1;
8426 sqlite3_exec(p
->db
, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8427 sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8430 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
8433 eputz("Usage: .eqp off|on|trace|trigger|full\n");
8438 #ifndef SQLITE_SHELL_FIDDLE
8439 if( c
=='e' && cli_strncmp(azArg
[0], "exit", n
)==0 ){
8440 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
8445 /* The ".explain" command is automatic now. It is largely pointless. It
8446 ** retained purely for backwards compatibility */
8447 if( c
=='e' && cli_strncmp(azArg
[0], "explain", n
)==0 ){
8450 if( cli_strcmp(azArg
[1],"auto")==0 ){
8453 val
= booleanValue(azArg
[1]);
8456 if( val
==1 && p
->mode
!=MODE_Explain
){
8457 p
->normalMode
= p
->mode
;
8458 p
->mode
= MODE_Explain
;
8461 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8463 }else if( val
==99 ){
8464 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8469 #ifndef SQLITE_OMIT_VIRTUALTABLE
8470 if( c
=='e' && cli_strncmp(azArg
[0], "expert", n
)==0 ){
8472 eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
8477 expertDotCommand(p
, azArg
, nArg
);
8482 if( c
=='f' && cli_strncmp(azArg
[0], "filectrl", n
)==0 ){
8483 static const struct {
8484 const char *zCtrlName
; /* Name of a test-control option */
8485 int ctrlCode
; /* Integer code for that option */
8486 const char *zUsage
; /* Usage notes */
8488 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE
, "SIZE" },
8489 { "data_version", SQLITE_FCNTL_DATA_VERSION
, "" },
8490 { "has_moved", SQLITE_FCNTL_HAS_MOVED
, "" },
8491 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT
, "MILLISEC" },
8492 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL
, "[BOOLEAN]" },
8493 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8494 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE
, "[BOOLEAN]" },
8495 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES
, "[N]" },
8496 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT
, "[LIMIT]" },
8497 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME
, "" },
8498 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8502 sqlite3_int64 iRes
= 0; /* Integer result to display if rc2==1 */
8503 int isOk
= 0; /* 0: usage 1: %lld 2: no-result */
8505 const char *zCmd
= 0;
8506 const char *zSchema
= 0;
8509 zCmd
= nArg
>=2 ? azArg
[1] : "help";
8512 && (cli_strcmp(zCmd
,"--schema")==0 || cli_strcmp(zCmd
,"-schema")==0)
8516 for(i
=3; i
<nArg
; i
++) azArg
[i
-2] = azArg
[i
];
8521 /* The argument can optionally begin with "-" or "--" */
8522 if( zCmd
[0]=='-' && zCmd
[1] ){
8524 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
8527 /* --help lists all file-controls */
8528 if( cli_strcmp(zCmd
,"help")==0 ){
8529 oputz("Available file-controls:\n");
8530 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8531 oputf(" .filectrl %s %s\n", aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
8534 goto meta_command_exit
;
8537 /* convert filectrl text option to value. allow any unique prefix
8538 ** of the option name, or a numerical value. */
8539 n2
= strlen30(zCmd
);
8540 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8541 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
8543 filectrl
= aCtrl
[i
].ctrlCode
;
8546 eputf("Error: ambiguous file-control: \"%s\"\n"
8547 "Use \".filectrl --help\" for help\n", zCmd
);
8549 goto meta_command_exit
;
8554 eputf("Error: unknown file-control: %s\n"
8555 "Use \".filectrl --help\" for help\n", zCmd
);
8558 case SQLITE_FCNTL_SIZE_LIMIT
: {
8559 if( nArg
!=2 && nArg
!=3 ) break;
8560 iRes
= nArg
==3 ? integerValue(azArg
[2]) : -1;
8561 sqlite3_file_control(p
->db
, zSchema
, SQLITE_FCNTL_SIZE_LIMIT
, &iRes
);
8565 case SQLITE_FCNTL_LOCK_TIMEOUT
:
8566 case SQLITE_FCNTL_CHUNK_SIZE
: {
8568 if( nArg
!=3 ) break;
8569 x
= (int)integerValue(azArg
[2]);
8570 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8574 case SQLITE_FCNTL_PERSIST_WAL
:
8575 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
8577 if( nArg
!=2 && nArg
!=3 ) break;
8578 x
= nArg
==3 ? booleanValue(azArg
[2]) : -1;
8579 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8584 case SQLITE_FCNTL_DATA_VERSION
:
8585 case SQLITE_FCNTL_HAS_MOVED
: {
8587 if( nArg
!=2 ) break;
8588 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8593 case SQLITE_FCNTL_TEMPFILENAME
: {
8595 if( nArg
!=2 ) break;
8596 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &z
);
8604 case SQLITE_FCNTL_RESERVE_BYTES
: {
8608 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8611 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8618 if( isOk
==0 && iCtrl
>=0 ){
8619 oputf("Usage: .filectrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
8621 }else if( isOk
==1 ){
8623 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%lld", iRes
);
8624 oputf("%s\n", zBuf
);
8628 if( c
=='f' && cli_strncmp(azArg
[0], "fullschema", n
)==0 ){
8631 memcpy(&data
, p
, sizeof(data
));
8632 data
.showHeader
= 0;
8633 data
.cMode
= data
.mode
= MODE_Semi
;
8634 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
8635 data
.cMode
= data
.mode
= MODE_Pretty
;
8639 eputz("Usage: .fullschema ?--indent?\n");
8641 goto meta_command_exit
;
8644 rc
= sqlite3_exec(p
->db
,
8646 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8647 " FROM sqlite_schema UNION ALL"
8648 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8649 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8653 if( rc
==SQLITE_OK
){
8654 sqlite3_stmt
*pStmt
;
8655 rc
= sqlite3_prepare_v2(p
->db
,
8656 "SELECT rowid FROM sqlite_schema"
8657 " WHERE name GLOB 'sqlite_stat[134]'",
8659 if( rc
==SQLITE_OK
){
8660 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
8661 sqlite3_finalize(pStmt
);
8665 oputz("/* No STAT tables available */\n");
8667 oputz("ANALYZE sqlite_schema;\n");
8668 data
.cMode
= data
.mode
= MODE_Insert
;
8669 data
.zDestTable
= "sqlite_stat1";
8670 shell_exec(&data
, "SELECT * FROM sqlite_stat1", 0);
8671 data
.zDestTable
= "sqlite_stat4";
8672 shell_exec(&data
, "SELECT * FROM sqlite_stat4", 0);
8673 oputz("ANALYZE sqlite_schema;\n");
8677 if( c
=='h' && cli_strncmp(azArg
[0], "headers", n
)==0 ){
8679 p
->showHeader
= booleanValue(azArg
[1]);
8680 p
->shellFlgs
|= SHFLG_HeaderSet
;
8682 eputz("Usage: .headers on|off\n");
8687 if( c
=='h' && cli_strncmp(azArg
[0], "help", n
)==0 ){
8689 n
= showHelp(p
->out
, azArg
[1]);
8691 oputf("Nothing matches '%s'\n", azArg
[1]);
8694 showHelp(p
->out
, 0);
8698 #ifndef SQLITE_SHELL_FIDDLE
8699 if( c
=='i' && cli_strncmp(azArg
[0], "import", n
)==0 ){
8700 char *zTable
= 0; /* Insert data into this table */
8701 char *zSchema
= 0; /* Schema of zTable */
8702 char *zFile
= 0; /* Name of file to extra content from */
8703 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
8704 int nCol
; /* Number of columns in the table */
8705 i64 nByte
; /* Number of bytes in an SQL string */
8706 int i
, j
; /* Loop counters */
8707 int needCommit
; /* True to COMMIT or ROLLBACK at end */
8708 int nSep
; /* Number of bytes in p->colSeparator[] */
8709 char *zSql
= 0; /* An SQL statement */
8710 ImportCtx sCtx
; /* Reader context */
8711 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
8712 int eVerbose
= 0; /* Larger for more console output */
8713 int nSkip
= 0; /* Initial lines to skip */
8714 int useOutputMode
= 1; /* Use output mode to determine separators */
8715 char *zCreate
= 0; /* CREATE TABLE statement text */
8717 failIfSafeMode(p
, "cannot run .import in safe mode");
8718 memset(&sCtx
, 0, sizeof(sCtx
));
8719 if( p
->mode
==MODE_Ascii
){
8720 xRead
= ascii_read_one_field
;
8722 xRead
= csv_read_one_field
;
8725 for(i
=1; i
<nArg
; i
++){
8727 if( z
[0]=='-' && z
[1]=='-' ) z
++;
8731 }else if( zTable
==0 ){
8734 oputf("ERROR: extra argument: \"%s\". Usage:\n", z
);
8735 showHelp(p
->out
, "import");
8736 goto meta_command_exit
;
8738 }else if( cli_strcmp(z
,"-v")==0 ){
8740 }else if( cli_strcmp(z
,"-schema")==0 && i
<nArg
-1 ){
8741 zSchema
= azArg
[++i
];
8742 }else if( cli_strcmp(z
,"-skip")==0 && i
<nArg
-1 ){
8743 nSkip
= integerValue(azArg
[++i
]);
8744 }else if( cli_strcmp(z
,"-ascii")==0 ){
8745 sCtx
.cColSep
= SEP_Unit
[0];
8746 sCtx
.cRowSep
= SEP_Record
[0];
8747 xRead
= ascii_read_one_field
;
8749 }else if( cli_strcmp(z
,"-csv")==0 ){
8751 sCtx
.cRowSep
= '\n';
8752 xRead
= csv_read_one_field
;
8755 oputf("ERROR: unknown option: \"%s\". Usage:\n", z
);
8756 showHelp(p
->out
, "import");
8757 goto meta_command_exit
;
8761 oputf("ERROR: missing %s argument. Usage:\n",
8762 zFile
==0 ? "FILE" : "TABLE");
8763 showHelp(p
->out
, "import");
8764 goto meta_command_exit
;
8768 if( useOutputMode
){
8769 /* If neither the --csv or --ascii options are specified, then set
8770 ** the column and row separator characters from the output mode. */
8771 nSep
= strlen30(p
->colSeparator
);
8773 eputz("Error: non-null column separator required for import\n");
8774 goto meta_command_exit
;
8777 eputz("Error: multi-character column separators not allowed"
8779 goto meta_command_exit
;
8781 nSep
= strlen30(p
->rowSeparator
);
8783 eputz("Error: non-null row separator required for import\n");
8784 goto meta_command_exit
;
8786 if( nSep
==2 && p
->mode
==MODE_Csv
8787 && cli_strcmp(p
->rowSeparator
,SEP_CrLf
)==0
8789 /* When importing CSV (only), if the row separator is set to the
8790 ** default output row separator, change it to the default input
8791 ** row separator. This avoids having to maintain different input
8792 ** and output row separators. */
8793 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8794 nSep
= strlen30(p
->rowSeparator
);
8797 eputz("Error: multi-character row separators not allowed"
8799 goto meta_command_exit
;
8801 sCtx
.cColSep
= (u8
)p
->colSeparator
[0];
8802 sCtx
.cRowSep
= (u8
)p
->rowSeparator
[0];
8806 if( sCtx
.zFile
[0]=='|' ){
8807 #ifdef SQLITE_OMIT_POPEN
8808 eputz("Error: pipes are not supported in this OS\n");
8809 goto meta_command_exit
;
8811 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
8812 sCtx
.zFile
= "<pipe>";
8813 sCtx
.xCloser
= pclose
;
8816 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
8817 sCtx
.xCloser
= fclose
;
8820 eputf("Error: cannot open \"%s\"\n", zFile
);
8821 goto meta_command_exit
;
8823 if( eVerbose
>=2 || (eVerbose
>=1 && useOutputMode
) ){
8826 zSep
[0] = sCtx
.cColSep
;
8827 oputz("Column separator ");
8828 output_c_string(zSep
);
8829 oputz(", row separator ");
8830 zSep
[0] = sCtx
.cRowSep
;
8831 output_c_string(zSep
);
8834 sCtx
.z
= sqlite3_malloc64(120);
8836 import_cleanup(&sCtx
);
8837 shell_out_of_memory();
8839 /* Below, resources must be freed before exit. */
8840 while( (nSkip
--)>0 ){
8841 while( xRead(&sCtx
) && sCtx
.cTerm
==sCtx
.cColSep
){}
8843 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
8844 if( sqlite3_table_column_metadata(p
->db
, zSchema
, zTable
,0,0,0,0,0,0) ){
8845 /* Table does not exist. Create it. */
8846 sqlite3
*dbCols
= 0;
8849 zCreate
= sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
8850 zSchema
? zSchema
: "main", zTable
);
8851 while( xRead(&sCtx
) ){
8852 zAutoColumn(sCtx
.z
, &dbCols
, 0);
8853 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
8855 zColDefs
= zAutoColumn(0, &dbCols
, &zRenames
);
8857 sputf((stdin_is_interactive
&& p
->in
==stdin
)? p
->out
: stderr
,
8858 "Columns renamed during .import %s due to duplicates:\n"
8859 "%s\n", sCtx
.zFile
, zRenames
);
8860 sqlite3_free(zRenames
);
8864 eputf("%s: empty file\n", sCtx
.zFile
);
8865 import_cleanup(&sCtx
);
8867 goto meta_command_exit
;
8869 zCreate
= sqlite3_mprintf("%z%z\n", zCreate
, zColDefs
);
8871 import_cleanup(&sCtx
);
8872 shell_out_of_memory();
8875 oputf("%s\n", zCreate
);
8877 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
8878 sqlite3_free(zCreate
);
8881 eputf("%s failed:\n%s\n", zCreate
, sqlite3_errmsg(p
->db
));
8882 import_cleanup(&sCtx
);
8884 goto meta_command_exit
;
8887 zSql
= sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
8890 import_cleanup(&sCtx
);
8891 shell_out_of_memory();
8893 nByte
= strlen(zSql
);
8894 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8898 if (pStmt
) sqlite3_finalize(pStmt
);
8899 eputf("Error: %s\n", sqlite3_errmsg(p
->db
));
8900 import_cleanup(&sCtx
);
8902 goto meta_command_exit
;
8904 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
8905 nCol
= sqlite3_column_int(pStmt
, 0);
8909 sqlite3_finalize(pStmt
);
8911 if( nCol
==0 ) return 0; /* no columns, no error */
8912 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
8914 import_cleanup(&sCtx
);
8915 shell_out_of_memory();
8918 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\".\"%w\" VALUES(?",
8921 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
8924 for(i
=1; i
<nCol
; i
++){
8931 oputf("Insert using: %s\n", zSql
);
8933 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8937 eputf("Error: %s\n", sqlite3_errmsg(p
->db
));
8938 if (pStmt
) sqlite3_finalize(pStmt
);
8939 import_cleanup(&sCtx
);
8941 goto meta_command_exit
;
8943 needCommit
= sqlite3_get_autocommit(p
->db
);
8944 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
8946 int startLine
= sCtx
.nLine
;
8947 for(i
=0; i
<nCol
; i
++){
8948 char *z
= xRead(&sCtx
);
8950 ** Did we reach end-of-file before finding any columns?
8951 ** If so, stop instead of NULL filling the remaining columns.
8953 if( z
==0 && i
==0 ) break;
8955 ** Did we reach end-of-file OR end-of-line before finding any
8956 ** columns in ASCII mode? If so, stop instead of NULL filling
8957 ** the remaining columns.
8959 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
8961 ** For CSV mode, per RFC 4180, accept EOF in lieu of final
8962 ** record terminator but only for last field of multi-field row.
8963 ** (If there are too few fields, it's not valid CSV anyway.)
8965 if( z
==0 && (xRead
==csv_read_one_field
) && i
==nCol
-1 && i
>0 ){
8968 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
8969 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
8970 eputf("%s:%d: expected %d columns but found %d"
8971 " - filling the rest with NULL\n",
8972 sCtx
.zFile
, startLine
, nCol
, i
+1);
8974 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
8977 if( sCtx
.cTerm
==sCtx
.cColSep
){
8981 }while( sCtx
.cTerm
==sCtx
.cColSep
);
8982 eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
8983 sCtx
.zFile
, startLine
, nCol
, i
);
8986 sqlite3_step(pStmt
);
8987 rc
= sqlite3_reset(pStmt
);
8988 if( rc
!=SQLITE_OK
){
8989 eputf("%s:%d: INSERT failed: %s\n",
8990 sCtx
.zFile
, startLine
, sqlite3_errmsg(p
->db
));
8996 }while( sCtx
.cTerm
!=EOF
);
8998 import_cleanup(&sCtx
);
8999 sqlite3_finalize(pStmt
);
9000 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
9002 oputf("Added %d rows with %d errors using %d lines of input\n",
9003 sCtx
.nRow
, sCtx
.nErr
, sCtx
.nLine
-1);
9006 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9008 #ifndef SQLITE_UNTESTABLE
9009 if( c
=='i' && cli_strncmp(azArg
[0], "imposter", n
)==0 ){
9012 sqlite3_stmt
*pStmt
;
9014 int isWO
= 0; /* True if making an imposter of a WITHOUT ROWID table */
9015 int lenPK
= 0; /* Length of the PRIMARY KEY string for isWO tables */
9017 if( !ShellHasFlag(p
,SHFLG_TestingMode
) ){
9018 eputf(".%s unavailable without --unsafe-testing\n",
9021 goto meta_command_exit
;
9023 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
9024 eputz("Usage: .imposter INDEX IMPOSTER\n"
9025 " .imposter off\n");
9026 /* Also allowed, but not documented:
9028 ** .imposter TABLE IMPOSTER
9030 ** where TABLE is a WITHOUT ROWID table. In that case, the
9031 ** imposter is another WITHOUT ROWID table with the columns in
9032 ** storage order. */
9034 goto meta_command_exit
;
9038 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
9039 goto meta_command_exit
;
9041 zSql
= sqlite3_mprintf(
9042 "SELECT rootpage, 0 FROM sqlite_schema"
9043 " WHERE name='%q' AND type='index'"
9045 "SELECT rootpage, 1 FROM sqlite_schema"
9046 " WHERE name='%q' AND type='table'"
9047 " AND sql LIKE '%%without%%rowid%%'",
9050 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9052 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
9053 tnum
= sqlite3_column_int(pStmt
, 0);
9054 isWO
= sqlite3_column_int(pStmt
, 1);
9056 sqlite3_finalize(pStmt
);
9057 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
9058 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9061 while( rc
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9063 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
9066 if( sqlite3_column_int(pStmt
,1)==-1 ){
9069 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
9073 if( isWO
&& lenPK
==0 && sqlite3_column_int(pStmt
,5)==0 && zCollist
){
9074 lenPK
= (int)strlen(zCollist
);
9077 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
9079 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
9082 sqlite3_finalize(pStmt
);
9083 if( i
==0 || tnum
==0 ){
9084 eputf("no such index: \"%s\"\n", azArg
[1]);
9086 sqlite3_free(zCollist
);
9087 goto meta_command_exit
;
9089 if( lenPK
==0 ) lenPK
= 100000;
9090 zSql
= sqlite3_mprintf(
9091 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9092 azArg
[2], zCollist
, lenPK
, zCollist
);
9093 sqlite3_free(zCollist
);
9094 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
9095 if( rc
==SQLITE_OK
){
9096 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9097 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
9099 eputf("Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
9101 sputf(stdout
, "%s;\n", zSql
);
9102 sputf(stdout
, "WARNING: writing to an imposter table will corrupt"
9103 " the \"%s\" %s!\n", azArg
[1], isWO
? "table" : "index");
9106 eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
9111 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9113 #ifdef SQLITE_ENABLE_IOTRACE
9114 if( c
=='i' && cli_strncmp(azArg
[0], "iotrace", n
)==0 ){
9115 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
9116 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
9120 }else if( cli_strcmp(azArg
[1], "-")==0 ){
9121 sqlite3IoTrace
= iotracePrintf
;
9124 iotrace
= fopen(azArg
[1], "w");
9126 eputf("Error: cannot open \"%s\"\n", azArg
[1]);
9130 sqlite3IoTrace
= iotracePrintf
;
9136 if( c
=='l' && n
>=5 && cli_strncmp(azArg
[0], "limits", n
)==0 ){
9137 static const struct {
9138 const char *zLimitName
; /* Name of a limit */
9139 int limitCode
; /* Integer code for that limit */
9141 { "length", SQLITE_LIMIT_LENGTH
},
9142 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
9143 { "column", SQLITE_LIMIT_COLUMN
},
9144 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
9145 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
9146 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
9147 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
9148 { "attached", SQLITE_LIMIT_ATTACHED
},
9149 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
9150 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
9151 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
9152 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
9157 for(i
=0; i
<ArraySize(aLimit
); i
++){
9158 sputf(stdout
, "%20s %d\n", aLimit
[i
].zLimitName
,
9159 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
9162 eputz("Usage: .limit NAME ?NEW-VALUE?\n");
9164 goto meta_command_exit
;
9167 n2
= strlen30(azArg
[1]);
9168 for(i
=0; i
<ArraySize(aLimit
); i
++){
9169 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
9173 eputf("ambiguous limit: \"%s\"\n", azArg
[1]);
9175 goto meta_command_exit
;
9180 eputf("unknown limit: \"%s\"\n"
9181 "enter \".limits\" with no arguments for a list.\n",
9184 goto meta_command_exit
;
9187 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
9188 (int)integerValue(azArg
[2]));
9190 sputf(stdout
, "%20s %d\n", aLimit
[iLimit
].zLimitName
,
9191 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
9195 if( c
=='l' && n
>2 && cli_strncmp(azArg
[0], "lint", n
)==0 ){
9197 lintDotCommand(p
, azArg
, nArg
);
9200 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9201 if( c
=='l' && cli_strncmp(azArg
[0], "load", n
)==0 ){
9202 const char *zFile
, *zProc
;
9204 failIfSafeMode(p
, "cannot run .load in safe mode");
9205 if( nArg
<2 || azArg
[1][0]==0 ){
9206 /* Must have a non-empty FILE. (Will not load self.) */
9207 eputz("Usage: .load FILE ?ENTRYPOINT?\n");
9209 goto meta_command_exit
;
9212 zProc
= nArg
>=3 ? azArg
[2] : 0;
9214 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
9215 if( rc
!=SQLITE_OK
){
9216 eputf("Error: %s\n", zErrMsg
);
9217 sqlite3_free(zErrMsg
);
9223 if( c
=='l' && cli_strncmp(azArg
[0], "log", n
)==0 ){
9225 eputz("Usage: .log FILENAME\n");
9228 const char *zFile
= azArg
[1];
9230 && cli_strcmp(zFile
,"on")!=0
9231 && cli_strcmp(zFile
,"off")!=0
9233 sputz(stdout
, "cannot set .log to anything other"
9234 " than \"on\" or \"off\"\n");
9237 output_file_close(p
->pLog
);
9238 if( cli_strcmp(zFile
,"on")==0 ) zFile
= "stdout";
9239 p
->pLog
= output_file_open(zFile
, 0);
9243 if( c
=='m' && cli_strncmp(azArg
[0], "mode", n
)==0 ){
9244 const char *zMode
= 0;
9245 const char *zTabname
= 0;
9247 ColModeOpts cmOpts
= ColModeOpts_default
;
9248 for(i
=1; i
<nArg
; i
++){
9249 const char *z
= azArg
[i
];
9250 if( optionMatch(z
,"wrap") && i
+1<nArg
){
9251 cmOpts
.iWrap
= integerValue(azArg
[++i
]);
9252 }else if( optionMatch(z
,"ww") ){
9253 cmOpts
.bWordWrap
= 1;
9254 }else if( optionMatch(z
,"wordwrap") && i
+1<nArg
){
9255 cmOpts
.bWordWrap
= (u8
)booleanValue(azArg
[++i
]);
9256 }else if( optionMatch(z
,"quote") ){
9258 }else if( optionMatch(z
,"noquote") ){
9260 }else if( zMode
==0 ){
9262 /* Apply defaults for qbox pseudo-mode. If that
9263 * overwrites already-set values, user was informed of this.
9265 if( cli_strcmp(z
, "qbox")==0 ){
9266 ColModeOpts cmo
= ColModeOpts_default_qbox
;
9270 }else if( zTabname
==0 ){
9272 }else if( z
[0]=='-' ){
9273 eputf("unknown option: %s\n", z
);
9277 " --wordwrap on/off\n"
9281 goto meta_command_exit
;
9283 eputf("extra argument: \"%s\"\n", z
);
9285 goto meta_command_exit
;
9289 if( p
->mode
==MODE_Column
9290 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
9292 oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9293 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
9294 p
->cmOpts
.bWordWrap
? "on" : "off",
9295 p
->cmOpts
.bQuote
? "" : "no");
9297 oputf("current output mode: %s\n", modeDescr
[p
->mode
]);
9299 zMode
= modeDescr
[p
->mode
];
9301 n2
= strlen30(zMode
);
9302 if( cli_strncmp(zMode
,"lines",n2
)==0 ){
9303 p
->mode
= MODE_Line
;
9304 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9305 }else if( cli_strncmp(zMode
,"columns",n2
)==0 ){
9306 p
->mode
= MODE_Column
;
9307 if( (p
->shellFlgs
& SHFLG_HeaderSet
)==0 ){
9310 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9312 }else if( cli_strncmp(zMode
,"list",n2
)==0 ){
9313 p
->mode
= MODE_List
;
9314 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
9315 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9316 }else if( cli_strncmp(zMode
,"html",n2
)==0 ){
9317 p
->mode
= MODE_Html
;
9318 }else if( cli_strncmp(zMode
,"tcl",n2
)==0 ){
9320 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
9321 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9322 }else if( cli_strncmp(zMode
,"csv",n2
)==0 ){
9324 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9325 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9326 }else if( cli_strncmp(zMode
,"tabs",n2
)==0 ){
9327 p
->mode
= MODE_List
;
9328 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
9329 }else if( cli_strncmp(zMode
,"insert",n2
)==0 ){
9330 p
->mode
= MODE_Insert
;
9331 set_table_name(p
, zTabname
? zTabname
: "table");
9332 }else if( cli_strncmp(zMode
,"quote",n2
)==0 ){
9333 p
->mode
= MODE_Quote
;
9334 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9335 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9336 }else if( cli_strncmp(zMode
,"ascii",n2
)==0 ){
9337 p
->mode
= MODE_Ascii
;
9338 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
9339 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
9340 }else if( cli_strncmp(zMode
,"markdown",n2
)==0 ){
9341 p
->mode
= MODE_Markdown
;
9343 }else if( cli_strncmp(zMode
,"table",n2
)==0 ){
9344 p
->mode
= MODE_Table
;
9346 }else if( cli_strncmp(zMode
,"box",n2
)==0 ){
9349 }else if( cli_strncmp(zMode
,"count",n2
)==0 ){
9350 p
->mode
= MODE_Count
;
9351 }else if( cli_strncmp(zMode
,"off",n2
)==0 ){
9353 }else if( cli_strncmp(zMode
,"json",n2
)==0 ){
9354 p
->mode
= MODE_Json
;
9356 eputz("Error: mode should be one of: "
9357 "ascii box column csv html insert json line list markdown "
9358 "qbox quote table tabs tcl\n");
9364 #ifndef SQLITE_SHELL_FIDDLE
9365 if( c
=='n' && cli_strcmp(azArg
[0], "nonce")==0 ){
9367 eputz("Usage: .nonce NONCE\n");
9369 }else if( p
->zNonce
==0 || cli_strcmp(azArg
[1],p
->zNonce
)!=0 ){
9370 eputf("line %d: incorrect nonce: \"%s\"\n",
9371 p
->lineno
, azArg
[1]);
9375 return 0; /* Return immediately to bypass the safe mode reset
9376 ** at the end of this procedure */
9379 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9381 if( c
=='n' && cli_strncmp(azArg
[0], "nullvalue", n
)==0 ){
9383 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
9384 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
9386 eputz("Usage: .nullvalue STRING\n");
9391 if( c
=='o' && cli_strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
9392 const char *zFN
= 0; /* Pointer to constant filename */
9393 char *zNewFilename
= 0; /* Name of the database file to open */
9394 int iName
= 1; /* Index in azArg[] of the filename */
9395 int newFlag
= 0; /* True to delete file before opening */
9396 int openMode
= SHELL_OPEN_UNSPEC
;
9398 /* Check for command-line arguments */
9399 for(iName
=1; iName
<nArg
; iName
++){
9400 const char *z
= azArg
[iName
];
9401 #ifndef SQLITE_SHELL_FIDDLE
9402 if( optionMatch(z
,"new") ){
9404 #ifdef SQLITE_HAVE_ZLIB
9405 }else if( optionMatch(z
, "zip") ){
9406 openMode
= SHELL_OPEN_ZIPFILE
;
9408 }else if( optionMatch(z
, "append") ){
9409 openMode
= SHELL_OPEN_APPENDVFS
;
9410 }else if( optionMatch(z
, "readonly") ){
9411 openMode
= SHELL_OPEN_READONLY
;
9412 }else if( optionMatch(z
, "nofollow") ){
9413 p
->openFlags
|= SQLITE_OPEN_NOFOLLOW
;
9414 #ifndef SQLITE_OMIT_DESERIALIZE
9415 }else if( optionMatch(z
, "deserialize") ){
9416 openMode
= SHELL_OPEN_DESERIALIZE
;
9417 }else if( optionMatch(z
, "hexdb") ){
9418 openMode
= SHELL_OPEN_HEXDB
;
9419 }else if( optionMatch(z
, "maxsize") && iName
+1<nArg
){
9420 p
->szMax
= integerValue(azArg
[++iName
]);
9421 #endif /* SQLITE_OMIT_DESERIALIZE */
9423 #endif /* !SQLITE_SHELL_FIDDLE */
9425 eputf("unknown option: %s\n", z
);
9427 goto meta_command_exit
;
9429 eputf("extra argument: \"%s\"\n", z
);
9431 goto meta_command_exit
;
9437 /* Close the existing database */
9438 session_close_all(p
, -1);
9441 p
->pAuxDb
->zDbFilename
= 0;
9442 sqlite3_free(p
->pAuxDb
->zFreeOnClose
);
9443 p
->pAuxDb
->zFreeOnClose
= 0;
9444 p
->openMode
= openMode
;
9448 /* If a filename is specified, try to open it first */
9449 if( zFN
|| p
->openMode
==SHELL_OPEN_HEXDB
){
9450 if( newFlag
&& zFN
&& !p
->bSafeMode
) shellDeleteFile(zFN
);
9451 #ifndef SQLITE_SHELL_FIDDLE
9453 && p
->openMode
!=SHELL_OPEN_HEXDB
9455 && cli_strcmp(zFN
,":memory:")!=0
9457 failIfSafeMode(p
, "cannot open disk-based database files in safe mode");
9460 /* WASM mode has its own sandboxed pseudo-filesystem. */
9463 zNewFilename
= sqlite3_mprintf("%s", zFN
);
9464 shell_check_oom(zNewFilename
);
9468 p
->pAuxDb
->zDbFilename
= zNewFilename
;
9469 open_db(p
, OPEN_DB_KEEPALIVE
);
9471 eputf("Error: cannot open '%s'\n", zNewFilename
);
9472 sqlite3_free(zNewFilename
);
9474 p
->pAuxDb
->zFreeOnClose
= zNewFilename
;
9478 /* As a fall-back open a TEMP database */
9479 p
->pAuxDb
->zDbFilename
= 0;
9484 #ifndef SQLITE_SHELL_FIDDLE
9486 && (cli_strncmp(azArg
[0], "output", n
)==0
9487 || cli_strncmp(azArg
[0], "once", n
)==0))
9488 || (c
=='e' && n
==5 && cli_strcmp(azArg
[0],"excel")==0)
9494 int bOnce
= 0; /* 0: .output, 1: .once, 2: .excel */
9495 static const char *zBomUtf8
= "\xef\xbb\xbf";
9496 const char *zBom
= 0;
9498 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
9502 }else if( cli_strncmp(azArg
[0],"once",n
)==0 ){
9505 for(i
=1; i
<nArg
; i
++){
9508 if( z
[1]=='-' ) z
++;
9509 if( cli_strcmp(z
,"-bom")==0 ){
9511 }else if( c
!='e' && cli_strcmp(z
,"-x")==0 ){
9512 eMode
= 'x'; /* spreadsheet */
9513 }else if( c
!='e' && cli_strcmp(z
,"-e")==0 ){
9514 eMode
= 'e'; /* text editor */
9516 oputf("ERROR: unknown option: \"%s\". Usage:\n", azArg
[i
]);
9517 showHelp(p
->out
, azArg
[0]);
9519 goto meta_command_exit
;
9521 }else if( zFile
==0 && eMode
!='e' && eMode
!='x' ){
9522 zFile
= sqlite3_mprintf("%s", z
);
9523 if( zFile
&& zFile
[0]=='|' ){
9524 while( i
+1<nArg
) zFile
= sqlite3_mprintf("%z %s", zFile
, azArg
[++i
]);
9528 oputf("ERROR: extra parameter: \"%s\". Usage:\n", azArg
[i
]);
9529 showHelp(p
->out
, azArg
[0]);
9531 sqlite3_free(zFile
);
9532 goto meta_command_exit
;
9536 zFile
= sqlite3_mprintf("stdout");
9544 #ifndef SQLITE_NOHAVE_SYSTEM
9545 if( eMode
=='e' || eMode
=='x' ){
9549 /* spreadsheet mode. Output as CSV. */
9550 newTempFile(p
, "csv");
9551 ShellClearFlag(p
, SHFLG_Echo
);
9553 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9554 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9556 /* text editor mode */
9557 newTempFile(p
, "txt");
9560 sqlite3_free(zFile
);
9561 zFile
= sqlite3_mprintf("%s", p
->zTempFile
);
9563 #endif /* SQLITE_NOHAVE_SYSTEM */
9564 shell_check_oom(zFile
);
9565 if( zFile
[0]=='|' ){
9566 #ifdef SQLITE_OMIT_POPEN
9567 eputz("Error: pipes are not supported in this OS\n");
9569 output_redir(p
, stdout
);
9571 FILE *pfPipe
= popen(zFile
+ 1, "w");
9573 eputf("Error: cannot open pipe \"%s\"\n", zFile
+ 1);
9576 output_redir(p
, pfPipe
);
9577 if( zBom
) oputz(zBom
);
9578 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9582 FILE *pfFile
= output_file_open(zFile
, bTxtMode
);
9584 if( cli_strcmp(zFile
,"off")!=0 ){
9585 eputf("Error: cannot write to \"%s\"\n", zFile
);
9589 output_redir(p
, pfFile
);
9590 if( zBom
) oputz(zBom
);
9591 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9594 sqlite3_free(zFile
);
9596 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9598 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "parameter", n
)==0 ){
9600 if( nArg
<=1 ) goto parameter_syntax_error
;
9603 ** Clear all bind parameters by dropping the TEMP table that holds them.
9605 if( nArg
==2 && cli_strcmp(azArg
[1],"clear")==0 ){
9606 sqlite3_exec(p
->db
, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9611 ** List all bind parameters.
9613 if( nArg
==2 && cli_strcmp(azArg
[1],"list")==0 ){
9614 sqlite3_stmt
*pStmt
= 0;
9617 rx
= sqlite3_prepare_v2(p
->db
,
9618 "SELECT max(length(key)) "
9619 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9620 if( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9621 len
= sqlite3_column_int(pStmt
, 0);
9622 if( len
>40 ) len
= 40;
9624 sqlite3_finalize(pStmt
);
9627 rx
= sqlite3_prepare_v2(p
->db
,
9628 "SELECT key, quote(value) "
9629 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9630 while( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9631 oputf("%-*s %s\n", len
, sqlite3_column_text(pStmt
,0),
9632 sqlite3_column_text(pStmt
,1));
9634 sqlite3_finalize(pStmt
);
9639 ** Make sure the TEMP table used to hold bind parameters exists.
9640 ** Create it if necessary.
9642 if( nArg
==2 && cli_strcmp(azArg
[1],"init")==0 ){
9646 /* .parameter set NAME VALUE
9647 ** Set or reset a bind parameter. NAME should be the full parameter
9648 ** name exactly as it appears in the query. (ex: $abc, @def). The
9649 ** VALUE can be in either SQL literal notation, or if not it will be
9650 ** understood to be a text string.
9652 if( nArg
==4 && cli_strcmp(azArg
[1],"set")==0 ){
9655 sqlite3_stmt
*pStmt
;
9656 const char *zKey
= azArg
[2];
9657 const char *zValue
= azArg
[3];
9659 zSql
= sqlite3_mprintf(
9660 "REPLACE INTO temp.sqlite_parameters(key,value)"
9661 "VALUES(%Q,%s);", zKey
, zValue
);
9662 shell_check_oom(zSql
);
9664 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9666 if( rx
!=SQLITE_OK
){
9667 sqlite3_finalize(pStmt
);
9669 zSql
= sqlite3_mprintf(
9670 "REPLACE INTO temp.sqlite_parameters(key,value)"
9671 "VALUES(%Q,%Q);", zKey
, zValue
);
9672 shell_check_oom(zSql
);
9673 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9675 if( rx
!=SQLITE_OK
){
9676 oputf("Error: %s\n", sqlite3_errmsg(p
->db
));
9677 sqlite3_finalize(pStmt
);
9682 sqlite3_step(pStmt
);
9683 sqlite3_finalize(pStmt
);
9686 /* .parameter unset NAME
9687 ** Remove the NAME binding from the parameter binding table, if it
9690 if( nArg
==3 && cli_strcmp(azArg
[1],"unset")==0 ){
9691 char *zSql
= sqlite3_mprintf(
9692 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg
[2]);
9693 shell_check_oom(zSql
);
9694 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9697 /* If no command name matches, show a syntax error */
9698 parameter_syntax_error
:
9699 showHelp(p
->out
, "parameter");
9702 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "print", n
)==0 ){
9704 for(i
=1; i
<nArg
; i
++){
9705 if( i
>1 ) oputz(" ");
9711 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9712 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "progress", n
)==0 ){
9718 for(i
=1; i
<nArg
; i
++){
9719 const char *z
= azArg
[i
];
9722 if( z
[0]=='-' ) z
++;
9723 if( cli_strcmp(z
,"quiet")==0 || cli_strcmp(z
,"q")==0 ){
9724 p
->flgProgress
|= SHELL_PROGRESS_QUIET
;
9727 if( cli_strcmp(z
,"reset")==0 ){
9728 p
->flgProgress
|= SHELL_PROGRESS_RESET
;
9731 if( cli_strcmp(z
,"once")==0 ){
9732 p
->flgProgress
|= SHELL_PROGRESS_ONCE
;
9735 if( cli_strcmp(z
,"limit")==0 ){
9737 eputz("Error: missing argument on --limit\n");
9739 goto meta_command_exit
;
9741 p
->mxProgress
= (int)integerValue(azArg
[++i
]);
9745 eputf("Error: unknown option: \"%s\"\n", azArg
[i
]);
9747 goto meta_command_exit
;
9749 nn
= (int)integerValue(z
);
9753 sqlite3_progress_handler(p
->db
, nn
, progress_handler
, p
);
9755 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9757 if( c
=='p' && cli_strncmp(azArg
[0], "prompt", n
)==0 ){
9759 shell_strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
9762 shell_strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
9766 #ifndef SQLITE_SHELL_FIDDLE
9767 if( c
=='q' && cli_strncmp(azArg
[0], "quit", n
)==0 ){
9772 #ifndef SQLITE_SHELL_FIDDLE
9773 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "read", n
)==0 ){
9774 FILE *inSaved
= p
->in
;
9775 int savedLineno
= p
->lineno
;
9776 failIfSafeMode(p
, "cannot run .read in safe mode");
9778 eputz("Usage: .read FILE\n");
9780 goto meta_command_exit
;
9782 if( azArg
[1][0]=='|' ){
9783 #ifdef SQLITE_OMIT_POPEN
9784 eputz("Error: pipes are not supported in this OS\n");
9788 p
->in
= popen(azArg
[1]+1, "r");
9790 eputf("Error: cannot open \"%s\"\n", azArg
[1]);
9793 rc
= process_input(p
);
9797 }else if( (p
->in
= openChrSource(azArg
[1]))==0 ){
9798 eputf("Error: cannot open \"%s\"\n", azArg
[1]);
9801 rc
= process_input(p
);
9805 p
->lineno
= savedLineno
;
9807 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9809 #ifndef SQLITE_SHELL_FIDDLE
9810 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "restore", n
)==0 ){
9811 const char *zSrcFile
;
9814 sqlite3_backup
*pBackup
;
9817 failIfSafeMode(p
, "cannot run .restore in safe mode");
9819 zSrcFile
= azArg
[1];
9821 }else if( nArg
==3 ){
9822 zSrcFile
= azArg
[2];
9825 eputz("Usage: .restore ?DB? FILE\n");
9827 goto meta_command_exit
;
9829 rc
= sqlite3_open(zSrcFile
, &pSrc
);
9830 if( rc
!=SQLITE_OK
){
9831 eputf("Error: cannot open \"%s\"\n", zSrcFile
);
9836 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
9838 eputf("Error: %s\n", sqlite3_errmsg(p
->db
));
9842 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
9843 || rc
==SQLITE_BUSY
){
9844 if( rc
==SQLITE_BUSY
){
9845 if( nTimeout
++ >= 3 ) break;
9849 sqlite3_backup_finish(pBackup
);
9850 if( rc
==SQLITE_DONE
){
9852 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
9853 eputz("Error: source database is busy\n");
9856 eputf("Error: %s\n", sqlite3_errmsg(p
->db
));
9861 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9863 if( c
=='s' && cli_strncmp(azArg
[0], "scanstats", n
)==0 ){
9865 if( cli_strcmp(azArg
[1], "vm")==0 ){
9868 if( cli_strcmp(azArg
[1], "est")==0 ){
9871 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
9875 p
->db
, SQLITE_DBCONFIG_STMT_SCANSTATUS
, p
->scanstatsOn
, (int*)0
9877 #if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
9878 eputz("Warning: .scanstats not available in this build.\n");
9879 #elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
9880 if( p
->scanstatsOn
==3 ){
9881 eputz("Warning: \".scanstats vm\" not available in this build.\n");
9885 eputz("Usage: .scanstats on|off|est\n");
9890 if( c
=='s' && cli_strncmp(azArg
[0], "schema", n
)==0 ){
9894 const char *zDiv
= "(";
9895 const char *zName
= 0;
9898 int bNoSystemTabs
= 0;
9902 memcpy(&data
, p
, sizeof(data
));
9903 data
.showHeader
= 0;
9904 data
.cMode
= data
.mode
= MODE_Semi
;
9906 for(ii
=1; ii
<nArg
; ii
++){
9907 if( optionMatch(azArg
[ii
],"indent") ){
9908 data
.cMode
= data
.mode
= MODE_Pretty
;
9909 }else if( optionMatch(azArg
[ii
],"debug") ){
9911 }else if( optionMatch(azArg
[ii
],"nosys") ){
9913 }else if( azArg
[ii
][0]=='-' ){
9914 eputf("Unknown option: \"%s\"\n", azArg
[ii
]);
9916 goto meta_command_exit
;
9917 }else if( zName
==0 ){
9920 eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9922 goto meta_command_exit
;
9926 int isSchema
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0
9927 || sqlite3_strlike(zName
, "sqlite_schema", '\\')==0
9928 || sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0
9929 || sqlite3_strlike(zName
,"sqlite_temp_schema", '\\')==0;
9931 char *new_argv
[2], *new_colv
[2];
9932 new_argv
[0] = sqlite3_mprintf(
9933 "CREATE TABLE %s (\n"
9937 " rootpage integer,\n"
9940 shell_check_oom(new_argv
[0]);
9942 new_colv
[0] = "sql";
9944 callback(&data
, 1, new_argv
, new_colv
);
9945 sqlite3_free(new_argv
[0]);
9949 sqlite3_stmt
*pStmt
= 0;
9950 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
9953 eputf("Error: %s\n", sqlite3_errmsg(p
->db
));
9954 sqlite3_finalize(pStmt
);
9956 goto meta_command_exit
;
9958 appendText(&sSelect
, "SELECT sql FROM", 0);
9960 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
9961 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
9963 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
9964 appendText(&sSelect
, zDiv
, 0);
9965 zDiv
= " UNION ALL ";
9966 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
9967 if( sqlite3_stricmp(zDb
, "main")!=0 ){
9968 appendText(&sSelect
, zDb
, '\'');
9970 appendText(&sSelect
, "NULL", 0);
9972 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9973 appendText(&sSelect
, zScNum
, 0);
9974 appendText(&sSelect
, " AS snum, ", 0);
9975 appendText(&sSelect
, zDb
, '\'');
9976 appendText(&sSelect
, " AS sname FROM ", 0);
9977 appendText(&sSelect
, zDb
, quoteChar(zDb
));
9978 appendText(&sSelect
, ".sqlite_schema", 0);
9980 sqlite3_finalize(pStmt
);
9981 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9983 appendText(&sSelect
,
9984 " UNION ALL SELECT shell_module_schema(name),"
9985 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9989 appendText(&sSelect
, ") WHERE ", 0);
9991 char *zQarg
= sqlite3_mprintf("%Q", zName
);
9993 shell_check_oom(zQarg
);
9994 bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
9995 strchr(zName
, '[') != 0;
9996 if( strchr(zName
, '.') ){
9997 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
9999 appendText(&sSelect
, "lower(tbl_name)", 0);
10001 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
10002 appendText(&sSelect
, zQarg
, 0);
10004 appendText(&sSelect
, " ESCAPE '\\' ", 0);
10006 appendText(&sSelect
, " AND ", 0);
10007 sqlite3_free(zQarg
);
10009 if( bNoSystemTabs
){
10010 appendText(&sSelect
, "name NOT LIKE 'sqlite_%%' AND ", 0);
10012 appendText(&sSelect
, "sql IS NOT NULL"
10013 " ORDER BY snum, rowid", 0);
10015 oputf("SQL: %s;\n", sSelect
.z
);
10017 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
10019 freeText(&sSelect
);
10022 eputf("Error: %s\n", zErrMsg
);
10023 sqlite3_free(zErrMsg
);
10025 }else if( rc
!= SQLITE_OK
){
10026 eputz("Error: querying schema information\n");
10033 if( (c
=='s' && n
==11 && cli_strncmp(azArg
[0], "selecttrace", n
)==0)
10034 || (c
=='t' && n
==9 && cli_strncmp(azArg
[0], "treetrace", n
)==0)
10036 unsigned int x
= nArg
>=2? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
10037 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &x
);
10040 #if defined(SQLITE_ENABLE_SESSION)
10041 if( c
=='s' && cli_strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
10042 struct AuxDb
*pAuxDb
= p
->pAuxDb
;
10043 OpenSession
*pSession
= &pAuxDb
->aSession
[0];
10044 char **azCmd
= &azArg
[1];
10046 int nCmd
= nArg
- 1;
10048 if( nArg
<=1 ) goto session_syntax_error
;
10051 for(iSes
=0; iSes
<pAuxDb
->nSession
; iSes
++){
10052 if( cli_strcmp(pAuxDb
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
10054 if( iSes
<pAuxDb
->nSession
){
10055 pSession
= &pAuxDb
->aSession
[iSes
];
10059 pSession
= &pAuxDb
->aSession
[0];
10064 /* .session attach TABLE
10065 ** Invoke the sqlite3session_attach() interface to attach a particular
10066 ** table so that it is never filtered.
10068 if( cli_strcmp(azCmd
[0],"attach")==0 ){
10069 if( nCmd
!=2 ) goto session_syntax_error
;
10070 if( pSession
->p
==0 ){
10072 eputz("ERROR: No sessions are open\n");
10074 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
10076 eputf("ERROR: sqlite3session_attach() returns %d\n",rc
);
10082 /* .session changeset FILE
10083 ** .session patchset FILE
10084 ** Write a changeset or patchset into a file. The file is overwritten.
10086 if( cli_strcmp(azCmd
[0],"changeset")==0
10087 || cli_strcmp(azCmd
[0],"patchset")==0
10090 failIfSafeMode(p
, "cannot run \".session %s\" in safe mode", azCmd
[0]);
10091 if( nCmd
!=2 ) goto session_syntax_error
;
10092 if( pSession
->p
==0 ) goto session_not_open
;
10093 out
= fopen(azCmd
[1], "wb");
10095 eputf("ERROR: cannot open \"%s\" for writing\n",
10100 if( azCmd
[0][0]=='c' ){
10101 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
10103 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
10106 sputf(stdout
, "Error: error code %d\n", rc
);
10110 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
10111 eputf("ERROR: Failed to write entire %d-byte output\n", szChng
);
10113 sqlite3_free(pChng
);
10119 ** Close the identified session
10121 if( cli_strcmp(azCmd
[0], "close")==0 ){
10122 if( nCmd
!=1 ) goto session_syntax_error
;
10123 if( pAuxDb
->nSession
){
10124 session_close(pSession
);
10125 pAuxDb
->aSession
[iSes
] = pAuxDb
->aSession
[--pAuxDb
->nSession
];
10129 /* .session enable ?BOOLEAN?
10130 ** Query or set the enable flag
10132 if( cli_strcmp(azCmd
[0], "enable")==0 ){
10134 if( nCmd
>2 ) goto session_syntax_error
;
10135 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
10136 if( pAuxDb
->nSession
){
10137 ii
= sqlite3session_enable(pSession
->p
, ii
);
10138 oputf("session %s enable flag = %d\n", pSession
->zName
, ii
);
10142 /* .session filter GLOB ....
10143 ** Set a list of GLOB patterns of table names to be excluded.
10145 if( cli_strcmp(azCmd
[0], "filter")==0 ){
10147 if( nCmd
<2 ) goto session_syntax_error
;
10148 if( pAuxDb
->nSession
){
10149 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
10150 sqlite3_free(pSession
->azFilter
[ii
]);
10152 sqlite3_free(pSession
->azFilter
);
10153 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
10154 pSession
->azFilter
= sqlite3_malloc( nByte
);
10155 shell_check_oom( pSession
->azFilter
);
10156 for(ii
=1; ii
<nCmd
; ii
++){
10157 char *x
= pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
10158 shell_check_oom(x
);
10160 pSession
->nFilter
= ii
-1;
10164 /* .session indirect ?BOOLEAN?
10165 ** Query or set the indirect flag
10167 if( cli_strcmp(azCmd
[0], "indirect")==0 ){
10169 if( nCmd
>2 ) goto session_syntax_error
;
10170 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
10171 if( pAuxDb
->nSession
){
10172 ii
= sqlite3session_indirect(pSession
->p
, ii
);
10173 oputf("session %s indirect flag = %d\n", pSession
->zName
, ii
);
10177 /* .session isempty
10178 ** Determine if the session is empty
10180 if( cli_strcmp(azCmd
[0], "isempty")==0 ){
10182 if( nCmd
!=1 ) goto session_syntax_error
;
10183 if( pAuxDb
->nSession
){
10184 ii
= sqlite3session_isempty(pSession
->p
);
10185 oputf("session %s isempty flag = %d\n", pSession
->zName
, ii
);
10190 ** List all currently open sessions
10192 if( cli_strcmp(azCmd
[0],"list")==0 ){
10193 for(i
=0; i
<pAuxDb
->nSession
; i
++){
10194 oputf("%d %s\n", i
, pAuxDb
->aSession
[i
].zName
);
10198 /* .session open DB NAME
10199 ** Open a new session called NAME on the attached database DB.
10200 ** DB is normally "main".
10202 if( cli_strcmp(azCmd
[0],"open")==0 ){
10204 if( nCmd
!=3 ) goto session_syntax_error
;
10206 if( zName
[0]==0 ) goto session_syntax_error
;
10207 for(i
=0; i
<pAuxDb
->nSession
; i
++){
10208 if( cli_strcmp(pAuxDb
->aSession
[i
].zName
,zName
)==0 ){
10209 eputf("Session \"%s\" already exists\n", zName
);
10210 goto meta_command_exit
;
10213 if( pAuxDb
->nSession
>=ArraySize(pAuxDb
->aSession
) ){
10214 eputf("Maximum of %d sessions\n", ArraySize(pAuxDb
->aSession
));
10215 goto meta_command_exit
;
10217 pSession
= &pAuxDb
->aSession
[pAuxDb
->nSession
];
10218 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
10220 eputf("Cannot open session: error code=%d\n", rc
);
10222 goto meta_command_exit
;
10224 pSession
->nFilter
= 0;
10225 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
10226 pAuxDb
->nSession
++;
10227 pSession
->zName
= sqlite3_mprintf("%s", zName
);
10228 shell_check_oom(pSession
->zName
);
10230 /* If no command name matches, show a syntax error */
10231 session_syntax_error
:
10232 showHelp(p
->out
, "session");
10236 #ifdef SQLITE_DEBUG
10237 /* Undocumented commands for internal testing. Subject to change
10238 ** without notice. */
10239 if( c
=='s' && n
>=10 && cli_strncmp(azArg
[0], "selftest-", 9)==0 ){
10240 if( cli_strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
10242 for(i
=1; i
<nArg
; i
++){
10243 v
= booleanValue(azArg
[i
]);
10244 oputf("%s: %d 0x%x\n", azArg
[i
], v
, v
);
10247 if( cli_strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
10248 int i
; sqlite3_int64 v
;
10249 for(i
=1; i
<nArg
; i
++){
10251 v
= integerValue(azArg
[i
]);
10252 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
10259 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"selftest",n
)==0 ){
10260 int bIsInit
= 0; /* True to initialize the SELFTEST table */
10261 int bVerbose
= 0; /* Verbose output */
10262 int bSelftestExists
; /* True if SELFTEST already exists */
10263 int i
, k
; /* Loop counters */
10264 int nTest
= 0; /* Number of tests runs */
10265 int nErr
= 0; /* Number of errors seen */
10266 ShellText str
; /* Answer for a query */
10267 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
10270 for(i
=1; i
<nArg
; i
++){
10271 const char *z
= azArg
[i
];
10272 if( z
[0]=='-' && z
[1]=='-' ) z
++;
10273 if( cli_strcmp(z
,"-init")==0 ){
10276 if( cli_strcmp(z
,"-v")==0 ){
10280 eputf("Unknown option \"%s\" on \"%s\"\n", azArg
[i
], azArg
[0]);
10281 eputz("Should be one of: --init -v\n");
10283 goto meta_command_exit
;
10286 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
10288 bSelftestExists
= 0;
10290 bSelftestExists
= 1;
10293 createSelftestTable(p
);
10294 bSelftestExists
= 1;
10297 appendText(&str
, "x", 0);
10298 for(k
=bSelftestExists
; k
>=0; k
--){
10300 rc
= sqlite3_prepare_v2(p
->db
,
10301 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10304 rc
= sqlite3_prepare_v2(p
->db
,
10305 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10306 " (1,'run','PRAGMA integrity_check','ok')",
10310 eputz("Error querying the selftest table\n");
10312 sqlite3_finalize(pStmt
);
10313 goto meta_command_exit
;
10315 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
10316 int tno
= sqlite3_column_int(pStmt
, 0);
10317 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
10318 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
10319 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
10321 if( zOp
==0 ) continue;
10322 if( zSql
==0 ) continue;
10323 if( zAns
==0 ) continue;
10326 sputf(stdout
, "%d: %s %s\n", tno
, zOp
, zSql
);
10328 if( cli_strcmp(zOp
,"memo")==0 ){
10329 oputf("%s\n", zSql
);
10331 if( cli_strcmp(zOp
,"run")==0 ){
10335 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
10338 oputf("Result: %s\n", str
.z
);
10340 if( rc
|| zErrMsg
){
10343 oputf("%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
10344 sqlite3_free(zErrMsg
);
10345 }else if( cli_strcmp(zAns
,str
.z
)!=0 ){
10348 oputf("%d: Expected: [%s]\n", tno
, zAns
);
10349 oputf("%d: Got: [%s]\n", tno
, str
.z
);
10353 eputf("Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
10357 } /* End loop over rows of content from SELFTEST */
10358 sqlite3_finalize(pStmt
);
10359 } /* End loop over k */
10361 oputf("%d errors out of %d tests\n", nErr
, nTest
);
10364 if( c
=='s' && cli_strncmp(azArg
[0], "separator", n
)==0 ){
10365 if( nArg
<2 || nArg
>3 ){
10366 eputz("Usage: .separator COL ?ROW?\n");
10370 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
10371 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
10374 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
10375 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
10379 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"sha3sum",n
)==0 ){
10380 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
10381 int i
; /* Loop counter */
10382 int bSchema
= 0; /* Also hash the schema */
10383 int bSeparate
= 0; /* Hash each table separately */
10384 int iSize
= 224; /* Hash algorithm to use */
10385 int bDebug
= 0; /* Only show the query that would have run */
10386 sqlite3_stmt
*pStmt
; /* For querying tables names */
10387 char *zSql
; /* SQL to be run */
10388 char *zSep
; /* Separator */
10389 ShellText sSql
; /* Complete SQL for the query to run the hash */
10390 ShellText sQuery
; /* Set of queries used to read all content */
10392 for(i
=1; i
<nArg
; i
++){
10393 const char *z
= azArg
[i
];
10396 if( z
[0]=='-' ) z
++;
10397 if( cli_strcmp(z
,"schema")==0 ){
10400 if( cli_strcmp(z
,"sha3-224")==0 || cli_strcmp(z
,"sha3-256")==0
10401 || cli_strcmp(z
,"sha3-384")==0 || cli_strcmp(z
,"sha3-512")==0
10403 iSize
= atoi(&z
[5]);
10405 if( cli_strcmp(z
,"debug")==0 ){
10409 eputf("Unknown option \"%s\" on \"%s\"\n", azArg
[i
], azArg
[0]);
10410 showHelp(p
->out
, azArg
[0]);
10412 goto meta_command_exit
;
10415 eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10417 goto meta_command_exit
;
10421 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
10425 zSql
= "SELECT lower(name) as tname FROM sqlite_schema"
10426 " WHERE type='table' AND coalesce(rootpage,0)>1"
10427 " UNION ALL SELECT 'sqlite_schema'"
10428 " ORDER BY 1 collate nocase";
10430 zSql
= "SELECT lower(name) as tname FROM sqlite_schema"
10431 " WHERE type='table' AND coalesce(rootpage,0)>1"
10432 " AND name NOT LIKE 'sqlite_%'"
10433 " ORDER BY 1 collate nocase";
10435 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
10438 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
10440 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
10441 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
10442 if( zTab
==0 ) continue;
10443 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
10444 if( cli_strncmp(zTab
, "sqlite_",7)!=0 ){
10445 appendText(&sQuery
,"SELECT * FROM ", 0);
10446 appendText(&sQuery
,zTab
,'"');
10447 appendText(&sQuery
," NOT INDEXED;", 0);
10448 }else if( cli_strcmp(zTab
, "sqlite_schema")==0 ){
10449 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10450 " ORDER BY name;", 0);
10451 }else if( cli_strcmp(zTab
, "sqlite_sequence")==0 ){
10452 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
10453 " ORDER BY name;", 0);
10454 }else if( cli_strcmp(zTab
, "sqlite_stat1")==0 ){
10455 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
10456 " ORDER BY tbl,idx;", 0);
10457 }else if( cli_strcmp(zTab
, "sqlite_stat4")==0 ){
10458 appendText(&sQuery
, "SELECT * FROM ", 0);
10459 appendText(&sQuery
, zTab
, 0);
10460 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
10462 appendText(&sSql
, zSep
, 0);
10463 appendText(&sSql
, sQuery
.z
, '\'');
10465 appendText(&sSql
, ",", 0);
10466 appendText(&sSql
, zTab
, '\'');
10469 sqlite3_finalize(pStmt
);
10471 zSql
= sqlite3_mprintf(
10473 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10474 " FROM [sha3sum$query]",
10477 zSql
= sqlite3_mprintf(
10479 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10480 " FROM [sha3sum$query]",
10483 shell_check_oom(zSql
);
10487 oputf("%s\n", zSql
);
10489 shell_exec(p
, zSql
, 0);
10491 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10494 char *zRevText
= /* Query for reversible to-blob-to-text check */
10495 "SELECT lower(name) as tname FROM sqlite_schema\n"
10496 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10497 "AND name NOT LIKE 'sqlite_%%'%s\n"
10498 "ORDER BY 1 collate nocase";
10499 zRevText
= sqlite3_mprintf(zRevText
, zLike
? " AND name LIKE $tspec" : "");
10500 zRevText
= sqlite3_mprintf(
10501 /* lower-case query is first run, producing upper-case query. */
10502 "with tabcols as materialized(\n"
10503 "select tname, cname\n"
10505 " select printf('\"%%w\"',ss.tname) as tname,"
10506 " printf('\"%%w\"',ti.name) as cname\n"
10507 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10508 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10509 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10510 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10511 "FROM '||tname||' WHERE '\n"
10512 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10513 "|| ' AND typeof('||cname||')=''text'' ',\n"
10514 "' OR ') as query, tname from tabcols group by tname)"
10516 shell_check_oom(zRevText
);
10517 if( bDebug
) oputf("%s\n", zRevText
);
10518 lrc
= sqlite3_prepare_v2(p
->db
, zRevText
, -1, &pStmt
, 0);
10519 if( lrc
!=SQLITE_OK
){
10520 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
10521 ** user does cruel and unnatural things like ".limit expr_depth 0". */
10524 if( zLike
) sqlite3_bind_text(pStmt
,1,zLike
,-1,SQLITE_STATIC
);
10525 lrc
= SQLITE_ROW
==sqlite3_step(pStmt
);
10527 const char *zGenQuery
= (char*)sqlite3_column_text(pStmt
,0);
10528 sqlite3_stmt
*pCheckStmt
;
10529 lrc
= sqlite3_prepare_v2(p
->db
, zGenQuery
, -1, &pCheckStmt
, 0);
10530 if( bDebug
) oputf("%s\n", zGenQuery
);
10531 if( lrc
!=SQLITE_OK
){
10534 if( SQLITE_ROW
==sqlite3_step(pCheckStmt
) ){
10535 double countIrreversible
= sqlite3_column_double(pCheckStmt
, 0);
10536 if( countIrreversible
>0 ){
10537 int sz
= (int)(countIrreversible
+ 0.5);
10538 eputf("Digest includes %d invalidly encoded text field%s.\n",
10539 sz
, (sz
>1)? "s": "");
10542 sqlite3_finalize(pCheckStmt
);
10544 sqlite3_finalize(pStmt
);
10547 if( rc
) eputz(".sha3sum failed.\n");
10548 sqlite3_free(zRevText
);
10550 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10551 sqlite3_free(zSql
);
10554 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10556 && (cli_strncmp(azArg
[0], "shell", n
)==0
10557 || cli_strncmp(azArg
[0],"system",n
)==0)
10561 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
10563 eputz("Usage: .system COMMAND\n");
10565 goto meta_command_exit
;
10567 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
10568 for(i
=2; i
<nArg
&& zCmd
!=0; i
++){
10569 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
10573 x
= zCmd
!=0 ? system(zCmd
) : 1;
10574 consoleRenewSetup();
10575 sqlite3_free(zCmd
);
10576 if( x
) eputf("System command returns %d\n", x
);
10578 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10580 if( c
=='s' && cli_strncmp(azArg
[0], "show", n
)==0 ){
10581 static const char *azBool
[] = { "off", "on", "trigger", "full"};
10585 eputz("Usage: .show\n");
10587 goto meta_command_exit
;
10589 oputf("%12.12s: %s\n","echo",
10590 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
10591 oputf("%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
10592 oputf("%12.12s: %s\n","explain",
10593 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
10594 oputf("%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
10595 if( p
->mode
==MODE_Column
10596 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
10598 oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10599 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
10600 p
->cmOpts
.bWordWrap
? "on" : "off",
10601 p
->cmOpts
.bQuote
? "" : "no");
10603 oputf("%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
10605 oputf("%12.12s: ", "nullvalue");
10606 output_c_string(p
->nullValue
);
10608 oputf("%12.12s: %s\n","output",
10609 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
10610 oputf("%12.12s: ", "colseparator");
10611 output_c_string(p
->colSeparator
);
10613 oputf("%12.12s: ", "rowseparator");
10614 output_c_string(p
->rowSeparator
);
10616 switch( p
->statsOn
){
10617 case 0: zOut
= "off"; break;
10618 default: zOut
= "on"; break;
10619 case 2: zOut
= "stmt"; break;
10620 case 3: zOut
= "vmstep"; break;
10622 oputf("%12.12s: %s\n","stats", zOut
);
10623 oputf("%12.12s: ", "width");
10624 for (i
=0;i
<p
->nWidth
;i
++) {
10625 oputf("%d ", p
->colWidth
[i
]);
10628 oputf("%12.12s: %s\n", "filename",
10629 p
->pAuxDb
->zDbFilename
? p
->pAuxDb
->zDbFilename
: "");
10632 if( c
=='s' && cli_strncmp(azArg
[0], "stats", n
)==0 ){
10634 if( cli_strcmp(azArg
[1],"stmt")==0 ){
10636 }else if( cli_strcmp(azArg
[1],"vmstep")==0 ){
10639 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
10641 }else if( nArg
==1 ){
10642 display_stats(p
->db
, p
, 0);
10644 eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
10649 if( (c
=='t' && n
>1 && cli_strncmp(azArg
[0], "tables", n
)==0)
10650 || (c
=='i' && (cli_strncmp(azArg
[0], "indices", n
)==0
10651 || cli_strncmp(azArg
[0], "indexes", n
)==0) )
10653 sqlite3_stmt
*pStmt
;
10660 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
10662 sqlite3_finalize(pStmt
);
10663 return shellDatabaseError(p
->db
);
10666 if( nArg
>2 && c
=='i' ){
10667 /* It is an historical accident that the .indexes command shows an error
10668 ** when called with the wrong number of arguments whereas the .tables
10669 ** command does not. */
10670 eputz("Usage: .indexes ?LIKE-PATTERN?\n");
10672 sqlite3_finalize(pStmt
);
10673 goto meta_command_exit
;
10675 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
10676 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
10677 if( zDbName
==0 ) continue;
10678 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
10679 if( sqlite3_stricmp(zDbName
, "main")==0 ){
10680 appendText(&s
, "SELECT name FROM ", 0);
10682 appendText(&s
, "SELECT ", 0);
10683 appendText(&s
, zDbName
, '\'');
10684 appendText(&s
, "||'.'||name FROM ", 0);
10686 appendText(&s
, zDbName
, '"');
10687 appendText(&s
, ".sqlite_schema ", 0);
10689 appendText(&s
," WHERE type IN ('table','view')"
10690 " AND name NOT LIKE 'sqlite_%'"
10691 " AND name LIKE ?1", 0);
10693 appendText(&s
," WHERE type='index'"
10694 " AND tbl_name LIKE ?1", 0);
10697 rc
= sqlite3_finalize(pStmt
);
10698 if( rc
==SQLITE_OK
){
10699 appendText(&s
, " ORDER BY 1", 0);
10700 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
10703 if( rc
) return shellDatabaseError(p
->db
);
10705 /* Run the SQL statement prepared by the above block. Store the results
10706 ** as an array of nul-terminated strings in azResult[]. */
10710 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
10712 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
10714 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
10715 if( nRow
>=nAlloc
){
10717 int n2
= nAlloc
*2 + 10;
10718 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
10719 shell_check_oom(azNew
);
10723 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
10724 shell_check_oom(azResult
[nRow
]);
10727 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
10728 rc
= shellDatabaseError(p
->db
);
10731 /* Pretty-print the contents of array azResult[] to the output */
10732 if( rc
==0 && nRow
>0 ){
10733 int len
, maxlen
= 0;
10735 int nPrintCol
, nPrintRow
;
10736 for(i
=0; i
<nRow
; i
++){
10737 len
= strlen30(azResult
[i
]);
10738 if( len
>maxlen
) maxlen
= len
;
10740 nPrintCol
= 80/(maxlen
+2);
10741 if( nPrintCol
<1 ) nPrintCol
= 1;
10742 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
10743 for(i
=0; i
<nPrintRow
; i
++){
10744 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
10745 char *zSp
= j
<nPrintRow
? "" : " ";
10746 oputf("%s%-*s", zSp
, maxlen
, azResult
[j
] ? azResult
[j
]:"");
10752 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
10753 sqlite3_free(azResult
);
10756 #ifndef SQLITE_SHELL_FIDDLE
10757 /* Begin redirecting output to the file "testcase-out.txt" */
10758 if( c
=='t' && cli_strcmp(azArg
[0],"testcase")==0 ){
10760 p
->out
= output_file_open("testcase-out.txt", 0);
10762 eputz("Error: cannot open 'testcase-out.txt'\n");
10765 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
10767 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
10770 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10772 #ifndef SQLITE_UNTESTABLE
10773 if( c
=='t' && n
>=8 && cli_strncmp(azArg
[0], "testctrl", n
)==0 ){
10774 static const struct {
10775 const char *zCtrlName
; /* Name of a test-control option */
10776 int ctrlCode
; /* Integer code for that option */
10777 int unSafe
; /* Not valid unless --unsafe-testing */
10778 const char *zUsage
; /* Usage notes */
10780 {"always", SQLITE_TESTCTRL_ALWAYS
, 1, "BOOLEAN" },
10781 {"assert", SQLITE_TESTCTRL_ASSERT
, 1, "BOOLEAN" },
10782 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10783 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10784 {"byteorder", SQLITE_TESTCTRL_BYTEORDER
, 0, "" },
10785 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
,0,"BOOLEAN" },
10786 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10787 {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION
, 0, "BOOLEAN" },
10788 {"imposter", SQLITE_TESTCTRL_IMPOSTER
,1,"SCHEMA ON/OFF ROOTPAGE"},
10789 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
,0,"" },
10790 {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK
,0,"BOOLEAN" },
10791 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,0,"BOOLEAN" },
10792 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
,1, "BOOLEAN" },
10793 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
,0,"DISABLE-MASK" },
10795 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
,0,"" },
10797 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
,0, "OFFSET " },
10798 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
,0, "" },
10799 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, 0, "" },
10800 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED
, 0, "SEED ?db?" },
10801 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT
, 0, "" },
10802 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP
, 0, "NMAX" },
10803 {"tune", SQLITE_TESTCTRL_TUNE
, 1, "ID VALUE" },
10804 {"uselongdouble", SQLITE_TESTCTRL_USELONGDOUBLE
,0,"?BOOLEAN|\"default\"?"},
10808 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10811 const char *zCmd
= 0;
10814 zCmd
= nArg
>=2 ? azArg
[1] : "help";
10816 /* The argument can optionally begin with "-" or "--" */
10817 if( zCmd
[0]=='-' && zCmd
[1] ){
10819 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
10822 /* --help lists all test-controls */
10823 if( cli_strcmp(zCmd
,"help")==0 ){
10824 oputz("Available test-controls:\n");
10825 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10826 if( aCtrl
[i
].unSafe
&& !ShellHasFlag(p
,SHFLG_TestingMode
) ) continue;
10827 oputf(" .testctrl %s %s\n",
10828 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
10831 goto meta_command_exit
;
10834 /* convert testctrl text option to value. allow any unique prefix
10835 ** of the option name, or a numerical value. */
10836 n2
= strlen30(zCmd
);
10837 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10838 if( aCtrl
[i
].unSafe
&& !ShellHasFlag(p
,SHFLG_TestingMode
) ) continue;
10839 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
10841 testctrl
= aCtrl
[i
].ctrlCode
;
10844 eputf("Error: ambiguous test-control: \"%s\"\n"
10845 "Use \".testctrl --help\" for help\n", zCmd
);
10847 goto meta_command_exit
;
10852 eputf("Error: unknown test-control: %s\n"
10853 "Use \".testctrl --help\" for help\n", zCmd
);
10857 /* sqlite3_test_control(int, db, int) */
10858 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
10859 case SQLITE_TESTCTRL_FK_NO_ACTION
:
10861 unsigned int opt
= (unsigned int)strtol(azArg
[2], 0, 0);
10862 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
10867 /* sqlite3_test_control(int) */
10868 case SQLITE_TESTCTRL_PRNG_SAVE
:
10869 case SQLITE_TESTCTRL_PRNG_RESTORE
:
10870 case SQLITE_TESTCTRL_BYTEORDER
:
10872 rc2
= sqlite3_test_control(testctrl
);
10873 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
10877 /* sqlite3_test_control(int, uint) */
10878 case SQLITE_TESTCTRL_PENDING_BYTE
:
10880 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
10881 rc2
= sqlite3_test_control(testctrl
, opt
);
10886 /* sqlite3_test_control(int, int, sqlite3*) */
10887 case SQLITE_TESTCTRL_PRNG_SEED
:
10888 if( nArg
==3 || nArg
==4 ){
10889 int ii
= (int)integerValue(azArg
[2]);
10891 if( ii
==0 && cli_strcmp(azArg
[2],"random")==0 ){
10892 sqlite3_randomness(sizeof(ii
),&ii
);
10893 sputf(stdout
, "-- random seed: %d\n", ii
);
10899 /* Make sure the schema has been loaded */
10900 sqlite3_table_column_metadata(db
, 0, "x", 0, 0, 0, 0, 0, 0);
10902 rc2
= sqlite3_test_control(testctrl
, ii
, db
);
10907 /* sqlite3_test_control(int, int) */
10908 case SQLITE_TESTCTRL_ASSERT
:
10909 case SQLITE_TESTCTRL_ALWAYS
:
10911 int opt
= booleanValue(azArg
[2]);
10912 rc2
= sqlite3_test_control(testctrl
, opt
);
10917 /* sqlite3_test_control(int, int) */
10918 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
10919 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
10921 int opt
= booleanValue(azArg
[2]);
10922 rc2
= sqlite3_test_control(testctrl
, opt
);
10927 /* sqlite3_test_control(int, int) */
10928 case SQLITE_TESTCTRL_USELONGDOUBLE
: {
10931 if( cli_strcmp(azArg
[2],"default")==0 ){
10934 opt
= booleanValue(azArg
[2]);
10937 rc2
= sqlite3_test_control(testctrl
, opt
);
10942 /* sqlite3_test_control(sqlite3*) */
10943 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
:
10944 rc2
= sqlite3_test_control(testctrl
, p
->db
);
10948 case SQLITE_TESTCTRL_IMPOSTER
:
10950 rc2
= sqlite3_test_control(testctrl
, p
->db
,
10952 integerValue(azArg
[3]),
10953 integerValue(azArg
[4]));
10958 case SQLITE_TESTCTRL_SEEK_COUNT
: {
10960 rc2
= sqlite3_test_control(testctrl
, p
->db
, &x
);
10961 oputf("%llu\n", x
);
10967 case SQLITE_TESTCTRL_PARSER_COVERAGE
: {
10969 sqlite3_test_control(testctrl
, p
->out
);
10975 #ifdef SQLITE_DEBUG
10976 case SQLITE_TESTCTRL_TUNE
: {
10978 int id
= (int)integerValue(azArg
[2]);
10979 int val
= (int)integerValue(azArg
[3]);
10980 sqlite3_test_control(testctrl
, id
, &val
);
10982 }else if( nArg
==3 ){
10983 int id
= (int)integerValue(azArg
[2]);
10984 sqlite3_test_control(testctrl
, -id
, &rc2
);
10986 }else if( nArg
==2 ){
10990 rc2
= sqlite3_test_control(testctrl
, -id
, &val
);
10991 if( rc2
!=SQLITE_OK
) break;
10992 if( id
>1 ) oputz(" ");
10993 oputf("%d: %d", id
, val
);
10996 if( id
>1 ) oputz("\n");
11002 case SQLITE_TESTCTRL_SORTER_MMAP
:
11004 int opt
= (unsigned int)integerValue(azArg
[2]);
11005 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
11009 case SQLITE_TESTCTRL_JSON_SELFCHECK
:
11014 rc2
= booleanValue(azArg
[2]);
11017 sqlite3_test_control(testctrl
, &rc2
);
11021 if( isOk
==0 && iCtrl
>=0 ){
11022 oputf("Usage: .testctrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
11024 }else if( isOk
==1 ){
11025 oputf("%d\n", rc2
);
11026 }else if( isOk
==2 ){
11027 oputf("0x%08x\n", rc2
);
11030 #endif /* !defined(SQLITE_UNTESTABLE) */
11032 if( c
=='t' && n
>4 && cli_strncmp(azArg
[0], "timeout", n
)==0 ){
11034 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
11037 if( c
=='t' && n
>=5 && cli_strncmp(azArg
[0], "timer", n
)==0 ){
11039 enableTimer
= booleanValue(azArg
[1]);
11040 if( enableTimer
&& !HAS_TIMER
){
11041 eputz("Error: timer not available on this system.\n");
11045 eputz("Usage: .timer on|off\n");
11050 #ifndef SQLITE_OMIT_TRACE
11051 if( c
=='t' && cli_strncmp(azArg
[0], "trace", n
)==0 ){
11055 for(jj
=1; jj
<nArg
; jj
++){
11056 const char *z
= azArg
[jj
];
11058 if( optionMatch(z
, "expanded") ){
11059 p
->eTraceType
= SHELL_TRACE_EXPANDED
;
11061 #ifdef SQLITE_ENABLE_NORMALIZE
11062 else if( optionMatch(z
, "normalized") ){
11063 p
->eTraceType
= SHELL_TRACE_NORMALIZED
;
11066 else if( optionMatch(z
, "plain") ){
11067 p
->eTraceType
= SHELL_TRACE_PLAIN
;
11069 else if( optionMatch(z
, "profile") ){
11070 mType
|= SQLITE_TRACE_PROFILE
;
11072 else if( optionMatch(z
, "row") ){
11073 mType
|= SQLITE_TRACE_ROW
;
11075 else if( optionMatch(z
, "stmt") ){
11076 mType
|= SQLITE_TRACE_STMT
;
11078 else if( optionMatch(z
, "close") ){
11079 mType
|= SQLITE_TRACE_CLOSE
;
11082 eputf("Unknown option \"%s\" on \".trace\"\n", z
);
11084 goto meta_command_exit
;
11087 output_file_close(p
->traceOut
);
11088 p
->traceOut
= output_file_open(z
, 0);
11091 if( p
->traceOut
==0 ){
11092 sqlite3_trace_v2(p
->db
, 0, 0, 0);
11094 if( mType
==0 ) mType
= SQLITE_TRACE_STMT
;
11095 sqlite3_trace_v2(p
->db
, mType
, sql_trace_callback
, p
);
11098 #endif /* !defined(SQLITE_OMIT_TRACE) */
11100 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11101 if( c
=='u' && cli_strncmp(azArg
[0], "unmodule", n
)==0 ){
11106 eputz("Usage: .unmodule [--allexcept] NAME ...\n");
11108 goto meta_command_exit
;
11112 if( zOpt
[0]=='-' && zOpt
[1]=='-' && zOpt
[2]!=0 ) zOpt
++;
11113 lenOpt
= (int)strlen(zOpt
);
11114 if( lenOpt
>=3 && cli_strncmp(zOpt
, "-allexcept",lenOpt
)==0 ){
11115 assert( azArg
[nArg
]==0 );
11116 sqlite3_drop_modules(p
->db
, nArg
>2 ? (const char**)(azArg
+2) : 0);
11118 for(ii
=1; ii
<nArg
; ii
++){
11119 sqlite3_create_module(p
->db
, azArg
[ii
], 0, 0);
11125 #if SQLITE_USER_AUTHENTICATION
11126 if( c
=='u' && cli_strncmp(azArg
[0], "user", n
)==0 ){
11128 eputz("Usage: .user SUBCOMMAND ...\n");
11130 goto meta_command_exit
;
11133 if( cli_strcmp(azArg
[1],"login")==0 ){
11135 eputz("Usage: .user login USER PASSWORD\n");
11137 goto meta_command_exit
;
11139 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
11140 strlen30(azArg
[3]));
11142 eputf("Authentication failed for user %s\n", azArg
[2]);
11145 }else if( cli_strcmp(azArg
[1],"add")==0 ){
11147 eputz("Usage: .user add USER PASSWORD ISADMIN\n");
11149 goto meta_command_exit
;
11151 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
11152 booleanValue(azArg
[4]));
11154 eputf("User-Add failed: %d\n", rc
);
11157 }else if( cli_strcmp(azArg
[1],"edit")==0 ){
11159 eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
11161 goto meta_command_exit
;
11163 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
11164 booleanValue(azArg
[4]));
11166 eputf("User-Edit failed: %d\n", rc
);
11169 }else if( cli_strcmp(azArg
[1],"delete")==0 ){
11171 eputz("Usage: .user delete USER\n");
11173 goto meta_command_exit
;
11175 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
11177 eputf("User-Delete failed: %d\n", rc
);
11181 eputz("Usage: .user login|add|edit|delete ...\n");
11183 goto meta_command_exit
;
11186 #endif /* SQLITE_USER_AUTHENTICATION */
11188 if( c
=='v' && cli_strncmp(azArg
[0], "version", n
)==0 ){
11189 char *zPtrSz
= sizeof(void*)==8 ? "64-bit" : "32-bit";
11190 oputf("SQLite %s %s\n" /*extra-version-info*/,
11191 sqlite3_libversion(), sqlite3_sourceid());
11192 #if SQLITE_HAVE_ZLIB
11193 oputf("zlib version %s\n", zlibVersion());
11195 #define CTIMEOPT_VAL_(opt) #opt
11196 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11197 #if defined(__clang__) && defined(__clang_major__)
11198 oputf("clang-" CTIMEOPT_VAL(__clang_major__
) "."
11199 CTIMEOPT_VAL(__clang_minor__
) "."
11200 CTIMEOPT_VAL(__clang_patchlevel__
) " (%s)\n", zPtrSz
);
11201 #elif defined(_MSC_VER)
11202 oputf("msvc-" CTIMEOPT_VAL(_MSC_VER
) " (%s)\n", zPtrSz
);
11203 #elif defined(__GNUC__) && defined(__VERSION__)
11204 oputf("gcc-" __VERSION__
" (%s)\n", zPtrSz
);
11208 if( c
=='v' && cli_strncmp(azArg
[0], "vfsinfo", n
)==0 ){
11209 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
11210 sqlite3_vfs
*pVfs
= 0;
11212 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
11214 oputf("vfs.zName = \"%s\"\n", pVfs
->zName
);
11215 oputf("vfs.iVersion = %d\n", pVfs
->iVersion
);
11216 oputf("vfs.szOsFile = %d\n", pVfs
->szOsFile
);
11217 oputf("vfs.mxPathname = %d\n", pVfs
->mxPathname
);
11222 if( c
=='v' && cli_strncmp(azArg
[0], "vfslist", n
)==0 ){
11224 sqlite3_vfs
*pCurrent
= 0;
11226 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
11228 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
11229 oputf("vfs.zName = \"%s\"%s\n", pVfs
->zName
,
11230 pVfs
==pCurrent
? " <--- CURRENT" : "");
11231 oputf("vfs.iVersion = %d\n", pVfs
->iVersion
);
11232 oputf("vfs.szOsFile = %d\n", pVfs
->szOsFile
);
11233 oputf("vfs.mxPathname = %d\n", pVfs
->mxPathname
);
11235 oputz("-----------------------------------\n");
11240 if( c
=='v' && cli_strncmp(azArg
[0], "vfsname", n
)==0 ){
11241 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
11242 char *zVfsName
= 0;
11244 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
11246 oputf("%s\n", zVfsName
);
11247 sqlite3_free(zVfsName
);
11252 if( c
=='w' && cli_strncmp(azArg
[0], "wheretrace", n
)==0 ){
11253 unsigned int x
= nArg
>=2? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
11254 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &x
);
11257 if( c
=='w' && cli_strncmp(azArg
[0], "width", n
)==0 ){
11259 assert( nArg
<=ArraySize(azArg
) );
11260 p
->nWidth
= nArg
-1;
11261 p
->colWidth
= realloc(p
->colWidth
, (p
->nWidth
+1)*sizeof(int)*2);
11262 if( p
->colWidth
==0 && p
->nWidth
>0 ) shell_out_of_memory();
11263 if( p
->nWidth
) p
->actualWidth
= &p
->colWidth
[p
->nWidth
];
11264 for(j
=1; j
<nArg
; j
++){
11265 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
11270 eputf("Error: unknown command or invalid arguments: "
11271 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
11278 if( p
->outCount
==0 ) output_reset(p
);
11280 p
->bSafeMode
= p
->bSafeModePersist
;
11284 /* Line scan result and intermediate states (supporting scan resumption)
11287 # define CHAR_BIT 8
11290 QSS_HasDark
= 1<<CHAR_BIT
, QSS_EndingSemi
= 2<<CHAR_BIT
,
11291 QSS_CharMask
= (1<<CHAR_BIT
)-1, QSS_ScanMask
= 3<<CHAR_BIT
,
11294 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11295 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11296 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11297 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11298 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11301 ** Scan line for classification to guide shell's handling.
11302 ** The scan is resumable for subsequent lines when prior
11303 ** return values are passed as the 2nd argument.
11305 static QuickScanState
quickscan(char *zLine
, QuickScanState qss
,
11306 SCAN_TRACKER_REFTYPE pst
){
11308 char cWait
= (char)qss
; /* intentional narrowing loss */
11311 assert( cWait
==0 );
11312 while( (cin
= *zLine
++)!=0 ){
11319 while((cin
= *++zLine
)!=0 )
11324 qss
|= QSS_EndingSemi
;
11330 CONTINUE_PROMPT_AWAITS(pst
, "/*");
11331 qss
= QSS_SETV(qss
, cWait
);
11337 deliberate_fall_through
;
11338 case '`': case '\'': case '"':
11340 qss
= QSS_HasDark
| cWait
;
11341 CONTINUE_PROMPT_AWAITC(pst
, cin
);
11344 CONTINUE_PAREN_INCR(pst
, 1);
11347 CONTINUE_PAREN_INCR(pst
, -1);
11352 qss
= (qss
& ~QSS_EndingSemi
) | QSS_HasDark
;
11356 while( (cin
= *zLine
++)!=0 ){
11360 if( *zLine
!= '/' )
11364 CONTINUE_PROMPT_AWAITC(pst
, 0);
11365 qss
= QSS_SETV(qss
, 0);
11367 case '`': case '\'': case '"':
11369 /* Swallow doubled end-delimiter.*/
11373 deliberate_fall_through
;
11376 CONTINUE_PROMPT_AWAITC(pst
, 0);
11377 qss
= QSS_SETV(qss
, 0);
11379 default: assert(0);
11388 ** Return TRUE if the line typed in is an SQL command terminator other
11389 ** than a semi-colon. The SQL Server style "go" command is understood
11390 ** as is the Oracle "/".
11392 static int line_is_command_terminator(char *zLine
){
11393 while( IsSpace(zLine
[0]) ){ zLine
++; };
11394 if( zLine
[0]=='/' )
11395 zLine
+= 1; /* Oracle */
11396 else if ( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o' )
11397 zLine
+= 2; /* SQL Server */
11400 return quickscan(zLine
, QSS_Start
, 0)==QSS_Start
;
11404 ** The CLI needs a working sqlite3_complete() to work properly. So error
11405 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11407 #ifdef SQLITE_OMIT_COMPLETE
11408 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11412 ** Return true if zSql is a complete SQL statement. Return false if it
11413 ** ends in the middle of a string literal or C-style comment.
11415 static int line_is_complete(char *zSql
, int nSql
){
11417 if( zSql
==0 ) return 1;
11420 rc
= sqlite3_complete(zSql
);
11426 ** This function is called after processing each line of SQL in the
11427 ** runOneSqlLine() function. Its purpose is to detect scenarios where
11428 ** defensive mode should be automatically turned off. Specifically, when
11430 ** 1. The first line of input is "PRAGMA foreign_keys=OFF;",
11431 ** 2. The second line of input is "BEGIN TRANSACTION;",
11432 ** 3. The database is empty, and
11433 ** 4. The shell is not running in --safe mode.
11435 ** The implementation uses the ShellState.eRestoreState to maintain state:
11437 ** 0: Have not seen any SQL.
11438 ** 1: Have seen "PRAGMA foreign_keys=OFF;".
11439 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
11440 ** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
11441 ** 7: Nothing left to do. This function becomes a no-op.
11443 static int doAutoDetectRestore(ShellState
*p
, const char *zSql
){
11444 int rc
= SQLITE_OK
;
11446 if( p
->eRestoreState
<7 ){
11447 switch( p
->eRestoreState
){
11449 const char *zExpect
= "PRAGMA foreign_keys=OFF;";
11450 assert( strlen(zExpect
)==24 );
11451 if( p
->bSafeMode
==0 && memcmp(zSql
, zExpect
, 25)==0 ){
11452 p
->eRestoreState
= 1;
11454 p
->eRestoreState
= 7;
11461 const char *zExpect
= "BEGIN TRANSACTION;";
11462 assert( strlen(zExpect
)==18 );
11463 if( memcmp(zSql
, zExpect
, 19)==0 ){
11464 /* Now check if the database is empty. */
11465 const char *zQuery
= "SELECT 1 FROM sqlite_schema LIMIT 1";
11466 sqlite3_stmt
*pStmt
= 0;
11469 shellPrepare(p
->db
, &rc
, zQuery
, &pStmt
);
11470 if( rc
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
11473 shellFinalize(&rc
, pStmt
);
11475 if( bIsDump
&& rc
==SQLITE_OK
){
11478 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, -1, &bDefense
);
11479 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DQS_DDL
, -1, &bDqsDdl
);
11480 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, 0, 0);
11481 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DQS_DDL
, 1, 0);
11482 p
->eRestoreState
= (bDefense
? 2 : 0) + (bDqsDdl
? 4 : 0);
11484 p
->eRestoreState
= 7;
11490 if( sqlite3_get_autocommit(p
->db
) ){
11491 if( (p
->eRestoreState
& 2) ){
11492 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, 1, 0);
11494 if( (p
->eRestoreState
& 4) ){
11495 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DQS_DDL
, 0, 0);
11497 p
->eRestoreState
= 7;
11508 ** Run a single line of SQL. Return the number of errors.
11510 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
11515 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
11516 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
11518 rc
= shell_exec(p
, zSql
, &zErrMsg
);
11520 if( rc
|| zErrMsg
){
11522 const char *zErrorTail
;
11523 const char *zErrorType
;
11525 zErrorType
= "Error";
11526 zErrorTail
= sqlite3_errmsg(p
->db
);
11527 }else if( cli_strncmp(zErrMsg
, "in prepare, ",12)==0 ){
11528 zErrorType
= "Parse error";
11529 zErrorTail
= &zErrMsg
[12];
11530 }else if( cli_strncmp(zErrMsg
, "stepping, ", 10)==0 ){
11531 zErrorType
= "Runtime error";
11532 zErrorTail
= &zErrMsg
[10];
11534 zErrorType
= "Error";
11535 zErrorTail
= zErrMsg
;
11537 if( in
!=0 || !stdin_is_interactive
){
11538 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
11539 "%s near line %d:", zErrorType
, startline
);
11541 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "%s:", zErrorType
);
11543 eputf("%s %s\n", zPrefix
, zErrorTail
);
11544 sqlite3_free(zErrMsg
);
11547 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
11548 char zLineBuf
[2000];
11549 sqlite3_snprintf(sizeof(zLineBuf
), zLineBuf
,
11550 "changes: %lld total_changes: %lld",
11551 sqlite3_changes64(p
->db
), sqlite3_total_changes64(p
->db
));
11552 oputf("%s\n", zLineBuf
);
11555 if( doAutoDetectRestore(p
, zSql
) ) return 1;
11559 static void echo_group_input(ShellState
*p
, const char *zDo
){
11560 if( ShellHasFlag(p
, SHFLG_Echo
) ) oputf("%s\n", zDo
);
11563 #ifdef SQLITE_SHELL_FIDDLE
11565 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11566 ** impl because we need the global shellState and cannot access it from that
11567 ** function without moving lots of code around (creating a larger/messier diff).
11569 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
11570 /* Parse the next line from shellState.wasm.zInput. */
11571 const char *zBegin
= shellState
.wasm
.zPos
;
11572 const char *z
= zBegin
;
11576 UNUSED_PARAMETER(in
);
11577 UNUSED_PARAMETER(isContinuation
);
11581 while(*z
&& isspace(*z
)) ++z
;
11583 for(; *z
&& '\n'!=*z
; ++nZ
, ++z
){}
11584 if(nZ
>0 && '\r'==zBegin
[nZ
-1]){
11587 shellState
.wasm
.zPos
= z
;
11588 zLine
= realloc(zPrior
, nZ
+1);
11589 shell_check_oom(zLine
);
11590 memcpy(zLine
, zBegin
, nZ
);
11594 #endif /* SQLITE_SHELL_FIDDLE */
11597 ** Read input from *in and process it. If *in==0 then input
11598 ** is interactive - the user is typing it it. Otherwise, input
11599 ** is coming from a file or device. A prompt is issued and history
11600 ** is saved only if input is interactive. An interrupt signal will
11601 ** cause this routine to exit immediately, unless input is interactive.
11603 ** Return the number of errors.
11605 static int process_input(ShellState
*p
){
11606 char *zLine
= 0; /* A single input line */
11607 char *zSql
= 0; /* Accumulated SQL text */
11608 i64 nLine
; /* Length of current line */
11609 i64 nSql
= 0; /* Bytes of zSql[] used */
11610 i64 nAlloc
= 0; /* Allocated zSql[] space */
11611 int rc
; /* Error code */
11612 int errCnt
= 0; /* Number of errors seen */
11613 i64 startline
= 0; /* Line number for start of current input */
11614 QuickScanState qss
= QSS_Start
; /* Accumulated line status (so far) */
11616 if( p
->inputNesting
==MAX_INPUT_NESTING
){
11617 /* This will be more informative in a later version. */
11618 eputf("Input nesting limit (%d) reached at line %d."
11619 " Check recursion.\n", MAX_INPUT_NESTING
, p
->lineno
);
11624 CONTINUE_PROMPT_RESET
;
11625 while( errCnt
==0 || !bail_on_error
|| (p
->in
==0 && stdin_is_interactive
) ){
11627 zLine
= one_input_line(p
->in
, zLine
, nSql
>0);
11630 if( p
->in
==0 && stdin_is_interactive
) oputz("\n");
11633 if( seenInterrupt
){
11634 if( p
->in
!=0 ) break;
11638 if( QSS_INPLAIN(qss
)
11639 && line_is_command_terminator(zLine
)
11640 && line_is_complete(zSql
, nSql
) ){
11641 memcpy(zLine
,";",2);
11643 qss
= quickscan(zLine
, qss
, CONTINUE_PROMPT_PSTATE
);
11644 if( QSS_PLAINWHITE(qss
) && nSql
==0 ){
11645 /* Just swallow single-line whitespace */
11646 echo_group_input(p
, zLine
);
11650 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
11651 CONTINUE_PROMPT_RESET
;
11652 echo_group_input(p
, zLine
);
11653 if( zLine
[0]=='.' ){
11654 rc
= do_meta_command(zLine
, p
);
11655 if( rc
==2 ){ /* exit requested */
11664 /* No single-line dispositions remain; accumulate line(s). */
11665 nLine
= strlen(zLine
);
11666 if( nSql
+nLine
+2>=nAlloc
){
11667 /* Grow buffer by half-again increments when big. */
11668 nAlloc
= nSql
+(nSql
>>1)+nLine
+100;
11669 zSql
= realloc(zSql
, nAlloc
);
11670 shell_check_oom(zSql
);
11674 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
11675 assert( nAlloc
>0 && zSql
!=0 );
11676 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
11677 startline
= p
->lineno
;
11680 zSql
[nSql
++] = '\n';
11681 memcpy(zSql
+nSql
, zLine
, nLine
+1);
11684 if( nSql
&& QSS_SEMITERM(qss
) && sqlite3_complete(zSql
) ){
11685 echo_group_input(p
, zSql
);
11686 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11687 CONTINUE_PROMPT_RESET
;
11695 p
->bSafeMode
= p
->bSafeModePersist
;
11697 }else if( nSql
&& QSS_PLAINWHITE(qss
) ){
11698 echo_group_input(p
, zSql
);
11704 /* This may be incomplete. Let the SQL parser deal with that. */
11705 echo_group_input(p
, zSql
);
11706 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11707 CONTINUE_PROMPT_RESET
;
11716 ** Return a pathname which is the user's home directory. A
11717 ** 0 return indicates an error of some kind.
11719 static char *find_home_dir(int clearFlag
){
11720 static char *home_dir
= NULL
;
11726 if( home_dir
) return home_dir
;
11728 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11729 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11731 struct passwd
*pwent
;
11732 uid_t uid
= getuid();
11733 if( (pwent
=getpwuid(uid
)) != NULL
) {
11734 home_dir
= pwent
->pw_dir
;
11739 #if defined(_WIN32_WCE)
11740 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11745 #if defined(_WIN32) || defined(WIN32)
11747 home_dir
= getenv("USERPROFILE");
11752 home_dir
= getenv("HOME");
11755 #if defined(_WIN32) || defined(WIN32)
11757 char *zDrive
, *zPath
;
11759 zDrive
= getenv("HOMEDRIVE");
11760 zPath
= getenv("HOMEPATH");
11761 if( zDrive
&& zPath
){
11762 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
11763 home_dir
= malloc( n
);
11764 if( home_dir
==0 ) return 0;
11765 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
11772 #endif /* !_WIN32_WCE */
11775 i64 n
= strlen(home_dir
) + 1;
11776 char *z
= malloc( n
);
11777 if( z
) memcpy(z
, home_dir
, n
);
11785 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11786 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11787 ** the path to it, else return 0. The result is cached for
11788 ** subsequent calls.
11790 static const char *find_xdg_config(void){
11791 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11792 || defined(__RTP__) || defined(_WRS_KERNEL)
11795 static int alreadyTried
= 0;
11796 static char *zConfig
= 0;
11797 const char *zXdgHome
;
11799 if( alreadyTried
!=0 ){
11803 zXdgHome
= getenv("XDG_CONFIG_HOME");
11807 zConfig
= sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome
);
11808 shell_check_oom(zConfig
);
11809 if( access(zConfig
,0)!=0 ){
11810 sqlite3_free(zConfig
);
11818 ** Read input from the file given by sqliterc_override. Or if that
11819 ** parameter is NULL, take input from the first of find_xdg_config()
11820 ** or ~/.sqliterc which is found.
11822 ** Returns the number of errors.
11824 static void process_sqliterc(
11825 ShellState
*p
, /* Configuration data */
11826 const char *sqliterc_override
/* Name of config file. NULL to use default */
11828 char *home_dir
= NULL
;
11829 const char *sqliterc
= sqliterc_override
;
11831 FILE *inSaved
= p
->in
;
11832 int savedLineno
= p
->lineno
;
11834 if( sqliterc
== NULL
){
11835 sqliterc
= find_xdg_config();
11837 if( sqliterc
== NULL
){
11838 home_dir
= find_home_dir(0);
11840 eputz("-- warning: cannot find home directory;"
11841 " cannot read ~/.sqliterc\n");
11844 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
11845 shell_check_oom(zBuf
);
11848 p
->in
= fopen(sqliterc
,"rb");
11850 if( stdin_is_interactive
){
11851 eputf("-- Loading resources from %s\n", sqliterc
);
11853 if( process_input(p
) && bail_on_error
) exit(1);
11855 }else if( sqliterc_override
!=0 ){
11856 eputf("cannot open: \"%s\"\n", sqliterc
);
11857 if( bail_on_error
) exit(1);
11860 p
->lineno
= savedLineno
;
11861 sqlite3_free(zBuf
);
11865 ** Show available command line options
11867 static const char zOptions
[] =
11868 " -- treat no subsequent arguments as options\n"
11869 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11870 " -A ARGS... run \".archive ARGS\" and exit\n"
11872 " -append append the database to the end of the file\n"
11873 " -ascii set output mode to 'ascii'\n"
11874 " -bail stop after hitting an error\n"
11875 " -batch force batch I/O\n"
11876 " -box set output mode to 'box'\n"
11877 " -column set output mode to 'column'\n"
11878 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11879 " -csv set output mode to 'csv'\n"
11880 #if !defined(SQLITE_OMIT_DESERIALIZE)
11881 " -deserialize open the database using sqlite3_deserialize()\n"
11883 " -echo print inputs before execution\n"
11884 " -init FILENAME read/process named file\n"
11885 " -[no]header turn headers on or off\n"
11886 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11887 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11889 " -help show this message\n"
11890 " -html set output mode to HTML\n"
11891 " -interactive force interactive I/O\n"
11892 " -json set output mode to 'json'\n"
11893 " -line set output mode to 'line'\n"
11894 " -list set output mode to 'list'\n"
11895 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11896 " -markdown set output mode to 'markdown'\n"
11897 #if !defined(SQLITE_OMIT_DESERIALIZE)
11898 " -maxsize N maximum size for a --deserialize database\n"
11900 " -memtrace trace all memory allocations and deallocations\n"
11901 " -mmap N default mmap size set to N\n"
11902 #ifdef SQLITE_ENABLE_MULTIPLEX
11903 " -multiplex enable the multiplexor VFS\n"
11905 " -newline SEP set output row separator. Default: '\\n'\n"
11906 " -nofollow refuse to open symbolic links to database files\n"
11907 " -nonce STRING set the safe-mode escape nonce\n"
11908 " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n"
11909 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11910 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11911 " -pcachetrace trace all page cache operations\n"
11912 " -quote set output mode to 'quote'\n"
11913 " -readonly open the database read-only\n"
11914 " -safe enable safe-mode\n"
11915 " -separator SEP set output column separator. Default: '|'\n"
11916 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11917 " -sorterref SIZE sorter references threshold size\n"
11919 " -stats print memory stats before each finalize\n"
11920 " -table set output mode to 'table'\n"
11921 " -tabs set output mode to 'tabs'\n"
11922 " -unsafe-testing allow unsafe commands and modes for testing\n"
11923 " -version show SQLite version\n"
11924 " -vfs NAME use NAME as the default VFS\n"
11925 #ifdef SQLITE_ENABLE_VFSTRACE
11926 " -vfstrace enable tracing of all VFS calls\n"
11928 #ifdef SQLITE_HAVE_ZLIB
11929 " -zip open the file as a ZIP Archive\n"
11932 static void usage(int showDetail
){
11933 eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
11934 "FILENAME is the name of an SQLite database. A new database is created\n"
11935 "if the file does not previously exist. Defaults to :memory:.\n", Argv0
);
11937 eputf("OPTIONS include:\n%s", zOptions
);
11939 eputz("Use the -help option for additional information\n");
11945 ** Internal check: Verify that the SQLite is uninitialized. Print a
11946 ** error message if it is initialized.
11948 static void verify_uninitialized(void){
11949 if( sqlite3_config(-1)==SQLITE_MISUSE
){
11950 sputz(stdout
, "WARNING: attempt to configure SQLite after"
11951 " initialization.\n");
11956 ** Initialize the state information in data
11958 static void main_init(ShellState
*data
) {
11959 memset(data
, 0, sizeof(*data
));
11960 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
11961 data
->autoExplain
= 1;
11962 data
->pAuxDb
= &data
->aAuxDb
[0];
11963 memcpy(data
->colSeparator
,SEP_Column
, 2);
11964 memcpy(data
->rowSeparator
,SEP_Row
, 2);
11965 data
->showHeader
= 0;
11966 data
->shellFlgs
= SHFLG_Lookaside
;
11967 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
11968 #if !defined(SQLITE_SHELL_FIDDLE)
11969 verify_uninitialized();
11971 sqlite3_config(SQLITE_CONFIG_URI
, 1);
11972 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
11973 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
11974 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
11978 ** Output text to the console in a font that attracts extra attention.
11980 #if defined(_WIN32) || defined(WIN32)
11981 static void printBold(const char *zText
){
11982 #if !SQLITE_OS_WINRT
11983 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
11984 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
11985 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
11986 SetConsoleTextAttribute(out
,
11987 FOREGROUND_RED
|FOREGROUND_INTENSITY
11990 sputz(stdout
, zText
);
11991 #if !SQLITE_OS_WINRT
11992 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
11996 static void printBold(const char *zText
){
11997 sputf(stdout
, "\033[1m%s\033[0m", zText
);
12002 ** Get the argument to an --option. Throw an error and die if no argument
12005 static char *cmdline_option_value(int argc
, char **argv
, int i
){
12007 eputf("%s: Error: missing argument to %s\n", argv
[0], argv
[argc
-1]);
12013 static void sayAbnormalExit(void){
12014 if( seenInterrupt
) eputz("Program interrupted.\n");
12017 #ifndef SQLITE_SHELL_IS_UTF8
12018 # if (defined(_WIN32) || defined(WIN32)) \
12019 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12020 # define SQLITE_SHELL_IS_UTF8 (0)
12022 # define SQLITE_SHELL_IS_UTF8 (1)
12026 #ifdef SQLITE_SHELL_FIDDLE
12027 # define main fiddle_main
12030 #if SQLITE_SHELL_IS_UTF8
12031 int SQLITE_CDECL
main(int argc
, char **argv
){
12033 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
12036 #ifdef SQLITE_DEBUG
12037 sqlite3_int64 mem_main_enter
= 0;
12040 #ifdef SQLITE_SHELL_FIDDLE
12041 # define data shellState
12044 StreamsAreConsole consStreams
= SAC_NoConsole
;
12046 const char *zInitFile
= 0;
12049 int warnInmemoryDb
= 0;
12052 int nOptsEnd
= argc
;
12054 const char *zVfs
= 0; /* Value of -vfs command-line option */
12055 #if !SQLITE_SHELL_IS_UTF8
12056 char **argvToFree
= 0;
12057 int argcToFree
= 0;
12059 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
12061 #ifdef SQLITE_SHELL_FIDDLE
12062 stdin_is_interactive
= 0;
12063 stdout_is_console
= 1;
12064 data
.wasm
.zDefaultDbName
= "/fiddle.sqlite3";
12066 consStreams
= consoleClassifySetup(stdin
, stdout
, stderr
);
12067 stdin_is_interactive
= (consStreams
& SAC_InConsole
)!=0;
12068 stdout_is_console
= (consStreams
& SAC_OutConsole
)!=0;
12069 atexit(consoleRestore
);
12071 atexit(sayAbnormalExit
);
12072 #ifdef SQLITE_DEBUG
12073 mem_main_enter
= sqlite3_memory_used();
12075 #if !defined(_WIN32_WCE)
12076 if( getenv("SQLITE_DEBUG_BREAK") ){
12077 if( isatty(0) && isatty(2) ){
12078 eputf("attach debugger to process %d and press any key to continue.\n",
12082 #if defined(_WIN32) || defined(WIN32)
12083 #if SQLITE_OS_WINRT
12088 #elif defined(SIGTRAP)
12094 /* Register a valid signal handler early, before much else is done. */
12096 signal(SIGINT
, interrupt_handler
);
12097 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12098 if( !SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
) ){
12099 eputz("No ^C handler.\n");
12103 #if USE_SYSTEM_SQLITE+0!=1
12104 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
12105 eputf("SQLite header and source version mismatch\n%s\n%s\n",
12106 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
12112 /* On Windows, we must translate command-line arguments into UTF-8.
12113 ** The SQLite memory allocator subsystem has to be enabled in order to
12114 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12115 ** subsequent sqlite3_config() calls will work. So copy all results into
12116 ** memory that does not come from the SQLite memory allocator.
12118 #if !SQLITE_SHELL_IS_UTF8
12119 sqlite3_initialize();
12120 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
12121 shell_check_oom(argvToFree
);
12123 argv
= argvToFree
+ argc
;
12124 for(i
=0; i
<argc
; i
++){
12125 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
12127 shell_check_oom(z
);
12129 argv
[i
] = malloc( n
+1 );
12130 shell_check_oom(argv
[i
]);
12131 memcpy(argv
[i
], z
, n
+1);
12132 argvToFree
[i
] = argv
[i
];
12135 sqlite3_shutdown();
12138 assert( argc
>=1 && argv
&& argv
[0] );
12141 #ifdef SQLITE_SHELL_DBNAME_PROC
12143 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12144 ** of a C-function that will provide the name of the database file. Use
12145 ** this compile-time option to embed this shell program in larger
12146 ** applications. */
12147 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12148 SQLITE_SHELL_DBNAME_PROC(&data
.pAuxDb
->zDbFilename
);
12149 warnInmemoryDb
= 0;
12153 /* Do an initial pass through the command-line argument to locate
12154 ** the name of the database file, the name of the initialization file,
12155 ** the size of the alternative malloc heap, options affecting commands
12156 ** or SQL run from the command line, and the first command to execute.
12158 #ifndef SQLITE_SHELL_FIDDLE
12159 verify_uninitialized();
12161 for(i
=1; i
<argc
; i
++){
12164 if( z
[0]!='-' || i
>nOptsEnd
){
12165 if( data
.aAuxDb
->zDbFilename
==0 ){
12166 data
.aAuxDb
->zDbFilename
= z
;
12168 /* Excess arguments are interpreted as SQL (or dot-commands) and
12169 ** mean that nothing is read from stdin */
12172 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
12173 shell_check_oom(azCmd
);
12178 if( z
[1]=='-' ) z
++;
12179 if( cli_strcmp(z
, "-")==0 ){
12182 }else if( cli_strcmp(z
,"-separator")==0
12183 || cli_strcmp(z
,"-nullvalue")==0
12184 || cli_strcmp(z
,"-newline")==0
12185 || cli_strcmp(z
,"-cmd")==0
12187 (void)cmdline_option_value(argc
, argv
, ++i
);
12188 }else if( cli_strcmp(z
,"-init")==0 ){
12189 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
12190 }else if( cli_strcmp(z
,"-interactive")==0 ){
12191 }else if( cli_strcmp(z
,"-batch")==0 ){
12192 /* Need to check for batch mode here to so we can avoid printing
12193 ** informational messages (like from process_sqliterc) before
12194 ** we do the actual processing of arguments later in a second pass.
12196 stdin_is_interactive
= 0;
12197 }else if( cli_strcmp(z
,"-utf8")==0 ){
12198 }else if( cli_strcmp(z
,"-no-utf8")==0 ){
12199 }else if( cli_strcmp(z
,"-no-rowid-in-view")==0 ){
12201 sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW
, &val
);
12203 }else if( cli_strcmp(z
,"-heap")==0 ){
12204 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12206 sqlite3_int64 szHeap
;
12208 zSize
= cmdline_option_value(argc
, argv
, ++i
);
12209 szHeap
= integerValue(zSize
);
12210 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
12211 verify_uninitialized();
12212 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
12214 (void)cmdline_option_value(argc
, argv
, ++i
);
12216 }else if( cli_strcmp(z
,"-pagecache")==0 ){
12217 sqlite3_int64 n
, sz
;
12218 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12219 if( sz
>70000 ) sz
= 70000;
12221 n
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12222 if( sz
>0 && n
>0 && 0xffffffffffffLL
/sz
<n
){
12223 n
= 0xffffffffffffLL
/sz
;
12225 verify_uninitialized();
12226 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
12227 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
12228 data
.shellFlgs
|= SHFLG_Pagecache
;
12229 }else if( cli_strcmp(z
,"-lookaside")==0 ){
12231 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12233 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12235 verify_uninitialized();
12236 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
12237 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
12238 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
12240 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12241 verify_uninitialized();
12243 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
); break;
12244 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD
); break;
12245 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED
); break;
12247 #ifdef SQLITE_ENABLE_VFSTRACE
12248 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
12249 extern int vfstrace_register(
12250 const char *zTraceName
,
12251 const char *zOldVfsName
,
12252 int (*xOut
)(const char*,void*),
12256 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
12258 #ifdef SQLITE_ENABLE_MULTIPLEX
12259 }else if( cli_strcmp(z
,"-multiplex")==0 ){
12260 extern int sqlite3_multiplex_initialize(const char*,int);
12261 sqlite3_multiplex_initialize(0, 1);
12263 }else if( cli_strcmp(z
,"-mmap")==0 ){
12264 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12265 verify_uninitialized();
12266 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
12267 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
12268 }else if( cli_strcmp(z
,"-sorterref")==0 ){
12269 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12270 verify_uninitialized();
12271 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
12273 }else if( cli_strcmp(z
,"-vfs")==0 ){
12274 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
12275 #ifdef SQLITE_HAVE_ZLIB
12276 }else if( cli_strcmp(z
,"-zip")==0 ){
12277 data
.openMode
= SHELL_OPEN_ZIPFILE
;
12279 }else if( cli_strcmp(z
,"-append")==0 ){
12280 data
.openMode
= SHELL_OPEN_APPENDVFS
;
12281 #ifndef SQLITE_OMIT_DESERIALIZE
12282 }else if( cli_strcmp(z
,"-deserialize")==0 ){
12283 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
12284 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
12285 data
.szMax
= integerValue(argv
[++i
]);
12287 }else if( cli_strcmp(z
,"-readonly")==0 ){
12288 data
.openMode
= SHELL_OPEN_READONLY
;
12289 }else if( cli_strcmp(z
,"-nofollow")==0 ){
12290 data
.openFlags
= SQLITE_OPEN_NOFOLLOW
;
12291 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12292 }else if( cli_strncmp(z
, "-A",2)==0 ){
12293 /* All remaining command-line arguments are passed to the ".archive"
12294 ** command, so ignore them */
12297 }else if( cli_strcmp(z
, "-memtrace")==0 ){
12298 sqlite3MemTraceActivate(stderr
);
12299 }else if( cli_strcmp(z
, "-pcachetrace")==0 ){
12300 sqlite3PcacheTraceActivate(stderr
);
12301 }else if( cli_strcmp(z
,"-bail")==0 ){
12303 }else if( cli_strcmp(z
,"-nonce")==0 ){
12305 data
.zNonce
= strdup(cmdline_option_value(argc
, argv
, ++i
));
12306 }else if( cli_strcmp(z
,"-unsafe-testing")==0 ){
12307 ShellSetFlag(&data
,SHFLG_TestingMode
);
12308 }else if( cli_strcmp(z
,"-safe")==0 ){
12309 /* no-op - catch this on the second pass */
12312 #ifndef SQLITE_SHELL_FIDDLE
12313 verify_uninitialized();
12317 #ifdef SQLITE_SHELL_INIT_PROC
12319 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12320 ** of a C-function that will perform initialization actions on SQLite that
12321 ** occur just before or after sqlite3_initialize(). Use this compile-time
12322 ** option to embed this shell program in larger applications. */
12323 extern void SQLITE_SHELL_INIT_PROC(void);
12324 SQLITE_SHELL_INIT_PROC();
12327 /* All the sqlite3_config() calls have now been made. So it is safe
12328 ** to call sqlite3_initialize() and process any command line -vfs option. */
12329 sqlite3_initialize();
12333 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
12335 sqlite3_vfs_register(pVfs
, 1);
12337 eputf("no such VFS: \"%s\"\n", zVfs
);
12342 if( data
.pAuxDb
->zDbFilename
==0 ){
12343 #ifndef SQLITE_OMIT_MEMORYDB
12344 data
.pAuxDb
->zDbFilename
= ":memory:";
12345 warnInmemoryDb
= argc
==1;
12347 eputf("%s: Error: no database filename specified\n", Argv0
);
12352 #ifndef SQLITE_SHELL_FIDDLE
12353 sqlite3_appendvfs_init(0,0,0);
12356 /* Go ahead and open the database file if it already exists. If the
12357 ** file does not exist, delay opening it. This prevents empty database
12358 ** files from being created if a user mistypes the database name argument
12359 ** to the sqlite command-line tool.
12361 if( access(data
.pAuxDb
->zDbFilename
, 0)==0 ){
12365 /* Process the initialization file if there is one. If no -init option
12366 ** is given on the command line, look for a file named ~/.sqliterc and
12367 ** try to process it.
12369 process_sqliterc(&data
,zInitFile
);
12371 /* Make a second pass through the command-line argument and set
12372 ** options. This second pass is delayed until after the initialization
12373 ** file is processed so that the command-line arguments will override
12374 ** settings in the initialization file.
12376 for(i
=1; i
<argc
; i
++){
12378 if( z
[0]!='-' || i
>=nOptsEnd
) continue;
12379 if( z
[1]=='-' ){ z
++; }
12380 if( cli_strcmp(z
,"-init")==0 ){
12382 }else if( cli_strcmp(z
,"-html")==0 ){
12383 data
.mode
= MODE_Html
;
12384 }else if( cli_strcmp(z
,"-list")==0 ){
12385 data
.mode
= MODE_List
;
12386 }else if( cli_strcmp(z
,"-quote")==0 ){
12387 data
.mode
= MODE_Quote
;
12388 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
, SEP_Comma
);
12389 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
, SEP_Row
);
12390 }else if( cli_strcmp(z
,"-line")==0 ){
12391 data
.mode
= MODE_Line
;
12392 }else if( cli_strcmp(z
,"-column")==0 ){
12393 data
.mode
= MODE_Column
;
12394 }else if( cli_strcmp(z
,"-json")==0 ){
12395 data
.mode
= MODE_Json
;
12396 }else if( cli_strcmp(z
,"-markdown")==0 ){
12397 data
.mode
= MODE_Markdown
;
12398 }else if( cli_strcmp(z
,"-table")==0 ){
12399 data
.mode
= MODE_Table
;
12400 }else if( cli_strcmp(z
,"-box")==0 ){
12401 data
.mode
= MODE_Box
;
12402 }else if( cli_strcmp(z
,"-csv")==0 ){
12403 data
.mode
= MODE_Csv
;
12404 memcpy(data
.colSeparator
,",",2);
12405 #ifdef SQLITE_HAVE_ZLIB
12406 }else if( cli_strcmp(z
,"-zip")==0 ){
12407 data
.openMode
= SHELL_OPEN_ZIPFILE
;
12409 }else if( cli_strcmp(z
,"-append")==0 ){
12410 data
.openMode
= SHELL_OPEN_APPENDVFS
;
12411 #ifndef SQLITE_OMIT_DESERIALIZE
12412 }else if( cli_strcmp(z
,"-deserialize")==0 ){
12413 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
12414 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
12415 data
.szMax
= integerValue(argv
[++i
]);
12417 }else if( cli_strcmp(z
,"-readonly")==0 ){
12418 data
.openMode
= SHELL_OPEN_READONLY
;
12419 }else if( cli_strcmp(z
,"-nofollow")==0 ){
12420 data
.openFlags
|= SQLITE_OPEN_NOFOLLOW
;
12421 }else if( cli_strcmp(z
,"-ascii")==0 ){
12422 data
.mode
= MODE_Ascii
;
12423 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,SEP_Unit
);
12424 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,SEP_Record
);
12425 }else if( cli_strcmp(z
,"-tabs")==0 ){
12426 data
.mode
= MODE_List
;
12427 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,SEP_Tab
);
12428 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,SEP_Row
);
12429 }else if( cli_strcmp(z
,"-separator")==0 ){
12430 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
12431 "%s",cmdline_option_value(argc
,argv
,++i
));
12432 }else if( cli_strcmp(z
,"-newline")==0 ){
12433 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
12434 "%s",cmdline_option_value(argc
,argv
,++i
));
12435 }else if( cli_strcmp(z
,"-nullvalue")==0 ){
12436 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
12437 "%s",cmdline_option_value(argc
,argv
,++i
));
12438 }else if( cli_strcmp(z
,"-header")==0 ){
12439 data
.showHeader
= 1;
12440 ShellSetFlag(&data
, SHFLG_HeaderSet
);
12441 }else if( cli_strcmp(z
,"-noheader")==0 ){
12442 data
.showHeader
= 0;
12443 ShellSetFlag(&data
, SHFLG_HeaderSet
);
12444 }else if( cli_strcmp(z
,"-echo")==0 ){
12445 ShellSetFlag(&data
, SHFLG_Echo
);
12446 }else if( cli_strcmp(z
,"-eqp")==0 ){
12447 data
.autoEQP
= AUTOEQP_on
;
12448 }else if( cli_strcmp(z
,"-eqpfull")==0 ){
12449 data
.autoEQP
= AUTOEQP_full
;
12450 }else if( cli_strcmp(z
,"-stats")==0 ){
12452 }else if( cli_strcmp(z
,"-scanstats")==0 ){
12453 data
.scanstatsOn
= 1;
12454 }else if( cli_strcmp(z
,"-backslash")==0 ){
12455 /* Undocumented command-line option: -backslash
12456 ** Causes C-style backslash escapes to be evaluated in SQL statements
12457 ** prior to sending the SQL into SQLite. Useful for injecting
12458 ** crazy bytes in the middle of SQL statements for testing and debugging.
12460 ShellSetFlag(&data
, SHFLG_Backslash
);
12461 }else if( cli_strcmp(z
,"-bail")==0 ){
12462 /* No-op. The bail_on_error flag should already be set. */
12463 }else if( cli_strcmp(z
,"-version")==0 ){
12464 sputf(stdout
, "%s %s (%d-bit)\n",
12465 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
12467 }else if( cli_strcmp(z
,"-interactive")==0 ){
12468 /* Need to check for interactive override here to so that it can
12469 ** affect console setup (for Windows only) and testing thereof.
12471 stdin_is_interactive
= 1;
12472 }else if( cli_strcmp(z
,"-batch")==0 ){
12473 /* already handled */
12474 }else if( cli_strcmp(z
,"-utf8")==0 ){
12475 /* already handled */
12476 }else if( cli_strcmp(z
,"-no-utf8")==0 ){
12477 /* already handled */
12478 }else if( cli_strcmp(z
,"-no-rowid-in-view")==0 ){
12479 /* already handled */
12480 }else if( cli_strcmp(z
,"-heap")==0 ){
12482 }else if( cli_strcmp(z
,"-pagecache")==0 ){
12484 }else if( cli_strcmp(z
,"-lookaside")==0 ){
12486 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
12488 }else if( cli_strcmp(z
,"-nonce")==0 ){
12490 }else if( cli_strcmp(z
,"-mmap")==0 ){
12492 }else if( cli_strcmp(z
,"-memtrace")==0 ){
12494 }else if( cli_strcmp(z
,"-pcachetrace")==0 ){
12496 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12497 }else if( cli_strcmp(z
,"-sorterref")==0 ){
12500 }else if( cli_strcmp(z
,"-vfs")==0 ){
12502 #ifdef SQLITE_ENABLE_VFSTRACE
12503 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
12506 #ifdef SQLITE_ENABLE_MULTIPLEX
12507 }else if( cli_strcmp(z
,"-multiplex")==0 ){
12510 }else if( cli_strcmp(z
,"-help")==0 ){
12512 }else if( cli_strcmp(z
,"-cmd")==0 ){
12513 /* Run commands that follow -cmd first and separately from commands
12514 ** that simply appear on the command-line. This seems goofy. It would
12515 ** be better if all commands ran in the order that they appear. But
12516 ** we retain the goofy behavior for historical compatibility. */
12517 if( i
==argc
-1 ) break;
12518 z
= cmdline_option_value(argc
,argv
,++i
);
12520 rc
= do_meta_command(z
, &data
);
12521 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
12524 rc
= shell_exec(&data
, z
, &zErrMsg
);
12526 eputf("Error: %s\n", zErrMsg
);
12527 if( bail_on_error
) return rc
!=0 ? rc
: 1;
12529 eputf("Error: unable to process SQL \"%s\"\n", z
);
12530 if( bail_on_error
) return rc
;
12533 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12534 }else if( cli_strncmp(z
, "-A", 2)==0 ){
12536 eputf("Error: cannot mix regular SQL or dot-commands"
12537 " with \"%s\"\n", z
);
12540 open_db(&data
, OPEN_DB_ZIPFILE
);
12543 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
12545 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
12550 }else if( cli_strcmp(z
,"-safe")==0 ){
12551 data
.bSafeMode
= data
.bSafeModePersist
= 1;
12552 }else if( cli_strcmp(z
,"-unsafe-testing")==0 ){
12553 /* Acted upon in first pass. */
12555 eputf("%s: Error: unknown option: %s\n", Argv0
, z
);
12556 eputz("Use -help for a list of options.\n");
12559 data
.cMode
= data
.mode
;
12563 /* Run all arguments that do not begin with '-' as if they were separate
12564 ** command-line inputs, except for the argToSkip argument which contains
12565 ** the database filename.
12567 for(i
=0; i
<nCmd
; i
++){
12568 if( azCmd
[i
][0]=='.' ){
12569 rc
= do_meta_command(azCmd
[i
], &data
);
12572 return rc
==2 ? 0 : rc
;
12576 echo_group_input(&data
, azCmd
[i
]);
12577 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
12578 if( zErrMsg
|| rc
){
12580 eputf("Error: %s\n", zErrMsg
);
12582 eputf("Error: unable to process SQL: %s\n", azCmd
[i
]);
12584 sqlite3_free(zErrMsg
);
12586 return rc
!=0 ? rc
: 1;
12591 /* Run commands received from standard input
12593 if( stdin_is_interactive
){
12597 #if CIO_WIN_WC_XLATE
12598 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
12600 # define SHELL_CIO_CHAR_SET ""
12602 sputf(stdout
, "SQLite version %s %.19s%s\n" /*extra-version-info*/
12603 "Enter \".help\" for usage hints.\n",
12604 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET
);
12605 if( warnInmemoryDb
){
12606 sputz(stdout
, "Connected to a ");
12607 printBold("transient in-memory database");
12608 sputz(stdout
, ".\nUse \".open FILENAME\" to reopen on a"
12609 " persistent database.\n");
12611 zHistory
= getenv("SQLITE_HISTORY");
12613 zHistory
= strdup(zHistory
);
12614 }else if( (zHome
= find_home_dir(0))!=0 ){
12615 nHistory
= strlen30(zHome
) + 20;
12616 if( (zHistory
= malloc(nHistory
))!=0 ){
12617 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
12620 if( zHistory
){ shell_read_history(zHistory
); }
12621 #if HAVE_READLINE || HAVE_EDITLINE
12622 rl_attempted_completion_function
= readline_completion
;
12623 #elif HAVE_LINENOISE
12624 linenoiseSetCompletionCallback(linenoise_completion
);
12627 rc
= process_input(&data
);
12629 shell_stifle_history(2000);
12630 shell_write_history(zHistory
);
12635 rc
= process_input(&data
);
12638 #ifndef SQLITE_SHELL_FIDDLE
12639 /* In WASM mode we have to leave the db state in place so that
12640 ** client code can "push" SQL into it after this call returns. */
12642 set_table_name(&data
, 0);
12644 session_close_all(&data
, -1);
12647 for(i
=0; i
<ArraySize(data
.aAuxDb
); i
++){
12648 sqlite3_free(data
.aAuxDb
[i
].zFreeOnClose
);
12649 if( data
.aAuxDb
[i
].db
){
12650 session_close_all(&data
, i
);
12651 close_db(data
.aAuxDb
[i
].db
);
12655 output_reset(&data
);
12656 data
.doXdgOpen
= 0;
12657 clearTempFile(&data
);
12658 #if !SQLITE_SHELL_IS_UTF8
12659 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
12662 free(data
.colWidth
);
12664 /* Clear the global data structure so that valgrind will detect memory
12666 memset(&data
, 0, sizeof(data
));
12667 #ifdef SQLITE_DEBUG
12668 if( sqlite3_memory_used()>mem_main_enter
){
12669 eputf("Memory leaked: %u bytes\n",
12670 (unsigned int)(sqlite3_memory_used()-mem_main_enter
));
12673 #endif /* !SQLITE_SHELL_FIDDLE */
12678 #ifdef SQLITE_SHELL_FIDDLE
12679 /* Only for emcc experimentation purposes. */
12680 int fiddle_experiment(int a
,int b
){
12685 ** Returns a pointer to the current DB handle.
12687 sqlite3
* fiddle_db_handle(){
12692 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12693 ** "main" is assumed. Returns 0 if no db with the given name is
12696 sqlite3_vfs
* fiddle_db_vfs(const char *zDbName
){
12697 sqlite3_vfs
* pVfs
= 0;
12699 sqlite3_file_control(globalDb
, zDbName
? zDbName
: "main",
12700 SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
12705 /* Only for emcc experimentation purposes. */
12706 sqlite3
* fiddle_db_arg(sqlite3
*arg
){
12707 printf("fiddle_db_arg(%p)\n", (const void*)arg
);
12712 ** Intended to be called via a SharedWorker() while a separate
12713 ** SharedWorker() (which manages the wasm module) is performing work
12714 ** which should be interrupted. Unfortunately, SharedWorker is not
12715 ** portable enough to make real use of.
12717 void fiddle_interrupt(void){
12718 if( globalDb
) sqlite3_interrupt(globalDb
);
12722 ** Returns the filename of the given db name, assuming "main" if
12723 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12725 const char * fiddle_db_filename(const char * zDbName
){
12727 ? sqlite3_db_filename(globalDb
, zDbName
? zDbName
: "main")
12732 ** Completely wipes out the contents of the currently-opened database
12733 ** but leaves its storage intact for reuse.
12735 void fiddle_reset_db(void){
12737 int rc
= sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 1, 0);
12738 if( 0==rc
) rc
= sqlite3_exec(globalDb
, "VACUUM", 0, 0, 0);
12739 sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 0, 0);
12744 ** Uses the current database's VFS xRead to stream the db file's
12745 ** contents out to the given callback. The callback gets a single
12746 ** chunk of size n (its 2nd argument) on each call and must return 0
12747 ** on success, non-0 on error. This function returns 0 on success,
12748 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12749 ** code from the callback. Note that this is not thread-friendly: it
12750 ** expects that it will be the only thread reading the db file and
12751 ** takes no measures to ensure that is the case.
12753 int fiddle_export_db( int (*xCallback
)(unsigned const char *zOut
, int n
) ){
12754 sqlite3_int64 nSize
= 0;
12755 sqlite3_int64 nPos
= 0;
12756 sqlite3_file
* pFile
= 0;
12757 unsigned char buf
[1024 * 8];
12758 int nBuf
= (int)sizeof(buf
);
12759 int rc
= shellState
.db
12760 ? sqlite3_file_control(shellState
.db
, "main",
12761 SQLITE_FCNTL_FILE_POINTER
, &pFile
)
12763 if( rc
) return rc
;
12764 rc
= pFile
->pMethods
->xFileSize(pFile
, &nSize
);
12765 if( rc
) return rc
;
12767 /* DB size is not an even multiple of the buffer size. Reduce
12768 ** buffer size so that we do not unduly inflate the db size when
12770 if(0 == nSize
% 4096) nBuf
= 4096;
12771 else if(0 == nSize
% 2048) nBuf
= 2048;
12772 else if(0 == nSize
% 1024) nBuf
= 1024;
12775 for( ; 0==rc
&& nPos
<nSize
; nPos
+= nBuf
){
12776 rc
= pFile
->pMethods
->xRead(pFile
, buf
, nBuf
, nPos
);
12777 if(SQLITE_IOERR_SHORT_READ
== rc
){
12778 rc
= (nPos
+ nBuf
) < nSize
? rc
: 0/*assume EOF*/;
12780 if( 0==rc
) rc
= xCallback(buf
, nBuf
);
12786 ** Trivial exportable function for emscripten. It processes zSql as if
12787 ** it were input to the sqlite3 shell and redirects all output to the
12788 ** wasm binding. fiddle_main() must have been called before this
12789 ** is called, or results are undefined.
12791 void fiddle_exec(const char * zSql
){
12793 if('.'==*zSql
) puts(zSql
);
12794 shellState
.wasm
.zInput
= zSql
;
12795 shellState
.wasm
.zPos
= zSql
;
12796 process_input(&shellState
);
12797 shellState
.wasm
.zInput
= shellState
.wasm
.zPos
= 0;
12800 #endif /* SQLITE_SHELL_FIDDLE */