4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code to implement the "sqlite" command line
13 ** utility for accessing SQLite databases.
15 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16 /* This needs to come before any includes for MSVC compiler */
17 #define _CRT_SECURE_NO_WARNINGS
19 typedef unsigned int u32
;
20 typedef unsigned short int u16
;
23 ** Optionally #include a user-defined header, whereby compilation options
24 ** may be set prior to where they take effect, but after platform setup.
25 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
26 ** file. Note that this macro has a like effect on sqlite3.c compilation.
28 # define SHELL_STRINGIFY_(f) #f
29 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
30 #ifdef SQLITE_CUSTOM_INCLUDE
31 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
35 ** Determine if we are dealing with WinRT, which provides only a subset of
36 ** the full Win32 API.
38 #if !defined(SQLITE_OS_WINRT)
39 # define SQLITE_OS_WINRT 0
43 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
44 ** somewhat for use as a WASM module in a web browser. This flag
45 ** should only be used when building the "fiddle" web application, as
46 ** the browser-mode build has much different user input requirements
47 ** and this build mode rewires the user input subsystem to account for
52 ** Warning pragmas copied from msvc.h in the core.
55 #pragma warning(disable : 4054)
56 #pragma warning(disable : 4055)
57 #pragma warning(disable : 4100)
58 #pragma warning(disable : 4127)
59 #pragma warning(disable : 4130)
60 #pragma warning(disable : 4152)
61 #pragma warning(disable : 4189)
62 #pragma warning(disable : 4206)
63 #pragma warning(disable : 4210)
64 #pragma warning(disable : 4232)
65 #pragma warning(disable : 4244)
66 #pragma warning(disable : 4305)
67 #pragma warning(disable : 4306)
68 #pragma warning(disable : 4702)
69 #pragma warning(disable : 4706)
70 #endif /* defined(_MSC_VER) */
73 ** No support for loadable extensions in VxWorks.
75 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
76 # define SQLITE_OMIT_LOAD_EXTENSION 1
80 ** Enable large-file support for fopen() and friends on unix.
82 #ifndef SQLITE_DISABLE_LFS
83 # define _LARGE_FILE 1
84 # ifndef _FILE_OFFSET_BITS
85 # define _FILE_OFFSET_BITS 64
87 # define _LARGEFILE_SOURCE 1
90 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
92 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
93 ** to expose strdup().
95 # define _POSIX_SOURCE
104 typedef sqlite3_int64 i64
;
105 typedef sqlite3_uint64 u64
;
106 typedef unsigned char u8
;
107 #if SQLITE_USER_AUTHENTICATION
108 # include "sqlite3userauth.h"
113 #if !defined(_WIN32) && !defined(WIN32)
115 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
119 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
122 # define GETPID getpid
123 # if defined(__MINGW32__)
124 # define DIRENT dirent
126 # define S_ISLNK(mode) (0)
130 # define GETPID (int)GetCurrentProcessId
132 #include <sys/types.h>
133 #include <sys/stat.h>
136 # include <readline/readline.h>
137 # include <readline/history.h>
141 # include <editline/readline.h>
144 #if HAVE_EDITLINE || HAVE_READLINE
146 # define shell_add_history(X) add_history(X)
147 # define shell_read_history(X) read_history(X)
148 # define shell_write_history(X) write_history(X)
149 # define shell_stifle_history(X) stifle_history(X)
150 # define shell_readline(X) readline(X)
154 # include "linenoise.h"
155 # define shell_add_history(X) linenoiseHistoryAdd(X)
156 # define shell_read_history(X) linenoiseHistoryLoad(X)
157 # define shell_write_history(X) linenoiseHistorySave(X)
158 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
159 # define shell_readline(X) linenoise(X)
163 # define shell_read_history(X)
164 # define shell_write_history(X)
165 # define shell_stifle_history(X)
167 # define SHELL_USE_LOCAL_GETLINE 1
170 #ifndef deliberate_fall_through
171 /* Quiet some compilers about some of our intentional code. */
172 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
173 # define deliberate_fall_through __attribute__((fallthrough));
175 # define deliberate_fall_through
179 #if defined(_WIN32) || defined(WIN32)
181 # define SQLITE_OMIT_POPEN 1
185 # define isatty(h) _isatty(h)
187 # define access(f,m) _access((f),(m))
190 # define unlink _unlink
193 # define strdup _strdup
196 # define popen _popen
198 # define pclose _pclose
201 /* Make sure isatty() has a prototype. */
202 extern int isatty(int);
204 # if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
205 /* popen and pclose are not C89 functions and so are
206 ** sometimes omitted from the <stdio.h> header */
207 extern FILE *popen(const char*,const char*);
208 extern int pclose(FILE*);
210 # define SQLITE_OMIT_POPEN 1
214 #if defined(_WIN32_WCE)
215 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
216 * thus we always assume that we have a console. That can be
217 * overridden with the -batch command line option.
222 /* ctype macros that work with signed characters */
223 #define IsSpace(X) isspace((unsigned char)X)
224 #define IsDigit(X) isdigit((unsigned char)X)
225 #define ToLower(X) (char)tolower((unsigned char)X)
227 #if defined(_WIN32) || defined(WIN32)
231 #define WIN32_LEAN_AND_MEAN
234 /* string conversion routines only needed on Win32 */
235 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
236 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
237 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
238 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
241 /* On Windows, we normally run with output mode of TEXT so that \n characters
242 ** are automatically translated into \r\n. However, this behavior needs
243 ** to be disabled in some cases (ex: when generating CSV output and when
244 ** rendering quoted strings that contain \n characters). The following
245 ** routines take care of that.
247 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
248 static void setBinaryMode(FILE *file
, int isOutput
){
249 if( isOutput
) fflush(file
);
250 _setmode(_fileno(file
), _O_BINARY
);
252 static void setTextMode(FILE *file
, int isOutput
){
253 if( isOutput
) fflush(file
);
254 _setmode(_fileno(file
), _O_TEXT
);
257 # define setBinaryMode(X,Y)
258 # define setTextMode(X,Y)
261 /* True if the timer is enabled */
262 static int enableTimer
= 0;
264 /* A version of strcmp() that works with NULL values */
265 static int cli_strcmp(const char *a
, const char *b
){
270 static int cli_strncmp(const char *a
, const char *b
, size_t n
){
273 return strncmp(a
,b
,n
);
276 /* Return the current wall-clock time */
277 static sqlite3_int64
timeOfDay(void){
278 static sqlite3_vfs
*clockVfs
= 0;
280 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
281 if( clockVfs
==0 ) return 0; /* Never actually happens */
282 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
283 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
286 clockVfs
->xCurrentTime(clockVfs
, &r
);
287 t
= (sqlite3_int64
)(r
*86400000.0);
292 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
293 #include <sys/time.h>
294 #include <sys/resource.h>
296 /* VxWorks does not support getrusage() as far as we can determine */
297 #if defined(_WRS_KERNEL) || defined(__RTP__)
299 struct timeval ru_utime
; /* user CPU time used */
300 struct timeval ru_stime
; /* system CPU time used */
302 #define getrusage(A,B) memset(B,0,sizeof(*B))
305 /* Saved resource information for the beginning of an operation */
306 static struct rusage sBegin
; /* CPU time at start */
307 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
310 ** Begin timing an operation
312 static void beginTimer(void){
314 getrusage(RUSAGE_SELF
, &sBegin
);
315 iBegin
= timeOfDay();
319 /* Return the difference of two time_structs in seconds */
320 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
321 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
322 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
326 ** Print the timing results.
328 static void endTimer(void){
330 sqlite3_int64 iEnd
= timeOfDay();
332 getrusage(RUSAGE_SELF
, &sEnd
);
333 printf("Run Time: real %.3f user %f sys %f\n",
334 (iEnd
- iBegin
)*0.001,
335 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
336 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
340 #define BEGIN_TIMER beginTimer()
341 #define END_TIMER endTimer()
344 #elif (defined(_WIN32) || defined(WIN32))
346 /* Saved resource information for the beginning of an operation */
347 static HANDLE hProcess
;
348 static FILETIME ftKernelBegin
;
349 static FILETIME ftUserBegin
;
350 static sqlite3_int64 ftWallBegin
;
351 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
352 LPFILETIME
, LPFILETIME
);
353 static GETPROCTIMES getProcessTimesAddr
= NULL
;
356 ** Check to see if we have timer support. Return 1 if necessary
357 ** support found (or found previously).
359 static int hasTimer(void){
360 if( getProcessTimesAddr
){
364 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
365 ** versions. See if the version we are running on has it, and if it
366 ** does, save off a pointer to it and the current process handle.
368 hProcess
= GetCurrentProcess();
370 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
371 if( NULL
!= hinstLib
){
372 getProcessTimesAddr
=
373 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
374 if( NULL
!= getProcessTimesAddr
){
377 FreeLibrary(hinstLib
);
386 ** Begin timing an operation
388 static void beginTimer(void){
389 if( enableTimer
&& getProcessTimesAddr
){
390 FILETIME ftCreation
, ftExit
;
391 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
392 &ftKernelBegin
,&ftUserBegin
);
393 ftWallBegin
= timeOfDay();
397 /* Return the difference of two FILETIME structs in seconds */
398 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
399 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
400 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
401 return (double) ((i64End
- i64Start
) / 10000000.0);
405 ** Print the timing results.
407 static void endTimer(void){
408 if( enableTimer
&& getProcessTimesAddr
){
409 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
410 sqlite3_int64 ftWallEnd
= timeOfDay();
411 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
412 printf("Run Time: real %.3f user %f sys %f\n",
413 (ftWallEnd
- ftWallBegin
)*0.001,
414 timeDiff(&ftUserBegin
, &ftUserEnd
),
415 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
419 #define BEGIN_TIMER beginTimer()
420 #define END_TIMER endTimer()
421 #define HAS_TIMER hasTimer()
430 ** Used to prevent warnings about unused parameters
432 #define UNUSED_PARAMETER(x) (void)(x)
435 ** Number of elements in an array
437 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
440 ** If the following flag is set, then command execution stops
441 ** at an error if we are not interactive.
443 static int bail_on_error
= 0;
446 ** Treat stdin as an interactive input if the following variable
447 ** is true. Otherwise, assume stdin is connected to a file or pipe.
449 static int stdin_is_interactive
= 1;
451 #if (defined(_WIN32) || defined(WIN32)) && SHELL_USE_LOCAL_GETLINE \
452 && !defined(SHELL_OMIT_WIN_UTF8)
453 # define SHELL_WIN_UTF8_OPT 1
455 # define SHELL_WIN_UTF8_OPT 0
458 #if SHELL_WIN_UTF8_OPT
460 ** Setup console for UTF-8 input/output when following variable true.
462 static int console_utf8
= 0;
466 ** On Windows systems we have to know if standard output is a console
467 ** in order to translate UTF-8 into MBCS. The following variable is
468 ** true if translation is required.
470 static int stdout_is_console
= 1;
473 ** The following is the open SQLite database. We make a pointer
474 ** to this database a static variable so that it can be accessed
475 ** by the SIGINT handler to interrupt database processing.
477 static sqlite3
*globalDb
= 0;
480 ** True if an interrupt (Control-C) has been received.
482 static volatile int seenInterrupt
= 0;
485 ** This is the name of our program. It is set in main(), used
486 ** in a number of other places, mostly for error messages.
491 ** Prompt strings. Initialized in main. Settable with
492 ** .prompt main continue
494 #define PROMPT_LEN_MAX 20
495 /* First line prompt. default: "sqlite> " */
496 static char mainPrompt
[PROMPT_LEN_MAX
];
497 /* Continuation prompt. default: " ...> " */
498 static char continuePrompt
[PROMPT_LEN_MAX
];
500 /* This is variant of the standard-library strncpy() routine with the
501 ** one change that the destination string is always zero-terminated, even
502 ** if there is no zero-terminator in the first n-1 characters of the source
505 static char *shell_strncpy(char *dest
, const char *src
, size_t n
){
507 for(i
=0; i
<n
-1 && src
[i
]!=0; i
++) dest
[i
] = src
[i
];
513 ** Optionally disable dynamic continuation prompt.
514 ** Unless disabled, the continuation prompt shows open SQL lexemes if any,
515 ** or open parentheses level if non-zero, or continuation prompt as set.
516 ** This facility interacts with the scanner and process_input() where the
517 ** below 5 macros are used.
519 #ifdef SQLITE_OMIT_DYNAPROMPT
520 # define CONTINUATION_PROMPT continuePrompt
521 # define CONTINUE_PROMPT_RESET
522 # define CONTINUE_PROMPT_AWAITS(p,s)
523 # define CONTINUE_PROMPT_AWAITC(p,c)
524 # define CONTINUE_PAREN_INCR(p,n)
525 # define CONTINUE_PROMPT_PSTATE 0
526 typedef void *t_NoDynaPrompt
;
527 # define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
529 # define CONTINUATION_PROMPT dynamicContinuePrompt()
530 # define CONTINUE_PROMPT_RESET \
531 do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
532 # define CONTINUE_PROMPT_AWAITS(p,s) \
533 if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
534 # define CONTINUE_PROMPT_AWAITC(p,c) \
535 if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
536 # define CONTINUE_PAREN_INCR(p,n) \
537 if(p && stdin_is_interactive) (trackParenLevel(p,n))
538 # define CONTINUE_PROMPT_PSTATE (&dynPrompt)
539 typedef struct DynaPrompt
*t_DynaPromptRef
;
540 # define SCAN_TRACKER_REFTYPE t_DynaPromptRef
542 static struct DynaPrompt
{
543 char dynamicPrompt
[PROMPT_LEN_MAX
];
546 char *zScannerAwaits
;
547 } dynPrompt
= { {0}, {0}, 0, 0 };
549 /* Record parenthesis nesting level change, or force level to 0. */
550 static void trackParenLevel(struct DynaPrompt
*p
, int ni
){
551 p
->inParenLevel
+= ni
;
552 if( ni
==0 ) p
->inParenLevel
= 0;
553 p
->zScannerAwaits
= 0;
556 /* Record that a lexeme is opened, or closed with args==0. */
557 static void setLexemeOpen(struct DynaPrompt
*p
, char *s
, char c
){
559 p
->zScannerAwaits
= s
;
563 p
->zScannerAwaits
= p
->acAwait
;
567 /* Upon demand, derive the continuation prompt to display. */
568 static char *dynamicContinuePrompt(void){
569 if( continuePrompt
[0]==0
570 || (dynPrompt
.zScannerAwaits
==0 && dynPrompt
.inParenLevel
== 0) ){
571 return continuePrompt
;
573 if( dynPrompt
.zScannerAwaits
){
574 size_t ncp
= strlen(continuePrompt
);
575 size_t ndp
= strlen(dynPrompt
.zScannerAwaits
);
576 if( ndp
> ncp
-3 ) return continuePrompt
;
577 strcpy(dynPrompt
.dynamicPrompt
, dynPrompt
.zScannerAwaits
);
578 while( ndp
<3 ) dynPrompt
.dynamicPrompt
[ndp
++] = ' ';
579 shell_strncpy(dynPrompt
.dynamicPrompt
+3, continuePrompt
+3,
582 if( dynPrompt
.inParenLevel
>9 ){
583 shell_strncpy(dynPrompt
.dynamicPrompt
, "(..", 4);
584 }else if( dynPrompt
.inParenLevel
<0 ){
585 shell_strncpy(dynPrompt
.dynamicPrompt
, ")x!", 4);
587 shell_strncpy(dynPrompt
.dynamicPrompt
, "(x.", 4);
588 dynPrompt
.dynamicPrompt
[2] = (char)('0'+dynPrompt
.inParenLevel
);
590 shell_strncpy(dynPrompt
.dynamicPrompt
+3, continuePrompt
+3, PROMPT_LEN_MAX
-4);
593 return dynPrompt
.dynamicPrompt
;
595 #endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
597 #if SHELL_WIN_UTF8_OPT
598 /* Following struct is used for -utf8 operation. */
599 static struct ConsoleState
{
600 int stdinEof
; /* EOF has been seen on console input */
601 int infsMode
; /* Input file stream mode upon shell start */
602 UINT inCodePage
; /* Input code page upon shell start */
603 UINT outCodePage
; /* Output code page upon shell start */
604 HANDLE hConsoleIn
; /* Console input handle */
605 DWORD consoleMode
; /* Console mode upon shell start */
606 } conState
= { 0, 0, 0, 0, INVALID_HANDLE_VALUE
, 0 };
608 #ifndef _O_U16TEXT /* For build environments lacking this constant: */
609 # define _O_U16TEXT 0x20000
613 ** Prepare console, (if known to be a WIN32 console), for UTF-8
614 ** input (from either typing or suitable paste operations) and for
615 ** UTF-8 rendering. This may "fail" with a message to stderr, where
616 ** the preparation is not done and common "code page" issues occur.
618 static void console_prepare(void){
619 HANDLE hCI
= GetStdHandle(STD_INPUT_HANDLE
);
620 DWORD consoleMode
= 0;
621 if( isatty(0) && GetFileType(hCI
)==FILE_TYPE_CHAR
622 && GetConsoleMode( hCI
, &consoleMode
) ){
623 if( !IsValidCodePage(CP_UTF8
) ){
624 fprintf(stderr
, "Cannot use UTF-8 code page.\n");
628 conState
.hConsoleIn
= hCI
;
629 conState
.consoleMode
= consoleMode
;
630 conState
.inCodePage
= GetConsoleCP();
631 conState
.outCodePage
= GetConsoleOutputCP();
632 SetConsoleCP(CP_UTF8
);
633 SetConsoleOutputCP(CP_UTF8
);
634 consoleMode
|= ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
;
635 SetConsoleMode(conState
.hConsoleIn
, consoleMode
);
636 conState
.infsMode
= _setmode(_fileno(stdin
), _O_U16TEXT
);
644 ** Undo the effects of console_prepare(), if any.
646 static void SQLITE_CDECL
console_restore(void){
647 if( console_utf8
&& conState
.inCodePage
!=0
648 && conState
.hConsoleIn
!=INVALID_HANDLE_VALUE
){
649 _setmode(_fileno(stdin
), conState
.infsMode
);
650 SetConsoleCP(conState
.inCodePage
);
651 SetConsoleOutputCP(conState
.outCodePage
);
652 SetConsoleMode(conState
.hConsoleIn
, conState
.consoleMode
);
653 /* Avoid multiple calls. */
654 conState
.hConsoleIn
= INVALID_HANDLE_VALUE
;
655 conState
.consoleMode
= 0;
661 ** Collect input like fgets(...) with special provisions for input
662 ** from the Windows console to get around its strange coding issues.
663 ** Defers to plain fgets() when input is not interactive or when the
664 ** startup option, -utf8, has not been provided or taken effect.
666 static char* utf8_fgets(char *buf
, int ncmax
, FILE *fin
){
667 if( fin
==0 ) fin
= stdin
;
668 if( fin
==stdin
&& stdin_is_interactive
&& console_utf8
){
669 # define SQLITE_IALIM 150
670 wchar_t wbuf
[SQLITE_IALIM
];
673 if( ncmax
==0 || conState
.stdinEof
) return 0;
675 while( noc
<ncmax
-7-1 && !lend
){
676 /* There is room for at least 2 more characters and a 0-terminator. */
677 int na
= (ncmax
> SQLITE_IALIM
*4+1 + noc
)
678 ? SQLITE_IALIM
: (ncmax
-1 - noc
)/4;
681 BOOL bRC
= ReadConsoleW(conState
.hConsoleIn
, wbuf
, na
, &nbr
, 0);
682 if( !bRC
|| (noc
==0 && nbr
==0) ) return 0;
684 int nmb
= WideCharToMultiByte(CP_UTF8
,WC_COMPOSITECHECK
|WC_DEFAULTCHAR
,
686 if( nmb
!=0 && noc
+nmb
<= ncmax
){
688 nmb
= WideCharToMultiByte(CP_UTF8
,WC_COMPOSITECHECK
|WC_DEFAULTCHAR
,
689 wbuf
,nbr
,buf
+noc
,nmb
,0,0);
691 /* Fixup line-ends as coded by Windows for CR (or "Enter".)*/
693 if( buf
[noc
-1]=='\n' ){
695 if( noc
> 1 && buf
[noc
-2]=='\r' ){
701 /* Check for ^Z (anywhere in line) too. */
703 if( buf
[iseg
]==0x1a ){
704 conState
.stdinEof
= 1;
705 noc
= iseg
; /* Chop ^Z and anything following. */
710 }else break; /* Drop apparent garbage in. (Could assert.) */
713 /* If got nothing, (after ^Z chop), must be at end-of-file. */
714 if( noc
== 0 ) return 0;
718 return fgets(buf
, ncmax
, fin
);
722 # define fgets(b,n,f) utf8_fgets(b,n,f)
723 #endif /* SHELL_WIN_UTF8_OPT */
726 ** Render output like fprintf(). Except, if the output is going to the
727 ** console and if this is running on a Windows machine, and if the -utf8
728 ** option is unavailable or (available and inactive), translate the
729 ** output from UTF-8 into MBCS for output through 8-bit stdout stream.
730 ** (With -utf8 active, no translation is needed and must not be done.)
732 #if defined(_WIN32) || defined(WIN32)
733 void utf8_printf(FILE *out
, const char *zFormat
, ...){
735 va_start(ap
, zFormat
);
736 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
)
737 # if SHELL_WIN_UTF8_OPT
741 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
742 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
747 vfprintf(out
, zFormat
, ap
);
751 #elif !defined(utf8_printf)
752 # define utf8_printf fprintf
756 ** Render output like fprintf(). This should not be used on anything that
757 ** includes string formatting (e.g. "%s").
759 #if !defined(raw_printf)
760 # define raw_printf fprintf
763 /* Indicate out-of-memory and exit. */
764 static void shell_out_of_memory(void){
765 raw_printf(stderr
,"Error: out of memory\n");
769 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
770 ** out-of-memory error.
772 static void shell_check_oom(const void *p
){
773 if( p
==0 ) shell_out_of_memory();
777 ** Write I/O traces to the following stream.
779 #ifdef SQLITE_ENABLE_IOTRACE
780 static FILE *iotrace
= 0;
784 ** This routine works like printf in that its first argument is a
785 ** format string and subsequent arguments are values to be substituted
786 ** in place of % fields. The result of formatting this string
787 ** is written to iotrace.
789 #ifdef SQLITE_ENABLE_IOTRACE
790 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
793 if( iotrace
==0 ) return;
794 va_start(ap
, zFormat
);
795 z
= sqlite3_vmprintf(zFormat
, ap
);
797 utf8_printf(iotrace
, "%s", z
);
803 ** Output string zUtf to stream pOut as w characters. If w is negative,
804 ** then right-justify the text. W is the width in UTF-8 characters, not
805 ** in bytes. This is different from the %*.*s specification in printf
806 ** since with %*.*s the width is measured in bytes, not characters.
808 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
811 int aw
= w
<0 ? -w
: w
;
812 if( zUtf
==0 ) zUtf
= "";
813 for(i
=n
=0; zUtf
[i
]; i
++){
814 if( (zUtf
[i
]&0xc0)!=0x80 ){
817 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
823 utf8_printf(pOut
, "%.*s", i
, zUtf
);
825 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
827 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
833 ** Determines if a string is a number of not.
835 static int isNumber(const char *z
, int *realnum
){
836 if( *z
=='-' || *z
=='+' ) z
++;
841 if( realnum
) *realnum
= 0;
842 while( IsDigit(*z
) ){ z
++; }
845 if( !IsDigit(*z
) ) return 0;
846 while( IsDigit(*z
) ){ z
++; }
847 if( realnum
) *realnum
= 1;
849 if( *z
=='e' || *z
=='E' ){
851 if( *z
=='+' || *z
=='-' ) z
++;
852 if( !IsDigit(*z
) ) return 0;
853 while( IsDigit(*z
) ){ z
++; }
854 if( realnum
) *realnum
= 1;
860 ** Compute a string length that is limited to what can be stored in
861 ** lower 30 bits of a 32-bit signed integer.
863 static int strlen30(const char *z
){
865 while( *z2
){ z2
++; }
866 return 0x3fffffff & (int)(z2
- z
);
870 ** Return the length of a string in characters. Multibyte UTF8 characters
871 ** count as a single character.
873 static int strlenChar(const char *z
){
876 if( (0xc0&*(z
++))!=0x80 ) n
++;
882 ** Return open FILE * if zFile exists, can be opened for read
883 ** and is an ordinary file or a character stream source.
884 ** Otherwise return 0.
886 static FILE * openChrSource(const char *zFile
){
888 struct _stat x
= {0};
889 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
890 /* On Windows, open first, then check the stream nature. This order
891 ** is necessary because _stat() and sibs, when checking a named pipe,
892 ** effectively break the pipe as its supplier sees it. */
893 FILE *rv
= fopen(zFile
, "rb");
894 if( rv
==0 ) return 0;
895 if( _fstat(_fileno(rv
), &x
) != 0
896 || !STAT_CHR_SRC(x
.st_mode
)){
903 int rc
= stat(zFile
, &x
);
904 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
905 if( rc
!=0 ) return 0;
906 if( STAT_CHR_SRC(x
.st_mode
) ){
907 return fopen(zFile
, "rb");
916 ** This routine reads a line of text from FILE in, stores
917 ** the text in memory obtained from malloc() and returns a pointer
918 ** to the text. NULL is returned at end of file, or if malloc()
921 ** If zLine is not NULL then it is a malloced buffer returned from
922 ** a previous call to this routine that may be reused.
924 static char *local_getline(char *zLine
, FILE *in
){
925 int nLine
= zLine
==0 ? 0 : 100;
930 nLine
= nLine
*2 + 100;
931 zLine
= realloc(zLine
, nLine
);
932 shell_check_oom(zLine
);
934 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
942 while( zLine
[n
] ) n
++;
943 if( n
>0 && zLine
[n
-1]=='\n' ){
945 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
950 #if defined(_WIN32) || defined(WIN32)
951 /* For interactive input on Windows systems, without -utf8,
952 ** translate the multi-byte characterset characters into UTF-8.
953 ** This is the translation that predates the -utf8 option. */
954 if( stdin_is_interactive
&& in
==stdin
955 # if SHELL_WIN_UTF8_OPT
957 # endif /* SHELL_WIN_UTF8_OPT */
959 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
961 i64 nTrans
= strlen(zTrans
)+1;
963 zLine
= realloc(zLine
, nTrans
);
964 shell_check_oom(zLine
);
966 memcpy(zLine
, zTrans
, nTrans
);
967 sqlite3_free(zTrans
);
970 #endif /* defined(_WIN32) || defined(WIN32) */
975 ** Retrieve a single line of input text.
977 ** If in==0 then read from standard input and prompt before each line.
978 ** If isContinuation is true, then a continuation prompt is appropriate.
979 ** If isContinuation is zero, then the main prompt should be used.
981 ** If zPrior is not NULL then it is a buffer from a prior call to this
982 ** routine that can be reused.
984 ** The result is stored in space obtained from malloc() and must either
985 ** be freed by the caller or else passed back into this routine via the
986 ** zPrior argument for reuse.
988 #ifndef SQLITE_SHELL_FIDDLE
989 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
993 zResult
= local_getline(zPrior
, in
);
995 zPrompt
= isContinuation
? CONTINUATION_PROMPT
: mainPrompt
;
996 #if SHELL_USE_LOCAL_GETLINE
997 printf("%s", zPrompt
);
1000 zResult
= local_getline(zPrior
, stdin
);
1002 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1003 if( zResult
==0 ) sqlite3_sleep(50);
1004 }while( zResult
==0 && seenInterrupt
>0 );
1007 zResult
= shell_readline(zPrompt
);
1008 while( zResult
==0 ){
1009 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1011 if( seenInterrupt
==0 ) break;
1012 zResult
= shell_readline("");
1014 if( zResult
&& *zResult
) shell_add_history(zResult
);
1019 #endif /* !SQLITE_SHELL_FIDDLE */
1022 ** Return the value of a hexadecimal digit. Return -1 if the input
1023 ** is not a hex digit.
1025 static int hexDigitValue(char c
){
1026 if( c
>='0' && c
<='9' ) return c
- '0';
1027 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
1028 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
1033 ** Interpret zArg as an integer value, possibly with suffixes.
1035 static sqlite3_int64
integerValue(const char *zArg
){
1036 sqlite3_int64 v
= 0;
1037 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
1039 { "MiB", 1024*1024 },
1040 { "GiB", 1024*1024*1024 },
1043 { "GB", 1000000000 },
1046 { "G", 1000000000 },
1053 }else if( zArg
[0]=='+' ){
1056 if( zArg
[0]=='0' && zArg
[1]=='x' ){
1059 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
1064 while( IsDigit(zArg
[0]) ){
1065 v
= v
*10 + zArg
[0] - '0';
1069 for(i
=0; i
<ArraySize(aMult
); i
++){
1070 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
1071 v
*= aMult
[i
].iMult
;
1075 return isNeg
? -v
: v
;
1079 ** A variable length string to which one can append text.
1081 typedef struct ShellText ShellText
;
1089 ** Initialize and destroy a ShellText object
1091 static void initText(ShellText
*p
){
1092 memset(p
, 0, sizeof(*p
));
1094 static void freeText(ShellText
*p
){
1099 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1100 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1101 ** added to zIn, and the result returned in memory obtained from malloc().
1102 ** zIn, if it was not NULL, is freed.
1104 ** If the third argument, quote, is not '\0', then it is used as a
1105 ** quote character for zAppend.
1107 static void appendText(ShellText
*p
, const char *zAppend
, char quote
){
1110 i64 nAppend
= strlen30(zAppend
);
1112 len
= nAppend
+p
->n
+1;
1115 for(i
=0; i
<nAppend
; i
++){
1116 if( zAppend
[i
]==quote
) len
++;
1120 if( p
->z
==0 || p
->n
+len
>=p
->nAlloc
){
1121 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
1122 p
->z
= realloc(p
->z
, p
->nAlloc
);
1123 shell_check_oom(p
->z
);
1127 char *zCsr
= p
->z
+p
->n
;
1129 for(i
=0; i
<nAppend
; i
++){
1130 *zCsr
++ = zAppend
[i
];
1131 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
1134 p
->n
= (int)(zCsr
- p
->z
);
1137 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
1144 ** Attempt to determine if identifier zName needs to be quoted, either
1145 ** because it contains non-alphanumeric characters, or because it is an
1146 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
1147 ** that quoting is required.
1149 ** Return '"' if quoting is required. Return 0 if no quoting is required.
1151 static char quoteChar(const char *zName
){
1153 if( zName
==0 ) return '"';
1154 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
1155 for(i
=0; zName
[i
]; i
++){
1156 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
1158 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
1162 ** Construct a fake object name and column list to describe the structure
1163 ** of the view, virtual table, or table valued function zSchema.zName.
1165 static char *shellFakeSchema(
1166 sqlite3
*db
, /* The database connection containing the vtab */
1167 const char *zSchema
, /* Schema of the database holding the vtab */
1168 const char *zName
/* The name of the virtual table */
1170 sqlite3_stmt
*pStmt
= 0;
1177 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
1178 zSchema
? zSchema
: "main", zName
);
1179 shell_check_oom(zSql
);
1180 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
1184 cQuote
= quoteChar(zSchema
);
1185 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
1186 appendText(&s
, zSchema
, cQuote
);
1187 appendText(&s
, ".", 0);
1189 cQuote
= quoteChar(zName
);
1190 appendText(&s
, zName
, cQuote
);
1191 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
1192 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
1194 appendText(&s
, zDiv
, 0);
1196 if( zCol
==0 ) zCol
= "";
1197 cQuote
= quoteChar(zCol
);
1198 appendText(&s
, zCol
, cQuote
);
1200 appendText(&s
, ")", 0);
1201 sqlite3_finalize(pStmt
);
1210 ** SQL function: shell_module_schema(X)
1212 ** Return a fake schema for the table-valued function or eponymous virtual
1215 static void shellModuleSchema(
1216 sqlite3_context
*pCtx
,
1218 sqlite3_value
**apVal
1222 UNUSED_PARAMETER(nVal
);
1223 zName
= (const char*)sqlite3_value_text(apVal
[0]);
1224 zFake
= zName
? shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
) : 0;
1226 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
1233 ** SQL function: shell_add_schema(S,X)
1235 ** Add the schema name X to the CREATE statement in S and return the result.
1238 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
1243 ** CREATE UNIQUE INDEX
1246 ** CREATE VIRTUAL TABLE
1248 ** This UDF is used by the .schema command to insert the schema name of
1249 ** attached databases into the middle of the sqlite_schema.sql field.
1251 static void shellAddSchemaName(
1252 sqlite3_context
*pCtx
,
1254 sqlite3_value
**apVal
1256 static const char *aPrefix
[] = {
1265 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
1266 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
1267 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
1268 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
1269 UNUSED_PARAMETER(nVal
);
1270 if( zIn
!=0 && cli_strncmp(zIn
, "CREATE ", 7)==0 ){
1271 for(i
=0; i
<ArraySize(aPrefix
); i
++){
1272 int n
= strlen30(aPrefix
[i
]);
1273 if( cli_strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
1277 char cQuote
= quoteChar(zSchema
);
1278 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
1279 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1281 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1285 && aPrefix
[i
][0]=='V'
1286 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
1289 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
1291 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
1296 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
1302 sqlite3_result_value(pCtx
, apVal
[0]);
1306 ** The source code for several run-time loadable extensions is inserted
1307 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1308 ** code, we need to override some macros to make the included program code
1309 ** work here in the middle of this regular program.
1311 #define SQLITE_EXTENSION_INIT1
1312 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1314 #if defined(_WIN32) && defined(_MSC_VER)
1315 INCLUDE test_windirent
.h
1316 INCLUDE test_windirent
.c
1317 #define dirent DIRENT
1319 INCLUDE
../ext
/misc
/memtrace
.c
1320 INCLUDE
../ext
/misc
/shathree
.c
1321 INCLUDE
../ext
/misc
/uint
.c
1322 INCLUDE
../ext
/misc
/decimal
.c
1323 #undef sqlite3_base_init
1324 #define sqlite3_base_init sqlite3_base64_init
1325 INCLUDE
../ext
/misc
/base64
.c
1326 #undef sqlite3_base_init
1327 #define sqlite3_base_init sqlite3_base85_init
1328 #define OMIT_BASE85_CHECKER
1329 INCLUDE
../ext
/misc
/base85
.c
1330 INCLUDE
../ext
/misc
/ieee754
.c
1331 INCLUDE
../ext
/misc
/series
.c
1332 INCLUDE
../ext
/misc
/regexp
.c
1333 #ifndef SQLITE_SHELL_FIDDLE
1334 INCLUDE
../ext
/misc
/fileio
.c
1335 INCLUDE
../ext
/misc
/completion
.c
1336 INCLUDE
../ext
/misc
/appendvfs
.c
1338 #ifdef SQLITE_HAVE_ZLIB
1339 INCLUDE
../ext
/misc
/zipfile
.c
1340 INCLUDE
../ext
/misc
/sqlar
.c
1342 INCLUDE
../ext
/expert
/sqlite3expert
.h
1343 INCLUDE
../ext
/expert
/sqlite3expert
.c
1345 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1346 #define SQLITE_SHELL_HAVE_RECOVER 1
1348 #define SQLITE_SHELL_HAVE_RECOVER 0
1350 #if SQLITE_SHELL_HAVE_RECOVER
1351 INCLUDE
../ext
/recover
/sqlite3recover
.h
1352 # ifndef SQLITE_HAVE_SQLITE3R
1353 INCLUDE
../ext
/recover
/dbdata
.c
1354 INCLUDE
../ext
/recover
/sqlite3recover
.c
1355 # endif /* SQLITE_HAVE_SQLITE3R */
1357 #ifdef SQLITE_SHELL_EXTSRC
1358 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
1361 #if defined(SQLITE_ENABLE_SESSION)
1363 ** State information for a single open session
1365 typedef struct OpenSession OpenSession
;
1366 struct OpenSession
{
1367 char *zName
; /* Symbolic name for this session */
1368 int nFilter
; /* Number of xFilter rejection GLOB patterns */
1369 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
1370 sqlite3_session
*p
; /* The open session */
1374 typedef struct ExpertInfo ExpertInfo
;
1376 sqlite3expert
*pExpert
;
1380 /* A single line in the EQP output */
1381 typedef struct EQPGraphRow EQPGraphRow
;
1382 struct EQPGraphRow
{
1383 int iEqpId
; /* ID for this row */
1384 int iParentId
; /* ID of the parent row */
1385 EQPGraphRow
*pNext
; /* Next row in sequence */
1386 char zText
[1]; /* Text to display for this row */
1389 /* All EQP output is collected into an instance of the following */
1390 typedef struct EQPGraph EQPGraph
;
1392 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
1393 EQPGraphRow
*pLast
; /* Last element of the pRow list */
1394 char zPrefix
[100]; /* Graph prefix */
1397 /* Parameters affecting columnar mode result display (defaulting together) */
1398 typedef struct ColModeOpts
{
1399 int iWrap
; /* In columnar modes, wrap lines reaching this limit */
1400 u8 bQuote
; /* Quote results for .mode box and table */
1401 u8 bWordWrap
; /* In columnar modes, wrap at word boundaries */
1403 #define ColModeOpts_default { 60, 0, 0 }
1404 #define ColModeOpts_default_qbox { 60, 1, 0 }
1407 ** State information about the database connection is contained in an
1408 ** instance of the following structure.
1410 typedef struct ShellState ShellState
;
1412 sqlite3
*db
; /* The database */
1413 u8 autoExplain
; /* Automatically turn on .explain mode */
1414 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1415 u8 autoEQPtest
; /* autoEQP is in test mode */
1416 u8 autoEQPtrace
; /* autoEQP is in trace mode */
1417 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1418 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1419 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1420 u8 nEqpLevel
; /* Depth of the EQP output graph */
1421 u8 eTraceType
; /* SHELL_TRACE_* value for type of trace */
1422 u8 bSafeMode
; /* True to prohibit unsafe operations */
1423 u8 bSafeModePersist
; /* The long-term value of bSafeMode */
1424 ColModeOpts cmOpts
; /* Option values affecting columnar mode output */
1425 unsigned statsOn
; /* True to display memory stats before each finalize */
1426 unsigned mEqpLines
; /* Mask of veritical lines in the EQP output graph */
1427 int inputNesting
; /* Track nesting level of .read and other redirects */
1428 int outCount
; /* Revert to stdout when reaching zero */
1429 int cnt
; /* Number of records displayed so far */
1430 int lineno
; /* Line number of last line read from in */
1431 int openFlags
; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1432 FILE *in
; /* Read commands from this stream */
1433 FILE *out
; /* Write results here */
1434 FILE *traceOut
; /* Output for sqlite3_trace() */
1435 int nErr
; /* Number of errors seen */
1436 int mode
; /* An output mode setting */
1437 int modePrior
; /* Saved mode */
1438 int cMode
; /* temporary output mode for the current query */
1439 int normalMode
; /* Output mode before ".explain on" */
1440 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1441 int showHeader
; /* True to show column names in List or Column mode */
1442 int nCheck
; /* Number of ".check" commands run */
1443 unsigned nProgress
; /* Number of progress callbacks encountered */
1444 unsigned mxProgress
; /* Maximum progress callbacks before failing */
1445 unsigned flgProgress
; /* Flags for the progress callback */
1446 unsigned shellFlgs
; /* Various flags */
1447 unsigned priorShFlgs
; /* Saved copy of flags */
1448 sqlite3_int64 szMax
; /* --maxsize argument to .open */
1449 char *zDestTable
; /* Name of destination table when MODE_Insert */
1450 char *zTempFile
; /* Temporary file that might need deleting */
1451 char zTestcase
[30]; /* Name of current test case */
1452 char colSeparator
[20]; /* Column separator character for several modes */
1453 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1454 char colSepPrior
[20]; /* Saved column separator */
1455 char rowSepPrior
[20]; /* Saved row separator */
1456 int *colWidth
; /* Requested width of each column in columnar modes */
1457 int *actualWidth
; /* Actual width of each column */
1458 int nWidth
; /* Number of slots in colWidth[] and actualWidth[] */
1459 char nullValue
[20]; /* The text to print when a NULL comes back from
1461 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1462 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1463 FILE *pLog
; /* Write log output here */
1464 struct AuxDb
{ /* Storage space for auxiliary database connections */
1465 sqlite3
*db
; /* Connection pointer */
1466 const char *zDbFilename
; /* Filename used to open the connection */
1467 char *zFreeOnClose
; /* Free this memory allocation on close */
1468 #if defined(SQLITE_ENABLE_SESSION)
1469 int nSession
; /* Number of active sessions */
1470 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1472 } aAuxDb
[5], /* Array of all database connections */
1473 *pAuxDb
; /* Currently active database connection */
1474 int *aiIndent
; /* Array of indents used in MODE_Explain */
1475 int nIndent
; /* Size of array aiIndent[] */
1476 int iIndent
; /* Index of current op in aiIndent[] */
1477 char *zNonce
; /* Nonce for temporary safe-mode excapes */
1478 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1479 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1480 #ifdef SQLITE_SHELL_FIDDLE
1482 const char * zInput
; /* Input string from wasm/JS proxy */
1483 const char * zPos
; /* Cursor pos into zInput */
1484 const char * zDefaultDbName
; /* Default name for db file */
1489 #ifdef SQLITE_SHELL_FIDDLE
1490 static ShellState shellState
;
1494 /* Allowed values for ShellState.autoEQP
1496 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1497 #define AUTOEQP_on 1 /* Automatic EQP is on */
1498 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1499 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1501 /* Allowed values for ShellState.openMode
1503 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1504 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1505 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1506 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1507 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1508 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1509 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1511 /* Allowed values for ShellState.eTraceType
1513 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1514 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1515 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1517 /* Bits in the ShellState.flgProgress variable */
1518 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1519 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1520 ** callback limit is reached, and for each
1521 ** top-level SQL statement */
1522 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1525 ** These are the allowed shellFlgs values
1527 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1528 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1529 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1530 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1531 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1532 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1533 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1534 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1535 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1536 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1537 #define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */
1540 ** Macros for testing and setting shellFlgs
1542 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1543 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1544 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1547 ** These are the allowed modes.
1549 #define MODE_Line 0 /* One column per line. Blank line between records */
1550 #define MODE_Column 1 /* One record per line in neat columns */
1551 #define MODE_List 2 /* One record per line with a separator */
1552 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1553 #define MODE_Html 4 /* Generate an XHTML table */
1554 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1555 #define MODE_Quote 6 /* Quote values as for SQL */
1556 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1557 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1558 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1559 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1560 #define MODE_Pretty 11 /* Pretty-print schemas */
1561 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1562 #define MODE_Json 13 /* Output JSON */
1563 #define MODE_Markdown 14 /* Markdown formatting */
1564 #define MODE_Table 15 /* MySQL-style table formatting */
1565 #define MODE_Box 16 /* Unicode box-drawing characters */
1566 #define MODE_Count 17 /* Output only a count of the rows of output */
1567 #define MODE_Off 18 /* No query output shown */
1569 static const char *modeDescr
[] = {
1592 ** These are the column/row/line separators used by the various
1593 ** import/export modes.
1595 #define SEP_Column "|"
1596 #define SEP_Row "\n"
1597 #define SEP_Tab "\t"
1598 #define SEP_Space " "
1599 #define SEP_Comma ","
1600 #define SEP_CrLf "\r\n"
1601 #define SEP_Unit "\x1F"
1602 #define SEP_Record "\x1E"
1605 ** Limit input nesting via .read or any other input redirect.
1606 ** It's not too expensive, so a generous allowance can be made.
1608 #define MAX_INPUT_NESTING 25
1611 ** A callback for the sqlite3_log() interface.
1613 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1614 ShellState
*p
= (ShellState
*)pArg
;
1615 if( p
->pLog
==0 ) return;
1616 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1621 ** SQL function: shell_putsnl(X)
1623 ** Write the text X to the screen (or whatever output is being directed)
1624 ** adding a newline at the end, and then return X.
1626 static void shellPutsFunc(
1627 sqlite3_context
*pCtx
,
1629 sqlite3_value
**apVal
1631 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1633 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1634 sqlite3_result_value(pCtx
, apVal
[0]);
1638 ** If in safe mode, print an error message described by the arguments
1639 ** and exit immediately.
1641 static void failIfSafeMode(
1643 const char *zErrMsg
,
1649 va_start(ap
, zErrMsg
);
1650 zMsg
= sqlite3_vmprintf(zErrMsg
, ap
);
1652 raw_printf(stderr
, "line %d: ", p
->lineno
);
1653 utf8_printf(stderr
, "%s\n", zMsg
);
1659 ** SQL function: edit(VALUE)
1660 ** edit(VALUE,EDITOR)
1664 ** (1) Write VALUE into a temporary file.
1665 ** (2) Run program EDITOR on that temporary file.
1666 ** (3) Read the temporary file back and return its content as the result.
1667 ** (4) Delete the temporary file
1669 ** If the EDITOR argument is omitted, use the value in the VISUAL
1670 ** environment variable. If still there is no EDITOR, through an error.
1672 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1674 #ifndef SQLITE_NOHAVE_SYSTEM
1675 static void editFunc(
1676 sqlite3_context
*context
,
1678 sqlite3_value
**argv
1680 const char *zEditor
;
1681 char *zTempFile
= 0;
1690 unsigned char *p
= 0;
1693 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1695 zEditor
= getenv("VISUAL");
1698 sqlite3_result_error(context
, "no editor for edit()", -1);
1701 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1702 sqlite3_result_error(context
, "NULL input to edit()", -1);
1705 db
= sqlite3_context_db_handle(context
);
1707 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1709 sqlite3_uint64 r
= 0;
1710 sqlite3_randomness(sizeof(r
), &r
);
1711 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1713 sqlite3_result_error_nomem(context
);
1717 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1718 /* When writing the file to be edited, do \n to \r\n conversions on systems
1719 ** that want \r\n line endings */
1720 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1722 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1725 sz
= sqlite3_value_bytes(argv
[0]);
1727 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, (size_t)sz
, f
);
1729 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
1730 /* Remember whether or not the value originally contained \r\n */
1731 if( z
&& strstr(z
,"\r\n")!=0 ) hasCRNL
= 1;
1732 x
= fwrite(sqlite3_value_text(argv
[0]), 1, (size_t)sz
, f
);
1737 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1740 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1742 sqlite3_result_error_nomem(context
);
1748 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1751 f
= fopen(zTempFile
, "rb");
1753 sqlite3_result_error(context
,
1754 "edit() cannot reopen temp file after edit", -1);
1757 fseek(f
, 0, SEEK_END
);
1760 p
= sqlite3_malloc64( sz
+1 );
1762 sqlite3_result_error_nomem(context
);
1765 x
= fread(p
, 1, (size_t)sz
, f
);
1769 sqlite3_result_error(context
, "could not read back the whole file", -1);
1773 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1777 /* If the original contains \r\n then do no conversions back to \n */
1779 /* If the file did not originally contain \r\n then convert any new
1780 ** \r\n back into \n */
1782 for(i
=j
=0; i
<sz
; i
++){
1783 if( p
[i
]=='\r' && p
[i
+1]=='\n' ) i
++;
1789 sqlite3_result_text64(context
, (const char*)p
, sz
,
1790 sqlite3_free
, SQLITE_UTF8
);
1797 sqlite3_free(zTempFile
);
1800 #endif /* SQLITE_NOHAVE_SYSTEM */
1803 ** Save or restore the current output mode
1805 static void outputModePush(ShellState
*p
){
1806 p
->modePrior
= p
->mode
;
1807 p
->priorShFlgs
= p
->shellFlgs
;
1808 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1809 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1811 static void outputModePop(ShellState
*p
){
1812 p
->mode
= p
->modePrior
;
1813 p
->shellFlgs
= p
->priorShFlgs
;
1814 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1815 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1819 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1821 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1823 unsigned char *aBlob
= (unsigned char*)pBlob
;
1825 char *zStr
= sqlite3_malloc(nBlob
*2 + 1);
1826 shell_check_oom(zStr
);
1828 for(i
=0; i
<nBlob
; i
++){
1829 static const char aHex
[] = {
1830 '0', '1', '2', '3', '4', '5', '6', '7',
1831 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1833 zStr
[i
*2] = aHex
[ (aBlob
[i
] >> 4) ];
1834 zStr
[i
*2+1] = aHex
[ (aBlob
[i
] & 0x0F) ];
1838 raw_printf(out
,"X'%s'", zStr
);
1843 ** Find a string that is not found anywhere in z[]. Return a pointer
1846 ** Try to use zA and zB first. If both of those are already found in z[]
1847 ** then make up some string and store it in the buffer zBuf.
1849 static const char *unused_string(
1850 const char *z
, /* Result must not appear anywhere in z */
1851 const char *zA
, const char *zB
, /* Try these first */
1852 char *zBuf
/* Space to store a generated string */
1855 if( strstr(z
, zA
)==0 ) return zA
;
1856 if( strstr(z
, zB
)==0 ) return zB
;
1858 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1859 }while( strstr(z
,zBuf
)!=0 );
1864 ** Output the given string as a quoted string using SQL quoting conventions.
1866 ** See also: output_quoted_escaped_string()
1868 static void output_quoted_string(FILE *out
, const char *z
){
1871 setBinaryMode(out
, 1);
1873 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1875 utf8_printf(out
,"'%s'",z
);
1877 raw_printf(out
, "'");
1879 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1882 utf8_printf(out
, "%.*s", i
, z
);
1886 raw_printf(out
, "'");
1894 raw_printf(out
, "'");
1896 setTextMode(out
, 1);
1900 ** Output the given string as a quoted string using SQL quoting conventions.
1901 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1902 ** get corrupted by end-of-line translation facilities in some operating
1905 ** This is like output_quoted_string() but with the addition of the \r\n
1906 ** escape mechanism.
1908 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1911 setBinaryMode(out
, 1);
1912 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1914 utf8_printf(out
,"'%s'",z
);
1916 const char *zNL
= 0;
1917 const char *zCR
= 0;
1920 char zBuf1
[20], zBuf2
[20];
1921 for(i
=0; z
[i
]; i
++){
1922 if( z
[i
]=='\n' ) nNL
++;
1923 if( z
[i
]=='\r' ) nCR
++;
1926 raw_printf(out
, "replace(");
1927 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1930 raw_printf(out
, "replace(");
1931 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1933 raw_printf(out
, "'");
1935 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1938 utf8_printf(out
, "%.*s", i
, z
);
1942 raw_printf(out
, "'");
1950 raw_printf(out
, "%s", zNL
);
1953 raw_printf(out
, "%s", zCR
);
1955 raw_printf(out
, "'");
1957 raw_printf(out
, ",'%s',char(13))", zCR
);
1960 raw_printf(out
, ",'%s',char(10))", zNL
);
1963 setTextMode(out
, 1);
1967 ** Output the given string as a quoted according to C or TCL quoting rules.
1969 static void output_c_string(FILE *out
, const char *z
){
1972 while( (c
= *(z
++))!=0 ){
1979 }else if( c
=='\t' ){
1982 }else if( c
=='\n' ){
1985 }else if( c
=='\r' ){
1988 }else if( !isprint(c
&0xff) ){
1989 raw_printf(out
, "\\%03o", c
&0xff);
1998 ** Output the given string as a quoted according to JSON quoting rules.
2000 static void output_json_string(FILE *out
, const char *z
, i64 n
){
2003 if( n
<0 ) n
= strlen(z
);
2007 if( c
=='\\' || c
=='"' ){
2010 }else if( c
<=0x1f ){
2014 }else if( c
=='\f' ){
2016 }else if( c
=='\n' ){
2018 }else if( c
=='\r' ){
2020 }else if( c
=='\t' ){
2023 raw_printf(out
, "u%04x",c
);
2033 ** Output the given string with characters that are special to
2036 static void output_html_string(FILE *out
, const char *z
){
2048 utf8_printf(out
,"%.*s",i
,z
);
2051 raw_printf(out
,"<");
2052 }else if( z
[i
]=='&' ){
2053 raw_printf(out
,"&");
2054 }else if( z
[i
]=='>' ){
2055 raw_printf(out
,">");
2056 }else if( z
[i
]=='\"' ){
2057 raw_printf(out
,""");
2058 }else if( z
[i
]=='\'' ){
2059 raw_printf(out
,"'");
2068 ** If a field contains any character identified by a 1 in the following
2069 ** array, then the string must be quoted for CSV.
2071 static const char needCsvQuote
[] = {
2072 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2073 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2074 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2075 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2076 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2077 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2078 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2079 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2082 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2083 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2084 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2085 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2086 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2087 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2091 ** Output a single term of CSV. Actually, p->colSeparator is used for
2092 ** the separator, which may or may not be a comma. p->nullValue is
2093 ** the null value. Strings are quoted if necessary. The separator
2094 ** is only issued if bSep is true.
2096 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
2099 utf8_printf(out
,"%s",p
->nullValue
);
2102 for(i
=0; z
[i
]; i
++){
2103 if( needCsvQuote
[((unsigned char*)z
)[i
]] ){
2108 if( i
==0 || strstr(z
, p
->colSeparator
)!=0 ){
2109 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
2110 shell_check_oom(zQuoted
);
2111 utf8_printf(out
, "%s", zQuoted
);
2112 sqlite3_free(zQuoted
);
2114 utf8_printf(out
, "%s", z
);
2118 utf8_printf(p
->out
, "%s", p
->colSeparator
);
2123 ** This routine runs when the user presses Ctrl-C
2125 static void interrupt_handler(int NotUsed
){
2126 UNUSED_PARAMETER(NotUsed
);
2127 if( ++seenInterrupt
>1 ) exit(1);
2128 if( globalDb
) sqlite3_interrupt(globalDb
);
2131 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
2133 ** This routine runs for console events (e.g. Ctrl-C) on Win32
2135 static BOOL WINAPI
ConsoleCtrlHandler(
2136 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
2138 if( dwCtrlType
==CTRL_C_EVENT
){
2139 interrupt_handler(0);
2146 #ifndef SQLITE_OMIT_AUTHORIZATION
2148 ** This authorizer runs in safe mode.
2150 static int safeModeAuth(
2158 ShellState
*p
= (ShellState
*)pClientData
;
2159 static const char *azProhibitedFunctions
[] = {
2168 UNUSED_PARAMETER(zA1
);
2169 UNUSED_PARAMETER(zA3
);
2170 UNUSED_PARAMETER(zA4
);
2172 case SQLITE_ATTACH
: {
2173 #ifndef SQLITE_SHELL_FIDDLE
2174 /* In WASM builds the filesystem is a virtual sandbox, so
2175 ** there's no harm in using ATTACH. */
2176 failIfSafeMode(p
, "cannot run ATTACH in safe mode");
2180 case SQLITE_FUNCTION
: {
2182 for(i
=0; i
<ArraySize(azProhibitedFunctions
); i
++){
2183 if( sqlite3_stricmp(zA2
, azProhibitedFunctions
[i
])==0 ){
2184 failIfSafeMode(p
, "cannot use the %s() function in safe mode",
2185 azProhibitedFunctions
[i
]);
2195 ** When the ".auth ON" is set, the following authorizer callback is
2196 ** invoked. It always returns SQLITE_OK.
2198 static int shellAuth(
2206 ShellState
*p
= (ShellState
*)pClientData
;
2207 static const char *azAction
[] = { 0,
2208 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2209 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2210 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2211 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2212 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2213 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2214 "PRAGMA", "READ", "SELECT",
2215 "TRANSACTION", "UPDATE", "ATTACH",
2216 "DETACH", "ALTER_TABLE", "REINDEX",
2217 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2218 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2226 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
2228 raw_printf(p
->out
, " ");
2230 output_c_string(p
->out
, az
[i
]);
2232 raw_printf(p
->out
, "NULL");
2235 raw_printf(p
->out
, "\n");
2236 if( p
->bSafeMode
) (void)safeModeAuth(pClientData
, op
, zA1
, zA2
, zA3
, zA4
);
2242 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2244 ** This routine converts some CREATE TABLE statements for shadow tables
2245 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2247 ** If the schema statement in z[] contains a start-of-comment and if
2248 ** sqlite3_complete() returns false, try to terminate the comment before
2249 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
2251 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
2254 if( zTail
==0 ) return;
2255 if( zTail
[0]==';' && (strstr(z
, "/*")!=0 || strstr(z
,"--")!=0) ){
2256 const char *zOrig
= z
;
2257 static const char *azTerm
[] = { "", "*/", "\n" };
2259 for(i
=0; i
<ArraySize(azTerm
); i
++){
2260 char *zNew
= sqlite3_mprintf("%s%s;", zOrig
, azTerm
[i
]);
2261 shell_check_oom(zNew
);
2262 if( sqlite3_complete(zNew
) ){
2263 size_t n
= strlen(zNew
);
2272 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
2273 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
2275 utf8_printf(out
, "%s%s", z
, zTail
);
2277 sqlite3_free(zToFree
);
2279 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
2282 printSchemaLine(out
, z
, zTail
);
2287 ** Return true if string z[] has nothing but whitespace and comments to the
2288 ** end of the first line.
2290 static int wsToEol(const char *z
){
2292 for(i
=0; z
[i
]; i
++){
2293 if( z
[i
]=='\n' ) return 1;
2294 if( IsSpace(z
[i
]) ) continue;
2295 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
2302 ** Add a new entry to the EXPLAIN QUERY PLAN data
2304 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
2307 if( zText
==0 ) return;
2308 nText
= strlen(zText
);
2309 if( p
->autoEQPtest
){
2310 utf8_printf(p
->out
, "%d,%d,%s\n", iEqpId
, p2
, zText
);
2312 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
2313 shell_check_oom(pNew
);
2314 pNew
->iEqpId
= iEqpId
;
2315 pNew
->iParentId
= p2
;
2316 memcpy(pNew
->zText
, zText
, nText
+1);
2318 if( p
->sGraph
.pLast
){
2319 p
->sGraph
.pLast
->pNext
= pNew
;
2321 p
->sGraph
.pRow
= pNew
;
2323 p
->sGraph
.pLast
= pNew
;
2327 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2330 static void eqp_reset(ShellState
*p
){
2331 EQPGraphRow
*pRow
, *pNext
;
2332 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
2333 pNext
= pRow
->pNext
;
2336 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
2339 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2340 ** pOld, or return the first such line if pOld is NULL
2342 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
2343 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
2344 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
2348 /* Render a single level of the graph that has iEqpId as its parent. Called
2349 ** recursively to render sublevels.
2351 static void eqp_render_level(ShellState
*p
, int iEqpId
){
2352 EQPGraphRow
*pRow
, *pNext
;
2353 i64 n
= strlen(p
->sGraph
.zPrefix
);
2355 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
2356 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
2358 utf8_printf(p
->out
, "%s%s%s\n", p
->sGraph
.zPrefix
,
2359 pNext
? "|--" : "`--", z
);
2360 if( n
<(i64
)sizeof(p
->sGraph
.zPrefix
)-7 ){
2361 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
2362 eqp_render_level(p
, pRow
->iEqpId
);
2363 p
->sGraph
.zPrefix
[n
] = 0;
2369 ** Display and reset the EXPLAIN QUERY PLAN data
2371 static void eqp_render(ShellState
*p
, i64 nCycle
){
2372 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
2374 if( pRow
->zText
[0]=='-' ){
2375 if( pRow
->pNext
==0 ){
2379 utf8_printf(p
->out
, "%s\n", pRow
->zText
+3);
2380 p
->sGraph
.pRow
= pRow
->pNext
;
2382 }else if( nCycle
>0 ){
2383 utf8_printf(p
->out
, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle
);
2385 utf8_printf(p
->out
, "QUERY PLAN\n");
2387 p
->sGraph
.zPrefix
[0] = 0;
2388 eqp_render_level(p
, 0);
2393 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2395 ** Progress handler callback.
2397 static int progress_handler(void *pClientData
) {
2398 ShellState
*p
= (ShellState
*)pClientData
;
2400 if( p
->nProgress
>=p
->mxProgress
&& p
->mxProgress
>0 ){
2401 raw_printf(p
->out
, "Progress limit reached (%u)\n", p
->nProgress
);
2402 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
2403 if( p
->flgProgress
& SHELL_PROGRESS_ONCE
) p
->mxProgress
= 0;
2406 if( (p
->flgProgress
& SHELL_PROGRESS_QUIET
)==0 ){
2407 raw_printf(p
->out
, "Progress %u\n", p
->nProgress
);
2411 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2416 static void print_dashes(FILE *out
, int N
){
2417 const char zDash
[] = "--------------------------------------------------";
2418 const int nDash
= sizeof(zDash
) - 1;
2423 raw_printf(out
, "%.*s", N
, zDash
);
2427 ** Print a markdown or table-style row separator using ascii-art
2429 static void print_row_separator(
2436 fputs(zSep
, p
->out
);
2437 print_dashes(p
->out
, p
->actualWidth
[0]+2);
2438 for(i
=1; i
<nArg
; i
++){
2439 fputs(zSep
, p
->out
);
2440 print_dashes(p
->out
, p
->actualWidth
[i
]+2);
2442 fputs(zSep
, p
->out
);
2444 fputs("\n", p
->out
);
2448 ** This is the callback routine that the shell
2449 ** invokes for each row of a query result.
2451 static int shell_callback(
2453 int nArg
, /* Number of result columns */
2454 char **azArg
, /* Text of each result column */
2455 char **azCol
, /* Column names */
2456 int *aiType
/* Column types. Might be NULL */
2459 ShellState
*p
= (ShellState
*)pArg
;
2461 if( azArg
==0 ) return 0;
2469 if( azArg
==0 ) break;
2470 for(i
=0; i
<nArg
; i
++){
2471 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
2472 if( len
>w
) w
= len
;
2474 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2475 for(i
=0; i
<nArg
; i
++){
2476 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
2477 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
2481 case MODE_Explain
: {
2482 static const int aExplainWidth
[] = {4, 13, 4, 4, 4, 13, 2, 13};
2483 if( nArg
>ArraySize(aExplainWidth
) ){
2484 nArg
= ArraySize(aExplainWidth
);
2487 for(i
=0; i
<nArg
; i
++){
2488 int w
= aExplainWidth
[i
];
2489 utf8_width_print(p
->out
, w
, azCol
[i
]);
2490 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2492 for(i
=0; i
<nArg
; i
++){
2493 int w
= aExplainWidth
[i
];
2494 print_dashes(p
->out
, w
);
2495 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2498 if( azArg
==0 ) break;
2499 for(i
=0; i
<nArg
; i
++){
2500 int w
= aExplainWidth
[i
];
2501 if( i
==nArg
-1 ) w
= 0;
2502 if( azArg
[i
] && strlenChar(azArg
[i
])>w
){
2503 w
= strlenChar(azArg
[i
]);
2505 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
2506 if( p
->iIndent
<p
->nIndent
){
2507 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
2511 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2512 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2516 case MODE_Semi
: { /* .schema and .fullschema output */
2517 printSchemaLine(p
->out
, azArg
[0], ";\n");
2520 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
2528 if( azArg
[0]==0 ) break;
2529 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
2530 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
2532 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
2535 z
= sqlite3_mprintf("%s", azArg
[0]);
2538 for(i
=0; IsSpace(z
[i
]); i
++){}
2539 for(; (c
= z
[i
])!=0; i
++){
2541 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
2542 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
2543 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
2548 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
2550 if( strlen30(z
)>=79 ){
2551 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy from z[i] back to z[j] */
2554 }else if( c
=='"' || c
=='\'' || c
=='`' ){
2558 }else if( c
=='-' && z
[i
+1]=='-' ){
2564 if( nLine
>0 && nParen
==0 && j
>0 ){
2565 printSchemaLineN(p
->out
, z
, j
, "\n");
2570 if( nParen
==1 && cEnd
==0
2571 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
2574 printSchemaLineN(p
->out
, z
, j
, "\n ");
2577 while( IsSpace(z
[i
+1]) ){ i
++; }
2582 printSchemaLine(p
->out
, z
, ";\n");
2587 if( p
->cnt
++==0 && p
->showHeader
){
2588 for(i
=0; i
<nArg
; i
++){
2589 utf8_printf(p
->out
,"%s%s",azCol
[i
],
2590 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
2593 if( azArg
==0 ) break;
2594 for(i
=0; i
<nArg
; i
++){
2596 if( z
==0 ) z
= p
->nullValue
;
2597 utf8_printf(p
->out
, "%s", z
);
2599 utf8_printf(p
->out
, "%s", p
->colSeparator
);
2601 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2607 if( p
->cnt
++==0 && p
->showHeader
){
2608 raw_printf(p
->out
,"<TR>");
2609 for(i
=0; i
<nArg
; i
++){
2610 raw_printf(p
->out
,"<TH>");
2611 output_html_string(p
->out
, azCol
[i
]);
2612 raw_printf(p
->out
,"</TH>\n");
2614 raw_printf(p
->out
,"</TR>\n");
2616 if( azArg
==0 ) break;
2617 raw_printf(p
->out
,"<TR>");
2618 for(i
=0; i
<nArg
; i
++){
2619 raw_printf(p
->out
,"<TD>");
2620 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2621 raw_printf(p
->out
,"</TD>\n");
2623 raw_printf(p
->out
,"</TR>\n");
2627 if( p
->cnt
++==0 && p
->showHeader
){
2628 for(i
=0; i
<nArg
; i
++){
2629 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
2630 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2632 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2634 if( azArg
==0 ) break;
2635 for(i
=0; i
<nArg
; i
++){
2636 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2637 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2639 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2643 setBinaryMode(p
->out
, 1);
2644 if( p
->cnt
++==0 && p
->showHeader
){
2645 for(i
=0; i
<nArg
; i
++){
2646 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
2648 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2651 for(i
=0; i
<nArg
; i
++){
2652 output_csv(p
, azArg
[i
], i
<nArg
-1);
2654 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2656 setTextMode(p
->out
, 1);
2660 if( azArg
==0 ) break;
2661 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
2662 if( p
->showHeader
){
2663 raw_printf(p
->out
,"(");
2664 for(i
=0; i
<nArg
; i
++){
2665 if( i
>0 ) raw_printf(p
->out
, ",");
2666 if( quoteChar(azCol
[i
]) ){
2667 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2669 utf8_printf(p
->out
, "%s", z
);
2672 raw_printf(p
->out
, "%s", azCol
[i
]);
2675 raw_printf(p
->out
,")");
2678 for(i
=0; i
<nArg
; i
++){
2679 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
2680 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2681 utf8_printf(p
->out
,"NULL");
2682 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2683 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2684 output_quoted_string(p
->out
, azArg
[i
]);
2686 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2688 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2689 utf8_printf(p
->out
,"%s", azArg
[i
]);
2690 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2692 double r
= sqlite3_column_double(p
->pStmt
, i
);
2694 memcpy(&ur
,&r
,sizeof(r
));
2695 if( ur
==0x7ff0000000000000LL
){
2696 raw_printf(p
->out
, "9.0e+999");
2697 }else if( ur
==0xfff0000000000000LL
){
2698 raw_printf(p
->out
, "-9.0e+999");
2700 sqlite3_int64 ir
= (sqlite3_int64
)r
;
2701 if( r
==(double)ir
){
2702 sqlite3_snprintf(50,z
,"%lld.0", ir
);
2704 sqlite3_snprintf(50,z
,"%!.20g", r
);
2706 raw_printf(p
->out
, "%s", z
);
2708 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2709 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2710 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2711 output_hex_blob(p
->out
, pBlob
, nBlob
);
2712 }else if( isNumber(azArg
[i
], 0) ){
2713 utf8_printf(p
->out
,"%s", azArg
[i
]);
2714 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2715 output_quoted_string(p
->out
, azArg
[i
]);
2717 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2720 raw_printf(p
->out
,");\n");
2724 if( azArg
==0 ) break;
2726 fputs("[{", p
->out
);
2728 fputs(",\n{", p
->out
);
2731 for(i
=0; i
<nArg
; i
++){
2732 output_json_string(p
->out
, azCol
[i
], -1);
2734 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2735 fputs("null",p
->out
);
2736 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2738 double r
= sqlite3_column_double(p
->pStmt
, i
);
2740 memcpy(&ur
,&r
,sizeof(r
));
2741 if( ur
==0x7ff0000000000000LL
){
2742 raw_printf(p
->out
, "9.0e+999");
2743 }else if( ur
==0xfff0000000000000LL
){
2744 raw_printf(p
->out
, "-9.0e+999");
2746 sqlite3_snprintf(50,z
,"%!.20g", r
);
2747 raw_printf(p
->out
, "%s", z
);
2749 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2750 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2751 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2752 output_json_string(p
->out
, pBlob
, nBlob
);
2753 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2754 output_json_string(p
->out
, azArg
[i
], -1);
2756 utf8_printf(p
->out
,"%s", azArg
[i
]);
2766 if( azArg
==0 ) break;
2767 if( p
->cnt
==0 && p
->showHeader
){
2768 for(i
=0; i
<nArg
; i
++){
2769 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2770 output_quoted_string(p
->out
, azCol
[i
]);
2772 fputs(p
->rowSeparator
, p
->out
);
2775 for(i
=0; i
<nArg
; i
++){
2776 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2777 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2778 utf8_printf(p
->out
,"NULL");
2779 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2780 output_quoted_string(p
->out
, azArg
[i
]);
2781 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2782 utf8_printf(p
->out
,"%s", azArg
[i
]);
2783 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2785 double r
= sqlite3_column_double(p
->pStmt
, i
);
2786 sqlite3_snprintf(50,z
,"%!.20g", r
);
2787 raw_printf(p
->out
, "%s", z
);
2788 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2789 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2790 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2791 output_hex_blob(p
->out
, pBlob
, nBlob
);
2792 }else if( isNumber(azArg
[i
], 0) ){
2793 utf8_printf(p
->out
,"%s", azArg
[i
]);
2795 output_quoted_string(p
->out
, azArg
[i
]);
2798 fputs(p
->rowSeparator
, p
->out
);
2802 if( p
->cnt
++==0 && p
->showHeader
){
2803 for(i
=0; i
<nArg
; i
++){
2804 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2805 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2807 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2809 if( azArg
==0 ) break;
2810 for(i
=0; i
<nArg
; i
++){
2811 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2812 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2814 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2818 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2826 ** This is the callback routine that the SQLite library
2827 ** invokes for each row of a query result.
2829 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2830 /* since we don't have type info, call the shell_callback with a NULL value */
2831 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2835 ** This is the callback routine from sqlite3_exec() that appends all
2836 ** output onto the end of a ShellText object.
2838 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2839 ShellText
*p
= (ShellText
*)pArg
;
2841 UNUSED_PARAMETER(az
);
2842 if( azArg
==0 ) return 0;
2843 if( p
->n
) appendText(p
, "|", 0);
2844 for(i
=0; i
<nArg
; i
++){
2845 if( i
) appendText(p
, ",", 0);
2846 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2852 ** Generate an appropriate SELFTEST table in the main database.
2854 static void createSelftestTable(ShellState
*p
){
2857 "SAVEPOINT selftest_init;\n"
2858 "CREATE TABLE IF NOT EXISTS selftest(\n"
2859 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2860 " op TEXT,\n" /* Operator: memo run */
2861 " cmd TEXT,\n" /* Command text */
2862 " ans TEXT\n" /* Desired answer */
2864 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2865 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2866 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2867 " 'memo','Tests generated by --init');\n"
2868 "INSERT INTO [_shell$self]\n"
2870 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2871 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2872 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2873 "FROM sqlite_schema ORDER BY 2',224));\n"
2874 "INSERT INTO [_shell$self]\n"
2876 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2877 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2878 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2880 " SELECT name FROM sqlite_schema\n"
2881 " WHERE type='table'\n"
2882 " AND name<>'selftest'\n"
2883 " AND coalesce(rootpage,0)>0\n"
2886 "INSERT INTO [_shell$self]\n"
2887 " VALUES('run','PRAGMA integrity_check','ok');\n"
2888 "INSERT INTO selftest(tno,op,cmd,ans)"
2889 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2890 "DROP TABLE [_shell$self];"
2893 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2894 sqlite3_free(zErrMsg
);
2896 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2901 ** Set the destination table field of the ShellState structure to
2902 ** the name of the table given. Escape any quote characters in the
2905 static void set_table_name(ShellState
*p
, const char *zName
){
2910 if( p
->zDestTable
){
2911 free(p
->zDestTable
);
2914 if( zName
==0 ) return;
2915 cQuote
= quoteChar(zName
);
2916 n
= strlen30(zName
);
2917 if( cQuote
) n
+= n
+2;
2918 z
= p
->zDestTable
= malloc( n
+1 );
2921 if( cQuote
) z
[n
++] = cQuote
;
2922 for(i
=0; zName
[i
]; i
++){
2924 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2926 if( cQuote
) z
[n
++] = cQuote
;
2931 ** Maybe construct two lines of text that point out the position of a
2932 ** syntax error. Return a pointer to the text, in memory obtained from
2933 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2934 ** specific token that we can point to, return an empty string.
2936 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2937 ** and should be released by the caller invoking sqlite3_free().
2939 static char *shell_error_context(const char *zSql
, sqlite3
*db
){
2947 || (iOffset
= sqlite3_error_offset(db
))<0
2948 || iOffset
>=(int)strlen(zSql
)
2950 return sqlite3_mprintf("");
2952 while( iOffset
>50 ){
2955 while( (zSql
[0]&0xc0)==0x80 ){ zSql
++; iOffset
--; }
2960 while( len
>0 && (zSql
[len
]&0xc0)==0x80 ) len
--;
2962 zCode
= sqlite3_mprintf("%.*s", len
, zSql
);
2963 shell_check_oom(zCode
);
2964 for(i
=0; zCode
[i
]; i
++){ if( IsSpace(zSql
[i
]) ) zCode
[i
] = ' '; }
2966 zMsg
= sqlite3_mprintf("\n %z\n %*s^--- error here", zCode
,iOffset
,"");
2968 zMsg
= sqlite3_mprintf("\n %z\n %*serror here ---^", zCode
,iOffset
-14,"");
2975 ** Execute a query statement that will generate SQL output. Print
2976 ** the result columns, comma-separated, on a line and then add a
2977 ** semicolon terminator to the end of that line.
2979 ** If the number of columns is 1 and that column contains text "--"
2980 ** then write the semicolon on a separate line. That way, if a
2981 ** "--" comment occurs at the end of the statement, the comment
2982 ** won't consume the semicolon terminator.
2984 static int run_table_dump_query(
2985 ShellState
*p
, /* Query context */
2986 const char *zSelect
/* SELECT statement to extract content */
2988 sqlite3_stmt
*pSelect
;
2993 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2994 if( rc
!=SQLITE_OK
|| !pSelect
){
2995 char *zContext
= shell_error_context(zSelect
, p
->db
);
2996 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n%s", rc
,
2997 sqlite3_errmsg(p
->db
), zContext
);
2998 sqlite3_free(zContext
);
2999 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
3002 rc
= sqlite3_step(pSelect
);
3003 nResult
= sqlite3_column_count(pSelect
);
3004 while( rc
==SQLITE_ROW
){
3005 z
= (const char*)sqlite3_column_text(pSelect
, 0);
3006 utf8_printf(p
->out
, "%s", z
);
3007 for(i
=1; i
<nResult
; i
++){
3008 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
3011 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
3013 raw_printf(p
->out
, "\n;\n");
3015 raw_printf(p
->out
, ";\n");
3017 rc
= sqlite3_step(pSelect
);
3019 rc
= sqlite3_finalize(pSelect
);
3020 if( rc
!=SQLITE_OK
){
3021 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
3022 sqlite3_errmsg(p
->db
));
3023 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
3029 ** Allocate space and save off string indicating current error.
3031 static char *save_err_msg(
3032 sqlite3
*db
, /* Database to query */
3033 const char *zPhase
, /* When the error occcurs */
3034 int rc
, /* Error code returned from API */
3035 const char *zSql
/* SQL string, or NULL */
3039 sqlite3_str
*pStr
= sqlite3_str_new(0);
3040 sqlite3_str_appendf(pStr
, "%s, %s", zPhase
, sqlite3_errmsg(db
));
3042 sqlite3_str_appendf(pStr
, " (%d)", rc
);
3044 zContext
= shell_error_context(zSql
, db
);
3046 sqlite3_str_appendall(pStr
, zContext
);
3047 sqlite3_free(zContext
);
3049 zErr
= sqlite3_str_finish(pStr
);
3050 shell_check_oom(zErr
);
3056 ** Attempt to display I/O stats on Linux using /proc/PID/io
3058 static void displayLinuxIoStats(FILE *out
){
3061 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
3062 in
= fopen(z
, "rb");
3064 while( fgets(z
, sizeof(z
), in
)!=0 ){
3065 static const struct {
3066 const char *zPattern
;
3069 { "rchar: ", "Bytes received by read():" },
3070 { "wchar: ", "Bytes sent to write():" },
3071 { "syscr: ", "Read() system calls:" },
3072 { "syscw: ", "Write() system calls:" },
3073 { "read_bytes: ", "Bytes read from storage:" },
3074 { "write_bytes: ", "Bytes written to storage:" },
3075 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
3078 for(i
=0; i
<ArraySize(aTrans
); i
++){
3079 int n
= strlen30(aTrans
[i
].zPattern
);
3080 if( cli_strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
3081 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
3091 ** Display a single line of status using 64-bit values.
3093 static void displayStatLine(
3094 ShellState
*p
, /* The shell context */
3095 char *zLabel
, /* Label for this one line */
3096 char *zFormat
, /* Format for the result */
3097 int iStatusCtrl
, /* Which status to display */
3098 int bReset
/* True to reset the stats */
3100 sqlite3_int64 iCur
= -1;
3101 sqlite3_int64 iHiwtr
= -1;
3104 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
3105 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
3106 if( zFormat
[i
]=='%' ) nPercent
++;
3109 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
3111 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
3113 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
3117 ** Display memory stats.
3119 static int display_stats(
3120 sqlite3
*db
, /* Database to query */
3121 ShellState
*pArg
, /* Pointer to ShellState */
3122 int bReset
/* True to reset the stats */
3127 if( pArg
==0 || pArg
->out
==0 ) return 0;
3130 if( pArg
->pStmt
&& pArg
->statsOn
==2 ){
3132 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
3134 nCol
= sqlite3_column_count(pStmt
);
3135 raw_printf(out
, "%-36s %d\n", "Number of output columns:", nCol
);
3136 for(i
=0; i
<nCol
; i
++){
3137 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
3138 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
3139 #ifndef SQLITE_OMIT_DECLTYPE
3140 sqlite3_snprintf(30, z
+x
, "declared type:");
3141 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
3143 #ifdef SQLITE_ENABLE_COLUMN_METADATA
3144 sqlite3_snprintf(30, z
+x
, "database name:");
3145 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
3146 sqlite3_snprintf(30, z
+x
, "table name:");
3147 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
3148 sqlite3_snprintf(30, z
+x
, "origin name:");
3149 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
3154 if( pArg
->statsOn
==3 ){
3156 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
,bReset
);
3157 raw_printf(pArg
->out
, "VM-steps: %d\n", iCur
);
3162 displayStatLine(pArg
, "Memory Used:",
3163 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
3164 displayStatLine(pArg
, "Number of Outstanding Allocations:",
3165 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
3166 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
3167 displayStatLine(pArg
, "Number of Pcache Pages Used:",
3168 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
3170 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
3171 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
3172 displayStatLine(pArg
, "Largest Allocation:",
3173 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
3174 displayStatLine(pArg
, "Largest Pcache Allocation:",
3175 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
3176 #ifdef YYTRACKMAXSTACKDEPTH
3177 displayStatLine(pArg
, "Deepest Parser Stack:",
3178 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
3182 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
3184 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
3185 &iCur
, &iHiwtr
, bReset
);
3186 raw_printf(pArg
->out
,
3187 "Lookaside Slots Used: %d (max %d)\n",
3189 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
3190 &iCur
, &iHiwtr
, bReset
);
3191 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
3193 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
3194 &iCur
, &iHiwtr
, bReset
);
3195 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
3197 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
3198 &iCur
, &iHiwtr
, bReset
);
3199 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
3203 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
3204 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
3207 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
3208 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
3210 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
3211 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
3213 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
3214 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
3216 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
3217 raw_printf(pArg
->out
, "Page cache spills: %d\n", iCur
);
3219 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
3220 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
3223 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
3224 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
3230 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
3232 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
3233 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
3234 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
3235 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
3236 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
3237 iHit
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_HIT
,
3239 iMiss
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_MISS
,
3241 if( iHit
|| iMiss
){
3242 raw_printf(pArg
->out
, "Bloom filter bypass taken: %d/%d\n",
3245 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
3246 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
3247 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
,bReset
);
3248 raw_printf(pArg
->out
, "Reprepare operations: %d\n", iCur
);
3249 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
3250 raw_printf(pArg
->out
, "Number of times run: %d\n", iCur
);
3251 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
3252 raw_printf(pArg
->out
, "Memory used by prepared stmt: %d\n", iCur
);
3256 displayLinuxIoStats(pArg
->out
);
3259 /* Do not remove this machine readable comment: extra-stats-output-here */
3265 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3266 static int scanStatsHeight(sqlite3_stmt
*p
, int iEntry
){
3269 sqlite3_stmt_scanstatus_v2(p
, iEntry
,
3270 SQLITE_SCANSTAT_SELECTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iPid
3277 res
= sqlite3_stmt_scanstatus_v2(p
, ii
,
3278 SQLITE_SCANSTAT_SELECTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iId
3282 sqlite3_stmt_scanstatus_v2(p
, ii
,
3283 SQLITE_SCANSTAT_PARENTID
, SQLITE_SCANSTAT_COMPLEX
, (void*)&iPid
3294 ** Display scan stats.
3296 static void display_scanstats(
3297 sqlite3
*db
, /* Database to query */
3298 ShellState
*pArg
/* Pointer to ShellState */
3300 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3301 UNUSED_PARAMETER(db
);
3302 UNUSED_PARAMETER(pArg
);
3304 static const int f
= SQLITE_SCANSTAT_COMPLEX
;
3305 sqlite3_stmt
*p
= pArg
->pStmt
;
3314 if( sqlite3_stmt_scanstatus_v2(p
,ii
,SQLITE_SCANSTAT_EXPLAIN
,f
,(void*)&z
) ){
3317 n
= strlen(z
) + scanStatsHeight(p
, ii
)*3;
3318 if( n
>nWidth
) nWidth
= n
;
3322 sqlite3_stmt_scanstatus_v2(p
, -1, SQLITE_SCANSTAT_NCYCLE
, f
, (void*)&nTotal
);
3330 const char *zName
= 0;
3334 if( sqlite3_stmt_scanstatus_v2(p
,ii
,SQLITE_SCANSTAT_EXPLAIN
,f
,(void*)&z
) ){
3337 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_EST
,f
,(void*)&rEst
);
3338 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NLOOP
,f
,(void*)&nLoop
);
3339 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NVISIT
,f
,(void*)&nRow
);
3340 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NCYCLE
,f
,(void*)&nCycle
);
3341 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_SELECTID
,f
,(void*)&iId
);
3342 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_PARENTID
,f
,(void*)&iPid
);
3343 sqlite3_stmt_scanstatus_v2(p
, ii
, SQLITE_SCANSTAT_NAME
,f
,(void*)&zName
);
3345 zText
= sqlite3_mprintf("%s", z
);
3346 if( nCycle
>=0 || nLoop
>=0 || nRow
>=0 ){
3348 if( nCycle
>=0 && nTotal
>0 ){
3349 z
= sqlite3_mprintf("%zcycles=%lld [%d%%]", z
,
3350 nCycle
, ((nCycle
*100)+nTotal
/2) / nTotal
3354 z
= sqlite3_mprintf("%z%sloops=%lld", z
, z
? " " : "", nLoop
);
3357 z
= sqlite3_mprintf("%z%srows=%lld", z
, z
? " " : "", nRow
);
3360 if( zName
&& pArg
->scanstatsOn
>1 ){
3361 double rpl
= (double)nRow
/ (double)nLoop
;
3362 z
= sqlite3_mprintf("%z rpl=%.1f est=%.1f", z
, rpl
, rEst
);
3365 zText
= sqlite3_mprintf(
3366 "% *z (%z)", -1*(nWidth
-scanStatsHeight(p
, ii
)*3), zText
, z
3370 eqp_append(pArg
, iId
, iPid
, zText
);
3371 sqlite3_free(zText
);
3374 eqp_render(pArg
, nTotal
);
3379 ** Parameter azArray points to a zero-terminated array of strings. zStr
3380 ** points to a single nul-terminated string. Return non-zero if zStr
3381 ** is equal, according to strcmp(), to any of the strings in the array.
3382 ** Otherwise, return zero.
3384 static int str_in_array(const char *zStr
, const char **azArray
){
3386 for(i
=0; azArray
[i
]; i
++){
3387 if( 0==cli_strcmp(zStr
, azArray
[i
]) ) return 1;
3393 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3394 ** and populate the ShellState.aiIndent[] array with the number of
3395 ** spaces each opcode should be indented before it is output.
3397 ** The indenting rules are:
3399 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3400 ** all opcodes that occur between the p2 jump destination and the opcode
3401 ** itself by 2 spaces.
3403 ** * Do the previous for "Return" instructions for when P2 is positive.
3404 ** See tag-20220407a in wherecode.c and vdbe.c.
3406 ** * For each "Goto", if the jump destination is earlier in the program
3407 ** and ends on one of:
3408 ** Yield SeekGt SeekLt RowSetRead Rewind
3409 ** or if the P1 parameter is one instead of zero,
3410 ** then indent all opcodes between the earlier instruction
3411 ** and "Goto" by 2 spaces.
3413 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
3414 const char *zSql
; /* The text of the SQL statement */
3415 const char *z
; /* Used to check if this is an EXPLAIN */
3416 int *abYield
= 0; /* True if op is an OP_Yield */
3417 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
3418 int iOp
; /* Index of operation in p->aiIndent[] */
3420 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3422 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3424 const char *azGoto
[] = { "Goto", 0 };
3426 /* Try to figure out if this is really an EXPLAIN statement. If this
3427 ** cannot be verified, return early. */
3428 if( sqlite3_column_count(pSql
)!=8 ){
3432 zSql
= sqlite3_sql(pSql
);
3433 if( zSql
==0 ) return;
3434 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
3435 if( sqlite3_strnicmp(z
, "explain", 7) ){
3440 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
3442 int iAddr
= sqlite3_column_int(pSql
, 0);
3443 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
3445 /* Set p2 to the P2 field of the current opcode. Then, assuming that
3446 ** p2 is an instruction address, set variable p2op to the index of that
3447 ** instruction in the aiIndent[] array. p2 and p2op may be different if
3448 ** the current instruction is part of a sub-program generated by an
3449 ** SQL trigger or foreign key. */
3450 int p2
= sqlite3_column_int(pSql
, 3);
3451 int p2op
= (p2
+ (iOp
-iAddr
));
3453 /* Grow the p->aiIndent array as required */
3456 /* Do further verfication that this is explain output. Abort if
3458 static const char *explainCols
[] = {
3459 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3461 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
3462 if( cli_strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
3464 sqlite3_reset(pSql
);
3470 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
3471 shell_check_oom(p
->aiIndent
);
3472 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
3473 shell_check_oom(abYield
);
3475 abYield
[iOp
] = str_in_array(zOp
, azYield
);
3476 p
->aiIndent
[iOp
] = 0;
3479 if( str_in_array(zOp
, azNext
) && p2op
>0 ){
3480 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3482 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
3483 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
3485 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3490 sqlite3_free(abYield
);
3491 sqlite3_reset(pSql
);
3495 ** Free the array allocated by explain_data_prepare().
3497 static void explain_data_delete(ShellState
*p
){
3498 sqlite3_free(p
->aiIndent
);
3505 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3507 static unsigned int savedSelectTrace
;
3508 static unsigned int savedWhereTrace
;
3509 static void disable_debug_trace_modes(void){
3510 unsigned int zero
= 0;
3511 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 0, &savedSelectTrace
);
3512 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &zero
);
3513 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 2, &savedWhereTrace
);
3514 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &zero
);
3516 static void restore_debug_trace_modes(void){
3517 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &savedSelectTrace
);
3518 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &savedWhereTrace
);
3521 /* Create the TEMP table used to store parameter bindings */
3522 static void bind_table_init(ShellState
*p
){
3524 int defensiveMode
= 0;
3525 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, -1, &defensiveMode
);
3526 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, 0, 0);
3527 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, -1, &wrSchema
);
3528 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, 1, 0);
3530 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3531 " key TEXT PRIMARY KEY,\n"
3535 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, wrSchema
, 0);
3536 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, defensiveMode
, 0);
3540 ** Bind parameters on a prepared statement.
3542 ** Parameter bindings are taken from a TEMP table of the form:
3544 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3547 ** No bindings occur if this table does not exist. The name of the table
3548 ** begins with "sqlite_" so that it will not collide with ordinary application
3549 ** tables. The table must be in the TEMP schema.
3551 static void bind_prepared_stmt(ShellState
*pArg
, sqlite3_stmt
*pStmt
){
3555 sqlite3_stmt
*pQ
= 0;
3557 nVar
= sqlite3_bind_parameter_count(pStmt
);
3558 if( nVar
==0 ) return; /* Nothing to do */
3559 if( sqlite3_table_column_metadata(pArg
->db
, "TEMP", "sqlite_parameters",
3560 "key", 0, 0, 0, 0, 0)!=SQLITE_OK
){
3561 rc
= SQLITE_NOTFOUND
;
3564 rc
= sqlite3_prepare_v2(pArg
->db
,
3565 "SELECT value FROM temp.sqlite_parameters"
3566 " WHERE key=?1", -1, &pQ
, 0);
3568 for(i
=1; i
<=nVar
; i
++){
3570 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
3572 sqlite3_snprintf(sizeof(zNum
),zNum
,"?%d",i
);
3575 sqlite3_bind_text(pQ
, 1, zVar
, -1, SQLITE_STATIC
);
3576 if( rc
==SQLITE_OK
&& pQ
&& sqlite3_step(pQ
)==SQLITE_ROW
){
3577 sqlite3_bind_value(pStmt
, i
, sqlite3_column_value(pQ
, 0));
3579 }else if( sqlite3_strlike("_NAN", zVar
, 0)==0 ){
3580 sqlite3_bind_double(pStmt
, i
, NAN
);
3583 }else if( sqlite3_strlike("_INF", zVar
, 0)==0 ){
3584 sqlite3_bind_double(pStmt
, i
, INFINITY
);
3587 sqlite3_bind_null(pStmt
, i
);
3591 sqlite3_finalize(pQ
);
3595 ** UTF8 box-drawing characters. Imagine box lines like this:
3603 ** Each box characters has between 2 and 4 of the lines leading from
3604 ** the center. The characters are here identified by the numbers of
3605 ** their corresponding lines.
3607 #define BOX_24 "\342\224\200" /* U+2500 --- */
3608 #define BOX_13 "\342\224\202" /* U+2502 | */
3609 #define BOX_23 "\342\224\214" /* U+250c ,- */
3610 #define BOX_34 "\342\224\220" /* U+2510 -, */
3611 #define BOX_12 "\342\224\224" /* U+2514 '- */
3612 #define BOX_14 "\342\224\230" /* U+2518 -' */
3613 #define BOX_123 "\342\224\234" /* U+251c |- */
3614 #define BOX_134 "\342\224\244" /* U+2524 -| */
3615 #define BOX_234 "\342\224\254" /* U+252c -,- */
3616 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3617 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3619 /* Draw horizontal line N characters long using unicode box
3622 static void print_box_line(FILE *out
, int N
){
3623 const char zDash
[] =
3624 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3625 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
;
3626 const int nDash
= sizeof(zDash
) - 1;
3629 utf8_printf(out
, zDash
);
3632 utf8_printf(out
, "%.*s", N
, zDash
);
3636 ** Draw a horizontal separator for a MODE_Box table.
3638 static void print_box_row_separator(
3647 utf8_printf(p
->out
, "%s", zSep1
);
3648 print_box_line(p
->out
, p
->actualWidth
[0]+2);
3649 for(i
=1; i
<nArg
; i
++){
3650 utf8_printf(p
->out
, "%s", zSep2
);
3651 print_box_line(p
->out
, p
->actualWidth
[i
]+2);
3653 utf8_printf(p
->out
, "%s", zSep3
);
3655 fputs("\n", p
->out
);
3659 ** z[] is a line of text that is to be displayed the .mode box or table or
3660 ** similar tabular formats. z[] might contain control characters such
3661 ** as \n, \t, \f, or \r.
3663 ** Compute characters to display on the first line of z[]. Stop at the
3664 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3665 ** from malloc()) of that first line, which caller should free sometime.
3666 ** Write anything to display on the next line into *pzTail. If this is
3667 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3669 static char *translateForDisplayAndDup(
3670 const unsigned char *z
, /* Input text to be transformed */
3671 const unsigned char **pzTail
, /* OUT: Tail of the input for next line */
3672 int mxWidth
, /* Max width. 0 means no limit */
3673 u8 bWordWrap
/* If true, avoid breaking mid-word */
3675 int i
; /* Input bytes consumed */
3676 int j
; /* Output bytes generated */
3677 int k
; /* Input bytes to be displayed */
3678 int n
; /* Output column number */
3679 unsigned char *zOut
; /* Output text */
3685 if( mxWidth
<0 ) mxWidth
= -mxWidth
;
3686 if( mxWidth
==0 ) mxWidth
= 1000000;
3691 do{ i
++; j
++; }while( (z
[i
]&0xc0)==0x80 );
3698 }while( (n
&7)!=0 && n
<mxWidth
);
3704 if( n
>=mxWidth
&& bWordWrap
){
3705 /* Perhaps try to back up to a better place to break the line */
3706 for(k
=i
; k
>i
/2; k
--){
3707 if( isspace(z
[k
-1]) ) break;
3710 for(k
=i
; k
>i
/2; k
--){
3711 if( isalnum(z
[k
-1])!=isalnum(z
[k
]) && (z
[k
]&0xc0)!=0x80 ) break;
3718 while( z
[i
]==' ' ) i
++;
3723 if( n
>=mxWidth
&& z
[i
]>=' ' ){
3725 }else if( z
[i
]=='\r' && z
[i
+1]=='\n' ){
3726 *pzTail
= z
[i
+2] ? &z
[i
+2] : 0;
3727 }else if( z
[i
]==0 || z
[i
+1]==0 ){
3732 zOut
= malloc( j
+1 );
3733 shell_check_oom(zOut
);
3738 do{ zOut
[j
++] = z
[i
++]; }while( (z
[i
]&0xc0)==0x80 );
3745 }while( (n
&7)!=0 && n
<mxWidth
);
3755 /* Extract the value of the i-th current column for pStmt as an SQL literal
3756 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3759 static char *quoted_column(sqlite3_stmt
*pStmt
, int i
){
3760 switch( sqlite3_column_type(pStmt
, i
) ){
3762 return sqlite3_mprintf("NULL");
3764 case SQLITE_INTEGER
:
3765 case SQLITE_FLOAT
: {
3766 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt
,i
));
3769 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt
,i
));
3773 sqlite3_str
*pStr
= sqlite3_str_new(0);
3774 const unsigned char *a
= sqlite3_column_blob(pStmt
,i
);
3775 int n
= sqlite3_column_bytes(pStmt
,i
);
3776 sqlite3_str_append(pStr
, "x'", 2);
3778 sqlite3_str_appendf(pStr
, "%02x", a
[j
]);
3780 sqlite3_str_append(pStr
, "'", 1);
3781 return sqlite3_str_finish(pStr
);
3784 return 0; /* Not reached */
3788 ** Run a prepared statement and output the result in one of the
3789 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3792 ** This is different from ordinary exec_prepared_stmt() in that
3793 ** it has to run the entire query and gather the results into memory
3794 ** first, in order to determine column widths, before providing
3797 static void exec_prepared_stmt_columnar(
3798 ShellState
*p
, /* Pointer to ShellState */
3799 sqlite3_stmt
*pStmt
/* Statment to run */
3801 sqlite3_int64 nRow
= 0;
3804 sqlite3_int64 nAlloc
= 0;
3806 const unsigned char *uz
;
3808 char **azQuoted
= 0;
3810 sqlite3_int64 i
, nData
;
3811 int j
, nTotal
, w
, n
;
3812 const char *colSep
= 0;
3813 const char *rowSep
= 0;
3814 const unsigned char **azNextLine
= 0;
3816 int bMultiLineRowExists
= 0;
3817 int bw
= p
->cmOpts
.bWordWrap
;
3818 const char *zEmpty
= "";
3819 const char *zShowNull
= p
->nullValue
;
3821 rc
= sqlite3_step(pStmt
);
3822 if( rc
!=SQLITE_ROW
) return;
3823 nColumn
= sqlite3_column_count(pStmt
);
3825 if( nAlloc
<=0 ) nAlloc
= 1;
3826 azData
= sqlite3_malloc64( nAlloc
*sizeof(char*) );
3827 shell_check_oom(azData
);
3828 azNextLine
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3829 shell_check_oom(azNextLine
);
3830 memset((void*)azNextLine
, 0, nColumn
*sizeof(char*) );
3831 if( p
->cmOpts
.bQuote
){
3832 azQuoted
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3833 shell_check_oom(azQuoted
);
3834 memset(azQuoted
, 0, nColumn
*sizeof(char*) );
3836 abRowDiv
= sqlite3_malloc64( nAlloc
/nColumn
);
3837 shell_check_oom(abRowDiv
);
3838 if( nColumn
>p
->nWidth
){
3839 p
->colWidth
= realloc(p
->colWidth
, (nColumn
+1)*2*sizeof(int));
3840 shell_check_oom(p
->colWidth
);
3841 for(i
=p
->nWidth
; i
<nColumn
; i
++) p
->colWidth
[i
] = 0;
3842 p
->nWidth
= nColumn
;
3843 p
->actualWidth
= &p
->colWidth
[nColumn
];
3845 memset(p
->actualWidth
, 0, nColumn
*sizeof(int));
3846 for(i
=0; i
<nColumn
; i
++){
3849 p
->actualWidth
[i
] = w
;
3851 for(i
=0; i
<nColumn
; i
++){
3852 const unsigned char *zNotUsed
;
3853 int wx
= p
->colWidth
[i
];
3855 wx
= p
->cmOpts
.iWrap
;
3857 if( wx
<0 ) wx
= -wx
;
3858 uz
= (const unsigned char*)sqlite3_column_name(pStmt
,i
);
3859 if( uz
==0 ) uz
= (u8
*)"";
3860 azData
[i
] = translateForDisplayAndDup(uz
, &zNotUsed
, wx
, bw
);
3863 int useNextLine
= bNextLine
;
3865 if( (nRow
+2)*nColumn
>= nAlloc
){
3867 azData
= sqlite3_realloc64(azData
, nAlloc
*sizeof(char*));
3868 shell_check_oom(azData
);
3869 abRowDiv
= sqlite3_realloc64(abRowDiv
, nAlloc
/nColumn
);
3870 shell_check_oom(abRowDiv
);
3874 for(i
=0; i
<nColumn
; i
++){
3875 int wx
= p
->colWidth
[i
];
3877 wx
= p
->cmOpts
.iWrap
;
3879 if( wx
<0 ) wx
= -wx
;
3882 if( uz
==0 ) uz
= (u8
*)zEmpty
;
3883 }else if( p
->cmOpts
.bQuote
){
3884 sqlite3_free(azQuoted
[i
]);
3885 azQuoted
[i
] = quoted_column(pStmt
,i
);
3886 uz
= (const unsigned char*)azQuoted
[i
];
3888 uz
= (const unsigned char*)sqlite3_column_text(pStmt
,i
);
3889 if( uz
==0 ) uz
= (u8
*)zShowNull
;
3891 azData
[nRow
*nColumn
+ i
]
3892 = translateForDisplayAndDup(uz
, &azNextLine
[i
], wx
, bw
);
3893 if( azNextLine
[i
] ){
3895 abRowDiv
[nRow
-1] = 0;
3896 bMultiLineRowExists
= 1;
3899 }while( bNextLine
|| sqlite3_step(pStmt
)==SQLITE_ROW
);
3900 nTotal
= nColumn
*(nRow
+1);
3901 for(i
=0; i
<nTotal
; i
++){
3903 if( z
==0 ) z
= (char*)zEmpty
;
3906 if( n
>p
->actualWidth
[j
] ) p
->actualWidth
[j
] = n
;
3908 if( seenInterrupt
) goto columnar_end
;
3909 if( nColumn
==0 ) goto columnar_end
;
3914 if( p
->showHeader
){
3915 for(i
=0; i
<nColumn
; i
++){
3916 w
= p
->actualWidth
[i
];
3917 if( p
->colWidth
[i
]<0 ) w
= -w
;
3918 utf8_width_print(p
->out
, w
, azData
[i
]);
3919 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3921 for(i
=0; i
<nColumn
; i
++){
3922 print_dashes(p
->out
, p
->actualWidth
[i
]);
3923 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3931 print_row_separator(p
, nColumn
, "+");
3932 fputs("| ", p
->out
);
3933 for(i
=0; i
<nColumn
; i
++){
3934 w
= p
->actualWidth
[i
];
3935 n
= strlenChar(azData
[i
]);
3936 utf8_printf(p
->out
, "%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3937 fputs(i
==nColumn
-1?" |\n":" | ", p
->out
);
3939 print_row_separator(p
, nColumn
, "+");
3942 case MODE_Markdown
: {
3945 fputs("| ", p
->out
);
3946 for(i
=0; i
<nColumn
; i
++){
3947 w
= p
->actualWidth
[i
];
3948 n
= strlenChar(azData
[i
]);
3949 utf8_printf(p
->out
, "%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3950 fputs(i
==nColumn
-1?" |\n":" | ", p
->out
);
3952 print_row_separator(p
, nColumn
, "|");
3956 colSep
= " " BOX_13
" ";
3957 rowSep
= " " BOX_13
"\n";
3958 print_box_row_separator(p
, nColumn
, BOX_23
, BOX_234
, BOX_34
);
3959 utf8_printf(p
->out
, BOX_13
" ");
3960 for(i
=0; i
<nColumn
; i
++){
3961 w
= p
->actualWidth
[i
];
3962 n
= strlenChar(azData
[i
]);
3963 utf8_printf(p
->out
, "%*s%s%*s%s",
3964 (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "",
3965 i
==nColumn
-1?" "BOX_13
"\n":" "BOX_13
" ");
3967 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3971 for(i
=nColumn
, j
=0; i
<nTotal
; i
++, j
++){
3972 if( j
==0 && p
->cMode
!=MODE_Column
){
3973 utf8_printf(p
->out
, "%s", p
->cMode
==MODE_Box
?BOX_13
" ":"| ");
3976 if( z
==0 ) z
= p
->nullValue
;
3977 w
= p
->actualWidth
[j
];
3978 if( p
->colWidth
[j
]<0 ) w
= -w
;
3979 utf8_width_print(p
->out
, w
, z
);
3981 utf8_printf(p
->out
, "%s", rowSep
);
3982 if( bMultiLineRowExists
&& abRowDiv
[i
/nColumn
-1] && i
+1<nTotal
){
3983 if( p
->cMode
==MODE_Table
){
3984 print_row_separator(p
, nColumn
, "+");
3985 }else if( p
->cMode
==MODE_Box
){
3986 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3987 }else if( p
->cMode
==MODE_Column
){
3988 raw_printf(p
->out
, "\n");
3992 if( seenInterrupt
) goto columnar_end
;
3994 utf8_printf(p
->out
, "%s", colSep
);
3997 if( p
->cMode
==MODE_Table
){
3998 print_row_separator(p
, nColumn
, "+");
3999 }else if( p
->cMode
==MODE_Box
){
4000 print_box_row_separator(p
, nColumn
, BOX_12
, BOX_124
, BOX_14
);
4003 if( seenInterrupt
){
4004 utf8_printf(p
->out
, "Interrupt\n");
4006 nData
= (nRow
+1)*nColumn
;
4007 for(i
=0; i
<nData
; i
++){
4009 if( z
!=zEmpty
&& z
!=zShowNull
) free(azData
[i
]);
4011 sqlite3_free(azData
);
4012 sqlite3_free((void*)azNextLine
);
4013 sqlite3_free(abRowDiv
);
4015 for(i
=0; i
<nColumn
; i
++) sqlite3_free(azQuoted
[i
]);
4016 sqlite3_free(azQuoted
);
4021 ** Run a prepared statement
4023 static void exec_prepared_stmt(
4024 ShellState
*pArg
, /* Pointer to ShellState */
4025 sqlite3_stmt
*pStmt
/* Statment to run */
4028 sqlite3_uint64 nRow
= 0;
4030 if( pArg
->cMode
==MODE_Column
4031 || pArg
->cMode
==MODE_Table
4032 || pArg
->cMode
==MODE_Box
4033 || pArg
->cMode
==MODE_Markdown
4035 exec_prepared_stmt_columnar(pArg
, pStmt
);
4039 /* perform the first step. this will tell us if we
4040 ** have a result set or not and how wide it is.
4042 rc
= sqlite3_step(pStmt
);
4043 /* if we have a result set... */
4044 if( SQLITE_ROW
== rc
){
4045 /* allocate space for col name ptr, value ptr, and type */
4046 int nCol
= sqlite3_column_count(pStmt
);
4047 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
4049 shell_out_of_memory();
4051 char **azCols
= (char **)pData
; /* Names of result columns */
4052 char **azVals
= &azCols
[nCol
]; /* Results */
4053 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
4055 assert(sizeof(int) <= sizeof(char *));
4056 /* save off ptrs to column names */
4057 for(i
=0; i
<nCol
; i
++){
4058 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
4062 /* extract the data and data types */
4063 for(i
=0; i
<nCol
; i
++){
4064 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
4067 && (pArg
->cMode
==MODE_Insert
|| pArg
->cMode
==MODE_Quote
)
4071 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
4073 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
4075 break; /* from for */
4079 /* if data and types extracted successfully... */
4080 if( SQLITE_ROW
== rc
){
4081 /* call the supplied callback with the result row data */
4082 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
4085 rc
= sqlite3_step(pStmt
);
4088 } while( SQLITE_ROW
== rc
);
4089 sqlite3_free(pData
);
4090 if( pArg
->cMode
==MODE_Json
){
4091 fputs("]\n", pArg
->out
);
4092 }else if( pArg
->cMode
==MODE_Count
){
4094 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%llu row%s\n",
4095 nRow
, nRow
!=1 ? "s" : "");
4102 #ifndef SQLITE_OMIT_VIRTUALTABLE
4104 ** This function is called to process SQL if the previous shell command
4105 ** was ".expert". It passes the SQL in the second argument directly to
4106 ** the sqlite3expert object.
4108 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4109 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4110 ** an English language error message. It is the responsibility of the
4111 ** caller to eventually free this buffer using sqlite3_free().
4113 static int expertHandleSQL(
4118 assert( pState
->expert
.pExpert
);
4119 assert( pzErr
==0 || *pzErr
==0 );
4120 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
4124 ** This function is called either to silently clean up the object
4125 ** created by the ".expert" command (if bCancel==1), or to generate a
4126 ** report from it and then clean it up (if bCancel==0).
4128 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
4129 ** code. In this case, (*pzErr) may be set to point to a buffer containing
4130 ** an English language error message. It is the responsibility of the
4131 ** caller to eventually free this buffer using sqlite3_free().
4133 static int expertFinish(
4139 sqlite3expert
*p
= pState
->expert
.pExpert
;
4141 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
4143 FILE *out
= pState
->out
;
4144 int bVerbose
= pState
->expert
.bVerbose
;
4146 rc
= sqlite3_expert_analyze(p
, pzErr
);
4147 if( rc
==SQLITE_OK
){
4148 int nQuery
= sqlite3_expert_count(p
);
4152 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
4153 raw_printf(out
, "-- Candidates -----------------------------\n");
4154 raw_printf(out
, "%s\n", zCand
);
4156 for(i
=0; i
<nQuery
; i
++){
4157 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
4158 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
4159 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
4160 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
4162 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
4163 raw_printf(out
, "%s\n\n", zSql
);
4165 raw_printf(out
, "%s\n", zIdx
);
4166 raw_printf(out
, "%s\n", zEQP
);
4170 sqlite3_expert_destroy(p
);
4171 pState
->expert
.pExpert
= 0;
4176 ** Implementation of ".expert" dot command.
4178 static int expertDotCommand(
4179 ShellState
*pState
, /* Current shell tool state */
4180 char **azArg
, /* Array of arguments passed to dot command */
4181 int nArg
/* Number of entries in azArg[] */
4188 assert( pState
->expert
.pExpert
==0 );
4189 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
4191 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
4194 if( z
[0]=='-' && z
[1]=='-' ) z
++;
4196 if( n
>=2 && 0==cli_strncmp(z
, "-verbose", n
) ){
4197 pState
->expert
.bVerbose
= 1;
4199 else if( n
>=2 && 0==cli_strncmp(z
, "-sample", n
) ){
4201 raw_printf(stderr
, "option requires an argument: %s\n", z
);
4204 iSample
= (int)integerValue(azArg
[++i
]);
4205 if( iSample
<0 || iSample
>100 ){
4206 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
4212 raw_printf(stderr
, "unknown option: %s\n", z
);
4217 if( rc
==SQLITE_OK
){
4218 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
4219 if( pState
->expert
.pExpert
==0 ){
4220 raw_printf(stderr
, "sqlite3_expert_new: %s\n",
4221 zErr
? zErr
: "out of memory");
4224 sqlite3_expert_config(
4225 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
4233 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
4236 ** Execute a statement or set of statements. Print
4237 ** any result rows/columns depending on the current mode
4238 ** set via the supplied callback.
4240 ** This is very similar to SQLite's built-in sqlite3_exec()
4241 ** function except it takes a slightly different callback
4242 ** and callback data argument.
4244 static int shell_exec(
4245 ShellState
*pArg
, /* Pointer to ShellState */
4246 const char *zSql
, /* SQL to be evaluated */
4247 char **pzErrMsg
/* Error msg written here */
4249 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
4250 int rc
= SQLITE_OK
; /* Return Code */
4252 const char *zLeftover
; /* Tail of unprocessed SQL */
4253 sqlite3
*db
= pArg
->db
;
4259 #ifndef SQLITE_OMIT_VIRTUALTABLE
4260 if( pArg
->expert
.pExpert
){
4261 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
4262 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
4266 while( zSql
[0] && (SQLITE_OK
== rc
) ){
4267 static const char *zStmtSql
;
4268 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
4269 if( SQLITE_OK
!= rc
){
4271 *pzErrMsg
= save_err_msg(db
, "in prepare", rc
, zSql
);
4275 /* this happens for a comment or white-space */
4277 while( IsSpace(zSql
[0]) ) zSql
++;
4280 zStmtSql
= sqlite3_sql(pStmt
);
4281 if( zStmtSql
==0 ) zStmtSql
= "";
4282 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
4284 /* save off the prepared statment handle and reset row count */
4286 pArg
->pStmt
= pStmt
;
4290 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
4291 if( pArg
&& pArg
->autoEQP
&& sqlite3_stmt_isexplain(pStmt
)==0 ){
4292 sqlite3_stmt
*pExplain
;
4295 disable_debug_trace_modes();
4296 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
4297 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
4298 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
4300 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
4301 shell_check_oom(zEQP
);
4302 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4303 if( rc
==SQLITE_OK
){
4304 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
4305 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
4306 int iEqpId
= sqlite3_column_int(pExplain
, 0);
4307 int iParentId
= sqlite3_column_int(pExplain
, 1);
4308 if( zEQPLine
==0 ) zEQPLine
= "";
4309 if( zEQPLine
[0]=='-' ) eqp_render(pArg
, 0);
4310 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
4312 eqp_render(pArg
, 0);
4314 sqlite3_finalize(pExplain
);
4316 if( pArg
->autoEQP
>=AUTOEQP_full
){
4317 /* Also do an EXPLAIN for ".eqp full" mode */
4318 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
4319 shell_check_oom(zEQP
);
4320 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4321 if( rc
==SQLITE_OK
){
4322 pArg
->cMode
= MODE_Explain
;
4323 explain_data_prepare(pArg
, pExplain
);
4324 exec_prepared_stmt(pArg
, pExplain
);
4325 explain_data_delete(pArg
);
4327 sqlite3_finalize(pExplain
);
4330 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
4331 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
4332 /* Reprepare pStmt before reactiving trace modes */
4333 sqlite3_finalize(pStmt
);
4334 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
4335 if( pArg
) pArg
->pStmt
= pStmt
;
4337 restore_debug_trace_modes();
4341 pArg
->cMode
= pArg
->mode
;
4342 if( pArg
->autoExplain
){
4343 if( sqlite3_stmt_isexplain(pStmt
)==1 ){
4344 pArg
->cMode
= MODE_Explain
;
4346 if( sqlite3_stmt_isexplain(pStmt
)==2 ){
4347 pArg
->cMode
= MODE_EQP
;
4351 /* If the shell is currently in ".explain" mode, gather the extra
4352 ** data required to add indents to the output.*/
4353 if( pArg
->cMode
==MODE_Explain
){
4354 explain_data_prepare(pArg
, pStmt
);
4358 bind_prepared_stmt(pArg
, pStmt
);
4359 exec_prepared_stmt(pArg
, pStmt
);
4360 explain_data_delete(pArg
);
4361 eqp_render(pArg
, 0);
4363 /* print usage stats if stats on */
4364 if( pArg
&& pArg
->statsOn
){
4365 display_stats(db
, pArg
, 0);
4368 /* print loop-counters if required */
4369 if( pArg
&& pArg
->scanstatsOn
){
4370 display_scanstats(db
, pArg
);
4373 /* Finalize the statement just executed. If this fails, save a
4374 ** copy of the error message. Otherwise, set zSql to point to the
4375 ** next statement to execute. */
4376 rc2
= sqlite3_finalize(pStmt
);
4377 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
4378 if( rc
==SQLITE_OK
){
4380 while( IsSpace(zSql
[0]) ) zSql
++;
4381 }else if( pzErrMsg
){
4382 *pzErrMsg
= save_err_msg(db
, "stepping", rc
, 0);
4385 /* clear saved stmt handle */
4396 ** Release memory previously allocated by tableColumnList().
4398 static void freeColumnList(char **azCol
){
4400 for(i
=1; azCol
[i
]; i
++){
4401 sqlite3_free(azCol
[i
]);
4403 /* azCol[0] is a static string */
4404 sqlite3_free(azCol
);
4408 ** Return a list of pointers to strings which are the names of all
4409 ** columns in table zTab. The memory to hold the names is dynamically
4410 ** allocated and must be released by the caller using a subsequent call
4411 ** to freeColumnList().
4413 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4414 ** value that needs to be preserved, then azCol[0] is filled in with the
4415 ** name of the rowid column.
4417 ** The first regular column in the table is azCol[1]. The list is terminated
4418 ** by an entry with azCol[i]==0.
4420 static char **tableColumnList(ShellState
*p
, const char *zTab
){
4422 sqlite3_stmt
*pStmt
;
4426 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
4427 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
4428 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
4431 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
4432 shell_check_oom(zSql
);
4433 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4436 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4437 if( nCol
>=nAlloc
-2 ){
4438 nAlloc
= nAlloc
*2 + nCol
+ 10;
4439 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
4440 shell_check_oom(azCol
);
4442 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
4443 shell_check_oom(azCol
[nCol
]);
4444 if( sqlite3_column_int(pStmt
, 5) ){
4447 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
4456 sqlite3_finalize(pStmt
);
4457 if( azCol
==0 ) return 0;
4461 /* The decision of whether or not a rowid really needs to be preserved
4462 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4463 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4464 ** rowids on tables where the rowid is inaccessible because there are other
4465 ** columns in the table named "rowid", "_rowid_", and "oid".
4467 if( preserveRowid
&& isIPK
){
4468 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4469 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
4470 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4471 ** ROWID aliases. To distinguish these cases, check to see if
4472 ** there is a "pk" entry in "PRAGMA index_list". There will be
4473 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4475 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4476 " WHERE origin='pk'", zTab
);
4477 shell_check_oom(zSql
);
4478 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4481 freeColumnList(azCol
);
4484 rc
= sqlite3_step(pStmt
);
4485 sqlite3_finalize(pStmt
);
4486 preserveRowid
= rc
==SQLITE_ROW
;
4488 if( preserveRowid
){
4489 /* Only preserve the rowid if we can find a name to use for the
4491 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
4494 for(i
=1; i
<=nCol
; i
++){
4495 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
4498 /* At this point, we know that azRowid[j] is not the name of any
4499 ** ordinary column in the table. Verify that azRowid[j] is a valid
4500 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4501 ** tables will fail this last check */
4502 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
4503 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
4512 ** Toggle the reverse_unordered_selects setting.
4514 static void toggleSelectOrder(sqlite3
*db
){
4515 sqlite3_stmt
*pStmt
= 0;
4518 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
4519 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
4520 iSetting
= sqlite3_column_int(pStmt
, 0);
4522 sqlite3_finalize(pStmt
);
4523 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
4524 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
4525 sqlite3_exec(db
, zStmt
, 0, 0, 0);
4529 ** This is a different callback routine used for dumping the database.
4530 ** Each row received by this callback consists of a table name,
4531 ** the table type ("index" or "table") and SQL to create the table.
4532 ** This routine should print text sufficient to recreate the table.
4534 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
4539 ShellState
*p
= (ShellState
*)pArg
;
4543 UNUSED_PARAMETER(azNotUsed
);
4544 if( nArg
!=3 || azArg
==0 ) return 0;
4548 if( zTable
==0 ) return 0;
4549 if( zType
==0 ) return 0;
4550 dataOnly
= (p
->shellFlgs
& SHFLG_DumpDataOnly
)!=0;
4551 noSys
= (p
->shellFlgs
& SHFLG_DumpNoSys
)!=0;
4553 if( cli_strcmp(zTable
, "sqlite_sequence")==0 && !noSys
){
4554 if( !dataOnly
) raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
4555 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 && !noSys
){
4556 if( !dataOnly
) raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
4557 }else if( cli_strncmp(zTable
, "sqlite_", 7)==0 ){
4559 }else if( dataOnly
){
4561 }else if( cli_strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
4563 if( !p
->writableSchema
){
4564 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
4565 p
->writableSchema
= 1;
4567 zIns
= sqlite3_mprintf(
4568 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4569 "VALUES('table','%q','%q',0,'%q');",
4570 zTable
, zTable
, zSql
);
4571 shell_check_oom(zIns
);
4572 utf8_printf(p
->out
, "%s\n", zIns
);
4576 printSchemaLine(p
->out
, zSql
, ";\n");
4579 if( cli_strcmp(zType
, "table")==0 ){
4584 char *savedDestTable
;
4587 azCol
= tableColumnList(p
, zTable
);
4593 /* Always quote the table name, even if it appears to be pure ascii,
4594 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4596 appendText(&sTable
, zTable
, quoteChar(zTable
));
4597 /* If preserving the rowid, add a column list after the table name.
4598 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4599 ** instead of the usual "INSERT INTO tab VALUES(...)".
4602 appendText(&sTable
, "(", 0);
4603 appendText(&sTable
, azCol
[0], 0);
4604 for(i
=1; azCol
[i
]; i
++){
4605 appendText(&sTable
, ",", 0);
4606 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
4608 appendText(&sTable
, ")", 0);
4611 /* Build an appropriate SELECT statement */
4613 appendText(&sSelect
, "SELECT ", 0);
4615 appendText(&sSelect
, azCol
[0], 0);
4616 appendText(&sSelect
, ",", 0);
4618 for(i
=1; azCol
[i
]; i
++){
4619 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
4621 appendText(&sSelect
, ",", 0);
4624 freeColumnList(azCol
);
4625 appendText(&sSelect
, " FROM ", 0);
4626 appendText(&sSelect
, zTable
, quoteChar(zTable
));
4628 savedDestTable
= p
->zDestTable
;
4629 savedMode
= p
->mode
;
4630 p
->zDestTable
= sTable
.z
;
4631 p
->mode
= p
->cMode
= MODE_Insert
;
4632 rc
= shell_exec(p
, sSelect
.z
, 0);
4633 if( (rc
&0xff)==SQLITE_CORRUPT
){
4634 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
4635 toggleSelectOrder(p
->db
);
4636 shell_exec(p
, sSelect
.z
, 0);
4637 toggleSelectOrder(p
->db
);
4639 p
->zDestTable
= savedDestTable
;
4640 p
->mode
= savedMode
;
4649 ** Run zQuery. Use dump_callback() as the callback routine so that
4650 ** the contents of the query are output as SQL statements.
4652 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4653 ** "ORDER BY rowid DESC" to the end.
4655 static int run_schema_dump_query(
4661 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
4662 if( rc
==SQLITE_CORRUPT
){
4664 int len
= strlen30(zQuery
);
4665 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
4667 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
4671 zQ2
= malloc( len
+100 );
4672 if( zQ2
==0 ) return rc
;
4673 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
4674 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
4676 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
4678 rc
= SQLITE_CORRUPT
;
4687 ** Text of help messages.
4689 ** The help text for each individual command begins with a line that starts
4690 ** with ".". Subsequent lines are supplemental information.
4692 ** There must be two or more spaces between the end of the command and the
4693 ** start of the description of what that command does.
4695 static const char *(azHelp
[]) = {
4696 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4697 && !defined(SQLITE_SHELL_FIDDLE)
4698 ".archive ... Manage SQL archives",
4699 " Each command must have exactly one of the following options:",
4700 " -c, --create Create a new archive",
4701 " -u, --update Add or update files with changed mtime",
4702 " -i, --insert Like -u but always add even if unchanged",
4703 " -r, --remove Remove files from archive",
4704 " -t, --list List contents of archive",
4705 " -x, --extract Extract files from archive",
4706 " Optional arguments:",
4707 " -v, --verbose Print each filename as it is processed",
4708 " -f FILE, --file FILE Use archive FILE (default is current db)",
4709 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4710 " -C DIR, --directory DIR Read/extract files from directory DIR",
4711 " -g, --glob Use glob matching for names in archive",
4712 " -n, --dryrun Show the SQL that would have occurred",
4714 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4715 " .ar -tf ARCHIVE # List members of ARCHIVE",
4716 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4718 " http://sqlite.org/cli.html#sqlite_archive_support",
4720 #ifndef SQLITE_OMIT_AUTHORIZATION
4721 ".auth ON|OFF Show authorizer callbacks",
4723 #ifndef SQLITE_SHELL_FIDDLE
4724 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4726 " --append Use the appendvfs",
4727 " --async Write to FILE without journal and fsync()",
4729 ".bail on|off Stop after hitting an error. Default OFF",
4730 ".binary on|off Turn binary output on or off. Default OFF",
4731 #ifndef SQLITE_SHELL_FIDDLE
4732 ".cd DIRECTORY Change the working directory to DIRECTORY",
4734 ".changes on|off Show number of rows changed by SQL",
4735 #ifndef SQLITE_SHELL_FIDDLE
4736 ".check GLOB Fail if output since .testcase does not match",
4737 ".clone NEWDB Clone data into NEWDB from the existing database",
4739 ".connection [close] [#] Open or close an auxiliary database connection",
4740 ".databases List names and files of attached databases",
4741 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4742 #if SQLITE_SHELL_HAVE_RECOVER
4743 ".dbinfo ?DB? Show status information about the database",
4745 ".dump ?OBJECTS? Render database content as SQL",
4747 " --data-only Output only INSERT statements",
4748 " --newlines Allow unescaped newline characters in output",
4749 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4750 " --preserve-rowids Include ROWID values in the output",
4751 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4752 " Additional LIKE patterns can be given in subsequent arguments",
4753 ".echo on|off Turn command echo on or off",
4754 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4757 " test Show raw EXPLAIN QUERY PLAN output",
4758 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4760 " trigger Like \"full\" but also show trigger bytecode",
4761 #ifndef SQLITE_SHELL_FIDDLE
4762 ".excel Display the output of next command in spreadsheet",
4763 " --bom Put a UTF8 byte-order mark on intermediate file",
4765 #ifndef SQLITE_SHELL_FIDDLE
4766 ".exit ?CODE? Exit this program with return-code CODE",
4768 ".expert EXPERIMENTAL. Suggest indexes for queries",
4769 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4770 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4771 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4772 " --help Show CMD details",
4773 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4774 ".headers on|off Turn display of headers on or off",
4775 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4776 #ifndef SQLITE_SHELL_FIDDLE
4777 ".import FILE TABLE Import data from FILE into TABLE",
4779 " --ascii Use \\037 and \\036 as column and row separators",
4780 " --csv Use , and \\n as column and row separators",
4781 " --skip N Skip the first N rows of input",
4782 " --schema S Target table to be S.TABLE",
4783 " -v \"Verbose\" - increase auxiliary output",
4785 " * If TABLE does not exist, it is created. The first row of input",
4786 " determines the column names.",
4787 " * If neither --csv or --ascii are used, the input mode is derived",
4788 " from the \".mode\" output mode",
4789 " * If FILE begins with \"|\" then it is a command that generates the",
4792 #ifndef SQLITE_OMIT_TEST_CONTROL
4793 ",imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4795 ".indexes ?TABLE? Show names of indexes",
4796 " If TABLE is specified, only show indexes for",
4797 " tables matching TABLE using the LIKE operator.",
4798 #ifdef SQLITE_ENABLE_IOTRACE
4799 ",iotrace FILE Enable I/O diagnostic logging to FILE",
4801 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4802 ".lint OPTIONS Report potential schema issues.",
4804 " fkey-indexes Find missing foreign key indexes",
4805 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4806 ".load FILE ?ENTRY? Load an extension library",
4808 #if !defined(SQLITE_SHELL_FIDDLE)
4809 ".log FILE|on|off Turn logging on or off. FILE can be stderr/stdout",
4811 ".log on|off Turn logging on or off.",
4813 ".mode MODE ?OPTIONS? Set output mode",
4815 " ascii Columns/rows delimited by 0x1F and 0x1E",
4816 " box Tables using unicode box-drawing characters",
4817 " csv Comma-separated values",
4818 " column Output in columns. (See .width)",
4819 " html HTML <table> code",
4820 " insert SQL insert statements for TABLE",
4821 " json Results in a JSON array",
4822 " line One value per line",
4823 " list Values delimited by \"|\"",
4824 " markdown Markdown table format",
4825 " qbox Shorthand for \"box --wrap 60 --quote\"",
4826 " quote Escape answers as for SQL",
4827 " table ASCII-art table",
4828 " tabs Tab-separated values",
4829 " tcl TCL list elements",
4830 " OPTIONS: (for columnar modes or insert mode):",
4831 " --wrap N Wrap output lines to no longer than N characters",
4832 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4833 " --ww Shorthand for \"--wordwrap 1\"",
4834 " --quote Quote output text as SQL literals",
4835 " --noquote Do not quote output text",
4836 " TABLE The name of SQL table used for \"insert\" mode",
4837 #ifndef SQLITE_SHELL_FIDDLE
4838 ".nonce STRING Suspend safe mode for one command if nonce matches",
4840 ".nullvalue STRING Use STRING in place of NULL values",
4841 #ifndef SQLITE_SHELL_FIDDLE
4842 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4843 " If FILE begins with '|' then open as a pipe",
4844 " --bom Put a UTF8 byte-order mark at the beginning",
4845 " -e Send output to the system text editor",
4846 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4847 /* Note that .open is (partially) available in WASM builds but is
4848 ** currently only intended to be used by the fiddle tool, not
4849 ** end users, so is "undocumented." */
4850 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4852 " --append Use appendvfs to append database to the end of FILE",
4854 #ifndef SQLITE_OMIT_DESERIALIZE
4855 " --deserialize Load into memory using sqlite3_deserialize()",
4856 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4857 " --maxsize N Maximum size for --hexdb or --deserialized database",
4859 " --new Initialize FILE to an empty database",
4860 " --nofollow Do not follow symbolic links",
4861 " --readonly Open FILE readonly",
4862 " --zip FILE is a ZIP archive",
4863 #ifndef SQLITE_SHELL_FIDDLE
4864 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4865 " If FILE begins with '|' then open it as a pipe.",
4867 " --bom Prefix output with a UTF8 byte-order mark",
4868 " -e Send output to the system text editor",
4869 " -x Send output as CSV to a spreadsheet",
4871 ".parameter CMD ... Manage SQL parameter bindings",
4872 " clear Erase all bindings",
4873 " init Initialize the TEMP table that holds bindings",
4874 " list List the current parameter bindings",
4875 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4876 " PARAMETER should start with one of: $ : @ ?",
4877 " unset PARAMETER Remove PARAMETER from the binding table",
4878 ".print STRING... Print literal STRING",
4879 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4880 ".progress N Invoke progress handler after every N opcodes",
4881 " --limit N Interrupt after N progress callbacks",
4882 " --once Do no more than one progress interrupt",
4883 " --quiet|-q No output except at interrupts",
4884 " --reset Reset the count for each input and interrupt",
4886 ".prompt MAIN CONTINUE Replace the standard prompts",
4887 #ifndef SQLITE_SHELL_FIDDLE
4888 ".quit Stop interpreting input stream, exit if primary.",
4889 ".read FILE Read input from FILE or command output",
4890 " If FILE begins with \"|\", it is a command that generates the input.",
4892 #if SQLITE_SHELL_HAVE_RECOVER
4893 ".recover Recover as much data as possible from corrupt db.",
4894 " --ignore-freelist Ignore pages that appear to be on db freelist",
4895 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4896 " --no-rowids Do not attempt to recover rowid values",
4897 " that are not also INTEGER PRIMARY KEYs",
4899 #ifndef SQLITE_SHELL_FIDDLE
4900 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4901 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4903 ".scanstats on|off|est Turn sqlite3_stmt_scanstatus() metrics on or off",
4904 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4906 " --indent Try to pretty-print the schema",
4907 " --nosys Omit objects whose names start with \"sqlite_\"",
4908 ",selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4910 " --init Create a new SELFTEST table",
4911 " -v Verbose output",
4912 ".separator COL ?ROW? Change the column and row separators",
4913 #if defined(SQLITE_ENABLE_SESSION)
4914 ".session ?NAME? CMD ... Create or control sessions",
4916 " attach TABLE Attach TABLE",
4917 " changeset FILE Write a changeset into FILE",
4918 " close Close one session",
4919 " enable ?BOOLEAN? Set or query the enable bit",
4920 " filter GLOB... Reject tables matching GLOBs",
4921 " indirect ?BOOLEAN? Mark or query the indirect status",
4922 " isempty Query whether the session is empty",
4923 " list List currently open session names",
4924 " open DB NAME Open a new session on DB",
4925 " patchset FILE Write a patchset into FILE",
4926 " If ?NAME? is omitted, the first defined session is used.",
4928 ".sha3sum ... Compute a SHA3 hash of database content",
4930 " --schema Also hash the sqlite_schema table",
4931 " --sha3-224 Use the sha3-224 algorithm",
4932 " --sha3-256 Use the sha3-256 algorithm (default)",
4933 " --sha3-384 Use the sha3-384 algorithm",
4934 " --sha3-512 Use the sha3-512 algorithm",
4935 " Any other argument is a LIKE pattern for tables to hash",
4936 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4937 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4939 ".show Show the current values for various settings",
4940 ".stats ?ARG? Show stats or turn stats on or off",
4941 " off Turn off automatic stat display",
4942 " on Turn on automatic stat display",
4943 " stmt Show statement stats",
4944 " vmstep Show the virtual machine step count only",
4945 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4946 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4948 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4949 #ifndef SQLITE_SHELL_FIDDLE
4950 ",testcase NAME Begin redirecting output to 'testcase-out.txt'",
4952 ",testctrl CMD ... Run various sqlite3_test_control() operations",
4953 " Run \".testctrl\" with no arguments for details",
4954 ".timeout MS Try opening locked tables for MS milliseconds",
4955 ".timer on|off Turn SQL timer on or off",
4956 #ifndef SQLITE_OMIT_TRACE
4957 ".trace ?OPTIONS? Output each SQL statement as it is run",
4958 " FILE Send output to FILE",
4959 " stdout Send output to stdout",
4960 " stderr Send output to stderr",
4961 " off Disable tracing",
4962 " --expanded Expand query parameters",
4963 #ifdef SQLITE_ENABLE_NORMALIZE
4964 " --normalized Normal the SQL statements",
4966 " --plain Show SQL as it is input",
4967 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4968 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4969 " --row Trace each row (SQLITE_TRACE_ROW)",
4970 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4971 #endif /* SQLITE_OMIT_TRACE */
4973 ".unmodule NAME ... Unregister virtual table modules",
4974 " --allexcept Unregister everything except those named",
4976 ".version Show source, library and compiler versions",
4977 ".vfsinfo ?AUX? Information about the top-level VFS",
4978 ".vfslist List all available VFSes",
4979 ".vfsname ?AUX? Print the name of the VFS stack",
4980 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4981 " Negative values right-justify",
4985 ** Output help text.
4987 ** zPattern describes the set of commands for which help text is provided.
4988 ** If zPattern is NULL, then show all commands, but only give a one-line
4989 ** description of each.
4991 ** Return the number of matches.
4993 static int showHelp(FILE *out
, const char *zPattern
){
5000 || cli_strcmp(zPattern
,"-a")==0
5001 || cli_strcmp(zPattern
,"-all")==0
5002 || cli_strcmp(zPattern
,"--all")==0
5004 enum HelpWanted
{ HW_NoCull
= 0, HW_SummaryOnly
= 1, HW_Undoc
= 2 };
5005 enum HelpHave
{ HH_Undoc
= 2, HH_Summary
= 1, HH_More
= 0 };
5006 /* Show all or most commands
5007 ** *zPattern==0 => summary of documented commands only
5008 ** *zPattern=='0' => whole help for undocumented commands
5009 ** Otherwise => whole help for documented commands
5011 enum HelpWanted hw
= HW_SummaryOnly
;
5012 enum HelpHave hh
= HH_More
;
5014 hw
= (*zPattern
=='0')? HW_NoCull
|HW_Undoc
: HW_NoCull
;
5016 for(i
=0; i
<ArraySize(azHelp
); i
++){
5017 switch( azHelp
[i
][0] ){
5019 hh
= HH_Summary
|HH_Undoc
;
5028 if( ((hw
^hh
)&HH_Undoc
)==0 ){
5029 if( (hh
&HH_Summary
)!=0 ){
5030 utf8_printf(out
, ".%s\n", azHelp
[i
]+1);
5032 }else if( (hw
&HW_SummaryOnly
)==0 ){
5033 utf8_printf(out
, "%s\n", azHelp
[i
]);
5038 /* Seek documented commands for which zPattern is an exact prefix */
5039 zPat
= sqlite3_mprintf(".%s*", zPattern
);
5040 shell_check_oom(zPat
);
5041 for(i
=0; i
<ArraySize(azHelp
); i
++){
5042 if( sqlite3_strglob(zPat
, azHelp
[i
])==0 ){
5043 utf8_printf(out
, "%s\n", azHelp
[i
]);
5051 /* when zPattern is a prefix of exactly one command, then include
5052 ** the details of that command, which should begin at offset j */
5053 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
][0]==' ' ){
5054 utf8_printf(out
, "%s\n", azHelp
[j
]);
5060 /* Look for documented commands that contain zPattern anywhere.
5061 ** Show complete text of all documented commands that match. */
5062 zPat
= sqlite3_mprintf("%%%s%%", zPattern
);
5063 shell_check_oom(zPat
);
5064 for(i
=0; i
<ArraySize(azHelp
); i
++){
5065 if( azHelp
[i
][0]==',' ){
5066 while( i
<ArraySize(azHelp
)-1 && azHelp
[i
+1][0]==' ' ) ++i
;
5069 if( azHelp
[i
][0]=='.' ) j
= i
;
5070 if( sqlite3_strlike(zPat
, azHelp
[i
], 0)==0 ){
5071 utf8_printf(out
, "%s\n", azHelp
[j
]);
5072 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
+1][0]==' ' ){
5074 utf8_printf(out
, "%s\n", azHelp
[j
]);
5085 /* Forward reference */
5086 static int process_input(ShellState
*p
);
5089 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
5090 ** and return a pointer to the buffer. The caller is responsible for freeing
5093 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
5096 ** For convenience, a nul-terminator byte is always appended to the data read
5097 ** from the file before the buffer is returned. This byte is not included in
5098 ** the final value of (*pnByte), if applicable.
5100 ** NULL is returned if any error is encountered. The final value of *pnByte
5101 ** is undefined in this case.
5103 static char *readFile(const char *zName
, int *pnByte
){
5104 FILE *in
= fopen(zName
, "rb");
5109 if( in
==0 ) return 0;
5110 rc
= fseek(in
, 0, SEEK_END
);
5112 raw_printf(stderr
, "Error: '%s' not seekable\n", zName
);
5118 pBuf
= sqlite3_malloc64( nIn
+1 );
5120 raw_printf(stderr
, "Error: out of memory\n");
5124 nRead
= fread(pBuf
, nIn
, 1, in
);
5128 raw_printf(stderr
, "Error: cannot read '%s'\n", zName
);
5132 if( pnByte
) *pnByte
= nIn
;
5136 #if defined(SQLITE_ENABLE_SESSION)
5138 ** Close a single OpenSession object and release all of its associated
5141 static void session_close(OpenSession
*pSession
){
5143 sqlite3session_delete(pSession
->p
);
5144 sqlite3_free(pSession
->zName
);
5145 for(i
=0; i
<pSession
->nFilter
; i
++){
5146 sqlite3_free(pSession
->azFilter
[i
]);
5148 sqlite3_free(pSession
->azFilter
);
5149 memset(pSession
, 0, sizeof(OpenSession
));
5154 ** Close all OpenSession objects and release all associated resources.
5156 #if defined(SQLITE_ENABLE_SESSION)
5157 static void session_close_all(ShellState
*p
, int i
){
5159 struct AuxDb
*pAuxDb
= i
<0 ? p
->pAuxDb
: &p
->aAuxDb
[i
];
5160 for(j
=0; j
<pAuxDb
->nSession
; j
++){
5161 session_close(&pAuxDb
->aSession
[j
]);
5163 pAuxDb
->nSession
= 0;
5166 # define session_close_all(X,Y)
5170 ** Implementation of the xFilter function for an open session. Omit
5171 ** any tables named by ".session filter" but let all other table through.
5173 #if defined(SQLITE_ENABLE_SESSION)
5174 static int session_filter(void *pCtx
, const char *zTab
){
5175 OpenSession
*pSession
= (OpenSession
*)pCtx
;
5177 for(i
=0; i
<pSession
->nFilter
; i
++){
5178 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
5185 ** Try to deduce the type of file for zName based on its content. Return
5186 ** one of the SHELL_OPEN_* constants.
5188 ** If the file does not exist or is empty but its name looks like a ZIP
5189 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
5190 ** Otherwise, assume an ordinary database regardless of the filename if
5191 ** the type cannot be determined from content.
5193 int deduceDatabaseType(const char *zName
, int dfltZip
){
5194 FILE *f
= fopen(zName
, "rb");
5196 int rc
= SHELL_OPEN_UNSPEC
;
5199 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
5200 return SHELL_OPEN_ZIPFILE
;
5202 return SHELL_OPEN_NORMAL
;
5205 n
= fread(zBuf
, 16, 1, f
);
5206 if( n
==1 && memcmp(zBuf
, "SQLite format 3", 16)==0 ){
5208 return SHELL_OPEN_NORMAL
;
5210 fseek(f
, -25, SEEK_END
);
5211 n
= fread(zBuf
, 25, 1, f
);
5212 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
5213 rc
= SHELL_OPEN_APPENDVFS
;
5215 fseek(f
, -22, SEEK_END
);
5216 n
= fread(zBuf
, 22, 1, f
);
5217 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
5219 rc
= SHELL_OPEN_ZIPFILE
;
5220 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
5221 rc
= SHELL_OPEN_ZIPFILE
;
5228 #ifndef SQLITE_OMIT_DESERIALIZE
5230 ** Reconstruct an in-memory database using the output from the "dbtotxt"
5231 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
5232 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
5234 static unsigned char *readHexDb(ShellState
*p
, int *pnData
){
5235 unsigned char *a
= 0;
5243 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5247 in
= fopen(zDbFilename
, "r");
5249 utf8_printf(stderr
, "cannot open \"%s\" for reading\n", zDbFilename
);
5256 if( in
==0 ) in
= stdin
;
5260 if( fgets(zLine
, sizeof(zLine
), in
)==0 ) goto readHexDb_error
;
5261 rc
= sscanf(zLine
, "| size %d pagesize %d", &n
, &pgsz
);
5262 if( rc
!=2 ) goto readHexDb_error
;
5263 if( n
<0 ) goto readHexDb_error
;
5264 if( pgsz
<512 || pgsz
>65536 || (pgsz
&(pgsz
-1))!=0 ) goto readHexDb_error
;
5265 n
= (n
+pgsz
-1)&~(pgsz
-1); /* Round n up to the next multiple of pgsz */
5266 a
= sqlite3_malloc( n
? n
: 1 );
5269 if( pgsz
<512 || pgsz
>65536 || (pgsz
& (pgsz
-1))!=0 ){
5270 utf8_printf(stderr
, "invalid pagesize\n");
5271 goto readHexDb_error
;
5273 for(nLine
++; fgets(zLine
, sizeof(zLine
), in
)!=0; nLine
++){
5274 rc
= sscanf(zLine
, "| page %d offset %d", &j
, &k
);
5279 if( cli_strncmp(zLine
, "| end ", 6)==0 ){
5282 rc
= sscanf(zLine
,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
5283 &j
, &x
[0], &x
[1], &x
[2], &x
[3], &x
[4], &x
[5], &x
[6], &x
[7],
5284 &x
[8], &x
[9], &x
[10], &x
[11], &x
[12], &x
[13], &x
[14], &x
[15]);
5287 if( k
+16<=n
&& k
>=0 ){
5289 for(ii
=0; ii
<16; ii
++) a
[k
+ii
] = x
[ii
]&0xff;
5305 while( fgets(zLine
, sizeof(zLine
), p
->in
)!=0 ){
5307 if(cli_strncmp(zLine
, "| end ", 6)==0 ) break;
5312 utf8_printf(stderr
,"Error on line %d of --hexdb input\n", nLine
);
5315 #endif /* SQLITE_OMIT_DESERIALIZE */
5318 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
5320 static void shellUSleepFunc(
5321 sqlite3_context
*context
,
5323 sqlite3_value
**argv
5325 int sleep
= sqlite3_value_int(argv
[0]);
5327 sqlite3_sleep(sleep
/1000);
5328 sqlite3_result_int(context
, sleep
);
5331 /* Flags for open_db().
5333 ** The default behavior of open_db() is to exit(1) if the database fails to
5334 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5335 ** but still returns without calling exit.
5337 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5338 ** ZIP archive if the file does not exist or is empty and its name matches
5339 ** the *.zip pattern.
5341 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5342 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5345 ** Make sure the database is open. If it is not, then open it. If
5346 ** the database fails to open, print an error message and exit.
5348 static void open_db(ShellState
*p
, int openFlags
){
5350 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5351 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
5352 if( zDbFilename
==0 || zDbFilename
[0]==0 ){
5353 p
->openMode
= SHELL_OPEN_NORMAL
;
5355 p
->openMode
= (u8
)deduceDatabaseType(zDbFilename
,
5356 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
5359 switch( p
->openMode
){
5360 case SHELL_OPEN_APPENDVFS
: {
5361 sqlite3_open_v2(zDbFilename
, &p
->db
,
5362 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, "apndvfs");
5365 case SHELL_OPEN_HEXDB
:
5366 case SHELL_OPEN_DESERIALIZE
: {
5367 sqlite3_open(0, &p
->db
);
5370 case SHELL_OPEN_ZIPFILE
: {
5371 sqlite3_open(":memory:", &p
->db
);
5374 case SHELL_OPEN_READONLY
: {
5375 sqlite3_open_v2(zDbFilename
, &p
->db
,
5376 SQLITE_OPEN_READONLY
|p
->openFlags
, 0);
5379 case SHELL_OPEN_UNSPEC
:
5380 case SHELL_OPEN_NORMAL
: {
5381 sqlite3_open_v2(zDbFilename
, &p
->db
,
5382 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, 0);
5387 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
5388 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
5389 zDbFilename
, sqlite3_errmsg(p
->db
));
5390 if( (openFlags
& OPEN_DB_KEEPALIVE
)==0 ){
5393 sqlite3_close(p
->db
);
5394 sqlite3_open(":memory:", &p
->db
);
5395 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
5397 "Also: unable to open substitute in-memory database.\n"
5402 "Notice: using substitute in-memory database instead of \"%s\"\n",
5406 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_STMT_SCANSTATUS
, (int)0, (int*)0);
5408 /* Reflect the use or absence of --unsafe-testing invocation. */
5410 int testmode_on
= ShellHasFlag(p
,SHFLG_TestingMode
);
5411 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_TRUSTED_SCHEMA
, testmode_on
,0);
5412 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, !testmode_on
,0);
5415 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5416 sqlite3_enable_load_extension(p
->db
, 1);
5418 sqlite3_shathree_init(p
->db
, 0, 0);
5419 sqlite3_uint_init(p
->db
, 0, 0);
5420 sqlite3_decimal_init(p
->db
, 0, 0);
5421 sqlite3_base64_init(p
->db
, 0, 0);
5422 sqlite3_base85_init(p
->db
, 0, 0);
5423 sqlite3_regexp_init(p
->db
, 0, 0);
5424 sqlite3_ieee_init(p
->db
, 0, 0);
5425 sqlite3_series_init(p
->db
, 0, 0);
5426 #ifndef SQLITE_SHELL_FIDDLE
5427 sqlite3_fileio_init(p
->db
, 0, 0);
5428 sqlite3_completion_init(p
->db
, 0, 0);
5430 #ifdef SQLITE_HAVE_ZLIB
5431 if( !p
->bSafeModePersist
){
5432 sqlite3_zipfile_init(p
->db
, 0, 0);
5433 sqlite3_sqlar_init(p
->db
, 0, 0);
5436 #ifdef SQLITE_SHELL_EXTFUNCS
5437 /* Create a preprocessing mechanism for extensions to make
5438 * their own provisions for being built into the shell.
5439 * This is a short-span macro. See further below for usage.
5441 #define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
5442 #define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
5443 /* Let custom-included extensions get their ..._init() called.
5444 * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
5445 * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
5446 * inititialization routine to be called.
5449 int irc
= SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS
, INIT
)(p
->db
);
5450 /* Let custom-included extensions expose their functionality.
5451 * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
5452 * the SQL functions, virtual tables, collating sequences or
5453 * VFS's implemented by the extension to be registered.
5456 || irc
==SQLITE_OK_LOAD_PERMANENTLY
){
5457 SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS
, EXPOSE
)(p
->db
, 0);
5459 #undef SHELL_SUB_MACRO
5460 #undef SHELL_SUBMACRO
5464 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
5465 shellAddSchemaName
, 0, 0);
5466 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
5467 shellModuleSchema
, 0, 0);
5468 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
5469 shellPutsFunc
, 0, 0);
5470 sqlite3_create_function(p
->db
, "usleep",1,SQLITE_UTF8
,0,
5471 shellUSleepFunc
, 0, 0);
5472 #ifndef SQLITE_NOHAVE_SYSTEM
5473 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
5475 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
5479 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
5480 char *zSql
= sqlite3_mprintf(
5481 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename
);
5482 shell_check_oom(zSql
);
5483 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
5486 #ifndef SQLITE_OMIT_DESERIALIZE
5488 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
|| p
->openMode
==SHELL_OPEN_HEXDB
){
5491 unsigned char *aData
;
5492 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
){
5493 aData
= (unsigned char*)readFile(zDbFilename
, &nData
);
5495 aData
= readHexDb(p
, &nData
);
5500 rc
= sqlite3_deserialize(p
->db
, "main", aData
, nData
, nData
,
5501 SQLITE_DESERIALIZE_RESIZEABLE
|
5502 SQLITE_DESERIALIZE_FREEONCLOSE
);
5504 utf8_printf(stderr
, "Error: sqlite3_deserialize() returns %d\n", rc
);
5507 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_SIZE_LIMIT
, &p
->szMax
);
5513 if( p
->bSafeModePersist
){
5514 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
5517 p
->db
, SQLITE_DBCONFIG_STMT_SCANSTATUS
, p
->scanstatsOn
, (int*)0
5523 ** Attempt to close the databaes connection. Report errors.
5525 void close_db(sqlite3
*db
){
5526 int rc
= sqlite3_close(db
);
5528 utf8_printf(stderr
, "Error: sqlite3_close() returns %d: %s\n",
5529 rc
, sqlite3_errmsg(db
));
5533 #if HAVE_READLINE || HAVE_EDITLINE
5535 ** Readline completion callbacks
5537 static char *readline_completion_generator(const char *text
, int state
){
5538 static sqlite3_stmt
*pStmt
= 0;
5542 sqlite3_finalize(pStmt
);
5543 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5544 " FROM completion(%Q) ORDER BY 1", text
);
5545 shell_check_oom(zSql
);
5546 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5549 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
5550 const char *z
= (const char*)sqlite3_column_text(pStmt
,0);
5551 zRet
= z
? strdup(z
) : 0;
5553 sqlite3_finalize(pStmt
);
5559 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
5562 rl_attempted_completion_over
= 1;
5563 return rl_completion_matches(zText
, readline_completion_generator
);
5566 #elif HAVE_LINENOISE
5568 ** Linenoise completion callback
5570 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
5571 i64 nLine
= strlen(zLine
);
5573 sqlite3_stmt
*pStmt
= 0;
5577 if( nLine
>(i64
)sizeof(zBuf
)-30 ) return;
5578 if( zLine
[0]=='.' || zLine
[0]=='#') return;
5579 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
5580 if( i
==nLine
-1 ) return;
5582 memcpy(zBuf
, zLine
, iStart
);
5583 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5584 " FROM completion(%Q,%Q) ORDER BY 1",
5585 &zLine
[iStart
], zLine
);
5586 shell_check_oom(zSql
);
5587 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5589 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5590 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5591 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
5592 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
5593 if( iStart
+nCompletion
< (i64
)sizeof(zBuf
)-1 && zCompletion
){
5594 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
5595 linenoiseAddCompletion(lc
, zBuf
);
5598 sqlite3_finalize(pStmt
);
5603 ** Do C-language style dequoting.
5609 ** \v -> vertical tab
5611 ** \r -> carriage return
5616 ** \NNN -> ascii character NNN in octal
5617 ** \xHH -> ascii character HH in hexadecimal
5619 static void resolve_backslashes(char *z
){
5622 while( *z
&& *z
!='\\' ) z
++;
5623 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
5624 if( c
=='\\' && z
[i
+1]!=0 ){
5642 }else if( c
=='\'' ){
5644 }else if( c
=='\\' ){
5649 while( nhd
<2 && (c
=z
[i
+1+nhd
])!=0 && (hdv
=hexDigitValue(c
))>=0 ){
5650 hv
= (u8
)((hv
<<4)|hdv
);
5655 }else if( c
>='0' && c
<='7' ){
5657 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5659 c
= (c
<<3) + z
[i
] - '0';
5660 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5662 c
= (c
<<3) + z
[i
] - '0';
5673 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5674 ** for TRUE and FALSE. Return the integer value if appropriate.
5676 static int booleanValue(const char *zArg
){
5678 if( zArg
[0]=='0' && zArg
[1]=='x' ){
5679 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
5681 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
5683 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
5684 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
5687 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
5690 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5696 ** Set or clear a shell flag according to a boolean value.
5698 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
5699 if( booleanValue(zArg
) ){
5700 ShellSetFlag(p
, mFlag
);
5702 ShellClearFlag(p
, mFlag
);
5707 ** Close an output file, assuming it is not stderr or stdout
5709 static void output_file_close(FILE *f
){
5710 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
5714 ** Try to open an output file. The names "stdout" and "stderr" are
5715 ** recognized and do the right thing. NULL is returned if the output
5716 ** filename is "off".
5718 static FILE *output_file_open(const char *zFile
, int bTextMode
){
5720 if( cli_strcmp(zFile
,"stdout")==0 ){
5722 }else if( cli_strcmp(zFile
, "stderr")==0 ){
5724 }else if( cli_strcmp(zFile
, "off")==0 ){
5727 f
= fopen(zFile
, bTextMode
? "w" : "wb");
5729 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
5735 #ifndef SQLITE_OMIT_TRACE
5737 ** A routine for handling output from sqlite3_trace().
5739 static int sql_trace_callback(
5740 unsigned mType
, /* The trace type */
5741 void *pArg
, /* The ShellState pointer */
5742 void *pP
, /* Usually a pointer to sqlite_stmt */
5743 void *pX
/* Auxiliary output */
5745 ShellState
*p
= (ShellState
*)pArg
;
5746 sqlite3_stmt
*pStmt
;
5749 if( p
->traceOut
==0 ) return 0;
5750 if( mType
==SQLITE_TRACE_CLOSE
){
5751 utf8_printf(p
->traceOut
, "-- closing database connection\n");
5754 if( mType
!=SQLITE_TRACE_ROW
&& pX
!=0 && ((const char*)pX
)[0]=='-' ){
5755 zSql
= (const char*)pX
;
5757 pStmt
= (sqlite3_stmt
*)pP
;
5758 switch( p
->eTraceType
){
5759 case SHELL_TRACE_EXPANDED
: {
5760 zSql
= sqlite3_expanded_sql(pStmt
);
5763 #ifdef SQLITE_ENABLE_NORMALIZE
5764 case SHELL_TRACE_NORMALIZED
: {
5765 zSql
= sqlite3_normalized_sql(pStmt
);
5770 zSql
= sqlite3_sql(pStmt
);
5775 if( zSql
==0 ) return 0;
5776 nSql
= strlen(zSql
);
5777 if( nSql
>1000000000 ) nSql
= 1000000000;
5778 while( nSql
>0 && zSql
[nSql
-1]==';' ){ nSql
--; }
5780 case SQLITE_TRACE_ROW
:
5781 case SQLITE_TRACE_STMT
: {
5782 utf8_printf(p
->traceOut
, "%.*s;\n", (int)nSql
, zSql
);
5785 case SQLITE_TRACE_PROFILE
: {
5786 sqlite3_int64 nNanosec
= pX
? *(sqlite3_int64
*)pX
: 0;
5787 utf8_printf(p
->traceOut
, "%.*s; -- %lld ns\n", (int)nSql
, zSql
, nNanosec
);
5796 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5797 ** a useful spot to set a debugger breakpoint.
5799 ** This routine does not do anything practical. The code are there simply
5800 ** to prevent the compiler from optimizing this routine out.
5802 static void test_breakpoint(void){
5803 static unsigned int nCall
= 0;
5804 if( (nCall
++)==0xffffffff ) printf("Many .breakpoints have run\n");
5808 ** An object used to read a CSV and other files for import.
5810 typedef struct ImportCtx ImportCtx
;
5812 const char *zFile
; /* Name of the input file */
5813 FILE *in
; /* Read the CSV text from this input stream */
5814 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close in */
5815 char *z
; /* Accumulated text for a field */
5816 int n
; /* Number of bytes in z */
5817 int nAlloc
; /* Space allocated for z[] */
5818 int nLine
; /* Current line number */
5819 int nRow
; /* Number of rows imported */
5820 int nErr
; /* Number of errors encountered */
5821 int bNotFirst
; /* True if one or more bytes already read */
5822 int cTerm
; /* Character that terminated the most recent field */
5823 int cColSep
; /* The column separator character. (Usually ",") */
5824 int cRowSep
; /* The row separator character. (Usually "\n") */
5827 /* Clean up resourced used by an ImportCtx */
5828 static void import_cleanup(ImportCtx
*p
){
5829 if( p
->in
!=0 && p
->xCloser
!=0 ){
5837 /* Append a single byte to z[] */
5838 static void import_append_char(ImportCtx
*p
, int c
){
5839 if( p
->n
+1>=p
->nAlloc
){
5840 p
->nAlloc
+= p
->nAlloc
+ 100;
5841 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
5842 shell_check_oom(p
->z
);
5844 p
->z
[p
->n
++] = (char)c
;
5847 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5848 ** with the option of having a separator other than ",".
5850 ** + Input comes from p->in.
5851 ** + Store results in p->z of length p->n. Space to hold p->z comes
5852 ** from sqlite3_malloc64().
5853 ** + Use p->cSep as the column separator. The default is ",".
5854 ** + Use p->rSep as the row separator. The default is "\n".
5855 ** + Keep track of the line number in p->nLine.
5856 ** + Store the character that terminates the field in p->cTerm. Store
5857 ** EOF on end-of-file.
5858 ** + Report syntax errors on stderr
5860 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
5862 int cSep
= (u8
)p
->cColSep
;
5863 int rSep
= (u8
)p
->cRowSep
;
5866 if( c
==EOF
|| seenInterrupt
){
5872 int startLine
= p
->nLine
;
5877 if( c
==rSep
) p
->nLine
++;
5884 if( (c
==cSep
&& pc
==cQuote
)
5885 || (c
==rSep
&& pc
==cQuote
)
5886 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
5887 || (c
==EOF
&& pc
==cQuote
)
5889 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
5893 if( pc
==cQuote
&& c
!='\r' ){
5894 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
5895 p
->zFile
, p
->nLine
, cQuote
);
5898 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
5899 p
->zFile
, startLine
, cQuote
);
5903 import_append_char(p
, c
);
5908 /* If this is the first field being parsed and it begins with the
5909 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5910 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
5911 import_append_char(p
, c
);
5913 if( (c
&0xff)==0xbb ){
5914 import_append_char(p
, c
);
5916 if( (c
&0xff)==0xbf ){
5919 return csv_read_one_field(p
);
5923 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5924 import_append_char(p
, c
);
5929 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
5933 if( p
->z
) p
->z
[p
->n
] = 0;
5938 /* Read a single field of ASCII delimited text.
5940 ** + Input comes from p->in.
5941 ** + Store results in p->z of length p->n. Space to hold p->z comes
5942 ** from sqlite3_malloc64().
5943 ** + Use p->cSep as the column separator. The default is "\x1F".
5944 ** + Use p->rSep as the row separator. The default is "\x1E".
5945 ** + Keep track of the row number in p->nLine.
5946 ** + Store the character that terminates the field in p->cTerm. Store
5947 ** EOF on end-of-file.
5948 ** + Report syntax errors on stderr
5950 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
5952 int cSep
= (u8
)p
->cColSep
;
5953 int rSep
= (u8
)p
->cRowSep
;
5956 if( c
==EOF
|| seenInterrupt
){
5960 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5961 import_append_char(p
, c
);
5968 if( p
->z
) p
->z
[p
->n
] = 0;
5973 ** Try to transfer data for table zTable. If an error is seen while
5974 ** moving forward, try to go backwards. The backwards movement won't
5975 ** work for WITHOUT ROWID tables.
5977 static void tryToCloneData(
5982 sqlite3_stmt
*pQuery
= 0;
5983 sqlite3_stmt
*pInsert
= 0;
5988 int nTable
= strlen30(zTable
);
5991 const int spinRate
= 10000;
5993 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
5994 shell_check_oom(zQuery
);
5995 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5997 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
5998 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
6002 n
= sqlite3_column_count(pQuery
);
6003 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
6004 shell_check_oom(zInsert
);
6005 sqlite3_snprintf(200+nTable
,zInsert
,
6006 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
6007 i
= strlen30(zInsert
);
6009 memcpy(zInsert
+i
, ",?", 2);
6012 memcpy(zInsert
+i
, ");", 3);
6013 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
6015 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
6016 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
6021 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
6023 switch( sqlite3_column_type(pQuery
, i
) ){
6025 sqlite3_bind_null(pInsert
, i
+1);
6028 case SQLITE_INTEGER
: {
6029 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
6032 case SQLITE_FLOAT
: {
6033 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
6037 sqlite3_bind_text(pInsert
, i
+1,
6038 (const char*)sqlite3_column_text(pQuery
,i
),
6043 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
6044 sqlite3_column_bytes(pQuery
,i
),
6050 rc
= sqlite3_step(pInsert
);
6051 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
6052 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
6053 sqlite3_errmsg(newDb
));
6055 sqlite3_reset(pInsert
);
6057 if( (cnt
%spinRate
)==0 ){
6058 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
6062 if( rc
==SQLITE_DONE
) break;
6063 sqlite3_finalize(pQuery
);
6064 sqlite3_free(zQuery
);
6065 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
6067 shell_check_oom(zQuery
);
6068 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6070 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
6073 } /* End for(k=0...) */
6076 sqlite3_finalize(pQuery
);
6077 sqlite3_finalize(pInsert
);
6078 sqlite3_free(zQuery
);
6079 sqlite3_free(zInsert
);
6084 ** Try to transfer all rows of the schema that match zWhere. For
6085 ** each row, invoke xForEach() on the object defined by that row.
6086 ** If an error is encountered while moving forward through the
6087 ** sqlite_schema table, try again moving backwards.
6089 static void tryToCloneSchema(
6093 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
6095 sqlite3_stmt
*pQuery
= 0;
6098 const unsigned char *zName
;
6099 const unsigned char *zSql
;
6102 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6103 " WHERE %s ORDER BY rowid ASC", zWhere
);
6104 shell_check_oom(zQuery
);
6105 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6107 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
6108 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
6110 goto end_schema_xfer
;
6112 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
6113 zName
= sqlite3_column_text(pQuery
, 0);
6114 zSql
= sqlite3_column_text(pQuery
, 1);
6115 if( zName
==0 || zSql
==0 ) continue;
6116 if( sqlite3_stricmp((char*)zName
, "sqlite_sequence")!=0 ){
6117 printf("%s... ", zName
); fflush(stdout
);
6118 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
6120 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
6121 sqlite3_free(zErrMsg
);
6126 xForEach(p
, newDb
, (const char*)zName
);
6130 if( rc
!=SQLITE_DONE
){
6131 sqlite3_finalize(pQuery
);
6132 sqlite3_free(zQuery
);
6133 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
6134 " WHERE %s ORDER BY rowid DESC", zWhere
);
6135 shell_check_oom(zQuery
);
6136 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
6138 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
6139 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
6141 goto end_schema_xfer
;
6143 while( sqlite3_step(pQuery
)==SQLITE_ROW
){
6144 zName
= sqlite3_column_text(pQuery
, 0);
6145 zSql
= sqlite3_column_text(pQuery
, 1);
6146 if( zName
==0 || zSql
==0 ) continue;
6147 if( sqlite3_stricmp((char*)zName
, "sqlite_sequence")==0 ) continue;
6148 printf("%s... ", zName
); fflush(stdout
);
6149 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
6151 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
6152 sqlite3_free(zErrMsg
);
6156 xForEach(p
, newDb
, (const char*)zName
);
6162 sqlite3_finalize(pQuery
);
6163 sqlite3_free(zQuery
);
6167 ** Open a new database file named "zNewDb". Try to recover as much information
6168 ** as possible out of the main database (which might be corrupt) and write it
6171 static void tryToClone(ShellState
*p
, const char *zNewDb
){
6174 if( access(zNewDb
,0)==0 ){
6175 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
6178 rc
= sqlite3_open(zNewDb
, &newDb
);
6180 utf8_printf(stderr
, "Cannot create output database: %s\n",
6181 sqlite3_errmsg(newDb
));
6183 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
6184 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
6185 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
6186 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
6187 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
6188 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6194 ** Change the output file back to stdout.
6196 ** If the p->doXdgOpen flag is set, that means the output was being
6197 ** redirected to a temporary file named by p->zTempFile. In that case,
6198 ** launch start/open/xdg-open on that temporary file.
6200 static void output_reset(ShellState
*p
){
6201 if( p
->outfile
[0]=='|' ){
6202 #ifndef SQLITE_OMIT_POPEN
6206 output_file_close(p
->out
);
6207 #ifndef SQLITE_NOHAVE_SYSTEM
6209 const char *zXdgOpenCmd
=
6212 #elif defined(__APPLE__)
6218 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
6220 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
6222 /* Give the start/open/xdg-open command some time to get
6223 ** going before we continue, and potential delete the
6224 ** p->zTempFile data file out from under it */
6225 sqlite3_sleep(2000);
6231 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
6238 ** Run an SQL command and return the single integer result.
6240 static int db_int(sqlite3
*db
, const char *zSql
){
6241 sqlite3_stmt
*pStmt
;
6243 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
6244 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
6245 res
= sqlite3_column_int(pStmt
,0);
6247 sqlite3_finalize(pStmt
);
6251 #if SQLITE_SHELL_HAVE_RECOVER
6253 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
6255 static unsigned int get2byteInt(unsigned char *a
){
6256 return (a
[0]<<8) + a
[1];
6258 static unsigned int get4byteInt(unsigned char *a
){
6259 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
6263 ** Implementation of the ".dbinfo" command.
6265 ** Return 1 on error, 2 to exit, and 0 otherwise.
6267 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
6268 static const struct { const char *zName
; int ofst
; } aField
[] = {
6269 { "file change counter:", 24 },
6270 { "database page count:", 28 },
6271 { "freelist page count:", 36 },
6272 { "schema cookie:", 40 },
6273 { "schema format:", 44 },
6274 { "default cache size:", 48 },
6275 { "autovacuum top root:", 52 },
6276 { "incremental vacuum:", 64 },
6277 { "text encoding:", 56 },
6278 { "user version:", 60 },
6279 { "application id:", 68 },
6280 { "software version:", 96 },
6282 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
6283 { "number of tables:",
6284 "SELECT count(*) FROM %s WHERE type='table'" },
6285 { "number of indexes:",
6286 "SELECT count(*) FROM %s WHERE type='index'" },
6287 { "number of triggers:",
6288 "SELECT count(*) FROM %s WHERE type='trigger'" },
6289 { "number of views:",
6290 "SELECT count(*) FROM %s WHERE type='view'" },
6292 "SELECT total(length(sql)) FROM %s" },
6295 unsigned iDataVersion
;
6297 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
6298 sqlite3_stmt
*pStmt
= 0;
6299 unsigned char aHdr
[100];
6301 if( p
->db
==0 ) return 1;
6302 rc
= sqlite3_prepare_v2(p
->db
,
6303 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
6306 utf8_printf(stderr
, "error: %s\n", sqlite3_errmsg(p
->db
));
6307 sqlite3_finalize(pStmt
);
6310 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
6311 if( sqlite3_step(pStmt
)==SQLITE_ROW
6312 && sqlite3_column_bytes(pStmt
,0)>100
6314 const u8
*pb
= sqlite3_column_blob(pStmt
,0);
6315 shell_check_oom(pb
);
6316 memcpy(aHdr
, pb
, 100);
6317 sqlite3_finalize(pStmt
);
6319 raw_printf(stderr
, "unable to read database header\n");
6320 sqlite3_finalize(pStmt
);
6323 i
= get2byteInt(aHdr
+16);
6324 if( i
==1 ) i
= 65536;
6325 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
6326 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
6327 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
6328 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
6329 for(i
=0; i
<ArraySize(aField
); i
++){
6330 int ofst
= aField
[i
].ofst
;
6331 unsigned int val
= get4byteInt(aHdr
+ ofst
);
6332 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
6335 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
6336 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
6337 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
6340 raw_printf(p
->out
, "\n");
6343 zSchemaTab
= sqlite3_mprintf("main.sqlite_schema");
6344 }else if( cli_strcmp(zDb
,"temp")==0 ){
6345 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_schema");
6347 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_schema", zDb
);
6349 for(i
=0; i
<ArraySize(aQuery
); i
++){
6350 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
6351 int val
= db_int(p
->db
, zSql
);
6353 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
6355 sqlite3_free(zSchemaTab
);
6356 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_DATA_VERSION
, &iDataVersion
);
6357 utf8_printf(p
->out
, "%-20s %u\n", "data version", iDataVersion
);
6360 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6363 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6365 static int shellDatabaseError(sqlite3
*db
){
6366 const char *zErr
= sqlite3_errmsg(db
);
6367 utf8_printf(stderr
, "Error: %s\n", zErr
);
6372 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6373 ** if they match and FALSE (0) if they do not match.
6377 ** '*' Matches any sequence of zero or more characters.
6379 ** '?' Matches exactly one character.
6381 ** [...] Matches one character from the enclosed list of
6384 ** [^...] Matches one character not in the enclosed list.
6386 ** '#' Matches any sequence of one or more digits with an
6387 ** optional + or - sign in front
6389 ** ' ' Any span of whitespace matches any other span of
6392 ** Extra whitespace at the end of z[] is ignored.
6394 static int testcase_glob(const char *zGlob
, const char *z
){
6399 while( (c
= (*(zGlob
++)))!=0 ){
6401 if( !IsSpace(*z
) ) return 0;
6402 while( IsSpace(*zGlob
) ) zGlob
++;
6403 while( IsSpace(*z
) ) z
++;
6405 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
6406 if( c
=='?' && (*(z
++))==0 ) return 0;
6411 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
6416 while( (c2
= (*(z
++)))!=0 ){
6419 if( c2
==0 ) return 0;
6421 if( testcase_glob(zGlob
,z
) ) return 1;
6425 if( (*(z
++))==0 ) return 0;
6431 if( c
==0 ) return 0;
6438 if( c
==']' ) seen
= 1;
6441 while( c2
&& c2
!=']' ){
6442 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
6444 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
6454 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
6456 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
6457 if( !IsDigit(z
[0]) ) return 0;
6459 while( IsDigit(z
[0]) ){ z
++; }
6461 if( c
!=(*(z
++)) ) return 0;
6464 while( IsSpace(*z
) ){ z
++; }
6470 ** Compare the string as a command-line option with either one or two
6471 ** initial "-" characters.
6473 static int optionMatch(const char *zStr
, const char *zOpt
){
6474 if( zStr
[0]!='-' ) return 0;
6476 if( zStr
[0]=='-' ) zStr
++;
6477 return cli_strcmp(zStr
, zOpt
)==0;
6483 int shellDeleteFile(const char *zFilename
){
6486 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
6490 rc
= unlink(zFilename
);
6496 ** Try to delete the temporary file (if there is one) and free the
6497 ** memory used to hold the name of the temp file.
6499 static void clearTempFile(ShellState
*p
){
6500 if( p
->zTempFile
==0 ) return;
6501 if( p
->doXdgOpen
) return;
6502 if( shellDeleteFile(p
->zTempFile
) ) return;
6503 sqlite3_free(p
->zTempFile
);
6508 ** Create a new temp file name with the given suffix.
6510 static void newTempFile(ShellState
*p
, const char *zSuffix
){
6512 sqlite3_free(p
->zTempFile
);
6515 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
6517 if( p
->zTempFile
==0 ){
6518 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6519 ** will not work and we will need to fallback to guessing */
6522 sqlite3_randomness(sizeof(r
), &r
);
6523 zTemp
= getenv("TEMP");
6524 if( zTemp
==0 ) zTemp
= getenv("TMP");
6532 p
->zTempFile
= sqlite3_mprintf("%s/temp%llx.%s", zTemp
, r
, zSuffix
);
6534 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
6536 shell_check_oom(p
->zTempFile
);
6541 ** The implementation of SQL scalar function fkey_collate_clause(), used
6542 ** by the ".lint fkey-indexes" command. This scalar function is always
6543 ** called with four arguments - the parent table name, the parent column name,
6544 ** the child table name and the child column name.
6546 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6548 ** If either of the named tables or columns do not exist, this function
6549 ** returns an empty string. An empty string is also returned if both tables
6550 ** and columns exist but have the same default collation sequence. Or,
6551 ** if both exist but the default collation sequences are different, this
6552 ** function returns the string " COLLATE <parent-collation>", where
6553 ** <parent-collation> is the default collation sequence of the parent column.
6555 static void shellFkeyCollateClause(
6556 sqlite3_context
*pCtx
,
6558 sqlite3_value
**apVal
6560 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
6561 const char *zParent
;
6562 const char *zParentCol
;
6563 const char *zParentSeq
;
6565 const char *zChildCol
;
6566 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
6570 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
6571 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
6572 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
6573 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
6575 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
6576 rc
= sqlite3_table_column_metadata(
6577 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
6579 if( rc
==SQLITE_OK
){
6580 rc
= sqlite3_table_column_metadata(
6581 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
6585 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
6586 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
6587 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
6594 ** The implementation of dot-command ".lint fkey-indexes".
6596 static int lintFkeyIndexes(
6597 ShellState
*pState
, /* Current shell tool state */
6598 char **azArg
, /* Array of arguments passed to dot command */
6599 int nArg
/* Number of entries in azArg[] */
6601 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
6602 FILE *out
= pState
->out
; /* Stream to write non-error output to */
6603 int bVerbose
= 0; /* If -verbose is present */
6604 int bGroupByParent
= 0; /* If -groupbyparent is present */
6605 int i
; /* To iterate through azArg[] */
6606 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
6607 int rc
; /* Return code */
6608 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
6611 ** This SELECT statement returns one row for each foreign key constraint
6612 ** in the schema of the main database. The column values are:
6614 ** 0. The text of an SQL statement similar to:
6616 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6618 ** This SELECT is similar to the one that the foreign keys implementation
6619 ** needs to run internally on child tables. If there is an index that can
6620 ** be used to optimize this query, then it can also be used by the FK
6621 ** implementation to optimize DELETE or UPDATE statements on the parent
6624 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6625 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6626 ** contains an index that can be used to optimize the query.
6628 ** 2. Human readable text that describes the child table and columns. e.g.
6630 ** "child_table(child_key1, child_key2)"
6632 ** 3. Human readable text that describes the parent table and columns. e.g.
6634 ** "parent_table(parent_key1, parent_key2)"
6636 ** 4. A full CREATE INDEX statement for an index that could be used to
6637 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6639 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6641 ** 5. The name of the parent table.
6643 ** These six values are used by the C logic below to generate the report.
6647 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6648 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6649 " || fkey_collate_clause("
6650 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6652 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6653 " || group_concat('*=?', ' AND ') || ')'"
6655 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6657 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6659 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6660 " || ' ON ' || quote(s.name) || '('"
6661 " || group_concat(quote(f.[from]) ||"
6662 " fkey_collate_clause("
6663 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6667 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6668 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6669 "GROUP BY s.name, f.id "
6670 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6672 const char *zGlobIPK
= "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6674 for(i
=2; i
<nArg
; i
++){
6675 int n
= strlen30(azArg
[i
]);
6676 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
6679 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
6684 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6687 return SQLITE_ERROR
;
6691 /* Register the fkey_collate_clause() SQL function */
6692 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
6693 0, shellFkeyCollateClause
, 0, 0
6697 if( rc
==SQLITE_OK
){
6698 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
6700 if( rc
==SQLITE_OK
){
6701 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
6704 if( rc
==SQLITE_OK
){
6707 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
6709 sqlite3_stmt
*pExplain
= 0;
6710 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
6711 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
6712 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
6713 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
6714 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
6715 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
6717 if( zEQP
==0 ) continue;
6718 if( zGlob
==0 ) continue;
6719 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
6720 if( rc
!=SQLITE_OK
) break;
6721 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
6722 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
6723 res
= zPlan
!=0 && ( 0==sqlite3_strglob(zGlob
, zPlan
)
6724 || 0==sqlite3_strglob(zGlobIPK
, zPlan
));
6726 rc
= sqlite3_finalize(pExplain
);
6727 if( rc
!=SQLITE_OK
) break;
6730 raw_printf(stderr
, "Error: internal error");
6734 && (bVerbose
|| res
==0)
6735 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
6737 raw_printf(out
, "-- Parent table %s\n", zParent
);
6738 sqlite3_free(zPrev
);
6739 zPrev
= sqlite3_mprintf("%s", zParent
);
6743 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
6744 }else if( bVerbose
){
6745 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
6746 zIndent
, zFrom
, zTarget
6751 sqlite3_free(zPrev
);
6753 if( rc
!=SQLITE_OK
){
6754 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6757 rc2
= sqlite3_finalize(pSql
);
6758 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
6760 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6763 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6770 ** Implementation of ".lint" dot command.
6772 static int lintDotCommand(
6773 ShellState
*pState
, /* Current shell tool state */
6774 char **azArg
, /* Array of arguments passed to dot command */
6775 int nArg
/* Number of entries in azArg[] */
6778 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
6779 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
6780 return lintFkeyIndexes(pState
, azArg
, nArg
);
6783 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
6784 raw_printf(stderr
, "Where sub-commands are:\n");
6785 raw_printf(stderr
, " fkey-indexes\n");
6786 return SQLITE_ERROR
;
6789 #if !defined SQLITE_OMIT_VIRTUALTABLE
6790 static void shellPrepare(
6794 sqlite3_stmt
**ppStmt
6797 if( *pRc
==SQLITE_OK
){
6798 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
6799 if( rc
!=SQLITE_OK
){
6800 raw_printf(stderr
, "sql error: %s (%d)\n",
6801 sqlite3_errmsg(db
), sqlite3_errcode(db
)
6809 ** Create a prepared statement using printf-style arguments for the SQL.
6811 ** This routine is could be marked "static". But it is not always used,
6812 ** depending on compile-time options. By omitting the "static", we avoid
6813 ** nuisance compiler warnings about "defined but not used".
6815 void shellPreparePrintf(
6818 sqlite3_stmt
**ppStmt
,
6823 if( *pRc
==SQLITE_OK
){
6827 z
= sqlite3_vmprintf(zFmt
, ap
);
6830 *pRc
= SQLITE_NOMEM
;
6832 shellPrepare(db
, pRc
, z
, ppStmt
);
6838 /* Finalize the prepared statement created using shellPreparePrintf().
6840 ** This routine is could be marked "static". But it is not always used,
6841 ** depending on compile-time options. By omitting the "static", we avoid
6842 ** nuisance compiler warnings about "defined but not used".
6849 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6850 int rc
= sqlite3_finalize(pStmt
);
6851 if( *pRc
==SQLITE_OK
){
6852 if( rc
!=SQLITE_OK
){
6853 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
6860 /* Reset the prepared statement created using shellPreparePrintf().
6862 ** This routine is could be marked "static". But it is not always used,
6863 ** depending on compile-time options. By omitting the "static", we avoid
6864 ** nuisance compiler warnings about "defined but not used".
6870 int rc
= sqlite3_reset(pStmt
);
6871 if( *pRc
==SQLITE_OK
){
6872 if( rc
!=SQLITE_OK
){
6873 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6874 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
6879 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6881 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6882 /******************************************************************************
6883 ** The ".archive" or ".ar" command.
6886 ** Structure representing a single ".ar" command.
6888 typedef struct ArCommand ArCommand
;
6890 u8 eCmd
; /* An AR_CMD_* value */
6891 u8 bVerbose
; /* True if --verbose */
6892 u8 bZip
; /* True if the archive is a ZIP */
6893 u8 bDryRun
; /* True if --dry-run */
6894 u8 bAppend
; /* True if --append */
6895 u8 bGlob
; /* True if --glob */
6896 u8 fromCmdLine
; /* Run from -A instead of .archive */
6897 int nArg
; /* Number of command arguments */
6898 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
6899 const char *zFile
; /* --file argument, or NULL */
6900 const char *zDir
; /* --directory argument, or NULL */
6901 char **azArg
; /* Array of command arguments */
6902 ShellState
*p
; /* Shell state */
6903 sqlite3
*db
; /* Database containing the archive */
6907 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6909 static int arUsage(FILE *f
){
6910 showHelp(f
,"archive");
6911 return SQLITE_ERROR
;
6915 ** Print an error message for the .ar command to stderr and return
6918 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
6922 z
= sqlite3_vmprintf(zFmt
, ap
);
6924 utf8_printf(stderr
, "Error: %s\n", z
);
6925 if( pAr
->fromCmdLine
){
6926 utf8_printf(stderr
, "Use \"-A\" for more help\n");
6928 utf8_printf(stderr
, "Use \".archive --help\" for more help\n");
6931 return SQLITE_ERROR
;
6935 ** Values for ArCommand.eCmd.
6937 #define AR_CMD_CREATE 1
6938 #define AR_CMD_UPDATE 2
6939 #define AR_CMD_INSERT 3
6940 #define AR_CMD_EXTRACT 4
6941 #define AR_CMD_LIST 5
6942 #define AR_CMD_HELP 6
6943 #define AR_CMD_REMOVE 7
6946 ** Other (non-command) switches.
6948 #define AR_SWITCH_VERBOSE 8
6949 #define AR_SWITCH_FILE 9
6950 #define AR_SWITCH_DIRECTORY 10
6951 #define AR_SWITCH_APPEND 11
6952 #define AR_SWITCH_DRYRUN 12
6953 #define AR_SWITCH_GLOB 13
6955 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
6958 case AR_CMD_EXTRACT
:
6965 return arErrorMsg(pAr
, "multiple command options");
6967 pAr
->eCmd
= eSwitch
;
6970 case AR_SWITCH_DRYRUN
:
6973 case AR_SWITCH_GLOB
:
6976 case AR_SWITCH_VERBOSE
:
6979 case AR_SWITCH_APPEND
:
6981 deliberate_fall_through
;
6982 case AR_SWITCH_FILE
:
6985 case AR_SWITCH_DIRECTORY
:
6994 ** Parse the command line for an ".ar" command. The results are written into
6995 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6996 ** successfully, otherwise an error message is written to stderr and
6997 ** SQLITE_ERROR returned.
6999 static int arParseCommand(
7000 char **azArg
, /* Array of arguments passed to dot command */
7001 int nArg
, /* Number of entries in azArg[] */
7002 ArCommand
*pAr
/* Populate this object */
7010 { "create", 'c', AR_CMD_CREATE
, 0 },
7011 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
7012 { "insert", 'i', AR_CMD_INSERT
, 0 },
7013 { "list", 't', AR_CMD_LIST
, 0 },
7014 { "remove", 'r', AR_CMD_REMOVE
, 0 },
7015 { "update", 'u', AR_CMD_UPDATE
, 0 },
7016 { "help", 'h', AR_CMD_HELP
, 0 },
7017 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
7018 { "file", 'f', AR_SWITCH_FILE
, 1 },
7019 { "append", 'a', AR_SWITCH_APPEND
, 1 },
7020 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
7021 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
7022 { "glob", 'g', AR_SWITCH_GLOB
, 0 },
7024 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
7025 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
7028 utf8_printf(stderr
, "Wrong number of arguments. Usage:\n");
7029 return arUsage(stderr
);
7033 /* Traditional style [tar] invocation */
7036 for(i
=0; z
[i
]; i
++){
7037 const char *zArg
= 0;
7038 struct ArSwitch
*pOpt
;
7039 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
7040 if( z
[i
]==pOpt
->cShort
) break;
7043 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
7047 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
7049 zArg
= azArg
[iArg
++];
7051 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
7053 pAr
->nArg
= nArg
-iArg
;
7055 pAr
->azArg
= &azArg
[iArg
];
7058 /* Non-traditional invocation */
7060 for(iArg
=1; iArg
<nArg
; iArg
++){
7064 /* All remaining command line words are command arguments. */
7065 pAr
->azArg
= &azArg
[iArg
];
7066 pAr
->nArg
= nArg
-iArg
;
7073 /* One or more short options */
7075 const char *zArg
= 0;
7076 struct ArSwitch
*pOpt
;
7077 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
7078 if( z
[i
]==pOpt
->cShort
) break;
7081 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
7088 if( iArg
>=(nArg
-1) ){
7089 return arErrorMsg(pAr
, "option requires an argument: %c",
7092 zArg
= azArg
[++iArg
];
7095 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
7097 }else if( z
[2]=='\0' ){
7098 /* A -- option, indicating that all remaining command line words
7099 ** are command arguments. */
7100 pAr
->azArg
= &azArg
[iArg
+1];
7101 pAr
->nArg
= nArg
-iArg
-1;
7105 const char *zArg
= 0; /* Argument for option, if any */
7106 struct ArSwitch
*pMatch
= 0; /* Matching option */
7107 struct ArSwitch
*pOpt
; /* Iterator */
7108 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
7109 const char *zLong
= pOpt
->zLong
;
7110 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
7112 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
7120 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
7123 if( iArg
>=(nArg
-1) ){
7124 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
7126 zArg
= azArg
[++iArg
];
7128 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
7134 utf8_printf(stderr
, "Required argument missing. Usage:\n");
7135 return arUsage(stderr
);
7141 ** This function assumes that all arguments within the ArCommand.azArg[]
7142 ** array refer to archive members, as for the --extract, --list or --remove
7143 ** commands. It checks that each of them are "present". If any specified
7144 ** file is not present in the archive, an error is printed to stderr and an
7145 ** error code returned. Otherwise, if all specified arguments are present
7146 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
7147 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
7148 ** when pAr->bGlob is true.
7150 ** This function strips any trailing '/' characters from each argument.
7151 ** This is consistent with the way the [tar] command seems to work on
7154 static int arCheckEntries(ArCommand
*pAr
){
7158 sqlite3_stmt
*pTest
= 0;
7159 const char *zSel
= (pAr
->bGlob
)
7160 ? "SELECT name FROM %s WHERE glob($name,name)"
7161 : "SELECT name FROM %s WHERE name=$name";
7163 shellPreparePrintf(pAr
->db
, &rc
, &pTest
, zSel
, pAr
->zSrcTable
);
7164 j
= sqlite3_bind_parameter_index(pTest
, "$name");
7165 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7166 char *z
= pAr
->azArg
[i
];
7167 int n
= strlen30(z
);
7169 while( n
>0 && z
[n
-1]=='/' ) n
--;
7171 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
7172 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
7175 shellReset(&rc
, pTest
);
7176 if( rc
==SQLITE_OK
&& bOk
==0 ){
7177 utf8_printf(stderr
, "not found in archive: %s\n", z
);
7181 shellFinalize(&rc
, pTest
);
7187 ** Format a WHERE clause that can be used against the "sqlar" table to
7188 ** identify all archive members that match the command arguments held
7189 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
7190 ** The caller is responsible for eventually calling sqlite3_free() on
7191 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
7192 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
7194 static void arWhereClause(
7197 char **pzWhere
/* OUT: New WHERE clause */
7200 const char *zSameOp
= (pAr
->bGlob
)? "GLOB" : "=";
7201 if( *pRc
==SQLITE_OK
){
7203 zWhere
= sqlite3_mprintf("1");
7206 const char *zSep
= "";
7207 for(i
=0; i
<pAr
->nArg
; i
++){
7208 const char *z
= pAr
->azArg
[i
];
7209 zWhere
= sqlite3_mprintf(
7210 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
7211 zWhere
, zSep
, zSameOp
, z
, strlen30(z
)+1, zSameOp
, z
7214 *pRc
= SQLITE_NOMEM
;
7225 ** Implementation of .ar "lisT" command.
7227 static int arListCommand(ArCommand
*pAr
){
7228 const char *zSql
= "SELECT %s FROM %s WHERE %s";
7229 const char *azCols
[] = {
7231 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
7235 sqlite3_stmt
*pSql
= 0;
7238 rc
= arCheckEntries(pAr
);
7239 arWhereClause(&rc
, pAr
, &zWhere
);
7241 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
7242 pAr
->zSrcTable
, zWhere
);
7244 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
7246 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7247 if( pAr
->bVerbose
){
7248 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
7249 sqlite3_column_text(pSql
, 0),
7250 sqlite3_column_int(pSql
, 1),
7251 sqlite3_column_text(pSql
, 2),
7252 sqlite3_column_text(pSql
, 3)
7255 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
7259 shellFinalize(&rc
, pSql
);
7260 sqlite3_free(zWhere
);
7266 ** Implementation of .ar "Remove" command.
7268 static int arRemoveCommand(ArCommand
*pAr
){
7274 /* Verify that args actually exist within the archive before proceeding.
7275 ** And formulate a WHERE clause to match them. */
7276 rc
= arCheckEntries(pAr
);
7277 arWhereClause(&rc
, pAr
, &zWhere
);
7279 if( rc
==SQLITE_OK
){
7280 zSql
= sqlite3_mprintf("DELETE FROM %s WHERE %s;",
7281 pAr
->zSrcTable
, zWhere
);
7283 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
7286 rc
= sqlite3_exec(pAr
->db
, "SAVEPOINT ar;", 0, 0, 0);
7287 if( rc
==SQLITE_OK
){
7288 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7289 if( rc
!=SQLITE_OK
){
7290 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7292 rc
= sqlite3_exec(pAr
->db
, "RELEASE ar;", 0, 0, 0);
7296 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
7301 sqlite3_free(zWhere
);
7307 ** Implementation of .ar "eXtract" command.
7309 static int arExtractCommand(ArCommand
*pAr
){
7313 " writefile(($dir || name), %s, mode, mtime) "
7314 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
7315 " AND name NOT GLOB '*..[/\\]*'";
7317 const char *azExtraArg
[] = {
7318 "sqlar_uncompress(data, sz)",
7322 sqlite3_stmt
*pSql
= 0;
7328 /* If arguments are specified, check that they actually exist within
7329 ** the archive before proceeding. And formulate a WHERE clause to
7331 rc
= arCheckEntries(pAr
);
7332 arWhereClause(&rc
, pAr
, &zWhere
);
7334 if( rc
==SQLITE_OK
){
7336 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
7338 zDir
= sqlite3_mprintf("");
7340 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
7343 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
7344 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
7347 if( rc
==SQLITE_OK
){
7348 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
7349 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
7351 /* Run the SELECT statement twice. The first time, writefile() is called
7352 ** for all archive members that should be extracted. The second time,
7353 ** only for the directories. This is because the timestamps for
7354 ** extracted directories must be reset after they are populated (as
7355 ** populating them changes the timestamp). */
7357 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
7358 sqlite3_bind_int(pSql
, j
, i
);
7360 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
7362 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7363 if( i
==0 && pAr
->bVerbose
){
7364 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
7368 shellReset(&rc
, pSql
);
7370 shellFinalize(&rc
, pSql
);
7374 sqlite3_free(zWhere
);
7379 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7381 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
7384 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
7388 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7390 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
7399 ** Implementation of .ar "create", "insert", and "update" commands.
7401 ** create -> Create a new SQL archive
7402 ** insert -> Insert or reinsert all files listed
7403 ** update -> Insert files that have changed or that were not
7404 ** previously in the archive
7406 ** Create the "sqlar" table in the database if it does not already exist.
7407 ** Then add each file in the azFile[] array to the archive. Directories
7408 ** are added recursively. If argument bVerbose is non-zero, a message is
7409 ** printed on stdout for each file archived.
7411 ** The create command is the same as update, except that it drops
7412 ** any existing "sqlar" table before beginning. The "insert" command
7413 ** always overwrites every file named on the command-line, where as
7414 ** "update" only overwrites if the size or mtime or mode has changed.
7416 static int arCreateOrUpdateCommand(
7417 ArCommand
*pAr
, /* Command arguments and options */
7418 int bUpdate
, /* true for a --create. */
7419 int bOnlyIfChanged
/* Only update if file has changed */
7421 const char *zCreate
=
7422 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7423 " name TEXT PRIMARY KEY, -- name of the file\n"
7424 " mode INT, -- access permissions\n"
7425 " mtime INT, -- last modification time\n"
7426 " sz INT, -- original file size\n"
7427 " data BLOB -- compressed content\n"
7429 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
7430 const char *zInsertFmt
[2] = {
7431 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7436 " CASE substr(lsmode(mode),1,1)\n"
7437 " WHEN '-' THEN length(data)\n"
7438 " WHEN 'd' THEN 0\n"
7440 " sqlar_compress(data)\n"
7441 " FROM fsdir(%Q,%Q) AS disk\n"
7442 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7444 "REPLACE INTO %s(name,mode,mtime,data)\n"
7450 " FROM fsdir(%Q,%Q) AS disk\n"
7451 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7453 int i
; /* For iterating through azFile[] */
7454 int rc
; /* Return code */
7455 const char *zTab
= 0; /* SQL table into which to insert */
7460 arExecSql(pAr
, "PRAGMA page_size=512");
7461 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
7462 if( rc
!=SQLITE_OK
) return rc
;
7465 /* Initialize the zipfile virtual table, if necessary */
7468 sqlite3_randomness(sizeof(r
),&r
);
7469 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
7471 zSql
= sqlite3_mprintf(
7472 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7475 rc
= arExecSql(pAr
, zSql
);
7481 /* Initialize the table for an SQLAR */
7484 rc
= arExecSql(pAr
, zDrop
);
7485 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
7487 rc
= arExecSql(pAr
, zCreate
);
7489 if( bOnlyIfChanged
){
7490 zExists
= sqlite3_mprintf(
7492 "SELECT 1 FROM %s AS mem"
7493 " WHERE mem.name=disk.name"
7494 " AND mem.mtime=disk.mtime"
7495 " AND mem.mode=disk.mode)", zTab
);
7497 zExists
= sqlite3_mprintf("");
7499 if( zExists
==0 ) rc
= SQLITE_NOMEM
;
7500 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7501 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
7502 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
7503 pAr
->azArg
[i
], pAr
->zDir
, zExists
);
7504 rc
= arExecSql(pAr
, zSql2
);
7505 sqlite3_free(zSql2
);
7508 if( rc
!=SQLITE_OK
){
7509 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7511 rc
= arExecSql(pAr
, "RELEASE ar;");
7512 if( pAr
->bZip
&& pAr
->zFile
){
7513 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
7514 arExecSql(pAr
, zSql
);
7518 sqlite3_free(zExists
);
7523 ** Implementation of ".ar" dot command.
7525 static int arDotCommand(
7526 ShellState
*pState
, /* Current shell tool state */
7527 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
7528 char **azArg
, /* Array of arguments passed to dot command */
7529 int nArg
/* Number of entries in azArg[] */
7533 memset(&cmd
, 0, sizeof(cmd
));
7534 cmd
.fromCmdLine
= fromCmdLine
;
7535 rc
= arParseCommand(azArg
, nArg
, &cmd
);
7536 if( rc
==SQLITE_OK
){
7537 int eDbType
= SHELL_OPEN_UNSPEC
;
7539 cmd
.db
= pState
->db
;
7541 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
7543 eDbType
= pState
->openMode
;
7545 if( eDbType
==SHELL_OPEN_ZIPFILE
){
7546 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
7548 cmd
.zSrcTable
= sqlite3_mprintf("zip");
7550 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
7554 }else if( cmd
.zFile
){
7556 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
7557 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_INSERT
7558 || cmd
.eCmd
==AR_CMD_REMOVE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
7559 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
7561 flags
= SQLITE_OPEN_READONLY
;
7565 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
7566 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
7568 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
7569 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
7570 if( rc
!=SQLITE_OK
){
7571 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
7572 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
7574 goto end_ar_command
;
7576 sqlite3_fileio_init(cmd
.db
, 0, 0);
7577 sqlite3_sqlar_init(cmd
.db
, 0, 0);
7578 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
7579 shellPutsFunc
, 0, 0);
7582 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
7583 if( cmd
.eCmd
!=AR_CMD_CREATE
7584 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
7586 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
7588 goto end_ar_command
;
7590 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
7595 rc
= arCreateOrUpdateCommand(&cmd
, 0, 0);
7598 case AR_CMD_EXTRACT
:
7599 rc
= arExtractCommand(&cmd
);
7603 rc
= arListCommand(&cmd
);
7607 arUsage(pState
->out
);
7611 rc
= arCreateOrUpdateCommand(&cmd
, 1, 0);
7615 rc
= arRemoveCommand(&cmd
);
7619 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
7620 rc
= arCreateOrUpdateCommand(&cmd
, 1, 1);
7625 if( cmd
.db
!=pState
->db
){
7628 sqlite3_free(cmd
.zSrcTable
);
7632 /* End of the ".archive" or ".ar" command logic
7633 *******************************************************************************/
7634 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7636 #if SQLITE_SHELL_HAVE_RECOVER
7639 ** This function is used as a callback by the recover extension. Simply
7640 ** print the supplied SQL statement to stdout.
7642 static int recoverSqlCb(void *pCtx
, const char *zSql
){
7643 ShellState
*pState
= (ShellState
*)pCtx
;
7644 utf8_printf(pState
->out
, "%s;\n", zSql
);
7649 ** This function is called to recover data from the database. A script
7650 ** to construct a new database containing all recovered data is output
7651 ** on stream pState->out.
7653 static int recoverDatabaseCmd(ShellState
*pState
, int nArg
, char **azArg
){
7655 const char *zRecoveryDb
= ""; /* Name of "recovery" database. Debug only */
7656 const char *zLAF
= "lost_and_found";
7657 int bFreelist
= 1; /* 0 if --ignore-freelist is specified */
7658 int bRowids
= 1; /* 0 if --no-rowids */
7659 sqlite3_recover
*p
= 0;
7662 for(i
=1; i
<nArg
; i
++){
7665 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7667 if( n
<=17 && memcmp("-ignore-freelist", z
, n
)==0 ){
7670 if( n
<=12 && memcmp("-recovery-db", z
, n
)==0 && i
<(nArg
-1) ){
7671 /* This option determines the name of the ATTACH-ed database used
7672 ** internally by the recovery extension. The default is "" which
7673 ** means to use a temporary database that is automatically deleted
7674 ** when closed. This option is undocumented and might disappear at
7677 zRecoveryDb
= azArg
[i
];
7679 if( n
<=15 && memcmp("-lost-and-found", z
, n
)==0 && i
<(nArg
-1) ){
7683 if( n
<=10 && memcmp("-no-rowids", z
, n
)==0 ){
7687 utf8_printf(stderr
, "unexpected option: %s\n", azArg
[i
]);
7688 showHelp(pState
->out
, azArg
[0]);
7693 p
= sqlite3_recover_init_sql(
7694 pState
->db
, "main", recoverSqlCb
, (void*)pState
7697 sqlite3_recover_config(p
, 789, (void*)zRecoveryDb
); /* Debug use only */
7698 sqlite3_recover_config(p
, SQLITE_RECOVER_LOST_AND_FOUND
, (void*)zLAF
);
7699 sqlite3_recover_config(p
, SQLITE_RECOVER_ROWIDS
, (void*)&bRowids
);
7700 sqlite3_recover_config(p
, SQLITE_RECOVER_FREELIST_CORRUPT
,(void*)&bFreelist
);
7702 sqlite3_recover_run(p
);
7703 if( sqlite3_recover_errcode(p
)!=SQLITE_OK
){
7704 const char *zErr
= sqlite3_recover_errmsg(p
);
7705 int errCode
= sqlite3_recover_errcode(p
);
7706 raw_printf(stderr
, "sql error: %s (%d)\n", zErr
, errCode
);
7708 rc
= sqlite3_recover_finish(p
);
7711 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7715 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7716 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7717 * close db and set it to 0, and return the columns spec, to later
7718 * be sqlite3_free()'ed by the caller.
7719 * The return is 0 when either:
7720 * (a) The db was not initialized and zCol==0 (There are no columns.)
7721 * (b) zCol!=0 (Column was added, db initialized as needed.)
7722 * The 3rd argument, pRenamed, references an out parameter. If the
7723 * pointer is non-zero, its referent will be set to a summary of renames
7724 * done if renaming was necessary, or set to 0 if none was done. The out
7725 * string (if any) must be sqlite3_free()'ed by the caller.
7728 #define rc_err_oom_die(rc) \
7729 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7730 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7731 fprintf(stderr,"E:%d\n",rc), assert(0)
7733 static void rc_err_oom_die(int rc
){
7734 if( rc
==SQLITE_NOMEM
) shell_check_oom(0);
7735 assert(rc
==SQLITE_OK
||rc
==SQLITE_DONE
);
7739 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7740 static char zCOL_DB
[] = SHELL_STRINGIFY(SHELL_COLFIX_DB
);
7741 #else /* Otherwise, memory is faster/better for the transient DB. */
7742 static const char *zCOL_DB
= ":memory:";
7745 /* Define character (as C string) to separate generated column ordinal
7746 * from protected part of incoming column names. This defaults to "_"
7747 * so that incoming column identifiers that did not need not be quoted
7748 * remain usable without being quoted. It must be one character.
7750 #ifndef SHELL_AUTOCOLUMN_SEP
7751 # define AUTOCOLUMN_SEP "_"
7753 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7756 static char *zAutoColumn(const char *zColNew
, sqlite3
**pDb
, char **pzRenamed
){
7757 /* Queries and D{D,M}L used here */
7758 static const char * const zTabMake
= "\
7759 CREATE TABLE ColNames(\
7760 cpos INTEGER PRIMARY KEY,\
7761 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7762 CREATE VIEW RepeatedNames AS \
7763 SELECT DISTINCT t.name FROM ColNames t \
7764 WHERE t.name COLLATE NOCASE IN (\
7765 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7768 static const char * const zTabFill
= "\
7769 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7770 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7772 static const char * const zHasDupes
= "\
7773 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7774 <count(name) FROM ColNames\
7776 #ifdef SHELL_COLUMN_RENAME_CLEAN
7777 static const char * const zDedoctor
= "\
7778 UPDATE ColNames SET chop=iif(\
7779 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7780 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP
"'),\
7781 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP
"0123456789')),\
7786 static const char * const zSetReps
= "\
7787 UPDATE ColNames AS t SET reps=\
7788 (SELECT count(*) FROM ColNames d \
7789 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7793 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7794 static const char * const zColDigits
= "\
7795 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7798 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7799 static const char * const zColDigits
= "\
7800 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7801 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7802 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7805 static const char * const zRenameRank
=
7806 #ifdef SHELL_COLUMN_RENAME_CLEAN
7807 "UPDATE ColNames AS t SET suff="
7808 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP
"', $1, cpos), '')"
7809 #else /* ...RENAME_MINIMAL_ONE_PASS */
7810 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7813 " SELECT nlz+1 AS nlz FROM Lzn"
7816 " FROM ColNames t, ColNames o"
7818 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7819 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7820 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7824 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7825 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7826 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7830 " AND o.cpos<>t.cpos"
7833 ") UPDATE Colnames AS t SET"
7834 " chop = 0," /* No chopping, never touch incoming names. */
7835 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7836 " printf('"AUTOCOLUMN_SEP
"%s', substring("
7837 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7842 static const char * const zCollectVar
= "\
7847 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7850 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7851 FROM ColNames ORDER BY cpos\
7853 static const char * const zRenamesDone
=
7854 "SELECT group_concat("
7855 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7857 "FROM ColNames WHERE suff<>'' OR chop!=0"
7860 sqlite3_stmt
*pStmt
= 0;
7863 /* Add initial or additional column. Init db if necessary. */
7865 if( SQLITE_OK
!=sqlite3_open(zCOL_DB
, pDb
) ) return 0;
7866 #ifdef SHELL_COLFIX_DB
7868 sqlite3_exec(*pDb
,"drop table if exists ColNames;"
7869 "drop view if exists RepeatedNames;",0,0,0);
7871 rc
= sqlite3_exec(*pDb
, zTabMake
, 0, 0, 0);
7875 rc
= sqlite3_prepare_v2(*pDb
, zTabFill
, -1, &pStmt
, 0);
7877 rc
= sqlite3_bind_text(pStmt
, 1, zColNew
, -1, 0);
7879 rc
= sqlite3_step(pStmt
);
7881 sqlite3_finalize(pStmt
);
7883 }else if( *pDb
==0 ){
7886 /* Formulate the columns spec, close the DB, zero *pDb. */
7887 char *zColsSpec
= 0;
7888 int hasDupes
= db_int(*pDb
, zHasDupes
);
7889 int nDigits
= (hasDupes
)? db_int(*pDb
, zColDigits
) : 0;
7891 #ifdef SHELL_COLUMN_RENAME_CLEAN
7892 rc
= sqlite3_exec(*pDb
, zDedoctor
, 0, 0, 0);
7895 rc
= sqlite3_exec(*pDb
, zSetReps
, 0, 0, 0);
7897 rc
= sqlite3_prepare_v2(*pDb
, zRenameRank
, -1, &pStmt
, 0);
7899 sqlite3_bind_int(pStmt
, 1, nDigits
);
7900 rc
= sqlite3_step(pStmt
);
7901 sqlite3_finalize(pStmt
);
7902 if( rc
!=SQLITE_DONE
) rc_err_oom_die(SQLITE_NOMEM
);
7904 assert(db_int(*pDb
, zHasDupes
)==0); /* Consider: remove this */
7905 rc
= sqlite3_prepare_v2(*pDb
, zCollectVar
, -1, &pStmt
, 0);
7907 rc
= sqlite3_step(pStmt
);
7908 if( rc
==SQLITE_ROW
){
7909 zColsSpec
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7914 if( !hasDupes
) *pzRenamed
= 0;
7916 sqlite3_finalize(pStmt
);
7917 if( SQLITE_OK
==sqlite3_prepare_v2(*pDb
, zRenamesDone
, -1, &pStmt
, 0)
7918 && SQLITE_ROW
==sqlite3_step(pStmt
) ){
7919 *pzRenamed
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7924 sqlite3_finalize(pStmt
);
7925 sqlite3_close(*pDb
);
7932 ** If an input line begins with "." then invoke this routine to
7933 ** process that line.
7935 ** Return 1 on error, 2 to exit, and 0 otherwise.
7937 static int do_meta_command(char *zLine
, ShellState
*p
){
7944 #ifndef SQLITE_OMIT_VIRTUALTABLE
7945 if( p
->expert
.pExpert
){
7946 expertFinish(p
, 1, 0);
7950 /* Parse the input line into tokens.
7952 while( zLine
[h
] && nArg
<ArraySize(azArg
)-1 ){
7953 while( IsSpace(zLine
[h
]) ){ h
++; }
7954 if( zLine
[h
]==0 ) break;
7955 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
7956 int delim
= zLine
[h
++];
7957 azArg
[nArg
++] = &zLine
[h
];
7958 while( zLine
[h
] && zLine
[h
]!=delim
){
7959 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
7962 if( zLine
[h
]==delim
){
7965 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
7967 azArg
[nArg
++] = &zLine
[h
];
7968 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
7969 if( zLine
[h
] ) zLine
[h
++] = 0;
7970 resolve_backslashes(azArg
[nArg
-1]);
7975 /* Process the input line.
7977 if( nArg
==0 ) return 0; /* no tokens, no error */
7978 n
= strlen30(azArg
[0]);
7982 #ifndef SQLITE_OMIT_AUTHORIZATION
7983 if( c
=='a' && cli_strncmp(azArg
[0], "auth", n
)==0 ){
7985 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
7987 goto meta_command_exit
;
7990 if( booleanValue(azArg
[1]) ){
7991 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
7992 }else if( p
->bSafeModePersist
){
7993 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
7995 sqlite3_set_authorizer(p
->db
, 0, 0);
8000 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8001 && !defined(SQLITE_SHELL_FIDDLE)
8002 if( c
=='a' && cli_strncmp(azArg
[0], "archive", n
)==0 ){
8004 failIfSafeMode(p
, "cannot run .archive in safe mode");
8005 rc
= arDotCommand(p
, 0, azArg
, nArg
);
8009 #ifndef SQLITE_SHELL_FIDDLE
8010 if( (c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "backup", n
)==0)
8011 || (c
=='s' && n
>=3 && cli_strncmp(azArg
[0], "save", n
)==0)
8013 const char *zDestFile
= 0;
8014 const char *zDb
= 0;
8016 sqlite3_backup
*pBackup
;
8019 const char *zVfs
= 0;
8020 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
8021 for(j
=1; j
<nArg
; j
++){
8022 const char *z
= azArg
[j
];
8024 if( z
[1]=='-' ) z
++;
8025 if( cli_strcmp(z
, "-append")==0 ){
8028 if( cli_strcmp(z
, "-async")==0 ){
8032 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
8035 }else if( zDestFile
==0 ){
8036 zDestFile
= azArg
[j
];
8039 zDestFile
= azArg
[j
];
8041 raw_printf(stderr
, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8046 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
8049 if( zDb
==0 ) zDb
= "main";
8050 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
8051 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
8052 if( rc
!=SQLITE_OK
){
8053 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
8058 sqlite3_exec(pDest
, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8062 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
8064 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
8068 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
8069 sqlite3_backup_finish(pBackup
);
8070 if( rc
==SQLITE_DONE
){
8073 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
8078 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8080 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "bail", n
)==0 ){
8082 bail_on_error
= booleanValue(azArg
[1]);
8084 raw_printf(stderr
, "Usage: .bail on|off\n");
8089 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "binary", n
)==0 ){
8091 if( booleanValue(azArg
[1]) ){
8092 setBinaryMode(p
->out
, 1);
8094 setTextMode(p
->out
, 1);
8097 raw_printf(stderr
, "Usage: .binary on|off\n");
8102 /* The undocumented ".breakpoint" command causes a call to the no-op
8103 ** routine named test_breakpoint().
8105 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "breakpoint", n
)==0 ){
8109 #ifndef SQLITE_SHELL_FIDDLE
8110 if( c
=='c' && cli_strcmp(azArg
[0],"cd")==0 ){
8111 failIfSafeMode(p
, "cannot run .cd in safe mode");
8113 #if defined(_WIN32) || defined(WIN32)
8114 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
8115 rc
= !SetCurrentDirectoryW(z
);
8118 rc
= chdir(azArg
[1]);
8121 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
8125 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
8129 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8131 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "changes", n
)==0 ){
8133 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
8135 raw_printf(stderr
, "Usage: .changes on|off\n");
8140 #ifndef SQLITE_SHELL_FIDDLE
8141 /* Cancel output redirection, if it is currently set (by .testcase)
8142 ** Then read the content of the testcase-out.txt file and compare against
8143 ** azArg[1]. If there are differences, report an error and exit.
8145 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "check", n
)==0 ){
8149 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
8151 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
8153 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
8155 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
8156 p
->zTestcase
, azArg
[1], zRes
);
8159 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
8164 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8166 #ifndef SQLITE_SHELL_FIDDLE
8167 if( c
=='c' && cli_strncmp(azArg
[0], "clone", n
)==0 ){
8168 failIfSafeMode(p
, "cannot run .clone in safe mode");
8170 tryToClone(p
, azArg
[1]);
8172 raw_printf(stderr
, "Usage: .clone FILENAME\n");
8176 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8178 if( c
=='c' && cli_strncmp(azArg
[0], "connection", n
)==0 ){
8180 /* List available connections */
8182 for(i
=0; i
<ArraySize(p
->aAuxDb
); i
++){
8183 const char *zFile
= p
->aAuxDb
[i
].zDbFilename
;
8184 if( p
->aAuxDb
[i
].db
==0 && p
->pAuxDb
!=&p
->aAuxDb
[i
] ){
8185 zFile
= "(not open)";
8186 }else if( zFile
==0 ){
8188 }else if( zFile
[0]==0 ){
8189 zFile
= "(temporary-file)";
8191 if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
8192 utf8_printf(stdout
, "ACTIVE %d: %s\n", i
, zFile
);
8193 }else if( p
->aAuxDb
[i
].db
!=0 ){
8194 utf8_printf(stdout
, " %d: %s\n", i
, zFile
);
8197 }else if( nArg
==2 && IsDigit(azArg
[1][0]) && azArg
[1][1]==0 ){
8198 int i
= azArg
[1][0] - '0';
8199 if( p
->pAuxDb
!= &p
->aAuxDb
[i
] && i
>=0 && i
<ArraySize(p
->aAuxDb
) ){
8200 p
->pAuxDb
->db
= p
->db
;
8201 p
->pAuxDb
= &p
->aAuxDb
[i
];
8202 globalDb
= p
->db
= p
->pAuxDb
->db
;
8205 }else if( nArg
==3 && cli_strcmp(azArg
[1], "close")==0
8206 && IsDigit(azArg
[2][0]) && azArg
[2][1]==0 ){
8207 int i
= azArg
[2][0] - '0';
8208 if( i
<0 || i
>=ArraySize(p
->aAuxDb
) ){
8210 }else if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
8211 raw_printf(stderr
, "cannot close the active database connection\n");
8213 }else if( p
->aAuxDb
[i
].db
){
8214 session_close_all(p
, i
);
8215 close_db(p
->aAuxDb
[i
].db
);
8216 p
->aAuxDb
[i
].db
= 0;
8219 raw_printf(stderr
, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8224 if( c
=='d' && n
>1 && cli_strncmp(azArg
[0], "databases", n
)==0 ){
8227 sqlite3_stmt
*pStmt
;
8230 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
8232 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
8235 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
8236 const char *zSchema
= (const char *)sqlite3_column_text(pStmt
,1);
8237 const char *zFile
= (const char*)sqlite3_column_text(pStmt
,2);
8238 if( zSchema
==0 || zFile
==0 ) continue;
8239 azName
= sqlite3_realloc(azName
, (nName
+1)*2*sizeof(char*));
8240 shell_check_oom(azName
);
8241 azName
[nName
*2] = strdup(zSchema
);
8242 azName
[nName
*2+1] = strdup(zFile
);
8246 sqlite3_finalize(pStmt
);
8247 for(i
=0; i
<nName
; i
++){
8248 int eTxn
= sqlite3_txn_state(p
->db
, azName
[i
*2]);
8249 int bRdonly
= sqlite3_db_readonly(p
->db
, azName
[i
*2]);
8250 const char *z
= azName
[i
*2+1];
8251 utf8_printf(p
->out
, "%s: %s %s%s\n",
8253 z
&& z
[0] ? z
: "\"\"",
8254 bRdonly
? "r/o" : "r/w",
8255 eTxn
==SQLITE_TXN_NONE
? "" :
8256 eTxn
==SQLITE_TXN_READ
? " read-txn" : " write-txn");
8258 free(azName
[i
*2+1]);
8260 sqlite3_free(azName
);
8263 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbconfig", n
)==0 ){
8264 static const struct DbConfigChoices
{
8268 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
8269 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
8270 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
8271 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
8272 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
8273 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
8274 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
8275 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
8276 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
8277 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
8278 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
8279 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
8280 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
8281 { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER
},
8282 { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS
},
8283 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
8284 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
8285 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
8289 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
8290 if( nArg
>1 && cli_strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
8292 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
8294 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
8295 utf8_printf(p
->out
, "%19s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
8298 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
8299 utf8_printf(stderr
, "Error: unknown dbconfig \"%s\"\n", azArg
[1]);
8300 utf8_printf(stderr
, "Enter \".dbconfig\" with no arguments for a list\n");
8304 #if SQLITE_SHELL_HAVE_RECOVER
8305 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbinfo", n
)==0 ){
8306 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
8309 if( c
=='r' && cli_strncmp(azArg
[0], "recover", n
)==0 ){
8311 rc
= recoverDatabaseCmd(p
, nArg
, azArg
);
8313 #endif /* SQLITE_SHELL_HAVE_RECOVER */
8315 if( c
=='d' && cli_strncmp(azArg
[0], "dump", n
)==0 ){
8319 int savedShowHeader
= p
->showHeader
;
8320 int savedShellFlags
= p
->shellFlgs
;
8322 SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
8323 |SHFLG_DumpDataOnly
|SHFLG_DumpNoSys
);
8324 for(i
=1; i
<nArg
; i
++){
8325 if( azArg
[i
][0]=='-' ){
8326 const char *z
= azArg
[i
]+1;
8327 if( z
[0]=='-' ) z
++;
8328 if( cli_strcmp(z
,"preserve-rowids")==0 ){
8329 #ifdef SQLITE_OMIT_VIRTUALTABLE
8330 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
8331 " with SQLITE_OMIT_VIRTUALTABLE\n");
8333 sqlite3_free(zLike
);
8334 goto meta_command_exit
;
8336 ShellSetFlag(p
, SHFLG_PreserveRowid
);
8339 if( cli_strcmp(z
,"newlines")==0 ){
8340 ShellSetFlag(p
, SHFLG_Newlines
);
8342 if( cli_strcmp(z
,"data-only")==0 ){
8343 ShellSetFlag(p
, SHFLG_DumpDataOnly
);
8345 if( cli_strcmp(z
,"nosys")==0 ){
8346 ShellSetFlag(p
, SHFLG_DumpNoSys
);
8349 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
8351 sqlite3_free(zLike
);
8352 goto meta_command_exit
;
8355 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8356 ** only dump data for tables for which either the table name matches
8357 ** the LIKE pattern, or the table appears to be a shadow table of
8358 ** a virtual table for which the name matches the LIKE pattern.
8360 char *zExpr
= sqlite3_mprintf(
8361 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8362 " SELECT 1 FROM sqlite_schema WHERE "
8363 " name LIKE %Q ESCAPE '\\' AND"
8364 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8365 " substr(o.name, 1, length(name)+1) == (name||'_')"
8366 ")", azArg
[i
], azArg
[i
]
8370 zLike
= sqlite3_mprintf("%z OR %z", zLike
, zExpr
);
8379 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8380 /* When playing back a "dump", the content might appear in an order
8381 ** which causes immediate foreign key constraints to be violated.
8382 ** So disable foreign-key constraint enforcement to prevent problems. */
8383 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
8384 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
8386 p
->writableSchema
= 0;
8388 /* Set writable_schema=ON since doing so forces SQLite to initialize
8389 ** as much of the schema as it can even if the sqlite_schema table is
8391 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8393 if( zLike
==0 ) zLike
= sqlite3_mprintf("true");
8394 zSql
= sqlite3_mprintf(
8395 "SELECT name, type, sql FROM sqlite_schema AS o "
8396 "WHERE (%s) AND type=='table'"
8398 " ORDER BY tbl_name='sqlite_sequence', rowid",
8401 run_schema_dump_query(p
,zSql
);
8403 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8404 zSql
= sqlite3_mprintf(
8405 "SELECT sql FROM sqlite_schema AS o "
8406 "WHERE (%s) AND sql NOT NULL"
8407 " AND type IN ('index','trigger','view')",
8410 run_table_dump_query(p
, zSql
);
8413 sqlite3_free(zLike
);
8414 if( p
->writableSchema
){
8415 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
8416 p
->writableSchema
= 0;
8418 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8419 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
8420 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8421 raw_printf(p
->out
, p
->nErr
?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8423 p
->showHeader
= savedShowHeader
;
8424 p
->shellFlgs
= savedShellFlags
;
8427 if( c
=='e' && cli_strncmp(azArg
[0], "echo", n
)==0 ){
8429 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
8431 raw_printf(stderr
, "Usage: .echo on|off\n");
8436 if( c
=='e' && cli_strncmp(azArg
[0], "eqp", n
)==0 ){
8439 if( p
->autoEQPtrace
){
8440 if( p
->db
) sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8441 p
->autoEQPtrace
= 0;
8443 if( cli_strcmp(azArg
[1],"full")==0 ){
8444 p
->autoEQP
= AUTOEQP_full
;
8445 }else if( cli_strcmp(azArg
[1],"trigger")==0 ){
8446 p
->autoEQP
= AUTOEQP_trigger
;
8448 }else if( cli_strcmp(azArg
[1],"test")==0 ){
8449 p
->autoEQP
= AUTOEQP_on
;
8451 }else if( cli_strcmp(azArg
[1],"trace")==0 ){
8452 p
->autoEQP
= AUTOEQP_full
;
8453 p
->autoEQPtrace
= 1;
8455 sqlite3_exec(p
->db
, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8456 sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8459 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
8462 raw_printf(stderr
, "Usage: .eqp off|on|trace|trigger|full\n");
8467 #ifndef SQLITE_SHELL_FIDDLE
8468 if( c
=='e' && cli_strncmp(azArg
[0], "exit", n
)==0 ){
8469 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
8474 /* The ".explain" command is automatic now. It is largely pointless. It
8475 ** retained purely for backwards compatibility */
8476 if( c
=='e' && cli_strncmp(azArg
[0], "explain", n
)==0 ){
8479 if( cli_strcmp(azArg
[1],"auto")==0 ){
8482 val
= booleanValue(azArg
[1]);
8485 if( val
==1 && p
->mode
!=MODE_Explain
){
8486 p
->normalMode
= p
->mode
;
8487 p
->mode
= MODE_Explain
;
8490 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8492 }else if( val
==99 ){
8493 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8498 #ifndef SQLITE_OMIT_VIRTUALTABLE
8499 if( c
=='e' && cli_strncmp(azArg
[0], "expert", n
)==0 ){
8502 "Cannot run experimental commands such as \"%s\" in safe mode\n",
8507 expertDotCommand(p
, azArg
, nArg
);
8512 if( c
=='f' && cli_strncmp(azArg
[0], "filectrl", n
)==0 ){
8513 static const struct {
8514 const char *zCtrlName
; /* Name of a test-control option */
8515 int ctrlCode
; /* Integer code for that option */
8516 const char *zUsage
; /* Usage notes */
8518 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE
, "SIZE" },
8519 { "data_version", SQLITE_FCNTL_DATA_VERSION
, "" },
8520 { "has_moved", SQLITE_FCNTL_HAS_MOVED
, "" },
8521 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT
, "MILLISEC" },
8522 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL
, "[BOOLEAN]" },
8523 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8524 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE
, "[BOOLEAN]" },
8525 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES
, "[N]" },
8526 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT
, "[LIMIT]" },
8527 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME
, "" },
8528 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8532 sqlite3_int64 iRes
= 0; /* Integer result to display if rc2==1 */
8533 int isOk
= 0; /* 0: usage 1: %lld 2: no-result */
8535 const char *zCmd
= 0;
8536 const char *zSchema
= 0;
8539 zCmd
= nArg
>=2 ? azArg
[1] : "help";
8542 && (cli_strcmp(zCmd
,"--schema")==0 || cli_strcmp(zCmd
,"-schema")==0)
8546 for(i
=3; i
<nArg
; i
++) azArg
[i
-2] = azArg
[i
];
8551 /* The argument can optionally begin with "-" or "--" */
8552 if( zCmd
[0]=='-' && zCmd
[1] ){
8554 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
8557 /* --help lists all file-controls */
8558 if( cli_strcmp(zCmd
,"help")==0 ){
8559 utf8_printf(p
->out
, "Available file-controls:\n");
8560 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8561 utf8_printf(p
->out
, " .filectrl %s %s\n",
8562 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
8565 goto meta_command_exit
;
8568 /* convert filectrl text option to value. allow any unique prefix
8569 ** of the option name, or a numerical value. */
8570 n2
= strlen30(zCmd
);
8571 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8572 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
8574 filectrl
= aCtrl
[i
].ctrlCode
;
8577 utf8_printf(stderr
, "Error: ambiguous file-control: \"%s\"\n"
8578 "Use \".filectrl --help\" for help\n", zCmd
);
8580 goto meta_command_exit
;
8585 utf8_printf(stderr
,"Error: unknown file-control: %s\n"
8586 "Use \".filectrl --help\" for help\n", zCmd
);
8589 case SQLITE_FCNTL_SIZE_LIMIT
: {
8590 if( nArg
!=2 && nArg
!=3 ) break;
8591 iRes
= nArg
==3 ? integerValue(azArg
[2]) : -1;
8592 sqlite3_file_control(p
->db
, zSchema
, SQLITE_FCNTL_SIZE_LIMIT
, &iRes
);
8596 case SQLITE_FCNTL_LOCK_TIMEOUT
:
8597 case SQLITE_FCNTL_CHUNK_SIZE
: {
8599 if( nArg
!=3 ) break;
8600 x
= (int)integerValue(azArg
[2]);
8601 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8605 case SQLITE_FCNTL_PERSIST_WAL
:
8606 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
8608 if( nArg
!=2 && nArg
!=3 ) break;
8609 x
= nArg
==3 ? booleanValue(azArg
[2]) : -1;
8610 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8615 case SQLITE_FCNTL_DATA_VERSION
:
8616 case SQLITE_FCNTL_HAS_MOVED
: {
8618 if( nArg
!=2 ) break;
8619 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8624 case SQLITE_FCNTL_TEMPFILENAME
: {
8626 if( nArg
!=2 ) break;
8627 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &z
);
8629 utf8_printf(p
->out
, "%s\n", z
);
8635 case SQLITE_FCNTL_RESERVE_BYTES
: {
8639 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8642 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8643 utf8_printf(p
->out
,"%d\n", x
);
8649 if( isOk
==0 && iCtrl
>=0 ){
8650 utf8_printf(p
->out
, "Usage: .filectrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
8652 }else if( isOk
==1 ){
8654 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%lld", iRes
);
8655 raw_printf(p
->out
, "%s\n", zBuf
);
8659 if( c
=='f' && cli_strncmp(azArg
[0], "fullschema", n
)==0 ){
8662 memcpy(&data
, p
, sizeof(data
));
8663 data
.showHeader
= 0;
8664 data
.cMode
= data
.mode
= MODE_Semi
;
8665 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
8666 data
.cMode
= data
.mode
= MODE_Pretty
;
8670 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
8672 goto meta_command_exit
;
8675 rc
= sqlite3_exec(p
->db
,
8677 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8678 " FROM sqlite_schema UNION ALL"
8679 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8680 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8684 if( rc
==SQLITE_OK
){
8685 sqlite3_stmt
*pStmt
;
8686 rc
= sqlite3_prepare_v2(p
->db
,
8687 "SELECT rowid FROM sqlite_schema"
8688 " WHERE name GLOB 'sqlite_stat[134]'",
8690 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
8691 sqlite3_finalize(pStmt
);
8694 raw_printf(p
->out
, "/* No STAT tables available */\n");
8696 raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
8697 data
.cMode
= data
.mode
= MODE_Insert
;
8698 data
.zDestTable
= "sqlite_stat1";
8699 shell_exec(&data
, "SELECT * FROM sqlite_stat1", 0);
8700 data
.zDestTable
= "sqlite_stat4";
8701 shell_exec(&data
, "SELECT * FROM sqlite_stat4", 0);
8702 raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
8706 if( c
=='h' && cli_strncmp(azArg
[0], "headers", n
)==0 ){
8708 p
->showHeader
= booleanValue(azArg
[1]);
8709 p
->shellFlgs
|= SHFLG_HeaderSet
;
8711 raw_printf(stderr
, "Usage: .headers on|off\n");
8716 if( c
=='h' && cli_strncmp(azArg
[0], "help", n
)==0 ){
8718 n
= showHelp(p
->out
, azArg
[1]);
8720 utf8_printf(p
->out
, "Nothing matches '%s'\n", azArg
[1]);
8723 showHelp(p
->out
, 0);
8727 #ifndef SQLITE_SHELL_FIDDLE
8728 if( c
=='i' && cli_strncmp(azArg
[0], "import", n
)==0 ){
8729 char *zTable
= 0; /* Insert data into this table */
8730 char *zSchema
= 0; /* within this schema (may default to "main") */
8731 char *zFile
= 0; /* Name of file to extra content from */
8732 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
8733 int nCol
; /* Number of columns in the table */
8734 int nByte
; /* Number of bytes in an SQL string */
8735 int i
, j
; /* Loop counters */
8736 int needCommit
; /* True to COMMIT or ROLLBACK at end */
8737 int nSep
; /* Number of bytes in p->colSeparator[] */
8738 char *zSql
; /* An SQL statement */
8739 char *zFullTabName
; /* Table name with schema if applicable */
8740 ImportCtx sCtx
; /* Reader context */
8741 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
8742 int eVerbose
= 0; /* Larger for more console output */
8743 int nSkip
= 0; /* Initial lines to skip */
8744 int useOutputMode
= 1; /* Use output mode to determine separators */
8745 char *zCreate
= 0; /* CREATE TABLE statement text */
8747 failIfSafeMode(p
, "cannot run .import in safe mode");
8748 memset(&sCtx
, 0, sizeof(sCtx
));
8749 if( p
->mode
==MODE_Ascii
){
8750 xRead
= ascii_read_one_field
;
8752 xRead
= csv_read_one_field
;
8755 for(i
=1; i
<nArg
; i
++){
8757 if( z
[0]=='-' && z
[1]=='-' ) z
++;
8761 }else if( zTable
==0 ){
8764 utf8_printf(p
->out
, "ERROR: extra argument: \"%s\". Usage:\n", z
);
8765 showHelp(p
->out
, "import");
8766 goto meta_command_exit
;
8768 }else if( cli_strcmp(z
,"-v")==0 ){
8770 }else if( cli_strcmp(z
,"-schema")==0 && i
<nArg
-1 ){
8771 zSchema
= azArg
[++i
];
8772 }else if( cli_strcmp(z
,"-skip")==0 && i
<nArg
-1 ){
8773 nSkip
= integerValue(azArg
[++i
]);
8774 }else if( cli_strcmp(z
,"-ascii")==0 ){
8775 sCtx
.cColSep
= SEP_Unit
[0];
8776 sCtx
.cRowSep
= SEP_Record
[0];
8777 xRead
= ascii_read_one_field
;
8779 }else if( cli_strcmp(z
,"-csv")==0 ){
8781 sCtx
.cRowSep
= '\n';
8782 xRead
= csv_read_one_field
;
8785 utf8_printf(p
->out
, "ERROR: unknown option: \"%s\". Usage:\n", z
);
8786 showHelp(p
->out
, "import");
8787 goto meta_command_exit
;
8791 utf8_printf(p
->out
, "ERROR: missing %s argument. Usage:\n",
8792 zFile
==0 ? "FILE" : "TABLE");
8793 showHelp(p
->out
, "import");
8794 goto meta_command_exit
;
8798 if( useOutputMode
){
8799 /* If neither the --csv or --ascii options are specified, then set
8800 ** the column and row separator characters from the output mode. */
8801 nSep
= strlen30(p
->colSeparator
);
8804 "Error: non-null column separator required for import\n");
8805 goto meta_command_exit
;
8809 "Error: multi-character column separators not allowed"
8811 goto meta_command_exit
;
8813 nSep
= strlen30(p
->rowSeparator
);
8816 "Error: non-null row separator required for import\n");
8817 goto meta_command_exit
;
8819 if( nSep
==2 && p
->mode
==MODE_Csv
8820 && cli_strcmp(p
->rowSeparator
,SEP_CrLf
)==0
8822 /* When importing CSV (only), if the row separator is set to the
8823 ** default output row separator, change it to the default input
8824 ** row separator. This avoids having to maintain different input
8825 ** and output row separators. */
8826 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8827 nSep
= strlen30(p
->rowSeparator
);
8830 raw_printf(stderr
, "Error: multi-character row separators not allowed"
8832 goto meta_command_exit
;
8834 sCtx
.cColSep
= (u8
)p
->colSeparator
[0];
8835 sCtx
.cRowSep
= (u8
)p
->rowSeparator
[0];
8839 if( sCtx
.zFile
[0]=='|' ){
8840 #ifdef SQLITE_OMIT_POPEN
8841 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
8842 goto meta_command_exit
;
8844 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
8845 sCtx
.zFile
= "<pipe>";
8846 sCtx
.xCloser
= pclose
;
8849 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
8850 sCtx
.xCloser
= fclose
;
8853 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
8854 goto meta_command_exit
;
8856 if( eVerbose
>=2 || (eVerbose
>=1 && useOutputMode
) ){
8859 zSep
[0] = sCtx
.cColSep
;
8860 utf8_printf(p
->out
, "Column separator ");
8861 output_c_string(p
->out
, zSep
);
8862 utf8_printf(p
->out
, ", row separator ");
8863 zSep
[0] = sCtx
.cRowSep
;
8864 output_c_string(p
->out
, zSep
);
8865 utf8_printf(p
->out
, "\n");
8867 sCtx
.z
= sqlite3_malloc64(120);
8869 import_cleanup(&sCtx
);
8870 shell_out_of_memory();
8872 /* Below, resources must be freed before exit. */
8873 while( (nSkip
--)>0 ){
8874 while( xRead(&sCtx
) && sCtx
.cTerm
==sCtx
.cColSep
){}
8877 zFullTabName
= sqlite3_mprintf("\"%w\".\"%w\"", zSchema
, zTable
);
8879 zFullTabName
= sqlite3_mprintf("\"%w\"", zTable
);
8881 zSql
= sqlite3_mprintf("SELECT * FROM %s", zFullTabName
);
8882 if( zSql
==0 || zFullTabName
==0 ){
8883 import_cleanup(&sCtx
);
8884 shell_out_of_memory();
8886 nByte
= strlen30(zSql
);
8887 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8888 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
8889 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
8890 sqlite3
*dbCols
= 0;
8893 zCreate
= sqlite3_mprintf("CREATE TABLE %s", zFullTabName
);
8894 while( xRead(&sCtx
) ){
8895 zAutoColumn(sCtx
.z
, &dbCols
, 0);
8896 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
8898 zColDefs
= zAutoColumn(0, &dbCols
, &zRenames
);
8900 utf8_printf((stdin_is_interactive
&& p
->in
==stdin
)? p
->out
: stderr
,
8901 "Columns renamed during .import %s due to duplicates:\n"
8902 "%s\n", sCtx
.zFile
, zRenames
);
8903 sqlite3_free(zRenames
);
8907 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
8909 sqlite3_free(zCreate
);
8911 sqlite3_free(zFullTabName
);
8912 import_cleanup(&sCtx
);
8914 goto meta_command_exit
;
8916 zCreate
= sqlite3_mprintf("%z%z\n", zCreate
, zColDefs
);
8918 utf8_printf(p
->out
, "%s\n", zCreate
);
8920 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
8922 utf8_printf(stderr
, "%s failed:\n%s\n", zCreate
, sqlite3_errmsg(p
->db
));
8925 sqlite3_free(zCreate
);
8927 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8930 if (pStmt
) sqlite3_finalize(pStmt
);
8931 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
8935 nCol
= sqlite3_column_count(pStmt
);
8936 sqlite3_finalize(pStmt
);
8938 if( nCol
==0 ) return 0; /* no columns, no error */
8939 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
8941 import_cleanup(&sCtx
);
8942 shell_out_of_memory();
8944 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO %s VALUES(?", zFullTabName
);
8946 for(i
=1; i
<nCol
; i
++){
8953 utf8_printf(p
->out
, "Insert using: %s\n", zSql
);
8955 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8957 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
8958 if (pStmt
) sqlite3_finalize(pStmt
);
8962 sqlite3_free(zFullTabName
);
8963 needCommit
= sqlite3_get_autocommit(p
->db
);
8964 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
8966 int startLine
= sCtx
.nLine
;
8967 for(i
=0; i
<nCol
; i
++){
8968 char *z
= xRead(&sCtx
);
8970 ** Did we reach end-of-file before finding any columns?
8971 ** If so, stop instead of NULL filling the remaining columns.
8973 if( z
==0 && i
==0 ) break;
8975 ** Did we reach end-of-file OR end-of-line before finding any
8976 ** columns in ASCII mode? If so, stop instead of NULL filling
8977 ** the remaining columns.
8979 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
8980 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
8981 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
8982 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
8983 "filling the rest with NULL\n",
8984 sCtx
.zFile
, startLine
, nCol
, i
+1);
8986 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
8989 if( sCtx
.cTerm
==sCtx
.cColSep
){
8993 }while( sCtx
.cTerm
==sCtx
.cColSep
);
8994 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
8996 sCtx
.zFile
, startLine
, nCol
, i
);
8999 sqlite3_step(pStmt
);
9000 rc
= sqlite3_reset(pStmt
);
9001 if( rc
!=SQLITE_OK
){
9002 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
9003 startLine
, sqlite3_errmsg(p
->db
));
9009 }while( sCtx
.cTerm
!=EOF
);
9011 import_cleanup(&sCtx
);
9012 sqlite3_finalize(pStmt
);
9013 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
9016 "Added %d rows with %d errors using %d lines of input\n",
9017 sCtx
.nRow
, sCtx
.nErr
, sCtx
.nLine
-1);
9020 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9022 #ifndef SQLITE_UNTESTABLE
9023 if( c
=='i' && cli_strncmp(azArg
[0], "imposter", n
)==0 ){
9026 sqlite3_stmt
*pStmt
;
9028 int isWO
= 0; /* True if making an imposter of a WITHOUT ROWID table */
9029 int lenPK
= 0; /* Length of the PRIMARY KEY string for isWO tables */
9031 if( !ShellHasFlag(p
,SHFLG_TestingMode
) ){
9032 utf8_printf(stderr
, ".%s unavailable without --unsafe-testing\n",
9035 goto meta_command_exit
;
9037 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
9038 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n"
9039 " .imposter off\n");
9040 /* Also allowed, but not documented:
9042 ** .imposter TABLE IMPOSTER
9044 ** where TABLE is a WITHOUT ROWID table. In that case, the
9045 ** imposter is another WITHOUT ROWID table with the columns in
9046 ** storage order. */
9048 goto meta_command_exit
;
9052 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
9053 goto meta_command_exit
;
9055 zSql
= sqlite3_mprintf(
9056 "SELECT rootpage, 0 FROM sqlite_schema"
9057 " WHERE name='%q' AND type='index'"
9059 "SELECT rootpage, 1 FROM sqlite_schema"
9060 " WHERE name='%q' AND type='table'"
9061 " AND sql LIKE '%%without%%rowid%%'",
9064 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9066 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
9067 tnum
= sqlite3_column_int(pStmt
, 0);
9068 isWO
= sqlite3_column_int(pStmt
, 1);
9070 sqlite3_finalize(pStmt
);
9071 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
9072 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9075 while( rc
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9077 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
9080 if( sqlite3_column_int(pStmt
,1)==-1 ){
9083 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
9087 if( isWO
&& lenPK
==0 && sqlite3_column_int(pStmt
,5)==0 && zCollist
){
9088 lenPK
= (int)strlen(zCollist
);
9091 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
9093 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
9096 sqlite3_finalize(pStmt
);
9097 if( i
==0 || tnum
==0 ){
9098 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
9100 sqlite3_free(zCollist
);
9101 goto meta_command_exit
;
9103 if( lenPK
==0 ) lenPK
= 100000;
9104 zSql
= sqlite3_mprintf(
9105 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9106 azArg
[2], zCollist
, lenPK
, zCollist
);
9107 sqlite3_free(zCollist
);
9108 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
9109 if( rc
==SQLITE_OK
){
9110 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9111 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
9113 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
9115 utf8_printf(stdout
, "%s;\n", zSql
);
9117 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9118 azArg
[1], isWO
? "table" : "index"
9122 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
9127 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9129 #ifdef SQLITE_ENABLE_IOTRACE
9130 if( c
=='i' && cli_strncmp(azArg
[0], "iotrace", n
)==0 ){
9131 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
9132 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
9136 }else if( cli_strcmp(azArg
[1], "-")==0 ){
9137 sqlite3IoTrace
= iotracePrintf
;
9140 iotrace
= fopen(azArg
[1], "w");
9142 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
9146 sqlite3IoTrace
= iotracePrintf
;
9152 if( c
=='l' && n
>=5 && cli_strncmp(azArg
[0], "limits", n
)==0 ){
9153 static const struct {
9154 const char *zLimitName
; /* Name of a limit */
9155 int limitCode
; /* Integer code for that limit */
9157 { "length", SQLITE_LIMIT_LENGTH
},
9158 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
9159 { "column", SQLITE_LIMIT_COLUMN
},
9160 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
9161 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
9162 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
9163 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
9164 { "attached", SQLITE_LIMIT_ATTACHED
},
9165 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
9166 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
9167 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
9168 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
9173 for(i
=0; i
<ArraySize(aLimit
); i
++){
9174 printf("%20s %d\n", aLimit
[i
].zLimitName
,
9175 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
9178 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
9180 goto meta_command_exit
;
9183 n2
= strlen30(azArg
[1]);
9184 for(i
=0; i
<ArraySize(aLimit
); i
++){
9185 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
9189 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
9191 goto meta_command_exit
;
9196 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
9197 "enter \".limits\" with no arguments for a list.\n",
9200 goto meta_command_exit
;
9203 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
9204 (int)integerValue(azArg
[2]));
9206 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
9207 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
9211 if( c
=='l' && n
>2 && cli_strncmp(azArg
[0], "lint", n
)==0 ){
9213 lintDotCommand(p
, azArg
, nArg
);
9216 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9217 if( c
=='l' && cli_strncmp(azArg
[0], "load", n
)==0 ){
9218 const char *zFile
, *zProc
;
9220 failIfSafeMode(p
, "cannot run .load in safe mode");
9221 if( nArg
<2 || azArg
[1][0]==0 ){
9222 /* Must have a non-empty FILE. (Will not load self.) */
9223 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
9225 goto meta_command_exit
;
9228 zProc
= nArg
>=3 ? azArg
[2] : 0;
9230 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
9231 if( rc
!=SQLITE_OK
){
9232 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
9233 sqlite3_free(zErrMsg
);
9239 if( c
=='l' && cli_strncmp(azArg
[0], "log", n
)==0 ){
9241 raw_printf(stderr
, "Usage: .log FILENAME\n");
9244 const char *zFile
= azArg
[1];
9246 && cli_strcmp(zFile
,"on")!=0
9247 && cli_strcmp(zFile
,"off")!=0
9249 raw_printf(stdout
, "cannot set .log to anything other "
9250 "than \"on\" or \"off\"\n");
9253 output_file_close(p
->pLog
);
9254 if( cli_strcmp(zFile
,"on")==0 ) zFile
= "stdout";
9255 p
->pLog
= output_file_open(zFile
, 0);
9259 if( c
=='m' && cli_strncmp(azArg
[0], "mode", n
)==0 ){
9260 const char *zMode
= 0;
9261 const char *zTabname
= 0;
9263 ColModeOpts cmOpts
= ColModeOpts_default
;
9264 for(i
=1; i
<nArg
; i
++){
9265 const char *z
= azArg
[i
];
9266 if( optionMatch(z
,"wrap") && i
+1<nArg
){
9267 cmOpts
.iWrap
= integerValue(azArg
[++i
]);
9268 }else if( optionMatch(z
,"ww") ){
9269 cmOpts
.bWordWrap
= 1;
9270 }else if( optionMatch(z
,"wordwrap") && i
+1<nArg
){
9271 cmOpts
.bWordWrap
= (u8
)booleanValue(azArg
[++i
]);
9272 }else if( optionMatch(z
,"quote") ){
9274 }else if( optionMatch(z
,"noquote") ){
9276 }else if( zMode
==0 ){
9278 /* Apply defaults for qbox pseudo-mode. If that
9279 * overwrites already-set values, user was informed of this.
9281 if( cli_strcmp(z
, "qbox")==0 ){
9282 ColModeOpts cmo
= ColModeOpts_default_qbox
;
9286 }else if( zTabname
==0 ){
9288 }else if( z
[0]=='-' ){
9289 utf8_printf(stderr
, "unknown option: %s\n", z
);
9290 utf8_printf(stderr
, "options:\n"
9293 " --wordwrap on/off\n"
9297 goto meta_command_exit
;
9299 utf8_printf(stderr
, "extra argument: \"%s\"\n", z
);
9301 goto meta_command_exit
;
9305 if( p
->mode
==MODE_Column
9306 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
9310 "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9311 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
9312 p
->cmOpts
.bWordWrap
? "on" : "off",
9313 p
->cmOpts
.bQuote
? "" : "no");
9315 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
9317 zMode
= modeDescr
[p
->mode
];
9319 n2
= strlen30(zMode
);
9320 if( cli_strncmp(zMode
,"lines",n2
)==0 ){
9321 p
->mode
= MODE_Line
;
9322 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9323 }else if( cli_strncmp(zMode
,"columns",n2
)==0 ){
9324 p
->mode
= MODE_Column
;
9325 if( (p
->shellFlgs
& SHFLG_HeaderSet
)==0 ){
9328 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9330 }else if( cli_strncmp(zMode
,"list",n2
)==0 ){
9331 p
->mode
= MODE_List
;
9332 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
9333 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9334 }else if( cli_strncmp(zMode
,"html",n2
)==0 ){
9335 p
->mode
= MODE_Html
;
9336 }else if( cli_strncmp(zMode
,"tcl",n2
)==0 ){
9338 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
9339 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9340 }else if( cli_strncmp(zMode
,"csv",n2
)==0 ){
9342 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9343 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9344 }else if( cli_strncmp(zMode
,"tabs",n2
)==0 ){
9345 p
->mode
= MODE_List
;
9346 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
9347 }else if( cli_strncmp(zMode
,"insert",n2
)==0 ){
9348 p
->mode
= MODE_Insert
;
9349 set_table_name(p
, zTabname
? zTabname
: "table");
9350 }else if( cli_strncmp(zMode
,"quote",n2
)==0 ){
9351 p
->mode
= MODE_Quote
;
9352 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9353 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
9354 }else if( cli_strncmp(zMode
,"ascii",n2
)==0 ){
9355 p
->mode
= MODE_Ascii
;
9356 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
9357 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
9358 }else if( cli_strncmp(zMode
,"markdown",n2
)==0 ){
9359 p
->mode
= MODE_Markdown
;
9361 }else if( cli_strncmp(zMode
,"table",n2
)==0 ){
9362 p
->mode
= MODE_Table
;
9364 }else if( cli_strncmp(zMode
,"box",n2
)==0 ){
9367 }else if( cli_strncmp(zMode
,"count",n2
)==0 ){
9368 p
->mode
= MODE_Count
;
9369 }else if( cli_strncmp(zMode
,"off",n2
)==0 ){
9371 }else if( cli_strncmp(zMode
,"json",n2
)==0 ){
9372 p
->mode
= MODE_Json
;
9374 raw_printf(stderr
, "Error: mode should be one of: "
9375 "ascii box column csv html insert json line list markdown "
9376 "qbox quote table tabs tcl\n");
9382 #ifndef SQLITE_SHELL_FIDDLE
9383 if( c
=='n' && cli_strcmp(azArg
[0], "nonce")==0 ){
9385 raw_printf(stderr
, "Usage: .nonce NONCE\n");
9387 }else if( p
->zNonce
==0 || cli_strcmp(azArg
[1],p
->zNonce
)!=0 ){
9388 raw_printf(stderr
, "line %d: incorrect nonce: \"%s\"\n",
9389 p
->lineno
, azArg
[1]);
9393 return 0; /* Return immediately to bypass the safe mode reset
9394 ** at the end of this procedure */
9397 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9399 if( c
=='n' && cli_strncmp(azArg
[0], "nullvalue", n
)==0 ){
9401 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
9402 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
9404 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
9409 if( c
=='o' && cli_strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
9410 const char *zFN
= 0; /* Pointer to constant filename */
9411 char *zNewFilename
= 0; /* Name of the database file to open */
9412 int iName
= 1; /* Index in azArg[] of the filename */
9413 int newFlag
= 0; /* True to delete file before opening */
9414 int openMode
= SHELL_OPEN_UNSPEC
;
9416 /* Check for command-line arguments */
9417 for(iName
=1; iName
<nArg
; iName
++){
9418 const char *z
= azArg
[iName
];
9419 #ifndef SQLITE_SHELL_FIDDLE
9420 if( optionMatch(z
,"new") ){
9422 #ifdef SQLITE_HAVE_ZLIB
9423 }else if( optionMatch(z
, "zip") ){
9424 openMode
= SHELL_OPEN_ZIPFILE
;
9426 }else if( optionMatch(z
, "append") ){
9427 openMode
= SHELL_OPEN_APPENDVFS
;
9428 }else if( optionMatch(z
, "readonly") ){
9429 openMode
= SHELL_OPEN_READONLY
;
9430 }else if( optionMatch(z
, "nofollow") ){
9431 p
->openFlags
|= SQLITE_OPEN_NOFOLLOW
;
9432 #ifndef SQLITE_OMIT_DESERIALIZE
9433 }else if( optionMatch(z
, "deserialize") ){
9434 openMode
= SHELL_OPEN_DESERIALIZE
;
9435 }else if( optionMatch(z
, "hexdb") ){
9436 openMode
= SHELL_OPEN_HEXDB
;
9437 }else if( optionMatch(z
, "maxsize") && iName
+1<nArg
){
9438 p
->szMax
= integerValue(azArg
[++iName
]);
9439 #endif /* SQLITE_OMIT_DESERIALIZE */
9441 #endif /* !SQLITE_SHELL_FIDDLE */
9443 utf8_printf(stderr
, "unknown option: %s\n", z
);
9445 goto meta_command_exit
;
9447 utf8_printf(stderr
, "extra argument: \"%s\"\n", z
);
9449 goto meta_command_exit
;
9455 /* Close the existing database */
9456 session_close_all(p
, -1);
9459 p
->pAuxDb
->zDbFilename
= 0;
9460 sqlite3_free(p
->pAuxDb
->zFreeOnClose
);
9461 p
->pAuxDb
->zFreeOnClose
= 0;
9462 p
->openMode
= openMode
;
9466 /* If a filename is specified, try to open it first */
9467 if( zFN
|| p
->openMode
==SHELL_OPEN_HEXDB
){
9468 if( newFlag
&& zFN
&& !p
->bSafeMode
) shellDeleteFile(zFN
);
9469 #ifndef SQLITE_SHELL_FIDDLE
9471 && p
->openMode
!=SHELL_OPEN_HEXDB
9473 && cli_strcmp(zFN
,":memory:")!=0
9475 failIfSafeMode(p
, "cannot open disk-based database files in safe mode");
9478 /* WASM mode has its own sandboxed pseudo-filesystem. */
9481 zNewFilename
= sqlite3_mprintf("%s", zFN
);
9482 shell_check_oom(zNewFilename
);
9486 p
->pAuxDb
->zDbFilename
= zNewFilename
;
9487 open_db(p
, OPEN_DB_KEEPALIVE
);
9489 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
9490 sqlite3_free(zNewFilename
);
9492 p
->pAuxDb
->zFreeOnClose
= zNewFilename
;
9496 /* As a fall-back open a TEMP database */
9497 p
->pAuxDb
->zDbFilename
= 0;
9502 #ifndef SQLITE_SHELL_FIDDLE
9504 && (cli_strncmp(azArg
[0], "output", n
)==0
9505 || cli_strncmp(azArg
[0], "once", n
)==0))
9506 || (c
=='e' && n
==5 && cli_strcmp(azArg
[0],"excel")==0)
9512 int bOnce
= 0; /* 0: .output, 1: .once, 2: .excel */
9513 unsigned char zBOM
[4]; /* Byte-order mark to using if --bom is present */
9516 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
9520 }else if( cli_strncmp(azArg
[0],"once",n
)==0 ){
9523 for(i
=1; i
<nArg
; i
++){
9526 if( z
[1]=='-' ) z
++;
9527 if( cli_strcmp(z
,"-bom")==0 ){
9532 }else if( c
!='e' && cli_strcmp(z
,"-x")==0 ){
9533 eMode
= 'x'; /* spreadsheet */
9534 }else if( c
!='e' && cli_strcmp(z
,"-e")==0 ){
9535 eMode
= 'e'; /* text editor */
9537 utf8_printf(p
->out
, "ERROR: unknown option: \"%s\". Usage:\n",
9539 showHelp(p
->out
, azArg
[0]);
9541 goto meta_command_exit
;
9543 }else if( zFile
==0 && eMode
!='e' && eMode
!='x' ){
9544 zFile
= sqlite3_mprintf("%s", z
);
9545 if( zFile
&& zFile
[0]=='|' ){
9546 while( i
+1<nArg
) zFile
= sqlite3_mprintf("%z %s", zFile
, azArg
[++i
]);
9550 utf8_printf(p
->out
,"ERROR: extra parameter: \"%s\". Usage:\n",
9552 showHelp(p
->out
, azArg
[0]);
9554 sqlite3_free(zFile
);
9555 goto meta_command_exit
;
9559 zFile
= sqlite3_mprintf("stdout");
9567 #ifndef SQLITE_NOHAVE_SYSTEM
9568 if( eMode
=='e' || eMode
=='x' ){
9572 /* spreadsheet mode. Output as CSV. */
9573 newTempFile(p
, "csv");
9574 ShellClearFlag(p
, SHFLG_Echo
);
9576 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9577 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9579 /* text editor mode */
9580 newTempFile(p
, "txt");
9583 sqlite3_free(zFile
);
9584 zFile
= sqlite3_mprintf("%s", p
->zTempFile
);
9586 #endif /* SQLITE_NOHAVE_SYSTEM */
9587 shell_check_oom(zFile
);
9588 if( zFile
[0]=='|' ){
9589 #ifdef SQLITE_OMIT_POPEN
9590 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
9594 p
->out
= popen(zFile
+ 1, "w");
9596 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
9600 if( zBOM
[0] ) fwrite(zBOM
, 1, 3, p
->out
);
9601 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9605 p
->out
= output_file_open(zFile
, bTxtMode
);
9607 if( cli_strcmp(zFile
,"off")!=0 ){
9608 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
9613 if( zBOM
[0] ) fwrite(zBOM
, 1, 3, p
->out
);
9614 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9617 sqlite3_free(zFile
);
9619 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9621 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "parameter", n
)==0 ){
9623 if( nArg
<=1 ) goto parameter_syntax_error
;
9626 ** Clear all bind parameters by dropping the TEMP table that holds them.
9628 if( nArg
==2 && cli_strcmp(azArg
[1],"clear")==0 ){
9629 sqlite3_exec(p
->db
, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9634 ** List all bind parameters.
9636 if( nArg
==2 && cli_strcmp(azArg
[1],"list")==0 ){
9637 sqlite3_stmt
*pStmt
= 0;
9640 rx
= sqlite3_prepare_v2(p
->db
,
9641 "SELECT max(length(key)) "
9642 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9643 if( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9644 len
= sqlite3_column_int(pStmt
, 0);
9645 if( len
>40 ) len
= 40;
9647 sqlite3_finalize(pStmt
);
9650 rx
= sqlite3_prepare_v2(p
->db
,
9651 "SELECT key, quote(value) "
9652 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9653 while( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9654 utf8_printf(p
->out
, "%-*s %s\n", len
, sqlite3_column_text(pStmt
,0),
9655 sqlite3_column_text(pStmt
,1));
9657 sqlite3_finalize(pStmt
);
9662 ** Make sure the TEMP table used to hold bind parameters exists.
9663 ** Create it if necessary.
9665 if( nArg
==2 && cli_strcmp(azArg
[1],"init")==0 ){
9669 /* .parameter set NAME VALUE
9670 ** Set or reset a bind parameter. NAME should be the full parameter
9671 ** name exactly as it appears in the query. (ex: $abc, @def). The
9672 ** VALUE can be in either SQL literal notation, or if not it will be
9673 ** understood to be a text string.
9675 if( nArg
==4 && cli_strcmp(azArg
[1],"set")==0 ){
9678 sqlite3_stmt
*pStmt
;
9679 const char *zKey
= azArg
[2];
9680 const char *zValue
= azArg
[3];
9682 zSql
= sqlite3_mprintf(
9683 "REPLACE INTO temp.sqlite_parameters(key,value)"
9684 "VALUES(%Q,%s);", zKey
, zValue
);
9685 shell_check_oom(zSql
);
9687 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9689 if( rx
!=SQLITE_OK
){
9690 sqlite3_finalize(pStmt
);
9692 zSql
= sqlite3_mprintf(
9693 "REPLACE INTO temp.sqlite_parameters(key,value)"
9694 "VALUES(%Q,%Q);", zKey
, zValue
);
9695 shell_check_oom(zSql
);
9696 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9698 if( rx
!=SQLITE_OK
){
9699 utf8_printf(p
->out
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9700 sqlite3_finalize(pStmt
);
9705 sqlite3_step(pStmt
);
9706 sqlite3_finalize(pStmt
);
9709 /* .parameter unset NAME
9710 ** Remove the NAME binding from the parameter binding table, if it
9713 if( nArg
==3 && cli_strcmp(azArg
[1],"unset")==0 ){
9714 char *zSql
= sqlite3_mprintf(
9715 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg
[2]);
9716 shell_check_oom(zSql
);
9717 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9720 /* If no command name matches, show a syntax error */
9721 parameter_syntax_error
:
9722 showHelp(p
->out
, "parameter");
9725 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "print", n
)==0 ){
9727 for(i
=1; i
<nArg
; i
++){
9728 if( i
>1 ) raw_printf(p
->out
, " ");
9729 utf8_printf(p
->out
, "%s", azArg
[i
]);
9731 raw_printf(p
->out
, "\n");
9734 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9735 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "progress", n
)==0 ){
9741 for(i
=1; i
<nArg
; i
++){
9742 const char *z
= azArg
[i
];
9745 if( z
[0]=='-' ) z
++;
9746 if( cli_strcmp(z
,"quiet")==0 || cli_strcmp(z
,"q")==0 ){
9747 p
->flgProgress
|= SHELL_PROGRESS_QUIET
;
9750 if( cli_strcmp(z
,"reset")==0 ){
9751 p
->flgProgress
|= SHELL_PROGRESS_RESET
;
9754 if( cli_strcmp(z
,"once")==0 ){
9755 p
->flgProgress
|= SHELL_PROGRESS_ONCE
;
9758 if( cli_strcmp(z
,"limit")==0 ){
9760 utf8_printf(stderr
, "Error: missing argument on --limit\n");
9762 goto meta_command_exit
;
9764 p
->mxProgress
= (int)integerValue(azArg
[++i
]);
9768 utf8_printf(stderr
, "Error: unknown option: \"%s\"\n", azArg
[i
]);
9770 goto meta_command_exit
;
9772 nn
= (int)integerValue(z
);
9776 sqlite3_progress_handler(p
->db
, nn
, progress_handler
, p
);
9778 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9780 if( c
=='p' && cli_strncmp(azArg
[0], "prompt", n
)==0 ){
9782 shell_strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
9785 shell_strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
9789 #ifndef SQLITE_SHELL_FIDDLE
9790 if( c
=='q' && cli_strncmp(azArg
[0], "quit", n
)==0 ){
9795 #ifndef SQLITE_SHELL_FIDDLE
9796 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "read", n
)==0 ){
9797 FILE *inSaved
= p
->in
;
9798 int savedLineno
= p
->lineno
;
9799 failIfSafeMode(p
, "cannot run .read in safe mode");
9801 raw_printf(stderr
, "Usage: .read FILE\n");
9803 goto meta_command_exit
;
9805 if( azArg
[1][0]=='|' ){
9806 #ifdef SQLITE_OMIT_POPEN
9807 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
9811 p
->in
= popen(azArg
[1]+1, "r");
9813 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
9816 rc
= process_input(p
);
9820 }else if( (p
->in
= openChrSource(azArg
[1]))==0 ){
9821 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
9824 rc
= process_input(p
);
9828 p
->lineno
= savedLineno
;
9830 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9832 #ifndef SQLITE_SHELL_FIDDLE
9833 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "restore", n
)==0 ){
9834 const char *zSrcFile
;
9837 sqlite3_backup
*pBackup
;
9840 failIfSafeMode(p
, "cannot run .restore in safe mode");
9842 zSrcFile
= azArg
[1];
9844 }else if( nArg
==3 ){
9845 zSrcFile
= azArg
[2];
9848 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
9850 goto meta_command_exit
;
9852 rc
= sqlite3_open(zSrcFile
, &pSrc
);
9853 if( rc
!=SQLITE_OK
){
9854 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
9859 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
9861 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9865 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
9866 || rc
==SQLITE_BUSY
){
9867 if( rc
==SQLITE_BUSY
){
9868 if( nTimeout
++ >= 3 ) break;
9872 sqlite3_backup_finish(pBackup
);
9873 if( rc
==SQLITE_DONE
){
9875 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
9876 raw_printf(stderr
, "Error: source database is busy\n");
9879 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9884 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9886 if( c
=='s' && cli_strncmp(azArg
[0], "scanstats", n
)==0 ){
9888 if( cli_strcmp(azArg
[1], "est")==0 ){
9891 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
9895 p
->db
, SQLITE_DBCONFIG_STMT_SCANSTATUS
, p
->scanstatsOn
, (int*)0
9897 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9898 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
9901 raw_printf(stderr
, "Usage: .scanstats on|off|est\n");
9906 if( c
=='s' && cli_strncmp(azArg
[0], "schema", n
)==0 ){
9910 const char *zDiv
= "(";
9911 const char *zName
= 0;
9914 int bNoSystemTabs
= 0;
9918 memcpy(&data
, p
, sizeof(data
));
9919 data
.showHeader
= 0;
9920 data
.cMode
= data
.mode
= MODE_Semi
;
9922 for(ii
=1; ii
<nArg
; ii
++){
9923 if( optionMatch(azArg
[ii
],"indent") ){
9924 data
.cMode
= data
.mode
= MODE_Pretty
;
9925 }else if( optionMatch(azArg
[ii
],"debug") ){
9927 }else if( optionMatch(azArg
[ii
],"nosys") ){
9929 }else if( azArg
[ii
][0]=='-' ){
9930 utf8_printf(stderr
, "Unknown option: \"%s\"\n", azArg
[ii
]);
9932 goto meta_command_exit
;
9933 }else if( zName
==0 ){
9937 "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9939 goto meta_command_exit
;
9943 int isSchema
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0
9944 || sqlite3_strlike(zName
, "sqlite_schema", '\\')==0
9945 || sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0
9946 || sqlite3_strlike(zName
,"sqlite_temp_schema", '\\')==0;
9948 char *new_argv
[2], *new_colv
[2];
9949 new_argv
[0] = sqlite3_mprintf(
9950 "CREATE TABLE %s (\n"
9954 " rootpage integer,\n"
9957 shell_check_oom(new_argv
[0]);
9959 new_colv
[0] = "sql";
9961 callback(&data
, 1, new_argv
, new_colv
);
9962 sqlite3_free(new_argv
[0]);
9966 sqlite3_stmt
*pStmt
= 0;
9967 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
9970 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9971 sqlite3_finalize(pStmt
);
9973 goto meta_command_exit
;
9975 appendText(&sSelect
, "SELECT sql FROM", 0);
9977 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
9978 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
9980 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
9981 appendText(&sSelect
, zDiv
, 0);
9982 zDiv
= " UNION ALL ";
9983 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
9984 if( sqlite3_stricmp(zDb
, "main")!=0 ){
9985 appendText(&sSelect
, zDb
, '\'');
9987 appendText(&sSelect
, "NULL", 0);
9989 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9990 appendText(&sSelect
, zScNum
, 0);
9991 appendText(&sSelect
, " AS snum, ", 0);
9992 appendText(&sSelect
, zDb
, '\'');
9993 appendText(&sSelect
, " AS sname FROM ", 0);
9994 appendText(&sSelect
, zDb
, quoteChar(zDb
));
9995 appendText(&sSelect
, ".sqlite_schema", 0);
9997 sqlite3_finalize(pStmt
);
9998 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10000 appendText(&sSelect
,
10001 " UNION ALL SELECT shell_module_schema(name),"
10002 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10006 appendText(&sSelect
, ") WHERE ", 0);
10008 char *zQarg
= sqlite3_mprintf("%Q", zName
);
10010 shell_check_oom(zQarg
);
10011 bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
10012 strchr(zName
, '[') != 0;
10013 if( strchr(zName
, '.') ){
10014 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
10016 appendText(&sSelect
, "lower(tbl_name)", 0);
10018 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
10019 appendText(&sSelect
, zQarg
, 0);
10021 appendText(&sSelect
, " ESCAPE '\\' ", 0);
10023 appendText(&sSelect
, " AND ", 0);
10024 sqlite3_free(zQarg
);
10026 if( bNoSystemTabs
){
10027 appendText(&sSelect
, "name NOT LIKE 'sqlite_%%' AND ", 0);
10029 appendText(&sSelect
, "sql IS NOT NULL"
10030 " ORDER BY snum, rowid", 0);
10032 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
10034 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
10036 freeText(&sSelect
);
10039 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
10040 sqlite3_free(zErrMsg
);
10042 }else if( rc
!= SQLITE_OK
){
10043 raw_printf(stderr
,"Error: querying schema information\n");
10050 if( (c
=='s' && n
==11 && cli_strncmp(azArg
[0], "selecttrace", n
)==0)
10051 || (c
=='t' && n
==9 && cli_strncmp(azArg
[0], "treetrace", n
)==0)
10053 unsigned int x
= nArg
>=2? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
10054 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &x
);
10057 #if defined(SQLITE_ENABLE_SESSION)
10058 if( c
=='s' && cli_strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
10059 struct AuxDb
*pAuxDb
= p
->pAuxDb
;
10060 OpenSession
*pSession
= &pAuxDb
->aSession
[0];
10061 char **azCmd
= &azArg
[1];
10063 int nCmd
= nArg
- 1;
10065 if( nArg
<=1 ) goto session_syntax_error
;
10068 for(iSes
=0; iSes
<pAuxDb
->nSession
; iSes
++){
10069 if( cli_strcmp(pAuxDb
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
10071 if( iSes
<pAuxDb
->nSession
){
10072 pSession
= &pAuxDb
->aSession
[iSes
];
10076 pSession
= &pAuxDb
->aSession
[0];
10081 /* .session attach TABLE
10082 ** Invoke the sqlite3session_attach() interface to attach a particular
10083 ** table so that it is never filtered.
10085 if( cli_strcmp(azCmd
[0],"attach")==0 ){
10086 if( nCmd
!=2 ) goto session_syntax_error
;
10087 if( pSession
->p
==0 ){
10089 raw_printf(stderr
, "ERROR: No sessions are open\n");
10091 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
10093 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
10099 /* .session changeset FILE
10100 ** .session patchset FILE
10101 ** Write a changeset or patchset into a file. The file is overwritten.
10103 if( cli_strcmp(azCmd
[0],"changeset")==0
10104 || cli_strcmp(azCmd
[0],"patchset")==0
10107 failIfSafeMode(p
, "cannot run \".session %s\" in safe mode", azCmd
[0]);
10108 if( nCmd
!=2 ) goto session_syntax_error
;
10109 if( pSession
->p
==0 ) goto session_not_open
;
10110 out
= fopen(azCmd
[1], "wb");
10112 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n",
10117 if( azCmd
[0][0]=='c' ){
10118 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
10120 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
10123 printf("Error: error code %d\n", rc
);
10127 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
10128 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
10131 sqlite3_free(pChng
);
10137 ** Close the identified session
10139 if( cli_strcmp(azCmd
[0], "close")==0 ){
10140 if( nCmd
!=1 ) goto session_syntax_error
;
10141 if( pAuxDb
->nSession
){
10142 session_close(pSession
);
10143 pAuxDb
->aSession
[iSes
] = pAuxDb
->aSession
[--pAuxDb
->nSession
];
10147 /* .session enable ?BOOLEAN?
10148 ** Query or set the enable flag
10150 if( cli_strcmp(azCmd
[0], "enable")==0 ){
10152 if( nCmd
>2 ) goto session_syntax_error
;
10153 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
10154 if( pAuxDb
->nSession
){
10155 ii
= sqlite3session_enable(pSession
->p
, ii
);
10156 utf8_printf(p
->out
, "session %s enable flag = %d\n",
10157 pSession
->zName
, ii
);
10161 /* .session filter GLOB ....
10162 ** Set a list of GLOB patterns of table names to be excluded.
10164 if( cli_strcmp(azCmd
[0], "filter")==0 ){
10166 if( nCmd
<2 ) goto session_syntax_error
;
10167 if( pAuxDb
->nSession
){
10168 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
10169 sqlite3_free(pSession
->azFilter
[ii
]);
10171 sqlite3_free(pSession
->azFilter
);
10172 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
10173 pSession
->azFilter
= sqlite3_malloc( nByte
);
10174 if( pSession
->azFilter
==0 ){
10175 raw_printf(stderr
, "Error: out or memory\n");
10178 for(ii
=1; ii
<nCmd
; ii
++){
10179 char *x
= pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
10180 shell_check_oom(x
);
10182 pSession
->nFilter
= ii
-1;
10186 /* .session indirect ?BOOLEAN?
10187 ** Query or set the indirect flag
10189 if( cli_strcmp(azCmd
[0], "indirect")==0 ){
10191 if( nCmd
>2 ) goto session_syntax_error
;
10192 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
10193 if( pAuxDb
->nSession
){
10194 ii
= sqlite3session_indirect(pSession
->p
, ii
);
10195 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
10196 pSession
->zName
, ii
);
10200 /* .session isempty
10201 ** Determine if the session is empty
10203 if( cli_strcmp(azCmd
[0], "isempty")==0 ){
10205 if( nCmd
!=1 ) goto session_syntax_error
;
10206 if( pAuxDb
->nSession
){
10207 ii
= sqlite3session_isempty(pSession
->p
);
10208 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
10209 pSession
->zName
, ii
);
10214 ** List all currently open sessions
10216 if( cli_strcmp(azCmd
[0],"list")==0 ){
10217 for(i
=0; i
<pAuxDb
->nSession
; i
++){
10218 utf8_printf(p
->out
, "%d %s\n", i
, pAuxDb
->aSession
[i
].zName
);
10222 /* .session open DB NAME
10223 ** Open a new session called NAME on the attached database DB.
10224 ** DB is normally "main".
10226 if( cli_strcmp(azCmd
[0],"open")==0 ){
10228 if( nCmd
!=3 ) goto session_syntax_error
;
10230 if( zName
[0]==0 ) goto session_syntax_error
;
10231 for(i
=0; i
<pAuxDb
->nSession
; i
++){
10232 if( cli_strcmp(pAuxDb
->aSession
[i
].zName
,zName
)==0 ){
10233 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
10234 goto meta_command_exit
;
10237 if( pAuxDb
->nSession
>=ArraySize(pAuxDb
->aSession
) ){
10239 "Maximum of %d sessions\n", ArraySize(pAuxDb
->aSession
));
10240 goto meta_command_exit
;
10242 pSession
= &pAuxDb
->aSession
[pAuxDb
->nSession
];
10243 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
10245 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
10247 goto meta_command_exit
;
10249 pSession
->nFilter
= 0;
10250 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
10251 pAuxDb
->nSession
++;
10252 pSession
->zName
= sqlite3_mprintf("%s", zName
);
10253 shell_check_oom(pSession
->zName
);
10255 /* If no command name matches, show a syntax error */
10256 session_syntax_error
:
10257 showHelp(p
->out
, "session");
10261 #ifdef SQLITE_DEBUG
10262 /* Undocumented commands for internal testing. Subject to change
10263 ** without notice. */
10264 if( c
=='s' && n
>=10 && cli_strncmp(azArg
[0], "selftest-", 9)==0 ){
10265 if( cli_strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
10267 for(i
=1; i
<nArg
; i
++){
10268 v
= booleanValue(azArg
[i
]);
10269 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
10272 if( cli_strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
10273 int i
; sqlite3_int64 v
;
10274 for(i
=1; i
<nArg
; i
++){
10276 v
= integerValue(azArg
[i
]);
10277 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
10278 utf8_printf(p
->out
, "%s", zBuf
);
10284 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"selftest",n
)==0 ){
10285 int bIsInit
= 0; /* True to initialize the SELFTEST table */
10286 int bVerbose
= 0; /* Verbose output */
10287 int bSelftestExists
; /* True if SELFTEST already exists */
10288 int i
, k
; /* Loop counters */
10289 int nTest
= 0; /* Number of tests runs */
10290 int nErr
= 0; /* Number of errors seen */
10291 ShellText str
; /* Answer for a query */
10292 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
10295 for(i
=1; i
<nArg
; i
++){
10296 const char *z
= azArg
[i
];
10297 if( z
[0]=='-' && z
[1]=='-' ) z
++;
10298 if( cli_strcmp(z
,"-init")==0 ){
10301 if( cli_strcmp(z
,"-v")==0 ){
10305 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
10306 azArg
[i
], azArg
[0]);
10307 raw_printf(stderr
, "Should be one of: --init -v\n");
10309 goto meta_command_exit
;
10312 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
10314 bSelftestExists
= 0;
10316 bSelftestExists
= 1;
10319 createSelftestTable(p
);
10320 bSelftestExists
= 1;
10323 appendText(&str
, "x", 0);
10324 for(k
=bSelftestExists
; k
>=0; k
--){
10326 rc
= sqlite3_prepare_v2(p
->db
,
10327 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10330 rc
= sqlite3_prepare_v2(p
->db
,
10331 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10332 " (1,'run','PRAGMA integrity_check','ok')",
10336 raw_printf(stderr
, "Error querying the selftest table\n");
10338 sqlite3_finalize(pStmt
);
10339 goto meta_command_exit
;
10341 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
10342 int tno
= sqlite3_column_int(pStmt
, 0);
10343 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
10344 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
10345 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
10347 if( zOp
==0 ) continue;
10348 if( zSql
==0 ) continue;
10349 if( zAns
==0 ) continue;
10352 printf("%d: %s %s\n", tno
, zOp
, zSql
);
10354 if( cli_strcmp(zOp
,"memo")==0 ){
10355 utf8_printf(p
->out
, "%s\n", zSql
);
10357 if( cli_strcmp(zOp
,"run")==0 ){
10361 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
10364 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
10366 if( rc
|| zErrMsg
){
10369 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
10370 sqlite3_free(zErrMsg
);
10371 }else if( cli_strcmp(zAns
,str
.z
)!=0 ){
10374 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
10375 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
10379 utf8_printf(stderr
,
10380 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
10384 } /* End loop over rows of content from SELFTEST */
10385 sqlite3_finalize(pStmt
);
10386 } /* End loop over k */
10388 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
10391 if( c
=='s' && cli_strncmp(azArg
[0], "separator", n
)==0 ){
10392 if( nArg
<2 || nArg
>3 ){
10393 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
10397 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
10398 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
10401 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
10402 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
10406 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"sha3sum",n
)==0 ){
10407 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
10408 int i
; /* Loop counter */
10409 int bSchema
= 0; /* Also hash the schema */
10410 int bSeparate
= 0; /* Hash each table separately */
10411 int iSize
= 224; /* Hash algorithm to use */
10412 int bDebug
= 0; /* Only show the query that would have run */
10413 sqlite3_stmt
*pStmt
; /* For querying tables names */
10414 char *zSql
; /* SQL to be run */
10415 char *zSep
; /* Separator */
10416 ShellText sSql
; /* Complete SQL for the query to run the hash */
10417 ShellText sQuery
; /* Set of queries used to read all content */
10419 for(i
=1; i
<nArg
; i
++){
10420 const char *z
= azArg
[i
];
10423 if( z
[0]=='-' ) z
++;
10424 if( cli_strcmp(z
,"schema")==0 ){
10427 if( cli_strcmp(z
,"sha3-224")==0 || cli_strcmp(z
,"sha3-256")==0
10428 || cli_strcmp(z
,"sha3-384")==0 || cli_strcmp(z
,"sha3-512")==0
10430 iSize
= atoi(&z
[5]);
10432 if( cli_strcmp(z
,"debug")==0 ){
10436 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
10437 azArg
[i
], azArg
[0]);
10438 showHelp(p
->out
, azArg
[0]);
10440 goto meta_command_exit
;
10443 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10445 goto meta_command_exit
;
10449 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
10453 zSql
= "SELECT lower(name) as tname FROM sqlite_schema"
10454 " WHERE type='table' AND coalesce(rootpage,0)>1"
10455 " UNION ALL SELECT 'sqlite_schema'"
10456 " ORDER BY 1 collate nocase";
10458 zSql
= "SELECT lower(name) as tname FROM sqlite_schema"
10459 " WHERE type='table' AND coalesce(rootpage,0)>1"
10460 " AND name NOT LIKE 'sqlite_%'"
10461 " ORDER BY 1 collate nocase";
10463 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
10466 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
10468 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
10469 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
10470 if( zTab
==0 ) continue;
10471 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
10472 if( cli_strncmp(zTab
, "sqlite_",7)!=0 ){
10473 appendText(&sQuery
,"SELECT * FROM ", 0);
10474 appendText(&sQuery
,zTab
,'"');
10475 appendText(&sQuery
," NOT INDEXED;", 0);
10476 }else if( cli_strcmp(zTab
, "sqlite_schema")==0 ){
10477 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10478 " ORDER BY name;", 0);
10479 }else if( cli_strcmp(zTab
, "sqlite_sequence")==0 ){
10480 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
10481 " ORDER BY name;", 0);
10482 }else if( cli_strcmp(zTab
, "sqlite_stat1")==0 ){
10483 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
10484 " ORDER BY tbl,idx;", 0);
10485 }else if( cli_strcmp(zTab
, "sqlite_stat4")==0 ){
10486 appendText(&sQuery
, "SELECT * FROM ", 0);
10487 appendText(&sQuery
, zTab
, 0);
10488 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
10490 appendText(&sSql
, zSep
, 0);
10491 appendText(&sSql
, sQuery
.z
, '\'');
10493 appendText(&sSql
, ",", 0);
10494 appendText(&sSql
, zTab
, '\'');
10497 sqlite3_finalize(pStmt
);
10499 zSql
= sqlite3_mprintf(
10501 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10502 " FROM [sha3sum$query]",
10505 zSql
= sqlite3_mprintf(
10507 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10508 " FROM [sha3sum$query]",
10511 shell_check_oom(zSql
);
10515 utf8_printf(p
->out
, "%s\n", zSql
);
10517 shell_exec(p
, zSql
, 0);
10519 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10522 char *zRevText
= /* Query for reversible to-blob-to-text check */
10523 "SELECT lower(name) as tname FROM sqlite_schema\n"
10524 "WHERE type='table' AND coalesce(rootpage,0)>1\n"
10525 "AND name NOT LIKE 'sqlite_%%'%s\n"
10526 "ORDER BY 1 collate nocase";
10527 zRevText
= sqlite3_mprintf(zRevText
, zLike
? " AND name LIKE $tspec" : "");
10528 zRevText
= sqlite3_mprintf(
10529 /* lower-case query is first run, producing upper-case query. */
10530 "with tabcols as materialized(\n"
10531 "select tname, cname\n"
10533 " select ss.tname as tname, ti.name as cname\n"
10534 " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
10535 "select 'SELECT total(bad_text_count) AS bad_text_count\n"
10536 "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
10537 " from (select 'SELECT COUNT(*) AS bad_text_count\n"
10538 "FROM '||tname||' WHERE '\n"
10539 "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
10540 "|| ' AND typeof('||cname||')=''text'' ',\n"
10541 "' OR ') as query, tname from tabcols group by tname)"
10543 shell_check_oom(zRevText
);
10544 if( bDebug
) utf8_printf(p
->out
, "%s\n", zRevText
);
10545 lrc
= sqlite3_prepare_v2(p
->db
, zRevText
, -1, &pStmt
, 0);
10546 if( lrc
!=SQLITE_OK
){
10547 /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
10548 ** user does cruel and unnatural things like ".limit expr_depth 0". */
10551 if( zLike
) sqlite3_bind_text(pStmt
,1,zLike
,-1,SQLITE_STATIC
);
10552 lrc
= SQLITE_ROW
==sqlite3_step(pStmt
);
10554 const char *zGenQuery
= (char*)sqlite3_column_text(pStmt
,0);
10555 sqlite3_stmt
*pCheckStmt
;
10556 lrc
= sqlite3_prepare_v2(p
->db
, zGenQuery
, -1, &pCheckStmt
, 0);
10557 if( bDebug
) utf8_printf(p
->out
, "%s\n", zGenQuery
);
10558 if( lrc
!=SQLITE_OK
){
10561 if( SQLITE_ROW
==sqlite3_step(pCheckStmt
) ){
10562 double countIrreversible
= sqlite3_column_double(pCheckStmt
, 0);
10563 if( countIrreversible
>0 ){
10564 int sz
= (int)(countIrreversible
+ 0.5);
10565 utf8_printf(stderr
,
10566 "Digest includes %d invalidly encoded text field%s.\n",
10567 sz
, (sz
>1)? "s": "");
10570 sqlite3_finalize(pCheckStmt
);
10572 sqlite3_finalize(pStmt
);
10575 if( rc
) utf8_printf(stderr
, ".sha3sum failed.\n");
10576 sqlite3_free(zRevText
);
10578 #endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
10579 sqlite3_free(zSql
);
10582 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10584 && (cli_strncmp(azArg
[0], "shell", n
)==0
10585 || cli_strncmp(azArg
[0],"system",n
)==0)
10589 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
10591 raw_printf(stderr
, "Usage: .system COMMAND\n");
10593 goto meta_command_exit
;
10595 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
10596 for(i
=2; i
<nArg
&& zCmd
!=0; i
++){
10597 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
10600 x
= zCmd
!=0 ? system(zCmd
) : 1;
10601 sqlite3_free(zCmd
);
10602 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
10604 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10606 if( c
=='s' && cli_strncmp(azArg
[0], "show", n
)==0 ){
10607 static const char *azBool
[] = { "off", "on", "trigger", "full"};
10611 raw_printf(stderr
, "Usage: .show\n");
10613 goto meta_command_exit
;
10615 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
10616 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
10617 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
10618 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
10619 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
10620 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
10621 if( p
->mode
==MODE_Column
10622 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
10625 (p
->out
, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10626 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
10627 p
->cmOpts
.bWordWrap
? "on" : "off",
10628 p
->cmOpts
.bQuote
? "" : "no");
10630 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
10632 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
10633 output_c_string(p
->out
, p
->nullValue
);
10634 raw_printf(p
->out
, "\n");
10635 utf8_printf(p
->out
,"%12.12s: %s\n","output",
10636 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
10637 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
10638 output_c_string(p
->out
, p
->colSeparator
);
10639 raw_printf(p
->out
, "\n");
10640 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
10641 output_c_string(p
->out
, p
->rowSeparator
);
10642 raw_printf(p
->out
, "\n");
10643 switch( p
->statsOn
){
10644 case 0: zOut
= "off"; break;
10645 default: zOut
= "on"; break;
10646 case 2: zOut
= "stmt"; break;
10647 case 3: zOut
= "vmstep"; break;
10649 utf8_printf(p
->out
, "%12.12s: %s\n","stats", zOut
);
10650 utf8_printf(p
->out
, "%12.12s: ", "width");
10651 for (i
=0;i
<p
->nWidth
;i
++) {
10652 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
10654 raw_printf(p
->out
, "\n");
10655 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
10656 p
->pAuxDb
->zDbFilename
? p
->pAuxDb
->zDbFilename
: "");
10659 if( c
=='s' && cli_strncmp(azArg
[0], "stats", n
)==0 ){
10661 if( cli_strcmp(azArg
[1],"stmt")==0 ){
10663 }else if( cli_strcmp(azArg
[1],"vmstep")==0 ){
10666 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
10668 }else if( nArg
==1 ){
10669 display_stats(p
->db
, p
, 0);
10671 raw_printf(stderr
, "Usage: .stats ?on|off|stmt|vmstep?\n");
10676 if( (c
=='t' && n
>1 && cli_strncmp(azArg
[0], "tables", n
)==0)
10677 || (c
=='i' && (cli_strncmp(azArg
[0], "indices", n
)==0
10678 || cli_strncmp(azArg
[0], "indexes", n
)==0) )
10680 sqlite3_stmt
*pStmt
;
10687 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
10689 sqlite3_finalize(pStmt
);
10690 return shellDatabaseError(p
->db
);
10693 if( nArg
>2 && c
=='i' ){
10694 /* It is an historical accident that the .indexes command shows an error
10695 ** when called with the wrong number of arguments whereas the .tables
10696 ** command does not. */
10697 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
10699 sqlite3_finalize(pStmt
);
10700 goto meta_command_exit
;
10702 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
10703 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
10704 if( zDbName
==0 ) continue;
10705 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
10706 if( sqlite3_stricmp(zDbName
, "main")==0 ){
10707 appendText(&s
, "SELECT name FROM ", 0);
10709 appendText(&s
, "SELECT ", 0);
10710 appendText(&s
, zDbName
, '\'');
10711 appendText(&s
, "||'.'||name FROM ", 0);
10713 appendText(&s
, zDbName
, '"');
10714 appendText(&s
, ".sqlite_schema ", 0);
10716 appendText(&s
," WHERE type IN ('table','view')"
10717 " AND name NOT LIKE 'sqlite_%'"
10718 " AND name LIKE ?1", 0);
10720 appendText(&s
," WHERE type='index'"
10721 " AND tbl_name LIKE ?1", 0);
10724 rc
= sqlite3_finalize(pStmt
);
10725 if( rc
==SQLITE_OK
){
10726 appendText(&s
, " ORDER BY 1", 0);
10727 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
10730 if( rc
) return shellDatabaseError(p
->db
);
10732 /* Run the SQL statement prepared by the above block. Store the results
10733 ** as an array of nul-terminated strings in azResult[]. */
10737 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
10739 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
10741 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
10742 if( nRow
>=nAlloc
){
10744 int n2
= nAlloc
*2 + 10;
10745 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
10746 shell_check_oom(azNew
);
10750 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
10751 shell_check_oom(azResult
[nRow
]);
10754 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
10755 rc
= shellDatabaseError(p
->db
);
10758 /* Pretty-print the contents of array azResult[] to the output */
10759 if( rc
==0 && nRow
>0 ){
10760 int len
, maxlen
= 0;
10762 int nPrintCol
, nPrintRow
;
10763 for(i
=0; i
<nRow
; i
++){
10764 len
= strlen30(azResult
[i
]);
10765 if( len
>maxlen
) maxlen
= len
;
10767 nPrintCol
= 80/(maxlen
+2);
10768 if( nPrintCol
<1 ) nPrintCol
= 1;
10769 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
10770 for(i
=0; i
<nPrintRow
; i
++){
10771 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
10772 char *zSp
= j
<nPrintRow
? "" : " ";
10773 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
10774 azResult
[j
] ? azResult
[j
]:"");
10776 raw_printf(p
->out
, "\n");
10780 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
10781 sqlite3_free(azResult
);
10784 #ifndef SQLITE_SHELL_FIDDLE
10785 /* Begin redirecting output to the file "testcase-out.txt" */
10786 if( c
=='t' && cli_strcmp(azArg
[0],"testcase")==0 ){
10788 p
->out
= output_file_open("testcase-out.txt", 0);
10790 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
10793 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
10795 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
10798 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10800 #ifndef SQLITE_UNTESTABLE
10801 if( c
=='t' && n
>=8 && cli_strncmp(azArg
[0], "testctrl", n
)==0 ){
10802 static const struct {
10803 const char *zCtrlName
; /* Name of a test-control option */
10804 int ctrlCode
; /* Integer code for that option */
10805 int unSafe
; /* Not valid for --safe mode */
10806 const char *zUsage
; /* Usage notes */
10808 {"always", SQLITE_TESTCTRL_ALWAYS
, 1, "BOOLEAN" },
10809 {"assert", SQLITE_TESTCTRL_ASSERT
, 1, "BOOLEAN" },
10810 /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10811 /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10812 {"byteorder", SQLITE_TESTCTRL_BYTEORDER
, 0, "" },
10813 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
,0,"BOOLEAN" },
10814 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10815 {"imposter", SQLITE_TESTCTRL_IMPOSTER
,1,"SCHEMA ON/OFF ROOTPAGE"},
10816 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
,0,"" },
10817 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,0,"BOOLEAN" },
10818 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
,1, "BOOLEAN" },
10819 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
,0,"DISABLE-MASK" },
10821 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
,0,"" },
10823 {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
,0, "OFFSET " },
10824 {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
,0, "" },
10825 {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, 0, "" },
10826 {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED
, 0, "SEED ?db?" },
10827 {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT
, 0, "" },
10828 {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP
, 0, "NMAX" },
10829 {"tune", SQLITE_TESTCTRL_TUNE
, 1, "ID VALUE" },
10833 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10836 const char *zCmd
= 0;
10838 if( !ShellHasFlag(p
,SHFLG_TestingMode
) ){
10839 utf8_printf(stderr
, ".%s unavailable without --unsafe-testing\n",
10842 goto meta_command_exit
;
10845 zCmd
= nArg
>=2 ? azArg
[1] : "help";
10847 /* The argument can optionally begin with "-" or "--" */
10848 if( zCmd
[0]=='-' && zCmd
[1] ){
10850 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
10853 /* --help lists all test-controls */
10854 if( cli_strcmp(zCmd
,"help")==0 ){
10855 utf8_printf(p
->out
, "Available test-controls:\n");
10856 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10857 utf8_printf(p
->out
, " .testctrl %s %s\n",
10858 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
10861 goto meta_command_exit
;
10864 /* convert testctrl text option to value. allow any unique prefix
10865 ** of the option name, or a numerical value. */
10866 n2
= strlen30(zCmd
);
10867 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10868 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
10870 testctrl
= aCtrl
[i
].ctrlCode
;
10873 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
10874 "Use \".testctrl --help\" for help\n", zCmd
);
10876 goto meta_command_exit
;
10881 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
10882 "Use \".testctrl --help\" for help\n", zCmd
);
10883 }else if( aCtrl
[iCtrl
].unSafe
&& p
->bSafeMode
){
10884 utf8_printf(stderr
,
10885 "line %d: \".testctrl %s\" may not be used in safe mode\n",
10886 p
->lineno
, aCtrl
[iCtrl
].zCtrlName
);
10891 /* sqlite3_test_control(int, db, int) */
10892 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
10894 unsigned int opt
= (unsigned int)strtol(azArg
[2], 0, 0);
10895 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
10900 /* sqlite3_test_control(int) */
10901 case SQLITE_TESTCTRL_PRNG_SAVE
:
10902 case SQLITE_TESTCTRL_PRNG_RESTORE
:
10903 case SQLITE_TESTCTRL_BYTEORDER
:
10905 rc2
= sqlite3_test_control(testctrl
);
10906 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
10910 /* sqlite3_test_control(int, uint) */
10911 case SQLITE_TESTCTRL_PENDING_BYTE
:
10913 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
10914 rc2
= sqlite3_test_control(testctrl
, opt
);
10919 /* sqlite3_test_control(int, int, sqlite3*) */
10920 case SQLITE_TESTCTRL_PRNG_SEED
:
10921 if( nArg
==3 || nArg
==4 ){
10922 int ii
= (int)integerValue(azArg
[2]);
10924 if( ii
==0 && cli_strcmp(azArg
[2],"random")==0 ){
10925 sqlite3_randomness(sizeof(ii
),&ii
);
10926 printf("-- random seed: %d\n", ii
);
10932 /* Make sure the schema has been loaded */
10933 sqlite3_table_column_metadata(db
, 0, "x", 0, 0, 0, 0, 0, 0);
10935 rc2
= sqlite3_test_control(testctrl
, ii
, db
);
10940 /* sqlite3_test_control(int, int) */
10941 case SQLITE_TESTCTRL_ASSERT
:
10942 case SQLITE_TESTCTRL_ALWAYS
:
10944 int opt
= booleanValue(azArg
[2]);
10945 rc2
= sqlite3_test_control(testctrl
, opt
);
10950 /* sqlite3_test_control(int, int) */
10951 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
10952 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
10954 int opt
= booleanValue(azArg
[2]);
10955 rc2
= sqlite3_test_control(testctrl
, opt
);
10960 /* sqlite3_test_control(sqlite3*) */
10961 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
:
10962 rc2
= sqlite3_test_control(testctrl
, p
->db
);
10966 case SQLITE_TESTCTRL_IMPOSTER
:
10968 rc2
= sqlite3_test_control(testctrl
, p
->db
,
10970 integerValue(azArg
[3]),
10971 integerValue(azArg
[4]));
10976 case SQLITE_TESTCTRL_SEEK_COUNT
: {
10978 rc2
= sqlite3_test_control(testctrl
, p
->db
, &x
);
10979 utf8_printf(p
->out
, "%llu\n", x
);
10985 case SQLITE_TESTCTRL_PARSER_COVERAGE
: {
10987 sqlite3_test_control(testctrl
, p
->out
);
10993 #ifdef SQLITE_DEBUG
10994 case SQLITE_TESTCTRL_TUNE
: {
10996 int id
= (int)integerValue(azArg
[2]);
10997 int val
= (int)integerValue(azArg
[3]);
10998 sqlite3_test_control(testctrl
, id
, &val
);
11000 }else if( nArg
==3 ){
11001 int id
= (int)integerValue(azArg
[2]);
11002 sqlite3_test_control(testctrl
, -id
, &rc2
);
11004 }else if( nArg
==2 ){
11008 rc2
= sqlite3_test_control(testctrl
, -id
, &val
);
11009 if( rc2
!=SQLITE_OK
) break;
11010 if( id
>1 ) utf8_printf(p
->out
, " ");
11011 utf8_printf(p
->out
, "%d: %d", id
, val
);
11014 if( id
>1 ) utf8_printf(p
->out
, "\n");
11020 case SQLITE_TESTCTRL_SORTER_MMAP
:
11022 int opt
= (unsigned int)integerValue(azArg
[2]);
11023 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
11029 if( isOk
==0 && iCtrl
>=0 ){
11030 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
11032 }else if( isOk
==1 ){
11033 raw_printf(p
->out
, "%d\n", rc2
);
11034 }else if( isOk
==2 ){
11035 raw_printf(p
->out
, "0x%08x\n", rc2
);
11038 #endif /* !defined(SQLITE_UNTESTABLE) */
11040 if( c
=='t' && n
>4 && cli_strncmp(azArg
[0], "timeout", n
)==0 ){
11042 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
11045 if( c
=='t' && n
>=5 && cli_strncmp(azArg
[0], "timer", n
)==0 ){
11047 enableTimer
= booleanValue(azArg
[1]);
11048 if( enableTimer
&& !HAS_TIMER
){
11049 raw_printf(stderr
, "Error: timer not available on this system.\n");
11053 raw_printf(stderr
, "Usage: .timer on|off\n");
11058 #ifndef SQLITE_OMIT_TRACE
11059 if( c
=='t' && cli_strncmp(azArg
[0], "trace", n
)==0 ){
11063 for(jj
=1; jj
<nArg
; jj
++){
11064 const char *z
= azArg
[jj
];
11066 if( optionMatch(z
, "expanded") ){
11067 p
->eTraceType
= SHELL_TRACE_EXPANDED
;
11069 #ifdef SQLITE_ENABLE_NORMALIZE
11070 else if( optionMatch(z
, "normalized") ){
11071 p
->eTraceType
= SHELL_TRACE_NORMALIZED
;
11074 else if( optionMatch(z
, "plain") ){
11075 p
->eTraceType
= SHELL_TRACE_PLAIN
;
11077 else if( optionMatch(z
, "profile") ){
11078 mType
|= SQLITE_TRACE_PROFILE
;
11080 else if( optionMatch(z
, "row") ){
11081 mType
|= SQLITE_TRACE_ROW
;
11083 else if( optionMatch(z
, "stmt") ){
11084 mType
|= SQLITE_TRACE_STMT
;
11086 else if( optionMatch(z
, "close") ){
11087 mType
|= SQLITE_TRACE_CLOSE
;
11090 raw_printf(stderr
, "Unknown option \"%s\" on \".trace\"\n", z
);
11092 goto meta_command_exit
;
11095 output_file_close(p
->traceOut
);
11096 p
->traceOut
= output_file_open(z
, 0);
11099 if( p
->traceOut
==0 ){
11100 sqlite3_trace_v2(p
->db
, 0, 0, 0);
11102 if( mType
==0 ) mType
= SQLITE_TRACE_STMT
;
11103 sqlite3_trace_v2(p
->db
, mType
, sql_trace_callback
, p
);
11106 #endif /* !defined(SQLITE_OMIT_TRACE) */
11108 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11109 if( c
=='u' && cli_strncmp(azArg
[0], "unmodule", n
)==0 ){
11114 raw_printf(stderr
, "Usage: .unmodule [--allexcept] NAME ...\n");
11116 goto meta_command_exit
;
11120 if( zOpt
[0]=='-' && zOpt
[1]=='-' && zOpt
[2]!=0 ) zOpt
++;
11121 lenOpt
= (int)strlen(zOpt
);
11122 if( lenOpt
>=3 && cli_strncmp(zOpt
, "-allexcept",lenOpt
)==0 ){
11123 assert( azArg
[nArg
]==0 );
11124 sqlite3_drop_modules(p
->db
, nArg
>2 ? (const char**)(azArg
+2) : 0);
11126 for(ii
=1; ii
<nArg
; ii
++){
11127 sqlite3_create_module(p
->db
, azArg
[ii
], 0, 0);
11133 #if SQLITE_USER_AUTHENTICATION
11134 if( c
=='u' && cli_strncmp(azArg
[0], "user", n
)==0 ){
11136 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
11138 goto meta_command_exit
;
11141 if( cli_strcmp(azArg
[1],"login")==0 ){
11143 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
11145 goto meta_command_exit
;
11147 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
11148 strlen30(azArg
[3]));
11150 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
11153 }else if( cli_strcmp(azArg
[1],"add")==0 ){
11155 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
11157 goto meta_command_exit
;
11159 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
11160 booleanValue(azArg
[4]));
11162 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
11165 }else if( cli_strcmp(azArg
[1],"edit")==0 ){
11167 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
11169 goto meta_command_exit
;
11171 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
11172 booleanValue(azArg
[4]));
11174 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
11177 }else if( cli_strcmp(azArg
[1],"delete")==0 ){
11179 raw_printf(stderr
, "Usage: .user delete USER\n");
11181 goto meta_command_exit
;
11183 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
11185 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
11189 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
11191 goto meta_command_exit
;
11194 #endif /* SQLITE_USER_AUTHENTICATION */
11196 if( c
=='v' && cli_strncmp(azArg
[0], "version", n
)==0 ){
11197 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
11198 sqlite3_libversion(), sqlite3_sourceid());
11199 #if SQLITE_HAVE_ZLIB
11200 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
11202 #define CTIMEOPT_VAL_(opt) #opt
11203 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11204 #if defined(__clang__) && defined(__clang_major__)
11205 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
11206 CTIMEOPT_VAL(__clang_minor__
) "."
11207 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
11208 #elif defined(_MSC_VER)
11209 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
11210 #elif defined(__GNUC__) && defined(__VERSION__)
11211 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
11215 if( c
=='v' && cli_strncmp(azArg
[0], "vfsinfo", n
)==0 ){
11216 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
11217 sqlite3_vfs
*pVfs
= 0;
11219 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
11221 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
11222 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
11223 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
11224 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
11229 if( c
=='v' && cli_strncmp(azArg
[0], "vfslist", n
)==0 ){
11231 sqlite3_vfs
*pCurrent
= 0;
11233 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
11235 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
11236 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
11237 pVfs
==pCurrent
? " <--- CURRENT" : "");
11238 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
11239 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
11240 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
11242 raw_printf(p
->out
, "-----------------------------------\n");
11247 if( c
=='v' && cli_strncmp(azArg
[0], "vfsname", n
)==0 ){
11248 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
11249 char *zVfsName
= 0;
11251 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
11253 utf8_printf(p
->out
, "%s\n", zVfsName
);
11254 sqlite3_free(zVfsName
);
11259 if( c
=='w' && cli_strncmp(azArg
[0], "wheretrace", n
)==0 ){
11260 unsigned int x
= nArg
>=2? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
11261 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &x
);
11264 if( c
=='w' && cli_strncmp(azArg
[0], "width", n
)==0 ){
11266 assert( nArg
<=ArraySize(azArg
) );
11267 p
->nWidth
= nArg
-1;
11268 p
->colWidth
= realloc(p
->colWidth
, (p
->nWidth
+1)*sizeof(int)*2);
11269 if( p
->colWidth
==0 && p
->nWidth
>0 ) shell_out_of_memory();
11270 if( p
->nWidth
) p
->actualWidth
= &p
->colWidth
[p
->nWidth
];
11271 for(j
=1; j
<nArg
; j
++){
11272 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
11277 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
11278 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
11285 if( p
->outCount
==0 ) output_reset(p
);
11287 p
->bSafeMode
= p
->bSafeModePersist
;
11291 /* Line scan result and intermediate states (supporting scan resumption)
11294 # define CHAR_BIT 8
11297 QSS_HasDark
= 1<<CHAR_BIT
, QSS_EndingSemi
= 2<<CHAR_BIT
,
11298 QSS_CharMask
= (1<<CHAR_BIT
)-1, QSS_ScanMask
= 3<<CHAR_BIT
,
11301 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11302 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11303 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11304 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11305 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11308 ** Scan line for classification to guide shell's handling.
11309 ** The scan is resumable for subsequent lines when prior
11310 ** return values are passed as the 2nd argument.
11312 static QuickScanState
quickscan(char *zLine
, QuickScanState qss
,
11313 SCAN_TRACKER_REFTYPE pst
){
11315 char cWait
= (char)qss
; /* intentional narrowing loss */
11318 assert( cWait
==0 );
11319 while( (cin
= *zLine
++)!=0 ){
11326 while((cin
= *++zLine
)!=0 )
11331 qss
|= QSS_EndingSemi
;
11337 CONTINUE_PROMPT_AWAITS(pst
, "/*");
11338 qss
= QSS_SETV(qss
, cWait
);
11344 deliberate_fall_through
;
11345 case '`': case '\'': case '"':
11347 qss
= QSS_HasDark
| cWait
;
11348 CONTINUE_PROMPT_AWAITC(pst
, cin
);
11351 CONTINUE_PAREN_INCR(pst
, 1);
11354 CONTINUE_PAREN_INCR(pst
, -1);
11359 qss
= (qss
& ~QSS_EndingSemi
) | QSS_HasDark
;
11363 while( (cin
= *zLine
++)!=0 ){
11367 if( *zLine
!= '/' )
11371 CONTINUE_PROMPT_AWAITC(pst
, 0);
11372 qss
= QSS_SETV(qss
, 0);
11374 case '`': case '\'': case '"':
11376 /* Swallow doubled end-delimiter.*/
11380 deliberate_fall_through
;
11383 CONTINUE_PROMPT_AWAITC(pst
, 0);
11384 qss
= QSS_SETV(qss
, 0);
11386 default: assert(0);
11395 ** Return TRUE if the line typed in is an SQL command terminator other
11396 ** than a semi-colon. The SQL Server style "go" command is understood
11397 ** as is the Oracle "/".
11399 static int line_is_command_terminator(char *zLine
){
11400 while( IsSpace(zLine
[0]) ){ zLine
++; };
11401 if( zLine
[0]=='/' )
11402 zLine
+= 1; /* Oracle */
11403 else if ( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o' )
11404 zLine
+= 2; /* SQL Server */
11407 return quickscan(zLine
, QSS_Start
, 0)==QSS_Start
;
11411 ** The CLI needs a working sqlite3_complete() to work properly. So error
11412 ** out of the build if compiling with SQLITE_OMIT_COMPLETE.
11414 #ifdef SQLITE_OMIT_COMPLETE
11415 # error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
11419 ** Return true if zSql is a complete SQL statement. Return false if it
11420 ** ends in the middle of a string literal or C-style comment.
11422 static int line_is_complete(char *zSql
, int nSql
){
11424 if( zSql
==0 ) return 1;
11427 rc
= sqlite3_complete(zSql
);
11433 ** Run a single line of SQL. Return the number of errors.
11435 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
11440 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
11441 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
11443 rc
= shell_exec(p
, zSql
, &zErrMsg
);
11445 if( rc
|| zErrMsg
){
11447 const char *zErrorTail
;
11448 const char *zErrorType
;
11450 zErrorType
= "Error";
11451 zErrorTail
= sqlite3_errmsg(p
->db
);
11452 }else if( cli_strncmp(zErrMsg
, "in prepare, ",12)==0 ){
11453 zErrorType
= "Parse error";
11454 zErrorTail
= &zErrMsg
[12];
11455 }else if( cli_strncmp(zErrMsg
, "stepping, ", 10)==0 ){
11456 zErrorType
= "Runtime error";
11457 zErrorTail
= &zErrMsg
[10];
11459 zErrorType
= "Error";
11460 zErrorTail
= zErrMsg
;
11462 if( in
!=0 || !stdin_is_interactive
){
11463 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
11464 "%s near line %d:", zErrorType
, startline
);
11466 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "%s:", zErrorType
);
11468 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrorTail
);
11469 sqlite3_free(zErrMsg
);
11472 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
11473 char zLineBuf
[2000];
11474 sqlite3_snprintf(sizeof(zLineBuf
), zLineBuf
,
11475 "changes: %lld total_changes: %lld",
11476 sqlite3_changes64(p
->db
), sqlite3_total_changes64(p
->db
));
11477 raw_printf(p
->out
, "%s\n", zLineBuf
);
11482 static void echo_group_input(ShellState
*p
, const char *zDo
){
11483 if( ShellHasFlag(p
, SHFLG_Echo
) ) utf8_printf(p
->out
, "%s\n", zDo
);
11486 #ifdef SQLITE_SHELL_FIDDLE
11488 ** Alternate one_input_line() impl for wasm mode. This is not in the primary
11489 ** impl because we need the global shellState and cannot access it from that
11490 ** function without moving lots of code around (creating a larger/messier diff).
11492 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
11493 /* Parse the next line from shellState.wasm.zInput. */
11494 const char *zBegin
= shellState
.wasm
.zPos
;
11495 const char *z
= zBegin
;
11499 UNUSED_PARAMETER(in
);
11500 UNUSED_PARAMETER(isContinuation
);
11504 while(*z
&& isspace(*z
)) ++z
;
11506 for(; *z
&& '\n'!=*z
; ++nZ
, ++z
){}
11507 if(nZ
>0 && '\r'==zBegin
[nZ
-1]){
11510 shellState
.wasm
.zPos
= z
;
11511 zLine
= realloc(zPrior
, nZ
+1);
11512 shell_check_oom(zLine
);
11513 memcpy(zLine
, zBegin
, nZ
);
11517 #endif /* SQLITE_SHELL_FIDDLE */
11520 ** Read input from *in and process it. If *in==0 then input
11521 ** is interactive - the user is typing it it. Otherwise, input
11522 ** is coming from a file or device. A prompt is issued and history
11523 ** is saved only if input is interactive. An interrupt signal will
11524 ** cause this routine to exit immediately, unless input is interactive.
11526 ** Return the number of errors.
11528 static int process_input(ShellState
*p
){
11529 char *zLine
= 0; /* A single input line */
11530 char *zSql
= 0; /* Accumulated SQL text */
11531 i64 nLine
; /* Length of current line */
11532 i64 nSql
= 0; /* Bytes of zSql[] used */
11533 i64 nAlloc
= 0; /* Allocated zSql[] space */
11534 int rc
; /* Error code */
11535 int errCnt
= 0; /* Number of errors seen */
11536 i64 startline
= 0; /* Line number for start of current input */
11537 QuickScanState qss
= QSS_Start
; /* Accumulated line status (so far) */
11539 if( p
->inputNesting
==MAX_INPUT_NESTING
){
11540 /* This will be more informative in a later version. */
11541 utf8_printf(stderr
,"Input nesting limit (%d) reached at line %d."
11542 " Check recursion.\n", MAX_INPUT_NESTING
, p
->lineno
);
11547 CONTINUE_PROMPT_RESET
;
11548 while( errCnt
==0 || !bail_on_error
|| (p
->in
==0 && stdin_is_interactive
) ){
11550 zLine
= one_input_line(p
->in
, zLine
, nSql
>0);
11553 if( p
->in
==0 && stdin_is_interactive
) printf("\n");
11556 if( seenInterrupt
){
11557 if( p
->in
!=0 ) break;
11561 if( QSS_INPLAIN(qss
)
11562 && line_is_command_terminator(zLine
)
11563 && line_is_complete(zSql
, nSql
) ){
11564 memcpy(zLine
,";",2);
11566 qss
= quickscan(zLine
, qss
, CONTINUE_PROMPT_PSTATE
);
11567 if( QSS_PLAINWHITE(qss
) && nSql
==0 ){
11568 /* Just swallow single-line whitespace */
11569 echo_group_input(p
, zLine
);
11573 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
11574 CONTINUE_PROMPT_RESET
;
11575 echo_group_input(p
, zLine
);
11576 if( zLine
[0]=='.' ){
11577 rc
= do_meta_command(zLine
, p
);
11578 if( rc
==2 ){ /* exit requested */
11587 /* No single-line dispositions remain; accumulate line(s). */
11588 nLine
= strlen(zLine
);
11589 if( nSql
+nLine
+2>=nAlloc
){
11590 /* Grow buffer by half-again increments when big. */
11591 nAlloc
= nSql
+(nSql
>>1)+nLine
+100;
11592 zSql
= realloc(zSql
, nAlloc
);
11593 shell_check_oom(zSql
);
11597 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
11598 assert( nAlloc
>0 && zSql
!=0 );
11599 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
11600 startline
= p
->lineno
;
11603 zSql
[nSql
++] = '\n';
11604 memcpy(zSql
+nSql
, zLine
, nLine
+1);
11607 if( nSql
&& QSS_SEMITERM(qss
) && sqlite3_complete(zSql
) ){
11608 echo_group_input(p
, zSql
);
11609 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11610 CONTINUE_PROMPT_RESET
;
11618 p
->bSafeMode
= p
->bSafeModePersist
;
11620 }else if( nSql
&& QSS_PLAINWHITE(qss
) ){
11621 echo_group_input(p
, zSql
);
11627 /* This may be incomplete. Let the SQL parser deal with that. */
11628 echo_group_input(p
, zSql
);
11629 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11630 CONTINUE_PROMPT_RESET
;
11639 ** Return a pathname which is the user's home directory. A
11640 ** 0 return indicates an error of some kind.
11642 static char *find_home_dir(int clearFlag
){
11643 static char *home_dir
= NULL
;
11649 if( home_dir
) return home_dir
;
11651 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11652 && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
11654 struct passwd
*pwent
;
11655 uid_t uid
= getuid();
11656 if( (pwent
=getpwuid(uid
)) != NULL
) {
11657 home_dir
= pwent
->pw_dir
;
11662 #if defined(_WIN32_WCE)
11663 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11668 #if defined(_WIN32) || defined(WIN32)
11670 home_dir
= getenv("USERPROFILE");
11675 home_dir
= getenv("HOME");
11678 #if defined(_WIN32) || defined(WIN32)
11680 char *zDrive
, *zPath
;
11682 zDrive
= getenv("HOMEDRIVE");
11683 zPath
= getenv("HOMEPATH");
11684 if( zDrive
&& zPath
){
11685 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
11686 home_dir
= malloc( n
);
11687 if( home_dir
==0 ) return 0;
11688 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
11695 #endif /* !_WIN32_WCE */
11698 i64 n
= strlen(home_dir
) + 1;
11699 char *z
= malloc( n
);
11700 if( z
) memcpy(z
, home_dir
, n
);
11708 ** On non-Windows platforms, look for $XDG_CONFIG_HOME.
11709 ** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
11710 ** the path to it, else return 0. The result is cached for
11711 ** subsequent calls.
11713 static const char *find_xdg_config(void){
11714 #if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
11715 || defined(__RTP__) || defined(_WRS_KERNEL)
11718 static int alreadyTried
= 0;
11719 static char *zConfig
= 0;
11720 const char *zXdgHome
;
11722 if( alreadyTried
!=0 ){
11726 zXdgHome
= getenv("XDG_CONFIG_HOME");
11730 zConfig
= sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome
);
11731 shell_check_oom(zConfig
);
11732 if( access(zConfig
,0)!=0 ){
11733 sqlite3_free(zConfig
);
11741 ** Read input from the file given by sqliterc_override. Or if that
11742 ** parameter is NULL, take input from the first of find_xdg_config()
11743 ** or ~/.sqliterc which is found.
11745 ** Returns the number of errors.
11747 static void process_sqliterc(
11748 ShellState
*p
, /* Configuration data */
11749 const char *sqliterc_override
/* Name of config file. NULL to use default */
11751 char *home_dir
= NULL
;
11752 const char *sqliterc
= sqliterc_override
;
11754 FILE *inSaved
= p
->in
;
11755 int savedLineno
= p
->lineno
;
11757 if( sqliterc
== NULL
){
11758 sqliterc
= find_xdg_config();
11760 if( sqliterc
== NULL
){
11761 home_dir
= find_home_dir(0);
11763 raw_printf(stderr
, "-- warning: cannot find home directory;"
11764 " cannot read ~/.sqliterc\n");
11767 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
11768 shell_check_oom(zBuf
);
11771 p
->in
= fopen(sqliterc
,"rb");
11773 if( stdin_is_interactive
){
11774 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
11776 if( process_input(p
) && bail_on_error
) exit(1);
11778 }else if( sqliterc_override
!=0 ){
11779 utf8_printf(stderr
,"cannot open: \"%s\"\n", sqliterc
);
11780 if( bail_on_error
) exit(1);
11783 p
->lineno
= savedLineno
;
11784 sqlite3_free(zBuf
);
11788 ** Show available command line options
11790 static const char zOptions
[] =
11791 " -- treat no subsequent arguments as options\n"
11792 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11793 " -A ARGS... run \".archive ARGS\" and exit\n"
11795 " -append append the database to the end of the file\n"
11796 " -ascii set output mode to 'ascii'\n"
11797 " -bail stop after hitting an error\n"
11798 " -batch force batch I/O\n"
11799 " -box set output mode to 'box'\n"
11800 " -column set output mode to 'column'\n"
11801 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11802 " -csv set output mode to 'csv'\n"
11803 #if !defined(SQLITE_OMIT_DESERIALIZE)
11804 " -deserialize open the database using sqlite3_deserialize()\n"
11806 " -echo print inputs before execution\n"
11807 " -init FILENAME read/process named file\n"
11808 " -[no]header turn headers on or off\n"
11809 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11810 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11812 " -help show this message\n"
11813 " -html set output mode to HTML\n"
11814 " -interactive force interactive I/O\n"
11815 " -json set output mode to 'json'\n"
11816 " -line set output mode to 'line'\n"
11817 " -list set output mode to 'list'\n"
11818 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11819 " -markdown set output mode to 'markdown'\n"
11820 #if !defined(SQLITE_OMIT_DESERIALIZE)
11821 " -maxsize N maximum size for a --deserialize database\n"
11823 " -memtrace trace all memory allocations and deallocations\n"
11824 " -mmap N default mmap size set to N\n"
11825 #ifdef SQLITE_ENABLE_MULTIPLEX
11826 " -multiplex enable the multiplexor VFS\n"
11828 " -newline SEP set output row separator. Default: '\\n'\n"
11829 " -nofollow refuse to open symbolic links to database files\n"
11830 " -nonce STRING set the safe-mode escape nonce\n"
11831 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11832 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11833 " -quote set output mode to 'quote'\n"
11834 " -readonly open the database read-only\n"
11835 " -safe enable safe-mode\n"
11836 " -separator SEP set output column separator. Default: '|'\n"
11837 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11838 " -sorterref SIZE sorter references threshold size\n"
11840 " -stats print memory stats before each finalize\n"
11841 " -table set output mode to 'table'\n"
11842 " -tabs set output mode to 'tabs'\n"
11843 " -unsafe-testing allow unsafe commands and modes for testing\n"
11844 #if SHELL_WIN_UTF8_OPT
11845 " -utf8 setup interactive console code page for UTF-8\n"
11847 " -version show SQLite version\n"
11848 " -vfs NAME use NAME as the default VFS\n"
11849 #ifdef SQLITE_ENABLE_VFSTRACE
11850 " -vfstrace enable tracing of all VFS calls\n"
11852 #ifdef SQLITE_HAVE_ZLIB
11853 " -zip open the file as a ZIP Archive\n"
11856 static void usage(int showDetail
){
11857 utf8_printf(stderr
,
11858 "Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
11859 "FILENAME is the name of an SQLite database. A new database is created\n"
11860 "if the file does not previously exist. Defaults to :memory:.\n", Argv0
);
11862 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
11864 raw_printf(stderr
, "Use the -help option for additional information\n");
11870 ** Internal check: Verify that the SQLite is uninitialized. Print a
11871 ** error message if it is initialized.
11873 static void verify_uninitialized(void){
11874 if( sqlite3_config(-1)==SQLITE_MISUSE
){
11875 utf8_printf(stdout
, "WARNING: attempt to configure SQLite after"
11876 " initialization.\n");
11881 ** Initialize the state information in data
11883 static void main_init(ShellState
*data
) {
11884 memset(data
, 0, sizeof(*data
));
11885 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
11886 data
->autoExplain
= 1;
11887 data
->pAuxDb
= &data
->aAuxDb
[0];
11888 memcpy(data
->colSeparator
,SEP_Column
, 2);
11889 memcpy(data
->rowSeparator
,SEP_Row
, 2);
11890 data
->showHeader
= 0;
11891 data
->shellFlgs
= SHFLG_Lookaside
;
11892 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
11893 #if !defined(SQLITE_SHELL_FIDDLE)
11894 verify_uninitialized();
11896 sqlite3_config(SQLITE_CONFIG_URI
, 1);
11897 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
11898 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
11899 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
11903 ** Output text to the console in a font that attracts extra attention.
11906 static void printBold(const char *zText
){
11907 #if !SQLITE_OS_WINRT
11908 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
11909 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
11910 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
11911 SetConsoleTextAttribute(out
,
11912 FOREGROUND_RED
|FOREGROUND_INTENSITY
11915 printf("%s", zText
);
11916 #if !SQLITE_OS_WINRT
11917 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
11921 static void printBold(const char *zText
){
11922 printf("\033[1m%s\033[0m", zText
);
11927 ** Get the argument to an --option. Throw an error and die if no argument
11930 static char *cmdline_option_value(int argc
, char **argv
, int i
){
11932 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
11933 argv
[0], argv
[argc
-1]);
11939 static void sayAbnormalExit(void){
11940 if( seenInterrupt
) fprintf(stderr
, "Program interrupted.\n");
11943 #ifndef SQLITE_SHELL_IS_UTF8
11944 # if (defined(_WIN32) || defined(WIN32)) \
11945 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11946 # define SQLITE_SHELL_IS_UTF8 (0)
11948 # define SQLITE_SHELL_IS_UTF8 (1)
11952 #ifdef SQLITE_SHELL_FIDDLE
11953 # define main fiddle_main
11956 #if SQLITE_SHELL_IS_UTF8
11957 int SQLITE_CDECL
main(int argc
, char **argv
){
11959 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
11962 #ifdef SQLITE_DEBUG
11963 sqlite3_int64 mem_main_enter
= 0;
11966 #ifdef SQLITE_SHELL_FIDDLE
11967 # define data shellState
11971 const char *zInitFile
= 0;
11974 int warnInmemoryDb
= 0;
11977 int nOptsEnd
= argc
;
11979 const char *zVfs
= 0; /* Value of -vfs command-line option */
11980 #if !SQLITE_SHELL_IS_UTF8
11981 char **argvToFree
= 0;
11982 int argcToFree
= 0;
11984 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
11986 #ifdef SQLITE_SHELL_FIDDLE
11987 stdin_is_interactive
= 0;
11988 stdout_is_console
= 1;
11989 data
.wasm
.zDefaultDbName
= "/fiddle.sqlite3";
11991 stdin_is_interactive
= isatty(0);
11992 stdout_is_console
= isatty(1);
11994 #if SHELL_WIN_UTF8_OPT
11995 atexit(console_restore
); /* Needs revision for CLI as library call */
11997 atexit(sayAbnormalExit
);
11998 #ifdef SQLITE_DEBUG
11999 mem_main_enter
= sqlite3_memory_used();
12001 #if !defined(_WIN32_WCE)
12002 if( getenv("SQLITE_DEBUG_BREAK") ){
12003 if( isatty(0) && isatty(2) ){
12005 "attach debugger to process %d and press any key to continue.\n",
12009 #if defined(_WIN32) || defined(WIN32)
12010 #if SQLITE_OS_WINRT
12015 #elif defined(SIGTRAP)
12021 /* Register a valid signal handler early, before much else is done. */
12023 signal(SIGINT
, interrupt_handler
);
12024 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12025 if( !SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
) ){
12026 fprintf(stderr
, "No ^C handler.\n");
12030 #if USE_SYSTEM_SQLITE+0!=1
12031 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
12032 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
12033 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
12039 /* On Windows, we must translate command-line arguments into UTF-8.
12040 ** The SQLite memory allocator subsystem has to be enabled in order to
12041 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
12042 ** subsequent sqlite3_config() calls will work. So copy all results into
12043 ** memory that does not come from the SQLite memory allocator.
12045 #if !SQLITE_SHELL_IS_UTF8
12046 sqlite3_initialize();
12047 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
12048 shell_check_oom(argvToFree
);
12050 argv
= argvToFree
+ argc
;
12051 for(i
=0; i
<argc
; i
++){
12052 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
12054 shell_check_oom(z
);
12056 argv
[i
] = malloc( n
+1 );
12057 shell_check_oom(argv
[i
]);
12058 memcpy(argv
[i
], z
, n
+1);
12059 argvToFree
[i
] = argv
[i
];
12062 sqlite3_shutdown();
12065 assert( argc
>=1 && argv
&& argv
[0] );
12068 #ifdef SQLITE_SHELL_DBNAME_PROC
12070 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12071 ** of a C-function that will provide the name of the database file. Use
12072 ** this compile-time option to embed this shell program in larger
12073 ** applications. */
12074 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12075 SQLITE_SHELL_DBNAME_PROC(&data
.pAuxDb
->zDbFilename
);
12076 warnInmemoryDb
= 0;
12080 /* Do an initial pass through the command-line argument to locate
12081 ** the name of the database file, the name of the initialization file,
12082 ** the size of the alternative malloc heap,
12083 ** and the first command to execute.
12085 #ifndef SQLITE_SHELL_FIDDLE
12086 verify_uninitialized();
12088 for(i
=1; i
<argc
; i
++){
12091 if( z
[0]!='-' || i
>nOptsEnd
){
12092 if( data
.aAuxDb
->zDbFilename
==0 ){
12093 data
.aAuxDb
->zDbFilename
= z
;
12095 /* Excesss arguments are interpreted as SQL (or dot-commands) and
12096 ** mean that nothing is read from stdin */
12099 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
12100 shell_check_oom(azCmd
);
12105 if( z
[1]=='-' ) z
++;
12106 if( cli_strcmp(z
, "-")==0 ){
12109 }else if( cli_strcmp(z
,"-separator")==0
12110 || cli_strcmp(z
,"-nullvalue")==0
12111 || cli_strcmp(z
,"-newline")==0
12112 || cli_strcmp(z
,"-cmd")==0
12114 (void)cmdline_option_value(argc
, argv
, ++i
);
12115 }else if( cli_strcmp(z
,"-init")==0 ){
12116 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
12117 }else if( cli_strcmp(z
,"-batch")==0 ){
12118 /* Need to check for batch mode here to so we can avoid printing
12119 ** informational messages (like from process_sqliterc) before
12120 ** we do the actual processing of arguments later in a second pass.
12122 stdin_is_interactive
= 0;
12123 }else if( cli_strcmp(z
,"-heap")==0 ){
12124 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12126 sqlite3_int64 szHeap
;
12128 zSize
= cmdline_option_value(argc
, argv
, ++i
);
12129 szHeap
= integerValue(zSize
);
12130 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
12131 verify_uninitialized();
12132 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
12134 (void)cmdline_option_value(argc
, argv
, ++i
);
12136 }else if( cli_strcmp(z
,"-pagecache")==0 ){
12137 sqlite3_int64 n
, sz
;
12138 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12139 if( sz
>70000 ) sz
= 70000;
12141 n
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12142 if( sz
>0 && n
>0 && 0xffffffffffffLL
/sz
<n
){
12143 n
= 0xffffffffffffLL
/sz
;
12145 verify_uninitialized();
12146 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
12147 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
12148 data
.shellFlgs
|= SHFLG_Pagecache
;
12149 }else if( cli_strcmp(z
,"-lookaside")==0 ){
12151 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12153 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12155 verify_uninitialized();
12156 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
12157 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
12158 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
12160 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
12161 verify_uninitialized();
12163 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
); break;
12164 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD
); break;
12165 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED
); break;
12167 #ifdef SQLITE_ENABLE_VFSTRACE
12168 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
12169 extern int vfstrace_register(
12170 const char *zTraceName
,
12171 const char *zOldVfsName
,
12172 int (*xOut
)(const char*,void*),
12176 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
12178 #ifdef SQLITE_ENABLE_MULTIPLEX
12179 }else if( cli_strcmp(z
,"-multiplex")==0 ){
12180 extern int sqlite3_multiple_initialize(const char*,int);
12181 sqlite3_multiplex_initialize(0, 1);
12183 }else if( cli_strcmp(z
,"-mmap")==0 ){
12184 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12185 verify_uninitialized();
12186 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
12187 #if defined(SQLITE_ENABLE_SORTER_REFERENCES)
12188 }else if( cli_strcmp(z
,"-sorterref")==0 ){
12189 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
12190 verify_uninitialized();
12191 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
12193 }else if( cli_strcmp(z
,"-vfs")==0 ){
12194 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
12195 #ifdef SQLITE_HAVE_ZLIB
12196 }else if( cli_strcmp(z
,"-zip")==0 ){
12197 data
.openMode
= SHELL_OPEN_ZIPFILE
;
12199 }else if( cli_strcmp(z
,"-append")==0 ){
12200 data
.openMode
= SHELL_OPEN_APPENDVFS
;
12201 #ifndef SQLITE_OMIT_DESERIALIZE
12202 }else if( cli_strcmp(z
,"-deserialize")==0 ){
12203 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
12204 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
12205 data
.szMax
= integerValue(argv
[++i
]);
12207 }else if( cli_strcmp(z
,"-readonly")==0 ){
12208 data
.openMode
= SHELL_OPEN_READONLY
;
12209 }else if( cli_strcmp(z
,"-nofollow")==0 ){
12210 data
.openFlags
= SQLITE_OPEN_NOFOLLOW
;
12211 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12212 }else if( cli_strncmp(z
, "-A",2)==0 ){
12213 /* All remaining command-line arguments are passed to the ".archive"
12214 ** command, so ignore them */
12217 }else if( cli_strcmp(z
, "-memtrace")==0 ){
12218 sqlite3MemTraceActivate(stderr
);
12219 }else if( cli_strcmp(z
,"-bail")==0 ){
12221 }else if( cli_strcmp(z
,"-nonce")==0 ){
12223 data
.zNonce
= strdup(argv
[++i
]);
12224 }else if( cli_strcmp(z
,"-unsafe-testing")==0 ){
12225 ShellSetFlag(&data
,SHFLG_TestingMode
);
12226 }else if( cli_strcmp(z
,"-safe")==0 ){
12227 /* no-op - catch this on the second pass */
12230 #ifndef SQLITE_SHELL_FIDDLE
12231 verify_uninitialized();
12235 #ifdef SQLITE_SHELL_INIT_PROC
12237 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12238 ** of a C-function that will perform initialization actions on SQLite that
12239 ** occur just before or after sqlite3_initialize(). Use this compile-time
12240 ** option to embed this shell program in larger applications. */
12241 extern void SQLITE_SHELL_INIT_PROC(void);
12242 SQLITE_SHELL_INIT_PROC();
12245 /* All the sqlite3_config() calls have now been made. So it is safe
12246 ** to call sqlite3_initialize() and process any command line -vfs option. */
12247 sqlite3_initialize();
12251 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
12253 sqlite3_vfs_register(pVfs
, 1);
12255 utf8_printf(stderr
, "no such VFS: \"%s\"\n", zVfs
);
12260 if( data
.pAuxDb
->zDbFilename
==0 ){
12261 #ifndef SQLITE_OMIT_MEMORYDB
12262 data
.pAuxDb
->zDbFilename
= ":memory:";
12263 warnInmemoryDb
= argc
==1;
12265 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
12270 #ifndef SQLITE_SHELL_FIDDLE
12271 sqlite3_appendvfs_init(0,0,0);
12274 /* Go ahead and open the database file if it already exists. If the
12275 ** file does not exist, delay opening it. This prevents empty database
12276 ** files from being created if a user mistypes the database name argument
12277 ** to the sqlite command-line tool.
12279 if( access(data
.pAuxDb
->zDbFilename
, 0)==0 ){
12283 /* Process the initialization file if there is one. If no -init option
12284 ** is given on the command line, look for a file named ~/.sqliterc and
12285 ** try to process it.
12287 process_sqliterc(&data
,zInitFile
);
12289 /* Make a second pass through the command-line argument and set
12290 ** options. This second pass is delayed until after the initialization
12291 ** file is processed so that the command-line arguments will override
12292 ** settings in the initialization file.
12294 for(i
=1; i
<argc
; i
++){
12296 if( z
[0]!='-' || i
>=nOptsEnd
) continue;
12297 if( z
[1]=='-' ){ z
++; }
12298 if( cli_strcmp(z
,"-init")==0 ){
12300 }else if( cli_strcmp(z
,"-html")==0 ){
12301 data
.mode
= MODE_Html
;
12302 }else if( cli_strcmp(z
,"-list")==0 ){
12303 data
.mode
= MODE_List
;
12304 }else if( cli_strcmp(z
,"-quote")==0 ){
12305 data
.mode
= MODE_Quote
;
12306 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
, SEP_Comma
);
12307 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
, SEP_Row
);
12308 }else if( cli_strcmp(z
,"-line")==0 ){
12309 data
.mode
= MODE_Line
;
12310 }else if( cli_strcmp(z
,"-column")==0 ){
12311 data
.mode
= MODE_Column
;
12312 }else if( cli_strcmp(z
,"-json")==0 ){
12313 data
.mode
= MODE_Json
;
12314 }else if( cli_strcmp(z
,"-markdown")==0 ){
12315 data
.mode
= MODE_Markdown
;
12316 }else if( cli_strcmp(z
,"-table")==0 ){
12317 data
.mode
= MODE_Table
;
12318 }else if( cli_strcmp(z
,"-box")==0 ){
12319 data
.mode
= MODE_Box
;
12320 }else if( cli_strcmp(z
,"-csv")==0 ){
12321 data
.mode
= MODE_Csv
;
12322 memcpy(data
.colSeparator
,",",2);
12323 #ifdef SQLITE_HAVE_ZLIB
12324 }else if( cli_strcmp(z
,"-zip")==0 ){
12325 data
.openMode
= SHELL_OPEN_ZIPFILE
;
12327 }else if( cli_strcmp(z
,"-append")==0 ){
12328 data
.openMode
= SHELL_OPEN_APPENDVFS
;
12329 #ifndef SQLITE_OMIT_DESERIALIZE
12330 }else if( cli_strcmp(z
,"-deserialize")==0 ){
12331 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
12332 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
12333 data
.szMax
= integerValue(argv
[++i
]);
12335 }else if( cli_strcmp(z
,"-readonly")==0 ){
12336 data
.openMode
= SHELL_OPEN_READONLY
;
12337 }else if( cli_strcmp(z
,"-nofollow")==0 ){
12338 data
.openFlags
|= SQLITE_OPEN_NOFOLLOW
;
12339 }else if( cli_strcmp(z
,"-ascii")==0 ){
12340 data
.mode
= MODE_Ascii
;
12341 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,SEP_Unit
);
12342 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,SEP_Record
);
12343 }else if( cli_strcmp(z
,"-tabs")==0 ){
12344 data
.mode
= MODE_List
;
12345 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,SEP_Tab
);
12346 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,SEP_Row
);
12347 }else if( cli_strcmp(z
,"-separator")==0 ){
12348 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
12349 "%s",cmdline_option_value(argc
,argv
,++i
));
12350 }else if( cli_strcmp(z
,"-newline")==0 ){
12351 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
12352 "%s",cmdline_option_value(argc
,argv
,++i
));
12353 }else if( cli_strcmp(z
,"-nullvalue")==0 ){
12354 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
12355 "%s",cmdline_option_value(argc
,argv
,++i
));
12356 }else if( cli_strcmp(z
,"-header")==0 ){
12357 data
.showHeader
= 1;
12358 ShellSetFlag(&data
, SHFLG_HeaderSet
);
12359 }else if( cli_strcmp(z
,"-noheader")==0 ){
12360 data
.showHeader
= 0;
12361 ShellSetFlag(&data
, SHFLG_HeaderSet
);
12362 }else if( cli_strcmp(z
,"-echo")==0 ){
12363 ShellSetFlag(&data
, SHFLG_Echo
);
12364 }else if( cli_strcmp(z
,"-eqp")==0 ){
12365 data
.autoEQP
= AUTOEQP_on
;
12366 }else if( cli_strcmp(z
,"-eqpfull")==0 ){
12367 data
.autoEQP
= AUTOEQP_full
;
12368 }else if( cli_strcmp(z
,"-stats")==0 ){
12370 }else if( cli_strcmp(z
,"-scanstats")==0 ){
12371 data
.scanstatsOn
= 1;
12372 }else if( cli_strcmp(z
,"-backslash")==0 ){
12373 /* Undocumented command-line option: -backslash
12374 ** Causes C-style backslash escapes to be evaluated in SQL statements
12375 ** prior to sending the SQL into SQLite. Useful for injecting
12376 ** crazy bytes in the middle of SQL statements for testing and debugging.
12378 ShellSetFlag(&data
, SHFLG_Backslash
);
12379 }else if( cli_strcmp(z
,"-bail")==0 ){
12380 /* No-op. The bail_on_error flag should already be set. */
12381 }else if( cli_strcmp(z
,"-version")==0 ){
12382 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12384 }else if( cli_strcmp(z
,"-interactive")==0 ){
12385 stdin_is_interactive
= 1;
12386 }else if( cli_strcmp(z
,"-batch")==0 ){
12387 stdin_is_interactive
= 0;
12388 }else if( cli_strcmp(z
,"-utf8")==0 ){
12389 #if SHELL_WIN_UTF8_OPT
12391 #endif /* SHELL_WIN_UTF8_OPT */
12392 }else if( cli_strcmp(z
,"-heap")==0 ){
12394 }else if( cli_strcmp(z
,"-pagecache")==0 ){
12396 }else if( cli_strcmp(z
,"-lookaside")==0 ){
12398 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
12400 }else if( cli_strcmp(z
,"-nonce")==0 ){
12402 }else if( cli_strcmp(z
,"-mmap")==0 ){
12404 }else if( cli_strcmp(z
,"-memtrace")==0 ){
12406 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
12407 }else if( cli_strcmp(z
,"-sorterref")==0 ){
12410 }else if( cli_strcmp(z
,"-vfs")==0 ){
12412 #ifdef SQLITE_ENABLE_VFSTRACE
12413 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
12416 #ifdef SQLITE_ENABLE_MULTIPLEX
12417 }else if( cli_strcmp(z
,"-multiplex")==0 ){
12420 }else if( cli_strcmp(z
,"-help")==0 ){
12422 }else if( cli_strcmp(z
,"-cmd")==0 ){
12423 /* Run commands that follow -cmd first and separately from commands
12424 ** that simply appear on the command-line. This seems goofy. It would
12425 ** be better if all commands ran in the order that they appear. But
12426 ** we retain the goofy behavior for historical compatibility. */
12427 if( i
==argc
-1 ) break;
12428 z
= cmdline_option_value(argc
,argv
,++i
);
12430 rc
= do_meta_command(z
, &data
);
12431 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
12434 rc
= shell_exec(&data
, z
, &zErrMsg
);
12436 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
12437 if( bail_on_error
) return rc
!=0 ? rc
: 1;
12439 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
12440 if( bail_on_error
) return rc
;
12443 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12444 }else if( cli_strncmp(z
, "-A", 2)==0 ){
12446 utf8_printf(stderr
, "Error: cannot mix regular SQL or dot-commands"
12447 " with \"%s\"\n", z
);
12450 open_db(&data
, OPEN_DB_ZIPFILE
);
12453 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
12455 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
12460 }else if( cli_strcmp(z
,"-safe")==0 ){
12461 data
.bSafeMode
= data
.bSafeModePersist
= 1;
12462 }else if( cli_strcmp(z
,"-unsafe-testing")==0 ){
12463 /* Acted upon in first pass. */
12465 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
12466 raw_printf(stderr
,"Use -help for a list of options.\n");
12469 data
.cMode
= data
.mode
;
12471 #if SHELL_WIN_UTF8_OPT
12472 if( console_utf8
&& stdin_is_interactive
){
12475 setBinaryMode(stdin
, 0);
12481 /* Run all arguments that do not begin with '-' as if they were separate
12482 ** command-line inputs, except for the argToSkip argument which contains
12483 ** the database filename.
12485 for(i
=0; i
<nCmd
; i
++){
12486 if( azCmd
[i
][0]=='.' ){
12487 rc
= do_meta_command(azCmd
[i
], &data
);
12490 return rc
==2 ? 0 : rc
;
12494 echo_group_input(&data
, azCmd
[i
]);
12495 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
12496 if( zErrMsg
|| rc
){
12498 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
12500 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
12502 sqlite3_free(zErrMsg
);
12504 return rc
!=0 ? rc
: 1;
12509 /* Run commands received from standard input
12511 if( stdin_is_interactive
){
12516 "SQLite version %s %.19s\n" /*extra-version-info*/
12517 "Enter \".help\" for usage hints.\n",
12518 sqlite3_libversion(), sqlite3_sourceid()
12520 if( warnInmemoryDb
){
12521 printf("Connected to a ");
12522 printBold("transient in-memory database");
12523 printf(".\nUse \".open FILENAME\" to reopen on a "
12524 "persistent database.\n");
12526 zHistory
= getenv("SQLITE_HISTORY");
12528 zHistory
= strdup(zHistory
);
12529 }else if( (zHome
= find_home_dir(0))!=0 ){
12530 nHistory
= strlen30(zHome
) + 20;
12531 if( (zHistory
= malloc(nHistory
))!=0 ){
12532 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
12535 if( zHistory
){ shell_read_history(zHistory
); }
12536 #if HAVE_READLINE || HAVE_EDITLINE
12537 rl_attempted_completion_function
= readline_completion
;
12538 #elif HAVE_LINENOISE
12539 linenoiseSetCompletionCallback(linenoise_completion
);
12542 rc
= process_input(&data
);
12544 shell_stifle_history(2000);
12545 shell_write_history(zHistory
);
12550 rc
= process_input(&data
);
12553 #ifndef SQLITE_SHELL_FIDDLE
12554 /* In WASM mode we have to leave the db state in place so that
12555 ** client code can "push" SQL into it after this call returns. */
12557 set_table_name(&data
, 0);
12559 session_close_all(&data
, -1);
12562 for(i
=0; i
<ArraySize(data
.aAuxDb
); i
++){
12563 sqlite3_free(data
.aAuxDb
[i
].zFreeOnClose
);
12564 if( data
.aAuxDb
[i
].db
){
12565 session_close_all(&data
, i
);
12566 close_db(data
.aAuxDb
[i
].db
);
12570 output_reset(&data
);
12571 data
.doXdgOpen
= 0;
12572 clearTempFile(&data
);
12573 #if !SQLITE_SHELL_IS_UTF8
12574 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
12577 free(data
.colWidth
);
12579 /* Clear the global data structure so that valgrind will detect memory
12581 memset(&data
, 0, sizeof(data
));
12582 #ifdef SQLITE_DEBUG
12583 if( sqlite3_memory_used()>mem_main_enter
){
12584 utf8_printf(stderr
, "Memory leaked: %u bytes\n",
12585 (unsigned int)(sqlite3_memory_used()-mem_main_enter
));
12588 #endif /* !SQLITE_SHELL_FIDDLE */
12593 #ifdef SQLITE_SHELL_FIDDLE
12594 /* Only for emcc experimentation purposes. */
12595 int fiddle_experiment(int a
,int b
){
12600 ** Returns a pointer to the current DB handle.
12602 sqlite3
* fiddle_db_handle(){
12607 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12608 ** "main" is assumed. Returns 0 if no db with the given name is
12611 sqlite3_vfs
* fiddle_db_vfs(const char *zDbName
){
12612 sqlite3_vfs
* pVfs
= 0;
12614 sqlite3_file_control(globalDb
, zDbName
? zDbName
: "main",
12615 SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
12620 /* Only for emcc experimentation purposes. */
12621 sqlite3
* fiddle_db_arg(sqlite3
*arg
){
12622 printf("fiddle_db_arg(%p)\n", (const void*)arg
);
12627 ** Intended to be called via a SharedWorker() while a separate
12628 ** SharedWorker() (which manages the wasm module) is performing work
12629 ** which should be interrupted. Unfortunately, SharedWorker is not
12630 ** portable enough to make real use of.
12632 void fiddle_interrupt(void){
12633 if( globalDb
) sqlite3_interrupt(globalDb
);
12637 ** Returns the filename of the given db name, assuming "main" if
12638 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12640 const char * fiddle_db_filename(const char * zDbName
){
12642 ? sqlite3_db_filename(globalDb
, zDbName
? zDbName
: "main")
12647 ** Completely wipes out the contents of the currently-opened database
12648 ** but leaves its storage intact for reuse.
12650 void fiddle_reset_db(void){
12652 int rc
= sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 1, 0);
12653 if( 0==rc
) rc
= sqlite3_exec(globalDb
, "VACUUM", 0, 0, 0);
12654 sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 0, 0);
12659 ** Uses the current database's VFS xRead to stream the db file's
12660 ** contents out to the given callback. The callback gets a single
12661 ** chunk of size n (its 2nd argument) on each call and must return 0
12662 ** on success, non-0 on error. This function returns 0 on success,
12663 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12664 ** code from the callback. Note that this is not thread-friendly: it
12665 ** expects that it will be the only thread reading the db file and
12666 ** takes no measures to ensure that is the case.
12668 int fiddle_export_db( int (*xCallback
)(unsigned const char *zOut
, int n
) ){
12669 sqlite3_int64 nSize
= 0;
12670 sqlite3_int64 nPos
= 0;
12671 sqlite3_file
* pFile
= 0;
12672 unsigned char buf
[1024 * 8];
12673 int nBuf
= (int)sizeof(buf
);
12674 int rc
= shellState
.db
12675 ? sqlite3_file_control(shellState
.db
, "main",
12676 SQLITE_FCNTL_FILE_POINTER
, &pFile
)
12678 if( rc
) return rc
;
12679 rc
= pFile
->pMethods
->xFileSize(pFile
, &nSize
);
12680 if( rc
) return rc
;
12682 /* DB size is not an even multiple of the buffer size. Reduce
12683 ** buffer size so that we do not unduly inflate the db size when
12685 if(0 == nSize
% 4096) nBuf
= 4096;
12686 else if(0 == nSize
% 2048) nBuf
= 2048;
12687 else if(0 == nSize
% 1024) nBuf
= 1024;
12690 for( ; 0==rc
&& nPos
<nSize
; nPos
+= nBuf
){
12691 rc
= pFile
->pMethods
->xRead(pFile
, buf
, nBuf
, nPos
);
12692 if(SQLITE_IOERR_SHORT_READ
== rc
){
12693 rc
= (nPos
+ nBuf
) < nSize
? rc
: 0/*assume EOF*/;
12695 if( 0==rc
) rc
= xCallback(buf
, nBuf
);
12701 ** Trivial exportable function for emscripten. It processes zSql as if
12702 ** it were input to the sqlite3 shell and redirects all output to the
12703 ** wasm binding. fiddle_main() must have been called before this
12704 ** is called, or results are undefined.
12706 void fiddle_exec(const char * zSql
){
12708 if('.'==*zSql
) puts(zSql
);
12709 shellState
.wasm
.zInput
= zSql
;
12710 shellState
.wasm
.zPos
= zSql
;
12711 process_input(&shellState
);
12712 shellState
.wasm
.zInput
= shellState
.wasm
.zPos
= 0;
12715 #endif /* SQLITE_SHELL_FIDDLE */