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
103 typedef sqlite3_int64 i64
;
104 typedef sqlite3_uint64 u64
;
105 typedef unsigned char u8
;
106 #if SQLITE_USER_AUTHENTICATION
107 # include "sqlite3userauth.h"
112 #if !defined(_WIN32) && !defined(WIN32)
114 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
118 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
121 # define GETPID getpid
122 # if defined(__MINGW32__)
123 # define DIRENT dirent
125 # define S_ISLNK(mode) (0)
129 # define GETPID (int)GetCurrentProcessId
131 #include <sys/types.h>
132 #include <sys/stat.h>
135 # include <readline/readline.h>
136 # include <readline/history.h>
140 # include <editline/readline.h>
143 #if HAVE_EDITLINE || HAVE_READLINE
145 # define shell_add_history(X) add_history(X)
146 # define shell_read_history(X) read_history(X)
147 # define shell_write_history(X) write_history(X)
148 # define shell_stifle_history(X) stifle_history(X)
149 # define shell_readline(X) readline(X)
153 # include "linenoise.h"
154 # define shell_add_history(X) linenoiseHistoryAdd(X)
155 # define shell_read_history(X) linenoiseHistoryLoad(X)
156 # define shell_write_history(X) linenoiseHistorySave(X)
157 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
158 # define shell_readline(X) linenoise(X)
162 # define shell_read_history(X)
163 # define shell_write_history(X)
164 # define shell_stifle_history(X)
166 # define SHELL_USE_LOCAL_GETLINE 1
169 #ifndef deliberate_fall_through
170 /* Quiet some compilers about some of our intentional code. */
171 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
172 # define deliberate_fall_through __attribute__((fallthrough));
174 # define deliberate_fall_through
178 #if defined(_WIN32) || defined(WIN32)
180 # define SQLITE_OMIT_POPEN 1
184 # define isatty(h) _isatty(h)
186 # define access(f,m) _access((f),(m))
189 # define unlink _unlink
192 # define strdup _strdup
195 # define popen _popen
197 # define pclose _pclose
200 /* Make sure isatty() has a prototype. */
201 extern int isatty(int);
203 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
204 /* popen and pclose are not C89 functions and so are
205 ** sometimes omitted from the <stdio.h> header */
206 extern FILE *popen(const char*,const char*);
207 extern int pclose(FILE*);
209 # define SQLITE_OMIT_POPEN 1
213 #if defined(_WIN32_WCE)
214 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
215 * thus we always assume that we have a console. That can be
216 * overridden with the -batch command line option.
221 /* ctype macros that work with signed characters */
222 #define IsSpace(X) isspace((unsigned char)X)
223 #define IsDigit(X) isdigit((unsigned char)X)
224 #define ToLower(X) (char)tolower((unsigned char)X)
226 #if defined(_WIN32) || defined(WIN32)
232 /* string conversion routines only needed on Win32 */
233 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
234 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
235 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
236 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
239 /* On Windows, we normally run with output mode of TEXT so that \n characters
240 ** are automatically translated into \r\n. However, this behavior needs
241 ** to be disabled in some cases (ex: when generating CSV output and when
242 ** rendering quoted strings that contain \n characters). The following
243 ** routines take care of that.
245 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
246 static void setBinaryMode(FILE *file
, int isOutput
){
247 if( isOutput
) fflush(file
);
248 _setmode(_fileno(file
), _O_BINARY
);
250 static void setTextMode(FILE *file
, int isOutput
){
251 if( isOutput
) fflush(file
);
252 _setmode(_fileno(file
), _O_TEXT
);
255 # define setBinaryMode(X,Y)
256 # define setTextMode(X,Y)
259 /* True if the timer is enabled */
260 static int enableTimer
= 0;
262 /* A version of strcmp() that works with NULL values */
263 static int cli_strcmp(const char *a
, const char *b
){
268 static int cli_strncmp(const char *a
, const char *b
, size_t n
){
271 return strncmp(a
,b
,n
);
274 /* Return the current wall-clock time */
275 static sqlite3_int64
timeOfDay(void){
276 static sqlite3_vfs
*clockVfs
= 0;
278 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
279 if( clockVfs
==0 ) return 0; /* Never actually happens */
280 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
281 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
284 clockVfs
->xCurrentTime(clockVfs
, &r
);
285 t
= (sqlite3_int64
)(r
*86400000.0);
290 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
291 #include <sys/time.h>
292 #include <sys/resource.h>
294 /* VxWorks does not support getrusage() as far as we can determine */
295 #if defined(_WRS_KERNEL) || defined(__RTP__)
297 struct timeval ru_utime
; /* user CPU time used */
298 struct timeval ru_stime
; /* system CPU time used */
300 #define getrusage(A,B) memset(B,0,sizeof(*B))
303 /* Saved resource information for the beginning of an operation */
304 static struct rusage sBegin
; /* CPU time at start */
305 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
308 ** Begin timing an operation
310 static void beginTimer(void){
312 getrusage(RUSAGE_SELF
, &sBegin
);
313 iBegin
= timeOfDay();
317 /* Return the difference of two time_structs in seconds */
318 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
319 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
320 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
324 ** Print the timing results.
326 static void endTimer(void){
328 sqlite3_int64 iEnd
= timeOfDay();
330 getrusage(RUSAGE_SELF
, &sEnd
);
331 printf("Run Time: real %.3f user %f sys %f\n",
332 (iEnd
- iBegin
)*0.001,
333 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
334 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
338 #define BEGIN_TIMER beginTimer()
339 #define END_TIMER endTimer()
342 #elif (defined(_WIN32) || defined(WIN32))
344 /* Saved resource information for the beginning of an operation */
345 static HANDLE hProcess
;
346 static FILETIME ftKernelBegin
;
347 static FILETIME ftUserBegin
;
348 static sqlite3_int64 ftWallBegin
;
349 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
350 LPFILETIME
, LPFILETIME
);
351 static GETPROCTIMES getProcessTimesAddr
= NULL
;
354 ** Check to see if we have timer support. Return 1 if necessary
355 ** support found (or found previously).
357 static int hasTimer(void){
358 if( getProcessTimesAddr
){
362 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
363 ** versions. See if the version we are running on has it, and if it
364 ** does, save off a pointer to it and the current process handle.
366 hProcess
= GetCurrentProcess();
368 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
369 if( NULL
!= hinstLib
){
370 getProcessTimesAddr
=
371 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
372 if( NULL
!= getProcessTimesAddr
){
375 FreeLibrary(hinstLib
);
384 ** Begin timing an operation
386 static void beginTimer(void){
387 if( enableTimer
&& getProcessTimesAddr
){
388 FILETIME ftCreation
, ftExit
;
389 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
390 &ftKernelBegin
,&ftUserBegin
);
391 ftWallBegin
= timeOfDay();
395 /* Return the difference of two FILETIME structs in seconds */
396 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
397 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
398 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
399 return (double) ((i64End
- i64Start
) / 10000000.0);
403 ** Print the timing results.
405 static void endTimer(void){
406 if( enableTimer
&& getProcessTimesAddr
){
407 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
408 sqlite3_int64 ftWallEnd
= timeOfDay();
409 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
410 printf("Run Time: real %.3f user %f sys %f\n",
411 (ftWallEnd
- ftWallBegin
)*0.001,
412 timeDiff(&ftUserBegin
, &ftUserEnd
),
413 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
417 #define BEGIN_TIMER beginTimer()
418 #define END_TIMER endTimer()
419 #define HAS_TIMER hasTimer()
428 ** Used to prevent warnings about unused parameters
430 #define UNUSED_PARAMETER(x) (void)(x)
433 ** Number of elements in an array
435 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
438 ** If the following flag is set, then command execution stops
439 ** at an error if we are not interactive.
441 static int bail_on_error
= 0;
444 ** Threat stdin as an interactive input if the following variable
445 ** is true. Otherwise, assume stdin is connected to a file or pipe.
447 static int stdin_is_interactive
= 1;
450 ** On Windows systems we have to know if standard output is a console
451 ** in order to translate UTF-8 into MBCS. The following variable is
452 ** true if translation is required.
454 static int stdout_is_console
= 1;
457 ** The following is the open SQLite database. We make a pointer
458 ** to this database a static variable so that it can be accessed
459 ** by the SIGINT handler to interrupt database processing.
461 static sqlite3
*globalDb
= 0;
464 ** True if an interrupt (Control-C) has been received.
466 static volatile int seenInterrupt
= 0;
469 ** This is the name of our program. It is set in main(), used
470 ** in a number of other places, mostly for error messages.
475 ** Prompt strings. Initialized in main. Settable with
476 ** .prompt main continue
478 #define PROMPT_LEN_MAX 20
479 /* First line prompt. default: "sqlite> " */
480 static char mainPrompt
[PROMPT_LEN_MAX
];
481 /* Continuation prompt. default: " ...> " */
482 static char continuePrompt
[PROMPT_LEN_MAX
];
484 /* This is variant of the standard-library strncpy() routine with the
485 ** one change that the destination string is always zero-terminated, even
486 ** if there is no zero-terminator in the first n-1 characters of the source
489 static char *shell_strncpy(char *dest
, const char *src
, size_t n
){
491 for(i
=0; i
<n
-1 && src
[i
]!=0; i
++) dest
[i
] = src
[i
];
497 ** Optionally disable dynamic continuation prompt.
498 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
499 ** or open parentheses level if non-zero, or continuation prompt as set.
500 ** This facility interacts with the scanner and process_input() where the
501 ** below 5 macros are used.
503 #ifdef SQLITE_OMIT_DYNAPROMPT
504 # define CONTINUATION_PROMPT continuePrompt
505 # define CONTINUE_PROMPT_RESET
506 # define CONTINUE_PROMPT_AWAITS(p,s)
507 # define CONTINUE_PROMPT_AWAITC(p,c)
508 # define CONTINUE_PAREN_INCR(p,n)
509 # define CONTINUE_PROMPT_PSTATE 0
510 typedef void *t_NoDynaPrompt
;
511 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
513 # define CONTINUATION_PROMPT dynamicContinuePrompt()
514 # define CONTINUE_PROMPT_RESET \
515 do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
516 # define CONTINUE_PROMPT_AWAITS(p,s) \
517 if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
518 # define CONTINUE_PROMPT_AWAITC(p,c) \
519 if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
520 # define CONTINUE_PAREN_INCR(p,n) \
521 if(p && stdin_is_interactive) (trackParenLevel(p,n))
522 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
523 typedef struct DynaPrompt
*t_DynaPromptRef
;
524 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
526 static struct DynaPrompt
{
527 char dynamicPrompt
[PROMPT_LEN_MAX
];
530 char *zScannerAwaits
;
531 } dynPrompt
= { {0}, {0}, 0, 0 };
533 /* Record parenthesis nesting level change, or force level to 0. */
534 static void trackParenLevel(struct DynaPrompt
*p
, int ni
){
535 p
->inParenLevel
+= ni
;
536 if( ni
==0 ) p
->inParenLevel
= 0;
537 p
->zScannerAwaits
= 0;
540 /* Record that a lexeme is opened, or closed with args==0. */
541 static void setLexemeOpen(struct DynaPrompt
*p
, char *s
, char c
){
543 p
->zScannerAwaits
= s
;
547 p
->zScannerAwaits
= p
->acAwait
;
551 /* Upon demand, derive the continuation prompt to display. */
552 static char *dynamicContinuePrompt(void){
553 if( continuePrompt
[0]==0
554 || (dynPrompt
.zScannerAwaits
==0 && dynPrompt
.inParenLevel
== 0) ){
555 return continuePrompt
;
557 if( dynPrompt
.zScannerAwaits
){
558 size_t ncp
= strlen(continuePrompt
);
559 size_t ndp
= strlen(dynPrompt
.zScannerAwaits
);
560 if( ndp
> ncp
-3 ) return continuePrompt
;
561 strcpy(dynPrompt
.dynamicPrompt
, dynPrompt
.zScannerAwaits
);
562 while( ndp
<3 ) dynPrompt
.dynamicPrompt
[ndp
++] = ' ';
563 shell_strncpy(dynPrompt
.dynamicPrompt
+3, continuePrompt
+3,
566 if( dynPrompt
.inParenLevel
>9 ){
567 shell_strncpy(dynPrompt
.dynamicPrompt
, "(..", 4);
568 }else if( dynPrompt
.inParenLevel
<0 ){
569 shell_strncpy(dynPrompt
.dynamicPrompt
, ")x!", 4);
571 shell_strncpy(dynPrompt
.dynamicPrompt
, "(x.", 4);
572 dynPrompt
.dynamicPrompt
[2] = (char)('0'+dynPrompt
.inParenLevel
);
574 shell_strncpy(dynPrompt
.dynamicPrompt
+3, continuePrompt
+3, PROMPT_LEN_MAX
-4);
577 return dynPrompt
.dynamicPrompt
;
579 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
582 ** Render output like fprintf(). Except, if the output is going to the
583 ** console and if this is running on a Windows machine, translate the
584 ** output from UTF-8 into MBCS.
586 #if defined(_WIN32) || defined(WIN32)
587 void utf8_printf(FILE *out
, const char *zFormat
, ...){
589 va_start(ap
, zFormat
);
590 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
591 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
592 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
597 vfprintf(out
, zFormat
, ap
);
601 #elif !defined(utf8_printf)
602 # define utf8_printf fprintf
606 ** Render output like fprintf(). This should not be used on anything that
607 ** includes string formatting (e.g. "%s").
609 #if !defined(raw_printf)
610 # define raw_printf fprintf
613 /* Indicate out-of-memory and exit. */
614 static void shell_out_of_memory(void){
615 raw_printf(stderr
,"Error: out of memory\n");
619 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
620 ** out-of-memory error.
622 static void shell_check_oom(void *p
){
623 if( p
==0 ) shell_out_of_memory();
627 ** Write I/O traces to the following stream.
629 #ifdef SQLITE_ENABLE_IOTRACE
630 static FILE *iotrace
= 0;
634 ** This routine works like printf in that its first argument is a
635 ** format string and subsequent arguments are values to be substituted
636 ** in place of % fields. The result of formatting this string
637 ** is written to iotrace.
639 #ifdef SQLITE_ENABLE_IOTRACE
640 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
643 if( iotrace
==0 ) return;
644 va_start(ap
, zFormat
);
645 z
= sqlite3_vmprintf(zFormat
, ap
);
647 utf8_printf(iotrace
, "%s", z
);
653 ** Output string zUtf to stream pOut as w characters. If w is negative,
654 ** then right-justify the text. W is the width in UTF-8 characters, not
655 ** in bytes. This is different from the %*.*s specification in printf
656 ** since with %*.*s the width is measured in bytes, not characters.
658 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
661 int aw
= w
<0 ? -w
: w
;
662 if( zUtf
==0 ) zUtf
= "";
663 for(i
=n
=0; zUtf
[i
]; i
++){
664 if( (zUtf
[i
]&0xc0)!=0x80 ){
667 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
673 utf8_printf(pOut
, "%.*s", i
, zUtf
);
675 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
677 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
683 ** Determines if a string is a number of not.
685 static int isNumber(const char *z
, int *realnum
){
686 if( *z
=='-' || *z
=='+' ) z
++;
691 if( realnum
) *realnum
= 0;
692 while( IsDigit(*z
) ){ z
++; }
695 if( !IsDigit(*z
) ) return 0;
696 while( IsDigit(*z
) ){ z
++; }
697 if( realnum
) *realnum
= 1;
699 if( *z
=='e' || *z
=='E' ){
701 if( *z
=='+' || *z
=='-' ) z
++;
702 if( !IsDigit(*z
) ) return 0;
703 while( IsDigit(*z
) ){ z
++; }
704 if( realnum
) *realnum
= 1;
710 ** Compute a string length that is limited to what can be stored in
711 ** lower 30 bits of a 32-bit signed integer.
713 static int strlen30(const char *z
){
715 while( *z2
){ z2
++; }
716 return 0x3fffffff & (int)(z2
- z
);
720 ** Return the length of a string in characters. Multibyte UTF8 characters
721 ** count as a single character.
723 static int strlenChar(const char *z
){
726 if( (0xc0&*(z
++))!=0x80 ) n
++;
732 ** Return open FILE * if zFile exists, can be opened for read
733 ** and is an ordinary file or a character stream source.
734 ** Otherwise return 0.
736 static FILE * openChrSource(const char *zFile
){
738 struct _stat x
= {0};
739 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
740 /* On Windows, open first, then check the stream nature. This order
741 ** is necessary because _stat() and sibs, when checking a named pipe,
742 ** effectively break the pipe as its supplier sees it. */
743 FILE *rv
= fopen(zFile
, "rb");
744 if( rv
==0 ) return 0;
745 if( _fstat(_fileno(rv
), &x
) != 0
746 || !STAT_CHR_SRC(x
.st_mode
)){
753 int rc
= stat(zFile
, &x
);
754 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
755 if( rc
!=0 ) return 0;
756 if( STAT_CHR_SRC(x
.st_mode
) ){
757 return fopen(zFile
, "rb");
766 ** This routine reads a line of text from FILE in, stores
767 ** the text in memory obtained from malloc() and returns a pointer
768 ** to the text. NULL is returned at end of file, or if malloc()
771 ** If zLine is not NULL then it is a malloced buffer returned from
772 ** a previous call to this routine that may be reused.
774 static char *local_getline(char *zLine
, FILE *in
){
775 int nLine
= zLine
==0 ? 0 : 100;
780 nLine
= nLine
*2 + 100;
781 zLine
= realloc(zLine
, nLine
);
782 shell_check_oom(zLine
);
784 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
792 while( zLine
[n
] ) n
++;
793 if( n
>0 && zLine
[n
-1]=='\n' ){
795 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
800 #if defined(_WIN32) || defined(WIN32)
801 /* For interactive input on Windows systems, translate the
802 ** multi-byte characterset characters into UTF-8. */
803 if( stdin_is_interactive
&& in
==stdin
){
804 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
806 i64 nTrans
= strlen(zTrans
)+1;
808 zLine
= realloc(zLine
, nTrans
);
809 shell_check_oom(zLine
);
811 memcpy(zLine
, zTrans
, nTrans
);
812 sqlite3_free(zTrans
);
815 #endif /* defined(_WIN32) || defined(WIN32) */
820 ** Retrieve a single line of input text.
822 ** If in==0 then read from standard input and prompt before each line.
823 ** If isContinuation is true, then a continuation prompt is appropriate.
824 ** If isContinuation is zero, then the main prompt should be used.
826 ** If zPrior is not NULL then it is a buffer from a prior call to this
827 ** routine that can be reused.
829 ** The result is stored in space obtained from malloc() and must either
830 ** be freed by the caller or else passed back into this routine via the
831 ** zPrior argument for reuse.
833 #ifndef SQLITE_SHELL_FIDDLE
834 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
838 zResult
= local_getline(zPrior
, in
);
840 zPrompt
= isContinuation
? CONTINUATION_PROMPT
: mainPrompt
;
841 #if SHELL_USE_LOCAL_GETLINE
842 printf("%s", zPrompt
);
844 zResult
= local_getline(zPrior
, stdin
);
847 zResult
= shell_readline(zPrompt
);
848 /* BEGIN SQLCIPHER */
849 #ifdef SQLITE_HAS_CODEC
850 /* Simplistic filtering of input lines to prevent PRAGKA key and
851 PRAGMA rekey statements from being stored in readline history.
852 Note that this will only prevent single line statements, but that
853 will be sufficient for common cases. */
854 if(zResult
&& *zResult
&& (
855 sqlite3_strlike("%pragma%key%=%", zResult
, 0)==0 ||
856 sqlite3_strlike("%attach%database%as%key%", zResult
, 0)==0
861 if( zResult
&& *zResult
) shell_add_history(zResult
);
866 #endif /* !SQLITE_SHELL_FIDDLE */
869 ** Return the value of a hexadecimal digit. Return -1 if the input
870 ** is not a hex digit.
872 static int hexDigitValue(char c
){
873 if( c
>='0' && c
<='9' ) return c
- '0';
874 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
875 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
880 ** Interpret zArg as an integer value, possibly with suffixes.
882 static sqlite3_int64
integerValue(const char *zArg
){
884 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
886 { "MiB", 1024*1024 },
887 { "GiB", 1024*1024*1024 },
890 { "GB", 1000000000 },
900 }else if( zArg
[0]=='+' ){
903 if( zArg
[0]=='0' && zArg
[1]=='x' ){
906 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
911 while( IsDigit(zArg
[0]) ){
912 v
= v
*10 + zArg
[0] - '0';
916 for(i
=0; i
<ArraySize(aMult
); i
++){
917 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
922 return isNeg
? -v
: v
;
926 ** A variable length string to which one can append text.
928 typedef struct ShellText ShellText
;
936 ** Initialize and destroy a ShellText object
938 static void initText(ShellText
*p
){
939 memset(p
, 0, sizeof(*p
));
941 static void freeText(ShellText
*p
){
946 /* zIn is either a pointer to a NULL-terminated string in memory obtained
947 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
948 ** added to zIn, and the result returned in memory obtained from malloc().
949 ** zIn, if it was not NULL, is freed.
951 ** If the third argument, quote, is not '\0', then it is used as a
952 ** quote character for zAppend.
954 static void appendText(ShellText
*p
, const char *zAppend
, char quote
){
957 i64 nAppend
= strlen30(zAppend
);
959 len
= nAppend
+p
->n
+1;
962 for(i
=0; i
<nAppend
; i
++){
963 if( zAppend
[i
]==quote
) len
++;
967 if( p
->z
==0 || p
->n
+len
>=p
->nAlloc
){
968 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
969 p
->z
= realloc(p
->z
, p
->nAlloc
);
970 shell_check_oom(p
->z
);
974 char *zCsr
= p
->z
+p
->n
;
976 for(i
=0; i
<nAppend
; i
++){
977 *zCsr
++ = zAppend
[i
];
978 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
981 p
->n
= (int)(zCsr
- p
->z
);
984 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
991 ** Attempt to determine if identifier zName needs to be quoted, either
992 ** because it contains non-alphanumeric characters, or because it is an
993 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
994 ** that quoting is required.
996 ** Return '"' if quoting is required. Return 0 if no quoting is required.
998 static char quoteChar(const char *zName
){
1000 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
1001 for(i
=0; zName
[i
]; i
++){
1002 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
1004 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
1008 ** Construct a fake object name and column list to describe the structure
1009 ** of the view, virtual table, or table valued function zSchema.zName.
1011 static char *shellFakeSchema(
1012 sqlite3
*db
, /* The database connection containing the vtab */
1013 const char *zSchema
, /* Schema of the database holding the vtab */
1014 const char *zName
/* The name of the virtual table */
1016 sqlite3_stmt
*pStmt
= 0;
1023 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1024 zSchema
? zSchema
: "main", zName
);
1025 shell_check_oom(zSql
);
1026 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
1030 cQuote
= quoteChar(zSchema
);
1031 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
1032 appendText(&s
, zSchema
, cQuote
);
1033 appendText(&s
, ".", 0);
1035 cQuote
= quoteChar(zName
);
1036 appendText(&s
, zName
, cQuote
);
1037 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
1038 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
1040 appendText(&s
, zDiv
, 0);
1042 if( zCol
==0 ) zCol
= "";
1043 cQuote
= quoteChar(zCol
);
1044 appendText(&s
, zCol
, cQuote
);
1046 appendText(&s
, ")", 0);
1047 sqlite3_finalize(pStmt
);
1056 ** SQL function: shell_module_schema(X)
1058 ** Return a fake schema for the table-valued function or eponymous virtual
1061 static void shellModuleSchema(
1062 sqlite3_context
*pCtx
,
1064 sqlite3_value
**apVal
1068 UNUSED_PARAMETER(nVal
);
1069 zName
= (const char*)sqlite3_value_text(apVal
[0]);
1070 zFake
= zName
? shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
) : 0;
1072 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
1079 ** SQL function: shell_add_schema(S,X)
1081 ** Add the schema name X to the CREATE statement in S and return the result.
1084 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1089 ** CREATE UNIQUE INDEX
1092 ** CREATE VIRTUAL TABLE
1094 ** This UDF is used by the .schema command to insert the schema name of
1095 ** attached databases into the middle of the sqlite_schema.sql field.
1097 static void shellAddSchemaName(
1098 sqlite3_context
*pCtx
,
1100 sqlite3_value
**apVal
1102 static const char *aPrefix
[] = {
1111 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
1112 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
1113 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
1114 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
1115 UNUSED_PARAMETER(nVal
);
1116 if( zIn
!=0 && cli_strncmp(zIn
, "CREATE ", 7)==0 ){
1117 for(i
=0; i
<ArraySize(aPrefix
); i
++){
1118 int n
= strlen30(aPrefix
[i
]);
1119 if( cli_strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
1123 char cQuote
= quoteChar(zSchema
);
1124 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
1125 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1127 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1131 && aPrefix
[i
][0]=='V'
1132 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
1135 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
1137 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
1142 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
1148 sqlite3_result_value(pCtx
, apVal
[0]);
1152 ** The source code for several run-time loadable extensions is inserted
1153 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1154 ** code, we need to override some macros to make the included program code
1155 ** work here in the middle of this regular program.
1157 #define SQLITE_EXTENSION_INIT1
1158 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1160 #if defined(_WIN32) && defined(_MSC_VER)
1161 INCLUDE test_windirent
.h
1162 INCLUDE test_windirent
.c
1163 #define dirent DIRENT
1165 INCLUDE
../ext
/misc
/memtrace
.c
1166 INCLUDE
../ext
/misc
/shathree
.c
1167 INCLUDE
../ext
/misc
/uint
.c
1168 INCLUDE
../ext
/misc
/decimal
.c
1169 #undef sqlite3_base_init
1170 #define sqlite3_base_init sqlite3_base64_init
1171 INCLUDE
../ext
/misc
/base64
.c
1172 #undef sqlite3_base_init
1173 #define sqlite3_base_init sqlite3_base85_init
1174 #define OMIT_BASE85_CHECKER
1175 INCLUDE
../ext
/misc
/base85
.c
1176 INCLUDE
../ext
/misc
/ieee754
.c
1177 INCLUDE
../ext
/misc
/series
.c
1178 INCLUDE
../ext
/misc
/regexp
.c
1179 #ifndef SQLITE_SHELL_FIDDLE
1180 INCLUDE
../ext
/misc
/fileio
.c
1181 INCLUDE
../ext
/misc
/completion
.c
1182 INCLUDE
../ext
/misc
/appendvfs
.c
1184 #ifdef SQLITE_HAVE_ZLIB
1185 INCLUDE
../ext
/misc
/zipfile
.c
1186 INCLUDE
../ext
/misc
/sqlar
.c
1188 INCLUDE
../ext
/expert
/sqlite3expert
.h
1189 INCLUDE
../ext
/expert
/sqlite3expert
.c
1191 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1192 #define SQLITE_SHELL_HAVE_RECOVER 1
1194 #define SQLITE_SHELL_HAVE_RECOVER 0
1196 #if SQLITE_SHELL_HAVE_RECOVER
1197 INCLUDE
../ext
/recover
/sqlite3recover
.h
1198 # ifndef SQLITE_HAVE_SQLITE3R
1199 INCLUDE
../ext
/recover
/dbdata
.c
1200 INCLUDE
../ext
/recover
/sqlite3recover
.c
1203 #ifdef SQLITE_SHELL_EXTSRC
1204 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1207 #if defined(SQLITE_ENABLE_SESSION)
1209 ** State information for a single open session
1211 typedef struct OpenSession OpenSession
;
1212 struct OpenSession
{
1213 char *zName
; /* Symbolic name for this session */
1214 int nFilter
; /* Number of xFilter rejection GLOB patterns */
1215 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
1216 sqlite3_session
*p
; /* The open session */
1220 typedef struct ExpertInfo ExpertInfo
;
1222 sqlite3expert
*pExpert
;
1226 /* A single line in the EQP output */
1227 typedef struct EQPGraphRow EQPGraphRow
;
1228 struct EQPGraphRow
{
1229 int iEqpId
; /* ID for this row */
1230 int iParentId
; /* ID of the parent row */
1231 EQPGraphRow
*pNext
; /* Next row in sequence */
1232 char zText
[1]; /* Text to display for this row */
1235 /* All EQP output is collected into an instance of the following */
1236 typedef struct EQPGraph EQPGraph
;
1238 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
1239 EQPGraphRow
*pLast
; /* Last element of the pRow list */
1240 char zPrefix
[100]; /* Graph prefix */
1243 /* Parameters affecting columnar mode result display (defaulting together) */
1244 typedef struct ColModeOpts
{
1245 int iWrap
; /* In columnar modes, wrap lines reaching this limit */
1246 u8 bQuote
; /* Quote results for .mode box and table */
1247 u8 bWordWrap
; /* In columnar modes, wrap at word boundaries */
1249 #define ColModeOpts_default { 60, 0, 0 }
1250 #define ColModeOpts_default_qbox { 60, 1, 0 }
1253 ** State information about the database connection is contained in an
1254 ** instance of the following structure.
1256 typedef struct ShellState ShellState
;
1258 sqlite3
*db
; /* The database */
1259 u8 autoExplain
; /* Automatically turn on .explain mode */
1260 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1261 u8 autoEQPtest
; /* autoEQP is in test mode */
1262 u8 autoEQPtrace
; /* autoEQP is in trace mode */
1263 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1264 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1265 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1266 u8 nEqpLevel
; /* Depth of the EQP output graph */
1267 u8 eTraceType
; /* SHELL_TRACE_* value for type of trace */
1268 u8 bSafeMode
; /* True to prohibit unsafe operations */
1269 u8 bSafeModePersist
; /* The long-term value of bSafeMode */
1270 ColModeOpts cmOpts
; /* Option values affecting columnar mode output */
1271 unsigned statsOn
; /* True to display memory stats before each finalize */
1272 unsigned mEqpLines
; /* Mask of veritical lines in the EQP output graph */
1273 int inputNesting
; /* Track nesting level of .read and other redirects */
1274 int outCount
; /* Revert to stdout when reaching zero */
1275 int cnt
; /* Number of records displayed so far */
1276 int lineno
; /* Line number of last line read from in */
1277 int openFlags
; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1278 FILE *in
; /* Read commands from this stream */
1279 FILE *out
; /* Write results here */
1280 FILE *traceOut
; /* Output for sqlite3_trace() */
1281 int nErr
; /* Number of errors seen */
1282 int mode
; /* An output mode setting */
1283 int modePrior
; /* Saved mode */
1284 int cMode
; /* temporary output mode for the current query */
1285 int normalMode
; /* Output mode before ".explain on" */
1286 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1287 int showHeader
; /* True to show column names in List or Column mode */
1288 int nCheck
; /* Number of ".check" commands run */
1289 unsigned nProgress
; /* Number of progress callbacks encountered */
1290 unsigned mxProgress
; /* Maximum progress callbacks before failing */
1291 unsigned flgProgress
; /* Flags for the progress callback */
1292 unsigned shellFlgs
; /* Various flags */
1293 unsigned priorShFlgs
; /* Saved copy of flags */
1294 sqlite3_int64 szMax
; /* --maxsize argument to .open */
1295 char *zDestTable
; /* Name of destination table when MODE_Insert */
1296 char *zTempFile
; /* Temporary file that might need deleting */
1297 char zTestcase
[30]; /* Name of current test case */
1298 char colSeparator
[20]; /* Column separator character for several modes */
1299 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1300 char colSepPrior
[20]; /* Saved column separator */
1301 char rowSepPrior
[20]; /* Saved row separator */
1302 int *colWidth
; /* Requested width of each column in columnar modes */
1303 int *actualWidth
; /* Actual width of each column */
1304 int nWidth
; /* Number of slots in colWidth[] and actualWidth[] */
1305 char nullValue
[20]; /* The text to print when a NULL comes back from
1307 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1308 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1309 FILE *pLog
; /* Write log output here */
1310 struct AuxDb
{ /* Storage space for auxiliary database connections */
1311 sqlite3
*db
; /* Connection pointer */
1312 const char *zDbFilename
; /* Filename used to open the connection */
1313 char *zFreeOnClose
; /* Free this memory allocation on close */
1314 #if defined(SQLITE_ENABLE_SESSION)
1315 int nSession
; /* Number of active sessions */
1316 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1318 } aAuxDb
[5], /* Array of all database connections */
1319 *pAuxDb
; /* Currently active database connection */
1320 int *aiIndent
; /* Array of indents used in MODE_Explain */
1321 int nIndent
; /* Size of array aiIndent[] */
1322 int iIndent
; /* Index of current op in aiIndent[] */
1323 char *zNonce
; /* Nonce for temporary safe-mode excapes */
1324 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1325 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1326 #ifdef SQLITE_SHELL_FIDDLE
1328 const char * zInput
; /* Input string from wasm/JS proxy */
1329 const char * zPos
; /* Cursor pos into zInput */
1330 const char * zDefaultDbName
; /* Default name for db file */
1335 #ifdef SQLITE_SHELL_FIDDLE
1336 static ShellState shellState
;
1340 /* Allowed values for ShellState.autoEQP
1342 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1343 #define AUTOEQP_on 1 /* Automatic EQP is on */
1344 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1345 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1347 /* Allowed values for ShellState.openMode
1349 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1350 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1351 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1352 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1353 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1354 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1355 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1357 /* Allowed values for ShellState.eTraceType
1359 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1360 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1361 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1363 /* Bits in the ShellState.flgProgress variable */
1364 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1365 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1366 ** callback limit is reached, and for each
1367 ** top-level SQL statement */
1368 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1371 ** These are the allowed shellFlgs values
1373 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1374 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1375 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1376 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1377 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1378 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1379 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1380 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1381 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1382 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1385 ** Macros for testing and setting shellFlgs
1387 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1388 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1389 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1392 ** These are the allowed modes.
1394 #define MODE_Line 0 /* One column per line. Blank line between records */
1395 #define MODE_Column 1 /* One record per line in neat columns */
1396 #define MODE_List 2 /* One record per line with a separator */
1397 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1398 #define MODE_Html 4 /* Generate an XHTML table */
1399 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1400 #define MODE_Quote 6 /* Quote values as for SQL */
1401 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1402 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1403 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1404 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1405 #define MODE_Pretty 11 /* Pretty-print schemas */
1406 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1407 #define MODE_Json 13 /* Output JSON */
1408 #define MODE_Markdown 14 /* Markdown formatting */
1409 #define MODE_Table 15 /* MySQL-style table formatting */
1410 #define MODE_Box 16 /* Unicode box-drawing characters */
1411 #define MODE_Count 17 /* Output only a count of the rows of output */
1412 #define MODE_Off 18 /* No query output shown */
1414 static const char *modeDescr
[] = {
1437 ** These are the column/row/line separators used by the various
1438 ** import/export modes.
1440 #define SEP_Column "|"
1441 #define SEP_Row "\n"
1442 #define SEP_Tab "\t"
1443 #define SEP_Space " "
1444 #define SEP_Comma ","
1445 #define SEP_CrLf "\r\n"
1446 #define SEP_Unit "\x1F"
1447 #define SEP_Record "\x1E"
1450 ** Limit input nesting via .read or any other input redirect.
1451 ** It's not too expensive, so a generous allowance can be made.
1453 #define MAX_INPUT_NESTING 25
1456 ** A callback for the sqlite3_log() interface.
1458 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1459 ShellState
*p
= (ShellState
*)pArg
;
1460 if( p
->pLog
==0 ) return;
1461 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1466 ** SQL function: shell_putsnl(X)
1468 ** Write the text X to the screen (or whatever output is being directed)
1469 ** adding a newline at the end, and then return X.
1471 static void shellPutsFunc(
1472 sqlite3_context
*pCtx
,
1474 sqlite3_value
**apVal
1476 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1478 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1479 sqlite3_result_value(pCtx
, apVal
[0]);
1483 ** If in safe mode, print an error message described by the arguments
1484 ** and exit immediately.
1486 static void failIfSafeMode(
1488 const char *zErrMsg
,
1494 va_start(ap
, zErrMsg
);
1495 zMsg
= sqlite3_vmprintf(zErrMsg
, ap
);
1497 raw_printf(stderr
, "line %d: ", p
->lineno
);
1498 utf8_printf(stderr
, "%s\n", zMsg
);
1504 ** SQL function: edit(VALUE)
1505 ** edit(VALUE,EDITOR)
1509 ** (1) Write VALUE into a temporary file.
1510 ** (2) Run program EDITOR on that temporary file.
1511 ** (3) Read the temporary file back and return its content as the result.
1512 ** (4) Delete the temporary file
1514 ** If the EDITOR argument is omitted, use the value in the VISUAL
1515 ** environment variable. If still there is no EDITOR, through an error.
1517 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1519 #ifndef SQLITE_NOHAVE_SYSTEM
1520 static void editFunc(
1521 sqlite3_context
*context
,
1523 sqlite3_value
**argv
1525 const char *zEditor
;
1526 char *zTempFile
= 0;
1535 unsigned char *p
= 0;
1538 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1540 zEditor
= getenv("VISUAL");
1543 sqlite3_result_error(context
, "no editor for edit()", -1);
1546 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1547 sqlite3_result_error(context
, "NULL input to edit()", -1);
1550 db
= sqlite3_context_db_handle(context
);
1552 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1554 sqlite3_uint64 r
= 0;
1555 sqlite3_randomness(sizeof(r
), &r
);
1556 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1558 sqlite3_result_error_nomem(context
);
1562 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1563 /* When writing the file to be edited, do \n to \r\n conversions on systems
1564 ** that want \r\n line endings */
1565 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1567 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1570 sz
= sqlite3_value_bytes(argv
[0]);
1572 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, (size_t)sz
, f
);
1574 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
1575 /* Remember whether or not the value originally contained \r\n */
1576 if( z
&& strstr(z
,"\r\n")!=0 ) hasCRNL
= 1;
1577 x
= fwrite(sqlite3_value_text(argv
[0]), 1, (size_t)sz
, f
);
1582 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1585 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1587 sqlite3_result_error_nomem(context
);
1593 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1596 f
= fopen(zTempFile
, "rb");
1598 sqlite3_result_error(context
,
1599 "edit() cannot reopen temp file after edit", -1);
1602 fseek(f
, 0, SEEK_END
);
1605 p
= sqlite3_malloc64( sz
+1 );
1607 sqlite3_result_error_nomem(context
);
1610 x
= fread(p
, 1, (size_t)sz
, f
);
1614 sqlite3_result_error(context
, "could not read back the whole file", -1);
1618 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1622 /* If the original contains \r\n then do no conversions back to \n */
1624 /* If the file did not originally contain \r\n then convert any new
1625 ** \r\n back into \n */
1626 for(i
=j
=0; i
<sz
; i
++){
1627 if( p
[i
]=='\r' && p
[i
+1]=='\n' ) i
++;
1633 sqlite3_result_text64(context
, (const char*)p
, sz
,
1634 sqlite3_free
, SQLITE_UTF8
);
1641 sqlite3_free(zTempFile
);
1644 #endif /* SQLITE_NOHAVE_SYSTEM */
1647 ** Save or restore the current output mode
1649 static void outputModePush(ShellState
*p
){
1650 p
->modePrior
= p
->mode
;
1651 p
->priorShFlgs
= p
->shellFlgs
;
1652 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1653 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1655 static void outputModePop(ShellState
*p
){
1656 p
->mode
= p
->modePrior
;
1657 p
->shellFlgs
= p
->priorShFlgs
;
1658 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1659 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1663 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1665 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1667 unsigned char *aBlob
= (unsigned char*)pBlob
;
1669 char *zStr
= sqlite3_malloc(nBlob
*2 + 1);
1670 shell_check_oom(zStr
);
1672 for(i
=0; i
<nBlob
; i
++){
1673 static const char aHex
[] = {
1674 '0', '1', '2', '3', '4', '5', '6', '7',
1675 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1677 zStr
[i
*2] = aHex
[ (aBlob
[i
] >> 4) ];
1678 zStr
[i
*2+1] = aHex
[ (aBlob
[i
] & 0x0F) ];
1682 raw_printf(out
,"X'%s'", zStr
);
1687 ** Find a string that is not found anywhere in z[]. Return a pointer
1690 ** Try to use zA and zB first. If both of those are already found in z[]
1691 ** then make up some string and store it in the buffer zBuf.
1693 static const char *unused_string(
1694 const char *z
, /* Result must not appear anywhere in z */
1695 const char *zA
, const char *zB
, /* Try these first */
1696 char *zBuf
/* Space to store a generated string */
1699 if( strstr(z
, zA
)==0 ) return zA
;
1700 if( strstr(z
, zB
)==0 ) return zB
;
1702 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1703 }while( strstr(z
,zBuf
)!=0 );
1708 ** Output the given string as a quoted string using SQL quoting conventions.
1710 ** See also: output_quoted_escaped_string()
1712 static void output_quoted_string(FILE *out
, const char *z
){
1715 setBinaryMode(out
, 1);
1716 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1718 utf8_printf(out
,"'%s'",z
);
1720 raw_printf(out
, "'");
1722 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1725 utf8_printf(out
, "%.*s", i
, z
);
1729 raw_printf(out
, "'");
1737 raw_printf(out
, "'");
1739 setTextMode(out
, 1);
1743 ** Output the given string as a quoted string using SQL quoting conventions.
1744 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1745 ** get corrupted by end-of-line translation facilities in some operating
1748 ** This is like output_quoted_string() but with the addition of the \r\n
1749 ** escape mechanism.
1751 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1754 setBinaryMode(out
, 1);
1755 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1757 utf8_printf(out
,"'%s'",z
);
1759 const char *zNL
= 0;
1760 const char *zCR
= 0;
1763 char zBuf1
[20], zBuf2
[20];
1764 for(i
=0; z
[i
]; i
++){
1765 if( z
[i
]=='\n' ) nNL
++;
1766 if( z
[i
]=='\r' ) nCR
++;
1769 raw_printf(out
, "replace(");
1770 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1773 raw_printf(out
, "replace(");
1774 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1776 raw_printf(out
, "'");
1778 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1781 utf8_printf(out
, "%.*s", i
, z
);
1785 raw_printf(out
, "'");
1793 raw_printf(out
, "%s", zNL
);
1796 raw_printf(out
, "%s", zCR
);
1798 raw_printf(out
, "'");
1800 raw_printf(out
, ",'%s',char(13))", zCR
);
1803 raw_printf(out
, ",'%s',char(10))", zNL
);
1806 setTextMode(out
, 1);
1810 ** Output the given string as a quoted according to C or TCL quoting rules.
1812 static void output_c_string(FILE *out
, const char *z
){
1815 while( (c
= *(z
++))!=0 ){
1822 }else if( c
=='\t' ){
1825 }else if( c
=='\n' ){
1828 }else if( c
=='\r' ){
1831 }else if( !isprint(c
&0xff) ){
1832 raw_printf(out
, "\\%03o", c
&0xff);
1841 ** Output the given string as a quoted according to JSON quoting rules.
1843 static void output_json_string(FILE *out
, const char *z
, i64 n
){
1845 if( n
<0 ) n
= strlen(z
);
1849 if( c
=='\\' || c
=='"' ){
1852 }else if( c
<=0x1f ){
1856 }else if( c
=='\f' ){
1858 }else if( c
=='\n' ){
1860 }else if( c
=='\r' ){
1862 }else if( c
=='\t' ){
1865 raw_printf(out
, "u%04x",c
);
1875 ** Output the given string with characters that are special to
1878 static void output_html_string(FILE *out
, const char *z
){
1890 utf8_printf(out
,"%.*s",i
,z
);
1893 raw_printf(out
,"<");
1894 }else if( z
[i
]=='&' ){
1895 raw_printf(out
,"&");
1896 }else if( z
[i
]=='>' ){
1897 raw_printf(out
,">");
1898 }else if( z
[i
]=='\"' ){
1899 raw_printf(out
,""");
1900 }else if( z
[i
]=='\'' ){
1901 raw_printf(out
,"'");
1910 ** If a field contains any character identified by a 1 in the following
1911 ** array, then the string must be quoted for CSV.
1913 static const char needCsvQuote
[] = {
1914 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1915 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1916 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1917 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1918 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1919 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1920 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1921 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1922 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1923 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1924 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1925 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1926 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1927 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1928 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1929 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1933 ** Output a single term of CSV. Actually, p->colSeparator is used for
1934 ** the separator, which may or may not be a comma. p->nullValue is
1935 ** the null value. Strings are quoted if necessary. The separator
1936 ** is only issued if bSep is true.
1938 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1941 utf8_printf(out
,"%s",p
->nullValue
);
1944 for(i
=0; z
[i
]; i
++){
1945 if( needCsvQuote
[((unsigned char*)z
)[i
]] ){
1950 if( i
==0 || strstr(z
, p
->colSeparator
)!=0 ){
1951 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1952 shell_check_oom(zQuoted
);
1953 utf8_printf(out
, "%s", zQuoted
);
1954 sqlite3_free(zQuoted
);
1956 utf8_printf(out
, "%s", z
);
1960 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1965 ** This routine runs when the user presses Ctrl-C
1967 static void interrupt_handler(int NotUsed
){
1968 UNUSED_PARAMETER(NotUsed
);
1970 if( seenInterrupt
>2 ) exit(1);
1971 if( globalDb
) sqlite3_interrupt(globalDb
);
1974 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1976 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1978 static BOOL WINAPI
ConsoleCtrlHandler(
1979 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1981 if( dwCtrlType
==CTRL_C_EVENT
){
1982 interrupt_handler(0);
1989 #ifndef SQLITE_OMIT_AUTHORIZATION
1991 ** This authorizer runs in safe mode.
1993 static int safeModeAuth(
2001 ShellState
*p
= (ShellState
*)pClientData
;
2002 static const char *azProhibitedFunctions
[] = {
2011 UNUSED_PARAMETER(zA1
);
2012 UNUSED_PARAMETER(zA3
);
2013 UNUSED_PARAMETER(zA4
);
2015 case SQLITE_ATTACH
: {
2016 #ifndef SQLITE_SHELL_FIDDLE
2017 /* In WASM builds the filesystem is a virtual sandbox, so
2018 ** there's no harm in using ATTACH. */
2019 failIfSafeMode(p
, "cannot run ATTACH in safe mode");
2023 case SQLITE_FUNCTION
: {
2025 for(i
=0; i
<ArraySize(azProhibitedFunctions
); i
++){
2026 if( sqlite3_stricmp(zA2
, azProhibitedFunctions
[i
])==0 ){
2027 failIfSafeMode(p
, "cannot use the %s() function in safe mode",
2028 azProhibitedFunctions
[i
]);
2038 ** When the ".auth ON" is set, the following authorizer callback is
2039 ** invoked. It always returns SQLITE_OK.
2041 static int shellAuth(
2049 ShellState
*p
= (ShellState
*)pClientData
;
2050 static const char *azAction
[] = { 0,
2051 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2052 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2053 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2054 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2055 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2056 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2057 "PRAGMA", "READ", "SELECT",
2058 "TRANSACTION", "UPDATE", "ATTACH",
2059 "DETACH", "ALTER_TABLE", "REINDEX",
2060 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2061 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2069 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
2071 raw_printf(p
->out
, " ");
2073 output_c_string(p
->out
, az
[i
]);
2075 raw_printf(p
->out
, "NULL");
2078 raw_printf(p
->out
, "\n");
2079 if( p
->bSafeMode
) (void)safeModeAuth(pClientData
, op
, zA1
, zA2
, zA3
, zA4
);
2085 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2087 ** This routine converts some CREATE TABLE statements for shadow tables
2088 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2090 ** If the schema statement in z[] contains a start-of-comment and if
2091 ** sqlite3_complete() returns false, try to terminate the comment before
2092 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2094 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
2097 if( zTail
==0 ) return;
2098 if( zTail
[0]==';' && (strstr(z
, "/*")!=0 || strstr(z
,"--")!=0) ){
2099 const char *zOrig
= z
;
2100 static const char *azTerm
[] = { "", "*/", "\n" };
2102 for(i
=0; i
<ArraySize(azTerm
); i
++){
2103 char *zNew
= sqlite3_mprintf("%s%s;", zOrig
, azTerm
[i
]);
2104 if( sqlite3_complete(zNew
) ){
2105 size_t n
= strlen(zNew
);
2114 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
2115 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
2117 utf8_printf(out
, "%s%s", z
, zTail
);
2119 sqlite3_free(zToFree
);
2121 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
2124 printSchemaLine(out
, z
, zTail
);
2129 ** Return true if string z[] has nothing but whitespace and comments to the
2130 ** end of the first line.
2132 static int wsToEol(const char *z
){
2134 for(i
=0; z
[i
]; i
++){
2135 if( z
[i
]=='\n' ) return 1;
2136 if( IsSpace(z
[i
]) ) continue;
2137 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
2144 ** Add a new entry to the EXPLAIN QUERY PLAN data
2146 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
2149 if( zText
==0 ) return;
2150 nText
= strlen(zText
);
2151 if( p
->autoEQPtest
){
2152 utf8_printf(p
->out
, "%d,%d,%s\n", iEqpId
, p2
, zText
);
2154 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
2155 shell_check_oom(pNew
);
2156 pNew
->iEqpId
= iEqpId
;
2157 pNew
->iParentId
= p2
;
2158 memcpy(pNew
->zText
, zText
, nText
+1);
2160 if( p
->sGraph
.pLast
){
2161 p
->sGraph
.pLast
->pNext
= pNew
;
2163 p
->sGraph
.pRow
= pNew
;
2165 p
->sGraph
.pLast
= pNew
;
2169 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2172 static void eqp_reset(ShellState
*p
){
2173 EQPGraphRow
*pRow
, *pNext
;
2174 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
2175 pNext
= pRow
->pNext
;
2178 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
2181 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2182 ** pOld, or return the first such line if pOld is NULL
2184 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
2185 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
2186 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
2190 /* Render a single level of the graph that has iEqpId as its parent. Called
2191 ** recursively to render sublevels.
2193 static void eqp_render_level(ShellState
*p
, int iEqpId
){
2194 EQPGraphRow
*pRow
, *pNext
;
2195 i64 n
= strlen(p
->sGraph
.zPrefix
);
2197 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
2198 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
2200 utf8_printf(p
->out
, "%s%s%s\n", p
->sGraph
.zPrefix
,
2201 pNext
? "|--" : "`--", z
);
2202 if( n
<(i64
)sizeof(p
->sGraph
.zPrefix
)-7 ){
2203 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
2204 eqp_render_level(p
, pRow
->iEqpId
);
2205 p
->sGraph
.zPrefix
[n
] = 0;
2211 ** Display and reset the EXPLAIN QUERY PLAN data
2213 static void eqp_render(ShellState
*p
, i64 nCycle
){
2214 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
2216 if( pRow
->zText
[0]=='-' ){
2217 if( pRow
->pNext
==0 ){
2221 utf8_printf(p
->out
, "%s\n", pRow
->zText
+3);
2222 p
->sGraph
.pRow
= pRow
->pNext
;
2224 }else if( nCycle
>0 ){
2225 utf8_printf(p
->out
, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle
);
2227 utf8_printf(p
->out
, "QUERY PLAN\n");
2229 p
->sGraph
.zPrefix
[0] = 0;
2230 eqp_render_level(p
, 0);
2235 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2237 ** Progress handler callback.
2239 static int progress_handler(void *pClientData
) {
2240 ShellState
*p
= (ShellState
*)pClientData
;
2242 if( p
->nProgress
>=p
->mxProgress
&& p
->mxProgress
>0 ){
2243 raw_printf(p
->out
, "Progress limit reached (%u)\n", p
->nProgress
);
2244 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
2245 if( p
->flgProgress
& SHELL_PROGRESS_ONCE
) p
->mxProgress
= 0;
2248 if( (p
->flgProgress
& SHELL_PROGRESS_QUIET
)==0 ){
2249 raw_printf(p
->out
, "Progress %u\n", p
->nProgress
);
2253 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2258 static void print_dashes(FILE *out
, int N
){
2259 const char zDash
[] = "--------------------------------------------------";
2260 const int nDash
= sizeof(zDash
) - 1;
2265 raw_printf(out
, "%.*s", N
, zDash
);
2269 ** Print a markdown or table-style row separator using ascii-art
2271 static void print_row_separator(
2278 fputs(zSep
, p
->out
);
2279 print_dashes(p
->out
, p
->actualWidth
[0]+2);
2280 for(i
=1; i
<nArg
; i
++){
2281 fputs(zSep
, p
->out
);
2282 print_dashes(p
->out
, p
->actualWidth
[i
]+2);
2284 fputs(zSep
, p
->out
);
2286 fputs("\n", p
->out
);
2290 ** This is the callback routine that the shell
2291 ** invokes for each row of a query result.
2293 static int shell_callback(
2295 int nArg
, /* Number of result columns */
2296 char **azArg
, /* Text of each result column */
2297 char **azCol
, /* Column names */
2298 int *aiType
/* Column types. Might be NULL */
2301 ShellState
*p
= (ShellState
*)pArg
;
2303 if( azArg
==0 ) return 0;
2311 if( azArg
==0 ) break;
2312 for(i
=0; i
<nArg
; i
++){
2313 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
2314 if( len
>w
) w
= len
;
2316 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2317 for(i
=0; i
<nArg
; i
++){
2318 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
2319 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
2323 case MODE_Explain
: {
2324 static const int aExplainWidth
[] = {4, 13, 4, 4, 4, 13, 2, 13};
2325 if( nArg
>ArraySize(aExplainWidth
) ){
2326 nArg
= ArraySize(aExplainWidth
);
2329 for(i
=0; i
<nArg
; i
++){
2330 int w
= aExplainWidth
[i
];
2331 utf8_width_print(p
->out
, w
, azCol
[i
]);
2332 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2334 for(i
=0; i
<nArg
; i
++){
2335 int w
= aExplainWidth
[i
];
2336 print_dashes(p
->out
, w
);
2337 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2340 if( azArg
==0 ) break;
2341 for(i
=0; i
<nArg
; i
++){
2342 int w
= aExplainWidth
[i
];
2343 if( i
==nArg
-1 ) w
= 0;
2344 if( azArg
[i
] && strlenChar(azArg
[i
])>w
){
2345 w
= strlenChar(azArg
[i
]);
2347 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
2348 if( p
->iIndent
<p
->nIndent
){
2349 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
2353 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2354 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2358 case MODE_Semi
: { /* .schema and .fullschema output */
2359 printSchemaLine(p
->out
, azArg
[0], ";\n");
2362 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
2370 if( azArg
[0]==0 ) break;
2371 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
2372 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
2374 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
2377 z
= sqlite3_mprintf("%s", azArg
[0]);
2380 for(i
=0; IsSpace(z
[i
]); i
++){}
2381 for(; (c
= z
[i
])!=0; i
++){
2383 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
2384 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
2385 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
2390 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
2392 if( strlen30(z
)>=79 ){
2393 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy from z[i] back to z[j] */
2396 }else if( c
=='"' || c
=='\'' || c
=='`' ){
2400 }else if( c
=='-' && z
[i
+1]=='-' ){
2406 if( nLine
>0 && nParen
==0 && j
>0 ){
2407 printSchemaLineN(p
->out
, z
, j
, "\n");
2412 if( nParen
==1 && cEnd
==0
2413 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
2416 printSchemaLineN(p
->out
, z
, j
, "\n ");
2419 while( IsSpace(z
[i
+1]) ){ i
++; }
2424 printSchemaLine(p
->out
, z
, ";\n");
2429 if( p
->cnt
++==0 && p
->showHeader
){
2430 for(i
=0; i
<nArg
; i
++){
2431 utf8_printf(p
->out
,"%s%s",azCol
[i
],
2432 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
2435 if( azArg
==0 ) break;
2436 for(i
=0; i
<nArg
; i
++){
2438 if( z
==0 ) z
= p
->nullValue
;
2439 utf8_printf(p
->out
, "%s", z
);
2441 utf8_printf(p
->out
, "%s", p
->colSeparator
);
2443 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2449 if( p
->cnt
++==0 && p
->showHeader
){
2450 raw_printf(p
->out
,"<TR>");
2451 for(i
=0; i
<nArg
; i
++){
2452 raw_printf(p
->out
,"<TH>");
2453 output_html_string(p
->out
, azCol
[i
]);
2454 raw_printf(p
->out
,"</TH>\n");
2456 raw_printf(p
->out
,"</TR>\n");
2458 if( azArg
==0 ) break;
2459 raw_printf(p
->out
,"<TR>");
2460 for(i
=0; i
<nArg
; i
++){
2461 raw_printf(p
->out
,"<TD>");
2462 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2463 raw_printf(p
->out
,"</TD>\n");
2465 raw_printf(p
->out
,"</TR>\n");
2469 if( p
->cnt
++==0 && p
->showHeader
){
2470 for(i
=0; i
<nArg
; i
++){
2471 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
2472 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2474 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2476 if( azArg
==0 ) break;
2477 for(i
=0; i
<nArg
; i
++){
2478 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2479 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2481 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2485 setBinaryMode(p
->out
, 1);
2486 if( p
->cnt
++==0 && p
->showHeader
){
2487 for(i
=0; i
<nArg
; i
++){
2488 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
2490 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2493 for(i
=0; i
<nArg
; i
++){
2494 output_csv(p
, azArg
[i
], i
<nArg
-1);
2496 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2498 setTextMode(p
->out
, 1);
2502 if( azArg
==0 ) break;
2503 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
2504 if( p
->showHeader
){
2505 raw_printf(p
->out
,"(");
2506 for(i
=0; i
<nArg
; i
++){
2507 if( i
>0 ) raw_printf(p
->out
, ",");
2508 if( quoteChar(azCol
[i
]) ){
2509 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2511 utf8_printf(p
->out
, "%s", z
);
2514 raw_printf(p
->out
, "%s", azCol
[i
]);
2517 raw_printf(p
->out
,")");
2520 for(i
=0; i
<nArg
; i
++){
2521 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
2522 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2523 utf8_printf(p
->out
,"NULL");
2524 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2525 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2526 output_quoted_string(p
->out
, azArg
[i
]);
2528 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2530 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2531 utf8_printf(p
->out
,"%s", azArg
[i
]);
2532 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2534 double r
= sqlite3_column_double(p
->pStmt
, i
);
2536 memcpy(&ur
,&r
,sizeof(r
));
2537 if( ur
==0x7ff0000000000000LL
){
2538 raw_printf(p
->out
, "1e999");
2539 }else if( ur
==0xfff0000000000000LL
){
2540 raw_printf(p
->out
, "-1e999");
2542 sqlite3_int64 ir
= (sqlite3_int64
)r
;
2543 if( r
==(double)ir
){
2544 sqlite3_snprintf(50,z
,"%lld.0", ir
);
2546 sqlite3_snprintf(50,z
,"%!.20g", r
);
2548 raw_printf(p
->out
, "%s", z
);
2550 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2551 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2552 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2553 output_hex_blob(p
->out
, pBlob
, nBlob
);
2554 }else if( isNumber(azArg
[i
], 0) ){
2555 utf8_printf(p
->out
,"%s", azArg
[i
]);
2556 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2557 output_quoted_string(p
->out
, azArg
[i
]);
2559 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2562 raw_printf(p
->out
,");\n");
2566 if( azArg
==0 ) break;
2568 fputs("[{", p
->out
);
2570 fputs(",\n{", p
->out
);
2573 for(i
=0; i
<nArg
; i
++){
2574 output_json_string(p
->out
, azCol
[i
], -1);
2576 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2577 fputs("null",p
->out
);
2578 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2580 double r
= sqlite3_column_double(p
->pStmt
, i
);
2582 memcpy(&ur
,&r
,sizeof(r
));
2583 if( ur
==0x7ff0000000000000LL
){
2584 raw_printf(p
->out
, "1e999");
2585 }else if( ur
==0xfff0000000000000LL
){
2586 raw_printf(p
->out
, "-1e999");
2588 sqlite3_snprintf(50,z
,"%!.20g", r
);
2589 raw_printf(p
->out
, "%s", z
);
2591 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2592 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2593 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2594 output_json_string(p
->out
, pBlob
, nBlob
);
2595 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2596 output_json_string(p
->out
, azArg
[i
], -1);
2598 utf8_printf(p
->out
,"%s", azArg
[i
]);
2608 if( azArg
==0 ) break;
2609 if( p
->cnt
==0 && p
->showHeader
){
2610 for(i
=0; i
<nArg
; i
++){
2611 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2612 output_quoted_string(p
->out
, azCol
[i
]);
2614 fputs(p
->rowSeparator
, p
->out
);
2617 for(i
=0; i
<nArg
; i
++){
2618 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2619 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2620 utf8_printf(p
->out
,"NULL");
2621 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2622 output_quoted_string(p
->out
, azArg
[i
]);
2623 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2624 utf8_printf(p
->out
,"%s", azArg
[i
]);
2625 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2627 double r
= sqlite3_column_double(p
->pStmt
, i
);
2628 sqlite3_snprintf(50,z
,"%!.20g", r
);
2629 raw_printf(p
->out
, "%s", z
);
2630 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2631 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2632 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2633 output_hex_blob(p
->out
, pBlob
, nBlob
);
2634 }else if( isNumber(azArg
[i
], 0) ){
2635 utf8_printf(p
->out
,"%s", azArg
[i
]);
2637 output_quoted_string(p
->out
, azArg
[i
]);
2640 fputs(p
->rowSeparator
, p
->out
);
2644 if( p
->cnt
++==0 && p
->showHeader
){
2645 for(i
=0; i
<nArg
; i
++){
2646 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2647 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2649 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2651 if( azArg
==0 ) break;
2652 for(i
=0; i
<nArg
; i
++){
2653 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2654 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2656 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2660 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2668 ** This is the callback routine that the SQLite library
2669 ** invokes for each row of a query result.
2671 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2672 /* since we don't have type info, call the shell_callback with a NULL value */
2673 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2677 ** This is the callback routine from sqlite3_exec() that appends all
2678 ** output onto the end of a ShellText object.
2680 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2681 ShellText
*p
= (ShellText
*)pArg
;
2683 UNUSED_PARAMETER(az
);
2684 if( azArg
==0 ) return 0;
2685 if( p
->n
) appendText(p
, "|", 0);
2686 for(i
=0; i
<nArg
; i
++){
2687 if( i
) appendText(p
, ",", 0);
2688 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2694 ** Generate an appropriate SELFTEST table in the main database.
2696 static void createSelftestTable(ShellState
*p
){
2699 "SAVEPOINT selftest_init;\n"
2700 "CREATE TABLE IF NOT EXISTS selftest(\n"
2701 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2702 " op TEXT,\n" /* Operator: memo run */
2703 " cmd TEXT,\n" /* Command text */
2704 " ans TEXT\n" /* Desired answer */
2706 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2707 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2708 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2709 " 'memo','Tests generated by --init');\n"
2710 "INSERT INTO [_shell$self]\n"
2712 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2713 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2714 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2715 "FROM sqlite_schema ORDER BY 2',224));\n"
2716 "INSERT INTO [_shell$self]\n"
2718 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2719 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2720 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2722 " SELECT name FROM sqlite_schema\n"
2723 " WHERE type='table'\n"
2724 " AND name<>'selftest'\n"
2725 " AND coalesce(rootpage,0)>0\n"
2728 "INSERT INTO [_shell$self]\n"
2729 " VALUES('run','PRAGMA integrity_check','ok');\n"
2730 "INSERT INTO selftest(tno,op,cmd,ans)"
2731 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2732 "DROP TABLE [_shell$self];"
2735 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2736 sqlite3_free(zErrMsg
);
2738 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2743 ** Set the destination table field of the ShellState structure to
2744 ** the name of the table given. Escape any quote characters in the
2747 static void set_table_name(ShellState
*p
, const char *zName
){
2752 if( p
->zDestTable
){
2753 free(p
->zDestTable
);
2756 if( zName
==0 ) return;
2757 cQuote
= quoteChar(zName
);
2758 n
= strlen30(zName
);
2759 if( cQuote
) n
+= n
+2;
2760 z
= p
->zDestTable
= malloc( n
+1 );
2763 if( cQuote
) z
[n
++] = cQuote
;
2764 for(i
=0; zName
[i
]; i
++){
2766 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2768 if( cQuote
) z
[n
++] = cQuote
;
2773 ** Maybe construct two lines of text that point out the position of a
2774 ** syntax error. Return a pointer to the text, in memory obtained from
2775 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2776 ** specific token that we can point to, return an empty string.
2778 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2779 ** and should be released by the caller invoking sqlite3_free().
2781 static char *shell_error_context(const char *zSql
, sqlite3
*db
){
2789 || (iOffset
= sqlite3_error_offset(db
))<0
2790 || iOffset
>=strlen(zSql
)
2792 return sqlite3_mprintf("");
2794 while( iOffset
>50 ){
2797 while( (zSql
[0]&0xc0)==0x80 ){ zSql
++; iOffset
--; }
2802 while( (zSql
[len
]&0xc0)==0x80 ) len
--;
2804 zCode
= sqlite3_mprintf("%.*s", len
, zSql
);
2805 shell_check_oom(zCode
);
2806 for(i
=0; zCode
[i
]; i
++){ if( IsSpace(zSql
[i
]) ) zCode
[i
] = ' '; }
2808 zMsg
= sqlite3_mprintf("\n %z\n %*s^--- error here", zCode
,iOffset
,"");
2810 zMsg
= sqlite3_mprintf("\n %z\n %*serror here ---^", zCode
,iOffset
-14,"");
2817 ** Execute a query statement that will generate SQL output. Print
2818 ** the result columns, comma-separated, on a line and then add a
2819 ** semicolon terminator to the end of that line.
2821 ** If the number of columns is 1 and that column contains text "--"
2822 ** then write the semicolon on a separate line. That way, if a
2823 ** "--" comment occurs at the end of the statement, the comment
2824 ** won't consume the semicolon terminator.
2826 static int run_table_dump_query(
2827 ShellState
*p
, /* Query context */
2828 const char *zSelect
/* SELECT statement to extract content */
2830 sqlite3_stmt
*pSelect
;
2835 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2836 if( rc
!=SQLITE_OK
|| !pSelect
){
2837 char *zContext
= shell_error_context(zSelect
, p
->db
);
2838 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n%s", rc
,
2839 sqlite3_errmsg(p
->db
), zContext
);
2840 sqlite3_free(zContext
);
2841 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2844 rc
= sqlite3_step(pSelect
);
2845 nResult
= sqlite3_column_count(pSelect
);
2846 while( rc
==SQLITE_ROW
){
2847 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2848 utf8_printf(p
->out
, "%s", z
);
2849 for(i
=1; i
<nResult
; i
++){
2850 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2853 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2855 raw_printf(p
->out
, "\n;\n");
2857 raw_printf(p
->out
, ";\n");
2859 rc
= sqlite3_step(pSelect
);
2861 rc
= sqlite3_finalize(pSelect
);
2862 if( rc
!=SQLITE_OK
){
2863 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2864 sqlite3_errmsg(p
->db
));
2865 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2871 ** Allocate space and save off string indicating current error.
2873 static char *save_err_msg(
2874 sqlite3
*db
, /* Database to query */
2875 const char *zPhase
, /* When the error occcurs */
2876 int rc
, /* Error code returned from API */
2877 const char *zSql
/* SQL string, or NULL */
2881 sqlite3_str
*pStr
= sqlite3_str_new(0);
2882 sqlite3_str_appendf(pStr
, "%s, %s", zPhase
, sqlite3_errmsg(db
));
2884 sqlite3_str_appendf(pStr
, " (%d)", rc
);
2886 zContext
= shell_error_context(zSql
, db
);
2888 sqlite3_str_appendall(pStr
, zContext
);
2889 sqlite3_free(zContext
);
2891 zErr
= sqlite3_str_finish(pStr
);
2892 shell_check_oom(zErr
);
2898 ** Attempt to display I/O stats on Linux using /proc/PID/io
2900 static void displayLinuxIoStats(FILE *out
){
2903 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2904 in
= fopen(z
, "rb");
2906 while( fgets(z
, sizeof(z
), in
)!=0 ){
2907 static const struct {
2908 const char *zPattern
;
2911 { "rchar: ", "Bytes received by read():" },
2912 { "wchar: ", "Bytes sent to write():" },
2913 { "syscr: ", "Read() system calls:" },
2914 { "syscw: ", "Write() system calls:" },
2915 { "read_bytes: ", "Bytes read from storage:" },
2916 { "write_bytes: ", "Bytes written to storage:" },
2917 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2920 for(i
=0; i
<ArraySize(aTrans
); i
++){
2921 int n
= strlen30(aTrans
[i
].zPattern
);
2922 if( cli_strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2923 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2933 ** Display a single line of status using 64-bit values.
2935 static void displayStatLine(
2936 ShellState
*p
, /* The shell context */
2937 char *zLabel
, /* Label for this one line */
2938 char *zFormat
, /* Format for the result */
2939 int iStatusCtrl
, /* Which status to display */
2940 int bReset
/* True to reset the stats */
2942 sqlite3_int64 iCur
= -1;
2943 sqlite3_int64 iHiwtr
= -1;
2946 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2947 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2948 if( zFormat
[i
]=='%' ) nPercent
++;
2951 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2953 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2955 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2959 ** Display memory stats.
2961 static int display_stats(
2962 sqlite3
*db
, /* Database to query */
2963 ShellState
*pArg
, /* Pointer to ShellState */
2964 int bReset
/* True to reset the stats */
2969 if( pArg
==0 || pArg
->out
==0 ) return 0;
2972 if( pArg
->pStmt
&& pArg
->statsOn
==2 ){
2974 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
2976 nCol
= sqlite3_column_count(pStmt
);
2977 raw_printf(out
, "%-36s %d\n", "Number of output columns:", nCol
);
2978 for(i
=0; i
<nCol
; i
++){
2979 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
2980 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
2981 #ifndef SQLITE_OMIT_DECLTYPE
2982 sqlite3_snprintf(30, z
+x
, "declared type:");
2983 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
2985 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2986 sqlite3_snprintf(30, z
+x
, "database name:");
2987 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
2988 sqlite3_snprintf(30, z
+x
, "table name:");
2989 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
2990 sqlite3_snprintf(30, z
+x
, "origin name:");
2991 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
2996 if( pArg
->statsOn
==3 ){
2998 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
,bReset
);
2999 raw_printf(pArg
->out
, "VM-steps: %d\n", iCur
);
3004 displayStatLine(pArg
, "Memory Used:",
3005 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
3006 displayStatLine(pArg
, "Number of Outstanding Allocations:",
3007 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
3008 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
3009 displayStatLine(pArg
, "Number of Pcache Pages Used:",
3010 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
3012 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
3013 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
3014 displayStatLine(pArg
, "Largest Allocation:",
3015 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
3016 displayStatLine(pArg
, "Largest Pcache Allocation:",
3017 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
3018 #ifdef YYTRACKMAXSTACKDEPTH
3019 displayStatLine(pArg
, "Deepest Parser Stack:",
3020 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
3024 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
3026 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
3027 &iCur
, &iHiwtr
, bReset
);
3028 raw_printf(pArg
->out
,
3029 "Lookaside Slots Used: %d (max %d)\n",
3031 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
3032 &iCur
, &iHiwtr
, bReset
);
3033 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
3035 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
3036 &iCur
, &iHiwtr
, bReset
);
3037 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
3039 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
3040 &iCur
, &iHiwtr
, bReset
);
3041 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
3045 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
3046 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
3049 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
3050 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
3052 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
3053 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
3055 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
3056 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
3058 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
3059 raw_printf(pArg
->out
, "Page cache spills: %d\n", iCur
);
3061 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
3062 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
3065 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
3066 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
3072 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
3074 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
3075 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
3076 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
3077 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
3078 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
3079 iHit
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_HIT
,
3081 iMiss
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_MISS
,
3083 if( iHit
|| iMiss
){
3084 raw_printf(pArg
->out
, "Bloom filter bypass taken: %d/%d\n",
3087 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
3088 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
3089 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
,bReset
);
3090 raw_printf(pArg
->out
, "Reprepare operations: %d\n", iCur
);
3091 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
3092 raw_printf(pArg
->out
, "Number of times run: %d\n", iCur
);
3093 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
3094 raw_printf(pArg
->out
, "Memory used by prepared stmt: %d\n", iCur
);
3098 displayLinuxIoStats(pArg
->out
);
3101 /* Do not remove this machine readable comment: extra-stats-output-here */
3107 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3108 static int scanStatsHeight(sqlite3_stmt
*p
, int iEntry
){
3111 sqlite3_stmt_scanstatus_v2(p
, iEntry
,
3112 SQLITE_SCANSTAT_SELECTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iPid
3119 res
= sqlite3_stmt_scanstatus_v2(p
, ii
,
3120 SQLITE_SCANSTAT_SELECTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iId
3124 sqlite3_stmt_scanstatus_v2(p
, ii
,
3125 SQLITE_SCANSTAT_PARENTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iPid
3136 ** Display scan stats.
3138 static void display_scanstats(
3139 sqlite3
*db
, /* Database to query */
3140 ShellState
*pArg
/* Pointer to ShellState */
3142 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3143 UNUSED_PARAMETER(db
);
3144 UNUSED_PARAMETER(pArg
);
3146 static const int f
= SQLITE_SCANSTAT_COMPLEX
;
3147 sqlite3_stmt
*p
= pArg
->pStmt
;
3156 if( sqlite3_stmt_scanstatus_v2(p
,ii
,SQLITE_SCANSTAT_EXPLAIN
,f
,(void*)&z
) ){
3159 n
= strlen(z
) + scanStatsHeight(p
, ii
)*3;
3160 if( n
>nWidth
) nWidth
= n
;
3164 sqlite3_stmt_scanstatus_v2(p
, -1, SQLITE_SCANSTAT_NCYCLE
, f
, (void*)&nTotal
);
3172 const char *zName
= 0;
3176 if( sqlite3_stmt_scanstatus_v2(p
,ii
,SQLITE_SCANSTAT_EXPLAIN
,f
,(void*)&z
) ){
3179 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_EST
,f
,(void*)&rEst
);
3180 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NLOOP
,f
,(void*)&nLoop
);
3181 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NVISIT
,f
,(void*)&nRow
);
3182 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NCYCLE
,f
,(void*)&nCycle
);
3183 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_SELECTID
,f
,(void*)&iId
);
3184 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_PARENTID
,f
,(void*)&iPid
);
3185 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NAME
,f
,(void*)&zName
);
3187 zText
= sqlite3_mprintf("%s", z
);
3188 if( nCycle
>=0 || nLoop
>=0 || nRow
>=0 ){
3190 if( nCycle
>=0 && nTotal
>0 ){
3191 z
= sqlite3_mprintf("%zcycles=%lld [%d%%]", z
,
3192 nCycle
, ((nCycle
*100)+nTotal
/2) / nTotal
3196 z
= sqlite3_mprintf("%z%sloops=%lld", z
, z
? " " : "", nLoop
);
3199 z
= sqlite3_mprintf("%z%srows=%lld", z
, z
? " " : "", nRow
);
3202 if( zName
&& pArg
->scanstatsOn
>1 ){
3203 double rpl
= (double)nRow
/ (double)nLoop
;
3204 z
= sqlite3_mprintf("%z rpl=%.1f est=%.1f", z
, rpl
, rEst
);
3207 zText
= sqlite3_mprintf(
3208 "% *z (%z)", -1*(nWidth
-scanStatsHeight(p
, ii
)*3), zText
, z
3212 eqp_append(pArg
, iId
, iPid
, zText
);
3213 sqlite3_free(zText
);
3216 eqp_render(pArg
, nTotal
);
3221 ** Parameter azArray points to a zero-terminated array of strings. zStr
3222 ** points to a single nul-terminated string. Return non-zero if zStr
3223 ** is equal, according to strcmp(), to any of the strings in the array.
3224 ** Otherwise, return zero.
3226 static int str_in_array(const char *zStr
, const char **azArray
){
3228 for(i
=0; azArray
[i
]; i
++){
3229 if( 0==cli_strcmp(zStr
, azArray
[i
]) ) return 1;
3235 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3236 ** and populate the ShellState.aiIndent[] array with the number of
3237 ** spaces each opcode should be indented before it is output.
3239 ** The indenting rules are:
3241 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3242 ** all opcodes that occur between the p2 jump destination and the opcode
3243 ** itself by 2 spaces.
3245 ** * Do the previous for "Return" instructions for when P2 is positive.
3246 ** See tag-20220407a in wherecode.c and vdbe.c.
3248 ** * For each "Goto", if the jump destination is earlier in the program
3249 ** and ends on one of:
3250 ** Yield SeekGt SeekLt RowSetRead Rewind
3251 ** or if the P1 parameter is one instead of zero,
3252 ** then indent all opcodes between the earlier instruction
3253 ** and "Goto" by 2 spaces.
3255 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
3256 const char *zSql
; /* The text of the SQL statement */
3257 const char *z
; /* Used to check if this is an EXPLAIN */
3258 int *abYield
= 0; /* True if op is an OP_Yield */
3259 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
3260 int iOp
; /* Index of operation in p->aiIndent[] */
3262 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3264 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3266 const char *azGoto
[] = { "Goto", 0 };
3268 /* Try to figure out if this is really an EXPLAIN statement. If this
3269 ** cannot be verified, return early. */
3270 if( sqlite3_column_count(pSql
)!=8 ){
3274 zSql
= sqlite3_sql(pSql
);
3275 if( zSql
==0 ) return;
3276 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
3277 if( sqlite3_strnicmp(z
, "explain", 7) ){
3282 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
3284 int iAddr
= sqlite3_column_int(pSql
, 0);
3285 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
3287 /* Set p2 to the P2 field of the current opcode. Then, assuming that
3288 ** p2 is an instruction address, set variable p2op to the index of that
3289 ** instruction in the aiIndent[] array. p2 and p2op may be different if
3290 ** the current instruction is part of a sub-program generated by an
3291 ** SQL trigger or foreign key. */
3292 int p2
= sqlite3_column_int(pSql
, 3);
3293 int p2op
= (p2
+ (iOp
-iAddr
));
3295 /* Grow the p->aiIndent array as required */
3298 /* Do further verfication that this is explain output. Abort if
3300 static const char *explainCols
[] = {
3301 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3303 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
3304 if( cli_strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
3306 sqlite3_reset(pSql
);
3312 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
3313 shell_check_oom(p
->aiIndent
);
3314 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
3315 shell_check_oom(abYield
);
3317 abYield
[iOp
] = str_in_array(zOp
, azYield
);
3318 p
->aiIndent
[iOp
] = 0;
3321 if( str_in_array(zOp
, azNext
) && p2op
>0 ){
3322 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3324 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
3325 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
3327 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3332 sqlite3_free(abYield
);
3333 sqlite3_reset(pSql
);
3337 ** Free the array allocated by explain_data_prepare().
3339 static void explain_data_delete(ShellState
*p
){
3340 sqlite3_free(p
->aiIndent
);
3347 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3349 static unsigned int savedSelectTrace
;
3350 static unsigned int savedWhereTrace
;
3351 static void disable_debug_trace_modes(void){
3352 unsigned int zero
= 0;
3353 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 0, &savedSelectTrace
);
3354 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &zero
);
3355 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 2, &savedWhereTrace
);
3356 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &zero
);
3358 static void restore_debug_trace_modes(void){
3359 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &savedSelectTrace
);
3360 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &savedWhereTrace
);
3363 /* Create the TEMP table used to store parameter bindings */
3364 static void bind_table_init(ShellState
*p
){
3366 int defensiveMode
= 0;
3367 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, -1, &defensiveMode
);
3368 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, 0, 0);
3369 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, -1, &wrSchema
);
3370 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, 1, 0);
3372 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3373 " key TEXT PRIMARY KEY,\n"
3377 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, wrSchema
, 0);
3378 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, defensiveMode
, 0);
3382 ** Bind parameters on a prepared statement.
3384 ** Parameter bindings are taken from a TEMP table of the form:
3386 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3389 ** No bindings occur if this table does not exist. The name of the table
3390 ** begins with "sqlite_" so that it will not collide with ordinary application
3391 ** tables. The table must be in the TEMP schema.
3393 static void bind_prepared_stmt(ShellState
*pArg
, sqlite3_stmt
*pStmt
){
3397 sqlite3_stmt
*pQ
= 0;
3399 nVar
= sqlite3_bind_parameter_count(pStmt
);
3400 if( nVar
==0 ) return; /* Nothing to do */
3401 if( sqlite3_table_column_metadata(pArg
->db
, "TEMP", "sqlite_parameters",
3402 "key", 0, 0, 0, 0, 0)!=SQLITE_OK
){
3403 return; /* Parameter table does not exist */
3405 rc
= sqlite3_prepare_v2(pArg
->db
,
3406 "SELECT value FROM temp.sqlite_parameters"
3407 " WHERE key=?1", -1, &pQ
, 0);
3408 if( rc
|| pQ
==0 ) return;
3409 for(i
=1; i
<=nVar
; i
++){
3411 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
3413 sqlite3_snprintf(sizeof(zNum
),zNum
,"?%d",i
);
3416 sqlite3_bind_text(pQ
, 1, zVar
, -1, SQLITE_STATIC
);
3417 if( sqlite3_step(pQ
)==SQLITE_ROW
){
3418 sqlite3_bind_value(pStmt
, i
, sqlite3_column_value(pQ
, 0));
3420 sqlite3_bind_null(pStmt
, i
);
3424 sqlite3_finalize(pQ
);
3428 ** UTF8 box-drawing characters. Imagine box lines like this:
3436 ** Each box characters has between 2 and 4 of the lines leading from
3437 ** the center. The characters are here identified by the numbers of
3438 ** their corresponding lines.
3440 #define BOX_24 "\342\224\200" /* U+2500 --- */
3441 #define BOX_13 "\342\224\202" /* U+2502 | */
3442 #define BOX_23 "\342\224\214" /* U+250c ,- */
3443 #define BOX_34 "\342\224\220" /* U+2510 -, */
3444 #define BOX_12 "\342\224\224" /* U+2514 '- */
3445 #define BOX_14 "\342\224\230" /* U+2518 -' */
3446 #define BOX_123 "\342\224\234" /* U+251c |- */
3447 #define BOX_134 "\342\224\244" /* U+2524 -| */
3448 #define BOX_234 "\342\224\254" /* U+252c -,- */
3449 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3450 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3452 /* Draw horizontal line N characters long using unicode box
3455 static void print_box_line(FILE *out
, int N
){
3456 const char zDash
[] =
3457 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3458 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
;
3459 const int nDash
= sizeof(zDash
) - 1;
3462 utf8_printf(out
, zDash
);
3465 utf8_printf(out
, "%.*s", N
, zDash
);
3469 ** Draw a horizontal separator for a MODE_Box table.
3471 static void print_box_row_separator(
3480 utf8_printf(p
->out
, "%s", zSep1
);
3481 print_box_line(p
->out
, p
->actualWidth
[0]+2);
3482 for(i
=1; i
<nArg
; i
++){
3483 utf8_printf(p
->out
, "%s", zSep2
);
3484 print_box_line(p
->out
, p
->actualWidth
[i
]+2);
3486 utf8_printf(p
->out
, "%s", zSep3
);
3488 fputs("\n", p
->out
);
3492 ** z[] is a line of text that is to be displayed the .mode box or table or
3493 ** similar tabular formats. z[] might contain control characters such
3494 ** as \n, \t, \f, or \r.
3496 ** Compute characters to display on the first line of z[]. Stop at the
3497 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3498 ** from malloc()) of that first line, which caller should free sometime.
3499 ** Write anything to display on the next line into *pzTail. If this is
3500 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3502 static char *translateForDisplayAndDup(
3503 const unsigned char *z
, /* Input text to be transformed */
3504 const unsigned char **pzTail
, /* OUT: Tail of the input for next line */
3505 int mxWidth
, /* Max width. 0 means no limit */
3506 u8 bWordWrap
/* If true, avoid breaking mid-word */
3508 int i
; /* Input bytes consumed */
3509 int j
; /* Output bytes generated */
3510 int k
; /* Input bytes to be displayed */
3511 int n
; /* Output column number */
3512 unsigned char *zOut
; /* Output text */
3518 if( mxWidth
<0 ) mxWidth
= -mxWidth
;
3519 if( mxWidth
==0 ) mxWidth
= 1000000;
3524 do{ i
++; j
++; }while( (z
[i
]&0xc0)==0x80 );
3531 }while( (n
&7)!=0 && n
<mxWidth
);
3537 if( n
>=mxWidth
&& bWordWrap
){
3538 /* Perhaps try to back up to a better place to break the line */
3539 for(k
=i
; k
>i
/2; k
--){
3540 if( isspace(z
[k
-1]) ) break;
3543 for(k
=i
; k
>i
/2; k
--){
3544 if( isalnum(z
[k
-1])!=isalnum(z
[k
]) && (z
[k
]&0xc0)!=0x80 ) break;
3551 while( z
[i
]==' ' ) i
++;
3556 if( n
>=mxWidth
&& z
[i
]>=' ' ){
3558 }else if( z
[i
]=='\r' && z
[i
+1]=='\n' ){
3559 *pzTail
= z
[i
+2] ? &z
[i
+2] : 0;
3560 }else if( z
[i
]==0 || z
[i
+1]==0 ){
3565 zOut
= malloc( j
+1 );
3566 shell_check_oom(zOut
);
3571 do{ zOut
[j
++] = z
[i
++]; }while( (z
[i
]&0xc0)==0x80 );
3578 }while( (n
&7)!=0 && n
<mxWidth
);
3588 /* Extract the value of the i-th current column for pStmt as an SQL literal
3589 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3592 static char *quoted_column(sqlite3_stmt
*pStmt
, int i
){
3593 switch( sqlite3_column_type(pStmt
, i
) ){
3595 return sqlite3_mprintf("NULL");
3597 case SQLITE_INTEGER
:
3598 case SQLITE_FLOAT
: {
3599 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt
,i
));
3602 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt
,i
));
3606 sqlite3_str
*pStr
= sqlite3_str_new(0);
3607 const unsigned char *a
= sqlite3_column_blob(pStmt
,i
);
3608 int n
= sqlite3_column_bytes(pStmt
,i
);
3609 sqlite3_str_append(pStr
, "x'", 2);
3611 sqlite3_str_appendf(pStr
, "%02x", a
[j
]);
3613 sqlite3_str_append(pStr
, "'", 1);
3614 return sqlite3_str_finish(pStr
);
3617 return 0; /* Not reached */
3621 ** Run a prepared statement and output the result in one of the
3622 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3625 ** This is different from ordinary exec_prepared_stmt() in that
3626 ** it has to run the entire query and gather the results into memory
3627 ** first, in order to determine column widths, before providing
3630 static void exec_prepared_stmt_columnar(
3631 ShellState
*p
, /* Pointer to ShellState */
3632 sqlite3_stmt
*pStmt
/* Statment to run */
3634 sqlite3_int64 nRow
= 0;
3637 sqlite3_int64 nAlloc
= 0;
3639 const unsigned char *uz
;
3641 char **azQuoted
= 0;
3643 sqlite3_int64 i
, nData
;
3644 int j
, nTotal
, w
, n
;
3645 const char *colSep
= 0;
3646 const char *rowSep
= 0;
3647 const unsigned char **azNextLine
= 0;
3649 int bMultiLineRowExists
= 0;
3650 int bw
= p
->cmOpts
.bWordWrap
;
3651 const char *zEmpty
= "";
3652 const char *zShowNull
= p
->nullValue
;
3654 rc
= sqlite3_step(pStmt
);
3655 if( rc
!=SQLITE_ROW
) return;
3656 nColumn
= sqlite3_column_count(pStmt
);
3658 if( nAlloc
<=0 ) nAlloc
= 1;
3659 azData
= sqlite3_malloc64( nAlloc
*sizeof(char*) );
3660 shell_check_oom(azData
);
3661 azNextLine
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3662 shell_check_oom((void*)azNextLine
);
3663 memset((void*)azNextLine
, 0, nColumn
*sizeof(char*) );
3664 if( p
->cmOpts
.bQuote
){
3665 azQuoted
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3666 shell_check_oom(azQuoted
);
3667 memset(azQuoted
, 0, nColumn
*sizeof(char*) );
3669 abRowDiv
= sqlite3_malloc64( nAlloc
/nColumn
);
3670 shell_check_oom(abRowDiv
);
3671 if( nColumn
>p
->nWidth
){
3672 p
->colWidth
= realloc(p
->colWidth
, (nColumn
+1)*2*sizeof(int));
3673 shell_check_oom(p
->colWidth
);
3674 for(i
=p
->nWidth
; i
<nColumn
; i
++) p
->colWidth
[i
] = 0;
3675 p
->nWidth
= nColumn
;
3676 p
->actualWidth
= &p
->colWidth
[nColumn
];
3678 memset(p
->actualWidth
, 0, nColumn
*sizeof(int));
3679 for(i
=0; i
<nColumn
; i
++){
3682 p
->actualWidth
[i
] = w
;
3684 for(i
=0; i
<nColumn
; i
++){
3685 const unsigned char *zNotUsed
;
3686 int wx
= p
->colWidth
[i
];
3688 wx
= p
->cmOpts
.iWrap
;
3690 if( wx
<0 ) wx
= -wx
;
3691 uz
= (const unsigned char*)sqlite3_column_name(pStmt
,i
);
3692 azData
[i
] = translateForDisplayAndDup(uz
, &zNotUsed
, wx
, bw
);
3695 int useNextLine
= bNextLine
;
3697 if( (nRow
+2)*nColumn
>= nAlloc
){
3699 azData
= sqlite3_realloc64(azData
, nAlloc
*sizeof(char*));
3700 shell_check_oom(azData
);
3701 abRowDiv
= sqlite3_realloc64(abRowDiv
, nAlloc
/nColumn
);
3702 shell_check_oom(abRowDiv
);
3706 for(i
=0; i
<nColumn
; i
++){
3707 int wx
= p
->colWidth
[i
];
3709 wx
= p
->cmOpts
.iWrap
;
3711 if( wx
<0 ) wx
= -wx
;
3714 if( uz
==0 ) uz
= (u8
*)zEmpty
;
3715 }else if( p
->cmOpts
.bQuote
){
3716 sqlite3_free(azQuoted
[i
]);
3717 azQuoted
[i
] = quoted_column(pStmt
,i
);
3718 uz
= (const unsigned char*)azQuoted
[i
];
3720 uz
= (const unsigned char*)sqlite3_column_text(pStmt
,i
);
3721 if( uz
==0 ) uz
= (u8
*)zShowNull
;
3723 azData
[nRow
*nColumn
+ i
]
3724 = translateForDisplayAndDup(uz
, &azNextLine
[i
], wx
, bw
);
3725 if( azNextLine
[i
] ){
3727 abRowDiv
[nRow
-1] = 0;
3728 bMultiLineRowExists
= 1;
3731 }while( bNextLine
|| sqlite3_step(pStmt
)==SQLITE_ROW
);
3732 nTotal
= nColumn
*(nRow
+1);
3733 for(i
=0; i
<nTotal
; i
++){
3735 if( z
==0 ) z
= (char*)zEmpty
;
3738 if( n
>p
->actualWidth
[j
] ) p
->actualWidth
[j
] = n
;
3740 if( seenInterrupt
) goto columnar_end
;
3741 if( nColumn
==0 ) goto columnar_end
;
3746 if( p
->showHeader
){
3747 for(i
=0; i
<nColumn
; i
++){
3748 w
= p
->actualWidth
[i
];
3749 if( p
->colWidth
[i
]<0 ) w
= -w
;
3750 utf8_width_print(p
->out
, w
, azData
[i
]);
3751 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3753 for(i
=0; i
<nColumn
; i
++){
3754 print_dashes(p
->out
, p
->actualWidth
[i
]);
3755 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3763 print_row_separator(p
, nColumn
, "+");
3764 fputs("| ", p
->out
);
3765 for(i
=0; i
<nColumn
; i
++){
3766 w
= p
->actualWidth
[i
];
3767 n
= strlenChar(azData
[i
]);
3768 utf8_printf(p
->out
, "%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3769 fputs(i
==nColumn
-1?" |\n":" | ", p
->out
);
3771 print_row_separator(p
, nColumn
, "+");
3774 case MODE_Markdown
: {
3777 fputs("| ", p
->out
);
3778 for(i
=0; i
<nColumn
; i
++){
3779 w
= p
->actualWidth
[i
];
3780 n
= strlenChar(azData
[i
]);
3781 utf8_printf(p
->out
, "%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3782 fputs(i
==nColumn
-1?" |\n":" | ", p
->out
);
3784 print_row_separator(p
, nColumn
, "|");
3788 colSep
= " " BOX_13
" ";
3789 rowSep
= " " BOX_13
"\n";
3790 print_box_row_separator(p
, nColumn
, BOX_23
, BOX_234
, BOX_34
);
3791 utf8_printf(p
->out
, BOX_13
" ");
3792 for(i
=0; i
<nColumn
; i
++){
3793 w
= p
->actualWidth
[i
];
3794 n
= strlenChar(azData
[i
]);
3795 utf8_printf(p
->out
, "%*s%s%*s%s",
3796 (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "",
3797 i
==nColumn
-1?" "BOX_13
"\n":" "BOX_13
" ");
3799 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3803 for(i
=nColumn
, j
=0; i
<nTotal
; i
++, j
++){
3804 if( j
==0 && p
->cMode
!=MODE_Column
){
3805 utf8_printf(p
->out
, "%s", p
->cMode
==MODE_Box
?BOX_13
" ":"| ");
3808 if( z
==0 ) z
= p
->nullValue
;
3809 w
= p
->actualWidth
[j
];
3810 if( p
->colWidth
[j
]<0 ) w
= -w
;
3811 utf8_width_print(p
->out
, w
, z
);
3813 utf8_printf(p
->out
, "%s", rowSep
);
3814 if( bMultiLineRowExists
&& abRowDiv
[i
/nColumn
-1] && i
+1<nTotal
){
3815 if( p
->cMode
==MODE_Table
){
3816 print_row_separator(p
, nColumn
, "+");
3817 }else if( p
->cMode
==MODE_Box
){
3818 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3819 }else if( p
->cMode
==MODE_Column
){
3820 raw_printf(p
->out
, "\n");
3824 if( seenInterrupt
) goto columnar_end
;
3826 utf8_printf(p
->out
, "%s", colSep
);
3829 if( p
->cMode
==MODE_Table
){
3830 print_row_separator(p
, nColumn
, "+");
3831 }else if( p
->cMode
==MODE_Box
){
3832 print_box_row_separator(p
, nColumn
, BOX_12
, BOX_124
, BOX_14
);
3835 if( seenInterrupt
){
3836 utf8_printf(p
->out
, "Interrupt\n");
3838 nData
= (nRow
+1)*nColumn
;
3839 for(i
=0; i
<nData
; i
++){
3841 if( z
!=zEmpty
&& z
!=zShowNull
) free(azData
[i
]);
3843 sqlite3_free(azData
);
3844 sqlite3_free((void*)azNextLine
);
3845 sqlite3_free(abRowDiv
);
3847 for(i
=0; i
<nColumn
; i
++) sqlite3_free(azQuoted
[i
]);
3848 sqlite3_free(azQuoted
);
3853 ** Run a prepared statement
3855 static void exec_prepared_stmt(
3856 ShellState
*pArg
, /* Pointer to ShellState */
3857 sqlite3_stmt
*pStmt
/* Statment to run */
3860 sqlite3_uint64 nRow
= 0;
3862 if( pArg
->cMode
==MODE_Column
3863 || pArg
->cMode
==MODE_Table
3864 || pArg
->cMode
==MODE_Box
3865 || pArg
->cMode
==MODE_Markdown
3867 exec_prepared_stmt_columnar(pArg
, pStmt
);
3871 /* perform the first step. this will tell us if we
3872 ** have a result set or not and how wide it is.
3874 rc
= sqlite3_step(pStmt
);
3875 /* if we have a result set... */
3876 if( SQLITE_ROW
== rc
){
3877 /* allocate space for col name ptr, value ptr, and type */
3878 int nCol
= sqlite3_column_count(pStmt
);
3879 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
3881 shell_out_of_memory();
3883 char **azCols
= (char **)pData
; /* Names of result columns */
3884 char **azVals
= &azCols
[nCol
]; /* Results */
3885 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
3887 assert(sizeof(int) <= sizeof(char *));
3888 /* save off ptrs to column names */
3889 for(i
=0; i
<nCol
; i
++){
3890 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
3894 /* extract the data and data types */
3895 for(i
=0; i
<nCol
; i
++){
3896 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
3899 && (pArg
->cMode
==MODE_Insert
|| pArg
->cMode
==MODE_Quote
)
3903 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
3905 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
3907 break; /* from for */
3911 /* if data and types extracted successfully... */
3912 if( SQLITE_ROW
== rc
){
3913 /* call the supplied callback with the result row data */
3914 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
3917 rc
= sqlite3_step(pStmt
);
3920 } while( SQLITE_ROW
== rc
);
3921 sqlite3_free(pData
);
3922 if( pArg
->cMode
==MODE_Json
){
3923 fputs("]\n", pArg
->out
);
3924 }else if( pArg
->cMode
==MODE_Count
){
3926 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%llu row%s\n",
3927 nRow
, nRow
!=1 ? "s" : "");
3934 #ifndef SQLITE_OMIT_VIRTUALTABLE
3936 ** This function is called to process SQL if the previous shell command
3937 ** was ".expert". It passes the SQL in the second argument directly to
3938 ** the sqlite3expert object.
3940 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3941 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3942 ** an English language error message. It is the responsibility of the
3943 ** caller to eventually free this buffer using sqlite3_free().
3945 static int expertHandleSQL(
3950 assert( pState
->expert
.pExpert
);
3951 assert( pzErr
==0 || *pzErr
==0 );
3952 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
3956 ** This function is called either to silently clean up the object
3957 ** created by the ".expert" command (if bCancel==1), or to generate a
3958 ** report from it and then clean it up (if bCancel==0).
3960 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3961 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3962 ** an English language error message. It is the responsibility of the
3963 ** caller to eventually free this buffer using sqlite3_free().
3965 static int expertFinish(
3971 sqlite3expert
*p
= pState
->expert
.pExpert
;
3973 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
3975 FILE *out
= pState
->out
;
3976 int bVerbose
= pState
->expert
.bVerbose
;
3978 rc
= sqlite3_expert_analyze(p
, pzErr
);
3979 if( rc
==SQLITE_OK
){
3980 int nQuery
= sqlite3_expert_count(p
);
3984 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
3985 raw_printf(out
, "-- Candidates -----------------------------\n");
3986 raw_printf(out
, "%s\n", zCand
);
3988 for(i
=0; i
<nQuery
; i
++){
3989 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
3990 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
3991 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
3992 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
3994 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
3995 raw_printf(out
, "%s\n\n", zSql
);
3997 raw_printf(out
, "%s\n", zIdx
);
3998 raw_printf(out
, "%s\n", zEQP
);
4002 sqlite3_expert_destroy(p
);
4003 pState
->expert
.pExpert
= 0;
4008 ** Implementation of ".expert" dot command.
4010 static int expertDotCommand(
4011 ShellState
*pState
, /* Current shell tool state */
4012 char **azArg
, /* Array of arguments passed to dot command */
4013 int nArg
/* Number of entries in azArg[] */
4020 assert( pState
->expert
.pExpert
==0 );
4021 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
4023 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
4026 if( z
[0]=='-' && z
[1]=='-' ) z
++;
4028 if( n
>=2 && 0==cli_strncmp(z
, "-verbose", n
) ){
4029 pState
->expert
.bVerbose
= 1;
4031 else if( n
>=2 && 0==cli_strncmp(z
, "-sample", n
) ){
4033 raw_printf(stderr
, "option requires an argument: %s\n", z
);
4036 iSample
= (int)integerValue(azArg
[++i
]);
4037 if( iSample
<0 || iSample
>100 ){
4038 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
4044 raw_printf(stderr
, "unknown option: %s\n", z
);
4049 if( rc
==SQLITE_OK
){
4050 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
4051 if( pState
->expert
.pExpert
==0 ){
4052 raw_printf(stderr
, "sqlite3_expert_new: %s\n",
4053 zErr
? zErr
: "out of memory");
4056 sqlite3_expert_config(
4057 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
4065 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4068 ** Execute a statement or set of statements. Print
4069 ** any result rows/columns depending on the current mode
4070 ** set via the supplied callback.
4072 ** This is very similar to SQLite's built-in sqlite3_exec()
4073 ** function except it takes a slightly different callback
4074 ** and callback data argument.
4076 static int shell_exec(
4077 ShellState
*pArg
, /* Pointer to ShellState */
4078 const char *zSql
, /* SQL to be evaluated */
4079 char **pzErrMsg
/* Error msg written here */
4081 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
4082 int rc
= SQLITE_OK
; /* Return Code */
4084 const char *zLeftover
; /* Tail of unprocessed SQL */
4085 sqlite3
*db
= pArg
->db
;
4091 #ifndef SQLITE_OMIT_VIRTUALTABLE
4092 if( pArg
->expert
.pExpert
){
4093 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
4094 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
4098 while( zSql
[0] && (SQLITE_OK
== rc
) ){
4099 static const char *zStmtSql
;
4100 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
4101 if( SQLITE_OK
!= rc
){
4103 *pzErrMsg
= save_err_msg(db
, "in prepare", rc
, zSql
);
4107 /* this happens for a comment or white-space */
4109 while( IsSpace(zSql
[0]) ) zSql
++;
4112 zStmtSql
= sqlite3_sql(pStmt
);
4113 if( zStmtSql
==0 ) zStmtSql
= "";
4114 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
4116 /* save off the prepared statment handle and reset row count */
4118 pArg
->pStmt
= pStmt
;
4122 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4123 if( pArg
&& pArg
->autoEQP
&& sqlite3_stmt_isexplain(pStmt
)==0 ){
4124 sqlite3_stmt
*pExplain
;
4127 disable_debug_trace_modes();
4128 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
4129 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
4130 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
4132 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
4133 shell_check_oom(zEQP
);
4134 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4135 if( rc
==SQLITE_OK
){
4136 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
4137 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
4138 int iEqpId
= sqlite3_column_int(pExplain
, 0);
4139 int iParentId
= sqlite3_column_int(pExplain
, 1);
4140 if( zEQPLine
==0 ) zEQPLine
= "";
4141 if( zEQPLine
[0]=='-' ) eqp_render(pArg
, 0);
4142 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
4144 eqp_render(pArg
, 0);
4146 sqlite3_finalize(pExplain
);
4148 if( pArg
->autoEQP
>=AUTOEQP_full
){
4149 /* Also do an EXPLAIN for ".eqp full" mode */
4150 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
4151 shell_check_oom(zEQP
);
4152 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4153 if( rc
==SQLITE_OK
){
4154 pArg
->cMode
= MODE_Explain
;
4155 explain_data_prepare(pArg
, pExplain
);
4156 exec_prepared_stmt(pArg
, pExplain
);
4157 explain_data_delete(pArg
);
4159 sqlite3_finalize(pExplain
);
4162 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
4163 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
4164 /* Reprepare pStmt before reactiving trace modes */
4165 sqlite3_finalize(pStmt
);
4166 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
4167 if( pArg
) pArg
->pStmt
= pStmt
;
4169 restore_debug_trace_modes();
4173 pArg
->cMode
= pArg
->mode
;
4174 if( pArg
->autoExplain
){
4175 if( sqlite3_stmt_isexplain(pStmt
)==1 ){
4176 pArg
->cMode
= MODE_Explain
;
4178 if( sqlite3_stmt_isexplain(pStmt
)==2 ){
4179 pArg
->cMode
= MODE_EQP
;
4183 /* If the shell is currently in ".explain" mode, gather the extra
4184 ** data required to add indents to the output.*/
4185 if( pArg
->cMode
==MODE_Explain
){
4186 explain_data_prepare(pArg
, pStmt
);
4190 bind_prepared_stmt(pArg
, pStmt
);
4191 exec_prepared_stmt(pArg
, pStmt
);
4192 explain_data_delete(pArg
);
4193 eqp_render(pArg
, 0);
4195 /* print usage stats if stats on */
4196 if( pArg
&& pArg
->statsOn
){
4197 display_stats(db
, pArg
, 0);
4200 /* print loop-counters if required */
4201 if( pArg
&& pArg
->scanstatsOn
){
4202 display_scanstats(db
, pArg
);
4205 /* Finalize the statement just executed. If this fails, save a
4206 ** copy of the error message. Otherwise, set zSql to point to the
4207 ** next statement to execute. */
4208 rc2
= sqlite3_finalize(pStmt
);
4209 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
4210 if( rc
==SQLITE_OK
){
4212 while( IsSpace(zSql
[0]) ) zSql
++;
4213 }else if( pzErrMsg
){
4214 *pzErrMsg
= save_err_msg(db
, "stepping", rc
, 0);
4217 /* clear saved stmt handle */
4228 ** Release memory previously allocated by tableColumnList().
4230 static void freeColumnList(char **azCol
){
4232 for(i
=1; azCol
[i
]; i
++){
4233 sqlite3_free(azCol
[i
]);
4235 /* azCol[0] is a static string */
4236 sqlite3_free(azCol
);
4240 ** Return a list of pointers to strings which are the names of all
4241 ** columns in table zTab. The memory to hold the names is dynamically
4242 ** allocated and must be released by the caller using a subsequent call
4243 ** to freeColumnList().
4245 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4246 ** value that needs to be preserved, then azCol[0] is filled in with the
4247 ** name of the rowid column.
4249 ** The first regular column in the table is azCol[1]. The list is terminated
4250 ** by an entry with azCol[i]==0.
4252 static char **tableColumnList(ShellState
*p
, const char *zTab
){
4254 sqlite3_stmt
*pStmt
;
4258 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
4259 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
4260 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
4263 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
4264 shell_check_oom(zSql
);
4265 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4268 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4269 if( nCol
>=nAlloc
-2 ){
4270 nAlloc
= nAlloc
*2 + nCol
+ 10;
4271 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
4272 shell_check_oom(azCol
);
4274 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
4275 shell_check_oom(azCol
[nCol
]);
4276 if( sqlite3_column_int(pStmt
, 5) ){
4279 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
4288 sqlite3_finalize(pStmt
);
4289 if( azCol
==0 ) return 0;
4293 /* The decision of whether or not a rowid really needs to be preserved
4294 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4295 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4296 ** rowids on tables where the rowid is inaccessible because there are other
4297 ** columns in the table named "rowid", "_rowid_", and "oid".
4299 if( preserveRowid
&& isIPK
){
4300 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4301 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
4302 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4303 ** ROWID aliases. To distinguish these cases, check to see if
4304 ** there is a "pk" entry in "PRAGMA index_list". There will be
4305 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4307 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4308 " WHERE origin='pk'", zTab
);
4309 shell_check_oom(zSql
);
4310 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4313 freeColumnList(azCol
);
4316 rc
= sqlite3_step(pStmt
);
4317 sqlite3_finalize(pStmt
);
4318 preserveRowid
= rc
==SQLITE_ROW
;
4320 if( preserveRowid
){
4321 /* Only preserve the rowid if we can find a name to use for the
4323 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
4326 for(i
=1; i
<=nCol
; i
++){
4327 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
4330 /* At this point, we know that azRowid[j] is not the name of any
4331 ** ordinary column in the table. Verify that azRowid[j] is a valid
4332 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4333 ** tables will fail this last check */
4334 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
4335 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
4344 ** Toggle the reverse_unordered_selects setting.
4346 static void toggleSelectOrder(sqlite3
*db
){
4347 sqlite3_stmt
*pStmt
= 0;
4350 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
4351 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
4352 iSetting
= sqlite3_column_int(pStmt
, 0);
4354 sqlite3_finalize(pStmt
);
4355 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
4356 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
4357 sqlite3_exec(db
, zStmt
, 0, 0, 0);
4361 ** This is a different callback routine used for dumping the database.
4362 ** Each row received by this callback consists of a table name,
4363 ** the table type ("index" or "table") and SQL to create the table.
4364 ** This routine should print text sufficient to recreate the table.
4366 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
4371 ShellState
*p
= (ShellState
*)pArg
;
4375 UNUSED_PARAMETER(azNotUsed
);
4376 if( nArg
!=3 || azArg
==0 ) return 0;
4380 if( zTable
==0 ) return 0;
4381 if( zType
==0 ) return 0;
4382 dataOnly
= (p
->shellFlgs
& SHFLG_DumpDataOnly
)!=0;
4383 noSys
= (p
->shellFlgs
& SHFLG_DumpNoSys
)!=0;
4385 if( cli_strcmp(zTable
, "sqlite_sequence")==0 && !noSys
){
4386 if( !dataOnly
) raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
4387 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 && !noSys
){
4388 if( !dataOnly
) raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
4389 }else if( cli_strncmp(zTable
, "sqlite_", 7)==0 ){
4391 }else if( dataOnly
){
4393 }else if( cli_strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
4395 if( !p
->writableSchema
){
4396 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
4397 p
->writableSchema
= 1;
4399 zIns
= sqlite3_mprintf(
4400 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4401 "VALUES('table','%q','%q',0,'%q');",
4402 zTable
, zTable
, zSql
);
4403 shell_check_oom(zIns
);
4404 utf8_printf(p
->out
, "%s\n", zIns
);
4408 printSchemaLine(p
->out
, zSql
, ";\n");
4411 if( cli_strcmp(zType
, "table")==0 ){
4416 char *savedDestTable
;
4419 azCol
= tableColumnList(p
, zTable
);
4425 /* Always quote the table name, even if it appears to be pure ascii,
4426 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4428 appendText(&sTable
, zTable
, quoteChar(zTable
));
4429 /* If preserving the rowid, add a column list after the table name.
4430 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4431 ** instead of the usual "INSERT INTO tab VALUES(...)".
4434 appendText(&sTable
, "(", 0);
4435 appendText(&sTable
, azCol
[0], 0);
4436 for(i
=1; azCol
[i
]; i
++){
4437 appendText(&sTable
, ",", 0);
4438 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
4440 appendText(&sTable
, ")", 0);
4443 /* Build an appropriate SELECT statement */
4445 appendText(&sSelect
, "SELECT ", 0);
4447 appendText(&sSelect
, azCol
[0], 0);
4448 appendText(&sSelect
, ",", 0);
4450 for(i
=1; azCol
[i
]; i
++){
4451 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
4453 appendText(&sSelect
, ",", 0);
4456 freeColumnList(azCol
);
4457 appendText(&sSelect
, " FROM ", 0);
4458 appendText(&sSelect
, zTable
, quoteChar(zTable
));
4460 savedDestTable
= p
->zDestTable
;
4461 savedMode
= p
->mode
;
4462 p
->zDestTable
= sTable
.z
;
4463 p
->mode
= p
->cMode
= MODE_Insert
;
4464 rc
= shell_exec(p
, sSelect
.z
, 0);
4465 if( (rc
&0xff)==SQLITE_CORRUPT
){
4466 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
4467 toggleSelectOrder(p
->db
);
4468 shell_exec(p
, sSelect
.z
, 0);
4469 toggleSelectOrder(p
->db
);
4471 p
->zDestTable
= savedDestTable
;
4472 p
->mode
= savedMode
;
4481 ** Run zQuery. Use dump_callback() as the callback routine so that
4482 ** the contents of the query are output as SQL statements.
4484 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4485 ** "ORDER BY rowid DESC" to the end.
4487 static int run_schema_dump_query(
4493 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
4494 if( rc
==SQLITE_CORRUPT
){
4496 int len
= strlen30(zQuery
);
4497 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
4499 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
4503 zQ2
= malloc( len
+100 );
4504 if( zQ2
==0 ) return rc
;
4505 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
4506 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
4508 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
4510 rc
= SQLITE_CORRUPT
;
4519 ** Text of help messages.
4521 ** The help text for each individual command begins with a line that starts
4522 ** with ".". Subsequent lines are supplemental information.
4524 ** There must be two or more spaces between the end of the command and the
4525 ** start of the description of what that command does.
4527 static const char *(azHelp
[]) = {
4528 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4529 && !defined(SQLITE_SHELL_FIDDLE)
4530 ".archive ... Manage SQL archives",
4531 " Each command must have exactly one of the following options:",
4532 " -c, --create Create a new archive",
4533 " -u, --update Add or update files with changed mtime",
4534 " -i, --insert Like -u but always add even if unchanged",
4535 " -r, --remove Remove files from archive",
4536 " -t, --list List contents of archive",
4537 " -x, --extract Extract files from archive",
4538 " Optional arguments:",
4539 " -v, --verbose Print each filename as it is processed",
4540 " -f FILE, --file FILE Use archive FILE (default is current db)",
4541 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4542 " -C DIR, --directory DIR Read/extract files from directory DIR",
4543 " -g, --glob Use glob matching for names in archive",
4544 " -n, --dryrun Show the SQL that would have occurred",
4546 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4547 " .ar -tf ARCHIVE # List members of ARCHIVE",
4548 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4550 " http://sqlite.org/cli.html#sqlite_archive_support",
4552 #ifndef SQLITE_OMIT_AUTHORIZATION
4553 ".auth ON|OFF Show authorizer callbacks",
4555 #ifndef SQLITE_SHELL_FIDDLE
4556 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4558 " --append Use the appendvfs",
4559 " --async Write to FILE without journal and fsync()",
4561 ".bail on|off Stop after hitting an error. Default OFF",
4562 ".binary on|off Turn binary output on or off. Default OFF",
4563 #ifndef SQLITE_SHELL_FIDDLE
4564 ".cd DIRECTORY Change the working directory to DIRECTORY",
4566 ".changes on|off Show number of rows changed by SQL",
4567 #ifndef SQLITE_SHELL_FIDDLE
4568 ".check GLOB Fail if output since .testcase does not match",
4569 ".clone NEWDB Clone data into NEWDB from the existing database",
4571 ".connection [close] [#] Open or close an auxiliary database connection",
4572 ".databases List names and files of attached databases",
4573 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4574 #if SQLITE_SHELL_HAVE_RECOVER
4575 ".dbinfo ?DB? Show status information about the database",
4577 ".dump ?OBJECTS? Render database content as SQL",
4579 " --data-only Output only INSERT statements",
4580 " --newlines Allow unescaped newline characters in output",
4581 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4582 " --preserve-rowids Include ROWID values in the output",
4583 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4584 " Additional LIKE patterns can be given in subsequent arguments",
4585 ".echo on|off Turn command echo on or off",
4586 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4589 " test Show raw EXPLAIN QUERY PLAN output",
4590 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4592 " trigger Like \"full\" but also show trigger bytecode",
4593 #ifndef SQLITE_SHELL_FIDDLE
4594 ".excel Display the output of next command in spreadsheet",
4595 " --bom Put a UTF8 byte-order mark on intermediate file",
4597 #ifndef SQLITE_SHELL_FIDDLE
4598 ".exit ?CODE? Exit this program with return-code CODE",
4600 ".expert EXPERIMENTAL. Suggest indexes for queries",
4601 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4602 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4603 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4604 " --help Show CMD details",
4605 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4606 ".headers on|off Turn display of headers on or off",
4607 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4608 #ifndef SQLITE_SHELL_FIDDLE
4609 ".import FILE TABLE Import data from FILE into TABLE",
4611 " --ascii Use \\037 and \\036 as column and row separators",
4612 " --csv Use , and \\n as column and row separators",
4613 " --skip N Skip the first N rows of input",
4614 " --schema S Target table to be S.TABLE",
4615 " -v \"Verbose\" - increase auxiliary output",
4617 " * If TABLE does not exist, it is created. The first row of input",
4618 " determines the column names.",
4619 " * If neither --csv or --ascii are used, the input mode is derived",
4620 " from the \".mode\" output mode",
4621 " * If FILE begins with \"|\" then it is a command that generates the",
4624 #ifndef SQLITE_OMIT_TEST_CONTROL
4625 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4627 ".indexes ?TABLE? Show names of indexes",
4628 " If TABLE is specified, only show indexes for",
4629 " tables matching TABLE using the LIKE operator.",
4630 #ifdef SQLITE_ENABLE_IOTRACE
4631 ".iotrace FILE Enable I/O diagnostic logging to FILE",
4633 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4634 ".lint OPTIONS Report potential schema issues.",
4636 " fkey-indexes Find missing foreign key indexes",
4637 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4638 ".load FILE ?ENTRY? Load an extension library",
4640 #ifndef SQLITE_SHELL_FIDDLE
4641 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
4643 ".mode MODE ?OPTIONS? Set output mode",
4645 " ascii Columns/rows delimited by 0x1F and 0x1E",
4646 " box Tables using unicode box-drawing characters",
4647 " csv Comma-separated values",
4648 " column Output in columns. (See .width)",
4649 " html HTML <table> code",
4650 " insert SQL insert statements for TABLE",
4651 " json Results in a JSON array",
4652 " line One value per line",
4653 " list Values delimited by \"|\"",
4654 " markdown Markdown table format",
4655 " qbox Shorthand for \"box --wrap 60 --quote\"",
4656 " quote Escape answers as for SQL",
4657 " table ASCII-art table",
4658 " tabs Tab-separated values",
4659 " tcl TCL list elements",
4660 " OPTIONS: (for columnar modes or insert mode):",
4661 " --wrap N Wrap output lines to no longer than N characters",
4662 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4663 " --ww Shorthand for \"--wordwrap 1\"",
4664 " --quote Quote output text as SQL literals",
4665 " --noquote Do not quote output text",
4666 " TABLE The name of SQL table used for \"insert\" mode",
4667 #ifndef SQLITE_SHELL_FIDDLE
4668 ".nonce STRING Suspend safe mode for one command if nonce matches",
4670 ".nullvalue STRING Use STRING in place of NULL values",
4671 #ifndef SQLITE_SHELL_FIDDLE
4672 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4673 " If FILE begins with '|' then open as a pipe",
4674 " --bom Put a UTF8 byte-order mark at the beginning",
4675 " -e Send output to the system text editor",
4676 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4677 /* Note that .open is (partially) available in WASM builds but is
4678 ** currently only intended to be used by the fiddle tool, not
4679 ** end users, so is "undocumented." */
4680 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4682 " --append Use appendvfs to append database to the end of FILE",
4684 #ifndef SQLITE_OMIT_DESERIALIZE
4685 " --deserialize Load into memory using sqlite3_deserialize()",
4686 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4687 " --maxsize N Maximum size for --hexdb or --deserialized database",
4689 " --new Initialize FILE to an empty database",
4690 " --nofollow Do not follow symbolic links",
4691 " --readonly Open FILE readonly",
4692 " --zip FILE is a ZIP archive",
4693 #ifndef SQLITE_SHELL_FIDDLE
4694 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4695 " If FILE begins with '|' then open it as a pipe.",
4697 " --bom Prefix output with a UTF8 byte-order mark",
4698 " -e Send output to the system text editor",
4699 " -x Send output as CSV to a spreadsheet",
4701 ".parameter CMD ... Manage SQL parameter bindings",
4702 " clear Erase all bindings",
4703 " init Initialize the TEMP table that holds bindings",
4704 " list List the current parameter bindings",
4705 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4706 " PARAMETER should start with one of: $ : @ ?",
4707 " unset PARAMETER Remove PARAMETER from the binding table",
4708 ".print STRING... Print literal STRING",
4709 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4710 ".progress N Invoke progress handler after every N opcodes",
4711 " --limit N Interrupt after N progress callbacks",
4712 " --once Do no more than one progress interrupt",
4713 " --quiet|-q No output except at interrupts",
4714 " --reset Reset the count for each input and interrupt",
4716 ".prompt MAIN CONTINUE Replace the standard prompts",
4717 #ifndef SQLITE_SHELL_FIDDLE
4718 ".quit Stop interpreting input stream, exit if primary.",
4719 ".read FILE Read input from FILE or command output",
4720 " If FILE begins with \"|\", it is a command that generates the input.",
4722 #if SQLITE_SHELL_HAVE_RECOVER
4723 ".recover Recover as much data as possible from corrupt db.",
4724 " --ignore-freelist Ignore pages that appear to be on db freelist",
4725 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4726 " --no-rowids Do not attempt to recover rowid values",
4727 " that are not also INTEGER PRIMARY KEYs",
4729 #ifndef SQLITE_SHELL_FIDDLE
4730 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4731 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4733 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4734 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4736 " --indent Try to pretty-print the schema",
4737 " --nosys Omit objects whose names start with \"sqlite_\"",
4738 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4740 " --init Create a new SELFTEST table",
4741 " -v Verbose output",
4742 ".separator COL ?ROW? Change the column and row separators",
4743 #if defined(SQLITE_ENABLE_SESSION)
4744 ".session ?NAME? CMD ... Create or control sessions",
4746 " attach TABLE Attach TABLE",
4747 " changeset FILE Write a changeset into FILE",
4748 " close Close one session",
4749 " enable ?BOOLEAN? Set or query the enable bit",
4750 " filter GLOB... Reject tables matching GLOBs",
4751 " indirect ?BOOLEAN? Mark or query the indirect status",
4752 " isempty Query whether the session is empty",
4753 " list List currently open session names",
4754 " open DB NAME Open a new session on DB",
4755 " patchset FILE Write a patchset into FILE",
4756 " If ?NAME? is omitted, the first defined session is used.",
4758 ".sha3sum ... Compute a SHA3 hash of database content",
4760 " --schema Also hash the sqlite_schema table",
4761 " --sha3-224 Use the sha3-224 algorithm",
4762 " --sha3-256 Use the sha3-256 algorithm (default)",
4763 " --sha3-384 Use the sha3-384 algorithm",
4764 " --sha3-512 Use the sha3-512 algorithm",
4765 " Any other argument is a LIKE pattern for tables to hash",
4766 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4767 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4769 ".show Show the current values for various settings",
4770 ".stats ?ARG? Show stats or turn stats on or off",
4771 " off Turn off automatic stat display",
4772 " on Turn on automatic stat display",
4773 " stmt Show statement stats",
4774 " vmstep Show the virtual machine step count only",
4775 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4776 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4778 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4779 #ifndef SQLITE_SHELL_FIDDLE
4780 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
4782 ".testctrl CMD ... Run various sqlite3_test_control() operations",
4783 " Run \".testctrl\" with no arguments for details",
4784 ".timeout MS Try opening locked tables for MS milliseconds",
4785 ".timer on|off Turn SQL timer on or off",
4786 #ifndef SQLITE_OMIT_TRACE
4787 ".trace ?OPTIONS? Output each SQL statement as it is run",
4788 " FILE Send output to FILE",
4789 " stdout Send output to stdout",
4790 " stderr Send output to stderr",
4791 " off Disable tracing",
4792 " --expanded Expand query parameters",
4793 #ifdef SQLITE_ENABLE_NORMALIZE
4794 " --normalized Normal the SQL statements",
4796 " --plain Show SQL as it is input",
4797 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4798 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4799 " --row Trace each row (SQLITE_TRACE_ROW)",
4800 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4801 #endif /* SQLITE_OMIT_TRACE */
4803 ".unmodule NAME ... Unregister virtual table modules",
4804 " --allexcept Unregister everything except those named",
4806 ".version Show source, library and compiler versions",
4807 ".vfsinfo ?AUX? Information about the top-level VFS",
4808 ".vfslist List all available VFSes",
4809 ".vfsname ?AUX? Print the name of the VFS stack",
4810 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4811 " Negative values right-justify",
4815 ** Output help text.
4817 ** zPattern describes the set of commands for which help text is provided.
4818 ** If zPattern is NULL, then show all commands, but only give a one-line
4819 ** description of each.
4821 ** Return the number of matches.
4823 static int showHelp(FILE *out
, const char *zPattern
){
4830 || cli_strcmp(zPattern
,"-a")==0
4831 || cli_strcmp(zPattern
,"-all")==0
4832 || cli_strcmp(zPattern
,"--all")==0
4834 /* Show all commands, but only one line per command */
4835 if( zPattern
==0 ) zPattern
= "";
4836 for(i
=0; i
<ArraySize(azHelp
); i
++){
4837 if( azHelp
[i
][0]=='.' || zPattern
[0] ){
4838 utf8_printf(out
, "%s\n", azHelp
[i
]);
4843 /* Look for commands that for which zPattern is an exact prefix */
4844 zPat
= sqlite3_mprintf(".%s*", zPattern
);
4845 shell_check_oom(zPat
);
4846 for(i
=0; i
<ArraySize(azHelp
); i
++){
4847 if( sqlite3_strglob(zPat
, azHelp
[i
])==0 ){
4848 utf8_printf(out
, "%s\n", azHelp
[i
]);
4856 /* when zPattern is a prefix of exactly one command, then include the
4857 ** details of that command, which should begin at offset j */
4858 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
][0]!='.' ){
4859 utf8_printf(out
, "%s\n", azHelp
[j
]);
4865 /* Look for commands that contain zPattern anywhere. Show the complete
4866 ** text of all commands that match. */
4867 zPat
= sqlite3_mprintf("%%%s%%", zPattern
);
4868 shell_check_oom(zPat
);
4869 for(i
=0; i
<ArraySize(azHelp
); i
++){
4870 if( azHelp
[i
][0]=='.' ) j
= i
;
4871 if( sqlite3_strlike(zPat
, azHelp
[i
], 0)==0 ){
4872 utf8_printf(out
, "%s\n", azHelp
[j
]);
4873 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
+1][0]!='.' ){
4875 utf8_printf(out
, "%s\n", azHelp
[j
]);
4886 /* Forward reference */
4887 static int process_input(ShellState
*p
);
4890 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
4891 ** and return a pointer to the buffer. The caller is responsible for freeing
4894 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4897 ** For convenience, a nul-terminator byte is always appended to the data read
4898 ** from the file before the buffer is returned. This byte is not included in
4899 ** the final value of (*pnByte), if applicable.
4901 ** NULL is returned if any error is encountered. The final value of *pnByte
4902 ** is undefined in this case.
4904 static char *readFile(const char *zName
, int *pnByte
){
4905 FILE *in
= fopen(zName
, "rb");
4909 if( in
==0 ) return 0;
4910 fseek(in
, 0, SEEK_END
);
4913 pBuf
= sqlite3_malloc64( nIn
+1 );
4914 if( pBuf
==0 ){ fclose(in
); return 0; }
4915 nRead
= fread(pBuf
, nIn
, 1, in
);
4922 if( pnByte
) *pnByte
= nIn
;
4926 #if defined(SQLITE_ENABLE_SESSION)
4928 ** Close a single OpenSession object and release all of its associated
4931 static void session_close(OpenSession
*pSession
){
4933 sqlite3session_delete(pSession
->p
);
4934 sqlite3_free(pSession
->zName
);
4935 for(i
=0; i
<pSession
->nFilter
; i
++){
4936 sqlite3_free(pSession
->azFilter
[i
]);
4938 sqlite3_free(pSession
->azFilter
);
4939 memset(pSession
, 0, sizeof(OpenSession
));
4944 ** Close all OpenSession objects and release all associated resources.
4946 #if defined(SQLITE_ENABLE_SESSION)
4947 static void session_close_all(ShellState
*p
, int i
){
4949 struct AuxDb
*pAuxDb
= i
<0 ? p
->pAuxDb
: &p
->aAuxDb
[i
];
4950 for(j
=0; j
<pAuxDb
->nSession
; j
++){
4951 session_close(&pAuxDb
->aSession
[j
]);
4953 pAuxDb
->nSession
= 0;
4956 # define session_close_all(X,Y)
4960 ** Implementation of the xFilter function for an open session. Omit
4961 ** any tables named by ".session filter" but let all other table through.
4963 #if defined(SQLITE_ENABLE_SESSION)
4964 static int session_filter(void *pCtx
, const char *zTab
){
4965 OpenSession
*pSession
= (OpenSession
*)pCtx
;
4967 for(i
=0; i
<pSession
->nFilter
; i
++){
4968 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
4975 ** Try to deduce the type of file for zName based on its content. Return
4976 ** one of the SHELL_OPEN_* constants.
4978 ** If the file does not exist or is empty but its name looks like a ZIP
4979 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4980 ** Otherwise, assume an ordinary database regardless of the filename if
4981 ** the type cannot be determined from content.
4983 int deduceDatabaseType(const char *zName
, int dfltZip
){
4984 FILE *f
= fopen(zName
, "rb");
4986 int rc
= SHELL_OPEN_UNSPEC
;
4989 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
4990 return SHELL_OPEN_ZIPFILE
;
4992 return SHELL_OPEN_NORMAL
;
4995 n
= fread(zBuf
, 16, 1, f
);
4996 if( n
==1 && memcmp(zBuf
, "SQLite format 3", 16)==0 ){
4998 return SHELL_OPEN_NORMAL
;
5000 fseek(f
, -25, SEEK_END
);
5001 n
= fread(zBuf
, 25, 1, f
);
5002 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
5003 rc
= SHELL_OPEN_APPENDVFS
;
5005 fseek(f
, -22, SEEK_END
);
5006 n
= fread(zBuf
, 22, 1, f
);
5007 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
5009 rc
= SHELL_OPEN_ZIPFILE
;
5010 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
5011 rc
= SHELL_OPEN_ZIPFILE
;
5018 #ifndef SQLITE_OMIT_DESERIALIZE
5020 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5021 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5022 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5024 static unsigned char *readHexDb(ShellState
*p
, int *pnData
){
5025 unsigned char *a
= 0;
5033 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5037 in
= fopen(zDbFilename
, "r");
5039 utf8_printf(stderr
, "cannot open \"%s\" for reading\n", zDbFilename
);
5046 if( in
==0 ) in
= stdin
;
5050 if( fgets(zLine
, sizeof(zLine
), in
)==0 ) goto readHexDb_error
;
5051 rc
= sscanf(zLine
, "| size %d pagesize %d", &n
, &pgsz
);
5052 if( rc
!=2 ) goto readHexDb_error
;
5053 if( n
<0 ) goto readHexDb_error
;
5054 if( pgsz
<512 || pgsz
>65536 || (pgsz
&(pgsz
-1))!=0 ) goto readHexDb_error
;
5055 n
= (n
+pgsz
-1)&~(pgsz
-1); /* Round n up to the next multiple of pgsz */
5056 a
= sqlite3_malloc( n
? n
: 1 );
5059 if( pgsz
<512 || pgsz
>65536 || (pgsz
& (pgsz
-1))!=0 ){
5060 utf8_printf(stderr
, "invalid pagesize\n");
5061 goto readHexDb_error
;
5063 for(nLine
++; fgets(zLine
, sizeof(zLine
), in
)!=0; nLine
++){
5064 rc
= sscanf(zLine
, "| page %d offset %d", &j
, &k
);
5069 if( cli_strncmp(zLine
, "| end ", 6)==0 ){
5072 rc
= sscanf(zLine
,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5073 &j
, &x
[0], &x
[1], &x
[2], &x
[3], &x
[4], &x
[5], &x
[6], &x
[7],
5074 &x
[8], &x
[9], &x
[10], &x
[11], &x
[12], &x
[13], &x
[14], &x
[15]);
5077 if( k
+16<=n
&& k
>=0 ){
5079 for(ii
=0; ii
<16; ii
++) a
[k
+ii
] = x
[ii
]&0xff;
5095 while( fgets(zLine
, sizeof(zLine
), p
->in
)!=0 ){
5097 if(cli_strncmp(zLine
, "| end ", 6)==0 ) break;
5102 utf8_printf(stderr
,"Error on line %d of --hexdb input\n", nLine
);
5105 #endif /* SQLITE_OMIT_DESERIALIZE */
5108 ** Scalar function "shell_int32". The first argument to this function
5109 ** must be a blob. The second a non-negative integer. This function
5110 ** reads and returns a 32-bit big-endian integer from byte
5111 ** offset (4*<arg2>) of the blob.
5113 static void shellInt32(
5114 sqlite3_context
*context
,
5116 sqlite3_value
**argv
5118 const unsigned char *pBlob
;
5122 UNUSED_PARAMETER(argc
);
5123 nBlob
= sqlite3_value_bytes(argv
[0]);
5124 pBlob
= (const unsigned char*)sqlite3_value_blob(argv
[0]);
5125 iInt
= sqlite3_value_int(argv
[1]);
5127 if( iInt
>=0 && (iInt
+1)*4<=nBlob
){
5128 const unsigned char *a
= &pBlob
[iInt
*4];
5129 sqlite3_int64 iVal
= ((sqlite3_int64
)a
[0]<<24)
5130 + ((sqlite3_int64
)a
[1]<<16)
5131 + ((sqlite3_int64
)a
[2]<< 8)
5132 + ((sqlite3_int64
)a
[3]<< 0);
5133 sqlite3_result_int64(context
, iVal
);
5138 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
5139 ** using "..." with internal double-quote characters doubled.
5141 static void shellIdQuote(
5142 sqlite3_context
*context
,
5144 sqlite3_value
**argv
5146 const char *zName
= (const char*)sqlite3_value_text(argv
[0]);
5147 UNUSED_PARAMETER(argc
);
5149 char *z
= sqlite3_mprintf("\"%w\"", zName
);
5150 sqlite3_result_text(context
, z
, -1, sqlite3_free
);
5155 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5157 static void shellUSleepFunc(
5158 sqlite3_context
*context
,
5160 sqlite3_value
**argv
5162 int sleep
= sqlite3_value_int(argv
[0]);
5164 sqlite3_sleep(sleep
/1000);
5165 sqlite3_result_int(context
, sleep
);
5169 ** Scalar function "shell_escape_crnl" used by the .recover command.
5170 ** The argument passed to this function is the output of built-in
5171 ** function quote(). If the first character of the input is "'",
5172 ** indicating that the value passed to quote() was a text value,
5173 ** then this function searches the input for "\n" and "\r" characters
5174 ** and adds a wrapper similar to the following:
5176 ** replace(replace(<input>, '\n', char(10), '\r', char(13));
5178 ** Or, if the first character of the input is not "'", then a copy
5179 ** of the input is returned.
5181 static void shellEscapeCrnl(
5182 sqlite3_context
*context
,
5184 sqlite3_value
**argv
5186 const char *zText
= (const char*)sqlite3_value_text(argv
[0]);
5187 UNUSED_PARAMETER(argc
);
5188 if( zText
&& zText
[0]=='\'' ){
5189 i64 nText
= sqlite3_value_bytes(argv
[0]);
5193 const char *zNL
= 0;
5194 const char *zCR
= 0;
5198 for(i
=0; zText
[i
]; i
++){
5199 if( zNL
==0 && zText
[i
]=='\n' ){
5200 zNL
= unused_string(zText
, "\\n", "\\012", zBuf1
);
5203 if( zCR
==0 && zText
[i
]=='\r' ){
5204 zCR
= unused_string(zText
, "\\r", "\\015", zBuf2
);
5211 i64 nMax
= (nNL
> nCR
) ? nNL
: nCR
;
5212 i64 nAlloc
= nMax
* nText
+ (nMax
+64)*2;
5213 char *zOut
= (char*)sqlite3_malloc64(nAlloc
);
5215 sqlite3_result_error_nomem(context
);
5220 memcpy(&zOut
[iOut
], "replace(replace(", 16);
5223 memcpy(&zOut
[iOut
], "replace(", 8);
5226 for(i
=0; zText
[i
]; i
++){
5227 if( zText
[i
]=='\n' ){
5228 memcpy(&zOut
[iOut
], zNL
, nNL
);
5230 }else if( zText
[i
]=='\r' ){
5231 memcpy(&zOut
[iOut
], zCR
, nCR
);
5234 zOut
[iOut
] = zText
[i
];
5240 memcpy(&zOut
[iOut
], ",'", 2); iOut
+= 2;
5241 memcpy(&zOut
[iOut
], zNL
, nNL
); iOut
+= nNL
;
5242 memcpy(&zOut
[iOut
], "', char(10))", 12); iOut
+= 12;
5245 memcpy(&zOut
[iOut
], ",'", 2); iOut
+= 2;
5246 memcpy(&zOut
[iOut
], zCR
, nCR
); iOut
+= nCR
;
5247 memcpy(&zOut
[iOut
], "', char(13))", 12); iOut
+= 12;
5250 sqlite3_result_text(context
, zOut
, iOut
, SQLITE_TRANSIENT
);
5256 sqlite3_result_value(context
, argv
[0]);
5259 /* Flags for open_db().
5261 ** The default behavior of open_db() is to exit(1) if the database fails to
5262 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5263 ** but still returns without calling exit.
5265 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5266 ** ZIP archive if the file does not exist or is empty and its name matches
5267 ** the *.zip pattern.
5269 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5270 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5273 ** Make sure the database is open. If it is not, then open it. If
5274 ** the database fails to open, print an error message and exit.
5276 static void open_db(ShellState
*p
, int openFlags
){
5278 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5279 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
5280 if( zDbFilename
==0 || zDbFilename
[0]==0 ){
5281 p
->openMode
= SHELL_OPEN_NORMAL
;
5283 p
->openMode
= (u8
)deduceDatabaseType(zDbFilename
,
5284 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
5287 switch( p
->openMode
){
5288 case SHELL_OPEN_APPENDVFS
: {
5289 sqlite3_open_v2(zDbFilename
, &p
->db
,
5290 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, "apndvfs");
5293 case SHELL_OPEN_HEXDB
:
5294 case SHELL_OPEN_DESERIALIZE
: {
5295 sqlite3_open(0, &p
->db
);
5298 case SHELL_OPEN_ZIPFILE
: {
5299 sqlite3_open(":memory:", &p
->db
);
5302 case SHELL_OPEN_READONLY
: {
5303 sqlite3_open_v2(zDbFilename
, &p
->db
,
5304 SQLITE_OPEN_READONLY
|p
->openFlags
, 0);
5307 case SHELL_OPEN_UNSPEC
:
5308 case SHELL_OPEN_NORMAL
: {
5309 sqlite3_open_v2(zDbFilename
, &p
->db
,
5310 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, 0);
5315 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
5316 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
5317 zDbFilename
, sqlite3_errmsg(p
->db
));
5318 if( openFlags
& OPEN_DB_KEEPALIVE
){
5319 sqlite3_open(":memory:", &p
->db
);
5325 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5326 sqlite3_enable_load_extension(p
->db
, 1);
5328 sqlite3_shathree_init(p
->db
, 0, 0);
5329 sqlite3_uint_init(p
->db
, 0, 0);
5330 sqlite3_decimal_init(p
->db
, 0, 0);
5331 sqlite3_base64_init(p
->db
, 0, 0);
5332 sqlite3_base85_init(p
->db
, 0, 0);
5333 sqlite3_regexp_init(p
->db
, 0, 0);
5334 sqlite3_ieee_init(p
->db
, 0, 0);
5335 sqlite3_series_init(p
->db
, 0, 0);
5336 #ifndef SQLITE_SHELL_FIDDLE
5337 sqlite3_fileio_init(p
->db
, 0, 0);
5338 sqlite3_completion_init(p
->db
, 0, 0);
5340 #if SQLITE_SHELL_HAVE_RECOVER
5341 sqlite3_dbdata_init(p
->db
, 0, 0);
5343 #ifdef SQLITE_HAVE_ZLIB
5344 if( !p
->bSafeModePersist
){
5345 sqlite3_zipfile_init(p
->db
, 0, 0);
5346 sqlite3_sqlar_init(p
->db
, 0, 0);
5349 #ifdef SQLITE_SHELL_EXTFUNCS
5350 /* Create a preprocessing mechanism for extensions to make
5351 * their own provisions for being built into the shell.
5352 * This is a short-span macro. See further below for usage.
5354 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5355 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5356 /* Let custom-included extensions get their ..._init() called.
5357 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5358 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5359 * inititialization routine to be called.
5362 int irc
= SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS
, INIT
)(p
->db
);
5363 /* Let custom-included extensions expose their functionality.
5364 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5365 * the SQL functions, virtual tables, collating sequences or
5366 * VFS's implemented by the extension to be registered.
5369 || irc
==SQLITE_OK_LOAD_PERMANENTLY
){
5370 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS
, EXPOSE
)(p
->db
, 0);
5372 #undef SHELL_SUB_MACRO
5373 #undef SHELL_SUBMACRO
5377 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
5378 shellAddSchemaName
, 0, 0);
5379 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
5380 shellModuleSchema
, 0, 0);
5381 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
5382 shellPutsFunc
, 0, 0);
5383 sqlite3_create_function(p
->db
, "shell_escape_crnl", 1, SQLITE_UTF8
, 0,
5384 shellEscapeCrnl
, 0, 0);
5385 sqlite3_create_function(p
->db
, "shell_int32", 2, SQLITE_UTF8
, 0,
5387 sqlite3_create_function(p
->db
, "shell_idquote", 1, SQLITE_UTF8
, 0,
5388 shellIdQuote
, 0, 0);
5389 sqlite3_create_function(p
->db
, "usleep",1,SQLITE_UTF8
,0,
5390 shellUSleepFunc
, 0, 0);
5391 #ifndef SQLITE_NOHAVE_SYSTEM
5392 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
5394 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
5398 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
5399 char *zSql
= sqlite3_mprintf(
5400 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename
);
5401 shell_check_oom(zSql
);
5402 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
5405 #ifndef SQLITE_OMIT_DESERIALIZE
5407 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
|| p
->openMode
==SHELL_OPEN_HEXDB
){
5410 unsigned char *aData
;
5411 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
){
5412 aData
= (unsigned char*)readFile(zDbFilename
, &nData
);
5414 aData
= readHexDb(p
, &nData
);
5419 rc
= sqlite3_deserialize(p
->db
, "main", aData
, nData
, nData
,
5420 SQLITE_DESERIALIZE_RESIZEABLE
|
5421 SQLITE_DESERIALIZE_FREEONCLOSE
);
5423 utf8_printf(stderr
, "Error: sqlite3_deserialize() returns %d\n", rc
);
5426 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_SIZE_LIMIT
, &p
->szMax
);
5431 if( p
->bSafeModePersist
&& p
->db
!=0 ){
5432 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
5437 ** Attempt to close the databaes connection. Report errors.
5439 void close_db(sqlite3
*db
){
5440 int rc
= sqlite3_close(db
);
5442 utf8_printf(stderr
, "Error: sqlite3_close() returns %d: %s\n",
5443 rc
, sqlite3_errmsg(db
));
5447 #if HAVE_READLINE || HAVE_EDITLINE
5449 ** Readline completion callbacks
5451 static char *readline_completion_generator(const char *text
, int state
){
5452 static sqlite3_stmt
*pStmt
= 0;
5456 sqlite3_finalize(pStmt
);
5457 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5458 " FROM completion(%Q) ORDER BY 1", text
);
5459 shell_check_oom(zSql
);
5460 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5463 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
5464 const char *z
= (const char*)sqlite3_column_text(pStmt
,0);
5465 zRet
= z
? strdup(z
) : 0;
5467 sqlite3_finalize(pStmt
);
5473 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
5476 rl_attempted_completion_over
= 1;
5477 return rl_completion_matches(zText
, readline_completion_generator
);
5480 #elif HAVE_LINENOISE
5482 ** Linenoise completion callback
5484 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
5485 i64 nLine
= strlen(zLine
);
5487 sqlite3_stmt
*pStmt
= 0;
5491 if( nLine
>(i64
)sizeof(zBuf
)-30 ) return;
5492 if( zLine
[0]=='.' || zLine
[0]=='#') return;
5493 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
5494 if( i
==nLine
-1 ) return;
5496 memcpy(zBuf
, zLine
, iStart
);
5497 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5498 " FROM completion(%Q,%Q) ORDER BY 1",
5499 &zLine
[iStart
], zLine
);
5500 shell_check_oom(zSql
);
5501 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5503 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5504 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5505 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
5506 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
5507 if( iStart
+nCompletion
< (i64
)sizeof(zBuf
)-1 && zCompletion
){
5508 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
5509 linenoiseAddCompletion(lc
, zBuf
);
5512 sqlite3_finalize(pStmt
);
5517 ** Do C-language style dequoting.
5523 ** \v -> vertical tab
5525 ** \r -> carriage return
5530 ** \NNN -> ascii character NNN in octal
5532 static void resolve_backslashes(char *z
){
5535 while( *z
&& *z
!='\\' ) z
++;
5536 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
5537 if( c
=='\\' && z
[i
+1]!=0 ){
5555 }else if( c
=='\'' ){
5557 }else if( c
=='\\' ){
5559 }else if( c
>='0' && c
<='7' ){
5561 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5563 c
= (c
<<3) + z
[i
] - '0';
5564 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5566 c
= (c
<<3) + z
[i
] - '0';
5577 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5578 ** for TRUE and FALSE. Return the integer value if appropriate.
5580 static int booleanValue(const char *zArg
){
5582 if( zArg
[0]=='0' && zArg
[1]=='x' ){
5583 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
5585 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
5587 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
5588 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
5591 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
5594 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5600 ** Set or clear a shell flag according to a boolean value.
5602 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
5603 if( booleanValue(zArg
) ){
5604 ShellSetFlag(p
, mFlag
);
5606 ShellClearFlag(p
, mFlag
);
5611 ** Close an output file, assuming it is not stderr or stdout
5613 static void output_file_close(FILE *f
){
5614 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
5618 ** Try to open an output file. The names "stdout" and "stderr" are
5619 ** recognized and do the right thing. NULL is returned if the output
5620 ** filename is "off".
5622 static FILE *output_file_open(const char *zFile
, int bTextMode
){
5624 if( cli_strcmp(zFile
,"stdout")==0 ){
5626 }else if( cli_strcmp(zFile
, "stderr")==0 ){
5628 }else if( cli_strcmp(zFile
, "off")==0 ){
5631 f
= fopen(zFile
, bTextMode
? "w" : "wb");
5633 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
5639 #ifndef SQLITE_OMIT_TRACE
5641 ** A routine for handling output from sqlite3_trace().
5643 static int sql_trace_callback(
5644 unsigned mType
, /* The trace type */
5645 void *pArg
, /* The ShellState pointer */
5646 void *pP
, /* Usually a pointer to sqlite_stmt */
5647 void *pX
/* Auxiliary output */
5649 ShellState
*p
= (ShellState
*)pArg
;
5650 sqlite3_stmt
*pStmt
;
5653 if( p
->traceOut
==0 ) return 0;
5654 if( mType
==SQLITE_TRACE_CLOSE
){
5655 utf8_printf(p
->traceOut
, "-- closing database connection\n");
5658 if( mType
!=SQLITE_TRACE_ROW
&& ((const char*)pX
)[0]=='-' ){
5659 zSql
= (const char*)pX
;
5661 pStmt
= (sqlite3_stmt
*)pP
;
5662 switch( p
->eTraceType
){
5663 case SHELL_TRACE_EXPANDED
: {
5664 zSql
= sqlite3_expanded_sql(pStmt
);
5667 #ifdef SQLITE_ENABLE_NORMALIZE
5668 case SHELL_TRACE_NORMALIZED
: {
5669 zSql
= sqlite3_normalized_sql(pStmt
);
5674 zSql
= sqlite3_sql(pStmt
);
5679 if( zSql
==0 ) return 0;
5680 nSql
= strlen(zSql
);
5681 if( nSql
>1000000000 ) nSql
= 1000000000;
5682 while( nSql
>0 && zSql
[nSql
-1]==';' ){ nSql
--; }
5684 case SQLITE_TRACE_ROW
:
5685 case SQLITE_TRACE_STMT
: {
5686 utf8_printf(p
->traceOut
, "%.*s;\n", (int)nSql
, zSql
);
5689 case SQLITE_TRACE_PROFILE
: {
5690 sqlite3_int64 nNanosec
= *(sqlite3_int64
*)pX
;
5691 utf8_printf(p
->traceOut
, "%.*s; -- %lld ns\n", (int)nSql
, zSql
, nNanosec
);
5700 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5701 ** a useful spot to set a debugger breakpoint.
5703 ** This routine does not do anything practical. The code are there simply
5704 ** to prevent the compiler from optimizing this routine out.
5706 static void test_breakpoint(void){
5707 static unsigned int nCall
= 0;
5708 if( (nCall
++)==0xffffffff ) printf("Many .breakpoints have run\n");
5712 ** An object used to read a CSV and other files for import.
5714 typedef struct ImportCtx ImportCtx
;
5716 const char *zFile
; /* Name of the input file */
5717 FILE *in
; /* Read the CSV text from this input stream */
5718 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close in */
5719 char *z
; /* Accumulated text for a field */
5720 int n
; /* Number of bytes in z */
5721 int nAlloc
; /* Space allocated for z[] */
5722 int nLine
; /* Current line number */
5723 int nRow
; /* Number of rows imported */
5724 int nErr
; /* Number of errors encountered */
5725 int bNotFirst
; /* True if one or more bytes already read */
5726 int cTerm
; /* Character that terminated the most recent field */
5727 int cColSep
; /* The column separator character. (Usually ",") */
5728 int cRowSep
; /* The row separator character. (Usually "\n") */
5731 /* Clean up resourced used by an ImportCtx */
5732 static void import_cleanup(ImportCtx
*p
){
5733 if( p
->in
!=0 && p
->xCloser
!=0 ){
5741 /* Append a single byte to z[] */
5742 static void import_append_char(ImportCtx
*p
, int c
){
5743 if( p
->n
+1>=p
->nAlloc
){
5744 p
->nAlloc
+= p
->nAlloc
+ 100;
5745 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
5746 shell_check_oom(p
->z
);
5748 p
->z
[p
->n
++] = (char)c
;
5751 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5752 ** with the option of having a separator other than ",".
5754 ** + Input comes from p->in.
5755 ** + Store results in p->z of length p->n. Space to hold p->z comes
5756 ** from sqlite3_malloc64().
5757 ** + Use p->cSep as the column separator. The default is ",".
5758 ** + Use p->rSep as the row separator. The default is "\n".
5759 ** + Keep track of the line number in p->nLine.
5760 ** + Store the character that terminates the field in p->cTerm. Store
5761 ** EOF on end-of-file.
5762 ** + Report syntax errors on stderr
5764 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
5766 int cSep
= p
->cColSep
;
5767 int rSep
= p
->cRowSep
;
5770 if( c
==EOF
|| seenInterrupt
){
5776 int startLine
= p
->nLine
;
5781 if( c
==rSep
) p
->nLine
++;
5788 if( (c
==cSep
&& pc
==cQuote
)
5789 || (c
==rSep
&& pc
==cQuote
)
5790 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
5791 || (c
==EOF
&& pc
==cQuote
)
5793 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
5797 if( pc
==cQuote
&& c
!='\r' ){
5798 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
5799 p
->zFile
, p
->nLine
, cQuote
);
5802 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
5803 p
->zFile
, startLine
, cQuote
);
5807 import_append_char(p
, c
);
5812 /* If this is the first field being parsed and it begins with the
5813 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5814 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
5815 import_append_char(p
, c
);
5817 if( (c
&0xff)==0xbb ){
5818 import_append_char(p
, c
);
5820 if( (c
&0xff)==0xbf ){
5823 return csv_read_one_field(p
);
5827 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5828 import_append_char(p
, c
);
5833 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
5837 if( p
->z
) p
->z
[p
->n
] = 0;
5842 /* Read a single field of ASCII delimited text.
5844 ** + Input comes from p->in.
5845 ** + Store results in p->z of length p->n. Space to hold p->z comes
5846 ** from sqlite3_malloc64().
5847 ** + Use p->cSep as the column separator. The default is "\x1F".
5848 ** + Use p->rSep as the row separator. The default is "\x1E".
5849 ** + Keep track of the row number in p->nLine.
5850 ** + Store the character that terminates the field in p->cTerm. Store
5851 ** EOF on end-of-file.
5852 ** + Report syntax errors on stderr
5854 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
5856 int cSep
= p
->cColSep
;
5857 int rSep
= p
->cRowSep
;
5860 if( c
==EOF
|| seenInterrupt
){
5864 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5865 import_append_char(p
, c
);
5872 if( p
->z
) p
->z
[p
->n
] = 0;
5877 ** Try to transfer data for table zTable. If an error is seen while
5878 ** moving forward, try to go backwards. The backwards movement won't
5879 ** work for WITHOUT ROWID tables.
5881 static void tryToCloneData(
5886 sqlite3_stmt
*pQuery
= 0;
5887 sqlite3_stmt
*pInsert
= 0;
5892 int nTable
= strlen30(zTable
);
5895 const int spinRate
= 10000;
5897 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
5898 shell_check_oom(zQuery
);
5899 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5901 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
5902 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
5906 n
= sqlite3_column_count(pQuery
);
5907 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
5908 shell_check_oom(zInsert
);
5909 sqlite3_snprintf(200+nTable
,zInsert
,
5910 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
5911 i
= strlen30(zInsert
);
5913 memcpy(zInsert
+i
, ",?", 2);
5916 memcpy(zInsert
+i
, ");", 3);
5917 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
5919 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
5920 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
5925 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
5927 switch( sqlite3_column_type(pQuery
, i
) ){
5929 sqlite3_bind_null(pInsert
, i
+1);
5932 case SQLITE_INTEGER
: {
5933 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
5936 case SQLITE_FLOAT
: {
5937 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
5941 sqlite3_bind_text(pInsert
, i
+1,
5942 (const char*)sqlite3_column_text(pQuery
,i
),
5947 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
5948 sqlite3_column_bytes(pQuery
,i
),
5954 rc
= sqlite3_step(pInsert
);
5955 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
5956 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
5957 sqlite3_errmsg(newDb
));
5959 sqlite3_reset(pInsert
);
5961 if( (cnt
%spinRate
)==0 ){
5962 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
5966 if( rc
==SQLITE_DONE
) break;
5967 sqlite3_finalize(pQuery
);
5968 sqlite3_free(zQuery
);
5969 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5971 shell_check_oom(zQuery
);
5972 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5974 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
5977 } /* End for(k=0...) */
5980 sqlite3_finalize(pQuery
);
5981 sqlite3_finalize(pInsert
);
5982 sqlite3_free(zQuery
);
5983 sqlite3_free(zInsert
);
5988 ** Try to transfer all rows of the schema that match zWhere. For
5989 ** each row, invoke xForEach() on the object defined by that row.
5990 ** If an error is encountered while moving forward through the
5991 ** sqlite_schema table, try again moving backwards.
5993 static void tryToCloneSchema(
5997 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
5999 sqlite3_stmt
*pQuery
= 0;
6002 const unsigned char *zName
;
6003 const unsigned char *zSql
;
6006 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6007 " WHERE %s ORDER BY rowid ASC", zWhere
);
6008 shell_check_oom(zQuery
);
6009 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6011 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
6012 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
6014 goto end_schema_xfer
;
6016 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
6017 zName
= sqlite3_column_text(pQuery
, 0);
6018 zSql
= sqlite3_column_text(pQuery
, 1);
6019 if( zName
==0 || zSql
==0 ) continue;
6020 if( sqlite3_stricmp((char*)zName
, "sqlite_sequence")!=0 ){
6021 printf("%s... ", zName
); fflush(stdout
);
6022 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
6024 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
6025 sqlite3_free(zErrMsg
);
6030 xForEach(p
, newDb
, (const char*)zName
);
6034 if( rc
!=SQLITE_DONE
){
6035 sqlite3_finalize(pQuery
);
6036 sqlite3_free(zQuery
);
6037 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6038 " WHERE %s ORDER BY rowid DESC", zWhere
);
6039 shell_check_oom(zQuery
);
6040 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6042 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
6043 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
6045 goto end_schema_xfer
;
6047 while( sqlite3_step(pQuery
)==SQLITE_ROW
){
6048 zName
= sqlite3_column_text(pQuery
, 0);
6049 zSql
= sqlite3_column_text(pQuery
, 1);
6050 if( zName
==0 || zSql
==0 ) continue;
6051 if( sqlite3_stricmp((char*)zName
, "sqlite_sequence")!=0 ) continue;
6052 printf("%s... ", zName
); fflush(stdout
);
6053 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
6055 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
6056 sqlite3_free(zErrMsg
);
6060 xForEach(p
, newDb
, (const char*)zName
);
6066 sqlite3_finalize(pQuery
);
6067 sqlite3_free(zQuery
);
6071 ** Open a new database file named "zNewDb". Try to recover as much information
6072 ** as possible out of the main database (which might be corrupt) and write it
6075 static void tryToClone(ShellState
*p
, const char *zNewDb
){
6078 if( access(zNewDb
,0)==0 ){
6079 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
6082 rc
= sqlite3_open(zNewDb
, &newDb
);
6084 utf8_printf(stderr
, "Cannot create output database: %s\n",
6085 sqlite3_errmsg(newDb
));
6087 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
6088 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
6089 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
6090 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
6091 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
6092 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6098 ** Change the output file back to stdout.
6100 ** If the p->doXdgOpen flag is set, that means the output was being
6101 ** redirected to a temporary file named by p->zTempFile. In that case,
6102 ** launch start/open/xdg-open on that temporary file.
6104 static void output_reset(ShellState
*p
){
6105 if( p
->outfile
[0]=='|' ){
6106 #ifndef SQLITE_OMIT_POPEN
6110 output_file_close(p
->out
);
6111 #ifndef SQLITE_NOHAVE_SYSTEM
6113 const char *zXdgOpenCmd
=
6116 #elif defined(__APPLE__)
6122 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
6124 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
6126 /* Give the start/open/xdg-open command some time to get
6127 ** going before we continue, and potential delete the
6128 ** p->zTempFile data file out from under it */
6129 sqlite3_sleep(2000);
6135 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6142 ** Run an SQL command and return the single integer result.
6144 static int db_int(sqlite3
*db
, const char *zSql
){
6145 sqlite3_stmt
*pStmt
;
6147 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
6148 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
6149 res
= sqlite3_column_int(pStmt
,0);
6151 sqlite3_finalize(pStmt
);
6155 #if defined(SQLITE_SHELL_HAVE_RECOVER)
6157 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6159 static unsigned int get2byteInt(unsigned char *a
){
6160 return (a
[0]<<8) + a
[1];
6162 static unsigned int get4byteInt(unsigned char *a
){
6163 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
6167 ** Implementation of the ".dbinfo" command.
6169 ** Return 1 on error, 2 to exit, and 0 otherwise.
6171 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
6172 static const struct { const char *zName
; int ofst
; } aField
[] = {
6173 { "file change counter:", 24 },
6174 { "database page count:", 28 },
6175 { "freelist page count:", 36 },
6176 { "schema cookie:", 40 },
6177 { "schema format:", 44 },
6178 { "default cache size:", 48 },
6179 { "autovacuum top root:", 52 },
6180 { "incremental vacuum:", 64 },
6181 { "text encoding:", 56 },
6182 { "user version:", 60 },
6183 { "application id:", 68 },
6184 { "software version:", 96 },
6186 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
6187 { "number of tables:",
6188 "SELECT count(*) FROM %s WHERE type='table'" },
6189 { "number of indexes:",
6190 "SELECT count(*) FROM %s WHERE type='index'" },
6191 { "number of triggers:",
6192 "SELECT count(*) FROM %s WHERE type='trigger'" },
6193 { "number of views:",
6194 "SELECT count(*) FROM %s WHERE type='view'" },
6196 "SELECT total(length(sql)) FROM %s" },
6199 unsigned iDataVersion
;
6201 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
6202 sqlite3_stmt
*pStmt
= 0;
6203 unsigned char aHdr
[100];
6205 if( p
->db
==0 ) return 1;
6206 rc
= sqlite3_prepare_v2(p
->db
,
6207 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6210 utf8_printf(stderr
, "error: %s\n", sqlite3_errmsg(p
->db
));
6211 sqlite3_finalize(pStmt
);
6214 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
6215 if( sqlite3_step(pStmt
)==SQLITE_ROW
6216 && sqlite3_column_bytes(pStmt
,0)>100
6218 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
6219 sqlite3_finalize(pStmt
);
6221 raw_printf(stderr
, "unable to read database header\n");
6222 sqlite3_finalize(pStmt
);
6225 i
= get2byteInt(aHdr
+16);
6226 if( i
==1 ) i
= 65536;
6227 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
6228 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
6229 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
6230 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
6231 for(i
=0; i
<ArraySize(aField
); i
++){
6232 int ofst
= aField
[i
].ofst
;
6233 unsigned int val
= get4byteInt(aHdr
+ ofst
);
6234 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
6237 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
6238 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
6239 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
6242 raw_printf(p
->out
, "\n");
6245 zSchemaTab
= sqlite3_mprintf("main.sqlite_schema");
6246 }else if( cli_strcmp(zDb
,"temp")==0 ){
6247 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_schema");
6249 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_schema", zDb
);
6251 for(i
=0; i
<ArraySize(aQuery
); i
++){
6252 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
6253 int val
= db_int(p
->db
, zSql
);
6255 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
6257 sqlite3_free(zSchemaTab
);
6258 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_DATA_VERSION
, &iDataVersion
);
6259 utf8_printf(p
->out
, "%-20s %u\n", "data version", iDataVersion
);
6262 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6265 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6267 static int shellDatabaseError(sqlite3
*db
){
6268 const char *zErr
= sqlite3_errmsg(db
);
6269 utf8_printf(stderr
, "Error: %s\n", zErr
);
6274 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6275 ** if they match and FALSE (0) if they do not match.
6279 ** '*' Matches any sequence of zero or more characters.
6281 ** '?' Matches exactly one character.
6283 ** [...] Matches one character from the enclosed list of
6286 ** [^...] Matches one character not in the enclosed list.
6288 ** '#' Matches any sequence of one or more digits with an
6289 ** optional + or - sign in front
6291 ** ' ' Any span of whitespace matches any other span of
6294 ** Extra whitespace at the end of z[] is ignored.
6296 static int testcase_glob(const char *zGlob
, const char *z
){
6301 while( (c
= (*(zGlob
++)))!=0 ){
6303 if( !IsSpace(*z
) ) return 0;
6304 while( IsSpace(*zGlob
) ) zGlob
++;
6305 while( IsSpace(*z
) ) z
++;
6307 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
6308 if( c
=='?' && (*(z
++))==0 ) return 0;
6313 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
6318 while( (c2
= (*(z
++)))!=0 ){
6321 if( c2
==0 ) return 0;
6323 if( testcase_glob(zGlob
,z
) ) return 1;
6327 if( (*(z
++))==0 ) return 0;
6333 if( c
==0 ) return 0;
6340 if( c
==']' ) seen
= 1;
6343 while( c2
&& c2
!=']' ){
6344 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
6346 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
6356 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
6358 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
6359 if( !IsDigit(z
[0]) ) return 0;
6361 while( IsDigit(z
[0]) ){ z
++; }
6363 if( c
!=(*(z
++)) ) return 0;
6366 while( IsSpace(*z
) ){ z
++; }
6372 ** Compare the string as a command-line option with either one or two
6373 ** initial "-" characters.
6375 static int optionMatch(const char *zStr
, const char *zOpt
){
6376 if( zStr
[0]!='-' ) return 0;
6378 if( zStr
[0]=='-' ) zStr
++;
6379 return cli_strcmp(zStr
, zOpt
)==0;
6385 int shellDeleteFile(const char *zFilename
){
6388 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
6392 rc
= unlink(zFilename
);
6398 ** Try to delete the temporary file (if there is one) and free the
6399 ** memory used to hold the name of the temp file.
6401 static void clearTempFile(ShellState
*p
){
6402 if( p
->zTempFile
==0 ) return;
6403 if( p
->doXdgOpen
) return;
6404 if( shellDeleteFile(p
->zTempFile
) ) return;
6405 sqlite3_free(p
->zTempFile
);
6410 ** Create a new temp file name with the given suffix.
6412 static void newTempFile(ShellState
*p
, const char *zSuffix
){
6414 sqlite3_free(p
->zTempFile
);
6417 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
6419 if( p
->zTempFile
==0 ){
6420 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6421 ** will not work and we will need to fallback to guessing */
6424 sqlite3_randomness(sizeof(r
), &r
);
6425 zTemp
= getenv("TEMP");
6426 if( zTemp
==0 ) zTemp
= getenv("TMP");
6434 p
->zTempFile
= sqlite3_mprintf("%s/temp%llx.%s", zTemp
, r
, zSuffix
);
6436 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
6438 shell_check_oom(p
->zTempFile
);
6443 ** The implementation of SQL scalar function fkey_collate_clause(), used
6444 ** by the ".lint fkey-indexes" command. This scalar function is always
6445 ** called with four arguments - the parent table name, the parent column name,
6446 ** the child table name and the child column name.
6448 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6450 ** If either of the named tables or columns do not exist, this function
6451 ** returns an empty string. An empty string is also returned if both tables
6452 ** and columns exist but have the same default collation sequence. Or,
6453 ** if both exist but the default collation sequences are different, this
6454 ** function returns the string " COLLATE <parent-collation>", where
6455 ** <parent-collation> is the default collation sequence of the parent column.
6457 static void shellFkeyCollateClause(
6458 sqlite3_context
*pCtx
,
6460 sqlite3_value
**apVal
6462 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
6463 const char *zParent
;
6464 const char *zParentCol
;
6465 const char *zParentSeq
;
6467 const char *zChildCol
;
6468 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
6472 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
6473 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
6474 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
6475 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
6477 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
6478 rc
= sqlite3_table_column_metadata(
6479 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
6481 if( rc
==SQLITE_OK
){
6482 rc
= sqlite3_table_column_metadata(
6483 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
6487 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
6488 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
6489 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
6496 ** The implementation of dot-command ".lint fkey-indexes".
6498 static int lintFkeyIndexes(
6499 ShellState
*pState
, /* Current shell tool state */
6500 char **azArg
, /* Array of arguments passed to dot command */
6501 int nArg
/* Number of entries in azArg[] */
6503 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
6504 FILE *out
= pState
->out
; /* Stream to write non-error output to */
6505 int bVerbose
= 0; /* If -verbose is present */
6506 int bGroupByParent
= 0; /* If -groupbyparent is present */
6507 int i
; /* To iterate through azArg[] */
6508 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
6509 int rc
; /* Return code */
6510 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
6513 ** This SELECT statement returns one row for each foreign key constraint
6514 ** in the schema of the main database. The column values are:
6516 ** 0. The text of an SQL statement similar to:
6518 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6520 ** This SELECT is similar to the one that the foreign keys implementation
6521 ** needs to run internally on child tables. If there is an index that can
6522 ** be used to optimize this query, then it can also be used by the FK
6523 ** implementation to optimize DELETE or UPDATE statements on the parent
6526 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6527 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6528 ** contains an index that can be used to optimize the query.
6530 ** 2. Human readable text that describes the child table and columns. e.g.
6532 ** "child_table(child_key1, child_key2)"
6534 ** 3. Human readable text that describes the parent table and columns. e.g.
6536 ** "parent_table(parent_key1, parent_key2)"
6538 ** 4. A full CREATE INDEX statement for an index that could be used to
6539 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6541 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6543 ** 5. The name of the parent table.
6545 ** These six values are used by the C logic below to generate the report.
6549 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6550 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6551 " || fkey_collate_clause("
6552 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6554 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6555 " || group_concat('*=?', ' AND ') || ')'"
6557 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6559 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6561 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6562 " || ' ON ' || quote(s.name) || '('"
6563 " || group_concat(quote(f.[from]) ||"
6564 " fkey_collate_clause("
6565 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6569 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6570 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6571 "GROUP BY s.name, f.id "
6572 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6574 const char *zGlobIPK
= "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6576 for(i
=2; i
<nArg
; i
++){
6577 int n
= strlen30(azArg
[i
]);
6578 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
6581 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
6586 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6589 return SQLITE_ERROR
;
6593 /* Register the fkey_collate_clause() SQL function */
6594 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
6595 0, shellFkeyCollateClause
, 0, 0
6599 if( rc
==SQLITE_OK
){
6600 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
6602 if( rc
==SQLITE_OK
){
6603 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
6606 if( rc
==SQLITE_OK
){
6609 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
6611 sqlite3_stmt
*pExplain
= 0;
6612 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
6613 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
6614 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
6615 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
6616 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
6617 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
6619 if( zEQP
==0 ) continue;
6620 if( zGlob
==0 ) continue;
6621 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
6622 if( rc
!=SQLITE_OK
) break;
6623 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
6624 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
6625 res
= zPlan
!=0 && ( 0==sqlite3_strglob(zGlob
, zPlan
)
6626 || 0==sqlite3_strglob(zGlobIPK
, zPlan
));
6628 rc
= sqlite3_finalize(pExplain
);
6629 if( rc
!=SQLITE_OK
) break;
6632 raw_printf(stderr
, "Error: internal error");
6636 && (bVerbose
|| res
==0)
6637 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
6639 raw_printf(out
, "-- Parent table %s\n", zParent
);
6640 sqlite3_free(zPrev
);
6641 zPrev
= sqlite3_mprintf("%s", zParent
);
6645 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
6646 }else if( bVerbose
){
6647 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
6648 zIndent
, zFrom
, zTarget
6653 sqlite3_free(zPrev
);
6655 if( rc
!=SQLITE_OK
){
6656 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6659 rc2
= sqlite3_finalize(pSql
);
6660 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
6662 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6665 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6672 ** Implementation of ".lint" dot command.
6674 static int lintDotCommand(
6675 ShellState
*pState
, /* Current shell tool state */
6676 char **azArg
, /* Array of arguments passed to dot command */
6677 int nArg
/* Number of entries in azArg[] */
6680 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
6681 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
6682 return lintFkeyIndexes(pState
, azArg
, nArg
);
6685 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
6686 raw_printf(stderr
, "Where sub-commands are:\n");
6687 raw_printf(stderr
, " fkey-indexes\n");
6688 return SQLITE_ERROR
;
6691 #if !defined SQLITE_OMIT_VIRTUALTABLE
6692 static void shellPrepare(
6696 sqlite3_stmt
**ppStmt
6699 if( *pRc
==SQLITE_OK
){
6700 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
6701 if( rc
!=SQLITE_OK
){
6702 raw_printf(stderr
, "sql error: %s (%d)\n",
6703 sqlite3_errmsg(db
), sqlite3_errcode(db
)
6711 ** Create a prepared statement using printf-style arguments for the SQL.
6713 ** This routine is could be marked "static". But it is not always used,
6714 ** depending on compile-time options. By omitting the "static", we avoid
6715 ** nuisance compiler warnings about "defined but not used".
6717 void shellPreparePrintf(
6720 sqlite3_stmt
**ppStmt
,
6725 if( *pRc
==SQLITE_OK
){
6729 z
= sqlite3_vmprintf(zFmt
, ap
);
6732 *pRc
= SQLITE_NOMEM
;
6734 shellPrepare(db
, pRc
, z
, ppStmt
);
6740 /* Finalize the prepared statement created using shellPreparePrintf().
6742 ** This routine is could be marked "static". But it is not always used,
6743 ** depending on compile-time options. By omitting the "static", we avoid
6744 ** nuisance compiler warnings about "defined but not used".
6751 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6752 int rc
= sqlite3_finalize(pStmt
);
6753 if( *pRc
==SQLITE_OK
){
6754 if( rc
!=SQLITE_OK
){
6755 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
6762 /* Reset the prepared statement created using shellPreparePrintf().
6764 ** This routine is could be marked "static". But it is not always used,
6765 ** depending on compile-time options. By omitting the "static", we avoid
6766 ** nuisance compiler warnings about "defined but not used".
6772 int rc
= sqlite3_reset(pStmt
);
6773 if( *pRc
==SQLITE_OK
){
6774 if( rc
!=SQLITE_OK
){
6775 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6776 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
6781 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6783 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6784 /******************************************************************************
6785 ** The ".archive" or ".ar" command.
6788 ** Structure representing a single ".ar" command.
6790 typedef struct ArCommand ArCommand
;
6792 u8 eCmd
; /* An AR_CMD_* value */
6793 u8 bVerbose
; /* True if --verbose */
6794 u8 bZip
; /* True if the archive is a ZIP */
6795 u8 bDryRun
; /* True if --dry-run */
6796 u8 bAppend
; /* True if --append */
6797 u8 bGlob
; /* True if --glob */
6798 u8 fromCmdLine
; /* Run from -A instead of .archive */
6799 int nArg
; /* Number of command arguments */
6800 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
6801 const char *zFile
; /* --file argument, or NULL */
6802 const char *zDir
; /* --directory argument, or NULL */
6803 char **azArg
; /* Array of command arguments */
6804 ShellState
*p
; /* Shell state */
6805 sqlite3
*db
; /* Database containing the archive */
6809 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6811 static int arUsage(FILE *f
){
6812 showHelp(f
,"archive");
6813 return SQLITE_ERROR
;
6817 ** Print an error message for the .ar command to stderr and return
6820 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
6824 z
= sqlite3_vmprintf(zFmt
, ap
);
6826 utf8_printf(stderr
, "Error: %s\n", z
);
6827 if( pAr
->fromCmdLine
){
6828 utf8_printf(stderr
, "Use \"-A\" for more help\n");
6830 utf8_printf(stderr
, "Use \".archive --help\" for more help\n");
6833 return SQLITE_ERROR
;
6837 ** Values for ArCommand.eCmd.
6839 #define AR_CMD_CREATE 1
6840 #define AR_CMD_UPDATE 2
6841 #define AR_CMD_INSERT 3
6842 #define AR_CMD_EXTRACT 4
6843 #define AR_CMD_LIST 5
6844 #define AR_CMD_HELP 6
6845 #define AR_CMD_REMOVE 7
6848 ** Other (non-command) switches.
6850 #define AR_SWITCH_VERBOSE 8
6851 #define AR_SWITCH_FILE 9
6852 #define AR_SWITCH_DIRECTORY 10
6853 #define AR_SWITCH_APPEND 11
6854 #define AR_SWITCH_DRYRUN 12
6855 #define AR_SWITCH_GLOB 13
6857 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
6860 case AR_CMD_EXTRACT
:
6867 return arErrorMsg(pAr
, "multiple command options");
6869 pAr
->eCmd
= eSwitch
;
6872 case AR_SWITCH_DRYRUN
:
6875 case AR_SWITCH_GLOB
:
6878 case AR_SWITCH_VERBOSE
:
6881 case AR_SWITCH_APPEND
:
6883 deliberate_fall_through
;
6884 case AR_SWITCH_FILE
:
6887 case AR_SWITCH_DIRECTORY
:
6896 ** Parse the command line for an ".ar" command. The results are written into
6897 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6898 ** successfully, otherwise an error message is written to stderr and
6899 ** SQLITE_ERROR returned.
6901 static int arParseCommand(
6902 char **azArg
, /* Array of arguments passed to dot command */
6903 int nArg
, /* Number of entries in azArg[] */
6904 ArCommand
*pAr
/* Populate this object */
6912 { "create", 'c', AR_CMD_CREATE
, 0 },
6913 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
6914 { "insert", 'i', AR_CMD_INSERT
, 0 },
6915 { "list", 't', AR_CMD_LIST
, 0 },
6916 { "remove", 'r', AR_CMD_REMOVE
, 0 },
6917 { "update", 'u', AR_CMD_UPDATE
, 0 },
6918 { "help", 'h', AR_CMD_HELP
, 0 },
6919 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
6920 { "file", 'f', AR_SWITCH_FILE
, 1 },
6921 { "append", 'a', AR_SWITCH_APPEND
, 1 },
6922 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
6923 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
6924 { "glob", 'g', AR_SWITCH_GLOB
, 0 },
6926 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
6927 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
6930 utf8_printf(stderr
, "Wrong number of arguments. Usage:\n");
6931 return arUsage(stderr
);
6935 /* Traditional style [tar] invocation */
6938 for(i
=0; z
[i
]; i
++){
6939 const char *zArg
= 0;
6940 struct ArSwitch
*pOpt
;
6941 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
6942 if( z
[i
]==pOpt
->cShort
) break;
6945 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
6949 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
6951 zArg
= azArg
[iArg
++];
6953 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
6955 pAr
->nArg
= nArg
-iArg
;
6957 pAr
->azArg
= &azArg
[iArg
];
6960 /* Non-traditional invocation */
6962 for(iArg
=1; iArg
<nArg
; iArg
++){
6966 /* All remaining command line words are command arguments. */
6967 pAr
->azArg
= &azArg
[iArg
];
6968 pAr
->nArg
= nArg
-iArg
;
6975 /* One or more short options */
6977 const char *zArg
= 0;
6978 struct ArSwitch
*pOpt
;
6979 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
6980 if( z
[i
]==pOpt
->cShort
) break;
6983 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
6990 if( iArg
>=(nArg
-1) ){
6991 return arErrorMsg(pAr
, "option requires an argument: %c",
6994 zArg
= azArg
[++iArg
];
6997 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
6999 }else if( z
[2]=='\0' ){
7000 /* A -- option, indicating that all remaining command line words
7001 ** are command arguments. */
7002 pAr
->azArg
= &azArg
[iArg
+1];
7003 pAr
->nArg
= nArg
-iArg
-1;
7007 const char *zArg
= 0; /* Argument for option, if any */
7008 struct ArSwitch
*pMatch
= 0; /* Matching option */
7009 struct ArSwitch
*pOpt
; /* Iterator */
7010 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
7011 const char *zLong
= pOpt
->zLong
;
7012 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
7014 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
7022 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
7025 if( iArg
>=(nArg
-1) ){
7026 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
7028 zArg
= azArg
[++iArg
];
7030 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
7040 ** This function assumes that all arguments within the ArCommand.azArg[]
7041 ** array refer to archive members, as for the --extract, --list or --remove
7042 ** commands. It checks that each of them are "present". If any specified
7043 ** file is not present in the archive, an error is printed to stderr and an
7044 ** error code returned. Otherwise, if all specified arguments are present
7045 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7046 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7047 ** when pAr->bGlob is true.
7049 ** This function strips any trailing '/' characters from each argument.
7050 ** This is consistent with the way the [tar] command seems to work on
7053 static int arCheckEntries(ArCommand
*pAr
){
7057 sqlite3_stmt
*pTest
= 0;
7058 const char *zSel
= (pAr
->bGlob
)
7059 ? "SELECT name FROM %s WHERE glob($name,name)"
7060 : "SELECT name FROM %s WHERE name=$name";
7062 shellPreparePrintf(pAr
->db
, &rc
, &pTest
, zSel
, pAr
->zSrcTable
);
7063 j
= sqlite3_bind_parameter_index(pTest
, "$name");
7064 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7065 char *z
= pAr
->azArg
[i
];
7066 int n
= strlen30(z
);
7068 while( n
>0 && z
[n
-1]=='/' ) n
--;
7070 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
7071 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
7074 shellReset(&rc
, pTest
);
7075 if( rc
==SQLITE_OK
&& bOk
==0 ){
7076 utf8_printf(stderr
, "not found in archive: %s\n", z
);
7080 shellFinalize(&rc
, pTest
);
7086 ** Format a WHERE clause that can be used against the "sqlar" table to
7087 ** identify all archive members that match the command arguments held
7088 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7089 ** The caller is responsible for eventually calling sqlite3_free() on
7090 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7091 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7093 static void arWhereClause(
7096 char **pzWhere
/* OUT: New WHERE clause */
7099 const char *zSameOp
= (pAr
->bGlob
)? "GLOB" : "=";
7100 if( *pRc
==SQLITE_OK
){
7102 zWhere
= sqlite3_mprintf("1");
7105 const char *zSep
= "";
7106 for(i
=0; i
<pAr
->nArg
; i
++){
7107 const char *z
= pAr
->azArg
[i
];
7108 zWhere
= sqlite3_mprintf(
7109 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7110 zWhere
, zSep
, zSameOp
, z
, strlen30(z
)+1, zSameOp
, z
7113 *pRc
= SQLITE_NOMEM
;
7124 ** Implementation of .ar "lisT" command.
7126 static int arListCommand(ArCommand
*pAr
){
7127 const char *zSql
= "SELECT %s FROM %s WHERE %s";
7128 const char *azCols
[] = {
7130 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7134 sqlite3_stmt
*pSql
= 0;
7137 rc
= arCheckEntries(pAr
);
7138 arWhereClause(&rc
, pAr
, &zWhere
);
7140 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
7141 pAr
->zSrcTable
, zWhere
);
7143 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
7145 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7146 if( pAr
->bVerbose
){
7147 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
7148 sqlite3_column_text(pSql
, 0),
7149 sqlite3_column_int(pSql
, 1),
7150 sqlite3_column_text(pSql
, 2),
7151 sqlite3_column_text(pSql
, 3)
7154 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
7158 shellFinalize(&rc
, pSql
);
7159 sqlite3_free(zWhere
);
7165 ** Implementation of .ar "Remove" command.
7167 static int arRemoveCommand(ArCommand
*pAr
){
7173 /* Verify that args actually exist within the archive before proceeding.
7174 ** And formulate a WHERE clause to match them. */
7175 rc
= arCheckEntries(pAr
);
7176 arWhereClause(&rc
, pAr
, &zWhere
);
7178 if( rc
==SQLITE_OK
){
7179 zSql
= sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7180 pAr
->zSrcTable
, zWhere
);
7182 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
7185 rc
= sqlite3_exec(pAr
->db
, "SAVEPOINT ar;", 0, 0, 0);
7186 if( rc
==SQLITE_OK
){
7187 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7188 if( rc
!=SQLITE_OK
){
7189 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7191 rc
= sqlite3_exec(pAr
->db
, "RELEASE ar;", 0, 0, 0);
7195 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
7200 sqlite3_free(zWhere
);
7206 ** Implementation of .ar "eXtract" command.
7208 static int arExtractCommand(ArCommand
*pAr
){
7212 " writefile(($dir || name), %s, mode, mtime) "
7213 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7214 " AND name NOT GLOB '*..[/\\]*'";
7216 const char *azExtraArg
[] = {
7217 "sqlar_uncompress(data, sz)",
7221 sqlite3_stmt
*pSql
= 0;
7227 /* If arguments are specified, check that they actually exist within
7228 ** the archive before proceeding. And formulate a WHERE clause to
7230 rc
= arCheckEntries(pAr
);
7231 arWhereClause(&rc
, pAr
, &zWhere
);
7233 if( rc
==SQLITE_OK
){
7235 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
7237 zDir
= sqlite3_mprintf("");
7239 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
7242 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
7243 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
7246 if( rc
==SQLITE_OK
){
7247 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
7248 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
7250 /* Run the SELECT statement twice. The first time, writefile() is called
7251 ** for all archive members that should be extracted. The second time,
7252 ** only for the directories. This is because the timestamps for
7253 ** extracted directories must be reset after they are populated (as
7254 ** populating them changes the timestamp). */
7256 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
7257 sqlite3_bind_int(pSql
, j
, i
);
7259 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
7261 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7262 if( i
==0 && pAr
->bVerbose
){
7263 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
7267 shellReset(&rc
, pSql
);
7269 shellFinalize(&rc
, pSql
);
7273 sqlite3_free(zWhere
);
7278 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7280 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
7283 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
7287 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7289 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
7298 ** Implementation of .ar "create", "insert", and "update" commands.
7300 ** create -> Create a new SQL archive
7301 ** insert -> Insert or reinsert all files listed
7302 ** update -> Insert files that have changed or that were not
7303 ** previously in the archive
7305 ** Create the "sqlar" table in the database if it does not already exist.
7306 ** Then add each file in the azFile[] array to the archive. Directories
7307 ** are added recursively. If argument bVerbose is non-zero, a message is
7308 ** printed on stdout for each file archived.
7310 ** The create command is the same as update, except that it drops
7311 ** any existing "sqlar" table before beginning. The "insert" command
7312 ** always overwrites every file named on the command-line, where as
7313 ** "update" only overwrites if the size or mtime or mode has changed.
7315 static int arCreateOrUpdateCommand(
7316 ArCommand
*pAr
, /* Command arguments and options */
7317 int bUpdate
, /* true for a --create. */
7318 int bOnlyIfChanged
/* Only update if file has changed */
7320 const char *zCreate
=
7321 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7322 " name TEXT PRIMARY KEY, -- name of the file\n"
7323 " mode INT, -- access permissions\n"
7324 " mtime INT, -- last modification time\n"
7325 " sz INT, -- original file size\n"
7326 " data BLOB -- compressed content\n"
7328 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
7329 const char *zInsertFmt
[2] = {
7330 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7335 " CASE substr(lsmode(mode),1,1)\n"
7336 " WHEN '-' THEN length(data)\n"
7337 " WHEN 'd' THEN 0\n"
7339 " sqlar_compress(data)\n"
7340 " FROM fsdir(%Q,%Q) AS disk\n"
7341 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7343 "REPLACE INTO %s(name,mode,mtime,data)\n"
7349 " FROM fsdir(%Q,%Q) AS disk\n"
7350 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7352 int i
; /* For iterating through azFile[] */
7353 int rc
; /* Return code */
7354 const char *zTab
= 0; /* SQL table into which to insert */
7359 arExecSql(pAr
, "PRAGMA page_size=512");
7360 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
7361 if( rc
!=SQLITE_OK
) return rc
;
7364 /* Initialize the zipfile virtual table, if necessary */
7367 sqlite3_randomness(sizeof(r
),&r
);
7368 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
7370 zSql
= sqlite3_mprintf(
7371 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7374 rc
= arExecSql(pAr
, zSql
);
7380 /* Initialize the table for an SQLAR */
7383 rc
= arExecSql(pAr
, zDrop
);
7384 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
7386 rc
= arExecSql(pAr
, zCreate
);
7388 if( bOnlyIfChanged
){
7389 zExists
= sqlite3_mprintf(
7391 "SELECT 1 FROM %s AS mem"
7392 " WHERE mem.name=disk.name"
7393 " AND mem.mtime=disk.mtime"
7394 " AND mem.mode=disk.mode)", zTab
);
7396 zExists
= sqlite3_mprintf("");
7398 if( zExists
==0 ) rc
= SQLITE_NOMEM
;
7399 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7400 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
7401 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
7402 pAr
->azArg
[i
], pAr
->zDir
, zExists
);
7403 rc
= arExecSql(pAr
, zSql2
);
7404 sqlite3_free(zSql2
);
7407 if( rc
!=SQLITE_OK
){
7408 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7410 rc
= arExecSql(pAr
, "RELEASE ar;");
7411 if( pAr
->bZip
&& pAr
->zFile
){
7412 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
7413 arExecSql(pAr
, zSql
);
7417 sqlite3_free(zExists
);
7422 ** Implementation of ".ar" dot command.
7424 static int arDotCommand(
7425 ShellState
*pState
, /* Current shell tool state */
7426 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
7427 char **azArg
, /* Array of arguments passed to dot command */
7428 int nArg
/* Number of entries in azArg[] */
7432 memset(&cmd
, 0, sizeof(cmd
));
7433 cmd
.fromCmdLine
= fromCmdLine
;
7434 rc
= arParseCommand(azArg
, nArg
, &cmd
);
7435 if( rc
==SQLITE_OK
){
7436 int eDbType
= SHELL_OPEN_UNSPEC
;
7438 cmd
.db
= pState
->db
;
7440 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
7442 eDbType
= pState
->openMode
;
7444 if( eDbType
==SHELL_OPEN_ZIPFILE
){
7445 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
7447 cmd
.zSrcTable
= sqlite3_mprintf("zip");
7449 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
7453 }else if( cmd
.zFile
){
7455 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
7456 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_INSERT
7457 || cmd
.eCmd
==AR_CMD_REMOVE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
7458 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
7460 flags
= SQLITE_OPEN_READONLY
;
7464 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
7465 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
7467 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
7468 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
7469 if( rc
!=SQLITE_OK
){
7470 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
7471 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
7473 goto end_ar_command
;
7475 sqlite3_fileio_init(cmd
.db
, 0, 0);
7476 sqlite3_sqlar_init(cmd
.db
, 0, 0);
7477 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
7478 shellPutsFunc
, 0, 0);
7481 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
7482 if( cmd
.eCmd
!=AR_CMD_CREATE
7483 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
7485 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
7487 goto end_ar_command
;
7489 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
7494 rc
= arCreateOrUpdateCommand(&cmd
, 0, 0);
7497 case AR_CMD_EXTRACT
:
7498 rc
= arExtractCommand(&cmd
);
7502 rc
= arListCommand(&cmd
);
7506 arUsage(pState
->out
);
7510 rc
= arCreateOrUpdateCommand(&cmd
, 1, 0);
7514 rc
= arRemoveCommand(&cmd
);
7518 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
7519 rc
= arCreateOrUpdateCommand(&cmd
, 1, 1);
7524 if( cmd
.db
!=pState
->db
){
7527 sqlite3_free(cmd
.zSrcTable
);
7531 /* End of the ".archive" or ".ar" command logic
7532 *******************************************************************************/
7533 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7535 #if SQLITE_SHELL_HAVE_RECOVER
7538 ** This function is used as a callback by the recover extension. Simply
7539 ** print the supplied SQL statement to stdout.
7541 static int recoverSqlCb(void *pCtx
, const char *zSql
){
7542 ShellState
*pState
= (ShellState
*)pCtx
;
7543 utf8_printf(pState
->out
, "%s;\n", zSql
);
7548 ** This function is called to recover data from the database. A script
7549 ** to construct a new database containing all recovered data is output
7550 ** on stream pState->out.
7552 static int recoverDatabaseCmd(ShellState
*pState
, int nArg
, char **azArg
){
7554 const char *zRecoveryDb
= ""; /* Name of "recovery" database. Debug only */
7555 const char *zLAF
= "lost_and_found";
7556 int bFreelist
= 1; /* 0 if --ignore-freelist is specified */
7557 int bRowids
= 1; /* 0 if --no-rowids */
7558 sqlite3_recover
*p
= 0;
7561 for(i
=1; i
<nArg
; i
++){
7564 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7566 if( n
<=17 && memcmp("-ignore-freelist", z
, n
)==0 ){
7569 if( n
<=12 && memcmp("-recovery-db", z
, n
)==0 && i
<(nArg
-1) ){
7570 /* This option determines the name of the ATTACH-ed database used
7571 ** internally by the recovery extension. The default is "" which
7572 ** means to use a temporary database that is automatically deleted
7573 ** when closed. This option is undocumented and might disappear at
7576 zRecoveryDb
= azArg
[i
];
7578 if( n
<=15 && memcmp("-lost-and-found", z
, n
)==0 && i
<(nArg
-1) ){
7582 if( n
<=10 && memcmp("-no-rowids", z
, n
)==0 ){
7586 utf8_printf(stderr
, "unexpected option: %s\n", azArg
[i
]);
7587 showHelp(pState
->out
, azArg
[0]);
7592 p
= sqlite3_recover_init_sql(
7593 pState
->db
, "main", recoverSqlCb
, (void*)pState
7596 sqlite3_recover_config(p
, 789, (void*)zRecoveryDb
); /* Debug use only */
7597 sqlite3_recover_config(p
, SQLITE_RECOVER_LOST_AND_FOUND
, (void*)zLAF
);
7598 sqlite3_recover_config(p
, SQLITE_RECOVER_ROWIDS
, (void*)&bRowids
);
7599 sqlite3_recover_config(p
, SQLITE_RECOVER_FREELIST_CORRUPT
,(void*)&bFreelist
);
7601 sqlite3_recover_run(p
);
7602 if( sqlite3_recover_errcode(p
)!=SQLITE_OK
){
7603 const char *zErr
= sqlite3_recover_errmsg(p
);
7604 int errCode
= sqlite3_recover_errcode(p
);
7605 raw_printf(stderr
, "sql error: %s (%d)\n", zErr
, errCode
);
7607 rc
= sqlite3_recover_finish(p
);
7610 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7614 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7615 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7616 * close db and set it to 0, and return the columns spec, to later
7617 * be sqlite3_free()'ed by the caller.
7618 * The return is 0 when either:
7619 * (a) The db was not initialized and zCol==0 (There are no columns.)
7620 * (b) zCol!=0 (Column was added, db initialized as needed.)
7621 * The 3rd argument, pRenamed, references an out parameter. If the
7622 * pointer is non-zero, its referent will be set to a summary of renames
7623 * done if renaming was necessary, or set to 0 if none was done. The out
7624 * string (if any) must be sqlite3_free()'ed by the caller.
7627 #define rc_err_oom_die(rc) \
7628 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7629 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7630 fprintf(stderr,"E:%d\n",rc), assert(0)
7632 static void rc_err_oom_die(int rc
){
7633 if( rc
==SQLITE_NOMEM
) shell_check_oom(0);
7634 assert(rc
==SQLITE_OK
||rc
==SQLITE_DONE
);
7638 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7639 static char zCOL_DB
[] = SHELL_STRINGIFY(SHELL_COLFIX_DB
);
7640 #else /* Otherwise, memory is faster/better for the transient DB. */
7641 static const char *zCOL_DB
= ":memory:";
7644 /* Define character (as C string) to separate generated column ordinal
7645 * from protected part of incoming column names. This defaults to "_"
7646 * so that incoming column identifiers that did not need not be quoted
7647 * remain usable without being quoted. It must be one character.
7649 #ifndef SHELL_AUTOCOLUMN_SEP
7650 # define AUTOCOLUMN_SEP "_"
7652 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7655 static char *zAutoColumn(const char *zColNew
, sqlite3
**pDb
, char **pzRenamed
){
7656 /* Queries and D{D,M}L used here */
7657 static const char * const zTabMake
= "\
7658 CREATE TABLE ColNames(\
7659 cpos INTEGER PRIMARY KEY,\
7660 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7661 CREATE VIEW RepeatedNames AS \
7662 SELECT DISTINCT t.name FROM ColNames t \
7663 WHERE t.name COLLATE NOCASE IN (\
7664 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7667 static const char * const zTabFill
= "\
7668 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7669 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7671 static const char * const zHasDupes
= "\
7672 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7673 <count(name) FROM ColNames\
7675 #ifdef SHELL_COLUMN_RENAME_CLEAN
7676 static const char * const zDedoctor
= "\
7677 UPDATE ColNames SET chop=iif(\
7678 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7679 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP
"'),\
7680 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP
"0123456789')),\
7685 static const char * const zSetReps
= "\
7686 UPDATE ColNames AS t SET reps=\
7687 (SELECT count(*) FROM ColNames d \
7688 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7692 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7693 static const char * const zColDigits
= "\
7694 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7697 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7698 static const char * const zColDigits
= "\
7699 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7700 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7701 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7704 static const char * const zRenameRank
=
7705 #ifdef SHELL_COLUMN_RENAME_CLEAN
7706 "UPDATE ColNames AS t SET suff="
7707 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP
"', $1, cpos), '')"
7708 #else /* ...RENAME_MINIMAL_ONE_PASS */
7709 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7712 " SELECT nlz+1 AS nlz FROM Lzn"
7715 " FROM ColNames t, ColNames o"
7717 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7718 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7719 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7723 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7724 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7725 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7729 " AND o.cpos<>t.cpos"
7732 ") UPDATE Colnames AS t SET"
7733 " chop = 0," /* No chopping, never touch incoming names. */
7734 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7735 " printf('"AUTOCOLUMN_SEP
"%s', substring("
7736 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7741 static const char * const zCollectVar
= "\
7746 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7749 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7750 FROM ColNames ORDER BY cpos\
7752 static const char * const zRenamesDone
=
7753 "SELECT group_concat("
7754 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7756 "FROM ColNames WHERE suff<>'' OR chop!=0"
7759 sqlite3_stmt
*pStmt
= 0;
7762 /* Add initial or additional column. Init db if necessary. */
7764 if( SQLITE_OK
!=sqlite3_open(zCOL_DB
, pDb
) ) return 0;
7765 #ifdef SHELL_COLFIX_DB
7767 sqlite3_exec(*pDb
,"drop table if exists ColNames;"
7768 "drop view if exists RepeatedNames;",0,0,0);
7770 rc
= sqlite3_exec(*pDb
, zTabMake
, 0, 0, 0);
7774 rc
= sqlite3_prepare_v2(*pDb
, zTabFill
, -1, &pStmt
, 0);
7776 rc
= sqlite3_bind_text(pStmt
, 1, zColNew
, -1, 0);
7778 rc
= sqlite3_step(pStmt
);
7780 sqlite3_finalize(pStmt
);
7782 }else if( *pDb
==0 ){
7785 /* Formulate the columns spec, close the DB, zero *pDb. */
7786 char *zColsSpec
= 0;
7787 int hasDupes
= db_int(*pDb
, zHasDupes
);
7788 int nDigits
= (hasDupes
)? db_int(*pDb
, zColDigits
) : 0;
7790 #ifdef SHELL_COLUMN_RENAME_CLEAN
7791 rc
= sqlite3_exec(*pDb
, zDedoctor
, 0, 0, 0);
7794 rc
= sqlite3_exec(*pDb
, zSetReps
, 0, 0, 0);
7796 rc
= sqlite3_prepare_v2(*pDb
, zRenameRank
, -1, &pStmt
, 0);
7798 sqlite3_bind_int(pStmt
, 1, nDigits
);
7799 rc
= sqlite3_step(pStmt
);
7800 sqlite3_finalize(pStmt
);
7801 assert(rc
==SQLITE_DONE
);
7803 assert(db_int(*pDb
, zHasDupes
)==0); /* Consider: remove this */
7804 rc
= sqlite3_prepare_v2(*pDb
, zCollectVar
, -1, &pStmt
, 0);
7806 rc
= sqlite3_step(pStmt
);
7807 if( rc
==SQLITE_ROW
){
7808 zColsSpec
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7813 if( !hasDupes
) *pzRenamed
= 0;
7815 sqlite3_finalize(pStmt
);
7816 if( SQLITE_OK
==sqlite3_prepare_v2(*pDb
, zRenamesDone
, -1, &pStmt
, 0)
7817 && SQLITE_ROW
==sqlite3_step(pStmt
) ){
7818 *pzRenamed
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7823 sqlite3_finalize(pStmt
);
7824 sqlite3_close(*pDb
);
7831 ** If an input line begins with "." then invoke this routine to
7832 ** process that line.
7834 ** Return 1 on error, 2 to exit, and 0 otherwise.
7836 static int do_meta_command(char *zLine
, ShellState
*p
){
7843 #ifndef SQLITE_OMIT_VIRTUALTABLE
7844 if( p
->expert
.pExpert
){
7845 expertFinish(p
, 1, 0);
7849 /* Parse the input line into tokens.
7851 while( zLine
[h
] && nArg
<ArraySize(azArg
)-1 ){
7852 while( IsSpace(zLine
[h
]) ){ h
++; }
7853 if( zLine
[h
]==0 ) break;
7854 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
7855 int delim
= zLine
[h
++];
7856 azArg
[nArg
++] = &zLine
[h
];
7857 while( zLine
[h
] && zLine
[h
]!=delim
){
7858 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
7861 if( zLine
[h
]==delim
){
7864 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
7866 azArg
[nArg
++] = &zLine
[h
];
7867 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
7868 if( zLine
[h
] ) zLine
[h
++] = 0;
7869 resolve_backslashes(azArg
[nArg
-1]);
7874 /* Process the input line.
7876 if( nArg
==0 ) return 0; /* no tokens, no error */
7877 n
= strlen30(azArg
[0]);
7881 #ifndef SQLITE_OMIT_AUTHORIZATION
7882 if( c
=='a' && cli_strncmp(azArg
[0], "auth", n
)==0 ){
7884 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
7886 goto meta_command_exit
;
7889 if( booleanValue(azArg
[1]) ){
7890 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
7891 }else if( p
->bSafeModePersist
){
7892 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
7894 sqlite3_set_authorizer(p
->db
, 0, 0);
7899 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7900 && !defined(SQLITE_SHELL_FIDDLE)
7901 if( c
=='a' && cli_strncmp(azArg
[0], "archive", n
)==0 ){
7903 failIfSafeMode(p
, "cannot run .archive in safe mode");
7904 rc
= arDotCommand(p
, 0, azArg
, nArg
);
7908 #ifndef SQLITE_SHELL_FIDDLE
7909 if( (c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "backup", n
)==0)
7910 || (c
=='s' && n
>=3 && cli_strncmp(azArg
[0], "save", n
)==0)
7912 const char *zDestFile
= 0;
7913 const char *zDb
= 0;
7915 sqlite3_backup
*pBackup
;
7918 const char *zVfs
= 0;
7919 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
7920 for(j
=1; j
<nArg
; j
++){
7921 const char *z
= azArg
[j
];
7923 if( z
[1]=='-' ) z
++;
7924 if( cli_strcmp(z
, "-append")==0 ){
7927 if( cli_strcmp(z
, "-async")==0 ){
7931 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
7934 }else if( zDestFile
==0 ){
7935 zDestFile
= azArg
[j
];
7938 zDestFile
= azArg
[j
];
7940 raw_printf(stderr
, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7945 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
7948 if( zDb
==0 ) zDb
= "main";
7949 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
7950 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
7951 if( rc
!=SQLITE_OK
){
7952 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
7957 sqlite3_exec(pDest
, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7961 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
7963 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
7967 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
7968 sqlite3_backup_finish(pBackup
);
7969 if( rc
==SQLITE_DONE
){
7972 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
7977 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
7979 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "bail", n
)==0 ){
7981 bail_on_error
= booleanValue(azArg
[1]);
7983 raw_printf(stderr
, "Usage: .bail on|off\n");
7988 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "binary", n
)==0 ){
7990 if( booleanValue(azArg
[1]) ){
7991 setBinaryMode(p
->out
, 1);
7993 setTextMode(p
->out
, 1);
7996 raw_printf(stderr
, "Usage: .binary on|off\n");
8001 /* The undocumented ".breakpoint" command causes a call to the no-op
8002 ** routine named test_breakpoint().
8004 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "breakpoint", n
)==0 ){
8008 #ifndef SQLITE_SHELL_FIDDLE
8009 if( c
=='c' && cli_strcmp(azArg
[0],"cd")==0 ){
8010 failIfSafeMode(p
, "cannot run .cd in safe mode");
8012 #if defined(_WIN32) || defined(WIN32)
8013 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
8014 rc
= !SetCurrentDirectoryW(z
);
8017 rc
= chdir(azArg
[1]);
8020 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
8024 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
8028 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8030 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "changes", n
)==0 ){
8032 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
8034 raw_printf(stderr
, "Usage: .changes on|off\n");
8039 #ifndef SQLITE_SHELL_FIDDLE
8040 /* Cancel output redirection, if it is currently set (by .testcase)
8041 ** Then read the content of the testcase-out.txt file and compare against
8042 ** azArg[1]. If there are differences, report an error and exit.
8044 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "check", n
)==0 ){
8048 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
8050 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
8051 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
8053 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
8055 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8056 p
->zTestcase
, azArg
[1], zRes
);
8059 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
8064 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8066 #ifndef SQLITE_SHELL_FIDDLE
8067 if( c
=='c' && cli_strncmp(azArg
[0], "clone", n
)==0 ){
8068 failIfSafeMode(p
, "cannot run .clone in safe mode");
8070 tryToClone(p
, azArg
[1]);
8072 raw_printf(stderr
, "Usage: .clone FILENAME\n");
8076 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8078 if( c
=='c' && cli_strncmp(azArg
[0], "connection", n
)==0 ){
8080 /* List available connections */
8082 for(i
=0; i
<ArraySize(p
->aAuxDb
); i
++){
8083 const char *zFile
= p
->aAuxDb
[i
].zDbFilename
;
8084 if( p
->aAuxDb
[i
].db
==0 && p
->pAuxDb
!=&p
->aAuxDb
[i
] ){
8085 zFile
= "(not open)";
8086 }else if( zFile
==0 ){
8088 }else if( zFile
[0]==0 ){
8089 zFile
= "(temporary-file)";
8091 if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
8092 utf8_printf(stdout
, "ACTIVE %d: %s\n", i
, zFile
);
8093 }else if( p
->aAuxDb
[i
].db
!=0 ){
8094 utf8_printf(stdout
, " %d: %s\n", i
, zFile
);
8097 }else if( nArg
==2 && IsDigit(azArg
[1][0]) && azArg
[1][1]==0 ){
8098 int i
= azArg
[1][0] - '0';
8099 if( p
->pAuxDb
!= &p
->aAuxDb
[i
] && i
>=0 && i
<ArraySize(p
->aAuxDb
) ){
8100 p
->pAuxDb
->db
= p
->db
;
8101 p
->pAuxDb
= &p
->aAuxDb
[i
];
8102 globalDb
= p
->db
= p
->pAuxDb
->db
;
8105 }else if( nArg
==3 && cli_strcmp(azArg
[1], "close")==0
8106 && IsDigit(azArg
[2][0]) && azArg
[2][1]==0 ){
8107 int i
= azArg
[2][0] - '0';
8108 if( i
<0 || i
>=ArraySize(p
->aAuxDb
) ){
8110 }else if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
8111 raw_printf(stderr
, "cannot close the active database connection\n");
8113 }else if( p
->aAuxDb
[i
].db
){
8114 session_close_all(p
, i
);
8115 close_db(p
->aAuxDb
[i
].db
);
8116 p
->aAuxDb
[i
].db
= 0;
8119 raw_printf(stderr
, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8124 if( c
=='d' && n
>1 && cli_strncmp(azArg
[0], "databases", n
)==0 ){
8127 sqlite3_stmt
*pStmt
;
8130 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
8132 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
8135 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
8136 const char *zSchema
= (const char *)sqlite3_column_text(pStmt
,1);
8137 const char *zFile
= (const char*)sqlite3_column_text(pStmt
,2);
8138 if( zSchema
==0 || zFile
==0 ) continue;
8139 azName
= sqlite3_realloc(azName
, (nName
+1)*2*sizeof(char*));
8140 shell_check_oom(azName
);
8141 azName
[nName
*2] = strdup(zSchema
);
8142 azName
[nName
*2+1] = strdup(zFile
);
8146 sqlite3_finalize(pStmt
);
8147 for(i
=0; i
<nName
; i
++){
8148 int eTxn
= sqlite3_txn_state(p
->db
, azName
[i
*2]);
8149 int bRdonly
= sqlite3_db_readonly(p
->db
, azName
[i
*2]);
8150 const char *z
= azName
[i
*2+1];
8151 utf8_printf(p
->out
, "%s: %s %s%s\n",
8153 z
&& z
[0] ? z
: "\"\"",
8154 bRdonly
? "r/o" : "r/w",
8155 eTxn
==SQLITE_TXN_NONE
? "" :
8156 eTxn
==SQLITE_TXN_READ
? " read-txn" : " write-txn");
8158 free(azName
[i
*2+1]);
8160 sqlite3_free(azName
);
8163 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbconfig", n
)==0 ){
8164 static const struct DbConfigChoices
{
8168 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
8169 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
8170 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
8171 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
8172 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
8173 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
8174 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
8175 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
8176 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
8177 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
8178 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
8179 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
8180 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
8181 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
8182 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
8183 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
8187 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
8188 if( nArg
>1 && cli_strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
8190 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
8192 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
8193 utf8_printf(p
->out
, "%19s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
8196 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
8197 utf8_printf(stderr
, "Error: unknown dbconfig \"%s\"\n", azArg
[1]);
8198 utf8_printf(stderr
, "Enter \".dbconfig\" with no arguments for a list\n");
8202 #if SQLITE_SHELL_HAVE_RECOVER
8203 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbinfo", n
)==0 ){
8204 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
8207 if( c
=='r' && cli_strncmp(azArg
[0], "recover", n
)==0 ){
8209 rc
= recoverDatabaseCmd(p
, nArg
, azArg
);
8211 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8213 if( c
=='d' && cli_strncmp(azArg
[0], "dump", n
)==0 ){
8217 int savedShowHeader
= p
->showHeader
;
8218 int savedShellFlags
= p
->shellFlgs
;
8220 SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
8221 |SHFLG_DumpDataOnly
|SHFLG_DumpNoSys
);
8222 for(i
=1; i
<nArg
; i
++){
8223 if( azArg
[i
][0]=='-' ){
8224 const char *z
= azArg
[i
]+1;
8225 if( z
[0]=='-' ) z
++;
8226 if( cli_strcmp(z
,"preserve-rowids")==0 ){
8227 #ifdef SQLITE_OMIT_VIRTUALTABLE
8228 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
8229 " with SQLITE_OMIT_VIRTUALTABLE\n");
8231 sqlite3_free(zLike
);
8232 goto meta_command_exit
;
8234 ShellSetFlag(p
, SHFLG_PreserveRowid
);
8237 if( cli_strcmp(z
,"newlines")==0 ){
8238 ShellSetFlag(p
, SHFLG_Newlines
);
8240 if( cli_strcmp(z
,"data-only")==0 ){
8241 ShellSetFlag(p
, SHFLG_DumpDataOnly
);
8243 if( cli_strcmp(z
,"nosys")==0 ){
8244 ShellSetFlag(p
, SHFLG_DumpNoSys
);
8247 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
8249 sqlite3_free(zLike
);
8250 goto meta_command_exit
;
8253 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8254 ** only dump data for tables for which either the table name matches
8255 ** the LIKE pattern, or the table appears to be a shadow table of
8256 ** a virtual table for which the name matches the LIKE pattern.
8258 char *zExpr
= sqlite3_mprintf(
8259 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8260 " SELECT 1 FROM sqlite_schema WHERE "
8261 " name LIKE %Q ESCAPE '\\' AND"
8262 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8263 " substr(o.name, 1, length(name)+1) == (name||'_')"
8264 ")", azArg
[i
], azArg
[i
]
8268 zLike
= sqlite3_mprintf("%z OR %z", zLike
, zExpr
);
8277 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8278 /* When playing back a "dump", the content might appear in an order
8279 ** which causes immediate foreign key constraints to be violated.
8280 ** So disable foreign-key constraint enforcement to prevent problems. */
8281 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
8282 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
8284 p
->writableSchema
= 0;
8286 /* Set writable_schema=ON since doing so forces SQLite to initialize
8287 ** as much of the schema as it can even if the sqlite_schema table is
8289 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8291 if( zLike
==0 ) zLike
= sqlite3_mprintf("true");
8292 zSql
= sqlite3_mprintf(
8293 "SELECT name, type, sql FROM sqlite_schema AS o "
8294 "WHERE (%s) AND type=='table'"
8296 " ORDER BY tbl_name='sqlite_sequence', rowid",
8299 run_schema_dump_query(p
,zSql
);
8301 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8302 zSql
= sqlite3_mprintf(
8303 "SELECT sql FROM sqlite_schema AS o "
8304 "WHERE (%s) AND sql NOT NULL"
8305 " AND type IN ('index','trigger','view')",
8308 run_table_dump_query(p
, zSql
);
8311 sqlite3_free(zLike
);
8312 if( p
->writableSchema
){
8313 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
8314 p
->writableSchema
= 0;
8316 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8317 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
8318 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8319 raw_printf(p
->out
, p
->nErr
?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8321 p
->showHeader
= savedShowHeader
;
8322 p
->shellFlgs
= savedShellFlags
;
8325 if( c
=='e' && cli_strncmp(azArg
[0], "echo", n
)==0 ){
8327 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
8329 raw_printf(stderr
, "Usage: .echo on|off\n");
8334 if( c
=='e' && cli_strncmp(azArg
[0], "eqp", n
)==0 ){
8337 if( p
->autoEQPtrace
){
8338 if( p
->db
) sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8339 p
->autoEQPtrace
= 0;
8341 if( cli_strcmp(azArg
[1],"full")==0 ){
8342 p
->autoEQP
= AUTOEQP_full
;
8343 }else if( cli_strcmp(azArg
[1],"trigger")==0 ){
8344 p
->autoEQP
= AUTOEQP_trigger
;
8346 }else if( cli_strcmp(azArg
[1],"test")==0 ){
8347 p
->autoEQP
= AUTOEQP_on
;
8349 }else if( cli_strcmp(azArg
[1],"trace")==0 ){
8350 p
->autoEQP
= AUTOEQP_full
;
8351 p
->autoEQPtrace
= 1;
8353 sqlite3_exec(p
->db
, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8354 sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8357 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
8360 raw_printf(stderr
, "Usage: .eqp off|on|trace|trigger|full\n");
8365 #ifndef SQLITE_SHELL_FIDDLE
8366 if( c
=='e' && cli_strncmp(azArg
[0], "exit", n
)==0 ){
8367 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
8372 /* The ".explain" command is automatic now. It is largely pointless. It
8373 ** retained purely for backwards compatibility */
8374 if( c
=='e' && cli_strncmp(azArg
[0], "explain", n
)==0 ){
8377 if( cli_strcmp(azArg
[1],"auto")==0 ){
8380 val
= booleanValue(azArg
[1]);
8383 if( val
==1 && p
->mode
!=MODE_Explain
){
8384 p
->normalMode
= p
->mode
;
8385 p
->mode
= MODE_Explain
;
8388 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8390 }else if( val
==99 ){
8391 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8396 #ifndef SQLITE_OMIT_VIRTUALTABLE
8397 if( c
=='e' && cli_strncmp(azArg
[0], "expert", n
)==0 ){
8400 "Cannot run experimental commands such as \"%s\" in safe mode\n",
8405 expertDotCommand(p
, azArg
, nArg
);
8410 if( c
=='f' && cli_strncmp(azArg
[0], "filectrl", n
)==0 ){
8411 static const struct {
8412 const char *zCtrlName
; /* Name of a test-control option */
8413 int ctrlCode
; /* Integer code for that option */
8414 const char *zUsage
; /* Usage notes */
8416 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE
, "SIZE" },
8417 { "data_version", SQLITE_FCNTL_DATA_VERSION
, "" },
8418 { "has_moved", SQLITE_FCNTL_HAS_MOVED
, "" },
8419 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT
, "MILLISEC" },
8420 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL
, "[BOOLEAN]" },
8421 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8422 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE
, "[BOOLEAN]" },
8423 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES
, "[N]" },
8424 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT
, "[LIMIT]" },
8425 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME
, "" },
8426 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8430 sqlite3_int64 iRes
= 0; /* Integer result to display if rc2==1 */
8431 int isOk
= 0; /* 0: usage 1: %lld 2: no-result */
8433 const char *zCmd
= 0;
8434 const char *zSchema
= 0;
8437 zCmd
= nArg
>=2 ? azArg
[1] : "help";
8440 && (cli_strcmp(zCmd
,"--schema")==0 || cli_strcmp(zCmd
,"-schema")==0)
8444 for(i
=3; i
<nArg
; i
++) azArg
[i
-2] = azArg
[i
];
8449 /* The argument can optionally begin with "-" or "--" */
8450 if( zCmd
[0]=='-' && zCmd
[1] ){
8452 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
8455 /* --help lists all file-controls */
8456 if( cli_strcmp(zCmd
,"help")==0 ){
8457 utf8_printf(p
->out
, "Available file-controls:\n");
8458 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8459 utf8_printf(p
->out
, " .filectrl %s %s\n",
8460 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
8463 goto meta_command_exit
;
8466 /* convert filectrl text option to value. allow any unique prefix
8467 ** of the option name, or a numerical value. */
8468 n2
= strlen30(zCmd
);
8469 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8470 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
8472 filectrl
= aCtrl
[i
].ctrlCode
;
8475 utf8_printf(stderr
, "Error: ambiguous file-control: \"%s\"\n"
8476 "Use \".filectrl --help\" for help\n", zCmd
);
8478 goto meta_command_exit
;
8483 utf8_printf(stderr
,"Error: unknown file-control: %s\n"
8484 "Use \".filectrl --help\" for help\n", zCmd
);
8487 case SQLITE_FCNTL_SIZE_LIMIT
: {
8488 if( nArg
!=2 && nArg
!=3 ) break;
8489 iRes
= nArg
==3 ? integerValue(azArg
[2]) : -1;
8490 sqlite3_file_control(p
->db
, zSchema
, SQLITE_FCNTL_SIZE_LIMIT
, &iRes
);
8494 case SQLITE_FCNTL_LOCK_TIMEOUT
:
8495 case SQLITE_FCNTL_CHUNK_SIZE
: {
8497 if( nArg
!=3 ) break;
8498 x
= (int)integerValue(azArg
[2]);
8499 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8503 case SQLITE_FCNTL_PERSIST_WAL
:
8504 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
8506 if( nArg
!=2 && nArg
!=3 ) break;
8507 x
= nArg
==3 ? booleanValue(azArg
[2]) : -1;
8508 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8513 case SQLITE_FCNTL_DATA_VERSION
:
8514 case SQLITE_FCNTL_HAS_MOVED
: {
8516 if( nArg
!=2 ) break;
8517 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8522 case SQLITE_FCNTL_TEMPFILENAME
: {
8524 if( nArg
!=2 ) break;
8525 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &z
);
8527 utf8_printf(p
->out
, "%s\n", z
);
8533 case SQLITE_FCNTL_RESERVE_BYTES
: {
8537 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8540 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8541 utf8_printf(p
->out
,"%d\n", x
);
8547 if( isOk
==0 && iCtrl
>=0 ){
8548 utf8_printf(p
->out
, "Usage: .filectrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
8550 }else if( isOk
==1 ){
8552 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%lld", iRes
);
8553 raw_printf(p
->out
, "%s\n", zBuf
);
8557 if( c
=='f' && cli_strncmp(azArg
[0], "fullschema", n
)==0 ){
8560 memcpy(&data
, p
, sizeof(data
));
8561 data
.showHeader
= 0;
8562 data
.cMode
= data
.mode
= MODE_Semi
;
8563 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
8564 data
.cMode
= data
.mode
= MODE_Pretty
;
8568 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
8570 goto meta_command_exit
;
8573 rc
= sqlite3_exec(p
->db
,
8575 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8576 " FROM sqlite_schema UNION ALL"
8577 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8578 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8582 if( rc
==SQLITE_OK
){
8583 sqlite3_stmt
*pStmt
;
8584 rc
= sqlite3_prepare_v2(p
->db
,
8585 "SELECT rowid FROM sqlite_schema"
8586 " WHERE name GLOB 'sqlite_stat[134]'",
8588 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
8589 sqlite3_finalize(pStmt
);
8592 raw_printf(p
->out
, "/* No STAT tables available */\n");
8594 raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
8595 data
.cMode
= data
.mode
= MODE_Insert
;
8596 data
.zDestTable
= "sqlite_stat1";
8597 shell_exec(&data
, "SELECT * FROM sqlite_stat1", 0);
8598 data
.zDestTable
= "sqlite_stat4";
8599 shell_exec(&data
, "SELECT * FROM sqlite_stat4", 0);
8600 raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
8604 if( c
=='h' && cli_strncmp(azArg
[0], "headers", n
)==0 ){
8606 p
->showHeader
= booleanValue(azArg
[1]);
8607 p
->shellFlgs
|= SHFLG_HeaderSet
;
8609 raw_printf(stderr
, "Usage: .headers on|off\n");
8614 if( c
=='h' && cli_strncmp(azArg
[0], "help", n
)==0 ){
8616 n
= showHelp(p
->out
, azArg
[1]);
8618 utf8_printf(p
->out
, "Nothing matches '%s'\n", azArg
[1]);
8621 showHelp(p
->out
, 0);
8625 #ifndef SQLITE_SHELL_FIDDLE
8626 if( c
=='i' && cli_strncmp(azArg
[0], "import", n
)==0 ){
8627 char *zTable
= 0; /* Insert data into this table */
8628 char *zSchema
= 0; /* within this schema (may default to "main") */
8629 char *zFile
= 0; /* Name of file to extra content from */
8630 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
8631 int nCol
; /* Number of columns in the table */
8632 int nByte
; /* Number of bytes in an SQL string */
8633 int i
, j
; /* Loop counters */
8634 int needCommit
; /* True to COMMIT or ROLLBACK at end */
8635 int nSep
; /* Number of bytes in p->colSeparator[] */
8636 char *zSql
; /* An SQL statement */
8637 char *zFullTabName
; /* Table name with schema if applicable */
8638 ImportCtx sCtx
; /* Reader context */
8639 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
8640 int eVerbose
= 0; /* Larger for more console output */
8641 int nSkip
= 0; /* Initial lines to skip */
8642 int useOutputMode
= 1; /* Use output mode to determine separators */
8643 char *zCreate
= 0; /* CREATE TABLE statement text */
8645 failIfSafeMode(p
, "cannot run .import in safe mode");
8646 memset(&sCtx
, 0, sizeof(sCtx
));
8647 if( p
->mode
==MODE_Ascii
){
8648 xRead
= ascii_read_one_field
;
8650 xRead
= csv_read_one_field
;
8653 for(i
=1; i
<nArg
; i
++){
8655 if( z
[0]=='-' && z
[1]=='-' ) z
++;
8659 }else if( zTable
==0 ){
8662 utf8_printf(p
->out
, "ERROR: extra argument: \"%s\". Usage:\n", z
);
8663 showHelp(p
->out
, "import");
8664 goto meta_command_exit
;
8666 }else if( cli_strcmp(z
,"-v")==0 ){
8668 }else if( cli_strcmp(z
,"-schema")==0 && i
<nArg
-1 ){
8669 zSchema
= azArg
[++i
];
8670 }else if( cli_strcmp(z
,"-skip")==0 && i
<nArg
-1 ){
8671 nSkip
= integerValue(azArg
[++i
]);
8672 }else if( cli_strcmp(z
,"-ascii")==0 ){
8673 sCtx
.cColSep
= SEP_Unit
[0];
8674 sCtx
.cRowSep
= SEP_Record
[0];
8675 xRead
= ascii_read_one_field
;
8677 }else if( cli_strcmp(z
,"-csv")==0 ){
8679 sCtx
.cRowSep
= '\n';
8680 xRead
= csv_read_one_field
;
8683 utf8_printf(p
->out
, "ERROR: unknown option: \"%s\". Usage:\n", z
);
8684 showHelp(p
->out
, "import");
8685 goto meta_command_exit
;
8689 utf8_printf(p
->out
, "ERROR: missing %s argument. Usage:\n",
8690 zFile
==0 ? "FILE" : "TABLE");
8691 showHelp(p
->out
, "import");
8692 goto meta_command_exit
;
8696 if( useOutputMode
){
8697 /* If neither the --csv or --ascii options are specified, then set
8698 ** the column and row separator characters from the output mode. */
8699 nSep
= strlen30(p
->colSeparator
);
8702 "Error: non-null column separator required for import\n");
8703 goto meta_command_exit
;
8707 "Error: multi-character column separators not allowed"
8709 goto meta_command_exit
;
8711 nSep
= strlen30(p
->rowSeparator
);
8714 "Error: non-null row separator required for import\n");
8715 goto meta_command_exit
;
8717 if( nSep
==2 && p
->mode
==MODE_Csv
8718 && cli_strcmp(p
->rowSeparator
,SEP_CrLf
)==0
8720 /* When importing CSV (only), if the row separator is set to the
8721 ** default output row separator, change it to the default input
8722 ** row separator. This avoids having to maintain different input
8723 ** and output row separators. */
8724 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8725 nSep
= strlen30(p
->rowSeparator
);
8728 raw_printf(stderr
, "Error: multi-character row separators not allowed"
8730 goto meta_command_exit
;
8732 sCtx
.cColSep
= p
->colSeparator
[0];
8733 sCtx
.cRowSep
= p
->rowSeparator
[0];
8737 if( sCtx
.zFile
[0]=='|' ){
8738 #ifdef SQLITE_OMIT_POPEN
8739 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
8740 goto meta_command_exit
;
8742 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
8743 sCtx
.zFile
= "<pipe>";
8744 sCtx
.xCloser
= pclose
;
8747 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
8748 sCtx
.xCloser
= fclose
;
8751 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
8752 goto meta_command_exit
;
8754 if( eVerbose
>=2 || (eVerbose
>=1 && useOutputMode
) ){
8757 zSep
[0] = sCtx
.cColSep
;
8758 utf8_printf(p
->out
, "Column separator ");
8759 output_c_string(p
->out
, zSep
);
8760 utf8_printf(p
->out
, ", row separator ");
8761 zSep
[0] = sCtx
.cRowSep
;
8762 output_c_string(p
->out
, zSep
);
8763 utf8_printf(p
->out
, "\n");
8765 sCtx
.z
= sqlite3_malloc64(120);
8767 import_cleanup(&sCtx
);
8768 shell_out_of_memory();
8770 /* Below, resources must be freed before exit. */
8771 while( (nSkip
--)>0 ){
8772 while( xRead(&sCtx
) && sCtx
.cTerm
==sCtx
.cColSep
){}
8775 zFullTabName
= sqlite3_mprintf("\"%w\".\"%w\"", zSchema
, zTable
);
8777 zFullTabName
= sqlite3_mprintf("\"%w\"", zTable
);
8779 zSql
= sqlite3_mprintf("SELECT * FROM %s", zFullTabName
);
8780 if( zSql
==0 || zFullTabName
==0 ){
8781 import_cleanup(&sCtx
);
8782 shell_out_of_memory();
8784 nByte
= strlen30(zSql
);
8785 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8786 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
8787 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
8788 sqlite3
*dbCols
= 0;
8791 zCreate
= sqlite3_mprintf("CREATE TABLE %s", zFullTabName
);
8792 while( xRead(&sCtx
) ){
8793 zAutoColumn(sCtx
.z
, &dbCols
, 0);
8794 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
8796 zColDefs
= zAutoColumn(0, &dbCols
, &zRenames
);
8798 utf8_printf((stdin_is_interactive
&& p
->in
==stdin
)? p
->out
: stderr
,
8799 "Columns renamed during .import %s due to duplicates:\n"
8800 "%s\n", sCtx
.zFile
, zRenames
);
8801 sqlite3_free(zRenames
);
8805 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
8807 sqlite3_free(zCreate
);
8809 sqlite3_free(zFullTabName
);
8810 import_cleanup(&sCtx
);
8812 goto meta_command_exit
;
8814 zCreate
= sqlite3_mprintf("%z%z\n", zCreate
, zColDefs
);
8816 utf8_printf(p
->out
, "%s\n", zCreate
);
8818 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
8820 utf8_printf(stderr
, "%s failed:\n%s\n", zCreate
, sqlite3_errmsg(p
->db
));
8823 sqlite3_free(zCreate
);
8825 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8828 if (pStmt
) sqlite3_finalize(pStmt
);
8829 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
8833 nCol
= sqlite3_column_count(pStmt
);
8834 sqlite3_finalize(pStmt
);
8836 if( nCol
==0 ) return 0; /* no columns, no error */
8837 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
8839 import_cleanup(&sCtx
);
8840 shell_out_of_memory();
8842 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO %s VALUES(?", zFullTabName
);
8844 for(i
=1; i
<nCol
; i
++){
8851 utf8_printf(p
->out
, "Insert using: %s\n", zSql
);
8853 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8855 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
8856 if (pStmt
) sqlite3_finalize(pStmt
);
8860 sqlite3_free(zFullTabName
);
8861 needCommit
= sqlite3_get_autocommit(p
->db
);
8862 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
8864 int startLine
= sCtx
.nLine
;
8865 for(i
=0; i
<nCol
; i
++){
8866 char *z
= xRead(&sCtx
);
8868 ** Did we reach end-of-file before finding any columns?
8869 ** If so, stop instead of NULL filling the remaining columns.
8871 if( z
==0 && i
==0 ) break;
8873 ** Did we reach end-of-file OR end-of-line before finding any
8874 ** columns in ASCII mode? If so, stop instead of NULL filling
8875 ** the remaining columns.
8877 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
8878 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
8879 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
8880 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
8881 "filling the rest with NULL\n",
8882 sCtx
.zFile
, startLine
, nCol
, i
+1);
8884 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
8887 if( sCtx
.cTerm
==sCtx
.cColSep
){
8891 }while( sCtx
.cTerm
==sCtx
.cColSep
);
8892 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
8894 sCtx
.zFile
, startLine
, nCol
, i
);
8897 sqlite3_step(pStmt
);
8898 rc
= sqlite3_reset(pStmt
);
8899 if( rc
!=SQLITE_OK
){
8900 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
8901 startLine
, sqlite3_errmsg(p
->db
));
8907 }while( sCtx
.cTerm
!=EOF
);
8909 import_cleanup(&sCtx
);
8910 sqlite3_finalize(pStmt
);
8911 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
8914 "Added %d rows with %d errors using %d lines of input\n",
8915 sCtx
.nRow
, sCtx
.nErr
, sCtx
.nLine
-1);
8918 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8920 #ifndef SQLITE_UNTESTABLE
8921 if( c
=='i' && cli_strncmp(azArg
[0], "imposter", n
)==0 ){
8924 sqlite3_stmt
*pStmt
;
8926 int isWO
= 0; /* True if making an imposter of a WITHOUT ROWID table */
8927 int lenPK
= 0; /* Length of the PRIMARY KEY string for isWO tables */
8929 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
8930 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n"
8931 " .imposter off\n");
8932 /* Also allowed, but not documented:
8934 ** .imposter TABLE IMPOSTER
8936 ** where TABLE is a WITHOUT ROWID table. In that case, the
8937 ** imposter is another WITHOUT ROWID table with the columns in
8938 ** storage order. */
8940 goto meta_command_exit
;
8944 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
8945 goto meta_command_exit
;
8947 zSql
= sqlite3_mprintf(
8948 "SELECT rootpage, 0 FROM sqlite_schema"
8949 " WHERE name='%q' AND type='index'"
8951 "SELECT rootpage, 1 FROM sqlite_schema"
8952 " WHERE name='%q' AND type='table'"
8953 " AND sql LIKE '%%without%%rowid%%'",
8956 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8958 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
8959 tnum
= sqlite3_column_int(pStmt
, 0);
8960 isWO
= sqlite3_column_int(pStmt
, 1);
8962 sqlite3_finalize(pStmt
);
8963 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
8964 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8967 while( rc
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
8969 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
8972 if( sqlite3_column_int(pStmt
,1)==-1 ){
8975 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
8979 if( isWO
&& lenPK
==0 && sqlite3_column_int(pStmt
,5)==0 && zCollist
){
8980 lenPK
= (int)strlen(zCollist
);
8983 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
8985 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
8988 sqlite3_finalize(pStmt
);
8989 if( i
==0 || tnum
==0 ){
8990 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
8992 sqlite3_free(zCollist
);
8993 goto meta_command_exit
;
8995 if( lenPK
==0 ) lenPK
= 100000;
8996 zSql
= sqlite3_mprintf(
8997 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8998 azArg
[2], zCollist
, lenPK
, zCollist
);
8999 sqlite3_free(zCollist
);
9000 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
9001 if( rc
==SQLITE_OK
){
9002 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9003 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
9005 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
9007 utf8_printf(stdout
, "%s;\n", zSql
);
9009 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9010 azArg
[1], isWO
? "table" : "index"
9014 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
9019 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9021 #ifdef SQLITE_ENABLE_IOTRACE
9022 if( c
=='i' && cli_strncmp(azArg
[0], "iotrace", n
)==0 ){
9023 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
9024 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
9028 }else if( cli_strcmp(azArg
[1], "-")==0 ){
9029 sqlite3IoTrace
= iotracePrintf
;
9032 iotrace
= fopen(azArg
[1], "w");
9034 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
9038 sqlite3IoTrace
= iotracePrintf
;
9044 if( c
=='l' && n
>=5 && cli_strncmp(azArg
[0], "limits", n
)==0 ){
9045 static const struct {
9046 const char *zLimitName
; /* Name of a limit */
9047 int limitCode
; /* Integer code for that limit */
9049 { "length", SQLITE_LIMIT_LENGTH
},
9050 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
9051 { "column", SQLITE_LIMIT_COLUMN
},
9052 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
9053 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
9054 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
9055 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
9056 { "attached", SQLITE_LIMIT_ATTACHED
},
9057 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
9058 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
9059 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
9060 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
9065 for(i
=0; i
<ArraySize(aLimit
); i
++){
9066 printf("%20s %d\n", aLimit
[i
].zLimitName
,
9067 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
9070 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
9072 goto meta_command_exit
;
9075 n2
= strlen30(azArg
[1]);
9076 for(i
=0; i
<ArraySize(aLimit
); i
++){
9077 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
9081 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
9083 goto meta_command_exit
;
9088 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
9089 "enter \".limits\" with no arguments for a list.\n",
9092 goto meta_command_exit
;
9095 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
9096 (int)integerValue(azArg
[2]));
9098 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
9099 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
9103 if( c
=='l' && n
>2 && cli_strncmp(azArg
[0], "lint", n
)==0 ){
9105 lintDotCommand(p
, azArg
, nArg
);
9108 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9109 if( c
=='l' && cli_strncmp(azArg
[0], "load", n
)==0 ){
9110 const char *zFile
, *zProc
;
9112 failIfSafeMode(p
, "cannot run .load in safe mode");
9114 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
9116 goto meta_command_exit
;
9119 zProc
= nArg
>=3 ? azArg
[2] : 0;
9121 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
9122 if( rc
!=SQLITE_OK
){
9123 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
9124 sqlite3_free(zErrMsg
);
9130 #ifndef SQLITE_SHELL_FIDDLE
9131 if( c
=='l' && cli_strncmp(azArg
[0], "log", n
)==0 ){
9132 failIfSafeMode(p
, "cannot run .log in safe mode");
9134 raw_printf(stderr
, "Usage: .log FILENAME\n");
9137 const char *zFile
= azArg
[1];
9138 output_file_close(p
->pLog
);
9139 p
->pLog
= output_file_open(zFile
, 0);
9144 if( c
=='m' && cli_strncmp(azArg
[0], "mode", n
)==0 ){
9145 const char *zMode
= 0;
9146 const char *zTabname
= 0;
9148 ColModeOpts cmOpts
= ColModeOpts_default
;
9149 for(i
=1; i
<nArg
; i
++){
9150 const char *z
= azArg
[i
];
9151 if( optionMatch(z
,"wrap") && i
+1<nArg
){
9152 cmOpts
.iWrap
= integerValue(azArg
[++i
]);
9153 }else if( optionMatch(z
,"ww") ){
9154 cmOpts
.bWordWrap
= 1;
9155 }else if( optionMatch(z
,"wordwrap") && i
+1<nArg
){
9156 cmOpts
.bWordWrap
= (u8
)booleanValue(azArg
[++i
]);
9157 }else if( optionMatch(z
,"quote") ){
9159 }else if( optionMatch(z
,"noquote") ){
9161 }else if( zMode
==0 ){
9163 /* Apply defaults for qbox pseudo-mode. If that
9164 * overwrites already-set values, user was informed of this.
9166 if( cli_strcmp(z
, "qbox")==0 ){
9167 ColModeOpts cmo
= ColModeOpts_default_qbox
;
9171 }else if( zTabname
==0 ){
9173 }else if( z
[0]=='-' ){
9174 utf8_printf(stderr
, "unknown option: %s\n", z
);
9175 utf8_printf(stderr
, "options:\n"
9178 " --wordwrap on/off\n"
9182 goto meta_command_exit
;
9184 utf8_printf(stderr
, "extra argument: \"%s\"\n", z
);
9186 goto meta_command_exit
;
9190 if( p
->mode
==MODE_Column
9191 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
9195 "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9196 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
9197 p
->cmOpts
.bWordWrap
? "on" : "off",
9198 p
->cmOpts
.bQuote
? "" : "no");
9200 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
9202 zMode
= modeDescr
[p
->mode
];
9204 n2
= strlen30(zMode
);
9205 if( cli_strncmp(zMode
,"lines",n2
)==0 ){
9206 p
->mode
= MODE_Line
;
9207 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9208 }else if( cli_strncmp(zMode
,"columns",n2
)==0 ){
9209 p
->mode
= MODE_Column
;
9210 if( (p
->shellFlgs
& SHFLG_HeaderSet
)==0 ){
9213 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9215 }else if( cli_strncmp(zMode
,"list",n2
)==0 ){
9216 p
->mode
= MODE_List
;
9217 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
9218 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9219 }else if( cli_strncmp(zMode
,"html",n2
)==0 ){
9220 p
->mode
= MODE_Html
;
9221 }else if( cli_strncmp(zMode
,"tcl",n2
)==0 ){
9223 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
9224 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9225 }else if( cli_strncmp(zMode
,"csv",n2
)==0 ){
9227 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9228 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9229 }else if( cli_strncmp(zMode
,"tabs",n2
)==0 ){
9230 p
->mode
= MODE_List
;
9231 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
9232 }else if( cli_strncmp(zMode
,"insert",n2
)==0 ){
9233 p
->mode
= MODE_Insert
;
9234 set_table_name(p
, zTabname
? zTabname
: "table");
9235 }else if( cli_strncmp(zMode
,"quote",n2
)==0 ){
9236 p
->mode
= MODE_Quote
;
9237 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9238 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9239 }else if( cli_strncmp(zMode
,"ascii",n2
)==0 ){
9240 p
->mode
= MODE_Ascii
;
9241 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
9242 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
9243 }else if( cli_strncmp(zMode
,"markdown",n2
)==0 ){
9244 p
->mode
= MODE_Markdown
;
9246 }else if( cli_strncmp(zMode
,"table",n2
)==0 ){
9247 p
->mode
= MODE_Table
;
9249 }else if( cli_strncmp(zMode
,"box",n2
)==0 ){
9252 }else if( cli_strncmp(zMode
,"count",n2
)==0 ){
9253 p
->mode
= MODE_Count
;
9254 }else if( cli_strncmp(zMode
,"off",n2
)==0 ){
9256 }else if( cli_strncmp(zMode
,"json",n2
)==0 ){
9257 p
->mode
= MODE_Json
;
9259 raw_printf(stderr
, "Error: mode should be one of: "
9260 "ascii box column csv html insert json line list markdown "
9261 "qbox quote table tabs tcl\n");
9267 #ifndef SQLITE_SHELL_FIDDLE
9268 if( c
=='n' && cli_strcmp(azArg
[0], "nonce")==0 ){
9270 raw_printf(stderr
, "Usage: .nonce NONCE\n");
9272 }else if( p
->zNonce
==0 || cli_strcmp(azArg
[1],p
->zNonce
)!=0 ){
9273 raw_printf(stderr
, "line %d: incorrect nonce: \"%s\"\n",
9274 p
->lineno
, azArg
[1]);
9278 return 0; /* Return immediately to bypass the safe mode reset
9279 ** at the end of this procedure */
9282 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9284 if( c
=='n' && cli_strncmp(azArg
[0], "nullvalue", n
)==0 ){
9286 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
9287 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
9289 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
9294 if( c
=='o' && cli_strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
9295 const char *zFN
= 0; /* Pointer to constant filename */
9296 char *zNewFilename
= 0; /* Name of the database file to open */
9297 int iName
= 1; /* Index in azArg[] of the filename */
9298 int newFlag
= 0; /* True to delete file before opening */
9299 int openMode
= SHELL_OPEN_UNSPEC
;
9301 /* Check for command-line arguments */
9302 for(iName
=1; iName
<nArg
; iName
++){
9303 const char *z
= azArg
[iName
];
9304 #ifndef SQLITE_SHELL_FIDDLE
9305 if( optionMatch(z
,"new") ){
9307 #ifdef SQLITE_HAVE_ZLIB
9308 }else if( optionMatch(z
, "zip") ){
9309 openMode
= SHELL_OPEN_ZIPFILE
;
9311 }else if( optionMatch(z
, "append") ){
9312 openMode
= SHELL_OPEN_APPENDVFS
;
9313 }else if( optionMatch(z
, "readonly") ){
9314 openMode
= SHELL_OPEN_READONLY
;
9315 }else if( optionMatch(z
, "nofollow") ){
9316 p
->openFlags
|= SQLITE_OPEN_NOFOLLOW
;
9317 #ifndef SQLITE_OMIT_DESERIALIZE
9318 }else if( optionMatch(z
, "deserialize") ){
9319 openMode
= SHELL_OPEN_DESERIALIZE
;
9320 }else if( optionMatch(z
, "hexdb") ){
9321 openMode
= SHELL_OPEN_HEXDB
;
9322 }else if( optionMatch(z
, "maxsize") && iName
+1<nArg
){
9323 p
->szMax
= integerValue(azArg
[++iName
]);
9324 #endif /* SQLITE_OMIT_DESERIALIZE */
9326 #endif /* !SQLITE_SHELL_FIDDLE */
9328 utf8_printf(stderr
, "unknown option: %s\n", z
);
9330 goto meta_command_exit
;
9332 utf8_printf(stderr
, "extra argument: \"%s\"\n", z
);
9334 goto meta_command_exit
;
9340 /* Close the existing database */
9341 session_close_all(p
, -1);
9344 p
->pAuxDb
->zDbFilename
= 0;
9345 sqlite3_free(p
->pAuxDb
->zFreeOnClose
);
9346 p
->pAuxDb
->zFreeOnClose
= 0;
9347 p
->openMode
= openMode
;
9351 /* If a filename is specified, try to open it first */
9352 if( zFN
|| p
->openMode
==SHELL_OPEN_HEXDB
){
9353 if( newFlag
&& zFN
&& !p
->bSafeMode
) shellDeleteFile(zFN
);
9354 #ifndef SQLITE_SHELL_FIDDLE
9356 && p
->openMode
!=SHELL_OPEN_HEXDB
9358 && cli_strcmp(zFN
,":memory:")!=0
9360 failIfSafeMode(p
, "cannot open disk-based database files in safe mode");
9363 /* WASM mode has its own sandboxed pseudo-filesystem. */
9366 zNewFilename
= sqlite3_mprintf("%s", zFN
);
9367 shell_check_oom(zNewFilename
);
9371 p
->pAuxDb
->zDbFilename
= zNewFilename
;
9372 open_db(p
, OPEN_DB_KEEPALIVE
);
9374 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
9375 sqlite3_free(zNewFilename
);
9377 p
->pAuxDb
->zFreeOnClose
= zNewFilename
;
9381 /* As a fall-back open a TEMP database */
9382 p
->pAuxDb
->zDbFilename
= 0;
9387 #ifndef SQLITE_SHELL_FIDDLE
9389 && (cli_strncmp(azArg
[0], "output", n
)==0
9390 || cli_strncmp(azArg
[0], "once", n
)==0))
9391 || (c
=='e' && n
==5 && cli_strcmp(azArg
[0],"excel")==0)
9397 int bOnce
= 0; /* 0: .output, 1: .once, 2: .excel */
9398 unsigned char zBOM
[4]; /* Byte-order mark to using if --bom is present */
9401 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
9405 }else if( cli_strncmp(azArg
[0],"once",n
)==0 ){
9408 for(i
=1; i
<nArg
; i
++){
9411 if( z
[1]=='-' ) z
++;
9412 if( cli_strcmp(z
,"-bom")==0 ){
9417 }else if( c
!='e' && cli_strcmp(z
,"-x")==0 ){
9418 eMode
= 'x'; /* spreadsheet */
9419 }else if( c
!='e' && cli_strcmp(z
,"-e")==0 ){
9420 eMode
= 'e'; /* text editor */
9422 utf8_printf(p
->out
, "ERROR: unknown option: \"%s\". Usage:\n",
9424 showHelp(p
->out
, azArg
[0]);
9426 goto meta_command_exit
;
9428 }else if( zFile
==0 && eMode
!='e' && eMode
!='x' ){
9429 zFile
= sqlite3_mprintf("%s", z
);
9430 if( zFile
&& zFile
[0]=='|' ){
9431 while( i
+1<nArg
) zFile
= sqlite3_mprintf("%z %s", zFile
, azArg
[++i
]);
9435 utf8_printf(p
->out
,"ERROR: extra parameter: \"%s\". Usage:\n",
9437 showHelp(p
->out
, azArg
[0]);
9439 sqlite3_free(zFile
);
9440 goto meta_command_exit
;
9444 zFile
= sqlite3_mprintf("stdout");
9452 #ifndef SQLITE_NOHAVE_SYSTEM
9453 if( eMode
=='e' || eMode
=='x' ){
9457 /* spreadsheet mode. Output as CSV. */
9458 newTempFile(p
, "csv");
9459 ShellClearFlag(p
, SHFLG_Echo
);
9461 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9462 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9464 /* text editor mode */
9465 newTempFile(p
, "txt");
9468 sqlite3_free(zFile
);
9469 zFile
= sqlite3_mprintf("%s", p
->zTempFile
);
9471 #endif /* SQLITE_NOHAVE_SYSTEM */
9472 shell_check_oom(zFile
);
9473 if( zFile
[0]=='|' ){
9474 #ifdef SQLITE_OMIT_POPEN
9475 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
9479 p
->out
= popen(zFile
+ 1, "w");
9481 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
9485 if( zBOM
[0] ) fwrite(zBOM
, 1, 3, p
->out
);
9486 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9490 p
->out
= output_file_open(zFile
, bTxtMode
);
9492 if( cli_strcmp(zFile
,"off")!=0 ){
9493 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
9498 if( zBOM
[0] ) fwrite(zBOM
, 1, 3, p
->out
);
9499 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9502 sqlite3_free(zFile
);
9504 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9506 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "parameter", n
)==0 ){
9508 if( nArg
<=1 ) goto parameter_syntax_error
;
9511 ** Clear all bind parameters by dropping the TEMP table that holds them.
9513 if( nArg
==2 && cli_strcmp(azArg
[1],"clear")==0 ){
9514 sqlite3_exec(p
->db
, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9519 ** List all bind parameters.
9521 if( nArg
==2 && cli_strcmp(azArg
[1],"list")==0 ){
9522 sqlite3_stmt
*pStmt
= 0;
9525 rx
= sqlite3_prepare_v2(p
->db
,
9526 "SELECT max(length(key)) "
9527 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9528 if( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9529 len
= sqlite3_column_int(pStmt
, 0);
9530 if( len
>40 ) len
= 40;
9532 sqlite3_finalize(pStmt
);
9535 rx
= sqlite3_prepare_v2(p
->db
,
9536 "SELECT key, quote(value) "
9537 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9538 while( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9539 utf8_printf(p
->out
, "%-*s %s\n", len
, sqlite3_column_text(pStmt
,0),
9540 sqlite3_column_text(pStmt
,1));
9542 sqlite3_finalize(pStmt
);
9547 ** Make sure the TEMP table used to hold bind parameters exists.
9548 ** Create it if necessary.
9550 if( nArg
==2 && cli_strcmp(azArg
[1],"init")==0 ){
9554 /* .parameter set NAME VALUE
9555 ** Set or reset a bind parameter. NAME should be the full parameter
9556 ** name exactly as it appears in the query. (ex: $abc, @def). The
9557 ** VALUE can be in either SQL literal notation, or if not it will be
9558 ** understood to be a text string.
9560 if( nArg
==4 && cli_strcmp(azArg
[1],"set")==0 ){
9563 sqlite3_stmt
*pStmt
;
9564 const char *zKey
= azArg
[2];
9565 const char *zValue
= azArg
[3];
9567 zSql
= sqlite3_mprintf(
9568 "REPLACE INTO temp.sqlite_parameters(key,value)"
9569 "VALUES(%Q,%s);", zKey
, zValue
);
9570 shell_check_oom(zSql
);
9572 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9574 if( rx
!=SQLITE_OK
){
9575 sqlite3_finalize(pStmt
);
9577 zSql
= sqlite3_mprintf(
9578 "REPLACE INTO temp.sqlite_parameters(key,value)"
9579 "VALUES(%Q,%Q);", zKey
, zValue
);
9580 shell_check_oom(zSql
);
9581 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9583 if( rx
!=SQLITE_OK
){
9584 utf8_printf(p
->out
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9585 sqlite3_finalize(pStmt
);
9590 sqlite3_step(pStmt
);
9591 sqlite3_finalize(pStmt
);
9594 /* .parameter unset NAME
9595 ** Remove the NAME binding from the parameter binding table, if it
9598 if( nArg
==3 && cli_strcmp(azArg
[1],"unset")==0 ){
9599 char *zSql
= sqlite3_mprintf(
9600 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg
[2]);
9601 shell_check_oom(zSql
);
9602 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9605 /* If no command name matches, show a syntax error */
9606 parameter_syntax_error
:
9607 showHelp(p
->out
, "parameter");
9610 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "print", n
)==0 ){
9612 for(i
=1; i
<nArg
; i
++){
9613 if( i
>1 ) raw_printf(p
->out
, " ");
9614 utf8_printf(p
->out
, "%s", azArg
[i
]);
9616 raw_printf(p
->out
, "\n");
9619 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9620 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "progress", n
)==0 ){
9626 for(i
=1; i
<nArg
; i
++){
9627 const char *z
= azArg
[i
];
9630 if( z
[0]=='-' ) z
++;
9631 if( cli_strcmp(z
,"quiet")==0 || cli_strcmp(z
,"q")==0 ){
9632 p
->flgProgress
|= SHELL_PROGRESS_QUIET
;
9635 if( cli_strcmp(z
,"reset")==0 ){
9636 p
->flgProgress
|= SHELL_PROGRESS_RESET
;
9639 if( cli_strcmp(z
,"once")==0 ){
9640 p
->flgProgress
|= SHELL_PROGRESS_ONCE
;
9643 if( cli_strcmp(z
,"limit")==0 ){
9645 utf8_printf(stderr
, "Error: missing argument on --limit\n");
9647 goto meta_command_exit
;
9649 p
->mxProgress
= (int)integerValue(azArg
[++i
]);
9653 utf8_printf(stderr
, "Error: unknown option: \"%s\"\n", azArg
[i
]);
9655 goto meta_command_exit
;
9657 nn
= (int)integerValue(z
);
9661 sqlite3_progress_handler(p
->db
, nn
, progress_handler
, p
);
9663 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9665 if( c
=='p' && cli_strncmp(azArg
[0], "prompt", n
)==0 ){
9667 shell_strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
9670 shell_strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
9674 #ifndef SQLITE_SHELL_FIDDLE
9675 if( c
=='q' && cli_strncmp(azArg
[0], "quit", n
)==0 ){
9680 #ifndef SQLITE_SHELL_FIDDLE
9681 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "read", n
)==0 ){
9682 FILE *inSaved
= p
->in
;
9683 int savedLineno
= p
->lineno
;
9684 failIfSafeMode(p
, "cannot run .read in safe mode");
9686 raw_printf(stderr
, "Usage: .read FILE\n");
9688 goto meta_command_exit
;
9690 if( azArg
[1][0]=='|' ){
9691 #ifdef SQLITE_OMIT_POPEN
9692 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
9696 p
->in
= popen(azArg
[1]+1, "r");
9698 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
9701 rc
= process_input(p
);
9705 }else if( (p
->in
= openChrSource(azArg
[1]))==0 ){
9706 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
9709 rc
= process_input(p
);
9713 p
->lineno
= savedLineno
;
9715 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9717 #ifndef SQLITE_SHELL_FIDDLE
9718 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "restore", n
)==0 ){
9719 const char *zSrcFile
;
9722 sqlite3_backup
*pBackup
;
9725 failIfSafeMode(p
, "cannot run .restore in safe mode");
9727 zSrcFile
= azArg
[1];
9729 }else if( nArg
==3 ){
9730 zSrcFile
= azArg
[2];
9733 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
9735 goto meta_command_exit
;
9737 rc
= sqlite3_open(zSrcFile
, &pSrc
);
9738 if( rc
!=SQLITE_OK
){
9739 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
9744 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
9746 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9750 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
9751 || rc
==SQLITE_BUSY
){
9752 if( rc
==SQLITE_BUSY
){
9753 if( nTimeout
++ >= 3 ) break;
9757 sqlite3_backup_finish(pBackup
);
9758 if( rc
==SQLITE_DONE
){
9760 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
9761 raw_printf(stderr
, "Error: source database is busy\n");
9764 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9769 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9771 if( c
=='s' && cli_strncmp(azArg
[0], "scanstats", n
)==0 ){
9773 if( cli_strcmp(azArg
[1], "est")==0 ){
9776 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
9778 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9779 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
9782 raw_printf(stderr
, "Usage: .scanstats on|off|est\n");
9787 if( c
=='s' && cli_strncmp(azArg
[0], "schema", n
)==0 ){
9791 const char *zDiv
= "(";
9792 const char *zName
= 0;
9795 int bNoSystemTabs
= 0;
9799 memcpy(&data
, p
, sizeof(data
));
9800 data
.showHeader
= 0;
9801 data
.cMode
= data
.mode
= MODE_Semi
;
9803 for(ii
=1; ii
<nArg
; ii
++){
9804 if( optionMatch(azArg
[ii
],"indent") ){
9805 data
.cMode
= data
.mode
= MODE_Pretty
;
9806 }else if( optionMatch(azArg
[ii
],"debug") ){
9808 }else if( optionMatch(azArg
[ii
],"nosys") ){
9810 }else if( azArg
[ii
][0]=='-' ){
9811 utf8_printf(stderr
, "Unknown option: \"%s\"\n", azArg
[ii
]);
9813 goto meta_command_exit
;
9814 }else if( zName
==0 ){
9818 "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9820 goto meta_command_exit
;
9824 int isSchema
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0
9825 || sqlite3_strlike(zName
, "sqlite_schema", '\\')==0
9826 || sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0
9827 || sqlite3_strlike(zName
,"sqlite_temp_schema", '\\')==0;
9829 char *new_argv
[2], *new_colv
[2];
9830 new_argv
[0] = sqlite3_mprintf(
9831 "CREATE TABLE %s (\n"
9835 " rootpage integer,\n"
9838 shell_check_oom(new_argv
[0]);
9840 new_colv
[0] = "sql";
9842 callback(&data
, 1, new_argv
, new_colv
);
9843 sqlite3_free(new_argv
[0]);
9847 sqlite3_stmt
*pStmt
= 0;
9848 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
9851 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9852 sqlite3_finalize(pStmt
);
9854 goto meta_command_exit
;
9856 appendText(&sSelect
, "SELECT sql FROM", 0);
9858 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
9859 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
9861 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
9862 appendText(&sSelect
, zDiv
, 0);
9863 zDiv
= " UNION ALL ";
9864 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
9865 if( sqlite3_stricmp(zDb
, "main")!=0 ){
9866 appendText(&sSelect
, zDb
, '\'');
9868 appendText(&sSelect
, "NULL", 0);
9870 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9871 appendText(&sSelect
, zScNum
, 0);
9872 appendText(&sSelect
, " AS snum, ", 0);
9873 appendText(&sSelect
, zDb
, '\'');
9874 appendText(&sSelect
, " AS sname FROM ", 0);
9875 appendText(&sSelect
, zDb
, quoteChar(zDb
));
9876 appendText(&sSelect
, ".sqlite_schema", 0);
9878 sqlite3_finalize(pStmt
);
9879 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9881 appendText(&sSelect
,
9882 " UNION ALL SELECT shell_module_schema(name),"
9883 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9887 appendText(&sSelect
, ") WHERE ", 0);
9889 char *zQarg
= sqlite3_mprintf("%Q", zName
);
9891 shell_check_oom(zQarg
);
9892 bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
9893 strchr(zName
, '[') != 0;
9894 if( strchr(zName
, '.') ){
9895 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
9897 appendText(&sSelect
, "lower(tbl_name)", 0);
9899 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
9900 appendText(&sSelect
, zQarg
, 0);
9902 appendText(&sSelect
, " ESCAPE '\\' ", 0);
9904 appendText(&sSelect
, " AND ", 0);
9905 sqlite3_free(zQarg
);
9907 if( bNoSystemTabs
){
9908 appendText(&sSelect
, "name NOT LIKE 'sqlite_%%' AND ", 0);
9910 appendText(&sSelect
, "sql IS NOT NULL"
9911 " ORDER BY snum, rowid", 0);
9913 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
9915 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
9920 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
9921 sqlite3_free(zErrMsg
);
9923 }else if( rc
!= SQLITE_OK
){
9924 raw_printf(stderr
,"Error: querying schema information\n");
9931 if( (c
=='s' && n
==11 && cli_strncmp(azArg
[0], "selecttrace", n
)==0)
9932 || (c
=='t' && n
==9 && cli_strncmp(azArg
[0], "treetrace", n
)==0)
9934 unsigned int x
= nArg
>=2? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
9935 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &x
);
9938 #if defined(SQLITE_ENABLE_SESSION)
9939 if( c
=='s' && cli_strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
9940 struct AuxDb
*pAuxDb
= p
->pAuxDb
;
9941 OpenSession
*pSession
= &pAuxDb
->aSession
[0];
9942 char **azCmd
= &azArg
[1];
9944 int nCmd
= nArg
- 1;
9946 if( nArg
<=1 ) goto session_syntax_error
;
9949 for(iSes
=0; iSes
<pAuxDb
->nSession
; iSes
++){
9950 if( cli_strcmp(pAuxDb
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
9952 if( iSes
<pAuxDb
->nSession
){
9953 pSession
= &pAuxDb
->aSession
[iSes
];
9957 pSession
= &pAuxDb
->aSession
[0];
9962 /* .session attach TABLE
9963 ** Invoke the sqlite3session_attach() interface to attach a particular
9964 ** table so that it is never filtered.
9966 if( cli_strcmp(azCmd
[0],"attach")==0 ){
9967 if( nCmd
!=2 ) goto session_syntax_error
;
9968 if( pSession
->p
==0 ){
9970 raw_printf(stderr
, "ERROR: No sessions are open\n");
9972 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
9974 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
9980 /* .session changeset FILE
9981 ** .session patchset FILE
9982 ** Write a changeset or patchset into a file. The file is overwritten.
9984 if( cli_strcmp(azCmd
[0],"changeset")==0
9985 || cli_strcmp(azCmd
[0],"patchset")==0
9988 failIfSafeMode(p
, "cannot run \".session %s\" in safe mode", azCmd
[0]);
9989 if( nCmd
!=2 ) goto session_syntax_error
;
9990 if( pSession
->p
==0 ) goto session_not_open
;
9991 out
= fopen(azCmd
[1], "wb");
9993 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n",
9998 if( azCmd
[0][0]=='c' ){
9999 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
10001 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
10004 printf("Error: error code %d\n", rc
);
10008 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
10009 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
10012 sqlite3_free(pChng
);
10018 ** Close the identified session
10020 if( cli_strcmp(azCmd
[0], "close")==0 ){
10021 if( nCmd
!=1 ) goto session_syntax_error
;
10022 if( pAuxDb
->nSession
){
10023 session_close(pSession
);
10024 pAuxDb
->aSession
[iSes
] = pAuxDb
->aSession
[--pAuxDb
->nSession
];
10028 /* .session enable ?BOOLEAN?
10029 ** Query or set the enable flag
10031 if( cli_strcmp(azCmd
[0], "enable")==0 ){
10033 if( nCmd
>2 ) goto session_syntax_error
;
10034 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
10035 if( pAuxDb
->nSession
){
10036 ii
= sqlite3session_enable(pSession
->p
, ii
);
10037 utf8_printf(p
->out
, "session %s enable flag = %d\n",
10038 pSession
->zName
, ii
);
10042 /* .session filter GLOB ....
10043 ** Set a list of GLOB patterns of table names to be excluded.
10045 if( cli_strcmp(azCmd
[0], "filter")==0 ){
10047 if( nCmd
<2 ) goto session_syntax_error
;
10048 if( pAuxDb
->nSession
){
10049 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
10050 sqlite3_free(pSession
->azFilter
[ii
]);
10052 sqlite3_free(pSession
->azFilter
);
10053 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
10054 pSession
->azFilter
= sqlite3_malloc( nByte
);
10055 if( pSession
->azFilter
==0 ){
10056 raw_printf(stderr
, "Error: out or memory\n");
10059 for(ii
=1; ii
<nCmd
; ii
++){
10060 char *x
= pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
10061 shell_check_oom(x
);
10063 pSession
->nFilter
= ii
-1;
10067 /* .session indirect ?BOOLEAN?
10068 ** Query or set the indirect flag
10070 if( cli_strcmp(azCmd
[0], "indirect")==0 ){
10072 if( nCmd
>2 ) goto session_syntax_error
;
10073 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
10074 if( pAuxDb
->nSession
){
10075 ii
= sqlite3session_indirect(pSession
->p
, ii
);
10076 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
10077 pSession
->zName
, ii
);
10081 /* .session isempty
10082 ** Determine if the session is empty
10084 if( cli_strcmp(azCmd
[0], "isempty")==0 ){
10086 if( nCmd
!=1 ) goto session_syntax_error
;
10087 if( pAuxDb
->nSession
){
10088 ii
= sqlite3session_isempty(pSession
->p
);
10089 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
10090 pSession
->zName
, ii
);
10095 ** List all currently open sessions
10097 if( cli_strcmp(azCmd
[0],"list")==0 ){
10098 for(i
=0; i
<pAuxDb
->nSession
; i
++){
10099 utf8_printf(p
->out
, "%d %s\n", i
, pAuxDb
->aSession
[i
].zName
);
10103 /* .session open DB NAME
10104 ** Open a new session called NAME on the attached database DB.
10105 ** DB is normally "main".
10107 if( cli_strcmp(azCmd
[0],"open")==0 ){
10109 if( nCmd
!=3 ) goto session_syntax_error
;
10111 if( zName
[0]==0 ) goto session_syntax_error
;
10112 for(i
=0; i
<pAuxDb
->nSession
; i
++){
10113 if( cli_strcmp(pAuxDb
->aSession
[i
].zName
,zName
)==0 ){
10114 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
10115 goto meta_command_exit
;
10118 if( pAuxDb
->nSession
>=ArraySize(pAuxDb
->aSession
) ){
10120 "Maximum of %d sessions\n", ArraySize(pAuxDb
->aSession
));
10121 goto meta_command_exit
;
10123 pSession
= &pAuxDb
->aSession
[pAuxDb
->nSession
];
10124 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
10126 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
10128 goto meta_command_exit
;
10130 pSession
->nFilter
= 0;
10131 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
10132 pAuxDb
->nSession
++;
10133 pSession
->zName
= sqlite3_mprintf("%s", zName
);
10134 shell_check_oom(pSession
->zName
);
10136 /* If no command name matches, show a syntax error */
10137 session_syntax_error
:
10138 showHelp(p
->out
, "session");
10142 #ifdef SQLITE_DEBUG
10143 /* Undocumented commands for internal testing. Subject to change
10144 ** without notice. */
10145 if( c
=='s' && n
>=10 && cli_strncmp(azArg
[0], "selftest-", 9)==0 ){
10146 if( cli_strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
10148 for(i
=1; i
<nArg
; i
++){
10149 v
= booleanValue(azArg
[i
]);
10150 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
10153 if( cli_strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
10154 int i
; sqlite3_int64 v
;
10155 for(i
=1; i
<nArg
; i
++){
10157 v
= integerValue(azArg
[i
]);
10158 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
10159 utf8_printf(p
->out
, "%s", zBuf
);
10165 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"selftest",n
)==0 ){
10166 int bIsInit
= 0; /* True to initialize the SELFTEST table */
10167 int bVerbose
= 0; /* Verbose output */
10168 int bSelftestExists
; /* True if SELFTEST already exists */
10169 int i
, k
; /* Loop counters */
10170 int nTest
= 0; /* Number of tests runs */
10171 int nErr
= 0; /* Number of errors seen */
10172 ShellText str
; /* Answer for a query */
10173 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
10176 for(i
=1; i
<nArg
; i
++){
10177 const char *z
= azArg
[i
];
10178 if( z
[0]=='-' && z
[1]=='-' ) z
++;
10179 if( cli_strcmp(z
,"-init")==0 ){
10182 if( cli_strcmp(z
,"-v")==0 ){
10186 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
10187 azArg
[i
], azArg
[0]);
10188 raw_printf(stderr
, "Should be one of: --init -v\n");
10190 goto meta_command_exit
;
10193 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
10195 bSelftestExists
= 0;
10197 bSelftestExists
= 1;
10200 createSelftestTable(p
);
10201 bSelftestExists
= 1;
10204 appendText(&str
, "x", 0);
10205 for(k
=bSelftestExists
; k
>=0; k
--){
10207 rc
= sqlite3_prepare_v2(p
->db
,
10208 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10211 rc
= sqlite3_prepare_v2(p
->db
,
10212 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10213 " (1,'run','PRAGMA integrity_check','ok')",
10217 raw_printf(stderr
, "Error querying the selftest table\n");
10219 sqlite3_finalize(pStmt
);
10220 goto meta_command_exit
;
10222 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
10223 int tno
= sqlite3_column_int(pStmt
, 0);
10224 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
10225 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
10226 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
10228 if( zOp
==0 ) continue;
10229 if( zSql
==0 ) continue;
10230 if( zAns
==0 ) continue;
10233 printf("%d: %s %s\n", tno
, zOp
, zSql
);
10235 if( cli_strcmp(zOp
,"memo")==0 ){
10236 utf8_printf(p
->out
, "%s\n", zSql
);
10238 if( cli_strcmp(zOp
,"run")==0 ){
10242 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
10245 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
10247 if( rc
|| zErrMsg
){
10250 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
10251 sqlite3_free(zErrMsg
);
10252 }else if( cli_strcmp(zAns
,str
.z
)!=0 ){
10255 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
10256 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
10260 utf8_printf(stderr
,
10261 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
10265 } /* End loop over rows of content from SELFTEST */
10266 sqlite3_finalize(pStmt
);
10267 } /* End loop over k */
10269 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
10272 if( c
=='s' && cli_strncmp(azArg
[0], "separator", n
)==0 ){
10273 if( nArg
<2 || nArg
>3 ){
10274 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
10278 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
10279 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
10282 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
10283 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
10287 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"sha3sum",n
)==0 ){
10288 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
10289 int i
; /* Loop counter */
10290 int bSchema
= 0; /* Also hash the schema */
10291 int bSeparate
= 0; /* Hash each table separately */
10292 int iSize
= 224; /* Hash algorithm to use */
10293 int bDebug
= 0; /* Only show the query that would have run */
10294 sqlite3_stmt
*pStmt
; /* For querying tables names */
10295 char *zSql
; /* SQL to be run */
10296 char *zSep
; /* Separator */
10297 ShellText sSql
; /* Complete SQL for the query to run the hash */
10298 ShellText sQuery
; /* Set of queries used to read all content */
10300 for(i
=1; i
<nArg
; i
++){
10301 const char *z
= azArg
[i
];
10304 if( z
[0]=='-' ) z
++;
10305 if( cli_strcmp(z
,"schema")==0 ){
10308 if( cli_strcmp(z
,"sha3-224")==0 || cli_strcmp(z
,"sha3-256")==0
10309 || cli_strcmp(z
,"sha3-384")==0 || cli_strcmp(z
,"sha3-512")==0
10311 iSize
= atoi(&z
[5]);
10313 if( cli_strcmp(z
,"debug")==0 ){
10317 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
10318 azArg
[i
], azArg
[0]);
10319 showHelp(p
->out
, azArg
[0]);
10321 goto meta_command_exit
;
10324 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10326 goto meta_command_exit
;
10330 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
10334 zSql
= "SELECT lower(name) as tname FROM sqlite_schema"
10335 " WHERE type='table' AND coalesce(rootpage,0)>1"
10336 " UNION ALL SELECT 'sqlite_schema'"
10337 " ORDER BY 1 collate nocase";
10339 zSql
= "SELECT lower(name) as tname FROM sqlite_schema"
10340 " WHERE type='table' AND coalesce(rootpage,0)>1"
10341 " AND name NOT LIKE 'sqlite_%'"
10342 " ORDER BY 1 collate nocase";
10344 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
10347 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
10349 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
10350 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
10351 if( zTab
==0 ) continue;
10352 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
10353 if( cli_strncmp(zTab
, "sqlite_",7)!=0 ){
10354 appendText(&sQuery
,"SELECT * FROM ", 0);
10355 appendText(&sQuery
,zTab
,'"');
10356 appendText(&sQuery
," NOT INDEXED;", 0);
10357 }else if( cli_strcmp(zTab
, "sqlite_schema")==0 ){
10358 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10359 " ORDER BY name;", 0);
10360 }else if( cli_strcmp(zTab
, "sqlite_sequence")==0 ){
10361 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
10362 " ORDER BY name;", 0);
10363 }else if( cli_strcmp(zTab
, "sqlite_stat1")==0 ){
10364 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
10365 " ORDER BY tbl,idx;", 0);
10366 }else if( cli_strcmp(zTab
, "sqlite_stat4")==0 ){
10367 appendText(&sQuery
, "SELECT * FROM ", 0);
10368 appendText(&sQuery
, zTab
, 0);
10369 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
10371 appendText(&sSql
, zSep
, 0);
10372 appendText(&sSql
, sQuery
.z
, '\'');
10374 appendText(&sSql
, ",", 0);
10375 appendText(&sSql
, zTab
, '\'');
10378 sqlite3_finalize(pStmt
);
10380 zSql
= sqlite3_mprintf(
10382 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10383 " FROM [sha3sum$query]",
10386 zSql
= sqlite3_mprintf(
10388 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10389 " FROM [sha3sum$query]",
10392 shell_check_oom(zSql
);
10396 utf8_printf(p
->out
, "%s\n", zSql
);
10398 shell_exec(p
, zSql
, 0);
10400 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10403 char *zRevText
= /* Query for reversible to-blob-to-text check */
10404 "SELECT lower(name) as tname FROM sqlite_schema\n"
10405 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10406 "AND name NOT LIKE 'sqlite_%%'%s\n"
10407 "ORDER BY 1 collate nocase";
10408 zRevText
= sqlite3_mprintf(zRevText
, zLike
? " AND name LIKE $tspec" : "");
10409 zRevText
= sqlite3_mprintf(
10410 /* lower-case query is first run, producing upper-case query. */
10411 "with tabcols as materialized(\n"
10412 "select tname, cname\n"
10414 " select ss.tname as tname, ti.name as cname\n"
10415 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10416 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10417 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10418 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10419 "FROM '||tname||' WHERE '\n"
10420 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10421 "|| ' AND typeof('||cname||')=''text'' ',\n"
10422 "' OR ') as query, tname from tabcols group by tname)"
10424 shell_check_oom(zRevText
);
10425 if( bDebug
) utf8_printf(p
->out
, "%s\n", zRevText
);
10426 lrc
= sqlite3_prepare_v2(p
->db
, zRevText
, -1, &pStmt
, 0);
10427 assert(lrc
==SQLITE_OK
);
10428 if( zLike
) sqlite3_bind_text(pStmt
,1,zLike
,-1,SQLITE_STATIC
);
10429 lrc
= SQLITE_ROW
==sqlite3_step(pStmt
);
10431 const char *zGenQuery
= (char*)sqlite3_column_text(pStmt
,0);
10432 sqlite3_stmt
*pCheckStmt
;
10433 lrc
= sqlite3_prepare_v2(p
->db
, zGenQuery
, -1, &pCheckStmt
, 0);
10434 if( bDebug
) utf8_printf(p
->out
, "%s\n", zGenQuery
);
10435 if( SQLITE_OK
==lrc
){
10436 if( SQLITE_ROW
==sqlite3_step(pCheckStmt
) ){
10437 double countIrreversible
= sqlite3_column_double(pCheckStmt
, 0);
10438 if( countIrreversible
>0 ){
10439 int sz
= (int)(countIrreversible
+ 0.5);
10440 utf8_printf(stderr
,
10441 "Digest includes %d invalidly encoded text field%s.\n",
10442 sz
, (sz
>1)? "s": "");
10445 sqlite3_finalize(pCheckStmt
);
10447 sqlite3_finalize(pStmt
);
10449 sqlite3_free(zRevText
);
10451 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10452 sqlite3_free(zSql
);
10455 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10457 && (cli_strncmp(azArg
[0], "shell", n
)==0
10458 || cli_strncmp(azArg
[0],"system",n
)==0)
10462 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
10464 raw_printf(stderr
, "Usage: .system COMMAND\n");
10466 goto meta_command_exit
;
10468 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
10469 for(i
=2; i
<nArg
&& zCmd
!=0; i
++){
10470 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
10473 x
= zCmd
!=0 ? system(zCmd
) : 1;
10474 sqlite3_free(zCmd
);
10475 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
10477 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10479 if( c
=='s' && cli_strncmp(azArg
[0], "show", n
)==0 ){
10480 static const char *azBool
[] = { "off", "on", "trigger", "full"};
10484 raw_printf(stderr
, "Usage: .show\n");
10486 goto meta_command_exit
;
10488 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
10489 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
10490 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
10491 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
10492 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
10493 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
10494 if( p
->mode
==MODE_Column
10495 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
10498 (p
->out
, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10499 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
10500 p
->cmOpts
.bWordWrap
? "on" : "off",
10501 p
->cmOpts
.bQuote
? "" : "no");
10503 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
10505 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
10506 output_c_string(p
->out
, p
->nullValue
);
10507 raw_printf(p
->out
, "\n");
10508 utf8_printf(p
->out
,"%12.12s: %s\n","output",
10509 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
10510 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
10511 output_c_string(p
->out
, p
->colSeparator
);
10512 raw_printf(p
->out
, "\n");
10513 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
10514 output_c_string(p
->out
, p
->rowSeparator
);
10515 raw_printf(p
->out
, "\n");
10516 switch( p
->statsOn
){
10517 case 0: zOut
= "off"; break;
10518 default: zOut
= "on"; break;
10519 case 2: zOut
= "stmt"; break;
10520 case 3: zOut
= "vmstep"; break;
10522 utf8_printf(p
->out
, "%12.12s: %s\n","stats", zOut
);
10523 utf8_printf(p
->out
, "%12.12s: ", "width");
10524 for (i
=0;i
<p
->nWidth
;i
++) {
10525 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
10527 raw_printf(p
->out
, "\n");
10528 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
10529 p
->pAuxDb
->zDbFilename
? p
->pAuxDb
->zDbFilename
: "");
10532 if( c
=='s' && cli_strncmp(azArg
[0], "stats", n
)==0 ){
10534 if( cli_strcmp(azArg
[1],"stmt")==0 ){
10536 }else if( cli_strcmp(azArg
[1],"vmstep")==0 ){
10539 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
10541 }else if( nArg
==1 ){
10542 display_stats(p
->db
, p
, 0);
10544 raw_printf(stderr
, "Usage: .stats ?on|off|stmt|vmstep?\n");
10549 if( (c
=='t' && n
>1 && cli_strncmp(azArg
[0], "tables", n
)==0)
10550 || (c
=='i' && (cli_strncmp(azArg
[0], "indices", n
)==0
10551 || cli_strncmp(azArg
[0], "indexes", n
)==0) )
10553 sqlite3_stmt
*pStmt
;
10560 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
10562 sqlite3_finalize(pStmt
);
10563 return shellDatabaseError(p
->db
);
10566 if( nArg
>2 && c
=='i' ){
10567 /* It is an historical accident that the .indexes command shows an error
10568 ** when called with the wrong number of arguments whereas the .tables
10569 ** command does not. */
10570 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
10572 sqlite3_finalize(pStmt
);
10573 goto meta_command_exit
;
10575 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
10576 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
10577 if( zDbName
==0 ) continue;
10578 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
10579 if( sqlite3_stricmp(zDbName
, "main")==0 ){
10580 appendText(&s
, "SELECT name FROM ", 0);
10582 appendText(&s
, "SELECT ", 0);
10583 appendText(&s
, zDbName
, '\'');
10584 appendText(&s
, "||'.'||name FROM ", 0);
10586 appendText(&s
, zDbName
, '"');
10587 appendText(&s
, ".sqlite_schema ", 0);
10589 appendText(&s
," WHERE type IN ('table','view')"
10590 " AND name NOT LIKE 'sqlite_%'"
10591 " AND name LIKE ?1", 0);
10593 appendText(&s
," WHERE type='index'"
10594 " AND tbl_name LIKE ?1", 0);
10597 rc
= sqlite3_finalize(pStmt
);
10598 if( rc
==SQLITE_OK
){
10599 appendText(&s
, " ORDER BY 1", 0);
10600 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
10603 if( rc
) return shellDatabaseError(p
->db
);
10605 /* Run the SQL statement prepared by the above block. Store the results
10606 ** as an array of nul-terminated strings in azResult[]. */
10610 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
10612 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
10614 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
10615 if( nRow
>=nAlloc
){
10617 int n2
= nAlloc
*2 + 10;
10618 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
10619 shell_check_oom(azNew
);
10623 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
10624 shell_check_oom(azResult
[nRow
]);
10627 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
10628 rc
= shellDatabaseError(p
->db
);
10631 /* Pretty-print the contents of array azResult[] to the output */
10632 if( rc
==0 && nRow
>0 ){
10633 int len
, maxlen
= 0;
10635 int nPrintCol
, nPrintRow
;
10636 for(i
=0; i
<nRow
; i
++){
10637 len
= strlen30(azResult
[i
]);
10638 if( len
>maxlen
) maxlen
= len
;
10640 nPrintCol
= 80/(maxlen
+2);
10641 if( nPrintCol
<1 ) nPrintCol
= 1;
10642 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
10643 for(i
=0; i
<nPrintRow
; i
++){
10644 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
10645 char *zSp
= j
<nPrintRow
? "" : " ";
10646 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
10647 azResult
[j
] ? azResult
[j
]:"");
10649 raw_printf(p
->out
, "\n");
10653 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
10654 sqlite3_free(azResult
);
10657 #ifndef SQLITE_SHELL_FIDDLE
10658 /* Begin redirecting output to the file "testcase-out.txt" */
10659 if( c
=='t' && cli_strcmp(azArg
[0],"testcase")==0 ){
10661 p
->out
= output_file_open("testcase-out.txt", 0);
10663 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
10666 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
10668 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
10671 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10673 #ifndef SQLITE_UNTESTABLE
10674 if( c
=='t' && n
>=8 && cli_strncmp(azArg
[0], "testctrl", n
)==0 ){
10675 static const struct {
10676 const char *zCtrlName
; /* Name of a test-control option */
10677 int ctrlCode
; /* Integer code for that option */
10678 int unSafe
; /* Not valid for --safe mode */
10679 const char *zUsage
; /* Usage notes */
10681 {"always", SQLITE_TESTCTRL_ALWAYS
, 1, "BOOLEAN" },
10682 {"assert", SQLITE_TESTCTRL_ASSERT
, 1, "BOOLEAN" },
10683 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10684 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10685 {"byteorder", SQLITE_TESTCTRL_BYTEORDER
, 0, "" },
10686 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
,0,"BOOLEAN" },
10687 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10688 {"imposter", SQLITE_TESTCTRL_IMPOSTER
,1,"SCHEMA ON/OFF ROOTPAGE"},
10689 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
,0,"" },
10690 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,0,"BOOLEAN" },
10691 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
,1, "BOOLEAN" },
10692 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
,0,"DISABLE-MASK" },
10694 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
,0,"" },
10696 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
,0, "OFFSET " },
10697 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
,0, "" },
10698 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, 0, "" },
10699 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED
, 0, "SEED ?db?" },
10700 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT
, 0, "" },
10701 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP
, 0, "NMAX" },
10702 {"tune", SQLITE_TESTCTRL_TUNE
, 1, "ID VALUE" },
10706 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10709 const char *zCmd
= 0;
10712 zCmd
= nArg
>=2 ? azArg
[1] : "help";
10714 /* The argument can optionally begin with "-" or "--" */
10715 if( zCmd
[0]=='-' && zCmd
[1] ){
10717 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
10720 /* --help lists all test-controls */
10721 if( cli_strcmp(zCmd
,"help")==0 ){
10722 utf8_printf(p
->out
, "Available test-controls:\n");
10723 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10724 utf8_printf(p
->out
, " .testctrl %s %s\n",
10725 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
10728 goto meta_command_exit
;
10731 /* convert testctrl text option to value. allow any unique prefix
10732 ** of the option name, or a numerical value. */
10733 n2
= strlen30(zCmd
);
10734 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10735 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
10737 testctrl
= aCtrl
[i
].ctrlCode
;
10740 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
10741 "Use \".testctrl --help\" for help\n", zCmd
);
10743 goto meta_command_exit
;
10748 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
10749 "Use \".testctrl --help\" for help\n", zCmd
);
10750 }else if( aCtrl
[iCtrl
].unSafe
&& p
->bSafeMode
){
10751 utf8_printf(stderr
,
10752 "line %d: \".testctrl %s\" may not be used in safe mode\n",
10753 p
->lineno
, aCtrl
[iCtrl
].zCtrlName
);
10758 /* sqlite3_test_control(int, db, int) */
10759 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
10761 unsigned int opt
= (unsigned int)strtol(azArg
[2], 0, 0);
10762 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
10767 /* sqlite3_test_control(int) */
10768 case SQLITE_TESTCTRL_PRNG_SAVE
:
10769 case SQLITE_TESTCTRL_PRNG_RESTORE
:
10770 case SQLITE_TESTCTRL_BYTEORDER
:
10772 rc2
= sqlite3_test_control(testctrl
);
10773 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
10777 /* sqlite3_test_control(int, uint) */
10778 case SQLITE_TESTCTRL_PENDING_BYTE
:
10780 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
10781 rc2
= sqlite3_test_control(testctrl
, opt
);
10786 /* sqlite3_test_control(int, int, sqlite3*) */
10787 case SQLITE_TESTCTRL_PRNG_SEED
:
10788 if( nArg
==3 || nArg
==4 ){
10789 int ii
= (int)integerValue(azArg
[2]);
10791 if( ii
==0 && cli_strcmp(azArg
[2],"random")==0 ){
10792 sqlite3_randomness(sizeof(ii
),&ii
);
10793 printf("-- random seed: %d\n", ii
);
10799 /* Make sure the schema has been loaded */
10800 sqlite3_table_column_metadata(db
, 0, "x", 0, 0, 0, 0, 0, 0);
10802 rc2
= sqlite3_test_control(testctrl
, ii
, db
);
10807 /* sqlite3_test_control(int, int) */
10808 case SQLITE_TESTCTRL_ASSERT
:
10809 case SQLITE_TESTCTRL_ALWAYS
:
10811 int opt
= booleanValue(azArg
[2]);
10812 rc2
= sqlite3_test_control(testctrl
, opt
);
10817 /* sqlite3_test_control(int, int) */
10818 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
10819 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
10821 int opt
= booleanValue(azArg
[2]);
10822 rc2
= sqlite3_test_control(testctrl
, opt
);
10827 /* sqlite3_test_control(sqlite3*) */
10828 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
:
10829 rc2
= sqlite3_test_control(testctrl
, p
->db
);
10833 case SQLITE_TESTCTRL_IMPOSTER
:
10835 rc2
= sqlite3_test_control(testctrl
, p
->db
,
10837 integerValue(azArg
[3]),
10838 integerValue(azArg
[4]));
10843 case SQLITE_TESTCTRL_SEEK_COUNT
: {
10845 rc2
= sqlite3_test_control(testctrl
, p
->db
, &x
);
10846 utf8_printf(p
->out
, "%llu\n", x
);
10852 case SQLITE_TESTCTRL_PARSER_COVERAGE
: {
10854 sqlite3_test_control(testctrl
, p
->out
);
10860 #ifdef SQLITE_DEBUG
10861 case SQLITE_TESTCTRL_TUNE
: {
10863 int id
= (int)integerValue(azArg
[2]);
10864 int val
= (int)integerValue(azArg
[3]);
10865 sqlite3_test_control(testctrl
, id
, &val
);
10867 }else if( nArg
==3 ){
10868 int id
= (int)integerValue(azArg
[2]);
10869 sqlite3_test_control(testctrl
, -id
, &rc2
);
10871 }else if( nArg
==2 ){
10875 rc2
= sqlite3_test_control(testctrl
, -id
, &val
);
10876 if( rc2
!=SQLITE_OK
) break;
10877 if( id
>1 ) utf8_printf(p
->out
, " ");
10878 utf8_printf(p
->out
, "%d: %d", id
, val
);
10881 if( id
>1 ) utf8_printf(p
->out
, "\n");
10887 case SQLITE_TESTCTRL_SORTER_MMAP
:
10889 int opt
= (unsigned int)integerValue(azArg
[2]);
10890 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
10896 if( isOk
==0 && iCtrl
>=0 ){
10897 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
10899 }else if( isOk
==1 ){
10900 raw_printf(p
->out
, "%d\n", rc2
);
10901 }else if( isOk
==2 ){
10902 raw_printf(p
->out
, "0x%08x\n", rc2
);
10905 #endif /* !defined(SQLITE_UNTESTABLE) */
10907 if( c
=='t' && n
>4 && cli_strncmp(azArg
[0], "timeout", n
)==0 ){
10909 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
10912 if( c
=='t' && n
>=5 && cli_strncmp(azArg
[0], "timer", n
)==0 ){
10914 enableTimer
= booleanValue(azArg
[1]);
10915 if( enableTimer
&& !HAS_TIMER
){
10916 raw_printf(stderr
, "Error: timer not available on this system.\n");
10920 raw_printf(stderr
, "Usage: .timer on|off\n");
10925 #ifndef SQLITE_OMIT_TRACE
10926 if( c
=='t' && cli_strncmp(azArg
[0], "trace", n
)==0 ){
10930 for(jj
=1; jj
<nArg
; jj
++){
10931 const char *z
= azArg
[jj
];
10933 if( optionMatch(z
, "expanded") ){
10934 p
->eTraceType
= SHELL_TRACE_EXPANDED
;
10936 #ifdef SQLITE_ENABLE_NORMALIZE
10937 else if( optionMatch(z
, "normalized") ){
10938 p
->eTraceType
= SHELL_TRACE_NORMALIZED
;
10941 else if( optionMatch(z
, "plain") ){
10942 p
->eTraceType
= SHELL_TRACE_PLAIN
;
10944 else if( optionMatch(z
, "profile") ){
10945 mType
|= SQLITE_TRACE_PROFILE
;
10947 else if( optionMatch(z
, "row") ){
10948 mType
|= SQLITE_TRACE_ROW
;
10950 else if( optionMatch(z
, "stmt") ){
10951 mType
|= SQLITE_TRACE_STMT
;
10953 else if( optionMatch(z
, "close") ){
10954 mType
|= SQLITE_TRACE_CLOSE
;
10957 raw_printf(stderr
, "Unknown option \"%s\" on \".trace\"\n", z
);
10959 goto meta_command_exit
;
10962 output_file_close(p
->traceOut
);
10963 p
->traceOut
= output_file_open(z
, 0);
10966 if( p
->traceOut
==0 ){
10967 sqlite3_trace_v2(p
->db
, 0, 0, 0);
10969 if( mType
==0 ) mType
= SQLITE_TRACE_STMT
;
10970 sqlite3_trace_v2(p
->db
, mType
, sql_trace_callback
, p
);
10973 #endif /* !defined(SQLITE_OMIT_TRACE) */
10975 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10976 if( c
=='u' && cli_strncmp(azArg
[0], "unmodule", n
)==0 ){
10981 raw_printf(stderr
, "Usage: .unmodule [--allexcept] NAME ...\n");
10983 goto meta_command_exit
;
10987 if( zOpt
[0]=='-' && zOpt
[1]=='-' && zOpt
[2]!=0 ) zOpt
++;
10988 lenOpt
= (int)strlen(zOpt
);
10989 if( lenOpt
>=3 && cli_strncmp(zOpt
, "-allexcept",lenOpt
)==0 ){
10990 assert( azArg
[nArg
]==0 );
10991 sqlite3_drop_modules(p
->db
, nArg
>2 ? (const char**)(azArg
+2) : 0);
10993 for(ii
=1; ii
<nArg
; ii
++){
10994 sqlite3_create_module(p
->db
, azArg
[ii
], 0, 0);
11000 #if SQLITE_USER_AUTHENTICATION
11001 if( c
=='u' && cli_strncmp(azArg
[0], "user", n
)==0 ){
11003 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
11005 goto meta_command_exit
;
11008 if( cli_strcmp(azArg
[1],"login")==0 ){
11010 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
11012 goto meta_command_exit
;
11014 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
11015 strlen30(azArg
[3]));
11017 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
11020 }else if( cli_strcmp(azArg
[1],"add")==0 ){
11022 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
11024 goto meta_command_exit
;
11026 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
11027 booleanValue(azArg
[4]));
11029 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
11032 }else if( cli_strcmp(azArg
[1],"edit")==0 ){
11034 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
11036 goto meta_command_exit
;
11038 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
11039 booleanValue(azArg
[4]));
11041 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
11044 }else if( cli_strcmp(azArg
[1],"delete")==0 ){
11046 raw_printf(stderr
, "Usage: .user delete USER\n");
11048 goto meta_command_exit
;
11050 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
11052 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
11056 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
11058 goto meta_command_exit
;
11061 #endif /* SQLITE_USER_AUTHENTICATION */
11063 if( c
=='v' && cli_strncmp(azArg
[0], "version", n
)==0 ){
11064 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
11065 sqlite3_libversion(), sqlite3_sourceid());
11066 /* BEGIN SQLCIPHER */
11067 #ifdef SQLITE_HAS_CODEC
11069 extern char* sqlcipher_version();
11070 char *sqlcipher_ver
= sqlcipher_version();
11071 utf8_printf(p
->out
, "SQLCipher %s\n", sqlcipher_ver
);
11072 sqlite3_free(sqlcipher_ver
);
11075 /* END SQLCIPHER */
11076 #if SQLITE_HAVE_ZLIB
11077 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
11079 #define CTIMEOPT_VAL_(opt) #opt
11080 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11081 #if defined(__clang__) && defined(__clang_major__)
11082 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
11083 CTIMEOPT_VAL(__clang_minor__
) "."
11084 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
11085 #elif defined(_MSC_VER)
11086 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
11087 #elif defined(__GNUC__) && defined(__VERSION__)
11088 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
11092 if( c
=='v' && cli_strncmp(azArg
[0], "vfsinfo", n
)==0 ){
11093 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
11094 sqlite3_vfs
*pVfs
= 0;
11096 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
11098 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
11099 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
11100 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
11101 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
11106 if( c
=='v' && cli_strncmp(azArg
[0], "vfslist", n
)==0 ){
11108 sqlite3_vfs
*pCurrent
= 0;
11110 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
11112 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
11113 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
11114 pVfs
==pCurrent
? " <--- CURRENT" : "");
11115 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
11116 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
11117 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
11119 raw_printf(p
->out
, "-----------------------------------\n");
11124 if( c
=='v' && cli_strncmp(azArg
[0], "vfsname", n
)==0 ){
11125 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
11126 char *zVfsName
= 0;
11128 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
11130 utf8_printf(p
->out
, "%s\n", zVfsName
);
11131 sqlite3_free(zVfsName
);
11136 if( c
=='w' && cli_strncmp(azArg
[0], "wheretrace", n
)==0 ){
11137 unsigned int x
= nArg
>=2? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
11138 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &x
);
11141 if( c
=='w' && cli_strncmp(azArg
[0], "width", n
)==0 ){
11143 assert( nArg
<=ArraySize(azArg
) );
11144 p
->nWidth
= nArg
-1;
11145 p
->colWidth
= realloc(p
->colWidth
, (p
->nWidth
+1)*sizeof(int)*2);
11146 if( p
->colWidth
==0 && p
->nWidth
>0 ) shell_out_of_memory();
11147 if( p
->nWidth
) p
->actualWidth
= &p
->colWidth
[p
->nWidth
];
11148 for(j
=1; j
<nArg
; j
++){
11149 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
11154 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
11155 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
11162 if( p
->outCount
==0 ) output_reset(p
);
11164 p
->bSafeMode
= p
->bSafeModePersist
;
11168 /* Line scan result and intermediate states (supporting scan resumption)
11171 # define CHAR_BIT 8
11174 QSS_HasDark
= 1<<CHAR_BIT
, QSS_EndingSemi
= 2<<CHAR_BIT
,
11175 QSS_CharMask
= (1<<CHAR_BIT
)-1, QSS_ScanMask
= 3<<CHAR_BIT
,
11178 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11179 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11180 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11181 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11182 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11185 ** Scan line for classification to guide shell's handling.
11186 ** The scan is resumable for subsequent lines when prior
11187 ** return values are passed as the 2nd argument.
11189 static QuickScanState
quickscan(char *zLine
, QuickScanState qss
,
11190 SCAN_TRACKER_REFTYPE pst
){
11192 char cWait
= (char)qss
; /* intentional narrowing loss */
11195 assert( cWait
==0 );
11196 while( (cin
= *zLine
++)!=0 ){
11203 while((cin
= *++zLine
)!=0 )
11208 qss
|= QSS_EndingSemi
;
11214 CONTINUE_PROMPT_AWAITS(pst
, "/*");
11215 qss
= QSS_SETV(qss
, cWait
);
11221 deliberate_fall_through
;
11222 case '`': case '\'': case '"':
11224 qss
= QSS_HasDark
| cWait
;
11225 CONTINUE_PROMPT_AWAITC(pst
, cin
);
11228 CONTINUE_PAREN_INCR(pst
, 1);
11231 CONTINUE_PAREN_INCR(pst
, -1);
11236 qss
= (qss
& ~QSS_EndingSemi
) | QSS_HasDark
;
11240 while( (cin
= *zLine
++)!=0 ){
11244 if( *zLine
!= '/' )
11248 CONTINUE_PROMPT_AWAITC(pst
, 0);
11249 qss
= QSS_SETV(qss
, 0);
11251 case '`': case '\'': case '"':
11253 /* Swallow doubled end-delimiter.*/
11257 deliberate_fall_through
;
11260 CONTINUE_PROMPT_AWAITC(pst
, 0);
11261 qss
= QSS_SETV(qss
, 0);
11263 default: assert(0);
11272 ** Return TRUE if the line typed in is an SQL command terminator other
11273 ** than a semi-colon. The SQL Server style "go" command is understood
11274 ** as is the Oracle "/".
11276 static int line_is_command_terminator(char *zLine
){
11277 while( IsSpace(zLine
[0]) ){ zLine
++; };
11278 if( zLine
[0]=='/' )
11279 zLine
+= 1; /* Oracle */
11280 else if ( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o' )
11281 zLine
+= 2; /* SQL Server */
11284 return quickscan(zLine
, QSS_Start
, 0)==QSS_Start
;
11288 ** The CLI needs a working sqlite3_complete() to work properly. So error
11289 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11291 #ifdef SQLITE_OMIT_COMPLETE
11292 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11296 ** Return true if zSql is a complete SQL statement. Return false if it
11297 ** ends in the middle of a string literal or C-style comment.
11299 static int line_is_complete(char *zSql
, int nSql
){
11301 if( zSql
==0 ) return 1;
11304 rc
= sqlite3_complete(zSql
);
11310 ** Run a single line of SQL. Return the number of errors.
11312 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
11317 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
11318 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
11320 rc
= shell_exec(p
, zSql
, &zErrMsg
);
11322 if( rc
|| zErrMsg
){
11324 const char *zErrorTail
;
11325 const char *zErrorType
;
11327 zErrorType
= "Error";
11328 zErrorTail
= sqlite3_errmsg(p
->db
);
11329 }else if( cli_strncmp(zErrMsg
, "in prepare, ",12)==0 ){
11330 zErrorType
= "Parse error";
11331 zErrorTail
= &zErrMsg
[12];
11332 }else if( cli_strncmp(zErrMsg
, "stepping, ", 10)==0 ){
11333 zErrorType
= "Runtime error";
11334 zErrorTail
= &zErrMsg
[10];
11336 zErrorType
= "Error";
11337 zErrorTail
= zErrMsg
;
11339 if( in
!=0 || !stdin_is_interactive
){
11340 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
11341 "%s near line %d:", zErrorType
, startline
);
11343 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "%s:", zErrorType
);
11345 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrorTail
);
11346 sqlite3_free(zErrMsg
);
11349 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
11350 char zLineBuf
[2000];
11351 sqlite3_snprintf(sizeof(zLineBuf
), zLineBuf
,
11352 "changes: %lld total_changes: %lld",
11353 sqlite3_changes64(p
->db
), sqlite3_total_changes64(p
->db
));
11354 raw_printf(p
->out
, "%s\n", zLineBuf
);
11359 static void echo_group_input(ShellState
*p
, const char *zDo
){
11360 if( ShellHasFlag(p
, SHFLG_Echo
) ) utf8_printf(p
->out
, "%s\n", zDo
);
11363 #ifdef SQLITE_SHELL_FIDDLE
11365 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11366 ** impl because we need the global shellState and cannot access it from that
11367 ** function without moving lots of code around (creating a larger/messier diff).
11369 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
11370 /* Parse the next line from shellState.wasm.zInput. */
11371 const char *zBegin
= shellState
.wasm
.zPos
;
11372 const char *z
= zBegin
;
11376 UNUSED_PARAMETER(in
);
11377 UNUSED_PARAMETER(isContinuation
);
11381 while(*z
&& isspace(*z
)) ++z
;
11383 for(; *z
&& '\n'!=*z
; ++nZ
, ++z
){}
11384 if(nZ
>0 && '\r'==zBegin
[nZ
-1]){
11387 shellState
.wasm
.zPos
= z
;
11388 zLine
= realloc(zPrior
, nZ
+1);
11389 shell_check_oom(zLine
);
11390 memcpy(zLine
, zBegin
, nZ
);
11394 #endif /* SQLITE_SHELL_FIDDLE */
11397 ** Read input from *in and process it. If *in==0 then input
11398 ** is interactive - the user is typing it it. Otherwise, input
11399 ** is coming from a file or device. A prompt is issued and history
11400 ** is saved only if input is interactive. An interrupt signal will
11401 ** cause this routine to exit immediately, unless input is interactive.
11403 ** Return the number of errors.
11405 static int process_input(ShellState
*p
){
11406 char *zLine
= 0; /* A single input line */
11407 char *zSql
= 0; /* Accumulated SQL text */
11408 i64 nLine
; /* Length of current line */
11409 i64 nSql
= 0; /* Bytes of zSql[] used */
11410 i64 nAlloc
= 0; /* Allocated zSql[] space */
11411 int rc
; /* Error code */
11412 int errCnt
= 0; /* Number of errors seen */
11413 i64 startline
= 0; /* Line number for start of current input */
11414 QuickScanState qss
= QSS_Start
; /* Accumulated line status (so far) */
11416 if( p
->inputNesting
==MAX_INPUT_NESTING
){
11417 /* This will be more informative in a later version. */
11418 utf8_printf(stderr
,"Input nesting limit (%d) reached at line %d."
11419 " Check recursion.\n", MAX_INPUT_NESTING
, p
->lineno
);
11424 CONTINUE_PROMPT_RESET
;
11425 while( errCnt
==0 || !bail_on_error
|| (p
->in
==0 && stdin_is_interactive
) ){
11427 zLine
= one_input_line(p
->in
, zLine
, nSql
>0);
11430 if( p
->in
==0 && stdin_is_interactive
) printf("\n");
11433 if( seenInterrupt
){
11434 if( p
->in
!=0 ) break;
11438 if( QSS_INPLAIN(qss
)
11439 && line_is_command_terminator(zLine
)
11440 && line_is_complete(zSql
, nSql
) ){
11441 memcpy(zLine
,";",2);
11443 qss
= quickscan(zLine
, qss
, CONTINUE_PROMPT_PSTATE
);
11444 if( QSS_PLAINWHITE(qss
) && nSql
==0 ){
11445 /* Just swallow single-line whitespace */
11446 echo_group_input(p
, zLine
);
11450 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
11451 CONTINUE_PROMPT_RESET
;
11452 echo_group_input(p
, zLine
);
11453 if( zLine
[0]=='.' ){
11454 rc
= do_meta_command(zLine
, p
);
11455 if( rc
==2 ){ /* exit requested */
11464 /* No single-line dispositions remain; accumulate line(s). */
11465 nLine
= strlen(zLine
);
11466 if( nSql
+nLine
+2>=nAlloc
){
11467 /* Grow buffer by half-again increments when big. */
11468 nAlloc
= nSql
+(nSql
>>1)+nLine
+100;
11469 zSql
= realloc(zSql
, nAlloc
);
11470 shell_check_oom(zSql
);
11474 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
11475 assert( nAlloc
>0 && zSql
!=0 );
11476 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
11477 startline
= p
->lineno
;
11480 zSql
[nSql
++] = '\n';
11481 memcpy(zSql
+nSql
, zLine
, nLine
+1);
11484 if( nSql
&& QSS_SEMITERM(qss
) && sqlite3_complete(zSql
) ){
11485 echo_group_input(p
, zSql
);
11486 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11487 CONTINUE_PROMPT_RESET
;
11495 p
->bSafeMode
= p
->bSafeModePersist
;
11497 }else if( nSql
&& QSS_PLAINWHITE(qss
) ){
11498 echo_group_input(p
, zSql
);
11504 /* This may be incomplete. Let the SQL parser deal with that. */
11505 echo_group_input(p
, zSql
);
11506 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11507 CONTINUE_PROMPT_RESET
;
11516 ** Return a pathname which is the user's home directory. A
11517 ** 0 return indicates an error of some kind.
11519 static char *find_home_dir(int clearFlag
){
11520 static char *home_dir
= NULL
;
11526 if( home_dir
) return home_dir
;
11528 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11529 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11531 struct passwd
*pwent
;
11532 uid_t uid
= getuid();
11533 if( (pwent
=getpwuid(uid
)) != NULL
) {
11534 home_dir
= pwent
->pw_dir
;
11539 #if defined(_WIN32_WCE)
11540 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11545 #if defined(_WIN32) || defined(WIN32)
11547 home_dir
= getenv("USERPROFILE");
11552 home_dir
= getenv("HOME");
11555 #if defined(_WIN32) || defined(WIN32)
11557 char *zDrive
, *zPath
;
11559 zDrive
= getenv("HOMEDRIVE");
11560 zPath
= getenv("HOMEPATH");
11561 if( zDrive
&& zPath
){
11562 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
11563 home_dir
= malloc( n
);
11564 if( home_dir
==0 ) return 0;
11565 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
11572 #endif /* !_WIN32_WCE */
11575 i64 n
= strlen(home_dir
) + 1;
11576 char *z
= malloc( n
);
11577 if( z
) memcpy(z
, home_dir
, n
);
11585 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11586 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11587 ** the path to it, else return 0. The result is cached for
11588 ** subsequent calls.
11590 static const char *find_xdg_config(void){
11591 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11592 || defined(__RTP__) || defined(_WRS_KERNEL)
11595 static int alreadyTried
= 0;
11596 static char *zConfig
= 0;
11597 const char *zXdgHome
;
11599 if( alreadyTried
!=0 ){
11603 zXdgHome
= getenv("XDG_CONFIG_HOME");
11607 zConfig
= sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome
);
11608 shell_check_oom(zConfig
);
11609 if( access(zConfig
,0)!=0 ){
11610 sqlite3_free(zConfig
);
11618 ** Read input from the file given by sqliterc_override. Or if that
11619 ** parameter is NULL, take input from the first of find_xdg_config()
11620 ** or ~/.sqliterc which is found.
11622 ** Returns the number of errors.
11624 static void process_sqliterc(
11625 ShellState
*p
, /* Configuration data */
11626 const char *sqliterc_override
/* Name of config file. NULL to use default */
11628 char *home_dir
= NULL
;
11629 const char *sqliterc
= sqliterc_override
;
11631 FILE *inSaved
= p
->in
;
11632 int savedLineno
= p
->lineno
;
11634 if( sqliterc
== NULL
){
11635 sqliterc
= find_xdg_config();
11637 if( sqliterc
== NULL
){
11638 home_dir
= find_home_dir(0);
11640 raw_printf(stderr
, "-- warning: cannot find home directory;"
11641 " cannot read ~/.sqliterc\n");
11644 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
11645 shell_check_oom(zBuf
);
11648 p
->in
= fopen(sqliterc
,"rb");
11650 if( stdin_is_interactive
){
11651 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
11653 if( process_input(p
) && bail_on_error
) exit(1);
11655 }else if( sqliterc_override
!=0 ){
11656 utf8_printf(stderr
,"cannot open: \"%s\"\n", sqliterc
);
11657 if( bail_on_error
) exit(1);
11660 p
->lineno
= savedLineno
;
11661 sqlite3_free(zBuf
);
11665 ** Show available command line options
11667 static const char zOptions
[] =
11668 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11669 " -A ARGS... run \".archive ARGS\" and exit\n"
11671 " -append append the database to the end of the file\n"
11672 " -ascii set output mode to 'ascii'\n"
11673 " -bail stop after hitting an error\n"
11674 " -batch force batch I/O\n"
11675 " -box set output mode to 'box'\n"
11676 " -column set output mode to 'column'\n"
11677 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11678 " -csv set output mode to 'csv'\n"
11679 #if !defined(SQLITE_OMIT_DESERIALIZE)
11680 " -deserialize open the database using sqlite3_deserialize()\n"
11682 " -echo print inputs before execution\n"
11683 " -init FILENAME read/process named file\n"
11684 " -[no]header turn headers on or off\n"
11685 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11686 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11688 " -help show this message\n"
11689 " -html set output mode to HTML\n"
11690 " -interactive force interactive I/O\n"
11691 " -json set output mode to 'json'\n"
11692 " -line set output mode to 'line'\n"
11693 " -list set output mode to 'list'\n"
11694 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11695 " -markdown set output mode to 'markdown'\n"
11696 #if !defined(SQLITE_OMIT_DESERIALIZE)
11697 " -maxsize N maximum size for a --deserialize database\n"
11699 " -memtrace trace all memory allocations and deallocations\n"
11700 " -mmap N default mmap size set to N\n"
11701 #ifdef SQLITE_ENABLE_MULTIPLEX
11702 " -multiplex enable the multiplexor VFS\n"
11704 " -newline SEP set output row separator. Default: '\\n'\n"
11705 " -nofollow refuse to open symbolic links to database files\n"
11706 " -nonce STRING set the safe-mode escape nonce\n"
11707 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11708 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11709 " -quote set output mode to 'quote'\n"
11710 " -readonly open the database read-only\n"
11711 " -safe enable safe-mode\n"
11712 " -separator SEP set output column separator. Default: '|'\n"
11713 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11714 " -sorterref SIZE sorter references threshold size\n"
11716 " -stats print memory stats before each finalize\n"
11717 " -table set output mode to 'table'\n"
11718 " -tabs set output mode to 'tabs'\n"
11719 " -version show SQLite version\n"
11720 " -vfs NAME use NAME as the default VFS\n"
11721 #ifdef SQLITE_ENABLE_VFSTRACE
11722 " -vfstrace enable tracing of all VFS calls\n"
11724 #ifdef SQLITE_HAVE_ZLIB
11725 " -zip open the file as a ZIP Archive\n"
11728 static void usage(int showDetail
){
11729 utf8_printf(stderr
,
11730 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11731 "FILENAME is the name of an SQLite database. A new database is created\n"
11732 "if the file does not previously exist.\n", Argv0
);
11734 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
11736 raw_printf(stderr
, "Use the -help option for additional information\n");
11742 ** Internal check: Verify that the SQLite is uninitialized. Print a
11743 ** error message if it is initialized.
11745 static void verify_uninitialized(void){
11746 if( sqlite3_config(-1)==SQLITE_MISUSE
){
11747 utf8_printf(stdout
, "WARNING: attempt to configure SQLite after"
11748 " initialization.\n");
11753 ** Initialize the state information in data
11755 static void main_init(ShellState
*data
) {
11756 memset(data
, 0, sizeof(*data
));
11757 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
11758 data
->autoExplain
= 1;
11759 data
->pAuxDb
= &data
->aAuxDb
[0];
11760 memcpy(data
->colSeparator
,SEP_Column
, 2);
11761 memcpy(data
->rowSeparator
,SEP_Row
, 2);
11762 data
->showHeader
= 0;
11763 data
->shellFlgs
= SHFLG_Lookaside
;
11764 verify_uninitialized();
11765 sqlite3_config(SQLITE_CONFIG_URI
, 1);
11766 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
11767 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
11768 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
11769 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
11773 ** Output text to the console in a font that attracts extra attention.
11776 static void printBold(const char *zText
){
11777 #if !SQLITE_OS_WINRT
11778 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
11779 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
11780 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
11781 SetConsoleTextAttribute(out
,
11782 FOREGROUND_RED
|FOREGROUND_INTENSITY
11785 printf("%s", zText
);
11786 #if !SQLITE_OS_WINRT
11787 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
11791 static void printBold(const char *zText
){
11792 printf("\033[1m%s\033[0m", zText
);
11797 ** Get the argument to an --option. Throw an error and die if no argument
11800 static char *cmdline_option_value(int argc
, char **argv
, int i
){
11802 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
11803 argv
[0], argv
[argc
-1]);
11809 #ifndef SQLITE_SHELL_IS_UTF8
11810 # if (defined(_WIN32) || defined(WIN32)) \
11811 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11812 # define SQLITE_SHELL_IS_UTF8 (0)
11814 # define SQLITE_SHELL_IS_UTF8 (1)
11818 #ifdef SQLITE_SHELL_FIDDLE
11819 # define main fiddle_main
11822 #if SQLITE_SHELL_IS_UTF8
11823 int SQLITE_CDECL
main(int argc
, char **argv
){
11825 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
11828 #ifdef SQLITE_DEBUG
11829 sqlite3_int64 mem_main_enter
= sqlite3_memory_used();
11832 #ifdef SQLITE_SHELL_FIDDLE
11833 # define data shellState
11837 const char *zInitFile
= 0;
11840 int warnInmemoryDb
= 0;
11844 const char *zVfs
= 0; /* Value of -vfs command-line option */
11845 #if !SQLITE_SHELL_IS_UTF8
11846 char **argvToFree
= 0;
11847 int argcToFree
= 0;
11850 setBinaryMode(stdin
, 0);
11851 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
11852 #ifdef SQLITE_SHELL_FIDDLE
11853 stdin_is_interactive
= 0;
11854 stdout_is_console
= 1;
11855 data
.wasm
.zDefaultDbName
= "/fiddle.sqlite3";
11857 stdin_is_interactive
= isatty(0);
11858 stdout_is_console
= isatty(1);
11861 #if !defined(_WIN32_WCE)
11862 if( getenv("SQLITE_DEBUG_BREAK") ){
11863 if( isatty(0) && isatty(2) ){
11865 "attach debugger to process %d and press any key to continue.\n",
11869 #if defined(_WIN32) || defined(WIN32)
11870 #if SQLITE_OS_WINRT
11875 #elif defined(SIGTRAP)
11882 #if USE_SYSTEM_SQLITE+0!=1
11883 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
11884 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
11885 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
11891 /* On Windows, we must translate command-line arguments into UTF-8.
11892 ** The SQLite memory allocator subsystem has to be enabled in order to
11893 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
11894 ** subsequent sqlite3_config() calls will work. So copy all results into
11895 ** memory that does not come from the SQLite memory allocator.
11897 #if !SQLITE_SHELL_IS_UTF8
11898 sqlite3_initialize();
11899 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
11900 shell_check_oom(argvToFree
);
11902 argv
= argvToFree
+ argc
;
11903 for(i
=0; i
<argc
; i
++){
11904 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
11906 shell_check_oom(z
);
11908 argv
[i
] = malloc( n
+1 );
11909 shell_check_oom(argv
[i
]);
11910 memcpy(argv
[i
], z
, n
+1);
11911 argvToFree
[i
] = argv
[i
];
11914 sqlite3_shutdown();
11917 assert( argc
>=1 && argv
&& argv
[0] );
11920 /* Make sure we have a valid signal handler early, before anything
11924 signal(SIGINT
, interrupt_handler
);
11925 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11926 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
11929 #ifdef SQLITE_SHELL_DBNAME_PROC
11931 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11932 ** of a C-function that will provide the name of the database file. Use
11933 ** this compile-time option to embed this shell program in larger
11934 ** applications. */
11935 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11936 SQLITE_SHELL_DBNAME_PROC(&data
.pAuxDb
->zDbFilename
);
11937 warnInmemoryDb
= 0;
11941 /* Do an initial pass through the command-line argument to locate
11942 ** the name of the database file, the name of the initialization file,
11943 ** the size of the alternative malloc heap,
11944 ** and the first command to execute.
11946 verify_uninitialized();
11947 for(i
=1; i
<argc
; i
++){
11951 if( data
.aAuxDb
->zDbFilename
==0 ){
11952 data
.aAuxDb
->zDbFilename
= z
;
11954 /* Excesss arguments are interpreted as SQL (or dot-commands) and
11955 ** mean that nothing is read from stdin */
11958 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
11959 shell_check_oom(azCmd
);
11963 if( z
[1]=='-' ) z
++;
11964 if( cli_strcmp(z
,"-separator")==0
11965 || cli_strcmp(z
,"-nullvalue")==0
11966 || cli_strcmp(z
,"-newline")==0
11967 || cli_strcmp(z
,"-cmd")==0
11969 (void)cmdline_option_value(argc
, argv
, ++i
);
11970 }else if( cli_strcmp(z
,"-init")==0 ){
11971 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
11972 }else if( cli_strcmp(z
,"-batch")==0 ){
11973 /* Need to check for batch mode here to so we can avoid printing
11974 ** informational messages (like from process_sqliterc) before
11975 ** we do the actual processing of arguments later in a second pass.
11977 stdin_is_interactive
= 0;
11978 }else if( cli_strcmp(z
,"-heap")==0 ){
11979 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11981 sqlite3_int64 szHeap
;
11983 zSize
= cmdline_option_value(argc
, argv
, ++i
);
11984 szHeap
= integerValue(zSize
);
11985 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
11986 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
11988 (void)cmdline_option_value(argc
, argv
, ++i
);
11990 }else if( cli_strcmp(z
,"-pagecache")==0 ){
11991 sqlite3_int64 n
, sz
;
11992 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
11993 if( sz
>70000 ) sz
= 70000;
11995 n
= integerValue(cmdline_option_value(argc
,argv
,++i
));
11996 if( sz
>0 && n
>0 && 0xffffffffffffLL
/sz
<n
){
11997 n
= 0xffffffffffffLL
/sz
;
11999 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
12000 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
12001 data
.shellFlgs
|= SHFLG_Pagecache
;
12002 }else if( cli_strcmp(z
,"-lookaside")==0 ){
12004 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12006 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12008 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
12009 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
12010 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
12012 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12014 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
); break;
12015 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD
); break;
12016 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED
); break;
12018 #ifdef SQLITE_ENABLE_VFSTRACE
12019 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
12020 extern int vfstrace_register(
12021 const char *zTraceName
,
12022 const char *zOldVfsName
,
12023 int (*xOut
)(const char*,void*),
12027 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
12029 #ifdef SQLITE_ENABLE_MULTIPLEX
12030 }else if( cli_strcmp(z
,"-multiplex")==0 ){
12031 extern int sqlite3_multiple_initialize(const char*,int);
12032 sqlite3_multiplex_initialize(0, 1);
12034 }else if( cli_strcmp(z
,"-mmap")==0 ){
12035 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12036 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
12037 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12038 }else if( cli_strcmp(z
,"-sorterref")==0 ){
12039 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12040 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
12042 }else if( cli_strcmp(z
,"-vfs")==0 ){
12043 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
12044 #ifdef SQLITE_HAVE_ZLIB
12045 }else if( cli_strcmp(z
,"-zip")==0 ){
12046 data
.openMode
= SHELL_OPEN_ZIPFILE
;
12048 }else if( cli_strcmp(z
,"-append")==0 ){
12049 data
.openMode
= SHELL_OPEN_APPENDVFS
;
12050 #ifndef SQLITE_OMIT_DESERIALIZE
12051 }else if( cli_strcmp(z
,"-deserialize")==0 ){
12052 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
12053 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
12054 data
.szMax
= integerValue(argv
[++i
]);
12056 }else if( cli_strcmp(z
,"-readonly")==0 ){
12057 data
.openMode
= SHELL_OPEN_READONLY
;
12058 }else if( cli_strcmp(z
,"-nofollow")==0 ){
12059 data
.openFlags
= SQLITE_OPEN_NOFOLLOW
;
12060 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12061 }else if( cli_strncmp(z
, "-A",2)==0 ){
12062 /* All remaining command-line arguments are passed to the ".archive"
12063 ** command, so ignore them */
12066 }else if( cli_strcmp(z
, "-memtrace")==0 ){
12067 sqlite3MemTraceActivate(stderr
);
12068 }else if( cli_strcmp(z
,"-bail")==0 ){
12070 }else if( cli_strcmp(z
,"-nonce")==0 ){
12072 data
.zNonce
= strdup(argv
[++i
]);
12073 }else if( cli_strcmp(z
,"-safe")==0 ){
12074 /* no-op - catch this on the second pass */
12077 verify_uninitialized();
12080 #ifdef SQLITE_SHELL_INIT_PROC
12082 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12083 ** of a C-function that will perform initialization actions on SQLite that
12084 ** occur just before or after sqlite3_initialize(). Use this compile-time
12085 ** option to embed this shell program in larger applications. */
12086 extern void SQLITE_SHELL_INIT_PROC(void);
12087 SQLITE_SHELL_INIT_PROC();
12090 /* All the sqlite3_config() calls have now been made. So it is safe
12091 ** to call sqlite3_initialize() and process any command line -vfs option. */
12092 sqlite3_initialize();
12096 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
12098 sqlite3_vfs_register(pVfs
, 1);
12100 utf8_printf(stderr
, "no such VFS: \"%s\"\n", zVfs
);
12105 if( data
.pAuxDb
->zDbFilename
==0 ){
12106 #ifndef SQLITE_OMIT_MEMORYDB
12107 data
.pAuxDb
->zDbFilename
= ":memory:";
12108 warnInmemoryDb
= argc
==1;
12110 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
12115 #ifndef SQLITE_SHELL_FIDDLE
12116 sqlite3_appendvfs_init(0,0,0);
12119 /* Go ahead and open the database file if it already exists. If the
12120 ** file does not exist, delay opening it. This prevents empty database
12121 ** files from being created if a user mistypes the database name argument
12122 ** to the sqlite command-line tool.
12124 if( access(data
.pAuxDb
->zDbFilename
, 0)==0 ){
12128 /* Process the initialization file if there is one. If no -init option
12129 ** is given on the command line, look for a file named ~/.sqliterc and
12130 ** try to process it.
12132 process_sqliterc(&data
,zInitFile
);
12134 /* Make a second pass through the command-line argument and set
12135 ** options. This second pass is delayed until after the initialization
12136 ** file is processed so that the command-line arguments will override
12137 ** settings in the initialization file.
12139 for(i
=1; i
<argc
; i
++){
12141 if( z
[0]!='-' ) continue;
12142 if( z
[1]=='-' ){ z
++; }
12143 if( cli_strcmp(z
,"-init")==0 ){
12145 }else if( cli_strcmp(z
,"-html")==0 ){
12146 data
.mode
= MODE_Html
;
12147 }else if( cli_strcmp(z
,"-list")==0 ){
12148 data
.mode
= MODE_List
;
12149 }else if( cli_strcmp(z
,"-quote")==0 ){
12150 data
.mode
= MODE_Quote
;
12151 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
, SEP_Comma
);
12152 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
, SEP_Row
);
12153 }else if( cli_strcmp(z
,"-line")==0 ){
12154 data
.mode
= MODE_Line
;
12155 }else if( cli_strcmp(z
,"-column")==0 ){
12156 data
.mode
= MODE_Column
;
12157 }else if( cli_strcmp(z
,"-json")==0 ){
12158 data
.mode
= MODE_Json
;
12159 }else if( cli_strcmp(z
,"-markdown")==0 ){
12160 data
.mode
= MODE_Markdown
;
12161 }else if( cli_strcmp(z
,"-table")==0 ){
12162 data
.mode
= MODE_Table
;
12163 }else if( cli_strcmp(z
,"-box")==0 ){
12164 data
.mode
= MODE_Box
;
12165 }else if( cli_strcmp(z
,"-csv")==0 ){
12166 data
.mode
= MODE_Csv
;
12167 memcpy(data
.colSeparator
,",",2);
12168 #ifdef SQLITE_HAVE_ZLIB
12169 }else if( cli_strcmp(z
,"-zip")==0 ){
12170 data
.openMode
= SHELL_OPEN_ZIPFILE
;
12172 }else if( cli_strcmp(z
,"-append")==0 ){
12173 data
.openMode
= SHELL_OPEN_APPENDVFS
;
12174 #ifndef SQLITE_OMIT_DESERIALIZE
12175 }else if( cli_strcmp(z
,"-deserialize")==0 ){
12176 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
12177 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
12178 data
.szMax
= integerValue(argv
[++i
]);
12180 }else if( cli_strcmp(z
,"-readonly")==0 ){
12181 data
.openMode
= SHELL_OPEN_READONLY
;
12182 }else if( cli_strcmp(z
,"-nofollow")==0 ){
12183 data
.openFlags
|= SQLITE_OPEN_NOFOLLOW
;
12184 }else if( cli_strcmp(z
,"-ascii")==0 ){
12185 data
.mode
= MODE_Ascii
;
12186 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,SEP_Unit
);
12187 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,SEP_Record
);
12188 }else if( cli_strcmp(z
,"-tabs")==0 ){
12189 data
.mode
= MODE_List
;
12190 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,SEP_Tab
);
12191 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,SEP_Row
);
12192 }else if( cli_strcmp(z
,"-separator")==0 ){
12193 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
12194 "%s",cmdline_option_value(argc
,argv
,++i
));
12195 }else if( cli_strcmp(z
,"-newline")==0 ){
12196 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
12197 "%s",cmdline_option_value(argc
,argv
,++i
));
12198 }else if( cli_strcmp(z
,"-nullvalue")==0 ){
12199 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
12200 "%s",cmdline_option_value(argc
,argv
,++i
));
12201 }else if( cli_strcmp(z
,"-header")==0 ){
12202 data
.showHeader
= 1;
12203 ShellSetFlag(&data
, SHFLG_HeaderSet
);
12204 }else if( cli_strcmp(z
,"-noheader")==0 ){
12205 data
.showHeader
= 0;
12206 ShellSetFlag(&data
, SHFLG_HeaderSet
);
12207 }else if( cli_strcmp(z
,"-echo")==0 ){
12208 ShellSetFlag(&data
, SHFLG_Echo
);
12209 }else if( cli_strcmp(z
,"-eqp")==0 ){
12210 data
.autoEQP
= AUTOEQP_on
;
12211 }else if( cli_strcmp(z
,"-eqpfull")==0 ){
12212 data
.autoEQP
= AUTOEQP_full
;
12213 }else if( cli_strcmp(z
,"-stats")==0 ){
12215 }else if( cli_strcmp(z
,"-scanstats")==0 ){
12216 data
.scanstatsOn
= 1;
12217 }else if( cli_strcmp(z
,"-backslash")==0 ){
12218 /* Undocumented command-line option: -backslash
12219 ** Causes C-style backslash escapes to be evaluated in SQL statements
12220 ** prior to sending the SQL into SQLite. Useful for injecting
12221 ** crazy bytes in the middle of SQL statements for testing and debugging.
12223 ShellSetFlag(&data
, SHFLG_Backslash
);
12224 }else if( cli_strcmp(z
,"-bail")==0 ){
12225 /* No-op. The bail_on_error flag should already be set. */
12226 }else if( cli_strcmp(z
,"-version")==0 ){
12227 /* BEGIN SQLCIPHER */
12228 #ifdef SQLITE_HAS_CODEC
12229 extern char* sqlcipher_version();
12230 char *sqlcipher_ver
= sqlcipher_version();
12231 printf("%s %s", sqlite3_libversion(), sqlite3_sourceid());
12232 printf(" (SQLCipher %s)\n", sqlcipher_ver
);
12233 sqlite3_free(sqlcipher_ver
);
12235 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12237 /* END SQLCIPHER */
12239 }else if( cli_strcmp(z
,"-interactive")==0 ){
12240 stdin_is_interactive
= 1;
12241 }else if( cli_strcmp(z
,"-batch")==0 ){
12242 stdin_is_interactive
= 0;
12243 }else if( cli_strcmp(z
,"-heap")==0 ){
12245 }else if( cli_strcmp(z
,"-pagecache")==0 ){
12247 }else if( cli_strcmp(z
,"-lookaside")==0 ){
12249 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
12251 }else if( cli_strcmp(z
,"-nonce")==0 ){
12253 }else if( cli_strcmp(z
,"-mmap")==0 ){
12255 }else if( cli_strcmp(z
,"-memtrace")==0 ){
12257 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12258 }else if( cli_strcmp(z
,"-sorterref")==0 ){
12261 }else if( cli_strcmp(z
,"-vfs")==0 ){
12263 #ifdef SQLITE_ENABLE_VFSTRACE
12264 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
12267 #ifdef SQLITE_ENABLE_MULTIPLEX
12268 }else if( cli_strcmp(z
,"-multiplex")==0 ){
12271 }else if( cli_strcmp(z
,"-help")==0 ){
12273 }else if( cli_strcmp(z
,"-cmd")==0 ){
12274 /* Run commands that follow -cmd first and separately from commands
12275 ** that simply appear on the command-line. This seems goofy. It would
12276 ** be better if all commands ran in the order that they appear. But
12277 ** we retain the goofy behavior for historical compatibility. */
12278 if( i
==argc
-1 ) break;
12279 z
= cmdline_option_value(argc
,argv
,++i
);
12281 rc
= do_meta_command(z
, &data
);
12282 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
12285 rc
= shell_exec(&data
, z
, &zErrMsg
);
12287 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
12288 if( bail_on_error
) return rc
!=0 ? rc
: 1;
12290 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
12291 if( bail_on_error
) return rc
;
12294 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12295 }else if( cli_strncmp(z
, "-A", 2)==0 ){
12297 utf8_printf(stderr
, "Error: cannot mix regular SQL or dot-commands"
12298 " with \"%s\"\n", z
);
12301 open_db(&data
, OPEN_DB_ZIPFILE
);
12304 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
12306 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
12311 }else if( cli_strcmp(z
,"-safe")==0 ){
12312 data
.bSafeMode
= data
.bSafeModePersist
= 1;
12314 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
12315 raw_printf(stderr
,"Use -help for a list of options.\n");
12318 data
.cMode
= data
.mode
;
12322 /* Run all arguments that do not begin with '-' as if they were separate
12323 ** command-line inputs, except for the argToSkip argument which contains
12324 ** the database filename.
12326 for(i
=0; i
<nCmd
; i
++){
12327 if( azCmd
[i
][0]=='.' ){
12328 rc
= do_meta_command(azCmd
[i
], &data
);
12331 return rc
==2 ? 0 : rc
;
12335 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
12336 if( zErrMsg
|| rc
){
12338 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
12340 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
12342 sqlite3_free(zErrMsg
);
12344 return rc
!=0 ? rc
: 1;
12349 /* Run commands received from standard input
12351 if( stdin_is_interactive
){
12355 /* BEGIN SQLCIPHER */
12356 #ifdef SQLITE_HAS_CODEC
12357 extern char* sqlcipher_version();
12358 char *sqlcipher_ver
= sqlcipher_version();
12360 "SQLite version %s %.19s" /*extra-version-info*/
12361 " (SQLCipher %s)\n" /*sqlcipher version info*/
12362 "Enter \".help\" for usage hints.\n",
12363 sqlite3_libversion(), sqlite3_sourceid(), sqlcipher_ver
12365 sqlite3_free(sqlcipher_ver
);
12368 "SQLite version %s %.19s\n" /*extra-version-info*/
12369 "Enter \".help\" for usage hints.\n",
12370 sqlite3_libversion(), sqlite3_sourceid()
12373 /* END SQLCIPHER */
12374 if( warnInmemoryDb
){
12375 printf("Connected to a ");
12376 printBold("transient in-memory database");
12377 printf(".\nUse \".open FILENAME\" to reopen on a "
12378 "persistent database.\n");
12380 zHistory
= getenv("SQLITE_HISTORY");
12382 zHistory
= strdup(zHistory
);
12383 }else if( (zHome
= find_home_dir(0))!=0 ){
12384 nHistory
= strlen30(zHome
) + 20;
12385 if( (zHistory
= malloc(nHistory
))!=0 ){
12386 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
12389 if( zHistory
){ shell_read_history(zHistory
); }
12390 #if HAVE_READLINE || HAVE_EDITLINE
12391 rl_attempted_completion_function
= readline_completion
;
12392 #elif HAVE_LINENOISE
12393 linenoiseSetCompletionCallback(linenoise_completion
);
12396 rc
= process_input(&data
);
12398 shell_stifle_history(2000);
12399 shell_write_history(zHistory
);
12404 rc
= process_input(&data
);
12407 #ifndef SQLITE_SHELL_FIDDLE
12408 /* In WASM mode we have to leave the db state in place so that
12409 ** client code can "push" SQL into it after this call returns. */
12411 set_table_name(&data
, 0);
12413 session_close_all(&data
, -1);
12416 for(i
=0; i
<ArraySize(data
.aAuxDb
); i
++){
12417 sqlite3_free(data
.aAuxDb
[i
].zFreeOnClose
);
12418 if( data
.aAuxDb
[i
].db
){
12419 session_close_all(&data
, i
);
12420 close_db(data
.aAuxDb
[i
].db
);
12424 output_reset(&data
);
12425 data
.doXdgOpen
= 0;
12426 clearTempFile(&data
);
12427 #if !SQLITE_SHELL_IS_UTF8
12428 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
12431 free(data
.colWidth
);
12433 /* Clear the global data structure so that valgrind will detect memory
12435 memset(&data
, 0, sizeof(data
));
12436 #ifdef SQLITE_DEBUG
12437 if( sqlite3_memory_used()>mem_main_enter
){
12438 utf8_printf(stderr
, "Memory leaked: %u bytes\n",
12439 (unsigned int)(sqlite3_memory_used()-mem_main_enter
));
12442 #endif /* !SQLITE_SHELL_FIDDLE */
12447 #ifdef SQLITE_SHELL_FIDDLE
12448 /* Only for emcc experimentation purposes. */
12449 int fiddle_experiment(int a
,int b
){
12454 ** Returns a pointer to the current DB handle.
12456 sqlite3
* fiddle_db_handle(){
12461 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12462 ** "main" is assumed. Returns 0 if no db with the given name is
12465 sqlite3_vfs
* fiddle_db_vfs(const char *zDbName
){
12466 sqlite3_vfs
* pVfs
= 0;
12468 sqlite3_file_control(globalDb
, zDbName
? zDbName
: "main",
12469 SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
12474 /* Only for emcc experimentation purposes. */
12475 sqlite3
* fiddle_db_arg(sqlite3
*arg
){
12476 printf("fiddle_db_arg(%p)\n", (const void*)arg
);
12481 ** Intended to be called via a SharedWorker() while a separate
12482 ** SharedWorker() (which manages the wasm module) is performing work
12483 ** which should be interrupted. Unfortunately, SharedWorker is not
12484 ** portable enough to make real use of.
12486 void fiddle_interrupt(void){
12487 if( globalDb
) sqlite3_interrupt(globalDb
);
12491 ** Returns the filename of the given db name, assuming "main" if
12492 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12494 const char * fiddle_db_filename(const char * zDbName
){
12496 ? sqlite3_db_filename(globalDb
, zDbName
? zDbName
: "main")
12501 ** Completely wipes out the contents of the currently-opened database
12502 ** but leaves its storage intact for reuse.
12504 void fiddle_reset_db(void){
12506 int rc
= sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 1, 0);
12507 if( 0==rc
) rc
= sqlite3_exec(globalDb
, "VACUUM", 0, 0, 0);
12508 sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 0, 0);
12513 ** Uses the current database's VFS xRead to stream the db file's
12514 ** contents out to the given callback. The callback gets a single
12515 ** chunk of size n (its 2nd argument) on each call and must return 0
12516 ** on success, non-0 on error. This function returns 0 on success,
12517 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12518 ** code from the callback. Note that this is not thread-friendly: it
12519 ** expects that it will be the only thread reading the db file and
12520 ** takes no measures to ensure that is the case.
12522 int fiddle_export_db( int (*xCallback
)(unsigned const char *zOut
, int n
) ){
12523 sqlite3_int64 nSize
= 0;
12524 sqlite3_int64 nPos
= 0;
12525 sqlite3_file
* pFile
= 0;
12526 unsigned char buf
[1024 * 8];
12527 int nBuf
= (int)sizeof(buf
);
12528 int rc
= shellState
.db
12529 ? sqlite3_file_control(shellState
.db
, "main",
12530 SQLITE_FCNTL_FILE_POINTER
, &pFile
)
12532 if( rc
) return rc
;
12533 rc
= pFile
->pMethods
->xFileSize(pFile
, &nSize
);
12534 if( rc
) return rc
;
12536 /* DB size is not an even multiple of the buffer size. Reduce
12537 ** buffer size so that we do not unduly inflate the db size when
12539 if(0 == nSize
% 4096) nBuf
= 4096;
12540 else if(0 == nSize
% 2048) nBuf
= 2048;
12541 else if(0 == nSize
% 1024) nBuf
= 1024;
12544 for( ; 0==rc
&& nPos
<nSize
; nPos
+= nBuf
){
12545 rc
= pFile
->pMethods
->xRead(pFile
, buf
, nBuf
, nPos
);
12546 if(SQLITE_IOERR_SHORT_READ
== rc
){
12547 rc
= (nPos
+ nBuf
) < nSize
? rc
: 0/*assume EOF*/;
12549 if( 0==rc
) rc
= xCallback(buf
, nBuf
);
12555 ** Trivial exportable function for emscripten. It processes zSql as if
12556 ** it were input to the sqlite3 shell and redirects all output to the
12557 ** wasm binding. fiddle_main() must have been called before this
12558 ** is called, or results are undefined.
12560 void fiddle_exec(const char * zSql
){
12562 if('.'==*zSql
) puts(zSql
);
12563 shellState
.wasm
.zInput
= zSql
;
12564 shellState
.wasm
.zPos
= zSql
;
12565 process_input(&shellState
);
12566 shellState
.wasm
.zInput
= shellState
.wasm
.zPos
= 0;
12569 #endif /* SQLITE_SHELL_FIDDLE */