4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code to implement the "sqlite" command line
13 ** utility for accessing SQLite databases.
15 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16 /* This needs to come before any includes for MSVC compiler */
17 #define _CRT_SECURE_NO_WARNINGS
19 typedef unsigned int u32
;
20 typedef unsigned short int u16
;
23 ** Optionally #include a user-defined header, whereby compilation options
24 ** may be set prior to where they take effect, but after platform setup.
25 ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
26 ** file. Note that this macro has a like effect on sqlite3.c compilation.
28 # define SHELL_STRINGIFY_(f) #f
29 # define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
30 #ifdef SQLITE_CUSTOM_INCLUDE
31 # include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
35 ** Determine if we are dealing with WinRT, which provides only a subset of
36 ** the full Win32 API.
38 #if !defined(SQLITE_OS_WINRT)
39 # define SQLITE_OS_WINRT 0
43 ** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
44 ** somewhat for use as a WASM module in a web browser. This flag
45 ** should only be used when building the "fiddle" web application, as
46 ** the browser-mode build has much different user input requirements
47 ** and this build mode rewires the user input subsystem to account for
52 ** Warning pragmas copied from msvc.h in the core.
55 #pragma warning(disable : 4054)
56 #pragma warning(disable : 4055)
57 #pragma warning(disable : 4100)
58 #pragma warning(disable : 4127)
59 #pragma warning(disable : 4130)
60 #pragma warning(disable : 4152)
61 #pragma warning(disable : 4189)
62 #pragma warning(disable : 4206)
63 #pragma warning(disable : 4210)
64 #pragma warning(disable : 4232)
65 #pragma warning(disable : 4244)
66 #pragma warning(disable : 4305)
67 #pragma warning(disable : 4306)
68 #pragma warning(disable : 4702)
69 #pragma warning(disable : 4706)
70 #endif /* defined(_MSC_VER) */
73 ** No support for loadable extensions in VxWorks.
75 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
76 # define SQLITE_OMIT_LOAD_EXTENSION 1
80 ** Enable large-file support for fopen() and friends on unix.
82 #ifndef SQLITE_DISABLE_LFS
83 # define _LARGE_FILE 1
84 # ifndef _FILE_OFFSET_BITS
85 # define _FILE_OFFSET_BITS 64
87 # define _LARGEFILE_SOURCE 1
90 #if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
92 ** emcc requires _POSIX_SOURCE (or one of several similar defines)
93 ** to expose strdup().
95 # define _POSIX_SOURCE
103 typedef sqlite3_int64 i64
;
104 typedef sqlite3_uint64 u64
;
105 typedef unsigned char u8
;
106 #if SQLITE_USER_AUTHENTICATION
107 # include "sqlite3userauth.h"
112 #if !defined(_WIN32) && !defined(WIN32)
114 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
118 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
121 # define GETPID getpid
122 # if defined(__MINGW32__)
123 # define DIRENT dirent
125 # define S_ISLNK(mode) (0)
129 # define GETPID (int)GetCurrentProcessId
131 #include <sys/types.h>
132 #include <sys/stat.h>
135 # include <readline/readline.h>
136 # include <readline/history.h>
140 # include <editline/readline.h>
143 #if HAVE_EDITLINE || HAVE_READLINE
145 # define shell_add_history(X) add_history(X)
146 # define shell_read_history(X) read_history(X)
147 # define shell_write_history(X) write_history(X)
148 # define shell_stifle_history(X) stifle_history(X)
149 # define shell_readline(X) readline(X)
153 # include "linenoise.h"
154 # define shell_add_history(X) linenoiseHistoryAdd(X)
155 # define shell_read_history(X) linenoiseHistoryLoad(X)
156 # define shell_write_history(X) linenoiseHistorySave(X)
157 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
158 # define shell_readline(X) linenoise(X)
162 # define shell_read_history(X)
163 # define shell_write_history(X)
164 # define shell_stifle_history(X)
166 # define SHELL_USE_LOCAL_GETLINE 1
170 #if defined(_WIN32) || defined(WIN32)
172 # define SQLITE_OMIT_POPEN 1
176 # define isatty(h) _isatty(h)
178 # define access(f,m) _access((f),(m))
181 # define unlink _unlink
184 # define strdup _strdup
187 # define popen _popen
189 # define pclose _pclose
192 /* Make sure isatty() has a prototype. */
193 extern int isatty(int);
195 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
196 /* popen and pclose are not C89 functions and so are
197 ** sometimes omitted from the <stdio.h> header */
198 extern FILE *popen(const char*,const char*);
199 extern int pclose(FILE*);
201 # define SQLITE_OMIT_POPEN 1
205 #if defined(_WIN32_WCE)
206 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
207 * thus we always assume that we have a console. That can be
208 * overridden with the -batch command line option.
213 /* ctype macros that work with signed characters */
214 #define IsSpace(X) isspace((unsigned char)X)
215 #define IsDigit(X) isdigit((unsigned char)X)
216 #define ToLower(X) (char)tolower((unsigned char)X)
218 #if defined(_WIN32) || defined(WIN32)
224 /* string conversion routines only needed on Win32 */
225 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
226 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
227 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
228 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
231 /* On Windows, we normally run with output mode of TEXT so that \n characters
232 ** are automatically translated into \r\n. However, this behavior needs
233 ** to be disabled in some cases (ex: when generating CSV output and when
234 ** rendering quoted strings that contain \n characters). The following
235 ** routines take care of that.
237 #if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
238 static void setBinaryMode(FILE *file
, int isOutput
){
239 if( isOutput
) fflush(file
);
240 _setmode(_fileno(file
), _O_BINARY
);
242 static void setTextMode(FILE *file
, int isOutput
){
243 if( isOutput
) fflush(file
);
244 _setmode(_fileno(file
), _O_TEXT
);
247 # define setBinaryMode(X,Y)
248 # define setTextMode(X,Y)
251 /* True if the timer is enabled */
252 static int enableTimer
= 0;
254 /* A version of strcmp() that works with NULL values */
255 static int cli_strcmp(const char *a
, const char *b
){
260 static int cli_strncmp(const char *a
, const char *b
, size_t n
){
263 return strncmp(a
,b
,n
);
266 /* Return the current wall-clock time */
267 static sqlite3_int64
timeOfDay(void){
268 static sqlite3_vfs
*clockVfs
= 0;
270 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
271 if( clockVfs
==0 ) return 0; /* Never actually happens */
272 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
273 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
276 clockVfs
->xCurrentTime(clockVfs
, &r
);
277 t
= (sqlite3_int64
)(r
*86400000.0);
282 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
283 #include <sys/time.h>
284 #include <sys/resource.h>
286 /* VxWorks does not support getrusage() as far as we can determine */
287 #if defined(_WRS_KERNEL) || defined(__RTP__)
289 struct timeval ru_utime
; /* user CPU time used */
290 struct timeval ru_stime
; /* system CPU time used */
292 #define getrusage(A,B) memset(B,0,sizeof(*B))
295 /* Saved resource information for the beginning of an operation */
296 static struct rusage sBegin
; /* CPU time at start */
297 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
300 ** Begin timing an operation
302 static void beginTimer(void){
304 getrusage(RUSAGE_SELF
, &sBegin
);
305 iBegin
= timeOfDay();
309 /* Return the difference of two time_structs in seconds */
310 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
311 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
312 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
316 ** Print the timing results.
318 static void endTimer(void){
320 sqlite3_int64 iEnd
= timeOfDay();
322 getrusage(RUSAGE_SELF
, &sEnd
);
323 printf("Run Time: real %.3f user %f sys %f\n",
324 (iEnd
- iBegin
)*0.001,
325 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
326 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
330 #define BEGIN_TIMER beginTimer()
331 #define END_TIMER endTimer()
334 #elif (defined(_WIN32) || defined(WIN32))
336 /* Saved resource information for the beginning of an operation */
337 static HANDLE hProcess
;
338 static FILETIME ftKernelBegin
;
339 static FILETIME ftUserBegin
;
340 static sqlite3_int64 ftWallBegin
;
341 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
342 LPFILETIME
, LPFILETIME
);
343 static GETPROCTIMES getProcessTimesAddr
= NULL
;
346 ** Check to see if we have timer support. Return 1 if necessary
347 ** support found (or found previously).
349 static int hasTimer(void){
350 if( getProcessTimesAddr
){
354 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
355 ** versions. See if the version we are running on has it, and if it
356 ** does, save off a pointer to it and the current process handle.
358 hProcess
= GetCurrentProcess();
360 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
361 if( NULL
!= hinstLib
){
362 getProcessTimesAddr
=
363 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
364 if( NULL
!= getProcessTimesAddr
){
367 FreeLibrary(hinstLib
);
376 ** Begin timing an operation
378 static void beginTimer(void){
379 if( enableTimer
&& getProcessTimesAddr
){
380 FILETIME ftCreation
, ftExit
;
381 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
382 &ftKernelBegin
,&ftUserBegin
);
383 ftWallBegin
= timeOfDay();
387 /* Return the difference of two FILETIME structs in seconds */
388 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
389 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
390 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
391 return (double) ((i64End
- i64Start
) / 10000000.0);
395 ** Print the timing results.
397 static void endTimer(void){
398 if( enableTimer
&& getProcessTimesAddr
){
399 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
400 sqlite3_int64 ftWallEnd
= timeOfDay();
401 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
402 printf("Run Time: real %.3f user %f sys %f\n",
403 (ftWallEnd
- ftWallBegin
)*0.001,
404 timeDiff(&ftUserBegin
, &ftUserEnd
),
405 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
409 #define BEGIN_TIMER beginTimer()
410 #define END_TIMER endTimer()
411 #define HAS_TIMER hasTimer()
420 ** Used to prevent warnings about unused parameters
422 #define UNUSED_PARAMETER(x) (void)(x)
425 ** Number of elements in an array
427 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
430 ** If the following flag is set, then command execution stops
431 ** at an error if we are not interactive.
433 static int bail_on_error
= 0;
436 ** Threat stdin as an interactive input if the following variable
437 ** is true. Otherwise, assume stdin is connected to a file or pipe.
439 static int stdin_is_interactive
= 1;
442 ** On Windows systems we have to know if standard output is a console
443 ** in order to translate UTF-8 into MBCS. The following variable is
444 ** true if translation is required.
446 static int stdout_is_console
= 1;
449 ** The following is the open SQLite database. We make a pointer
450 ** to this database a static variable so that it can be accessed
451 ** by the SIGINT handler to interrupt database processing.
453 static sqlite3
*globalDb
= 0;
456 ** True if an interrupt (Control-C) has been received.
458 static volatile int seenInterrupt
= 0;
461 ** This is the name of our program. It is set in main(), used
462 ** in a number of other places, mostly for error messages.
467 ** Prompt strings. Initialized in main. Settable with
468 ** .prompt main continue
470 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
471 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
474 ** Render output like fprintf(). Except, if the output is going to the
475 ** console and if this is running on a Windows machine, translate the
476 ** output from UTF-8 into MBCS.
478 #if defined(_WIN32) || defined(WIN32)
479 void utf8_printf(FILE *out
, const char *zFormat
, ...){
481 va_start(ap
, zFormat
);
482 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
483 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
484 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
489 vfprintf(out
, zFormat
, ap
);
493 #elif !defined(utf8_printf)
494 # define utf8_printf fprintf
498 ** Render output like fprintf(). This should not be used on anything that
499 ** includes string formatting (e.g. "%s").
501 #if !defined(raw_printf)
502 # define raw_printf fprintf
505 /* Indicate out-of-memory and exit. */
506 static void shell_out_of_memory(void){
507 raw_printf(stderr
,"Error: out of memory\n");
511 /* Check a pointer to see if it is NULL. If it is NULL, exit with an
512 ** out-of-memory error.
514 static void shell_check_oom(void *p
){
515 if( p
==0 ) shell_out_of_memory();
519 ** Write I/O traces to the following stream.
521 #ifdef SQLITE_ENABLE_IOTRACE
522 static FILE *iotrace
= 0;
526 ** This routine works like printf in that its first argument is a
527 ** format string and subsequent arguments are values to be substituted
528 ** in place of % fields. The result of formatting this string
529 ** is written to iotrace.
531 #ifdef SQLITE_ENABLE_IOTRACE
532 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
535 if( iotrace
==0 ) return;
536 va_start(ap
, zFormat
);
537 z
= sqlite3_vmprintf(zFormat
, ap
);
539 utf8_printf(iotrace
, "%s", z
);
545 ** Output string zUtf to stream pOut as w characters. If w is negative,
546 ** then right-justify the text. W is the width in UTF-8 characters, not
547 ** in bytes. This is different from the %*.*s specification in printf
548 ** since with %*.*s the width is measured in bytes, not characters.
550 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
553 int aw
= w
<0 ? -w
: w
;
554 if( zUtf
==0 ) zUtf
= "";
555 for(i
=n
=0; zUtf
[i
]; i
++){
556 if( (zUtf
[i
]&0xc0)!=0x80 ){
559 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
565 utf8_printf(pOut
, "%.*s", i
, zUtf
);
567 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
569 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
575 ** Determines if a string is a number of not.
577 static int isNumber(const char *z
, int *realnum
){
578 if( *z
=='-' || *z
=='+' ) z
++;
583 if( realnum
) *realnum
= 0;
584 while( IsDigit(*z
) ){ z
++; }
587 if( !IsDigit(*z
) ) return 0;
588 while( IsDigit(*z
) ){ z
++; }
589 if( realnum
) *realnum
= 1;
591 if( *z
=='e' || *z
=='E' ){
593 if( *z
=='+' || *z
=='-' ) z
++;
594 if( !IsDigit(*z
) ) return 0;
595 while( IsDigit(*z
) ){ z
++; }
596 if( realnum
) *realnum
= 1;
602 ** Compute a string length that is limited to what can be stored in
603 ** lower 30 bits of a 32-bit signed integer.
605 static int strlen30(const char *z
){
607 while( *z2
){ z2
++; }
608 return 0x3fffffff & (int)(z2
- z
);
612 ** Return the length of a string in characters. Multibyte UTF8 characters
613 ** count as a single character.
615 static int strlenChar(const char *z
){
618 if( (0xc0&*(z
++))!=0x80 ) n
++;
624 ** Return open FILE * if zFile exists, can be opened for read
625 ** and is an ordinary file or a character stream source.
626 ** Otherwise return 0.
628 static FILE * openChrSource(const char *zFile
){
630 struct _stat x
= {0};
631 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
632 /* On Windows, open first, then check the stream nature. This order
633 ** is necessary because _stat() and sibs, when checking a named pipe,
634 ** effectively break the pipe as its supplier sees it. */
635 FILE *rv
= fopen(zFile
, "rb");
636 if( rv
==0 ) return 0;
637 if( _fstat(_fileno(rv
), &x
) != 0
638 || !STAT_CHR_SRC(x
.st_mode
)){
645 int rc
= stat(zFile
, &x
);
646 # define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
647 if( rc
!=0 ) return 0;
648 if( STAT_CHR_SRC(x
.st_mode
) ){
649 return fopen(zFile
, "rb");
658 ** This routine reads a line of text from FILE in, stores
659 ** the text in memory obtained from malloc() and returns a pointer
660 ** to the text. NULL is returned at end of file, or if malloc()
663 ** If zLine is not NULL then it is a malloced buffer returned from
664 ** a previous call to this routine that may be reused.
666 static char *local_getline(char *zLine
, FILE *in
){
667 int nLine
= zLine
==0 ? 0 : 100;
672 nLine
= nLine
*2 + 100;
673 zLine
= realloc(zLine
, nLine
);
674 shell_check_oom(zLine
);
676 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
684 while( zLine
[n
] ) n
++;
685 if( n
>0 && zLine
[n
-1]=='\n' ){
687 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
692 #if defined(_WIN32) || defined(WIN32)
693 /* For interactive input on Windows systems, translate the
694 ** multi-byte characterset characters into UTF-8. */
695 if( stdin_is_interactive
&& in
==stdin
){
696 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
698 i64 nTrans
= strlen(zTrans
)+1;
700 zLine
= realloc(zLine
, nTrans
);
701 shell_check_oom(zLine
);
703 memcpy(zLine
, zTrans
, nTrans
);
704 sqlite3_free(zTrans
);
707 #endif /* defined(_WIN32) || defined(WIN32) */
712 ** Retrieve a single line of input text.
714 ** If in==0 then read from standard input and prompt before each line.
715 ** If isContinuation is true, then a continuation prompt is appropriate.
716 ** If isContinuation is zero, then the main prompt should be used.
718 ** If zPrior is not NULL then it is a buffer from a prior call to this
719 ** routine that can be reused.
721 ** The result is stored in space obtained from malloc() and must either
722 ** be freed by the caller or else passed back into this routine via the
723 ** zPrior argument for reuse.
725 #ifndef SQLITE_SHELL_FIDDLE
726 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
730 zResult
= local_getline(zPrior
, in
);
732 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
733 #if SHELL_USE_LOCAL_GETLINE
734 printf("%s", zPrompt
);
736 zResult
= local_getline(zPrior
, stdin
);
739 zResult
= shell_readline(zPrompt
);
740 if( zResult
&& *zResult
) shell_add_history(zResult
);
745 #endif /* !SQLITE_SHELL_FIDDLE */
748 ** Return the value of a hexadecimal digit. Return -1 if the input
749 ** is not a hex digit.
751 static int hexDigitValue(char c
){
752 if( c
>='0' && c
<='9' ) return c
- '0';
753 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
754 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
759 ** Interpret zArg as an integer value, possibly with suffixes.
761 static sqlite3_int64
integerValue(const char *zArg
){
763 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
765 { "MiB", 1024*1024 },
766 { "GiB", 1024*1024*1024 },
769 { "GB", 1000000000 },
779 }else if( zArg
[0]=='+' ){
782 if( zArg
[0]=='0' && zArg
[1]=='x' ){
785 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
790 while( IsDigit(zArg
[0]) ){
791 v
= v
*10 + zArg
[0] - '0';
795 for(i
=0; i
<ArraySize(aMult
); i
++){
796 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
801 return isNeg
? -v
: v
;
805 ** A variable length string to which one can append text.
807 typedef struct ShellText ShellText
;
815 ** Initialize and destroy a ShellText object
817 static void initText(ShellText
*p
){
818 memset(p
, 0, sizeof(*p
));
820 static void freeText(ShellText
*p
){
825 /* zIn is either a pointer to a NULL-terminated string in memory obtained
826 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
827 ** added to zIn, and the result returned in memory obtained from malloc().
828 ** zIn, if it was not NULL, is freed.
830 ** If the third argument, quote, is not '\0', then it is used as a
831 ** quote character for zAppend.
833 static void appendText(ShellText
*p
, const char *zAppend
, char quote
){
836 i64 nAppend
= strlen30(zAppend
);
838 len
= nAppend
+p
->n
+1;
841 for(i
=0; i
<nAppend
; i
++){
842 if( zAppend
[i
]==quote
) len
++;
846 if( p
->z
==0 || p
->n
+len
>=p
->nAlloc
){
847 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
848 p
->z
= realloc(p
->z
, p
->nAlloc
);
849 shell_check_oom(p
->z
);
853 char *zCsr
= p
->z
+p
->n
;
855 for(i
=0; i
<nAppend
; i
++){
856 *zCsr
++ = zAppend
[i
];
857 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
860 p
->n
= (int)(zCsr
- p
->z
);
863 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
870 ** Attempt to determine if identifier zName needs to be quoted, either
871 ** because it contains non-alphanumeric characters, or because it is an
872 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
873 ** that quoting is required.
875 ** Return '"' if quoting is required. Return 0 if no quoting is required.
877 static char quoteChar(const char *zName
){
879 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
880 for(i
=0; zName
[i
]; i
++){
881 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
883 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
887 ** Construct a fake object name and column list to describe the structure
888 ** of the view, virtual table, or table valued function zSchema.zName.
890 static char *shellFakeSchema(
891 sqlite3
*db
, /* The database connection containing the vtab */
892 const char *zSchema
, /* Schema of the database holding the vtab */
893 const char *zName
/* The name of the virtual table */
895 sqlite3_stmt
*pStmt
= 0;
902 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
903 zSchema
? zSchema
: "main", zName
);
904 shell_check_oom(zSql
);
905 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
909 cQuote
= quoteChar(zSchema
);
910 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
911 appendText(&s
, zSchema
, cQuote
);
912 appendText(&s
, ".", 0);
914 cQuote
= quoteChar(zName
);
915 appendText(&s
, zName
, cQuote
);
916 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
917 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
919 appendText(&s
, zDiv
, 0);
921 if( zCol
==0 ) zCol
= "";
922 cQuote
= quoteChar(zCol
);
923 appendText(&s
, zCol
, cQuote
);
925 appendText(&s
, ")", 0);
926 sqlite3_finalize(pStmt
);
935 ** SQL function: shell_module_schema(X)
937 ** Return a fake schema for the table-valued function or eponymous virtual
940 static void shellModuleSchema(
941 sqlite3_context
*pCtx
,
943 sqlite3_value
**apVal
947 UNUSED_PARAMETER(nVal
);
948 zName
= (const char*)sqlite3_value_text(apVal
[0]);
949 zFake
= zName
? shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
) : 0;
951 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
958 ** SQL function: shell_add_schema(S,X)
960 ** Add the schema name X to the CREATE statement in S and return the result.
963 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
968 ** CREATE UNIQUE INDEX
971 ** CREATE VIRTUAL TABLE
973 ** This UDF is used by the .schema command to insert the schema name of
974 ** attached databases into the middle of the sqlite_schema.sql field.
976 static void shellAddSchemaName(
977 sqlite3_context
*pCtx
,
979 sqlite3_value
**apVal
981 static const char *aPrefix
[] = {
990 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
991 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
992 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
993 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
994 UNUSED_PARAMETER(nVal
);
995 if( zIn
!=0 && cli_strncmp(zIn
, "CREATE ", 7)==0 ){
996 for(i
=0; i
<ArraySize(aPrefix
); i
++){
997 int n
= strlen30(aPrefix
[i
]);
998 if( cli_strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
1002 char cQuote
= quoteChar(zSchema
);
1003 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
1004 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1006 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
1010 && aPrefix
[i
][0]=='V'
1011 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
1014 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
1016 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
1021 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
1027 sqlite3_result_value(pCtx
, apVal
[0]);
1031 ** The source code for several run-time loadable extensions is inserted
1032 ** below by the ../tool/mkshellc.tcl script. Before processing that included
1033 ** code, we need to override some macros to make the included program code
1034 ** work here in the middle of this regular program.
1036 #define SQLITE_EXTENSION_INIT1
1037 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
1039 #if defined(_WIN32) && defined(_MSC_VER)
1040 INCLUDE test_windirent
.h
1041 INCLUDE test_windirent
.c
1042 #define dirent DIRENT
1044 INCLUDE
../ext
/misc
/memtrace
.c
1045 INCLUDE
../ext
/misc
/shathree
.c
1046 INCLUDE
../ext
/misc
/uint
.c
1047 INCLUDE
../ext
/misc
/decimal
.c
1048 INCLUDE
../ext
/misc
/ieee754
.c
1049 INCLUDE
../ext
/misc
/series
.c
1050 INCLUDE
../ext
/misc
/regexp
.c
1051 #ifndef SQLITE_SHELL_FIDDLE
1052 INCLUDE
../ext
/misc
/fileio
.c
1053 INCLUDE
../ext
/misc
/completion
.c
1054 INCLUDE
../ext
/misc
/appendvfs
.c
1056 #ifdef SQLITE_HAVE_ZLIB
1057 INCLUDE
../ext
/misc
/zipfile
.c
1058 INCLUDE
../ext
/misc
/sqlar
.c
1060 INCLUDE
../ext
/expert
/sqlite3expert
.h
1061 INCLUDE
../ext
/expert
/sqlite3expert
.c
1063 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1064 #define SQLITE_SHELL_HAVE_RECOVER 1
1066 #define SQLITE_SHELL_HAVE_RECOVER 0
1068 #if SQLITE_SHELL_HAVE_RECOVER
1069 INCLUDE
../ext
/recover
/dbdata
.c
1070 INCLUDE
../ext
/recover
/sqlite3recover
.h
1071 INCLUDE
../ext
/recover
/sqlite3recover
.c
1074 #if defined(SQLITE_ENABLE_SESSION)
1076 ** State information for a single open session
1078 typedef struct OpenSession OpenSession
;
1079 struct OpenSession
{
1080 char *zName
; /* Symbolic name for this session */
1081 int nFilter
; /* Number of xFilter rejection GLOB patterns */
1082 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
1083 sqlite3_session
*p
; /* The open session */
1087 typedef struct ExpertInfo ExpertInfo
;
1089 sqlite3expert
*pExpert
;
1093 /* A single line in the EQP output */
1094 typedef struct EQPGraphRow EQPGraphRow
;
1095 struct EQPGraphRow
{
1096 int iEqpId
; /* ID for this row */
1097 int iParentId
; /* ID of the parent row */
1098 EQPGraphRow
*pNext
; /* Next row in sequence */
1099 char zText
[1]; /* Text to display for this row */
1102 /* All EQP output is collected into an instance of the following */
1103 typedef struct EQPGraph EQPGraph
;
1105 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
1106 EQPGraphRow
*pLast
; /* Last element of the pRow list */
1107 char zPrefix
[100]; /* Graph prefix */
1110 /* Parameters affecting columnar mode result display (defaulting together) */
1111 typedef struct ColModeOpts
{
1112 int iWrap
; /* In columnar modes, wrap lines reaching this limit */
1113 u8 bQuote
; /* Quote results for .mode box and table */
1114 u8 bWordWrap
; /* In columnar modes, wrap at word boundaries */
1116 #define ColModeOpts_default { 60, 0, 0 }
1117 #define ColModeOpts_default_qbox { 60, 1, 0 }
1120 ** State information about the database connection is contained in an
1121 ** instance of the following structure.
1123 typedef struct ShellState ShellState
;
1125 sqlite3
*db
; /* The database */
1126 u8 autoExplain
; /* Automatically turn on .explain mode */
1127 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1128 u8 autoEQPtest
; /* autoEQP is in test mode */
1129 u8 autoEQPtrace
; /* autoEQP is in trace mode */
1130 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1131 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1132 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1133 u8 nEqpLevel
; /* Depth of the EQP output graph */
1134 u8 eTraceType
; /* SHELL_TRACE_* value for type of trace */
1135 u8 bSafeMode
; /* True to prohibit unsafe operations */
1136 u8 bSafeModePersist
; /* The long-term value of bSafeMode */
1137 ColModeOpts cmOpts
; /* Option values affecting columnar mode output */
1138 unsigned statsOn
; /* True to display memory stats before each finalize */
1139 unsigned mEqpLines
; /* Mask of veritical lines in the EQP output graph */
1140 int inputNesting
; /* Track nesting level of .read and other redirects */
1141 int outCount
; /* Revert to stdout when reaching zero */
1142 int cnt
; /* Number of records displayed so far */
1143 int lineno
; /* Line number of last line read from in */
1144 int openFlags
; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */
1145 FILE *in
; /* Read commands from this stream */
1146 FILE *out
; /* Write results here */
1147 FILE *traceOut
; /* Output for sqlite3_trace() */
1148 int nErr
; /* Number of errors seen */
1149 int mode
; /* An output mode setting */
1150 int modePrior
; /* Saved mode */
1151 int cMode
; /* temporary output mode for the current query */
1152 int normalMode
; /* Output mode before ".explain on" */
1153 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1154 int showHeader
; /* True to show column names in List or Column mode */
1155 int nCheck
; /* Number of ".check" commands run */
1156 unsigned nProgress
; /* Number of progress callbacks encountered */
1157 unsigned mxProgress
; /* Maximum progress callbacks before failing */
1158 unsigned flgProgress
; /* Flags for the progress callback */
1159 unsigned shellFlgs
; /* Various flags */
1160 unsigned priorShFlgs
; /* Saved copy of flags */
1161 sqlite3_int64 szMax
; /* --maxsize argument to .open */
1162 char *zDestTable
; /* Name of destination table when MODE_Insert */
1163 char *zTempFile
; /* Temporary file that might need deleting */
1164 char zTestcase
[30]; /* Name of current test case */
1165 char colSeparator
[20]; /* Column separator character for several modes */
1166 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1167 char colSepPrior
[20]; /* Saved column separator */
1168 char rowSepPrior
[20]; /* Saved row separator */
1169 int *colWidth
; /* Requested width of each column in columnar modes */
1170 int *actualWidth
; /* Actual width of each column */
1171 int nWidth
; /* Number of slots in colWidth[] and actualWidth[] */
1172 char nullValue
[20]; /* The text to print when a NULL comes back from
1174 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1175 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1176 FILE *pLog
; /* Write log output here */
1177 struct AuxDb
{ /* Storage space for auxiliary database connections */
1178 sqlite3
*db
; /* Connection pointer */
1179 const char *zDbFilename
; /* Filename used to open the connection */
1180 char *zFreeOnClose
; /* Free this memory allocation on close */
1181 #if defined(SQLITE_ENABLE_SESSION)
1182 int nSession
; /* Number of active sessions */
1183 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1185 } aAuxDb
[5], /* Array of all database connections */
1186 *pAuxDb
; /* Currently active database connection */
1187 int *aiIndent
; /* Array of indents used in MODE_Explain */
1188 int nIndent
; /* Size of array aiIndent[] */
1189 int iIndent
; /* Index of current op in aiIndent[] */
1190 char *zNonce
; /* Nonce for temporary safe-mode excapes */
1191 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1192 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1193 #ifdef SQLITE_SHELL_FIDDLE
1195 const char * zInput
; /* Input string from wasm/JS proxy */
1196 const char * zPos
; /* Cursor pos into zInput */
1197 const char * zDefaultDbName
; /* Default name for db file */
1202 #ifdef SQLITE_SHELL_FIDDLE
1203 static ShellState shellState
;
1207 /* Allowed values for ShellState.autoEQP
1209 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1210 #define AUTOEQP_on 1 /* Automatic EQP is on */
1211 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1212 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1214 /* Allowed values for ShellState.openMode
1216 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1217 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1218 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1219 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1220 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1221 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1222 #define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
1224 /* Allowed values for ShellState.eTraceType
1226 #define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1227 #define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1228 #define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1230 /* Bits in the ShellState.flgProgress variable */
1231 #define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1232 #define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1233 ** callback limit is reached, and for each
1234 ** top-level SQL statement */
1235 #define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
1238 ** These are the allowed shellFlgs values
1240 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1241 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1242 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1243 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1244 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1245 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1246 #define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */
1247 #define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */
1248 #define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */
1249 #define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */
1252 ** Macros for testing and setting shellFlgs
1254 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1255 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1256 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1259 ** These are the allowed modes.
1261 #define MODE_Line 0 /* One column per line. Blank line between records */
1262 #define MODE_Column 1 /* One record per line in neat columns */
1263 #define MODE_List 2 /* One record per line with a separator */
1264 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1265 #define MODE_Html 4 /* Generate an XHTML table */
1266 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1267 #define MODE_Quote 6 /* Quote values as for SQL */
1268 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1269 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1270 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1271 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1272 #define MODE_Pretty 11 /* Pretty-print schemas */
1273 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1274 #define MODE_Json 13 /* Output JSON */
1275 #define MODE_Markdown 14 /* Markdown formatting */
1276 #define MODE_Table 15 /* MySQL-style table formatting */
1277 #define MODE_Box 16 /* Unicode box-drawing characters */
1278 #define MODE_Count 17 /* Output only a count of the rows of output */
1279 #define MODE_Off 18 /* No query output shown */
1281 static const char *modeDescr
[] = {
1304 ** These are the column/row/line separators used by the various
1305 ** import/export modes.
1307 #define SEP_Column "|"
1308 #define SEP_Row "\n"
1309 #define SEP_Tab "\t"
1310 #define SEP_Space " "
1311 #define SEP_Comma ","
1312 #define SEP_CrLf "\r\n"
1313 #define SEP_Unit "\x1F"
1314 #define SEP_Record "\x1E"
1317 ** Limit input nesting via .read or any other input redirect.
1318 ** It's not too expensive, so a generous allowance can be made.
1320 #define MAX_INPUT_NESTING 25
1323 ** A callback for the sqlite3_log() interface.
1325 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1326 ShellState
*p
= (ShellState
*)pArg
;
1327 if( p
->pLog
==0 ) return;
1328 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1333 ** SQL function: shell_putsnl(X)
1335 ** Write the text X to the screen (or whatever output is being directed)
1336 ** adding a newline at the end, and then return X.
1338 static void shellPutsFunc(
1339 sqlite3_context
*pCtx
,
1341 sqlite3_value
**apVal
1343 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1345 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1346 sqlite3_result_value(pCtx
, apVal
[0]);
1350 ** If in safe mode, print an error message described by the arguments
1351 ** and exit immediately.
1353 static void failIfSafeMode(
1355 const char *zErrMsg
,
1361 va_start(ap
, zErrMsg
);
1362 zMsg
= sqlite3_vmprintf(zErrMsg
, ap
);
1364 raw_printf(stderr
, "line %d: ", p
->lineno
);
1365 utf8_printf(stderr
, "%s\n", zMsg
);
1371 ** SQL function: edit(VALUE)
1372 ** edit(VALUE,EDITOR)
1376 ** (1) Write VALUE into a temporary file.
1377 ** (2) Run program EDITOR on that temporary file.
1378 ** (3) Read the temporary file back and return its content as the result.
1379 ** (4) Delete the temporary file
1381 ** If the EDITOR argument is omitted, use the value in the VISUAL
1382 ** environment variable. If still there is no EDITOR, through an error.
1384 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1386 #ifndef SQLITE_NOHAVE_SYSTEM
1387 static void editFunc(
1388 sqlite3_context
*context
,
1390 sqlite3_value
**argv
1392 const char *zEditor
;
1393 char *zTempFile
= 0;
1402 unsigned char *p
= 0;
1405 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1407 zEditor
= getenv("VISUAL");
1410 sqlite3_result_error(context
, "no editor for edit()", -1);
1413 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1414 sqlite3_result_error(context
, "NULL input to edit()", -1);
1417 db
= sqlite3_context_db_handle(context
);
1419 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1421 sqlite3_uint64 r
= 0;
1422 sqlite3_randomness(sizeof(r
), &r
);
1423 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1425 sqlite3_result_error_nomem(context
);
1429 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1430 /* When writing the file to be edited, do \n to \r\n conversions on systems
1431 ** that want \r\n line endings */
1432 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1434 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1437 sz
= sqlite3_value_bytes(argv
[0]);
1439 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, (size_t)sz
, f
);
1441 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
1442 /* Remember whether or not the value originally contained \r\n */
1443 if( z
&& strstr(z
,"\r\n")!=0 ) hasCRNL
= 1;
1444 x
= fwrite(sqlite3_value_text(argv
[0]), 1, (size_t)sz
, f
);
1449 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1452 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1454 sqlite3_result_error_nomem(context
);
1460 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1463 f
= fopen(zTempFile
, "rb");
1465 sqlite3_result_error(context
,
1466 "edit() cannot reopen temp file after edit", -1);
1469 fseek(f
, 0, SEEK_END
);
1472 p
= sqlite3_malloc64( sz
+1 );
1474 sqlite3_result_error_nomem(context
);
1477 x
= fread(p
, 1, (size_t)sz
, f
);
1481 sqlite3_result_error(context
, "could not read back the whole file", -1);
1485 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1489 /* If the original contains \r\n then do no conversions back to \n */
1491 /* If the file did not originally contain \r\n then convert any new
1492 ** \r\n back into \n */
1493 for(i
=j
=0; i
<sz
; i
++){
1494 if( p
[i
]=='\r' && p
[i
+1]=='\n' ) i
++;
1500 sqlite3_result_text64(context
, (const char*)p
, sz
,
1501 sqlite3_free
, SQLITE_UTF8
);
1508 sqlite3_free(zTempFile
);
1511 #endif /* SQLITE_NOHAVE_SYSTEM */
1514 ** Save or restore the current output mode
1516 static void outputModePush(ShellState
*p
){
1517 p
->modePrior
= p
->mode
;
1518 p
->priorShFlgs
= p
->shellFlgs
;
1519 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1520 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1522 static void outputModePop(ShellState
*p
){
1523 p
->mode
= p
->modePrior
;
1524 p
->shellFlgs
= p
->priorShFlgs
;
1525 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1526 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1530 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1532 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1534 unsigned char *aBlob
= (unsigned char*)pBlob
;
1536 char *zStr
= sqlite3_malloc(nBlob
*2 + 1);
1537 shell_check_oom(zStr
);
1539 for(i
=0; i
<nBlob
; i
++){
1540 static const char aHex
[] = {
1541 '0', '1', '2', '3', '4', '5', '6', '7',
1542 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1544 zStr
[i
*2] = aHex
[ (aBlob
[i
] >> 4) ];
1545 zStr
[i
*2+1] = aHex
[ (aBlob
[i
] & 0x0F) ];
1549 raw_printf(out
,"X'%s'", zStr
);
1554 ** Find a string that is not found anywhere in z[]. Return a pointer
1557 ** Try to use zA and zB first. If both of those are already found in z[]
1558 ** then make up some string and store it in the buffer zBuf.
1560 static const char *unused_string(
1561 const char *z
, /* Result must not appear anywhere in z */
1562 const char *zA
, const char *zB
, /* Try these first */
1563 char *zBuf
/* Space to store a generated string */
1566 if( strstr(z
, zA
)==0 ) return zA
;
1567 if( strstr(z
, zB
)==0 ) return zB
;
1569 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1570 }while( strstr(z
,zBuf
)!=0 );
1575 ** Output the given string as a quoted string using SQL quoting conventions.
1577 ** See also: output_quoted_escaped_string()
1579 static void output_quoted_string(FILE *out
, const char *z
){
1582 setBinaryMode(out
, 1);
1583 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1585 utf8_printf(out
,"'%s'",z
);
1587 raw_printf(out
, "'");
1589 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1592 utf8_printf(out
, "%.*s", i
, z
);
1596 raw_printf(out
, "'");
1604 raw_printf(out
, "'");
1606 setTextMode(out
, 1);
1610 ** Output the given string as a quoted string using SQL quoting conventions.
1611 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1612 ** get corrupted by end-of-line translation facilities in some operating
1615 ** This is like output_quoted_string() but with the addition of the \r\n
1616 ** escape mechanism.
1618 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1621 setBinaryMode(out
, 1);
1622 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1624 utf8_printf(out
,"'%s'",z
);
1626 const char *zNL
= 0;
1627 const char *zCR
= 0;
1630 char zBuf1
[20], zBuf2
[20];
1631 for(i
=0; z
[i
]; i
++){
1632 if( z
[i
]=='\n' ) nNL
++;
1633 if( z
[i
]=='\r' ) nCR
++;
1636 raw_printf(out
, "replace(");
1637 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1640 raw_printf(out
, "replace(");
1641 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1643 raw_printf(out
, "'");
1645 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1648 utf8_printf(out
, "%.*s", i
, z
);
1652 raw_printf(out
, "'");
1660 raw_printf(out
, "%s", zNL
);
1663 raw_printf(out
, "%s", zCR
);
1665 raw_printf(out
, "'");
1667 raw_printf(out
, ",'%s',char(13))", zCR
);
1670 raw_printf(out
, ",'%s',char(10))", zNL
);
1673 setTextMode(out
, 1);
1677 ** Output the given string as a quoted according to C or TCL quoting rules.
1679 static void output_c_string(FILE *out
, const char *z
){
1682 while( (c
= *(z
++))!=0 ){
1689 }else if( c
=='\t' ){
1692 }else if( c
=='\n' ){
1695 }else if( c
=='\r' ){
1698 }else if( !isprint(c
&0xff) ){
1699 raw_printf(out
, "\\%03o", c
&0xff);
1708 ** Output the given string as a quoted according to JSON quoting rules.
1710 static void output_json_string(FILE *out
, const char *z
, i64 n
){
1712 if( n
<0 ) n
= strlen(z
);
1716 if( c
=='\\' || c
=='"' ){
1719 }else if( c
<=0x1f ){
1723 }else if( c
=='\f' ){
1725 }else if( c
=='\n' ){
1727 }else if( c
=='\r' ){
1729 }else if( c
=='\t' ){
1732 raw_printf(out
, "u%04x",c
);
1742 ** Output the given string with characters that are special to
1745 static void output_html_string(FILE *out
, const char *z
){
1757 utf8_printf(out
,"%.*s",i
,z
);
1760 raw_printf(out
,"<");
1761 }else if( z
[i
]=='&' ){
1762 raw_printf(out
,"&");
1763 }else if( z
[i
]=='>' ){
1764 raw_printf(out
,">");
1765 }else if( z
[i
]=='\"' ){
1766 raw_printf(out
,""");
1767 }else if( z
[i
]=='\'' ){
1768 raw_printf(out
,"'");
1777 ** If a field contains any character identified by a 1 in the following
1778 ** array, then the string must be quoted for CSV.
1780 static const char needCsvQuote
[] = {
1781 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1782 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1783 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1784 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1785 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1786 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1787 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1788 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1789 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1790 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1791 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1792 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1793 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1794 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1795 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1796 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1800 ** Output a single term of CSV. Actually, p->colSeparator is used for
1801 ** the separator, which may or may not be a comma. p->nullValue is
1802 ** the null value. Strings are quoted if necessary. The separator
1803 ** is only issued if bSep is true.
1805 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1808 utf8_printf(out
,"%s",p
->nullValue
);
1811 for(i
=0; z
[i
]; i
++){
1812 if( needCsvQuote
[((unsigned char*)z
)[i
]] ){
1817 if( i
==0 || strstr(z
, p
->colSeparator
)!=0 ){
1818 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1819 shell_check_oom(zQuoted
);
1820 utf8_printf(out
, "%s", zQuoted
);
1821 sqlite3_free(zQuoted
);
1823 utf8_printf(out
, "%s", z
);
1827 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1832 ** This routine runs when the user presses Ctrl-C
1834 static void interrupt_handler(int NotUsed
){
1835 UNUSED_PARAMETER(NotUsed
);
1837 if( seenInterrupt
>2 ) exit(1);
1838 if( globalDb
) sqlite3_interrupt(globalDb
);
1841 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1843 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1845 static BOOL WINAPI
ConsoleCtrlHandler(
1846 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1848 if( dwCtrlType
==CTRL_C_EVENT
){
1849 interrupt_handler(0);
1856 #ifndef SQLITE_OMIT_AUTHORIZATION
1858 ** This authorizer runs in safe mode.
1860 static int safeModeAuth(
1868 ShellState
*p
= (ShellState
*)pClientData
;
1869 static const char *azProhibitedFunctions
[] = {
1878 UNUSED_PARAMETER(zA1
);
1879 UNUSED_PARAMETER(zA3
);
1880 UNUSED_PARAMETER(zA4
);
1882 case SQLITE_ATTACH
: {
1883 #ifndef SQLITE_SHELL_FIDDLE
1884 /* In WASM builds the filesystem is a virtual sandbox, so
1885 ** there's no harm in using ATTACH. */
1886 failIfSafeMode(p
, "cannot run ATTACH in safe mode");
1890 case SQLITE_FUNCTION
: {
1892 for(i
=0; i
<ArraySize(azProhibitedFunctions
); i
++){
1893 if( sqlite3_stricmp(zA2
, azProhibitedFunctions
[i
])==0 ){
1894 failIfSafeMode(p
, "cannot use the %s() function in safe mode",
1895 azProhibitedFunctions
[i
]);
1905 ** When the ".auth ON" is set, the following authorizer callback is
1906 ** invoked. It always returns SQLITE_OK.
1908 static int shellAuth(
1916 ShellState
*p
= (ShellState
*)pClientData
;
1917 static const char *azAction
[] = { 0,
1918 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1919 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1920 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1921 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1922 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1923 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1924 "PRAGMA", "READ", "SELECT",
1925 "TRANSACTION", "UPDATE", "ATTACH",
1926 "DETACH", "ALTER_TABLE", "REINDEX",
1927 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1928 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1936 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1938 raw_printf(p
->out
, " ");
1940 output_c_string(p
->out
, az
[i
]);
1942 raw_printf(p
->out
, "NULL");
1945 raw_printf(p
->out
, "\n");
1946 if( p
->bSafeMode
) (void)safeModeAuth(pClientData
, op
, zA1
, zA2
, zA3
, zA4
);
1952 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1954 ** This routine converts some CREATE TABLE statements for shadow tables
1955 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1957 ** If the schema statement in z[] contains a start-of-comment and if
1958 ** sqlite3_complete() returns false, try to terminate the comment before
1959 ** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c
1961 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1964 if( zTail
==0 ) return;
1965 if( zTail
[0]==';' && (strstr(z
, "/*")!=0 || strstr(z
,"--")!=0) ){
1966 const char *zOrig
= z
;
1967 static const char *azTerm
[] = { "", "*/", "\n" };
1969 for(i
=0; i
<ArraySize(azTerm
); i
++){
1970 char *zNew
= sqlite3_mprintf("%s%s;", zOrig
, azTerm
[i
]);
1971 if( sqlite3_complete(zNew
) ){
1972 size_t n
= strlen(zNew
);
1981 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1982 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1984 utf8_printf(out
, "%s%s", z
, zTail
);
1986 sqlite3_free(zToFree
);
1988 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1991 printSchemaLine(out
, z
, zTail
);
1996 ** Return true if string z[] has nothing but whitespace and comments to the
1997 ** end of the first line.
1999 static int wsToEol(const char *z
){
2001 for(i
=0; z
[i
]; i
++){
2002 if( z
[i
]=='\n' ) return 1;
2003 if( IsSpace(z
[i
]) ) continue;
2004 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
2011 ** Add a new entry to the EXPLAIN QUERY PLAN data
2013 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
2016 if( zText
==0 ) return;
2017 nText
= strlen(zText
);
2018 if( p
->autoEQPtest
){
2019 utf8_printf(p
->out
, "%d,%d,%s\n", iEqpId
, p2
, zText
);
2021 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
2022 shell_check_oom(pNew
);
2023 pNew
->iEqpId
= iEqpId
;
2024 pNew
->iParentId
= p2
;
2025 memcpy(pNew
->zText
, zText
, nText
+1);
2027 if( p
->sGraph
.pLast
){
2028 p
->sGraph
.pLast
->pNext
= pNew
;
2030 p
->sGraph
.pRow
= pNew
;
2032 p
->sGraph
.pLast
= pNew
;
2036 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2039 static void eqp_reset(ShellState
*p
){
2040 EQPGraphRow
*pRow
, *pNext
;
2041 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
2042 pNext
= pRow
->pNext
;
2045 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
2048 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2049 ** pOld, or return the first such line if pOld is NULL
2051 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
2052 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
2053 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
2057 /* Render a single level of the graph that has iEqpId as its parent. Called
2058 ** recursively to render sublevels.
2060 static void eqp_render_level(ShellState
*p
, int iEqpId
){
2061 EQPGraphRow
*pRow
, *pNext
;
2062 i64 n
= strlen(p
->sGraph
.zPrefix
);
2064 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
2065 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
2067 utf8_printf(p
->out
, "%s%s%s\n", p
->sGraph
.zPrefix
,
2068 pNext
? "|--" : "`--", z
);
2069 if( n
<(i64
)sizeof(p
->sGraph
.zPrefix
)-7 ){
2070 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
2071 eqp_render_level(p
, pRow
->iEqpId
);
2072 p
->sGraph
.zPrefix
[n
] = 0;
2078 ** Display and reset the EXPLAIN QUERY PLAN data
2080 static void eqp_render(ShellState
*p
){
2081 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
2083 if( pRow
->zText
[0]=='-' ){
2084 if( pRow
->pNext
==0 ){
2088 utf8_printf(p
->out
, "%s\n", pRow
->zText
+3);
2089 p
->sGraph
.pRow
= pRow
->pNext
;
2092 utf8_printf(p
->out
, "QUERY PLAN\n");
2094 p
->sGraph
.zPrefix
[0] = 0;
2095 eqp_render_level(p
, 0);
2100 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2102 ** Progress handler callback.
2104 static int progress_handler(void *pClientData
) {
2105 ShellState
*p
= (ShellState
*)pClientData
;
2107 if( p
->nProgress
>=p
->mxProgress
&& p
->mxProgress
>0 ){
2108 raw_printf(p
->out
, "Progress limit reached (%u)\n", p
->nProgress
);
2109 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
2110 if( p
->flgProgress
& SHELL_PROGRESS_ONCE
) p
->mxProgress
= 0;
2113 if( (p
->flgProgress
& SHELL_PROGRESS_QUIET
)==0 ){
2114 raw_printf(p
->out
, "Progress %u\n", p
->nProgress
);
2118 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2123 static void print_dashes(FILE *out
, int N
){
2124 const char zDash
[] = "--------------------------------------------------";
2125 const int nDash
= sizeof(zDash
) - 1;
2130 raw_printf(out
, "%.*s", N
, zDash
);
2134 ** Print a markdown or table-style row separator using ascii-art
2136 static void print_row_separator(
2143 fputs(zSep
, p
->out
);
2144 print_dashes(p
->out
, p
->actualWidth
[0]+2);
2145 for(i
=1; i
<nArg
; i
++){
2146 fputs(zSep
, p
->out
);
2147 print_dashes(p
->out
, p
->actualWidth
[i
]+2);
2149 fputs(zSep
, p
->out
);
2151 fputs("\n", p
->out
);
2155 ** This is the callback routine that the shell
2156 ** invokes for each row of a query result.
2158 static int shell_callback(
2160 int nArg
, /* Number of result columns */
2161 char **azArg
, /* Text of each result column */
2162 char **azCol
, /* Column names */
2163 int *aiType
/* Column types. Might be NULL */
2166 ShellState
*p
= (ShellState
*)pArg
;
2168 if( azArg
==0 ) return 0;
2176 if( azArg
==0 ) break;
2177 for(i
=0; i
<nArg
; i
++){
2178 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
2179 if( len
>w
) w
= len
;
2181 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2182 for(i
=0; i
<nArg
; i
++){
2183 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
2184 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
2188 case MODE_Explain
: {
2189 static const int aExplainWidth
[] = {4, 13, 4, 4, 4, 13, 2, 13};
2190 if( nArg
>ArraySize(aExplainWidth
) ){
2191 nArg
= ArraySize(aExplainWidth
);
2194 for(i
=0; i
<nArg
; i
++){
2195 int w
= aExplainWidth
[i
];
2196 utf8_width_print(p
->out
, w
, azCol
[i
]);
2197 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2199 for(i
=0; i
<nArg
; i
++){
2200 int w
= aExplainWidth
[i
];
2201 print_dashes(p
->out
, w
);
2202 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2205 if( azArg
==0 ) break;
2206 for(i
=0; i
<nArg
; i
++){
2207 int w
= aExplainWidth
[i
];
2208 if( i
==nArg
-1 ) w
= 0;
2209 if( azArg
[i
] && strlenChar(azArg
[i
])>w
){
2210 w
= strlenChar(azArg
[i
]);
2212 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
2213 if( p
->iIndent
<p
->nIndent
){
2214 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
2218 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2219 fputs(i
==nArg
-1 ? "\n" : " ", p
->out
);
2223 case MODE_Semi
: { /* .schema and .fullschema output */
2224 printSchemaLine(p
->out
, azArg
[0], ";\n");
2227 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
2235 if( azArg
[0]==0 ) break;
2236 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
2237 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
2239 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
2242 z
= sqlite3_mprintf("%s", azArg
[0]);
2245 for(i
=0; IsSpace(z
[i
]); i
++){}
2246 for(; (c
= z
[i
])!=0; i
++){
2248 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
2249 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
2250 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
2255 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
2257 if( strlen30(z
)>=79 ){
2258 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy from z[i] back to z[j] */
2261 }else if( c
=='"' || c
=='\'' || c
=='`' ){
2265 }else if( c
=='-' && z
[i
+1]=='-' ){
2271 if( nLine
>0 && nParen
==0 && j
>0 ){
2272 printSchemaLineN(p
->out
, z
, j
, "\n");
2277 if( nParen
==1 && cEnd
==0
2278 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
2281 printSchemaLineN(p
->out
, z
, j
, "\n ");
2284 while( IsSpace(z
[i
+1]) ){ i
++; }
2289 printSchemaLine(p
->out
, z
, ";\n");
2294 if( p
->cnt
++==0 && p
->showHeader
){
2295 for(i
=0; i
<nArg
; i
++){
2296 utf8_printf(p
->out
,"%s%s",azCol
[i
],
2297 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
2300 if( azArg
==0 ) break;
2301 for(i
=0; i
<nArg
; i
++){
2303 if( z
==0 ) z
= p
->nullValue
;
2304 utf8_printf(p
->out
, "%s", z
);
2306 utf8_printf(p
->out
, "%s", p
->colSeparator
);
2308 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2314 if( p
->cnt
++==0 && p
->showHeader
){
2315 raw_printf(p
->out
,"<TR>");
2316 for(i
=0; i
<nArg
; i
++){
2317 raw_printf(p
->out
,"<TH>");
2318 output_html_string(p
->out
, azCol
[i
]);
2319 raw_printf(p
->out
,"</TH>\n");
2321 raw_printf(p
->out
,"</TR>\n");
2323 if( azArg
==0 ) break;
2324 raw_printf(p
->out
,"<TR>");
2325 for(i
=0; i
<nArg
; i
++){
2326 raw_printf(p
->out
,"<TD>");
2327 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2328 raw_printf(p
->out
,"</TD>\n");
2330 raw_printf(p
->out
,"</TR>\n");
2334 if( p
->cnt
++==0 && p
->showHeader
){
2335 for(i
=0; i
<nArg
; i
++){
2336 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
2337 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2339 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2341 if( azArg
==0 ) break;
2342 for(i
=0; i
<nArg
; i
++){
2343 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2344 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2346 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2350 setBinaryMode(p
->out
, 1);
2351 if( p
->cnt
++==0 && p
->showHeader
){
2352 for(i
=0; i
<nArg
; i
++){
2353 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
2355 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2358 for(i
=0; i
<nArg
; i
++){
2359 output_csv(p
, azArg
[i
], i
<nArg
-1);
2361 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2363 setTextMode(p
->out
, 1);
2367 if( azArg
==0 ) break;
2368 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
2369 if( p
->showHeader
){
2370 raw_printf(p
->out
,"(");
2371 for(i
=0; i
<nArg
; i
++){
2372 if( i
>0 ) raw_printf(p
->out
, ",");
2373 if( quoteChar(azCol
[i
]) ){
2374 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2376 utf8_printf(p
->out
, "%s", z
);
2379 raw_printf(p
->out
, "%s", azCol
[i
]);
2382 raw_printf(p
->out
,")");
2385 for(i
=0; i
<nArg
; i
++){
2386 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
2387 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2388 utf8_printf(p
->out
,"NULL");
2389 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2390 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2391 output_quoted_string(p
->out
, azArg
[i
]);
2393 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2395 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2396 utf8_printf(p
->out
,"%s", azArg
[i
]);
2397 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2399 double r
= sqlite3_column_double(p
->pStmt
, i
);
2401 memcpy(&ur
,&r
,sizeof(r
));
2402 if( ur
==0x7ff0000000000000LL
){
2403 raw_printf(p
->out
, "1e999");
2404 }else if( ur
==0xfff0000000000000LL
){
2405 raw_printf(p
->out
, "-1e999");
2407 sqlite3_int64 ir
= (sqlite3_int64
)r
;
2408 if( r
==(double)ir
){
2409 sqlite3_snprintf(50,z
,"%lld.0", ir
);
2411 sqlite3_snprintf(50,z
,"%!.20g", r
);
2413 raw_printf(p
->out
, "%s", z
);
2415 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2416 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2417 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2418 output_hex_blob(p
->out
, pBlob
, nBlob
);
2419 }else if( isNumber(azArg
[i
], 0) ){
2420 utf8_printf(p
->out
,"%s", azArg
[i
]);
2421 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2422 output_quoted_string(p
->out
, azArg
[i
]);
2424 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2427 raw_printf(p
->out
,");\n");
2431 if( azArg
==0 ) break;
2433 fputs("[{", p
->out
);
2435 fputs(",\n{", p
->out
);
2438 for(i
=0; i
<nArg
; i
++){
2439 output_json_string(p
->out
, azCol
[i
], -1);
2441 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2442 fputs("null",p
->out
);
2443 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2445 double r
= sqlite3_column_double(p
->pStmt
, i
);
2447 memcpy(&ur
,&r
,sizeof(r
));
2448 if( ur
==0x7ff0000000000000LL
){
2449 raw_printf(p
->out
, "1e999");
2450 }else if( ur
==0xfff0000000000000LL
){
2451 raw_printf(p
->out
, "-1e999");
2453 sqlite3_snprintf(50,z
,"%!.20g", r
);
2454 raw_printf(p
->out
, "%s", z
);
2456 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2457 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2458 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2459 output_json_string(p
->out
, pBlob
, nBlob
);
2460 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2461 output_json_string(p
->out
, azArg
[i
], -1);
2463 utf8_printf(p
->out
,"%s", azArg
[i
]);
2473 if( azArg
==0 ) break;
2474 if( p
->cnt
==0 && p
->showHeader
){
2475 for(i
=0; i
<nArg
; i
++){
2476 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2477 output_quoted_string(p
->out
, azCol
[i
]);
2479 fputs(p
->rowSeparator
, p
->out
);
2482 for(i
=0; i
<nArg
; i
++){
2483 if( i
>0 ) fputs(p
->colSeparator
, p
->out
);
2484 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2485 utf8_printf(p
->out
,"NULL");
2486 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2487 output_quoted_string(p
->out
, azArg
[i
]);
2488 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2489 utf8_printf(p
->out
,"%s", azArg
[i
]);
2490 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2492 double r
= sqlite3_column_double(p
->pStmt
, i
);
2493 sqlite3_snprintf(50,z
,"%!.20g", r
);
2494 raw_printf(p
->out
, "%s", z
);
2495 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2496 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2497 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2498 output_hex_blob(p
->out
, pBlob
, nBlob
);
2499 }else if( isNumber(azArg
[i
], 0) ){
2500 utf8_printf(p
->out
,"%s", azArg
[i
]);
2502 output_quoted_string(p
->out
, azArg
[i
]);
2505 fputs(p
->rowSeparator
, p
->out
);
2509 if( p
->cnt
++==0 && p
->showHeader
){
2510 for(i
=0; i
<nArg
; i
++){
2511 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2512 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2514 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2516 if( azArg
==0 ) break;
2517 for(i
=0; i
<nArg
; i
++){
2518 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2519 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2521 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2525 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2533 ** This is the callback routine that the SQLite library
2534 ** invokes for each row of a query result.
2536 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2537 /* since we don't have type info, call the shell_callback with a NULL value */
2538 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2542 ** This is the callback routine from sqlite3_exec() that appends all
2543 ** output onto the end of a ShellText object.
2545 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2546 ShellText
*p
= (ShellText
*)pArg
;
2548 UNUSED_PARAMETER(az
);
2549 if( azArg
==0 ) return 0;
2550 if( p
->n
) appendText(p
, "|", 0);
2551 for(i
=0; i
<nArg
; i
++){
2552 if( i
) appendText(p
, ",", 0);
2553 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2559 ** Generate an appropriate SELFTEST table in the main database.
2561 static void createSelftestTable(ShellState
*p
){
2564 "SAVEPOINT selftest_init;\n"
2565 "CREATE TABLE IF NOT EXISTS selftest(\n"
2566 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2567 " op TEXT,\n" /* Operator: memo run */
2568 " cmd TEXT,\n" /* Command text */
2569 " ans TEXT\n" /* Desired answer */
2571 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2572 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2573 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2574 " 'memo','Tests generated by --init');\n"
2575 "INSERT INTO [_shell$self]\n"
2577 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2578 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2579 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2580 "FROM sqlite_schema ORDER BY 2',224));\n"
2581 "INSERT INTO [_shell$self]\n"
2583 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2584 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2585 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2587 " SELECT name FROM sqlite_schema\n"
2588 " WHERE type='table'\n"
2589 " AND name<>'selftest'\n"
2590 " AND coalesce(rootpage,0)>0\n"
2593 "INSERT INTO [_shell$self]\n"
2594 " VALUES('run','PRAGMA integrity_check','ok');\n"
2595 "INSERT INTO selftest(tno,op,cmd,ans)"
2596 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2597 "DROP TABLE [_shell$self];"
2600 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2601 sqlite3_free(zErrMsg
);
2603 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2608 ** Set the destination table field of the ShellState structure to
2609 ** the name of the table given. Escape any quote characters in the
2612 static void set_table_name(ShellState
*p
, const char *zName
){
2617 if( p
->zDestTable
){
2618 free(p
->zDestTable
);
2621 if( zName
==0 ) return;
2622 cQuote
= quoteChar(zName
);
2623 n
= strlen30(zName
);
2624 if( cQuote
) n
+= n
+2;
2625 z
= p
->zDestTable
= malloc( n
+1 );
2628 if( cQuote
) z
[n
++] = cQuote
;
2629 for(i
=0; zName
[i
]; i
++){
2631 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2633 if( cQuote
) z
[n
++] = cQuote
;
2638 ** Maybe construct two lines of text that point out the position of a
2639 ** syntax error. Return a pointer to the text, in memory obtained from
2640 ** sqlite3_malloc(). Or, if the most recent error does not involve a
2641 ** specific token that we can point to, return an empty string.
2643 ** In all cases, the memory returned is obtained from sqlite3_malloc64()
2644 ** and should be released by the caller invoking sqlite3_free().
2646 static char *shell_error_context(const char *zSql
, sqlite3
*db
){
2654 || (iOffset
= sqlite3_error_offset(db
))<0
2656 return sqlite3_mprintf("");
2658 while( iOffset
>50 ){
2661 while( (zSql
[0]&0xc0)==0x80 ){ zSql
++; iOffset
--; }
2666 while( (zSql
[len
]&0xc0)==0x80 ) len
--;
2668 zCode
= sqlite3_mprintf("%.*s", len
, zSql
);
2669 shell_check_oom(zCode
);
2670 for(i
=0; zCode
[i
]; i
++){ if( IsSpace(zSql
[i
]) ) zCode
[i
] = ' '; }
2672 zMsg
= sqlite3_mprintf("\n %z\n %*s^--- error here", zCode
, iOffset
, "");
2674 zMsg
= sqlite3_mprintf("\n %z\n %*serror here ---^", zCode
, iOffset
-14, "");
2681 ** Execute a query statement that will generate SQL output. Print
2682 ** the result columns, comma-separated, on a line and then add a
2683 ** semicolon terminator to the end of that line.
2685 ** If the number of columns is 1 and that column contains text "--"
2686 ** then write the semicolon on a separate line. That way, if a
2687 ** "--" comment occurs at the end of the statement, the comment
2688 ** won't consume the semicolon terminator.
2690 static int run_table_dump_query(
2691 ShellState
*p
, /* Query context */
2692 const char *zSelect
/* SELECT statement to extract content */
2694 sqlite3_stmt
*pSelect
;
2699 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2700 if( rc
!=SQLITE_OK
|| !pSelect
){
2701 char *zContext
= shell_error_context(zSelect
, p
->db
);
2702 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n%s", rc
,
2703 sqlite3_errmsg(p
->db
), zContext
);
2704 sqlite3_free(zContext
);
2705 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2708 rc
= sqlite3_step(pSelect
);
2709 nResult
= sqlite3_column_count(pSelect
);
2710 while( rc
==SQLITE_ROW
){
2711 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2712 utf8_printf(p
->out
, "%s", z
);
2713 for(i
=1; i
<nResult
; i
++){
2714 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2717 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2719 raw_printf(p
->out
, "\n;\n");
2721 raw_printf(p
->out
, ";\n");
2723 rc
= sqlite3_step(pSelect
);
2725 rc
= sqlite3_finalize(pSelect
);
2726 if( rc
!=SQLITE_OK
){
2727 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2728 sqlite3_errmsg(p
->db
));
2729 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2735 ** Allocate space and save off string indicating current error.
2737 static char *save_err_msg(
2738 sqlite3
*db
, /* Database to query */
2739 const char *zPhase
, /* When the error occcurs */
2740 int rc
, /* Error code returned from API */
2741 const char *zSql
/* SQL string, or NULL */
2745 sqlite3_str
*pStr
= sqlite3_str_new(0);
2746 sqlite3_str_appendf(pStr
, "%s, %s", zPhase
, sqlite3_errmsg(db
));
2748 sqlite3_str_appendf(pStr
, " (%d)", rc
);
2750 zContext
= shell_error_context(zSql
, db
);
2752 sqlite3_str_appendall(pStr
, zContext
);
2753 sqlite3_free(zContext
);
2755 zErr
= sqlite3_str_finish(pStr
);
2756 shell_check_oom(zErr
);
2762 ** Attempt to display I/O stats on Linux using /proc/PID/io
2764 static void displayLinuxIoStats(FILE *out
){
2767 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2768 in
= fopen(z
, "rb");
2770 while( fgets(z
, sizeof(z
), in
)!=0 ){
2771 static const struct {
2772 const char *zPattern
;
2775 { "rchar: ", "Bytes received by read():" },
2776 { "wchar: ", "Bytes sent to write():" },
2777 { "syscr: ", "Read() system calls:" },
2778 { "syscw: ", "Write() system calls:" },
2779 { "read_bytes: ", "Bytes read from storage:" },
2780 { "write_bytes: ", "Bytes written to storage:" },
2781 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2784 for(i
=0; i
<ArraySize(aTrans
); i
++){
2785 int n
= strlen30(aTrans
[i
].zPattern
);
2786 if( cli_strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2787 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2797 ** Display a single line of status using 64-bit values.
2799 static void displayStatLine(
2800 ShellState
*p
, /* The shell context */
2801 char *zLabel
, /* Label for this one line */
2802 char *zFormat
, /* Format for the result */
2803 int iStatusCtrl
, /* Which status to display */
2804 int bReset
/* True to reset the stats */
2806 sqlite3_int64 iCur
= -1;
2807 sqlite3_int64 iHiwtr
= -1;
2810 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2811 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2812 if( zFormat
[i
]=='%' ) nPercent
++;
2815 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2817 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2819 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2823 ** Display memory stats.
2825 static int display_stats(
2826 sqlite3
*db
, /* Database to query */
2827 ShellState
*pArg
, /* Pointer to ShellState */
2828 int bReset
/* True to reset the stats */
2833 if( pArg
==0 || pArg
->out
==0 ) return 0;
2836 if( pArg
->pStmt
&& pArg
->statsOn
==2 ){
2838 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
2840 nCol
= sqlite3_column_count(pStmt
);
2841 raw_printf(out
, "%-36s %d\n", "Number of output columns:", nCol
);
2842 for(i
=0; i
<nCol
; i
++){
2843 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
2844 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
2845 #ifndef SQLITE_OMIT_DECLTYPE
2846 sqlite3_snprintf(30, z
+x
, "declared type:");
2847 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
2849 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2850 sqlite3_snprintf(30, z
+x
, "database name:");
2851 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
2852 sqlite3_snprintf(30, z
+x
, "table name:");
2853 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
2854 sqlite3_snprintf(30, z
+x
, "origin name:");
2855 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
2860 if( pArg
->statsOn
==3 ){
2862 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2863 raw_printf(pArg
->out
, "VM-steps: %d\n", iCur
);
2868 displayStatLine(pArg
, "Memory Used:",
2869 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
2870 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2871 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2872 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2873 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2874 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2876 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2877 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2878 displayStatLine(pArg
, "Largest Allocation:",
2879 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2880 displayStatLine(pArg
, "Largest Pcache Allocation:",
2881 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2882 #ifdef YYTRACKMAXSTACKDEPTH
2883 displayStatLine(pArg
, "Deepest Parser Stack:",
2884 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2888 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2890 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2891 &iCur
, &iHiwtr
, bReset
);
2892 raw_printf(pArg
->out
,
2893 "Lookaside Slots Used: %d (max %d)\n",
2895 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2896 &iCur
, &iHiwtr
, bReset
);
2897 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2899 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2900 &iCur
, &iHiwtr
, bReset
);
2901 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2903 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2904 &iCur
, &iHiwtr
, bReset
);
2905 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2909 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2910 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2913 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2914 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2916 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2917 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2919 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2920 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2922 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
2923 raw_printf(pArg
->out
, "Page cache spills: %d\n", iCur
);
2925 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2926 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2929 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2930 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2936 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2938 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2939 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2940 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2941 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2942 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2943 iHit
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_HIT
, bReset
);
2944 iMiss
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FILTER_MISS
, bReset
);
2945 if( iHit
|| iMiss
){
2946 raw_printf(pArg
->out
, "Bloom filter bypass taken: %d/%d\n",
2949 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2950 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2951 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
,bReset
);
2952 raw_printf(pArg
->out
, "Reprepare operations: %d\n", iCur
);
2953 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
2954 raw_printf(pArg
->out
, "Number of times run: %d\n", iCur
);
2955 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
2956 raw_printf(pArg
->out
, "Memory used by prepared stmt: %d\n", iCur
);
2960 displayLinuxIoStats(pArg
->out
);
2963 /* Do not remove this machine readable comment: extra-stats-output-here */
2969 ** Display scan stats.
2971 static void display_scanstats(
2972 sqlite3
*db
, /* Database to query */
2973 ShellState
*pArg
/* Pointer to ShellState */
2975 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2976 UNUSED_PARAMETER(db
);
2977 UNUSED_PARAMETER(pArg
);
2980 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2982 for(k
=0; k
<=mx
; k
++){
2983 double rEstLoop
= 1.0;
2985 sqlite3_stmt
*p
= pArg
->pStmt
;
2986 sqlite3_int64 nLoop
, nVisit
;
2989 const char *zExplain
;
2990 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2993 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2994 if( iSid
>mx
) mx
= iSid
;
2995 if( iSid
!=k
) continue;
2997 rEstLoop
= (double)nLoop
;
2998 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
3001 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
3002 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
3003 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
3004 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
3006 raw_printf(pArg
->out
,
3007 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
3008 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
3012 raw_printf(pArg
->out
, "---------------------------\n");
3017 ** Parameter azArray points to a zero-terminated array of strings. zStr
3018 ** points to a single nul-terminated string. Return non-zero if zStr
3019 ** is equal, according to strcmp(), to any of the strings in the array.
3020 ** Otherwise, return zero.
3022 static int str_in_array(const char *zStr
, const char **azArray
){
3024 for(i
=0; azArray
[i
]; i
++){
3025 if( 0==cli_strcmp(zStr
, azArray
[i
]) ) return 1;
3031 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3032 ** and populate the ShellState.aiIndent[] array with the number of
3033 ** spaces each opcode should be indented before it is output.
3035 ** The indenting rules are:
3037 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3038 ** all opcodes that occur between the p2 jump destination and the opcode
3039 ** itself by 2 spaces.
3041 ** * Do the previous for "Return" instructions for when P2 is positive.
3042 ** See tag-20220407a in wherecode.c and vdbe.c.
3044 ** * For each "Goto", if the jump destination is earlier in the program
3045 ** and ends on one of:
3046 ** Yield SeekGt SeekLt RowSetRead Rewind
3047 ** or if the P1 parameter is one instead of zero,
3048 ** then indent all opcodes between the earlier instruction
3049 ** and "Goto" by 2 spaces.
3051 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
3052 const char *zSql
; /* The text of the SQL statement */
3053 const char *z
; /* Used to check if this is an EXPLAIN */
3054 int *abYield
= 0; /* True if op is an OP_Yield */
3055 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
3056 int iOp
; /* Index of operation in p->aiIndent[] */
3058 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3060 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3062 const char *azGoto
[] = { "Goto", 0 };
3064 /* Try to figure out if this is really an EXPLAIN statement. If this
3065 ** cannot be verified, return early. */
3066 if( sqlite3_column_count(pSql
)!=8 ){
3070 zSql
= sqlite3_sql(pSql
);
3071 if( zSql
==0 ) return;
3072 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
3073 if( sqlite3_strnicmp(z
, "explain", 7) ){
3078 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
3080 int iAddr
= sqlite3_column_int(pSql
, 0);
3081 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
3083 /* Set p2 to the P2 field of the current opcode. Then, assuming that
3084 ** p2 is an instruction address, set variable p2op to the index of that
3085 ** instruction in the aiIndent[] array. p2 and p2op may be different if
3086 ** the current instruction is part of a sub-program generated by an
3087 ** SQL trigger or foreign key. */
3088 int p2
= sqlite3_column_int(pSql
, 3);
3089 int p2op
= (p2
+ (iOp
-iAddr
));
3091 /* Grow the p->aiIndent array as required */
3094 /* Do further verfication that this is explain output. Abort if
3096 static const char *explainCols
[] = {
3097 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3099 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
3100 if( cli_strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
3102 sqlite3_reset(pSql
);
3108 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
3109 shell_check_oom(p
->aiIndent
);
3110 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
3111 shell_check_oom(abYield
);
3113 abYield
[iOp
] = str_in_array(zOp
, azYield
);
3114 p
->aiIndent
[iOp
] = 0;
3117 if( str_in_array(zOp
, azNext
) && p2op
>0 ){
3118 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3120 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
3121 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
3123 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
3128 sqlite3_free(abYield
);
3129 sqlite3_reset(pSql
);
3133 ** Free the array allocated by explain_data_prepare().
3135 static void explain_data_delete(ShellState
*p
){
3136 sqlite3_free(p
->aiIndent
);
3143 ** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3145 static unsigned int savedSelectTrace
;
3146 static unsigned int savedWhereTrace
;
3147 static void disable_debug_trace_modes(void){
3148 unsigned int zero
= 0;
3149 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 0, &savedSelectTrace
);
3150 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &zero
);
3151 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 2, &savedWhereTrace
);
3152 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &zero
);
3154 static void restore_debug_trace_modes(void){
3155 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &savedSelectTrace
);
3156 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &savedWhereTrace
);
3159 /* Create the TEMP table used to store parameter bindings */
3160 static void bind_table_init(ShellState
*p
){
3162 int defensiveMode
= 0;
3163 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, -1, &defensiveMode
);
3164 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, 0, 0);
3165 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, -1, &wrSchema
);
3166 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, 1, 0);
3168 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3169 " key TEXT PRIMARY KEY,\n"
3173 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, wrSchema
, 0);
3174 sqlite3_db_config(p
->db
, SQLITE_DBCONFIG_DEFENSIVE
, defensiveMode
, 0);
3178 ** Bind parameters on a prepared statement.
3180 ** Parameter bindings are taken from a TEMP table of the form:
3182 ** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3185 ** No bindings occur if this table does not exist. The name of the table
3186 ** begins with "sqlite_" so that it will not collide with ordinary application
3187 ** tables. The table must be in the TEMP schema.
3189 static void bind_prepared_stmt(ShellState
*pArg
, sqlite3_stmt
*pStmt
){
3193 sqlite3_stmt
*pQ
= 0;
3195 nVar
= sqlite3_bind_parameter_count(pStmt
);
3196 if( nVar
==0 ) return; /* Nothing to do */
3197 if( sqlite3_table_column_metadata(pArg
->db
, "TEMP", "sqlite_parameters",
3198 "key", 0, 0, 0, 0, 0)!=SQLITE_OK
){
3199 return; /* Parameter table does not exist */
3201 rc
= sqlite3_prepare_v2(pArg
->db
,
3202 "SELECT value FROM temp.sqlite_parameters"
3203 " WHERE key=?1", -1, &pQ
, 0);
3204 if( rc
|| pQ
==0 ) return;
3205 for(i
=1; i
<=nVar
; i
++){
3207 const char *zVar
= sqlite3_bind_parameter_name(pStmt
, i
);
3209 sqlite3_snprintf(sizeof(zNum
),zNum
,"?%d",i
);
3212 sqlite3_bind_text(pQ
, 1, zVar
, -1, SQLITE_STATIC
);
3213 if( sqlite3_step(pQ
)==SQLITE_ROW
){
3214 sqlite3_bind_value(pStmt
, i
, sqlite3_column_value(pQ
, 0));
3216 sqlite3_bind_null(pStmt
, i
);
3220 sqlite3_finalize(pQ
);
3224 ** UTF8 box-drawing characters. Imagine box lines like this:
3232 ** Each box characters has between 2 and 4 of the lines leading from
3233 ** the center. The characters are here identified by the numbers of
3234 ** their corresponding lines.
3236 #define BOX_24 "\342\224\200" /* U+2500 --- */
3237 #define BOX_13 "\342\224\202" /* U+2502 | */
3238 #define BOX_23 "\342\224\214" /* U+250c ,- */
3239 #define BOX_34 "\342\224\220" /* U+2510 -, */
3240 #define BOX_12 "\342\224\224" /* U+2514 '- */
3241 #define BOX_14 "\342\224\230" /* U+2518 -' */
3242 #define BOX_123 "\342\224\234" /* U+251c |- */
3243 #define BOX_134 "\342\224\244" /* U+2524 -| */
3244 #define BOX_234 "\342\224\254" /* U+252c -,- */
3245 #define BOX_124 "\342\224\264" /* U+2534 -'- */
3246 #define BOX_1234 "\342\224\274" /* U+253c -|- */
3248 /* Draw horizontal line N characters long using unicode box
3251 static void print_box_line(FILE *out
, int N
){
3252 const char zDash
[] =
3253 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3254 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
;
3255 const int nDash
= sizeof(zDash
) - 1;
3258 utf8_printf(out
, zDash
);
3261 utf8_printf(out
, "%.*s", N
, zDash
);
3265 ** Draw a horizontal separator for a MODE_Box table.
3267 static void print_box_row_separator(
3276 utf8_printf(p
->out
, "%s", zSep1
);
3277 print_box_line(p
->out
, p
->actualWidth
[0]+2);
3278 for(i
=1; i
<nArg
; i
++){
3279 utf8_printf(p
->out
, "%s", zSep2
);
3280 print_box_line(p
->out
, p
->actualWidth
[i
]+2);
3282 utf8_printf(p
->out
, "%s", zSep3
);
3284 fputs("\n", p
->out
);
3288 ** z[] is a line of text that is to be displayed the .mode box or table or
3289 ** similar tabular formats. z[] might contain control characters such
3290 ** as \n, \t, \f, or \r.
3292 ** Compute characters to display on the first line of z[]. Stop at the
3293 ** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained
3294 ** from malloc()) of that first line, which caller should free sometime.
3295 ** Write anything to display on the next line into *pzTail. If this is
3296 ** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3298 static char *translateForDisplayAndDup(
3299 const unsigned char *z
, /* Input text to be transformed */
3300 const unsigned char **pzTail
, /* OUT: Tail of the input for next line */
3301 int mxWidth
, /* Max width. 0 means no limit */
3302 u8 bWordWrap
/* If true, avoid breaking mid-word */
3304 int i
; /* Input bytes consumed */
3305 int j
; /* Output bytes generated */
3306 int k
; /* Input bytes to be displayed */
3307 int n
; /* Output column number */
3308 unsigned char *zOut
; /* Output text */
3314 if( mxWidth
<0 ) mxWidth
= -mxWidth
;
3315 if( mxWidth
==0 ) mxWidth
= 1000000;
3320 do{ i
++; j
++; }while( (z
[i
]&0xc0)==0x80 );
3327 }while( (n
&7)!=0 && n
<mxWidth
);
3333 if( n
>=mxWidth
&& bWordWrap
){
3334 /* Perhaps try to back up to a better place to break the line */
3335 for(k
=i
; k
>i
/2; k
--){
3336 if( isspace(z
[k
-1]) ) break;
3339 for(k
=i
; k
>i
/2; k
--){
3340 if( isalnum(z
[k
-1])!=isalnum(z
[k
]) && (z
[k
]&0xc0)!=0x80 ) break;
3347 while( z
[i
]==' ' ) i
++;
3352 if( n
>=mxWidth
&& z
[i
]>=' ' ){
3354 }else if( z
[i
]=='\r' && z
[i
+1]=='\n' ){
3355 *pzTail
= z
[i
+2] ? &z
[i
+2] : 0;
3356 }else if( z
[i
]==0 || z
[i
+1]==0 ){
3361 zOut
= malloc( j
+1 );
3362 shell_check_oom(zOut
);
3367 do{ zOut
[j
++] = z
[i
++]; }while( (z
[i
]&0xc0)==0x80 );
3374 }while( (n
&7)!=0 && n
<mxWidth
);
3384 /* Extract the value of the i-th current column for pStmt as an SQL literal
3385 ** value. Memory is obtained from sqlite3_malloc64() and must be freed by
3388 static char *quoted_column(sqlite3_stmt
*pStmt
, int i
){
3389 switch( sqlite3_column_type(pStmt
, i
) ){
3391 return sqlite3_mprintf("NULL");
3393 case SQLITE_INTEGER
:
3394 case SQLITE_FLOAT
: {
3395 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt
,i
));
3398 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt
,i
));
3402 sqlite3_str
*pStr
= sqlite3_str_new(0);
3403 const unsigned char *a
= sqlite3_column_blob(pStmt
,i
);
3404 int n
= sqlite3_column_bytes(pStmt
,i
);
3405 sqlite3_str_append(pStr
, "x'", 2);
3407 sqlite3_str_appendf(pStr
, "%02x", a
[j
]);
3409 sqlite3_str_append(pStr
, "'", 1);
3410 return sqlite3_str_finish(pStr
);
3413 return 0; /* Not reached */
3417 ** Run a prepared statement and output the result in one of the
3418 ** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3421 ** This is different from ordinary exec_prepared_stmt() in that
3422 ** it has to run the entire query and gather the results into memory
3423 ** first, in order to determine column widths, before providing
3426 static void exec_prepared_stmt_columnar(
3427 ShellState
*p
, /* Pointer to ShellState */
3428 sqlite3_stmt
*pStmt
/* Statment to run */
3430 sqlite3_int64 nRow
= 0;
3433 sqlite3_int64 nAlloc
= 0;
3435 const unsigned char *uz
;
3437 char **azQuoted
= 0;
3439 sqlite3_int64 i
, nData
;
3440 int j
, nTotal
, w
, n
;
3441 const char *colSep
= 0;
3442 const char *rowSep
= 0;
3443 const unsigned char **azNextLine
= 0;
3445 int bMultiLineRowExists
= 0;
3446 int bw
= p
->cmOpts
.bWordWrap
;
3447 const char *zEmpty
= "";
3448 const char *zShowNull
= p
->nullValue
;
3450 rc
= sqlite3_step(pStmt
);
3451 if( rc
!=SQLITE_ROW
) return;
3452 nColumn
= sqlite3_column_count(pStmt
);
3454 if( nAlloc
<=0 ) nAlloc
= 1;
3455 azData
= sqlite3_malloc64( nAlloc
*sizeof(char*) );
3456 shell_check_oom(azData
);
3457 azNextLine
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3458 shell_check_oom((void*)azNextLine
);
3459 memset((void*)azNextLine
, 0, nColumn
*sizeof(char*) );
3460 if( p
->cmOpts
.bQuote
){
3461 azQuoted
= sqlite3_malloc64( nColumn
*sizeof(char*) );
3462 shell_check_oom(azQuoted
);
3463 memset(azQuoted
, 0, nColumn
*sizeof(char*) );
3465 abRowDiv
= sqlite3_malloc64( nAlloc
/nColumn
);
3466 shell_check_oom(abRowDiv
);
3467 if( nColumn
>p
->nWidth
){
3468 p
->colWidth
= realloc(p
->colWidth
, (nColumn
+1)*2*sizeof(int));
3469 shell_check_oom(p
->colWidth
);
3470 for(i
=p
->nWidth
; i
<nColumn
; i
++) p
->colWidth
[i
] = 0;
3471 p
->nWidth
= nColumn
;
3472 p
->actualWidth
= &p
->colWidth
[nColumn
];
3474 memset(p
->actualWidth
, 0, nColumn
*sizeof(int));
3475 for(i
=0; i
<nColumn
; i
++){
3478 p
->actualWidth
[i
] = w
;
3480 for(i
=0; i
<nColumn
; i
++){
3481 const unsigned char *zNotUsed
;
3482 int wx
= p
->colWidth
[i
];
3484 wx
= p
->cmOpts
.iWrap
;
3486 if( wx
<0 ) wx
= -wx
;
3487 uz
= (const unsigned char*)sqlite3_column_name(pStmt
,i
);
3488 azData
[i
] = translateForDisplayAndDup(uz
, &zNotUsed
, wx
, bw
);
3491 int useNextLine
= bNextLine
;
3493 if( (nRow
+2)*nColumn
>= nAlloc
){
3495 azData
= sqlite3_realloc64(azData
, nAlloc
*sizeof(char*));
3496 shell_check_oom(azData
);
3497 abRowDiv
= sqlite3_realloc64(abRowDiv
, nAlloc
/nColumn
);
3498 shell_check_oom(abRowDiv
);
3502 for(i
=0; i
<nColumn
; i
++){
3503 int wx
= p
->colWidth
[i
];
3505 wx
= p
->cmOpts
.iWrap
;
3507 if( wx
<0 ) wx
= -wx
;
3510 if( uz
==0 ) uz
= (u8
*)zEmpty
;
3511 }else if( p
->cmOpts
.bQuote
){
3512 sqlite3_free(azQuoted
[i
]);
3513 azQuoted
[i
] = quoted_column(pStmt
,i
);
3514 uz
= (const unsigned char*)azQuoted
[i
];
3516 uz
= (const unsigned char*)sqlite3_column_text(pStmt
,i
);
3517 if( uz
==0 ) uz
= (u8
*)zShowNull
;
3519 azData
[nRow
*nColumn
+ i
]
3520 = translateForDisplayAndDup(uz
, &azNextLine
[i
], wx
, bw
);
3521 if( azNextLine
[i
] ){
3523 abRowDiv
[nRow
-1] = 0;
3524 bMultiLineRowExists
= 1;
3527 }while( bNextLine
|| sqlite3_step(pStmt
)==SQLITE_ROW
);
3528 nTotal
= nColumn
*(nRow
+1);
3529 for(i
=0; i
<nTotal
; i
++){
3531 if( z
==0 ) z
= (char*)zEmpty
;
3534 if( n
>p
->actualWidth
[j
] ) p
->actualWidth
[j
] = n
;
3536 if( seenInterrupt
) goto columnar_end
;
3537 if( nColumn
==0 ) goto columnar_end
;
3542 if( p
->showHeader
){
3543 for(i
=0; i
<nColumn
; i
++){
3544 w
= p
->actualWidth
[i
];
3545 if( p
->colWidth
[i
]<0 ) w
= -w
;
3546 utf8_width_print(p
->out
, w
, azData
[i
]);
3547 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3549 for(i
=0; i
<nColumn
; i
++){
3550 print_dashes(p
->out
, p
->actualWidth
[i
]);
3551 fputs(i
==nColumn
-1?"\n":" ", p
->out
);
3559 print_row_separator(p
, nColumn
, "+");
3560 fputs("| ", p
->out
);
3561 for(i
=0; i
<nColumn
; i
++){
3562 w
= p
->actualWidth
[i
];
3563 n
= strlenChar(azData
[i
]);
3564 utf8_printf(p
->out
, "%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3565 fputs(i
==nColumn
-1?" |\n":" | ", p
->out
);
3567 print_row_separator(p
, nColumn
, "+");
3570 case MODE_Markdown
: {
3573 fputs("| ", p
->out
);
3574 for(i
=0; i
<nColumn
; i
++){
3575 w
= p
->actualWidth
[i
];
3576 n
= strlenChar(azData
[i
]);
3577 utf8_printf(p
->out
, "%*s%s%*s", (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "");
3578 fputs(i
==nColumn
-1?" |\n":" | ", p
->out
);
3580 print_row_separator(p
, nColumn
, "|");
3584 colSep
= " " BOX_13
" ";
3585 rowSep
= " " BOX_13
"\n";
3586 print_box_row_separator(p
, nColumn
, BOX_23
, BOX_234
, BOX_34
);
3587 utf8_printf(p
->out
, BOX_13
" ");
3588 for(i
=0; i
<nColumn
; i
++){
3589 w
= p
->actualWidth
[i
];
3590 n
= strlenChar(azData
[i
]);
3591 utf8_printf(p
->out
, "%*s%s%*s%s",
3592 (w
-n
)/2, "", azData
[i
], (w
-n
+1)/2, "",
3593 i
==nColumn
-1?" "BOX_13
"\n":" "BOX_13
" ");
3595 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3599 for(i
=nColumn
, j
=0; i
<nTotal
; i
++, j
++){
3600 if( j
==0 && p
->cMode
!=MODE_Column
){
3601 utf8_printf(p
->out
, "%s", p
->cMode
==MODE_Box
?BOX_13
" ":"| ");
3604 if( z
==0 ) z
= p
->nullValue
;
3605 w
= p
->actualWidth
[j
];
3606 if( p
->colWidth
[j
]<0 ) w
= -w
;
3607 utf8_width_print(p
->out
, w
, z
);
3609 utf8_printf(p
->out
, "%s", rowSep
);
3610 if( bMultiLineRowExists
&& abRowDiv
[i
/nColumn
-1] && i
+1<nTotal
){
3611 if( p
->cMode
==MODE_Table
){
3612 print_row_separator(p
, nColumn
, "+");
3613 }else if( p
->cMode
==MODE_Box
){
3614 print_box_row_separator(p
, nColumn
, BOX_123
, BOX_1234
, BOX_134
);
3615 }else if( p
->cMode
==MODE_Column
){
3616 raw_printf(p
->out
, "\n");
3620 if( seenInterrupt
) goto columnar_end
;
3622 utf8_printf(p
->out
, "%s", colSep
);
3625 if( p
->cMode
==MODE_Table
){
3626 print_row_separator(p
, nColumn
, "+");
3627 }else if( p
->cMode
==MODE_Box
){
3628 print_box_row_separator(p
, nColumn
, BOX_12
, BOX_124
, BOX_14
);
3631 if( seenInterrupt
){
3632 utf8_printf(p
->out
, "Interrupt\n");
3634 nData
= (nRow
+1)*nColumn
;
3635 for(i
=0; i
<nData
; i
++){
3637 if( z
!=zEmpty
&& z
!=zShowNull
) free(azData
[i
]);
3639 sqlite3_free(azData
);
3640 sqlite3_free((void*)azNextLine
);
3641 sqlite3_free(abRowDiv
);
3643 for(i
=0; i
<nColumn
; i
++) sqlite3_free(azQuoted
[i
]);
3644 sqlite3_free(azQuoted
);
3649 ** Run a prepared statement
3651 static void exec_prepared_stmt(
3652 ShellState
*pArg
, /* Pointer to ShellState */
3653 sqlite3_stmt
*pStmt
/* Statment to run */
3656 sqlite3_uint64 nRow
= 0;
3658 if( pArg
->cMode
==MODE_Column
3659 || pArg
->cMode
==MODE_Table
3660 || pArg
->cMode
==MODE_Box
3661 || pArg
->cMode
==MODE_Markdown
3663 exec_prepared_stmt_columnar(pArg
, pStmt
);
3667 /* perform the first step. this will tell us if we
3668 ** have a result set or not and how wide it is.
3670 rc
= sqlite3_step(pStmt
);
3671 /* if we have a result set... */
3672 if( SQLITE_ROW
== rc
){
3673 /* allocate space for col name ptr, value ptr, and type */
3674 int nCol
= sqlite3_column_count(pStmt
);
3675 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
3677 shell_out_of_memory();
3679 char **azCols
= (char **)pData
; /* Names of result columns */
3680 char **azVals
= &azCols
[nCol
]; /* Results */
3681 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
3683 assert(sizeof(int) <= sizeof(char *));
3684 /* save off ptrs to column names */
3685 for(i
=0; i
<nCol
; i
++){
3686 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
3690 /* extract the data and data types */
3691 for(i
=0; i
<nCol
; i
++){
3692 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
3695 && (pArg
->cMode
==MODE_Insert
|| pArg
->cMode
==MODE_Quote
)
3699 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
3701 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
3703 break; /* from for */
3707 /* if data and types extracted successfully... */
3708 if( SQLITE_ROW
== rc
){
3709 /* call the supplied callback with the result row data */
3710 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
3713 rc
= sqlite3_step(pStmt
);
3716 } while( SQLITE_ROW
== rc
);
3717 sqlite3_free(pData
);
3718 if( pArg
->cMode
==MODE_Json
){
3719 fputs("]\n", pArg
->out
);
3720 }else if( pArg
->cMode
==MODE_Count
){
3722 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%llu row%s\n",
3723 nRow
, nRow
!=1 ? "s" : "");
3730 #ifndef SQLITE_OMIT_VIRTUALTABLE
3732 ** This function is called to process SQL if the previous shell command
3733 ** was ".expert". It passes the SQL in the second argument directly to
3734 ** the sqlite3expert object.
3736 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3737 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3738 ** an English language error message. It is the responsibility of the
3739 ** caller to eventually free this buffer using sqlite3_free().
3741 static int expertHandleSQL(
3746 assert( pState
->expert
.pExpert
);
3747 assert( pzErr
==0 || *pzErr
==0 );
3748 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
3752 ** This function is called either to silently clean up the object
3753 ** created by the ".expert" command (if bCancel==1), or to generate a
3754 ** report from it and then clean it up (if bCancel==0).
3756 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3757 ** code. In this case, (*pzErr) may be set to point to a buffer containing
3758 ** an English language error message. It is the responsibility of the
3759 ** caller to eventually free this buffer using sqlite3_free().
3761 static int expertFinish(
3767 sqlite3expert
*p
= pState
->expert
.pExpert
;
3769 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
3771 FILE *out
= pState
->out
;
3772 int bVerbose
= pState
->expert
.bVerbose
;
3774 rc
= sqlite3_expert_analyze(p
, pzErr
);
3775 if( rc
==SQLITE_OK
){
3776 int nQuery
= sqlite3_expert_count(p
);
3780 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
3781 raw_printf(out
, "-- Candidates -----------------------------\n");
3782 raw_printf(out
, "%s\n", zCand
);
3784 for(i
=0; i
<nQuery
; i
++){
3785 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
3786 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
3787 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
3788 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
3790 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
3791 raw_printf(out
, "%s\n\n", zSql
);
3793 raw_printf(out
, "%s\n", zIdx
);
3794 raw_printf(out
, "%s\n", zEQP
);
3798 sqlite3_expert_destroy(p
);
3799 pState
->expert
.pExpert
= 0;
3804 ** Implementation of ".expert" dot command.
3806 static int expertDotCommand(
3807 ShellState
*pState
, /* Current shell tool state */
3808 char **azArg
, /* Array of arguments passed to dot command */
3809 int nArg
/* Number of entries in azArg[] */
3816 assert( pState
->expert
.pExpert
==0 );
3817 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
3819 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
3822 if( z
[0]=='-' && z
[1]=='-' ) z
++;
3824 if( n
>=2 && 0==cli_strncmp(z
, "-verbose", n
) ){
3825 pState
->expert
.bVerbose
= 1;
3827 else if( n
>=2 && 0==cli_strncmp(z
, "-sample", n
) ){
3829 raw_printf(stderr
, "option requires an argument: %s\n", z
);
3832 iSample
= (int)integerValue(azArg
[++i
]);
3833 if( iSample
<0 || iSample
>100 ){
3834 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
3840 raw_printf(stderr
, "unknown option: %s\n", z
);
3845 if( rc
==SQLITE_OK
){
3846 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
3847 if( pState
->expert
.pExpert
==0 ){
3848 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
? zErr
: "out of memory");
3851 sqlite3_expert_config(
3852 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
3860 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3863 ** Execute a statement or set of statements. Print
3864 ** any result rows/columns depending on the current mode
3865 ** set via the supplied callback.
3867 ** This is very similar to SQLite's built-in sqlite3_exec()
3868 ** function except it takes a slightly different callback
3869 ** and callback data argument.
3871 static int shell_exec(
3872 ShellState
*pArg
, /* Pointer to ShellState */
3873 const char *zSql
, /* SQL to be evaluated */
3874 char **pzErrMsg
/* Error msg written here */
3876 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
3877 int rc
= SQLITE_OK
; /* Return Code */
3879 const char *zLeftover
; /* Tail of unprocessed SQL */
3880 sqlite3
*db
= pArg
->db
;
3886 #ifndef SQLITE_OMIT_VIRTUALTABLE
3887 if( pArg
->expert
.pExpert
){
3888 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
3889 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
3893 while( zSql
[0] && (SQLITE_OK
== rc
) ){
3894 static const char *zStmtSql
;
3895 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
3896 if( SQLITE_OK
!= rc
){
3898 *pzErrMsg
= save_err_msg(db
, "in prepare", rc
, zSql
);
3902 /* this happens for a comment or white-space */
3904 while( IsSpace(zSql
[0]) ) zSql
++;
3907 zStmtSql
= sqlite3_sql(pStmt
);
3908 if( zStmtSql
==0 ) zStmtSql
= "";
3909 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
3911 /* save off the prepared statment handle and reset row count */
3913 pArg
->pStmt
= pStmt
;
3917 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3918 if( pArg
&& pArg
->autoEQP
&& sqlite3_stmt_isexplain(pStmt
)==0 ){
3919 sqlite3_stmt
*pExplain
;
3922 disable_debug_trace_modes();
3923 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
3924 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
3925 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
3927 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
3928 shell_check_oom(zEQP
);
3929 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
3930 if( rc
==SQLITE_OK
){
3931 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
3932 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
3933 int iEqpId
= sqlite3_column_int(pExplain
, 0);
3934 int iParentId
= sqlite3_column_int(pExplain
, 1);
3935 if( zEQPLine
==0 ) zEQPLine
= "";
3936 if( zEQPLine
[0]=='-' ) eqp_render(pArg
);
3937 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
3941 sqlite3_finalize(pExplain
);
3943 if( pArg
->autoEQP
>=AUTOEQP_full
){
3944 /* Also do an EXPLAIN for ".eqp full" mode */
3945 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
3946 shell_check_oom(zEQP
);
3947 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
3948 if( rc
==SQLITE_OK
){
3949 pArg
->cMode
= MODE_Explain
;
3950 explain_data_prepare(pArg
, pExplain
);
3951 exec_prepared_stmt(pArg
, pExplain
);
3952 explain_data_delete(pArg
);
3954 sqlite3_finalize(pExplain
);
3957 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
3958 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
3959 /* Reprepare pStmt before reactiving trace modes */
3960 sqlite3_finalize(pStmt
);
3961 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
3962 if( pArg
) pArg
->pStmt
= pStmt
;
3964 restore_debug_trace_modes();
3968 pArg
->cMode
= pArg
->mode
;
3969 if( pArg
->autoExplain
){
3970 if( sqlite3_stmt_isexplain(pStmt
)==1 ){
3971 pArg
->cMode
= MODE_Explain
;
3973 if( sqlite3_stmt_isexplain(pStmt
)==2 ){
3974 pArg
->cMode
= MODE_EQP
;
3978 /* If the shell is currently in ".explain" mode, gather the extra
3979 ** data required to add indents to the output.*/
3980 if( pArg
->cMode
==MODE_Explain
){
3981 explain_data_prepare(pArg
, pStmt
);
3985 bind_prepared_stmt(pArg
, pStmt
);
3986 exec_prepared_stmt(pArg
, pStmt
);
3987 explain_data_delete(pArg
);
3990 /* print usage stats if stats on */
3991 if( pArg
&& pArg
->statsOn
){
3992 display_stats(db
, pArg
, 0);
3995 /* print loop-counters if required */
3996 if( pArg
&& pArg
->scanstatsOn
){
3997 display_scanstats(db
, pArg
);
4000 /* Finalize the statement just executed. If this fails, save a
4001 ** copy of the error message. Otherwise, set zSql to point to the
4002 ** next statement to execute. */
4003 rc2
= sqlite3_finalize(pStmt
);
4004 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
4005 if( rc
==SQLITE_OK
){
4007 while( IsSpace(zSql
[0]) ) zSql
++;
4008 }else if( pzErrMsg
){
4009 *pzErrMsg
= save_err_msg(db
, "stepping", rc
, 0);
4012 /* clear saved stmt handle */
4023 ** Release memory previously allocated by tableColumnList().
4025 static void freeColumnList(char **azCol
){
4027 for(i
=1; azCol
[i
]; i
++){
4028 sqlite3_free(azCol
[i
]);
4030 /* azCol[0] is a static string */
4031 sqlite3_free(azCol
);
4035 ** Return a list of pointers to strings which are the names of all
4036 ** columns in table zTab. The memory to hold the names is dynamically
4037 ** allocated and must be released by the caller using a subsequent call
4038 ** to freeColumnList().
4040 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
4041 ** value that needs to be preserved, then azCol[0] is filled in with the
4042 ** name of the rowid column.
4044 ** The first regular column in the table is azCol[1]. The list is terminated
4045 ** by an entry with azCol[i]==0.
4047 static char **tableColumnList(ShellState
*p
, const char *zTab
){
4049 sqlite3_stmt
*pStmt
;
4053 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
4054 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
4055 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
4058 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
4059 shell_check_oom(zSql
);
4060 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4063 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4064 if( nCol
>=nAlloc
-2 ){
4065 nAlloc
= nAlloc
*2 + nCol
+ 10;
4066 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
4067 shell_check_oom(azCol
);
4069 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
4070 shell_check_oom(azCol
[nCol
]);
4071 if( sqlite3_column_int(pStmt
, 5) ){
4074 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
4083 sqlite3_finalize(pStmt
);
4084 if( azCol
==0 ) return 0;
4088 /* The decision of whether or not a rowid really needs to be preserved
4089 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
4090 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
4091 ** rowids on tables where the rowid is inaccessible because there are other
4092 ** columns in the table named "rowid", "_rowid_", and "oid".
4094 if( preserveRowid
&& isIPK
){
4095 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4096 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
4097 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4098 ** ROWID aliases. To distinguish these cases, check to see if
4099 ** there is a "pk" entry in "PRAGMA index_list". There will be
4100 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4102 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4103 " WHERE origin='pk'", zTab
);
4104 shell_check_oom(zSql
);
4105 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4108 freeColumnList(azCol
);
4111 rc
= sqlite3_step(pStmt
);
4112 sqlite3_finalize(pStmt
);
4113 preserveRowid
= rc
==SQLITE_ROW
;
4115 if( preserveRowid
){
4116 /* Only preserve the rowid if we can find a name to use for the
4118 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
4121 for(i
=1; i
<=nCol
; i
++){
4122 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
4125 /* At this point, we know that azRowid[j] is not the name of any
4126 ** ordinary column in the table. Verify that azRowid[j] is a valid
4127 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
4128 ** tables will fail this last check */
4129 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
4130 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
4139 ** Toggle the reverse_unordered_selects setting.
4141 static void toggleSelectOrder(sqlite3
*db
){
4142 sqlite3_stmt
*pStmt
= 0;
4145 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
4146 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
4147 iSetting
= sqlite3_column_int(pStmt
, 0);
4149 sqlite3_finalize(pStmt
);
4150 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
4151 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
4152 sqlite3_exec(db
, zStmt
, 0, 0, 0);
4156 ** This is a different callback routine used for dumping the database.
4157 ** Each row received by this callback consists of a table name,
4158 ** the table type ("index" or "table") and SQL to create the table.
4159 ** This routine should print text sufficient to recreate the table.
4161 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
4166 ShellState
*p
= (ShellState
*)pArg
;
4170 UNUSED_PARAMETER(azNotUsed
);
4171 if( nArg
!=3 || azArg
==0 ) return 0;
4175 if( zTable
==0 ) return 0;
4176 if( zType
==0 ) return 0;
4177 dataOnly
= (p
->shellFlgs
& SHFLG_DumpDataOnly
)!=0;
4178 noSys
= (p
->shellFlgs
& SHFLG_DumpNoSys
)!=0;
4180 if( cli_strcmp(zTable
, "sqlite_sequence")==0 && !noSys
){
4181 if( !dataOnly
) raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
4182 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 && !noSys
){
4183 if( !dataOnly
) raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
4184 }else if( cli_strncmp(zTable
, "sqlite_", 7)==0 ){
4186 }else if( dataOnly
){
4188 }else if( cli_strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
4190 if( !p
->writableSchema
){
4191 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
4192 p
->writableSchema
= 1;
4194 zIns
= sqlite3_mprintf(
4195 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4196 "VALUES('table','%q','%q',0,'%q');",
4197 zTable
, zTable
, zSql
);
4198 shell_check_oom(zIns
);
4199 utf8_printf(p
->out
, "%s\n", zIns
);
4203 printSchemaLine(p
->out
, zSql
, ";\n");
4206 if( cli_strcmp(zType
, "table")==0 ){
4211 char *savedDestTable
;
4214 azCol
= tableColumnList(p
, zTable
);
4220 /* Always quote the table name, even if it appears to be pure ascii,
4221 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
4223 appendText(&sTable
, zTable
, quoteChar(zTable
));
4224 /* If preserving the rowid, add a column list after the table name.
4225 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4226 ** instead of the usual "INSERT INTO tab VALUES(...)".
4229 appendText(&sTable
, "(", 0);
4230 appendText(&sTable
, azCol
[0], 0);
4231 for(i
=1; azCol
[i
]; i
++){
4232 appendText(&sTable
, ",", 0);
4233 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
4235 appendText(&sTable
, ")", 0);
4238 /* Build an appropriate SELECT statement */
4240 appendText(&sSelect
, "SELECT ", 0);
4242 appendText(&sSelect
, azCol
[0], 0);
4243 appendText(&sSelect
, ",", 0);
4245 for(i
=1; azCol
[i
]; i
++){
4246 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
4248 appendText(&sSelect
, ",", 0);
4251 freeColumnList(azCol
);
4252 appendText(&sSelect
, " FROM ", 0);
4253 appendText(&sSelect
, zTable
, quoteChar(zTable
));
4255 savedDestTable
= p
->zDestTable
;
4256 savedMode
= p
->mode
;
4257 p
->zDestTable
= sTable
.z
;
4258 p
->mode
= p
->cMode
= MODE_Insert
;
4259 rc
= shell_exec(p
, sSelect
.z
, 0);
4260 if( (rc
&0xff)==SQLITE_CORRUPT
){
4261 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
4262 toggleSelectOrder(p
->db
);
4263 shell_exec(p
, sSelect
.z
, 0);
4264 toggleSelectOrder(p
->db
);
4266 p
->zDestTable
= savedDestTable
;
4267 p
->mode
= savedMode
;
4276 ** Run zQuery. Use dump_callback() as the callback routine so that
4277 ** the contents of the query are output as SQL statements.
4279 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
4280 ** "ORDER BY rowid DESC" to the end.
4282 static int run_schema_dump_query(
4288 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
4289 if( rc
==SQLITE_CORRUPT
){
4291 int len
= strlen30(zQuery
);
4292 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
4294 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
4298 zQ2
= malloc( len
+100 );
4299 if( zQ2
==0 ) return rc
;
4300 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
4301 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
4303 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
4305 rc
= SQLITE_CORRUPT
;
4314 ** Text of help messages.
4316 ** The help text for each individual command begins with a line that starts
4317 ** with ".". Subsequent lines are supplemental information.
4319 ** There must be two or more spaces between the end of the command and the
4320 ** start of the description of what that command does.
4322 static const char *(azHelp
[]) = {
4323 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4324 && !defined(SQLITE_SHELL_FIDDLE)
4325 ".archive ... Manage SQL archives",
4326 " Each command must have exactly one of the following options:",
4327 " -c, --create Create a new archive",
4328 " -u, --update Add or update files with changed mtime",
4329 " -i, --insert Like -u but always add even if unchanged",
4330 " -r, --remove Remove files from archive",
4331 " -t, --list List contents of archive",
4332 " -x, --extract Extract files from archive",
4333 " Optional arguments:",
4334 " -v, --verbose Print each filename as it is processed",
4335 " -f FILE, --file FILE Use archive FILE (default is current db)",
4336 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
4337 " -C DIR, --directory DIR Read/extract files from directory DIR",
4338 " -g, --glob Use glob matching for names in archive",
4339 " -n, --dryrun Show the SQL that would have occurred",
4341 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
4342 " .ar -tf ARCHIVE # List members of ARCHIVE",
4343 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
4345 " http://sqlite.org/cli.html#sqlite_archive_support",
4347 #ifndef SQLITE_OMIT_AUTHORIZATION
4348 ".auth ON|OFF Show authorizer callbacks",
4350 #ifndef SQLITE_SHELL_FIDDLE
4351 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
4353 " --append Use the appendvfs",
4354 " --async Write to FILE without journal and fsync()",
4356 ".bail on|off Stop after hitting an error. Default OFF",
4357 ".binary on|off Turn binary output on or off. Default OFF",
4358 #ifndef SQLITE_SHELL_FIDDLE
4359 ".cd DIRECTORY Change the working directory to DIRECTORY",
4361 ".changes on|off Show number of rows changed by SQL",
4362 #ifndef SQLITE_SHELL_FIDDLE
4363 ".check GLOB Fail if output since .testcase does not match",
4364 ".clone NEWDB Clone data into NEWDB from the existing database",
4366 ".connection [close] [#] Open or close an auxiliary database connection",
4367 ".databases List names and files of attached databases",
4368 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
4369 #if SQLITE_SHELL_HAVE_RECOVER
4370 ".dbinfo ?DB? Show status information about the database",
4372 ".dump ?OBJECTS? Render database content as SQL",
4374 " --data-only Output only INSERT statements",
4375 " --newlines Allow unescaped newline characters in output",
4376 " --nosys Omit system tables (ex: \"sqlite_stat1\")",
4377 " --preserve-rowids Include ROWID values in the output",
4378 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4379 " Additional LIKE patterns can be given in subsequent arguments",
4380 ".echo on|off Turn command echo on or off",
4381 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
4384 " test Show raw EXPLAIN QUERY PLAN output",
4385 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4387 " trigger Like \"full\" but also show trigger bytecode",
4388 #ifndef SQLITE_SHELL_FIDDLE
4389 ".excel Display the output of next command in spreadsheet",
4390 " --bom Put a UTF8 byte-order mark on intermediate file",
4392 #ifndef SQLITE_SHELL_FIDDLE
4393 ".exit ?CODE? Exit this program with return-code CODE",
4395 ".expert EXPERIMENTAL. Suggest indexes for queries",
4396 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto",
4397 ".filectrl CMD ... Run various sqlite3_file_control() operations",
4398 " --schema SCHEMA Use SCHEMA instead of \"main\"",
4399 " --help Show CMD details",
4400 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
4401 ".headers on|off Turn display of headers on or off",
4402 ".help ?-all? ?PATTERN? Show help text for PATTERN",
4403 #ifndef SQLITE_SHELL_FIDDLE
4404 ".import FILE TABLE Import data from FILE into TABLE",
4406 " --ascii Use \\037 and \\036 as column and row separators",
4407 " --csv Use , and \\n as column and row separators",
4408 " --skip N Skip the first N rows of input",
4409 " --schema S Target table to be S.TABLE",
4410 " -v \"Verbose\" - increase auxiliary output",
4412 " * If TABLE does not exist, it is created. The first row of input",
4413 " determines the column names.",
4414 " * If neither --csv or --ascii are used, the input mode is derived",
4415 " from the \".mode\" output mode",
4416 " * If FILE begins with \"|\" then it is a command that generates the",
4419 #ifndef SQLITE_OMIT_TEST_CONTROL
4420 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
4422 ".indexes ?TABLE? Show names of indexes",
4423 " If TABLE is specified, only show indexes for",
4424 " tables matching TABLE using the LIKE operator.",
4425 #ifdef SQLITE_ENABLE_IOTRACE
4426 ".iotrace FILE Enable I/O diagnostic logging to FILE",
4428 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
4429 ".lint OPTIONS Report potential schema issues.",
4431 " fkey-indexes Find missing foreign key indexes",
4432 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4433 ".load FILE ?ENTRY? Load an extension library",
4435 #ifndef SQLITE_SHELL_FIDDLE
4436 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
4438 ".mode MODE ?OPTIONS? Set output mode",
4440 " ascii Columns/rows delimited by 0x1F and 0x1E",
4441 " box Tables using unicode box-drawing characters",
4442 " csv Comma-separated values",
4443 " column Output in columns. (See .width)",
4444 " html HTML <table> code",
4445 " insert SQL insert statements for TABLE",
4446 " json Results in a JSON array",
4447 " line One value per line",
4448 " list Values delimited by \"|\"",
4449 " markdown Markdown table format",
4450 " qbox Shorthand for \"box --wrap 60 --quote\"",
4451 " quote Escape answers as for SQL",
4452 " table ASCII-art table",
4453 " tabs Tab-separated values",
4454 " tcl TCL list elements",
4455 " OPTIONS: (for columnar modes or insert mode):",
4456 " --wrap N Wrap output lines to no longer than N characters",
4457 " --wordwrap B Wrap or not at word boundaries per B (on/off)",
4458 " --ww Shorthand for \"--wordwrap 1\"",
4459 " --quote Quote output text as SQL literals",
4460 " --noquote Do not quote output text",
4461 " TABLE The name of SQL table used for \"insert\" mode",
4462 #ifndef SQLITE_SHELL_FIDDLE
4463 ".nonce STRING Suspend safe mode for one command if nonce matches",
4465 ".nullvalue STRING Use STRING in place of NULL values",
4466 #ifndef SQLITE_SHELL_FIDDLE
4467 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE",
4468 " If FILE begins with '|' then open as a pipe",
4469 " --bom Put a UTF8 byte-order mark at the beginning",
4470 " -e Send output to the system text editor",
4471 " -x Send output as CSV to a spreadsheet (same as \".excel\")",
4472 /* Note that .open is (partially) available in WASM builds but is
4473 ** currently only intended to be used by the fiddle tool, not
4474 ** end users, so is "undocumented." */
4475 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
4477 " --append Use appendvfs to append database to the end of FILE",
4479 #ifndef SQLITE_OMIT_DESERIALIZE
4480 " --deserialize Load into memory using sqlite3_deserialize()",
4481 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
4482 " --maxsize N Maximum size for --hexdb or --deserialized database",
4484 " --new Initialize FILE to an empty database",
4485 " --nofollow Do not follow symbolic links",
4486 " --readonly Open FILE readonly",
4487 " --zip FILE is a ZIP archive",
4488 #ifndef SQLITE_SHELL_FIDDLE
4489 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
4490 " If FILE begins with '|' then open it as a pipe.",
4492 " --bom Prefix output with a UTF8 byte-order mark",
4493 " -e Send output to the system text editor",
4494 " -x Send output as CSV to a spreadsheet",
4496 ".parameter CMD ... Manage SQL parameter bindings",
4497 " clear Erase all bindings",
4498 " init Initialize the TEMP table that holds bindings",
4499 " list List the current parameter bindings",
4500 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
4501 " PARAMETER should start with one of: $ : @ ?",
4502 " unset PARAMETER Remove PARAMETER from the binding table",
4503 ".print STRING... Print literal STRING",
4504 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4505 ".progress N Invoke progress handler after every N opcodes",
4506 " --limit N Interrupt after N progress callbacks",
4507 " --once Do no more than one progress interrupt",
4508 " --quiet|-q No output except at interrupts",
4509 " --reset Reset the count for each input and interrupt",
4511 ".prompt MAIN CONTINUE Replace the standard prompts",
4512 #ifndef SQLITE_SHELL_FIDDLE
4513 ".quit Exit this program",
4514 ".read FILE Read input from FILE or command output",
4515 " If FILE begins with \"|\", it is a command that generates the input.",
4517 #if SQLITE_SHELL_HAVE_RECOVER
4518 ".recover Recover as much data as possible from corrupt db.",
4519 " --ignore-freelist Ignore pages that appear to be on db freelist",
4520 " --lost-and-found TABLE Alternative name for the lost-and-found table",
4521 " --no-rowids Do not attempt to recover rowid values",
4522 " that are not also INTEGER PRIMARY KEYs",
4524 #ifndef SQLITE_SHELL_FIDDLE
4525 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
4526 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)",
4528 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
4529 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
4531 " --indent Try to pretty-print the schema",
4532 " --nosys Omit objects whose names start with \"sqlite_\"",
4533 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
4535 " --init Create a new SELFTEST table",
4536 " -v Verbose output",
4537 ".separator COL ?ROW? Change the column and row separators",
4538 #if defined(SQLITE_ENABLE_SESSION)
4539 ".session ?NAME? CMD ... Create or control sessions",
4541 " attach TABLE Attach TABLE",
4542 " changeset FILE Write a changeset into FILE",
4543 " close Close one session",
4544 " enable ?BOOLEAN? Set or query the enable bit",
4545 " filter GLOB... Reject tables matching GLOBs",
4546 " indirect ?BOOLEAN? Mark or query the indirect status",
4547 " isempty Query whether the session is empty",
4548 " list List currently open session names",
4549 " open DB NAME Open a new session on DB",
4550 " patchset FILE Write a patchset into FILE",
4551 " If ?NAME? is omitted, the first defined session is used.",
4553 ".sha3sum ... Compute a SHA3 hash of database content",
4555 " --schema Also hash the sqlite_schema table",
4556 " --sha3-224 Use the sha3-224 algorithm",
4557 " --sha3-256 Use the sha3-256 algorithm (default)",
4558 " --sha3-384 Use the sha3-384 algorithm",
4559 " --sha3-512 Use the sha3-512 algorithm",
4560 " Any other argument is a LIKE pattern for tables to hash",
4561 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4562 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
4564 ".show Show the current values for various settings",
4565 ".stats ?ARG? Show stats or turn stats on or off",
4566 " off Turn off automatic stat display",
4567 " on Turn on automatic stat display",
4568 " stmt Show statement stats",
4569 " vmstep Show the virtual machine step count only",
4570 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4571 ".system CMD ARGS... Run CMD ARGS... in a system shell",
4573 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
4574 #ifndef SQLITE_SHELL_FIDDLE
4575 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
4577 ".testctrl CMD ... Run various sqlite3_test_control() operations",
4578 " Run \".testctrl\" with no arguments for details",
4579 ".timeout MS Try opening locked tables for MS milliseconds",
4580 ".timer on|off Turn SQL timer on or off",
4581 #ifndef SQLITE_OMIT_TRACE
4582 ".trace ?OPTIONS? Output each SQL statement as it is run",
4583 " FILE Send output to FILE",
4584 " stdout Send output to stdout",
4585 " stderr Send output to stderr",
4586 " off Disable tracing",
4587 " --expanded Expand query parameters",
4588 #ifdef SQLITE_ENABLE_NORMALIZE
4589 " --normalized Normal the SQL statements",
4591 " --plain Show SQL as it is input",
4592 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
4593 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
4594 " --row Trace each row (SQLITE_TRACE_ROW)",
4595 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
4596 #endif /* SQLITE_OMIT_TRACE */
4598 ".unmodule NAME ... Unregister virtual table modules",
4599 " --allexcept Unregister everything except those named",
4601 ".vfsinfo ?AUX? Information about the top-level VFS",
4602 ".vfslist List all available VFSes",
4603 ".vfsname ?AUX? Print the name of the VFS stack",
4604 ".width NUM1 NUM2 ... Set minimum column widths for columnar output",
4605 " Negative values right-justify",
4609 ** Output help text.
4611 ** zPattern describes the set of commands for which help text is provided.
4612 ** If zPattern is NULL, then show all commands, but only give a one-line
4613 ** description of each.
4615 ** Return the number of matches.
4617 static int showHelp(FILE *out
, const char *zPattern
){
4624 || cli_strcmp(zPattern
,"-a")==0
4625 || cli_strcmp(zPattern
,"-all")==0
4626 || cli_strcmp(zPattern
,"--all")==0
4628 /* Show all commands, but only one line per command */
4629 if( zPattern
==0 ) zPattern
= "";
4630 for(i
=0; i
<ArraySize(azHelp
); i
++){
4631 if( azHelp
[i
][0]=='.' || zPattern
[0] ){
4632 utf8_printf(out
, "%s\n", azHelp
[i
]);
4637 /* Look for commands that for which zPattern is an exact prefix */
4638 zPat
= sqlite3_mprintf(".%s*", zPattern
);
4639 shell_check_oom(zPat
);
4640 for(i
=0; i
<ArraySize(azHelp
); i
++){
4641 if( sqlite3_strglob(zPat
, azHelp
[i
])==0 ){
4642 utf8_printf(out
, "%s\n", azHelp
[i
]);
4650 /* when zPattern is a prefix of exactly one command, then include the
4651 ** details of that command, which should begin at offset j */
4652 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
][0]!='.' ){
4653 utf8_printf(out
, "%s\n", azHelp
[j
]);
4659 /* Look for commands that contain zPattern anywhere. Show the complete
4660 ** text of all commands that match. */
4661 zPat
= sqlite3_mprintf("%%%s%%", zPattern
);
4662 shell_check_oom(zPat
);
4663 for(i
=0; i
<ArraySize(azHelp
); i
++){
4664 if( azHelp
[i
][0]=='.' ) j
= i
;
4665 if( sqlite3_strlike(zPat
, azHelp
[i
], 0)==0 ){
4666 utf8_printf(out
, "%s\n", azHelp
[j
]);
4667 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
+1][0]!='.' ){
4669 utf8_printf(out
, "%s\n", azHelp
[j
]);
4680 /* Forward reference */
4681 static int process_input(ShellState
*p
);
4684 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
4685 ** and return a pointer to the buffer. The caller is responsible for freeing
4688 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4691 ** For convenience, a nul-terminator byte is always appended to the data read
4692 ** from the file before the buffer is returned. This byte is not included in
4693 ** the final value of (*pnByte), if applicable.
4695 ** NULL is returned if any error is encountered. The final value of *pnByte
4696 ** is undefined in this case.
4698 static char *readFile(const char *zName
, int *pnByte
){
4699 FILE *in
= fopen(zName
, "rb");
4703 if( in
==0 ) return 0;
4704 fseek(in
, 0, SEEK_END
);
4707 pBuf
= sqlite3_malloc64( nIn
+1 );
4708 if( pBuf
==0 ){ fclose(in
); return 0; }
4709 nRead
= fread(pBuf
, nIn
, 1, in
);
4716 if( pnByte
) *pnByte
= nIn
;
4720 #if defined(SQLITE_ENABLE_SESSION)
4722 ** Close a single OpenSession object and release all of its associated
4725 static void session_close(OpenSession
*pSession
){
4727 sqlite3session_delete(pSession
->p
);
4728 sqlite3_free(pSession
->zName
);
4729 for(i
=0; i
<pSession
->nFilter
; i
++){
4730 sqlite3_free(pSession
->azFilter
[i
]);
4732 sqlite3_free(pSession
->azFilter
);
4733 memset(pSession
, 0, sizeof(OpenSession
));
4738 ** Close all OpenSession objects and release all associated resources.
4740 #if defined(SQLITE_ENABLE_SESSION)
4741 static void session_close_all(ShellState
*p
, int i
){
4743 struct AuxDb
*pAuxDb
= i
<0 ? p
->pAuxDb
: &p
->aAuxDb
[i
];
4744 for(j
=0; j
<pAuxDb
->nSession
; j
++){
4745 session_close(&pAuxDb
->aSession
[j
]);
4747 pAuxDb
->nSession
= 0;
4750 # define session_close_all(X,Y)
4754 ** Implementation of the xFilter function for an open session. Omit
4755 ** any tables named by ".session filter" but let all other table through.
4757 #if defined(SQLITE_ENABLE_SESSION)
4758 static int session_filter(void *pCtx
, const char *zTab
){
4759 OpenSession
*pSession
= (OpenSession
*)pCtx
;
4761 for(i
=0; i
<pSession
->nFilter
; i
++){
4762 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
4769 ** Try to deduce the type of file for zName based on its content. Return
4770 ** one of the SHELL_OPEN_* constants.
4772 ** If the file does not exist or is empty but its name looks like a ZIP
4773 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4774 ** Otherwise, assume an ordinary database regardless of the filename if
4775 ** the type cannot be determined from content.
4777 int deduceDatabaseType(const char *zName
, int dfltZip
){
4778 FILE *f
= fopen(zName
, "rb");
4780 int rc
= SHELL_OPEN_UNSPEC
;
4783 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
4784 return SHELL_OPEN_ZIPFILE
;
4786 return SHELL_OPEN_NORMAL
;
4789 n
= fread(zBuf
, 16, 1, f
);
4790 if( n
==1 && memcmp(zBuf
, "SQLite format 3", 16)==0 ){
4792 return SHELL_OPEN_NORMAL
;
4794 fseek(f
, -25, SEEK_END
);
4795 n
= fread(zBuf
, 25, 1, f
);
4796 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
4797 rc
= SHELL_OPEN_APPENDVFS
;
4799 fseek(f
, -22, SEEK_END
);
4800 n
= fread(zBuf
, 22, 1, f
);
4801 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
4803 rc
= SHELL_OPEN_ZIPFILE
;
4804 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
4805 rc
= SHELL_OPEN_ZIPFILE
;
4812 #ifndef SQLITE_OMIT_DESERIALIZE
4814 ** Reconstruct an in-memory database using the output from the "dbtotxt"
4815 ** program. Read content from the file in p->aAuxDb[].zDbFilename.
4816 ** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4818 static unsigned char *readHexDb(ShellState
*p
, int *pnData
){
4819 unsigned char *a
= 0;
4827 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
4831 in
= fopen(zDbFilename
, "r");
4833 utf8_printf(stderr
, "cannot open \"%s\" for reading\n", zDbFilename
);
4840 if( in
==0 ) in
= stdin
;
4844 if( fgets(zLine
, sizeof(zLine
), in
)==0 ) goto readHexDb_error
;
4845 rc
= sscanf(zLine
, "| size %d pagesize %d", &n
, &pgsz
);
4846 if( rc
!=2 ) goto readHexDb_error
;
4847 if( n
<0 ) goto readHexDb_error
;
4848 if( pgsz
<512 || pgsz
>65536 || (pgsz
&(pgsz
-1))!=0 ) goto readHexDb_error
;
4849 n
= (n
+pgsz
-1)&~(pgsz
-1); /* Round n up to the next multiple of pgsz */
4850 a
= sqlite3_malloc( n
? n
: 1 );
4853 if( pgsz
<512 || pgsz
>65536 || (pgsz
& (pgsz
-1))!=0 ){
4854 utf8_printf(stderr
, "invalid pagesize\n");
4855 goto readHexDb_error
;
4857 for(nLine
++; fgets(zLine
, sizeof(zLine
), in
)!=0; nLine
++){
4858 rc
= sscanf(zLine
, "| page %d offset %d", &j
, &k
);
4863 if( cli_strncmp(zLine
, "| end ", 6)==0 ){
4866 rc
= sscanf(zLine
,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4867 &j
, &x
[0], &x
[1], &x
[2], &x
[3], &x
[4], &x
[5], &x
[6], &x
[7],
4868 &x
[8], &x
[9], &x
[10], &x
[11], &x
[12], &x
[13], &x
[14], &x
[15]);
4871 if( k
+16<=n
&& k
>=0 ){
4873 for(ii
=0; ii
<16; ii
++) a
[k
+ii
] = x
[ii
]&0xff;
4889 while( fgets(zLine
, sizeof(zLine
), p
->in
)!=0 ){
4891 if(cli_strncmp(zLine
, "| end ", 6)==0 ) break;
4896 utf8_printf(stderr
,"Error on line %d of --hexdb input\n", nLine
);
4899 #endif /* SQLITE_OMIT_DESERIALIZE */
4902 ** Scalar function "shell_int32". The first argument to this function
4903 ** must be a blob. The second a non-negative integer. This function
4904 ** reads and returns a 32-bit big-endian integer from byte
4905 ** offset (4*<arg2>) of the blob.
4907 static void shellInt32(
4908 sqlite3_context
*context
,
4910 sqlite3_value
**argv
4912 const unsigned char *pBlob
;
4916 UNUSED_PARAMETER(argc
);
4917 nBlob
= sqlite3_value_bytes(argv
[0]);
4918 pBlob
= (const unsigned char*)sqlite3_value_blob(argv
[0]);
4919 iInt
= sqlite3_value_int(argv
[1]);
4921 if( iInt
>=0 && (iInt
+1)*4<=nBlob
){
4922 const unsigned char *a
= &pBlob
[iInt
*4];
4923 sqlite3_int64 iVal
= ((sqlite3_int64
)a
[0]<<24)
4924 + ((sqlite3_int64
)a
[1]<<16)
4925 + ((sqlite3_int64
)a
[2]<< 8)
4926 + ((sqlite3_int64
)a
[3]<< 0);
4927 sqlite3_result_int64(context
, iVal
);
4932 ** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4933 ** using "..." with internal double-quote characters doubled.
4935 static void shellIdQuote(
4936 sqlite3_context
*context
,
4938 sqlite3_value
**argv
4940 const char *zName
= (const char*)sqlite3_value_text(argv
[0]);
4941 UNUSED_PARAMETER(argc
);
4943 char *z
= sqlite3_mprintf("\"%w\"", zName
);
4944 sqlite3_result_text(context
, z
, -1, sqlite3_free
);
4949 ** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4951 static void shellUSleepFunc(
4952 sqlite3_context
*context
,
4954 sqlite3_value
**argv
4956 int sleep
= sqlite3_value_int(argv
[0]);
4958 sqlite3_sleep(sleep
/1000);
4959 sqlite3_result_int(context
, sleep
);
4963 ** Scalar function "shell_escape_crnl" used by the .recover command.
4964 ** The argument passed to this function is the output of built-in
4965 ** function quote(). If the first character of the input is "'",
4966 ** indicating that the value passed to quote() was a text value,
4967 ** then this function searches the input for "\n" and "\r" characters
4968 ** and adds a wrapper similar to the following:
4970 ** replace(replace(<input>, '\n', char(10), '\r', char(13));
4972 ** Or, if the first character of the input is not "'", then a copy
4973 ** of the input is returned.
4975 static void shellEscapeCrnl(
4976 sqlite3_context
*context
,
4978 sqlite3_value
**argv
4980 const char *zText
= (const char*)sqlite3_value_text(argv
[0]);
4981 UNUSED_PARAMETER(argc
);
4982 if( zText
&& zText
[0]=='\'' ){
4983 i64 nText
= sqlite3_value_bytes(argv
[0]);
4987 const char *zNL
= 0;
4988 const char *zCR
= 0;
4992 for(i
=0; zText
[i
]; i
++){
4993 if( zNL
==0 && zText
[i
]=='\n' ){
4994 zNL
= unused_string(zText
, "\\n", "\\012", zBuf1
);
4997 if( zCR
==0 && zText
[i
]=='\r' ){
4998 zCR
= unused_string(zText
, "\\r", "\\015", zBuf2
);
5005 i64 nMax
= (nNL
> nCR
) ? nNL
: nCR
;
5006 i64 nAlloc
= nMax
* nText
+ (nMax
+64)*2;
5007 char *zOut
= (char*)sqlite3_malloc64(nAlloc
);
5009 sqlite3_result_error_nomem(context
);
5014 memcpy(&zOut
[iOut
], "replace(replace(", 16);
5017 memcpy(&zOut
[iOut
], "replace(", 8);
5020 for(i
=0; zText
[i
]; i
++){
5021 if( zText
[i
]=='\n' ){
5022 memcpy(&zOut
[iOut
], zNL
, nNL
);
5024 }else if( zText
[i
]=='\r' ){
5025 memcpy(&zOut
[iOut
], zCR
, nCR
);
5028 zOut
[iOut
] = zText
[i
];
5034 memcpy(&zOut
[iOut
], ",'", 2); iOut
+= 2;
5035 memcpy(&zOut
[iOut
], zNL
, nNL
); iOut
+= nNL
;
5036 memcpy(&zOut
[iOut
], "', char(10))", 12); iOut
+= 12;
5039 memcpy(&zOut
[iOut
], ",'", 2); iOut
+= 2;
5040 memcpy(&zOut
[iOut
], zCR
, nCR
); iOut
+= nCR
;
5041 memcpy(&zOut
[iOut
], "', char(13))", 12); iOut
+= 12;
5044 sqlite3_result_text(context
, zOut
, iOut
, SQLITE_TRANSIENT
);
5050 sqlite3_result_value(context
, argv
[0]);
5053 /* Flags for open_db().
5055 ** The default behavior of open_db() is to exit(1) if the database fails to
5056 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5057 ** but still returns without calling exit.
5059 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5060 ** ZIP archive if the file does not exist or is empty and its name matches
5061 ** the *.zip pattern.
5063 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
5064 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
5067 ** Make sure the database is open. If it is not, then open it. If
5068 ** the database fails to open, print an error message and exit.
5070 static void open_db(ShellState
*p
, int openFlags
){
5072 const char *zDbFilename
= p
->pAuxDb
->zDbFilename
;
5073 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
5074 if( zDbFilename
==0 || zDbFilename
[0]==0 ){
5075 p
->openMode
= SHELL_OPEN_NORMAL
;
5077 p
->openMode
= (u8
)deduceDatabaseType(zDbFilename
,
5078 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
5081 switch( p
->openMode
){
5082 case SHELL_OPEN_APPENDVFS
: {
5083 sqlite3_open_v2(zDbFilename
, &p
->db
,
5084 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, "apndvfs");
5087 case SHELL_OPEN_HEXDB
:
5088 case SHELL_OPEN_DESERIALIZE
: {
5089 sqlite3_open(0, &p
->db
);
5092 case SHELL_OPEN_ZIPFILE
: {
5093 sqlite3_open(":memory:", &p
->db
);
5096 case SHELL_OPEN_READONLY
: {
5097 sqlite3_open_v2(zDbFilename
, &p
->db
,
5098 SQLITE_OPEN_READONLY
|p
->openFlags
, 0);
5101 case SHELL_OPEN_UNSPEC
:
5102 case SHELL_OPEN_NORMAL
: {
5103 sqlite3_open_v2(zDbFilename
, &p
->db
,
5104 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|p
->openFlags
, 0);
5109 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
5110 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
5111 zDbFilename
, sqlite3_errmsg(p
->db
));
5112 if( openFlags
& OPEN_DB_KEEPALIVE
){
5113 sqlite3_open(":memory:", &p
->db
);
5118 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5119 sqlite3_enable_load_extension(p
->db
, 1);
5121 sqlite3_shathree_init(p
->db
, 0, 0);
5122 sqlite3_uint_init(p
->db
, 0, 0);
5123 sqlite3_decimal_init(p
->db
, 0, 0);
5124 sqlite3_regexp_init(p
->db
, 0, 0);
5125 sqlite3_ieee_init(p
->db
, 0, 0);
5126 sqlite3_series_init(p
->db
, 0, 0);
5127 #ifndef SQLITE_SHELL_FIDDLE
5128 sqlite3_fileio_init(p
->db
, 0, 0);
5129 sqlite3_completion_init(p
->db
, 0, 0);
5131 #if SQLITE_SHELL_HAVE_RECOVER
5132 sqlite3_dbdata_init(p
->db
, 0, 0);
5134 #ifdef SQLITE_HAVE_ZLIB
5135 if( !p
->bSafeModePersist
){
5136 sqlite3_zipfile_init(p
->db
, 0, 0);
5137 sqlite3_sqlar_init(p
->db
, 0, 0);
5140 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
5141 shellAddSchemaName
, 0, 0);
5142 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
5143 shellModuleSchema
, 0, 0);
5144 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
5145 shellPutsFunc
, 0, 0);
5146 sqlite3_create_function(p
->db
, "shell_escape_crnl", 1, SQLITE_UTF8
, 0,
5147 shellEscapeCrnl
, 0, 0);
5148 sqlite3_create_function(p
->db
, "shell_int32", 2, SQLITE_UTF8
, 0,
5150 sqlite3_create_function(p
->db
, "shell_idquote", 1, SQLITE_UTF8
, 0,
5151 shellIdQuote
, 0, 0);
5152 sqlite3_create_function(p
->db
, "usleep",1,SQLITE_UTF8
,0,
5153 shellUSleepFunc
, 0, 0);
5154 #ifndef SQLITE_NOHAVE_SYSTEM
5155 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
5157 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
5160 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
5161 char *zSql
= sqlite3_mprintf(
5162 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename
);
5163 shell_check_oom(zSql
);
5164 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
5167 #ifndef SQLITE_OMIT_DESERIALIZE
5169 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
|| p
->openMode
==SHELL_OPEN_HEXDB
){
5172 unsigned char *aData
;
5173 if( p
->openMode
==SHELL_OPEN_DESERIALIZE
){
5174 aData
= (unsigned char*)readFile(zDbFilename
, &nData
);
5176 aData
= readHexDb(p
, &nData
);
5181 rc
= sqlite3_deserialize(p
->db
, "main", aData
, nData
, nData
,
5182 SQLITE_DESERIALIZE_RESIZEABLE
|
5183 SQLITE_DESERIALIZE_FREEONCLOSE
);
5185 utf8_printf(stderr
, "Error: sqlite3_deserialize() returns %d\n", rc
);
5188 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_SIZE_LIMIT
, &p
->szMax
);
5193 if( p
->bSafeModePersist
&& p
->db
!=0 ){
5194 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
5199 ** Attempt to close the databaes connection. Report errors.
5201 void close_db(sqlite3
*db
){
5202 int rc
= sqlite3_close(db
);
5204 utf8_printf(stderr
, "Error: sqlite3_close() returns %d: %s\n",
5205 rc
, sqlite3_errmsg(db
));
5209 #if HAVE_READLINE || HAVE_EDITLINE
5211 ** Readline completion callbacks
5213 static char *readline_completion_generator(const char *text
, int state
){
5214 static sqlite3_stmt
*pStmt
= 0;
5218 sqlite3_finalize(pStmt
);
5219 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5220 " FROM completion(%Q) ORDER BY 1", text
);
5221 shell_check_oom(zSql
);
5222 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5225 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
5226 const char *z
= (const char*)sqlite3_column_text(pStmt
,0);
5227 zRet
= z
? strdup(z
) : 0;
5229 sqlite3_finalize(pStmt
);
5235 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
5236 rl_attempted_completion_over
= 1;
5237 return rl_completion_matches(zText
, readline_completion_generator
);
5240 #elif HAVE_LINENOISE
5242 ** Linenoise completion callback
5244 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
5245 i64 nLine
= strlen(zLine
);
5247 sqlite3_stmt
*pStmt
= 0;
5251 if( nLine
>sizeof(zBuf
)-30 ) return;
5252 if( zLine
[0]=='.' || zLine
[0]=='#') return;
5253 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
5254 if( i
==nLine
-1 ) return;
5256 memcpy(zBuf
, zLine
, iStart
);
5257 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5258 " FROM completion(%Q,%Q) ORDER BY 1",
5259 &zLine
[iStart
], zLine
);
5260 shell_check_oom(zSql
);
5261 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
5263 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5264 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5265 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
5266 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
5267 if( iStart
+nCompletion
< sizeof(zBuf
)-1 && zCompletion
){
5268 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
5269 linenoiseAddCompletion(lc
, zBuf
);
5272 sqlite3_finalize(pStmt
);
5277 ** Do C-language style dequoting.
5283 ** \v -> vertical tab
5285 ** \r -> carriage return
5290 ** \NNN -> ascii character NNN in octal
5292 static void resolve_backslashes(char *z
){
5295 while( *z
&& *z
!='\\' ) z
++;
5296 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
5297 if( c
=='\\' && z
[i
+1]!=0 ){
5315 }else if( c
=='\'' ){
5317 }else if( c
=='\\' ){
5319 }else if( c
>='0' && c
<='7' ){
5321 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5323 c
= (c
<<3) + z
[i
] - '0';
5324 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
5326 c
= (c
<<3) + z
[i
] - '0';
5337 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
5338 ** for TRUE and FALSE. Return the integer value if appropriate.
5340 static int booleanValue(const char *zArg
){
5342 if( zArg
[0]=='0' && zArg
[1]=='x' ){
5343 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
5345 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
5347 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
5348 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
5351 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
5354 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5360 ** Set or clear a shell flag according to a boolean value.
5362 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
5363 if( booleanValue(zArg
) ){
5364 ShellSetFlag(p
, mFlag
);
5366 ShellClearFlag(p
, mFlag
);
5371 ** Close an output file, assuming it is not stderr or stdout
5373 static void output_file_close(FILE *f
){
5374 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
5378 ** Try to open an output file. The names "stdout" and "stderr" are
5379 ** recognized and do the right thing. NULL is returned if the output
5380 ** filename is "off".
5382 static FILE *output_file_open(const char *zFile
, int bTextMode
){
5384 if( cli_strcmp(zFile
,"stdout")==0 ){
5386 }else if( cli_strcmp(zFile
, "stderr")==0 ){
5388 }else if( cli_strcmp(zFile
, "off")==0 ){
5391 f
= fopen(zFile
, bTextMode
? "w" : "wb");
5393 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
5399 #ifndef SQLITE_OMIT_TRACE
5401 ** A routine for handling output from sqlite3_trace().
5403 static int sql_trace_callback(
5404 unsigned mType
, /* The trace type */
5405 void *pArg
, /* The ShellState pointer */
5406 void *pP
, /* Usually a pointer to sqlite_stmt */
5407 void *pX
/* Auxiliary output */
5409 ShellState
*p
= (ShellState
*)pArg
;
5410 sqlite3_stmt
*pStmt
;
5413 if( p
->traceOut
==0 ) return 0;
5414 if( mType
==SQLITE_TRACE_CLOSE
){
5415 utf8_printf(p
->traceOut
, "-- closing database connection\n");
5418 if( mType
!=SQLITE_TRACE_ROW
&& ((const char*)pX
)[0]=='-' ){
5419 zSql
= (const char*)pX
;
5421 pStmt
= (sqlite3_stmt
*)pP
;
5422 switch( p
->eTraceType
){
5423 case SHELL_TRACE_EXPANDED
: {
5424 zSql
= sqlite3_expanded_sql(pStmt
);
5427 #ifdef SQLITE_ENABLE_NORMALIZE
5428 case SHELL_TRACE_NORMALIZED
: {
5429 zSql
= sqlite3_normalized_sql(pStmt
);
5434 zSql
= sqlite3_sql(pStmt
);
5439 if( zSql
==0 ) return 0;
5440 nSql
= strlen(zSql
);
5441 if( nSql
>1000000000 ) nSql
= 1000000000;
5442 while( nSql
>0 && zSql
[nSql
-1]==';' ){ nSql
--; }
5444 case SQLITE_TRACE_ROW
:
5445 case SQLITE_TRACE_STMT
: {
5446 utf8_printf(p
->traceOut
, "%.*s;\n", (int)nSql
, zSql
);
5449 case SQLITE_TRACE_PROFILE
: {
5450 sqlite3_int64 nNanosec
= *(sqlite3_int64
*)pX
;
5451 utf8_printf(p
->traceOut
, "%.*s; -- %lld ns\n", (int)nSql
, zSql
, nNanosec
);
5460 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
5461 ** a useful spot to set a debugger breakpoint.
5463 static void test_breakpoint(void){
5464 static int nCall
= 0;
5469 ** An object used to read a CSV and other files for import.
5471 typedef struct ImportCtx ImportCtx
;
5473 const char *zFile
; /* Name of the input file */
5474 FILE *in
; /* Read the CSV text from this input stream */
5475 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close in */
5476 char *z
; /* Accumulated text for a field */
5477 int n
; /* Number of bytes in z */
5478 int nAlloc
; /* Space allocated for z[] */
5479 int nLine
; /* Current line number */
5480 int nRow
; /* Number of rows imported */
5481 int nErr
; /* Number of errors encountered */
5482 int bNotFirst
; /* True if one or more bytes already read */
5483 int cTerm
; /* Character that terminated the most recent field */
5484 int cColSep
; /* The column separator character. (Usually ",") */
5485 int cRowSep
; /* The row separator character. (Usually "\n") */
5488 /* Clean up resourced used by an ImportCtx */
5489 static void import_cleanup(ImportCtx
*p
){
5490 if( p
->in
!=0 && p
->xCloser
!=0 ){
5498 /* Append a single byte to z[] */
5499 static void import_append_char(ImportCtx
*p
, int c
){
5500 if( p
->n
+1>=p
->nAlloc
){
5501 p
->nAlloc
+= p
->nAlloc
+ 100;
5502 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
5503 shell_check_oom(p
->z
);
5505 p
->z
[p
->n
++] = (char)c
;
5508 /* Read a single field of CSV text. Compatible with rfc4180 and extended
5509 ** with the option of having a separator other than ",".
5511 ** + Input comes from p->in.
5512 ** + Store results in p->z of length p->n. Space to hold p->z comes
5513 ** from sqlite3_malloc64().
5514 ** + Use p->cSep as the column separator. The default is ",".
5515 ** + Use p->rSep as the row separator. The default is "\n".
5516 ** + Keep track of the line number in p->nLine.
5517 ** + Store the character that terminates the field in p->cTerm. Store
5518 ** EOF on end-of-file.
5519 ** + Report syntax errors on stderr
5521 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
5523 int cSep
= p
->cColSep
;
5524 int rSep
= p
->cRowSep
;
5527 if( c
==EOF
|| seenInterrupt
){
5533 int startLine
= p
->nLine
;
5538 if( c
==rSep
) p
->nLine
++;
5545 if( (c
==cSep
&& pc
==cQuote
)
5546 || (c
==rSep
&& pc
==cQuote
)
5547 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
5548 || (c
==EOF
&& pc
==cQuote
)
5550 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
5554 if( pc
==cQuote
&& c
!='\r' ){
5555 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
5556 p
->zFile
, p
->nLine
, cQuote
);
5559 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
5560 p
->zFile
, startLine
, cQuote
);
5564 import_append_char(p
, c
);
5569 /* If this is the first field being parsed and it begins with the
5570 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
5571 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
5572 import_append_char(p
, c
);
5574 if( (c
&0xff)==0xbb ){
5575 import_append_char(p
, c
);
5577 if( (c
&0xff)==0xbf ){
5580 return csv_read_one_field(p
);
5584 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5585 import_append_char(p
, c
);
5590 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
5594 if( p
->z
) p
->z
[p
->n
] = 0;
5599 /* Read a single field of ASCII delimited text.
5601 ** + Input comes from p->in.
5602 ** + Store results in p->z of length p->n. Space to hold p->z comes
5603 ** from sqlite3_malloc64().
5604 ** + Use p->cSep as the column separator. The default is "\x1F".
5605 ** + Use p->rSep as the row separator. The default is "\x1E".
5606 ** + Keep track of the row number in p->nLine.
5607 ** + Store the character that terminates the field in p->cTerm. Store
5608 ** EOF on end-of-file.
5609 ** + Report syntax errors on stderr
5611 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
5613 int cSep
= p
->cColSep
;
5614 int rSep
= p
->cRowSep
;
5617 if( c
==EOF
|| seenInterrupt
){
5621 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
5622 import_append_char(p
, c
);
5629 if( p
->z
) p
->z
[p
->n
] = 0;
5634 ** Try to transfer data for table zTable. If an error is seen while
5635 ** moving forward, try to go backwards. The backwards movement won't
5636 ** work for WITHOUT ROWID tables.
5638 static void tryToCloneData(
5643 sqlite3_stmt
*pQuery
= 0;
5644 sqlite3_stmt
*pInsert
= 0;
5649 int nTable
= strlen30(zTable
);
5652 const int spinRate
= 10000;
5654 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
5655 shell_check_oom(zQuery
);
5656 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5658 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
5659 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
5663 n
= sqlite3_column_count(pQuery
);
5664 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
5665 shell_check_oom(zInsert
);
5666 sqlite3_snprintf(200+nTable
,zInsert
,
5667 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
5668 i
= strlen30(zInsert
);
5670 memcpy(zInsert
+i
, ",?", 2);
5673 memcpy(zInsert
+i
, ");", 3);
5674 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
5676 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
5677 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
5682 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
5684 switch( sqlite3_column_type(pQuery
, i
) ){
5686 sqlite3_bind_null(pInsert
, i
+1);
5689 case SQLITE_INTEGER
: {
5690 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
5693 case SQLITE_FLOAT
: {
5694 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
5698 sqlite3_bind_text(pInsert
, i
+1,
5699 (const char*)sqlite3_column_text(pQuery
,i
),
5704 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
5705 sqlite3_column_bytes(pQuery
,i
),
5711 rc
= sqlite3_step(pInsert
);
5712 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
5713 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
5714 sqlite3_errmsg(newDb
));
5716 sqlite3_reset(pInsert
);
5718 if( (cnt
%spinRate
)==0 ){
5719 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
5723 if( rc
==SQLITE_DONE
) break;
5724 sqlite3_finalize(pQuery
);
5725 sqlite3_free(zQuery
);
5726 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5728 shell_check_oom(zQuery
);
5729 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5731 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
5734 } /* End for(k=0...) */
5737 sqlite3_finalize(pQuery
);
5738 sqlite3_finalize(pInsert
);
5739 sqlite3_free(zQuery
);
5740 sqlite3_free(zInsert
);
5745 ** Try to transfer all rows of the schema that match zWhere. For
5746 ** each row, invoke xForEach() on the object defined by that row.
5747 ** If an error is encountered while moving forward through the
5748 ** sqlite_schema table, try again moving backwards.
5750 static void tryToCloneSchema(
5754 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
5756 sqlite3_stmt
*pQuery
= 0;
5759 const unsigned char *zName
;
5760 const unsigned char *zSql
;
5763 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5764 " WHERE %s", zWhere
);
5765 shell_check_oom(zQuery
);
5766 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5768 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
5769 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
5771 goto end_schema_xfer
;
5773 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
5774 zName
= sqlite3_column_text(pQuery
, 0);
5775 zSql
= sqlite3_column_text(pQuery
, 1);
5776 if( zName
==0 || zSql
==0 ) continue;
5777 printf("%s... ", zName
); fflush(stdout
);
5778 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
5780 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
5781 sqlite3_free(zErrMsg
);
5785 xForEach(p
, newDb
, (const char*)zName
);
5789 if( rc
!=SQLITE_DONE
){
5790 sqlite3_finalize(pQuery
);
5791 sqlite3_free(zQuery
);
5792 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5793 " WHERE %s ORDER BY rowid DESC", zWhere
);
5794 shell_check_oom(zQuery
);
5795 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
5797 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
5798 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
5800 goto end_schema_xfer
;
5802 while( sqlite3_step(pQuery
)==SQLITE_ROW
){
5803 zName
= sqlite3_column_text(pQuery
, 0);
5804 zSql
= sqlite3_column_text(pQuery
, 1);
5805 if( zName
==0 || zSql
==0 ) continue;
5806 printf("%s... ", zName
); fflush(stdout
);
5807 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
5809 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
5810 sqlite3_free(zErrMsg
);
5814 xForEach(p
, newDb
, (const char*)zName
);
5820 sqlite3_finalize(pQuery
);
5821 sqlite3_free(zQuery
);
5825 ** Open a new database file named "zNewDb". Try to recover as much information
5826 ** as possible out of the main database (which might be corrupt) and write it
5829 static void tryToClone(ShellState
*p
, const char *zNewDb
){
5832 if( access(zNewDb
,0)==0 ){
5833 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
5836 rc
= sqlite3_open(zNewDb
, &newDb
);
5838 utf8_printf(stderr
, "Cannot create output database: %s\n",
5839 sqlite3_errmsg(newDb
));
5841 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
5842 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
5843 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
5844 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
5845 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
5846 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5852 ** Change the output file back to stdout.
5854 ** If the p->doXdgOpen flag is set, that means the output was being
5855 ** redirected to a temporary file named by p->zTempFile. In that case,
5856 ** launch start/open/xdg-open on that temporary file.
5858 static void output_reset(ShellState
*p
){
5859 if( p
->outfile
[0]=='|' ){
5860 #ifndef SQLITE_OMIT_POPEN
5864 output_file_close(p
->out
);
5865 #ifndef SQLITE_NOHAVE_SYSTEM
5867 const char *zXdgOpenCmd
=
5870 #elif defined(__APPLE__)
5876 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
5878 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
5880 /* Give the start/open/xdg-open command some time to get
5881 ** going before we continue, and potential delete the
5882 ** p->zTempFile data file out from under it */
5883 sqlite3_sleep(2000);
5889 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5896 ** Run an SQL command and return the single integer result.
5898 static int db_int(sqlite3
*db
, const char *zSql
){
5899 sqlite3_stmt
*pStmt
;
5901 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
5902 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
5903 res
= sqlite3_column_int(pStmt
,0);
5905 sqlite3_finalize(pStmt
);
5909 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5911 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
5913 static unsigned int get2byteInt(unsigned char *a
){
5914 return (a
[0]<<8) + a
[1];
5916 static unsigned int get4byteInt(unsigned char *a
){
5917 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
5921 ** Implementation of the ".dbinfo" command.
5923 ** Return 1 on error, 2 to exit, and 0 otherwise.
5925 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
5926 static const struct { const char *zName
; int ofst
; } aField
[] = {
5927 { "file change counter:", 24 },
5928 { "database page count:", 28 },
5929 { "freelist page count:", 36 },
5930 { "schema cookie:", 40 },
5931 { "schema format:", 44 },
5932 { "default cache size:", 48 },
5933 { "autovacuum top root:", 52 },
5934 { "incremental vacuum:", 64 },
5935 { "text encoding:", 56 },
5936 { "user version:", 60 },
5937 { "application id:", 68 },
5938 { "software version:", 96 },
5940 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
5941 { "number of tables:",
5942 "SELECT count(*) FROM %s WHERE type='table'" },
5943 { "number of indexes:",
5944 "SELECT count(*) FROM %s WHERE type='index'" },
5945 { "number of triggers:",
5946 "SELECT count(*) FROM %s WHERE type='trigger'" },
5947 { "number of views:",
5948 "SELECT count(*) FROM %s WHERE type='view'" },
5950 "SELECT total(length(sql)) FROM %s" },
5953 unsigned iDataVersion
;
5955 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
5956 sqlite3_stmt
*pStmt
= 0;
5957 unsigned char aHdr
[100];
5959 if( p
->db
==0 ) return 1;
5960 rc
= sqlite3_prepare_v2(p
->db
,
5961 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5964 utf8_printf(stderr
, "error: %s\n", sqlite3_errmsg(p
->db
));
5965 sqlite3_finalize(pStmt
);
5968 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
5969 if( sqlite3_step(pStmt
)==SQLITE_ROW
5970 && sqlite3_column_bytes(pStmt
,0)>100
5972 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
5973 sqlite3_finalize(pStmt
);
5975 raw_printf(stderr
, "unable to read database header\n");
5976 sqlite3_finalize(pStmt
);
5979 i
= get2byteInt(aHdr
+16);
5980 if( i
==1 ) i
= 65536;
5981 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
5982 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
5983 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
5984 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
5985 for(i
=0; i
<ArraySize(aField
); i
++){
5986 int ofst
= aField
[i
].ofst
;
5987 unsigned int val
= get4byteInt(aHdr
+ ofst
);
5988 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
5991 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
5992 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
5993 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
5996 raw_printf(p
->out
, "\n");
5999 zSchemaTab
= sqlite3_mprintf("main.sqlite_schema");
6000 }else if( cli_strcmp(zDb
,"temp")==0 ){
6001 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_schema");
6003 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_schema", zDb
);
6005 for(i
=0; i
<ArraySize(aQuery
); i
++){
6006 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
6007 int val
= db_int(p
->db
, zSql
);
6009 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
6011 sqlite3_free(zSchemaTab
);
6012 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_DATA_VERSION
, &iDataVersion
);
6013 utf8_printf(p
->out
, "%-20s %u\n", "data version", iDataVersion
);
6016 #endif /* SQLITE_SHELL_HAVE_RECOVER */
6019 ** Print the current sqlite3_errmsg() value to stderr and return 1.
6021 static int shellDatabaseError(sqlite3
*db
){
6022 const char *zErr
= sqlite3_errmsg(db
);
6023 utf8_printf(stderr
, "Error: %s\n", zErr
);
6028 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
6029 ** if they match and FALSE (0) if they do not match.
6033 ** '*' Matches any sequence of zero or more characters.
6035 ** '?' Matches exactly one character.
6037 ** [...] Matches one character from the enclosed list of
6040 ** [^...] Matches one character not in the enclosed list.
6042 ** '#' Matches any sequence of one or more digits with an
6043 ** optional + or - sign in front
6045 ** ' ' Any span of whitespace matches any other span of
6048 ** Extra whitespace at the end of z[] is ignored.
6050 static int testcase_glob(const char *zGlob
, const char *z
){
6055 while( (c
= (*(zGlob
++)))!=0 ){
6057 if( !IsSpace(*z
) ) return 0;
6058 while( IsSpace(*zGlob
) ) zGlob
++;
6059 while( IsSpace(*z
) ) z
++;
6061 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
6062 if( c
=='?' && (*(z
++))==0 ) return 0;
6067 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
6072 while( (c2
= (*(z
++)))!=0 ){
6075 if( c2
==0 ) return 0;
6077 if( testcase_glob(zGlob
,z
) ) return 1;
6081 if( (*(z
++))==0 ) return 0;
6087 if( c
==0 ) return 0;
6094 if( c
==']' ) seen
= 1;
6097 while( c2
&& c2
!=']' ){
6098 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
6100 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
6110 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
6112 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
6113 if( !IsDigit(z
[0]) ) return 0;
6115 while( IsDigit(z
[0]) ){ z
++; }
6117 if( c
!=(*(z
++)) ) return 0;
6120 while( IsSpace(*z
) ){ z
++; }
6126 ** Compare the string as a command-line option with either one or two
6127 ** initial "-" characters.
6129 static int optionMatch(const char *zStr
, const char *zOpt
){
6130 if( zStr
[0]!='-' ) return 0;
6132 if( zStr
[0]=='-' ) zStr
++;
6133 return cli_strcmp(zStr
, zOpt
)==0;
6139 int shellDeleteFile(const char *zFilename
){
6142 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
6146 rc
= unlink(zFilename
);
6152 ** Try to delete the temporary file (if there is one) and free the
6153 ** memory used to hold the name of the temp file.
6155 static void clearTempFile(ShellState
*p
){
6156 if( p
->zTempFile
==0 ) return;
6157 if( p
->doXdgOpen
) return;
6158 if( shellDeleteFile(p
->zTempFile
) ) return;
6159 sqlite3_free(p
->zTempFile
);
6164 ** Create a new temp file name with the given suffix.
6166 static void newTempFile(ShellState
*p
, const char *zSuffix
){
6168 sqlite3_free(p
->zTempFile
);
6171 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
6173 if( p
->zTempFile
==0 ){
6174 /* If p->db is an in-memory database then the TEMPFILENAME file-control
6175 ** will not work and we will need to fallback to guessing */
6178 sqlite3_randomness(sizeof(r
), &r
);
6179 zTemp
= getenv("TEMP");
6180 if( zTemp
==0 ) zTemp
= getenv("TMP");
6188 p
->zTempFile
= sqlite3_mprintf("%s/temp%llx.%s", zTemp
, r
, zSuffix
);
6190 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
6192 shell_check_oom(p
->zTempFile
);
6197 ** The implementation of SQL scalar function fkey_collate_clause(), used
6198 ** by the ".lint fkey-indexes" command. This scalar function is always
6199 ** called with four arguments - the parent table name, the parent column name,
6200 ** the child table name and the child column name.
6202 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6204 ** If either of the named tables or columns do not exist, this function
6205 ** returns an empty string. An empty string is also returned if both tables
6206 ** and columns exist but have the same default collation sequence. Or,
6207 ** if both exist but the default collation sequences are different, this
6208 ** function returns the string " COLLATE <parent-collation>", where
6209 ** <parent-collation> is the default collation sequence of the parent column.
6211 static void shellFkeyCollateClause(
6212 sqlite3_context
*pCtx
,
6214 sqlite3_value
**apVal
6216 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
6217 const char *zParent
;
6218 const char *zParentCol
;
6219 const char *zParentSeq
;
6221 const char *zChildCol
;
6222 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
6226 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
6227 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
6228 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
6229 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
6231 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
6232 rc
= sqlite3_table_column_metadata(
6233 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
6235 if( rc
==SQLITE_OK
){
6236 rc
= sqlite3_table_column_metadata(
6237 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
6241 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
6242 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
6243 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
6250 ** The implementation of dot-command ".lint fkey-indexes".
6252 static int lintFkeyIndexes(
6253 ShellState
*pState
, /* Current shell tool state */
6254 char **azArg
, /* Array of arguments passed to dot command */
6255 int nArg
/* Number of entries in azArg[] */
6257 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
6258 FILE *out
= pState
->out
; /* Stream to write non-error output to */
6259 int bVerbose
= 0; /* If -verbose is present */
6260 int bGroupByParent
= 0; /* If -groupbyparent is present */
6261 int i
; /* To iterate through azArg[] */
6262 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
6263 int rc
; /* Return code */
6264 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
6267 ** This SELECT statement returns one row for each foreign key constraint
6268 ** in the schema of the main database. The column values are:
6270 ** 0. The text of an SQL statement similar to:
6272 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6274 ** This SELECT is similar to the one that the foreign keys implementation
6275 ** needs to run internally on child tables. If there is an index that can
6276 ** be used to optimize this query, then it can also be used by the FK
6277 ** implementation to optimize DELETE or UPDATE statements on the parent
6280 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6281 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6282 ** contains an index that can be used to optimize the query.
6284 ** 2. Human readable text that describes the child table and columns. e.g.
6286 ** "child_table(child_key1, child_key2)"
6288 ** 3. Human readable text that describes the parent table and columns. e.g.
6290 ** "parent_table(parent_key1, parent_key2)"
6292 ** 4. A full CREATE INDEX statement for an index that could be used to
6293 ** optimize DELETE or UPDATE statements on the parent table. e.g.
6295 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
6297 ** 5. The name of the parent table.
6299 ** These six values are used by the C logic below to generate the report.
6303 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6304 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6305 " || fkey_collate_clause("
6306 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6308 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6309 " || group_concat('*=?', ' AND ') || ')'"
6311 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
6313 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6315 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6316 " || ' ON ' || quote(s.name) || '('"
6317 " || group_concat(quote(f.[from]) ||"
6318 " fkey_collate_clause("
6319 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6323 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6324 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6325 "GROUP BY s.name, f.id "
6326 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6328 const char *zGlobIPK
= "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6330 for(i
=2; i
<nArg
; i
++){
6331 int n
= strlen30(azArg
[i
]);
6332 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
6335 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
6340 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6343 return SQLITE_ERROR
;
6347 /* Register the fkey_collate_clause() SQL function */
6348 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
6349 0, shellFkeyCollateClause
, 0, 0
6353 if( rc
==SQLITE_OK
){
6354 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
6356 if( rc
==SQLITE_OK
){
6357 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
6360 if( rc
==SQLITE_OK
){
6363 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
6365 sqlite3_stmt
*pExplain
= 0;
6366 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
6367 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
6368 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
6369 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
6370 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
6371 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
6373 if( zEQP
==0 ) continue;
6374 if( zGlob
==0 ) continue;
6375 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
6376 if( rc
!=SQLITE_OK
) break;
6377 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
6378 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
6379 res
= zPlan
!=0 && ( 0==sqlite3_strglob(zGlob
, zPlan
)
6380 || 0==sqlite3_strglob(zGlobIPK
, zPlan
));
6382 rc
= sqlite3_finalize(pExplain
);
6383 if( rc
!=SQLITE_OK
) break;
6386 raw_printf(stderr
, "Error: internal error");
6390 && (bVerbose
|| res
==0)
6391 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
6393 raw_printf(out
, "-- Parent table %s\n", zParent
);
6394 sqlite3_free(zPrev
);
6395 zPrev
= sqlite3_mprintf("%s", zParent
);
6399 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
6400 }else if( bVerbose
){
6401 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
6402 zIndent
, zFrom
, zTarget
6407 sqlite3_free(zPrev
);
6409 if( rc
!=SQLITE_OK
){
6410 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6413 rc2
= sqlite3_finalize(pSql
);
6414 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
6416 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6419 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
6426 ** Implementation of ".lint" dot command.
6428 static int lintDotCommand(
6429 ShellState
*pState
, /* Current shell tool state */
6430 char **azArg
, /* Array of arguments passed to dot command */
6431 int nArg
/* Number of entries in azArg[] */
6434 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
6435 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
6436 return lintFkeyIndexes(pState
, azArg
, nArg
);
6439 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
6440 raw_printf(stderr
, "Where sub-commands are:\n");
6441 raw_printf(stderr
, " fkey-indexes\n");
6442 return SQLITE_ERROR
;
6445 #if !defined SQLITE_OMIT_VIRTUALTABLE
6446 static void shellPrepare(
6450 sqlite3_stmt
**ppStmt
6453 if( *pRc
==SQLITE_OK
){
6454 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
6455 if( rc
!=SQLITE_OK
){
6456 raw_printf(stderr
, "sql error: %s (%d)\n",
6457 sqlite3_errmsg(db
), sqlite3_errcode(db
)
6465 ** Create a prepared statement using printf-style arguments for the SQL.
6467 ** This routine is could be marked "static". But it is not always used,
6468 ** depending on compile-time options. By omitting the "static", we avoid
6469 ** nuisance compiler warnings about "defined but not used".
6471 void shellPreparePrintf(
6474 sqlite3_stmt
**ppStmt
,
6479 if( *pRc
==SQLITE_OK
){
6483 z
= sqlite3_vmprintf(zFmt
, ap
);
6486 *pRc
= SQLITE_NOMEM
;
6488 shellPrepare(db
, pRc
, z
, ppStmt
);
6494 /* Finalize the prepared statement created using shellPreparePrintf().
6496 ** This routine is could be marked "static". But it is not always used,
6497 ** depending on compile-time options. By omitting the "static", we avoid
6498 ** nuisance compiler warnings about "defined but not used".
6505 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6506 int rc
= sqlite3_finalize(pStmt
);
6507 if( *pRc
==SQLITE_OK
){
6508 if( rc
!=SQLITE_OK
){
6509 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
6516 /* Reset the prepared statement created using shellPreparePrintf().
6518 ** This routine is could be marked "static". But it is not always used,
6519 ** depending on compile-time options. By omitting the "static", we avoid
6520 ** nuisance compiler warnings about "defined but not used".
6526 int rc
= sqlite3_reset(pStmt
);
6527 if( *pRc
==SQLITE_OK
){
6528 if( rc
!=SQLITE_OK
){
6529 sqlite3
*db
= sqlite3_db_handle(pStmt
);
6530 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
6535 #endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6537 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6538 /******************************************************************************
6539 ** The ".archive" or ".ar" command.
6542 ** Structure representing a single ".ar" command.
6544 typedef struct ArCommand ArCommand
;
6546 u8 eCmd
; /* An AR_CMD_* value */
6547 u8 bVerbose
; /* True if --verbose */
6548 u8 bZip
; /* True if the archive is a ZIP */
6549 u8 bDryRun
; /* True if --dry-run */
6550 u8 bAppend
; /* True if --append */
6551 u8 bGlob
; /* True if --glob */
6552 u8 fromCmdLine
; /* Run from -A instead of .archive */
6553 int nArg
; /* Number of command arguments */
6554 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
6555 const char *zFile
; /* --file argument, or NULL */
6556 const char *zDir
; /* --directory argument, or NULL */
6557 char **azArg
; /* Array of command arguments */
6558 ShellState
*p
; /* Shell state */
6559 sqlite3
*db
; /* Database containing the archive */
6563 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6565 static int arUsage(FILE *f
){
6566 showHelp(f
,"archive");
6567 return SQLITE_ERROR
;
6571 ** Print an error message for the .ar command to stderr and return
6574 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
6578 z
= sqlite3_vmprintf(zFmt
, ap
);
6580 utf8_printf(stderr
, "Error: %s\n", z
);
6581 if( pAr
->fromCmdLine
){
6582 utf8_printf(stderr
, "Use \"-A\" for more help\n");
6584 utf8_printf(stderr
, "Use \".archive --help\" for more help\n");
6587 return SQLITE_ERROR
;
6591 ** Values for ArCommand.eCmd.
6593 #define AR_CMD_CREATE 1
6594 #define AR_CMD_UPDATE 2
6595 #define AR_CMD_INSERT 3
6596 #define AR_CMD_EXTRACT 4
6597 #define AR_CMD_LIST 5
6598 #define AR_CMD_HELP 6
6599 #define AR_CMD_REMOVE 7
6602 ** Other (non-command) switches.
6604 #define AR_SWITCH_VERBOSE 8
6605 #define AR_SWITCH_FILE 9
6606 #define AR_SWITCH_DIRECTORY 10
6607 #define AR_SWITCH_APPEND 11
6608 #define AR_SWITCH_DRYRUN 12
6609 #define AR_SWITCH_GLOB 13
6611 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
6614 case AR_CMD_EXTRACT
:
6621 return arErrorMsg(pAr
, "multiple command options");
6623 pAr
->eCmd
= eSwitch
;
6626 case AR_SWITCH_DRYRUN
:
6629 case AR_SWITCH_GLOB
:
6632 case AR_SWITCH_VERBOSE
:
6635 case AR_SWITCH_APPEND
:
6637 /* Fall thru into --file */
6638 case AR_SWITCH_FILE
:
6641 case AR_SWITCH_DIRECTORY
:
6650 ** Parse the command line for an ".ar" command. The results are written into
6651 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6652 ** successfully, otherwise an error message is written to stderr and
6653 ** SQLITE_ERROR returned.
6655 static int arParseCommand(
6656 char **azArg
, /* Array of arguments passed to dot command */
6657 int nArg
, /* Number of entries in azArg[] */
6658 ArCommand
*pAr
/* Populate this object */
6666 { "create", 'c', AR_CMD_CREATE
, 0 },
6667 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
6668 { "insert", 'i', AR_CMD_INSERT
, 0 },
6669 { "list", 't', AR_CMD_LIST
, 0 },
6670 { "remove", 'r', AR_CMD_REMOVE
, 0 },
6671 { "update", 'u', AR_CMD_UPDATE
, 0 },
6672 { "help", 'h', AR_CMD_HELP
, 0 },
6673 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
6674 { "file", 'f', AR_SWITCH_FILE
, 1 },
6675 { "append", 'a', AR_SWITCH_APPEND
, 1 },
6676 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
6677 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
6678 { "glob", 'g', AR_SWITCH_GLOB
, 0 },
6680 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
6681 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
6684 utf8_printf(stderr
, "Wrong number of arguments. Usage:\n");
6685 return arUsage(stderr
);
6689 /* Traditional style [tar] invocation */
6692 for(i
=0; z
[i
]; i
++){
6693 const char *zArg
= 0;
6694 struct ArSwitch
*pOpt
;
6695 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
6696 if( z
[i
]==pOpt
->cShort
) break;
6699 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
6703 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
6705 zArg
= azArg
[iArg
++];
6707 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
6709 pAr
->nArg
= nArg
-iArg
;
6711 pAr
->azArg
= &azArg
[iArg
];
6714 /* Non-traditional invocation */
6716 for(iArg
=1; iArg
<nArg
; iArg
++){
6720 /* All remaining command line words are command arguments. */
6721 pAr
->azArg
= &azArg
[iArg
];
6722 pAr
->nArg
= nArg
-iArg
;
6729 /* One or more short options */
6731 const char *zArg
= 0;
6732 struct ArSwitch
*pOpt
;
6733 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
6734 if( z
[i
]==pOpt
->cShort
) break;
6737 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
6744 if( iArg
>=(nArg
-1) ){
6745 return arErrorMsg(pAr
, "option requires an argument: %c",
6748 zArg
= azArg
[++iArg
];
6751 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
6753 }else if( z
[2]=='\0' ){
6754 /* A -- option, indicating that all remaining command line words
6755 ** are command arguments. */
6756 pAr
->azArg
= &azArg
[iArg
+1];
6757 pAr
->nArg
= nArg
-iArg
-1;
6761 const char *zArg
= 0; /* Argument for option, if any */
6762 struct ArSwitch
*pMatch
= 0; /* Matching option */
6763 struct ArSwitch
*pOpt
; /* Iterator */
6764 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
6765 const char *zLong
= pOpt
->zLong
;
6766 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
6768 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
6776 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
6779 if( iArg
>=(nArg
-1) ){
6780 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
6782 zArg
= azArg
[++iArg
];
6784 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
6794 ** This function assumes that all arguments within the ArCommand.azArg[]
6795 ** array refer to archive members, as for the --extract, --list or --remove
6796 ** commands. It checks that each of them are "present". If any specified
6797 ** file is not present in the archive, an error is printed to stderr and an
6798 ** error code returned. Otherwise, if all specified arguments are present
6799 ** in the archive, SQLITE_OK is returned. Here, "present" means either an
6800 ** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6801 ** when pAr->bGlob is true.
6803 ** This function strips any trailing '/' characters from each argument.
6804 ** This is consistent with the way the [tar] command seems to work on
6807 static int arCheckEntries(ArCommand
*pAr
){
6811 sqlite3_stmt
*pTest
= 0;
6812 const char *zSel
= (pAr
->bGlob
)
6813 ? "SELECT name FROM %s WHERE glob($name,name)"
6814 : "SELECT name FROM %s WHERE name=$name";
6816 shellPreparePrintf(pAr
->db
, &rc
, &pTest
, zSel
, pAr
->zSrcTable
);
6817 j
= sqlite3_bind_parameter_index(pTest
, "$name");
6818 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
6819 char *z
= pAr
->azArg
[i
];
6820 int n
= strlen30(z
);
6822 while( n
>0 && z
[n
-1]=='/' ) n
--;
6824 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
6825 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
6828 shellReset(&rc
, pTest
);
6829 if( rc
==SQLITE_OK
&& bOk
==0 ){
6830 utf8_printf(stderr
, "not found in archive: %s\n", z
);
6834 shellFinalize(&rc
, pTest
);
6840 ** Format a WHERE clause that can be used against the "sqlar" table to
6841 ** identify all archive members that match the command arguments held
6842 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6843 ** The caller is responsible for eventually calling sqlite3_free() on
6844 ** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6845 ** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6847 static void arWhereClause(
6850 char **pzWhere
/* OUT: New WHERE clause */
6853 const char *zSameOp
= (pAr
->bGlob
)? "GLOB" : "=";
6854 if( *pRc
==SQLITE_OK
){
6856 zWhere
= sqlite3_mprintf("1");
6859 const char *zSep
= "";
6860 for(i
=0; i
<pAr
->nArg
; i
++){
6861 const char *z
= pAr
->azArg
[i
];
6862 zWhere
= sqlite3_mprintf(
6863 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6864 zWhere
, zSep
, zSameOp
, z
, strlen30(z
)+1, zSameOp
, z
6867 *pRc
= SQLITE_NOMEM
;
6878 ** Implementation of .ar "lisT" command.
6880 static int arListCommand(ArCommand
*pAr
){
6881 const char *zSql
= "SELECT %s FROM %s WHERE %s";
6882 const char *azCols
[] = {
6884 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6888 sqlite3_stmt
*pSql
= 0;
6891 rc
= arCheckEntries(pAr
);
6892 arWhereClause(&rc
, pAr
, &zWhere
);
6894 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
6895 pAr
->zSrcTable
, zWhere
);
6897 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
6899 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
6900 if( pAr
->bVerbose
){
6901 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
6902 sqlite3_column_text(pSql
, 0),
6903 sqlite3_column_int(pSql
, 1),
6904 sqlite3_column_text(pSql
, 2),
6905 sqlite3_column_text(pSql
, 3)
6908 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
6912 shellFinalize(&rc
, pSql
);
6913 sqlite3_free(zWhere
);
6919 ** Implementation of .ar "Remove" command.
6921 static int arRemoveCommand(ArCommand
*pAr
){
6927 /* Verify that args actually exist within the archive before proceeding.
6928 ** And formulate a WHERE clause to match them. */
6929 rc
= arCheckEntries(pAr
);
6930 arWhereClause(&rc
, pAr
, &zWhere
);
6932 if( rc
==SQLITE_OK
){
6933 zSql
= sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6934 pAr
->zSrcTable
, zWhere
);
6936 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
6939 rc
= sqlite3_exec(pAr
->db
, "SAVEPOINT ar;", 0, 0, 0);
6940 if( rc
==SQLITE_OK
){
6941 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
6942 if( rc
!=SQLITE_OK
){
6943 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6945 rc
= sqlite3_exec(pAr
->db
, "RELEASE ar;", 0, 0, 0);
6949 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
6954 sqlite3_free(zWhere
);
6960 ** Implementation of .ar "eXtract" command.
6962 static int arExtractCommand(ArCommand
*pAr
){
6966 " writefile(($dir || name), %s, mode, mtime) "
6967 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6968 " AND name NOT GLOB '*..[/\\]*'";
6970 const char *azExtraArg
[] = {
6971 "sqlar_uncompress(data, sz)",
6975 sqlite3_stmt
*pSql
= 0;
6981 /* If arguments are specified, check that they actually exist within
6982 ** the archive before proceeding. And formulate a WHERE clause to
6984 rc
= arCheckEntries(pAr
);
6985 arWhereClause(&rc
, pAr
, &zWhere
);
6987 if( rc
==SQLITE_OK
){
6989 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
6991 zDir
= sqlite3_mprintf("");
6993 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
6996 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
6997 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
7000 if( rc
==SQLITE_OK
){
7001 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
7002 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
7004 /* Run the SELECT statement twice. The first time, writefile() is called
7005 ** for all archive members that should be extracted. The second time,
7006 ** only for the directories. This is because the timestamps for
7007 ** extracted directories must be reset after they are populated (as
7008 ** populating them changes the timestamp). */
7010 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
7011 sqlite3_bind_int(pSql
, j
, i
);
7013 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
7015 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
7016 if( i
==0 && pAr
->bVerbose
){
7017 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
7021 shellReset(&rc
, pSql
);
7023 shellFinalize(&rc
, pSql
);
7027 sqlite3_free(zWhere
);
7032 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
7034 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
7037 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
7041 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
7043 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
7052 ** Implementation of .ar "create", "insert", and "update" commands.
7054 ** create -> Create a new SQL archive
7055 ** insert -> Insert or reinsert all files listed
7056 ** update -> Insert files that have changed or that were not
7057 ** previously in the archive
7059 ** Create the "sqlar" table in the database if it does not already exist.
7060 ** Then add each file in the azFile[] array to the archive. Directories
7061 ** are added recursively. If argument bVerbose is non-zero, a message is
7062 ** printed on stdout for each file archived.
7064 ** The create command is the same as update, except that it drops
7065 ** any existing "sqlar" table before beginning. The "insert" command
7066 ** always overwrites every file named on the command-line, where as
7067 ** "update" only overwrites if the size or mtime or mode has changed.
7069 static int arCreateOrUpdateCommand(
7070 ArCommand
*pAr
, /* Command arguments and options */
7071 int bUpdate
, /* true for a --create. */
7072 int bOnlyIfChanged
/* Only update if file has changed */
7074 const char *zCreate
=
7075 "CREATE TABLE IF NOT EXISTS sqlar(\n"
7076 " name TEXT PRIMARY KEY, -- name of the file\n"
7077 " mode INT, -- access permissions\n"
7078 " mtime INT, -- last modification time\n"
7079 " sz INT, -- original file size\n"
7080 " data BLOB -- compressed content\n"
7082 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
7083 const char *zInsertFmt
[2] = {
7084 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7089 " CASE substr(lsmode(mode),1,1)\n"
7090 " WHEN '-' THEN length(data)\n"
7091 " WHEN 'd' THEN 0\n"
7093 " sqlar_compress(data)\n"
7094 " FROM fsdir(%Q,%Q) AS disk\n"
7095 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7097 "REPLACE INTO %s(name,mode,mtime,data)\n"
7103 " FROM fsdir(%Q,%Q) AS disk\n"
7104 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7106 int i
; /* For iterating through azFile[] */
7107 int rc
; /* Return code */
7108 const char *zTab
= 0; /* SQL table into which to insert */
7113 arExecSql(pAr
, "PRAGMA page_size=512");
7114 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
7115 if( rc
!=SQLITE_OK
) return rc
;
7118 /* Initialize the zipfile virtual table, if necessary */
7121 sqlite3_randomness(sizeof(r
),&r
);
7122 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
7124 zSql
= sqlite3_mprintf(
7125 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7128 rc
= arExecSql(pAr
, zSql
);
7134 /* Initialize the table for an SQLAR */
7137 rc
= arExecSql(pAr
, zDrop
);
7138 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
7140 rc
= arExecSql(pAr
, zCreate
);
7142 if( bOnlyIfChanged
){
7143 zExists
= sqlite3_mprintf(
7145 "SELECT 1 FROM %s AS mem"
7146 " WHERE mem.name=disk.name"
7147 " AND mem.mtime=disk.mtime"
7148 " AND mem.mode=disk.mode)", zTab
);
7150 zExists
= sqlite3_mprintf("");
7152 if( zExists
==0 ) rc
= SQLITE_NOMEM
;
7153 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
7154 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
7155 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
7156 pAr
->azArg
[i
], pAr
->zDir
, zExists
);
7157 rc
= arExecSql(pAr
, zSql2
);
7158 sqlite3_free(zSql2
);
7161 if( rc
!=SQLITE_OK
){
7162 sqlite3_exec(pAr
->db
, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7164 rc
= arExecSql(pAr
, "RELEASE ar;");
7165 if( pAr
->bZip
&& pAr
->zFile
){
7166 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
7167 arExecSql(pAr
, zSql
);
7171 sqlite3_free(zExists
);
7176 ** Implementation of ".ar" dot command.
7178 static int arDotCommand(
7179 ShellState
*pState
, /* Current shell tool state */
7180 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
7181 char **azArg
, /* Array of arguments passed to dot command */
7182 int nArg
/* Number of entries in azArg[] */
7186 memset(&cmd
, 0, sizeof(cmd
));
7187 cmd
.fromCmdLine
= fromCmdLine
;
7188 rc
= arParseCommand(azArg
, nArg
, &cmd
);
7189 if( rc
==SQLITE_OK
){
7190 int eDbType
= SHELL_OPEN_UNSPEC
;
7192 cmd
.db
= pState
->db
;
7194 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
7196 eDbType
= pState
->openMode
;
7198 if( eDbType
==SHELL_OPEN_ZIPFILE
){
7199 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
7201 cmd
.zSrcTable
= sqlite3_mprintf("zip");
7203 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
7207 }else if( cmd
.zFile
){
7209 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
7210 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_INSERT
7211 || cmd
.eCmd
==AR_CMD_REMOVE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
7212 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
7214 flags
= SQLITE_OPEN_READONLY
;
7218 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
7219 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
7221 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
7222 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
7223 if( rc
!=SQLITE_OK
){
7224 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
7225 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
7227 goto end_ar_command
;
7229 sqlite3_fileio_init(cmd
.db
, 0, 0);
7230 sqlite3_sqlar_init(cmd
.db
, 0, 0);
7231 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
7232 shellPutsFunc
, 0, 0);
7235 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
7236 if( cmd
.eCmd
!=AR_CMD_CREATE
7237 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
7239 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
7241 goto end_ar_command
;
7243 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
7248 rc
= arCreateOrUpdateCommand(&cmd
, 0, 0);
7251 case AR_CMD_EXTRACT
:
7252 rc
= arExtractCommand(&cmd
);
7256 rc
= arListCommand(&cmd
);
7260 arUsage(pState
->out
);
7264 rc
= arCreateOrUpdateCommand(&cmd
, 1, 0);
7268 rc
= arRemoveCommand(&cmd
);
7272 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
7273 rc
= arCreateOrUpdateCommand(&cmd
, 1, 1);
7278 if( cmd
.db
!=pState
->db
){
7281 sqlite3_free(cmd
.zSrcTable
);
7285 /* End of the ".archive" or ".ar" command logic
7286 *******************************************************************************/
7287 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7289 #if SQLITE_SHELL_HAVE_RECOVER
7292 ** This function is used as a callback by the recover extension. Simply
7293 ** print the supplied SQL statement to stdout.
7295 static int recoverSqlCb(void *pCtx
, const char *zSql
){
7296 ShellState
*pState
= (ShellState
*)pCtx
;
7297 utf8_printf(pState
->out
, "%s;\n", zSql
);
7302 ** This function is called to recover data from the database. A script
7303 ** to construct a new database containing all recovered data is output
7304 ** on stream pState->out.
7306 static int recoverDatabaseCmd(ShellState
*pState
, int nArg
, char **azArg
){
7308 const char *zRecoveryDb
= ""; /* Name of "recovery" database. Debug only */
7309 const char *zLAF
= "lost_and_found";
7310 int bFreelist
= 1; /* 0 if --ignore-freelist is specified */
7311 int bRowids
= 1; /* 0 if --no-rowids */
7312 sqlite3_recover
*p
= 0;
7315 for(i
=1; i
<nArg
; i
++){
7318 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7320 if( n
<=17 && memcmp("-ignore-freelist", z
, n
)==0 ){
7323 if( n
<=12 && memcmp("-recovery-db", z
, n
)==0 && i
<(nArg
-1) ){
7324 /* This option determines the name of the ATTACH-ed database used
7325 ** internally by the recovery extension. The default is "" which
7326 ** means to use a temporary database that is automatically deleted
7327 ** when closed. This option is undocumented and might disappear at
7330 zRecoveryDb
= azArg
[i
];
7332 if( n
<=15 && memcmp("-lost-and-found", z
, n
)==0 && i
<(nArg
-1) ){
7336 if( n
<=10 && memcmp("-no-rowids", z
, n
)==0 ){
7340 utf8_printf(stderr
, "unexpected option: %s\n", azArg
[i
]);
7341 showHelp(pState
->out
, azArg
[0]);
7346 p
= sqlite3_recover_init_sql(
7347 pState
->db
, "main", recoverSqlCb
, (void*)pState
7350 sqlite3_recover_config(p
, 789, (void*)zRecoveryDb
); /* Debug use only */
7351 sqlite3_recover_config(p
, SQLITE_RECOVER_LOST_AND_FOUND
, (void*)zLAF
);
7352 sqlite3_recover_config(p
, SQLITE_RECOVER_ROWIDS
, (void*)&bRowids
);
7353 sqlite3_recover_config(p
, SQLITE_RECOVER_FREELIST_CORRUPT
,(void*)&bFreelist
);
7355 sqlite3_recover_run(p
);
7356 if( sqlite3_recover_errcode(p
)!=SQLITE_OK
){
7357 const char *zErr
= sqlite3_recover_errmsg(p
);
7358 int errCode
= sqlite3_recover_errcode(p
);
7359 raw_printf(stderr
, "sql error: %s (%d)\n", zErr
, errCode
);
7361 rc
= sqlite3_recover_finish(p
);
7364 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7368 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7369 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7370 * close db and set it to 0, and return the columns spec, to later
7371 * be sqlite3_free()'ed by the caller.
7372 * The return is 0 when either:
7373 * (a) The db was not initialized and zCol==0 (There are no columns.)
7374 * (b) zCol!=0 (Column was added, db initialized as needed.)
7375 * The 3rd argument, pRenamed, references an out parameter. If the
7376 * pointer is non-zero, its referent will be set to a summary of renames
7377 * done if renaming was necessary, or set to 0 if none was done. The out
7378 * string (if any) must be sqlite3_free()'ed by the caller.
7381 #define rc_err_oom_die(rc) \
7382 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7383 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7384 fprintf(stderr,"E:%d\n",rc), assert(0)
7386 static void rc_err_oom_die(int rc
){
7387 if( rc
==SQLITE_NOMEM
) shell_check_oom(0);
7388 assert(rc
==SQLITE_OK
||rc
==SQLITE_DONE
);
7392 #ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7393 static char zCOL_DB
[] = SHELL_STRINGIFY(SHELL_COLFIX_DB
);
7394 #else /* Otherwise, memory is faster/better for the transient DB. */
7395 static const char *zCOL_DB
= ":memory:";
7398 /* Define character (as C string) to separate generated column ordinal
7399 * from protected part of incoming column names. This defaults to "_"
7400 * so that incoming column identifiers that did not need not be quoted
7401 * remain usable without being quoted. It must be one character.
7403 #ifndef SHELL_AUTOCOLUMN_SEP
7404 # define AUTOCOLUMN_SEP "_"
7406 # define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7409 static char *zAutoColumn(const char *zColNew
, sqlite3
**pDb
, char **pzRenamed
){
7410 /* Queries and D{D,M}L used here */
7411 static const char * const zTabMake
= "\
7412 CREATE TABLE ColNames(\
7413 cpos INTEGER PRIMARY KEY,\
7414 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7415 CREATE VIEW RepeatedNames AS \
7416 SELECT DISTINCT t.name FROM ColNames t \
7417 WHERE t.name COLLATE NOCASE IN (\
7418 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7421 static const char * const zTabFill
= "\
7422 INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7423 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7425 static const char * const zHasDupes
= "\
7426 SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7427 <count(name) FROM ColNames\
7429 #ifdef SHELL_COLUMN_RENAME_CLEAN
7430 static const char * const zDedoctor
= "\
7431 UPDATE ColNames SET chop=iif(\
7432 (substring(name,nlen,1) BETWEEN '0' AND '9')\
7433 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP
"'),\
7434 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP
"0123456789')),\
7439 static const char * const zSetReps
= "\
7440 UPDATE ColNames AS t SET reps=\
7441 (SELECT count(*) FROM ColNames d \
7442 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7446 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7447 static const char * const zColDigits
= "\
7448 SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7451 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7452 static const char * const zColDigits
= "\
7453 SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7454 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7455 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7458 static const char * const zRenameRank
=
7459 #ifdef SHELL_COLUMN_RENAME_CLEAN
7460 "UPDATE ColNames AS t SET suff="
7461 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP
"', $1, cpos), '')"
7462 #else /* ...RENAME_MINIMAL_ONE_PASS */
7463 "WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7466 " SELECT nlz+1 AS nlz FROM Lzn"
7469 " FROM ColNames t, ColNames o"
7471 " iif(t.name IN (SELECT * FROM RepeatedNames),"
7472 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7473 " t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7477 " iif(o.name IN (SELECT * FROM RepeatedNames),"
7478 " printf('%s"AUTOCOLUMN_SEP
"%s',"
7479 " o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7483 " AND o.cpos<>t.cpos"
7486 ") UPDATE Colnames AS t SET"
7487 " chop = 0," /* No chopping, never touch incoming names. */
7488 " suff = iif(name IN (SELECT * FROM RepeatedNames),"
7489 " printf('"AUTOCOLUMN_SEP
"%s', substring("
7490 " printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7495 static const char * const zCollectVar
= "\
7500 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7503 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7504 FROM ColNames ORDER BY cpos\
7506 static const char * const zRenamesDone
=
7507 "SELECT group_concat("
7508 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7510 "FROM ColNames WHERE suff<>'' OR chop!=0"
7513 sqlite3_stmt
*pStmt
= 0;
7516 /* Add initial or additional column. Init db if necessary. */
7518 if( SQLITE_OK
!=sqlite3_open(zCOL_DB
, pDb
) ) return 0;
7519 #ifdef SHELL_COLFIX_DB
7521 sqlite3_exec(*pDb
,"drop table if exists ColNames;"
7522 "drop view if exists RepeatedNames;",0,0,0);
7524 rc
= sqlite3_exec(*pDb
, zTabMake
, 0, 0, 0);
7528 rc
= sqlite3_prepare_v2(*pDb
, zTabFill
, -1, &pStmt
, 0);
7530 rc
= sqlite3_bind_text(pStmt
, 1, zColNew
, -1, 0);
7532 rc
= sqlite3_step(pStmt
);
7534 sqlite3_finalize(pStmt
);
7536 }else if( *pDb
==0 ){
7539 /* Formulate the columns spec, close the DB, zero *pDb. */
7540 char *zColsSpec
= 0;
7541 int hasDupes
= db_int(*pDb
, zHasDupes
);
7542 int nDigits
= (hasDupes
)? db_int(*pDb
, zColDigits
) : 0;
7544 #ifdef SHELL_COLUMN_RENAME_CLEAN
7545 rc
= sqlite3_exec(*pDb
, zDedoctor
, 0, 0, 0);
7548 rc
= sqlite3_exec(*pDb
, zSetReps
, 0, 0, 0);
7550 rc
= sqlite3_prepare_v2(*pDb
, zRenameRank
, -1, &pStmt
, 0);
7552 sqlite3_bind_int(pStmt
, 1, nDigits
);
7553 rc
= sqlite3_step(pStmt
);
7554 sqlite3_finalize(pStmt
);
7555 assert(rc
==SQLITE_DONE
);
7557 assert(db_int(*pDb
, zHasDupes
)==0); /* Consider: remove this */
7558 rc
= sqlite3_prepare_v2(*pDb
, zCollectVar
, -1, &pStmt
, 0);
7560 rc
= sqlite3_step(pStmt
);
7561 if( rc
==SQLITE_ROW
){
7562 zColsSpec
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7567 if( !hasDupes
) *pzRenamed
= 0;
7569 sqlite3_finalize(pStmt
);
7570 if( SQLITE_OK
==sqlite3_prepare_v2(*pDb
, zRenamesDone
, -1, &pStmt
, 0)
7571 && SQLITE_ROW
==sqlite3_step(pStmt
) ){
7572 *pzRenamed
= sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7577 sqlite3_finalize(pStmt
);
7578 sqlite3_close(*pDb
);
7585 ** If an input line begins with "." then invoke this routine to
7586 ** process that line.
7588 ** Return 1 on error, 2 to exit, and 0 otherwise.
7590 static int do_meta_command(char *zLine
, ShellState
*p
){
7597 #ifndef SQLITE_OMIT_VIRTUALTABLE
7598 if( p
->expert
.pExpert
){
7599 expertFinish(p
, 1, 0);
7603 /* Parse the input line into tokens.
7605 while( zLine
[h
] && nArg
<ArraySize(azArg
)-1 ){
7606 while( IsSpace(zLine
[h
]) ){ h
++; }
7607 if( zLine
[h
]==0 ) break;
7608 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
7609 int delim
= zLine
[h
++];
7610 azArg
[nArg
++] = &zLine
[h
];
7611 while( zLine
[h
] && zLine
[h
]!=delim
){
7612 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
7615 if( zLine
[h
]==delim
){
7618 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
7620 azArg
[nArg
++] = &zLine
[h
];
7621 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
7622 if( zLine
[h
] ) zLine
[h
++] = 0;
7623 resolve_backslashes(azArg
[nArg
-1]);
7628 /* Process the input line.
7630 if( nArg
==0 ) return 0; /* no tokens, no error */
7631 n
= strlen30(azArg
[0]);
7635 #ifndef SQLITE_OMIT_AUTHORIZATION
7636 if( c
=='a' && cli_strncmp(azArg
[0], "auth", n
)==0 ){
7638 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
7640 goto meta_command_exit
;
7643 if( booleanValue(azArg
[1]) ){
7644 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
7645 }else if( p
->bSafeModePersist
){
7646 sqlite3_set_authorizer(p
->db
, safeModeAuth
, p
);
7648 sqlite3_set_authorizer(p
->db
, 0, 0);
7653 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7654 && !defined(SQLITE_SHELL_FIDDLE)
7655 if( c
=='a' && cli_strncmp(azArg
[0], "archive", n
)==0 ){
7657 failIfSafeMode(p
, "cannot run .archive in safe mode");
7658 rc
= arDotCommand(p
, 0, azArg
, nArg
);
7662 #ifndef SQLITE_SHELL_FIDDLE
7663 if( (c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "backup", n
)==0)
7664 || (c
=='s' && n
>=3 && cli_strncmp(azArg
[0], "save", n
)==0)
7666 const char *zDestFile
= 0;
7667 const char *zDb
= 0;
7669 sqlite3_backup
*pBackup
;
7672 const char *zVfs
= 0;
7673 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
7674 for(j
=1; j
<nArg
; j
++){
7675 const char *z
= azArg
[j
];
7677 if( z
[1]=='-' ) z
++;
7678 if( cli_strcmp(z
, "-append")==0 ){
7681 if( cli_strcmp(z
, "-async")==0 ){
7685 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
7688 }else if( zDestFile
==0 ){
7689 zDestFile
= azArg
[j
];
7692 zDestFile
= azArg
[j
];
7694 raw_printf(stderr
, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7699 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
7702 if( zDb
==0 ) zDb
= "main";
7703 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
7704 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
7705 if( rc
!=SQLITE_OK
){
7706 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
7711 sqlite3_exec(pDest
, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7715 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
7717 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
7721 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
7722 sqlite3_backup_finish(pBackup
);
7723 if( rc
==SQLITE_DONE
){
7726 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
7731 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
7733 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "bail", n
)==0 ){
7735 bail_on_error
= booleanValue(azArg
[1]);
7737 raw_printf(stderr
, "Usage: .bail on|off\n");
7742 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "binary", n
)==0 ){
7744 if( booleanValue(azArg
[1]) ){
7745 setBinaryMode(p
->out
, 1);
7747 setTextMode(p
->out
, 1);
7750 raw_printf(stderr
, "Usage: .binary on|off\n");
7755 /* The undocumented ".breakpoint" command causes a call to the no-op
7756 ** routine named test_breakpoint().
7758 if( c
=='b' && n
>=3 && cli_strncmp(azArg
[0], "breakpoint", n
)==0 ){
7762 #ifndef SQLITE_SHELL_FIDDLE
7763 if( c
=='c' && cli_strcmp(azArg
[0],"cd")==0 ){
7764 failIfSafeMode(p
, "cannot run .cd in safe mode");
7766 #if defined(_WIN32) || defined(WIN32)
7767 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
7768 rc
= !SetCurrentDirectoryW(z
);
7771 rc
= chdir(azArg
[1]);
7774 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
7778 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
7782 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
7784 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "changes", n
)==0 ){
7786 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
7788 raw_printf(stderr
, "Usage: .changes on|off\n");
7793 #ifndef SQLITE_SHELL_FIDDLE
7794 /* Cancel output redirection, if it is currently set (by .testcase)
7795 ** Then read the content of the testcase-out.txt file and compare against
7796 ** azArg[1]. If there are differences, report an error and exit.
7798 if( c
=='c' && n
>=3 && cli_strncmp(azArg
[0], "check", n
)==0 ){
7802 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
7804 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
7805 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
7807 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
7809 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
7810 p
->zTestcase
, azArg
[1], zRes
);
7813 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
7818 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
7820 #ifndef SQLITE_SHELL_FIDDLE
7821 if( c
=='c' && cli_strncmp(azArg
[0], "clone", n
)==0 ){
7822 failIfSafeMode(p
, "cannot run .clone in safe mode");
7824 tryToClone(p
, azArg
[1]);
7826 raw_printf(stderr
, "Usage: .clone FILENAME\n");
7830 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
7832 if( c
=='c' && cli_strncmp(azArg
[0], "connection", n
)==0 ){
7834 /* List available connections */
7836 for(i
=0; i
<ArraySize(p
->aAuxDb
); i
++){
7837 const char *zFile
= p
->aAuxDb
[i
].zDbFilename
;
7838 if( p
->aAuxDb
[i
].db
==0 && p
->pAuxDb
!=&p
->aAuxDb
[i
] ){
7839 zFile
= "(not open)";
7840 }else if( zFile
==0 ){
7842 }else if( zFile
[0]==0 ){
7843 zFile
= "(temporary-file)";
7845 if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
7846 utf8_printf(stdout
, "ACTIVE %d: %s\n", i
, zFile
);
7847 }else if( p
->aAuxDb
[i
].db
!=0 ){
7848 utf8_printf(stdout
, " %d: %s\n", i
, zFile
);
7851 }else if( nArg
==2 && IsDigit(azArg
[1][0]) && azArg
[1][1]==0 ){
7852 int i
= azArg
[1][0] - '0';
7853 if( p
->pAuxDb
!= &p
->aAuxDb
[i
] && i
>=0 && i
<ArraySize(p
->aAuxDb
) ){
7854 p
->pAuxDb
->db
= p
->db
;
7855 p
->pAuxDb
= &p
->aAuxDb
[i
];
7856 globalDb
= p
->db
= p
->pAuxDb
->db
;
7859 }else if( nArg
==3 && cli_strcmp(azArg
[1], "close")==0
7860 && IsDigit(azArg
[2][0]) && azArg
[2][1]==0 ){
7861 int i
= azArg
[2][0] - '0';
7862 if( i
<0 || i
>=ArraySize(p
->aAuxDb
) ){
7864 }else if( p
->pAuxDb
== &p
->aAuxDb
[i
] ){
7865 raw_printf(stderr
, "cannot close the active database connection\n");
7867 }else if( p
->aAuxDb
[i
].db
){
7868 session_close_all(p
, i
);
7869 close_db(p
->aAuxDb
[i
].db
);
7870 p
->aAuxDb
[i
].db
= 0;
7873 raw_printf(stderr
, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7878 if( c
=='d' && n
>1 && cli_strncmp(azArg
[0], "databases", n
)==0 ){
7881 sqlite3_stmt
*pStmt
;
7884 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
7886 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
7889 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
7890 const char *zSchema
= (const char *)sqlite3_column_text(pStmt
,1);
7891 const char *zFile
= (const char*)sqlite3_column_text(pStmt
,2);
7892 if( zSchema
==0 || zFile
==0 ) continue;
7893 azName
= sqlite3_realloc(azName
, (nName
+1)*2*sizeof(char*));
7894 shell_check_oom(azName
);
7895 azName
[nName
*2] = strdup(zSchema
);
7896 azName
[nName
*2+1] = strdup(zFile
);
7900 sqlite3_finalize(pStmt
);
7901 for(i
=0; i
<nName
; i
++){
7902 int eTxn
= sqlite3_txn_state(p
->db
, azName
[i
*2]);
7903 int bRdonly
= sqlite3_db_readonly(p
->db
, azName
[i
*2]);
7904 const char *z
= azName
[i
*2+1];
7905 utf8_printf(p
->out
, "%s: %s %s%s\n",
7907 z
&& z
[0] ? z
: "\"\"",
7908 bRdonly
? "r/o" : "r/w",
7909 eTxn
==SQLITE_TXN_NONE
? "" :
7910 eTxn
==SQLITE_TXN_READ
? " read-txn" : " write-txn");
7912 free(azName
[i
*2+1]);
7914 sqlite3_free(azName
);
7917 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbconfig", n
)==0 ){
7918 static const struct DbConfigChoices
{
7922 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
7923 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL
},
7924 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML
},
7925 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
7926 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
7927 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
7928 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW
},
7929 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
7930 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
},
7931 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
},
7932 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
7933 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
7934 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
7935 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
7936 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA
},
7937 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA
},
7941 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
7942 if( nArg
>1 && cli_strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
7944 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
7946 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
7947 utf8_printf(p
->out
, "%19s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
7950 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
7951 utf8_printf(stderr
, "Error: unknown dbconfig \"%s\"\n", azArg
[1]);
7952 utf8_printf(stderr
, "Enter \".dbconfig\" with no arguments for a list\n");
7956 #if SQLITE_SHELL_HAVE_RECOVER
7957 if( c
=='d' && n
>=3 && cli_strncmp(azArg
[0], "dbinfo", n
)==0 ){
7958 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
7961 if( c
=='r' && cli_strncmp(azArg
[0], "recover", n
)==0 ){
7963 rc
= recoverDatabaseCmd(p
, nArg
, azArg
);
7965 #endif /* SQLITE_SHELL_HAVE_RECOVER */
7967 if( c
=='d' && cli_strncmp(azArg
[0], "dump", n
)==0 ){
7971 int savedShowHeader
= p
->showHeader
;
7972 int savedShellFlags
= p
->shellFlgs
;
7974 SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
7975 |SHFLG_DumpDataOnly
|SHFLG_DumpNoSys
);
7976 for(i
=1; i
<nArg
; i
++){
7977 if( azArg
[i
][0]=='-' ){
7978 const char *z
= azArg
[i
]+1;
7979 if( z
[0]=='-' ) z
++;
7980 if( cli_strcmp(z
,"preserve-rowids")==0 ){
7981 #ifdef SQLITE_OMIT_VIRTUALTABLE
7982 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
7983 " with SQLITE_OMIT_VIRTUALTABLE\n");
7985 sqlite3_free(zLike
);
7986 goto meta_command_exit
;
7988 ShellSetFlag(p
, SHFLG_PreserveRowid
);
7991 if( cli_strcmp(z
,"newlines")==0 ){
7992 ShellSetFlag(p
, SHFLG_Newlines
);
7994 if( cli_strcmp(z
,"data-only")==0 ){
7995 ShellSetFlag(p
, SHFLG_DumpDataOnly
);
7997 if( cli_strcmp(z
,"nosys")==0 ){
7998 ShellSetFlag(p
, SHFLG_DumpNoSys
);
8001 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
8003 sqlite3_free(zLike
);
8004 goto meta_command_exit
;
8007 /* azArg[i] contains a LIKE pattern. This ".dump" request should
8008 ** only dump data for tables for which either the table name matches
8009 ** the LIKE pattern, or the table appears to be a shadow table of
8010 ** a virtual table for which the name matches the LIKE pattern.
8012 char *zExpr
= sqlite3_mprintf(
8013 "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8014 " SELECT 1 FROM sqlite_schema WHERE "
8015 " name LIKE %Q ESCAPE '\\' AND"
8016 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8017 " substr(o.name, 1, length(name)+1) == (name||'_')"
8018 ")", azArg
[i
], azArg
[i
]
8022 zLike
= sqlite3_mprintf("%z OR %z", zLike
, zExpr
);
8031 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8032 /* When playing back a "dump", the content might appear in an order
8033 ** which causes immediate foreign key constraints to be violated.
8034 ** So disable foreign-key constraint enforcement to prevent problems. */
8035 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
8036 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
8038 p
->writableSchema
= 0;
8040 /* Set writable_schema=ON since doing so forces SQLite to initialize
8041 ** as much of the schema as it can even if the sqlite_schema table is
8043 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8045 if( zLike
==0 ) zLike
= sqlite3_mprintf("true");
8046 zSql
= sqlite3_mprintf(
8047 "SELECT name, type, sql FROM sqlite_schema AS o "
8048 "WHERE (%s) AND type=='table'"
8050 " ORDER BY tbl_name='sqlite_sequence', rowid",
8053 run_schema_dump_query(p
,zSql
);
8055 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8056 zSql
= sqlite3_mprintf(
8057 "SELECT sql FROM sqlite_schema AS o "
8058 "WHERE (%s) AND sql NOT NULL"
8059 " AND type IN ('index','trigger','view')",
8062 run_table_dump_query(p
, zSql
);
8065 sqlite3_free(zLike
);
8066 if( p
->writableSchema
){
8067 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
8068 p
->writableSchema
= 0;
8070 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8071 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
8072 if( (p
->shellFlgs
& SHFLG_DumpDataOnly
)==0 ){
8073 raw_printf(p
->out
, p
->nErr
?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8075 p
->showHeader
= savedShowHeader
;
8076 p
->shellFlgs
= savedShellFlags
;
8079 if( c
=='e' && cli_strncmp(azArg
[0], "echo", n
)==0 ){
8081 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
8083 raw_printf(stderr
, "Usage: .echo on|off\n");
8088 if( c
=='e' && cli_strncmp(azArg
[0], "eqp", n
)==0 ){
8091 if( p
->autoEQPtrace
){
8092 if( p
->db
) sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8093 p
->autoEQPtrace
= 0;
8095 if( cli_strcmp(azArg
[1],"full")==0 ){
8096 p
->autoEQP
= AUTOEQP_full
;
8097 }else if( cli_strcmp(azArg
[1],"trigger")==0 ){
8098 p
->autoEQP
= AUTOEQP_trigger
;
8100 }else if( cli_strcmp(azArg
[1],"test")==0 ){
8101 p
->autoEQP
= AUTOEQP_on
;
8103 }else if( cli_strcmp(azArg
[1],"trace")==0 ){
8104 p
->autoEQP
= AUTOEQP_full
;
8105 p
->autoEQPtrace
= 1;
8107 sqlite3_exec(p
->db
, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8108 sqlite3_exec(p
->db
, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8111 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
8114 raw_printf(stderr
, "Usage: .eqp off|on|trace|trigger|full\n");
8119 #ifndef SQLITE_SHELL_FIDDLE
8120 if( c
=='e' && cli_strncmp(azArg
[0], "exit", n
)==0 ){
8121 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
8126 /* The ".explain" command is automatic now. It is largely pointless. It
8127 ** retained purely for backwards compatibility */
8128 if( c
=='e' && cli_strncmp(azArg
[0], "explain", n
)==0 ){
8131 if( cli_strcmp(azArg
[1],"auto")==0 ){
8134 val
= booleanValue(azArg
[1]);
8137 if( val
==1 && p
->mode
!=MODE_Explain
){
8138 p
->normalMode
= p
->mode
;
8139 p
->mode
= MODE_Explain
;
8142 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8144 }else if( val
==99 ){
8145 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
8150 #ifndef SQLITE_OMIT_VIRTUALTABLE
8151 if( c
=='e' && cli_strncmp(azArg
[0], "expert", n
)==0 ){
8154 "Cannot run experimental commands such as \"%s\" in safe mode\n",
8159 expertDotCommand(p
, azArg
, nArg
);
8164 if( c
=='f' && cli_strncmp(azArg
[0], "filectrl", n
)==0 ){
8165 static const struct {
8166 const char *zCtrlName
; /* Name of a test-control option */
8167 int ctrlCode
; /* Integer code for that option */
8168 const char *zUsage
; /* Usage notes */
8170 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE
, "SIZE" },
8171 { "data_version", SQLITE_FCNTL_DATA_VERSION
, "" },
8172 { "has_moved", SQLITE_FCNTL_HAS_MOVED
, "" },
8173 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT
, "MILLISEC" },
8174 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL
, "[BOOLEAN]" },
8175 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
8176 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE
, "[BOOLEAN]" },
8177 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES
, "[N]" },
8178 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT
, "[LIMIT]" },
8179 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME
, "" },
8180 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
8184 sqlite3_int64 iRes
= 0; /* Integer result to display if rc2==1 */
8185 int isOk
= 0; /* 0: usage 1: %lld 2: no-result */
8187 const char *zCmd
= 0;
8188 const char *zSchema
= 0;
8191 zCmd
= nArg
>=2 ? azArg
[1] : "help";
8194 && (cli_strcmp(zCmd
,"--schema")==0 || cli_strcmp(zCmd
,"-schema")==0)
8198 for(i
=3; i
<nArg
; i
++) azArg
[i
-2] = azArg
[i
];
8203 /* The argument can optionally begin with "-" or "--" */
8204 if( zCmd
[0]=='-' && zCmd
[1] ){
8206 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
8209 /* --help lists all file-controls */
8210 if( cli_strcmp(zCmd
,"help")==0 ){
8211 utf8_printf(p
->out
, "Available file-controls:\n");
8212 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8213 utf8_printf(p
->out
, " .filectrl %s %s\n",
8214 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
8217 goto meta_command_exit
;
8220 /* convert filectrl text option to value. allow any unique prefix
8221 ** of the option name, or a numerical value. */
8222 n2
= strlen30(zCmd
);
8223 for(i
=0; i
<ArraySize(aCtrl
); i
++){
8224 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
8226 filectrl
= aCtrl
[i
].ctrlCode
;
8229 utf8_printf(stderr
, "Error: ambiguous file-control: \"%s\"\n"
8230 "Use \".filectrl --help\" for help\n", zCmd
);
8232 goto meta_command_exit
;
8237 utf8_printf(stderr
,"Error: unknown file-control: %s\n"
8238 "Use \".filectrl --help\" for help\n", zCmd
);
8241 case SQLITE_FCNTL_SIZE_LIMIT
: {
8242 if( nArg
!=2 && nArg
!=3 ) break;
8243 iRes
= nArg
==3 ? integerValue(azArg
[2]) : -1;
8244 sqlite3_file_control(p
->db
, zSchema
, SQLITE_FCNTL_SIZE_LIMIT
, &iRes
);
8248 case SQLITE_FCNTL_LOCK_TIMEOUT
:
8249 case SQLITE_FCNTL_CHUNK_SIZE
: {
8251 if( nArg
!=3 ) break;
8252 x
= (int)integerValue(azArg
[2]);
8253 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8257 case SQLITE_FCNTL_PERSIST_WAL
:
8258 case SQLITE_FCNTL_POWERSAFE_OVERWRITE
: {
8260 if( nArg
!=2 && nArg
!=3 ) break;
8261 x
= nArg
==3 ? booleanValue(azArg
[2]) : -1;
8262 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8267 case SQLITE_FCNTL_DATA_VERSION
:
8268 case SQLITE_FCNTL_HAS_MOVED
: {
8270 if( nArg
!=2 ) break;
8271 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8276 case SQLITE_FCNTL_TEMPFILENAME
: {
8278 if( nArg
!=2 ) break;
8279 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &z
);
8281 utf8_printf(p
->out
, "%s\n", z
);
8287 case SQLITE_FCNTL_RESERVE_BYTES
: {
8291 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8294 sqlite3_file_control(p
->db
, zSchema
, filectrl
, &x
);
8295 utf8_printf(p
->out
,"%d\n", x
);
8301 if( isOk
==0 && iCtrl
>=0 ){
8302 utf8_printf(p
->out
, "Usage: .filectrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
8304 }else if( isOk
==1 ){
8306 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%lld", iRes
);
8307 raw_printf(p
->out
, "%s\n", zBuf
);
8311 if( c
=='f' && cli_strncmp(azArg
[0], "fullschema", n
)==0 ){
8314 memcpy(&data
, p
, sizeof(data
));
8315 data
.showHeader
= 0;
8316 data
.cMode
= data
.mode
= MODE_Semi
;
8317 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
8318 data
.cMode
= data
.mode
= MODE_Pretty
;
8322 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
8324 goto meta_command_exit
;
8327 rc
= sqlite3_exec(p
->db
,
8329 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8330 " FROM sqlite_schema UNION ALL"
8331 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8332 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8336 if( rc
==SQLITE_OK
){
8337 sqlite3_stmt
*pStmt
;
8338 rc
= sqlite3_prepare_v2(p
->db
,
8339 "SELECT rowid FROM sqlite_schema"
8340 " WHERE name GLOB 'sqlite_stat[134]'",
8342 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
8343 sqlite3_finalize(pStmt
);
8346 raw_printf(p
->out
, "/* No STAT tables available */\n");
8348 raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
8349 data
.cMode
= data
.mode
= MODE_Insert
;
8350 data
.zDestTable
= "sqlite_stat1";
8351 shell_exec(&data
, "SELECT * FROM sqlite_stat1", 0);
8352 data
.zDestTable
= "sqlite_stat4";
8353 shell_exec(&data
, "SELECT * FROM sqlite_stat4", 0);
8354 raw_printf(p
->out
, "ANALYZE sqlite_schema;\n");
8358 if( c
=='h' && cli_strncmp(azArg
[0], "headers", n
)==0 ){
8360 p
->showHeader
= booleanValue(azArg
[1]);
8361 p
->shellFlgs
|= SHFLG_HeaderSet
;
8363 raw_printf(stderr
, "Usage: .headers on|off\n");
8368 if( c
=='h' && cli_strncmp(azArg
[0], "help", n
)==0 ){
8370 n
= showHelp(p
->out
, azArg
[1]);
8372 utf8_printf(p
->out
, "Nothing matches '%s'\n", azArg
[1]);
8375 showHelp(p
->out
, 0);
8379 #ifndef SQLITE_SHELL_FIDDLE
8380 if( c
=='i' && cli_strncmp(azArg
[0], "import", n
)==0 ){
8381 char *zTable
= 0; /* Insert data into this table */
8382 char *zSchema
= 0; /* within this schema (may default to "main") */
8383 char *zFile
= 0; /* Name of file to extra content from */
8384 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
8385 int nCol
; /* Number of columns in the table */
8386 int nByte
; /* Number of bytes in an SQL string */
8387 int i
, j
; /* Loop counters */
8388 int needCommit
; /* True to COMMIT or ROLLBACK at end */
8389 int nSep
; /* Number of bytes in p->colSeparator[] */
8390 char *zSql
; /* An SQL statement */
8391 char *zFullTabName
; /* Table name with schema if applicable */
8392 ImportCtx sCtx
; /* Reader context */
8393 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
8394 int eVerbose
= 0; /* Larger for more console output */
8395 int nSkip
= 0; /* Initial lines to skip */
8396 int useOutputMode
= 1; /* Use output mode to determine separators */
8397 char *zCreate
= 0; /* CREATE TABLE statement text */
8399 failIfSafeMode(p
, "cannot run .import in safe mode");
8400 memset(&sCtx
, 0, sizeof(sCtx
));
8401 if( p
->mode
==MODE_Ascii
){
8402 xRead
= ascii_read_one_field
;
8404 xRead
= csv_read_one_field
;
8407 for(i
=1; i
<nArg
; i
++){
8409 if( z
[0]=='-' && z
[1]=='-' ) z
++;
8413 }else if( zTable
==0 ){
8416 utf8_printf(p
->out
, "ERROR: extra argument: \"%s\". Usage:\n", z
);
8417 showHelp(p
->out
, "import");
8418 goto meta_command_exit
;
8420 }else if( cli_strcmp(z
,"-v")==0 ){
8422 }else if( cli_strcmp(z
,"-schema")==0 && i
<nArg
-1 ){
8423 zSchema
= azArg
[++i
];
8424 }else if( cli_strcmp(z
,"-skip")==0 && i
<nArg
-1 ){
8425 nSkip
= integerValue(azArg
[++i
]);
8426 }else if( cli_strcmp(z
,"-ascii")==0 ){
8427 sCtx
.cColSep
= SEP_Unit
[0];
8428 sCtx
.cRowSep
= SEP_Record
[0];
8429 xRead
= ascii_read_one_field
;
8431 }else if( cli_strcmp(z
,"-csv")==0 ){
8433 sCtx
.cRowSep
= '\n';
8434 xRead
= csv_read_one_field
;
8437 utf8_printf(p
->out
, "ERROR: unknown option: \"%s\". Usage:\n", z
);
8438 showHelp(p
->out
, "import");
8439 goto meta_command_exit
;
8443 utf8_printf(p
->out
, "ERROR: missing %s argument. Usage:\n",
8444 zFile
==0 ? "FILE" : "TABLE");
8445 showHelp(p
->out
, "import");
8446 goto meta_command_exit
;
8450 if( useOutputMode
){
8451 /* If neither the --csv or --ascii options are specified, then set
8452 ** the column and row separator characters from the output mode. */
8453 nSep
= strlen30(p
->colSeparator
);
8456 "Error: non-null column separator required for import\n");
8457 goto meta_command_exit
;
8461 "Error: multi-character column separators not allowed"
8463 goto meta_command_exit
;
8465 nSep
= strlen30(p
->rowSeparator
);
8468 "Error: non-null row separator required for import\n");
8469 goto meta_command_exit
;
8471 if( nSep
==2 && p
->mode
==MODE_Csv
8472 && cli_strcmp(p
->rowSeparator
,SEP_CrLf
)==0
8474 /* When importing CSV (only), if the row separator is set to the
8475 ** default output row separator, change it to the default input
8476 ** row separator. This avoids having to maintain different input
8477 ** and output row separators. */
8478 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8479 nSep
= strlen30(p
->rowSeparator
);
8482 raw_printf(stderr
, "Error: multi-character row separators not allowed"
8484 goto meta_command_exit
;
8486 sCtx
.cColSep
= p
->colSeparator
[0];
8487 sCtx
.cRowSep
= p
->rowSeparator
[0];
8491 if( sCtx
.zFile
[0]=='|' ){
8492 #ifdef SQLITE_OMIT_POPEN
8493 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
8494 goto meta_command_exit
;
8496 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
8497 sCtx
.zFile
= "<pipe>";
8498 sCtx
.xCloser
= pclose
;
8501 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
8502 sCtx
.xCloser
= fclose
;
8505 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
8506 goto meta_command_exit
;
8508 if( eVerbose
>=2 || (eVerbose
>=1 && useOutputMode
) ){
8511 zSep
[0] = sCtx
.cColSep
;
8512 utf8_printf(p
->out
, "Column separator ");
8513 output_c_string(p
->out
, zSep
);
8514 utf8_printf(p
->out
, ", row separator ");
8515 zSep
[0] = sCtx
.cRowSep
;
8516 output_c_string(p
->out
, zSep
);
8517 utf8_printf(p
->out
, "\n");
8519 sCtx
.z
= sqlite3_malloc64(120);
8521 import_cleanup(&sCtx
);
8522 shell_out_of_memory();
8524 /* Below, resources must be freed before exit. */
8525 while( (nSkip
--)>0 ){
8526 while( xRead(&sCtx
) && sCtx
.cTerm
==sCtx
.cColSep
){}
8529 zFullTabName
= sqlite3_mprintf("\"%w\".\"%w\"", zSchema
, zTable
);
8531 zFullTabName
= sqlite3_mprintf("\"%w\"", zTable
);
8533 zSql
= sqlite3_mprintf("SELECT * FROM %s", zFullTabName
);
8534 if( zSql
==0 || zFullTabName
==0 ){
8535 import_cleanup(&sCtx
);
8536 shell_out_of_memory();
8538 nByte
= strlen30(zSql
);
8539 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8540 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
8541 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
8542 sqlite3
*dbCols
= 0;
8545 zCreate
= sqlite3_mprintf("CREATE TABLE %s", zFullTabName
);
8546 while( xRead(&sCtx
) ){
8547 zAutoColumn(sCtx
.z
, &dbCols
, 0);
8548 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
8550 zColDefs
= zAutoColumn(0, &dbCols
, &zRenames
);
8552 utf8_printf((stdin_is_interactive
&& p
->in
==stdin
)? p
->out
: stderr
,
8553 "Columns renamed during .import %s due to duplicates:\n"
8554 "%s\n", sCtx
.zFile
, zRenames
);
8555 sqlite3_free(zRenames
);
8559 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
8561 sqlite3_free(zCreate
);
8563 sqlite3_free(zFullTabName
);
8564 import_cleanup(&sCtx
);
8566 goto meta_command_exit
;
8568 zCreate
= sqlite3_mprintf("%z%z\n", zCreate
, zColDefs
);
8570 utf8_printf(p
->out
, "%s\n", zCreate
);
8572 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
8574 utf8_printf(stderr
, "%s failed:\n%s\n", zCreate
, sqlite3_errmsg(p
->db
));
8577 sqlite3_free(zCreate
);
8579 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8582 if (pStmt
) sqlite3_finalize(pStmt
);
8583 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
8587 nCol
= sqlite3_column_count(pStmt
);
8588 sqlite3_finalize(pStmt
);
8590 if( nCol
==0 ) return 0; /* no columns, no error */
8591 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
8593 import_cleanup(&sCtx
);
8594 shell_out_of_memory();
8596 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO %s VALUES(?", zFullTabName
);
8598 for(i
=1; i
<nCol
; i
++){
8605 utf8_printf(p
->out
, "Insert using: %s\n", zSql
);
8607 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8609 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
8610 if (pStmt
) sqlite3_finalize(pStmt
);
8614 sqlite3_free(zFullTabName
);
8615 needCommit
= sqlite3_get_autocommit(p
->db
);
8616 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
8618 int startLine
= sCtx
.nLine
;
8619 for(i
=0; i
<nCol
; i
++){
8620 char *z
= xRead(&sCtx
);
8622 ** Did we reach end-of-file before finding any columns?
8623 ** If so, stop instead of NULL filling the remaining columns.
8625 if( z
==0 && i
==0 ) break;
8627 ** Did we reach end-of-file OR end-of-line before finding any
8628 ** columns in ASCII mode? If so, stop instead of NULL filling
8629 ** the remaining columns.
8631 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
8632 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
8633 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
8634 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
8635 "filling the rest with NULL\n",
8636 sCtx
.zFile
, startLine
, nCol
, i
+1);
8638 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
8641 if( sCtx
.cTerm
==sCtx
.cColSep
){
8645 }while( sCtx
.cTerm
==sCtx
.cColSep
);
8646 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
8648 sCtx
.zFile
, startLine
, nCol
, i
);
8651 sqlite3_step(pStmt
);
8652 rc
= sqlite3_reset(pStmt
);
8653 if( rc
!=SQLITE_OK
){
8654 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
8655 startLine
, sqlite3_errmsg(p
->db
));
8661 }while( sCtx
.cTerm
!=EOF
);
8663 import_cleanup(&sCtx
);
8664 sqlite3_finalize(pStmt
);
8665 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
8668 "Added %d rows with %d errors using %d lines of input\n",
8669 sCtx
.nRow
, sCtx
.nErr
, sCtx
.nLine
-1);
8672 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
8674 #ifndef SQLITE_UNTESTABLE
8675 if( c
=='i' && cli_strncmp(azArg
[0], "imposter", n
)==0 ){
8678 sqlite3_stmt
*pStmt
;
8680 int isWO
= 0; /* True if making an imposter of a WITHOUT ROWID table */
8681 int lenPK
= 0; /* Length of the PRIMARY KEY string for isWO tables */
8683 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
8684 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n"
8685 " .imposter off\n");
8686 /* Also allowed, but not documented:
8688 ** .imposter TABLE IMPOSTER
8690 ** where TABLE is a WITHOUT ROWID table. In that case, the
8691 ** imposter is another WITHOUT ROWID table with the columns in
8692 ** storage order. */
8694 goto meta_command_exit
;
8698 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
8699 goto meta_command_exit
;
8701 zSql
= sqlite3_mprintf(
8702 "SELECT rootpage, 0 FROM sqlite_schema"
8703 " WHERE name='%q' AND type='index'"
8705 "SELECT rootpage, 1 FROM sqlite_schema"
8706 " WHERE name='%q' AND type='table'"
8707 " AND sql LIKE '%%without%%rowid%%'",
8710 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8712 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
8713 tnum
= sqlite3_column_int(pStmt
, 0);
8714 isWO
= sqlite3_column_int(pStmt
, 1);
8716 sqlite3_finalize(pStmt
);
8717 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
8718 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
8721 while( rc
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
8723 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
8726 if( sqlite3_column_int(pStmt
,1)==-1 ){
8729 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
8733 if( isWO
&& lenPK
==0 && sqlite3_column_int(pStmt
,5)==0 && zCollist
){
8734 lenPK
= (int)strlen(zCollist
);
8737 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
8739 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
8742 sqlite3_finalize(pStmt
);
8743 if( i
==0 || tnum
==0 ){
8744 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
8746 sqlite3_free(zCollist
);
8747 goto meta_command_exit
;
8749 if( lenPK
==0 ) lenPK
= 100000;
8750 zSql
= sqlite3_mprintf(
8751 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8752 azArg
[2], zCollist
, lenPK
, zCollist
);
8753 sqlite3_free(zCollist
);
8754 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
8755 if( rc
==SQLITE_OK
){
8756 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
8757 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
8759 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
8761 utf8_printf(stdout
, "%s;\n", zSql
);
8763 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8764 azArg
[1], isWO
? "table" : "index"
8768 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
8773 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8775 #ifdef SQLITE_ENABLE_IOTRACE
8776 if( c
=='i' && cli_strncmp(azArg
[0], "iotrace", n
)==0 ){
8777 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
8778 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
8782 }else if( cli_strcmp(azArg
[1], "-")==0 ){
8783 sqlite3IoTrace
= iotracePrintf
;
8786 iotrace
= fopen(azArg
[1], "w");
8788 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
8792 sqlite3IoTrace
= iotracePrintf
;
8798 if( c
=='l' && n
>=5 && cli_strncmp(azArg
[0], "limits", n
)==0 ){
8799 static const struct {
8800 const char *zLimitName
; /* Name of a limit */
8801 int limitCode
; /* Integer code for that limit */
8803 { "length", SQLITE_LIMIT_LENGTH
},
8804 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
8805 { "column", SQLITE_LIMIT_COLUMN
},
8806 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
8807 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
8808 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
8809 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
8810 { "attached", SQLITE_LIMIT_ATTACHED
},
8811 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
8812 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
8813 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
8814 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
8819 for(i
=0; i
<ArraySize(aLimit
); i
++){
8820 printf("%20s %d\n", aLimit
[i
].zLimitName
,
8821 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
8824 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
8826 goto meta_command_exit
;
8829 n2
= strlen30(azArg
[1]);
8830 for(i
=0; i
<ArraySize(aLimit
); i
++){
8831 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
8835 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
8837 goto meta_command_exit
;
8842 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
8843 "enter \".limits\" with no arguments for a list.\n",
8846 goto meta_command_exit
;
8849 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
8850 (int)integerValue(azArg
[2]));
8852 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
8853 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
8857 if( c
=='l' && n
>2 && cli_strncmp(azArg
[0], "lint", n
)==0 ){
8859 lintDotCommand(p
, azArg
, nArg
);
8862 #if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
8863 if( c
=='l' && cli_strncmp(azArg
[0], "load", n
)==0 ){
8864 const char *zFile
, *zProc
;
8866 failIfSafeMode(p
, "cannot run .load in safe mode");
8868 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
8870 goto meta_command_exit
;
8873 zProc
= nArg
>=3 ? azArg
[2] : 0;
8875 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
8876 if( rc
!=SQLITE_OK
){
8877 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
8878 sqlite3_free(zErrMsg
);
8884 #ifndef SQLITE_SHELL_FIDDLE
8885 if( c
=='l' && cli_strncmp(azArg
[0], "log", n
)==0 ){
8886 failIfSafeMode(p
, "cannot run .log in safe mode");
8888 raw_printf(stderr
, "Usage: .log FILENAME\n");
8891 const char *zFile
= azArg
[1];
8892 output_file_close(p
->pLog
);
8893 p
->pLog
= output_file_open(zFile
, 0);
8898 if( c
=='m' && cli_strncmp(azArg
[0], "mode", n
)==0 ){
8899 const char *zMode
= 0;
8900 const char *zTabname
= 0;
8902 ColModeOpts cmOpts
= ColModeOpts_default
;
8903 for(i
=1; i
<nArg
; i
++){
8904 const char *z
= azArg
[i
];
8905 if( optionMatch(z
,"wrap") && i
+1<nArg
){
8906 cmOpts
.iWrap
= integerValue(azArg
[++i
]);
8907 }else if( optionMatch(z
,"ww") ){
8908 cmOpts
.bWordWrap
= 1;
8909 }else if( optionMatch(z
,"wordwrap") && i
+1<nArg
){
8910 cmOpts
.bWordWrap
= (u8
)booleanValue(azArg
[++i
]);
8911 }else if( optionMatch(z
,"quote") ){
8913 }else if( optionMatch(z
,"noquote") ){
8915 }else if( zMode
==0 ){
8917 /* Apply defaults for qbox pseudo-mode. If that
8918 * overwrites already-set values, user was informed of this.
8920 if( cli_strcmp(z
, "qbox")==0 ){
8921 ColModeOpts cmo
= ColModeOpts_default_qbox
;
8925 }else if( zTabname
==0 ){
8927 }else if( z
[0]=='-' ){
8928 utf8_printf(stderr
, "unknown option: %s\n", z
);
8929 utf8_printf(stderr
, "options:\n"
8932 " --wordwrap on/off\n"
8936 goto meta_command_exit
;
8938 utf8_printf(stderr
, "extra argument: \"%s\"\n", z
);
8940 goto meta_command_exit
;
8944 if( p
->mode
==MODE_Column
8945 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
8949 "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
8950 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
8951 p
->cmOpts
.bWordWrap
? "on" : "off",
8952 p
->cmOpts
.bQuote
? "" : "no");
8954 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
8956 zMode
= modeDescr
[p
->mode
];
8958 n2
= strlen30(zMode
);
8959 if( cli_strncmp(zMode
,"lines",n2
)==0 ){
8960 p
->mode
= MODE_Line
;
8961 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8962 }else if( cli_strncmp(zMode
,"columns",n2
)==0 ){
8963 p
->mode
= MODE_Column
;
8964 if( (p
->shellFlgs
& SHFLG_HeaderSet
)==0 ){
8967 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8969 }else if( cli_strncmp(zMode
,"list",n2
)==0 ){
8970 p
->mode
= MODE_List
;
8971 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
8972 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8973 }else if( cli_strncmp(zMode
,"html",n2
)==0 ){
8974 p
->mode
= MODE_Html
;
8975 }else if( cli_strncmp(zMode
,"tcl",n2
)==0 ){
8977 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
8978 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8979 }else if( cli_strncmp(zMode
,"csv",n2
)==0 ){
8981 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
8982 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
8983 }else if( cli_strncmp(zMode
,"tabs",n2
)==0 ){
8984 p
->mode
= MODE_List
;
8985 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
8986 }else if( cli_strncmp(zMode
,"insert",n2
)==0 ){
8987 p
->mode
= MODE_Insert
;
8988 set_table_name(p
, zTabname
? zTabname
: "table");
8989 }else if( cli_strncmp(zMode
,"quote",n2
)==0 ){
8990 p
->mode
= MODE_Quote
;
8991 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
8992 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
8993 }else if( cli_strncmp(zMode
,"ascii",n2
)==0 ){
8994 p
->mode
= MODE_Ascii
;
8995 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
8996 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
8997 }else if( cli_strncmp(zMode
,"markdown",n2
)==0 ){
8998 p
->mode
= MODE_Markdown
;
9000 }else if( cli_strncmp(zMode
,"table",n2
)==0 ){
9001 p
->mode
= MODE_Table
;
9003 }else if( cli_strncmp(zMode
,"box",n2
)==0 ){
9006 }else if( cli_strncmp(zMode
,"count",n2
)==0 ){
9007 p
->mode
= MODE_Count
;
9008 }else if( cli_strncmp(zMode
,"off",n2
)==0 ){
9010 }else if( cli_strncmp(zMode
,"json",n2
)==0 ){
9011 p
->mode
= MODE_Json
;
9013 raw_printf(stderr
, "Error: mode should be one of: "
9014 "ascii box column csv html insert json line list markdown "
9015 "qbox quote table tabs tcl\n");
9021 #ifndef SQLITE_SHELL_FIDDLE
9022 if( c
=='n' && cli_strcmp(azArg
[0], "nonce")==0 ){
9024 raw_printf(stderr
, "Usage: .nonce NONCE\n");
9026 }else if( p
->zNonce
==0 || cli_strcmp(azArg
[1],p
->zNonce
)!=0 ){
9027 raw_printf(stderr
, "line %d: incorrect nonce: \"%s\"\n",
9028 p
->lineno
, azArg
[1]);
9032 return 0; /* Return immediately to bypass the safe mode reset
9033 ** at the end of this procedure */
9036 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9038 if( c
=='n' && cli_strncmp(azArg
[0], "nullvalue", n
)==0 ){
9040 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
9041 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
9043 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
9048 if( c
=='o' && cli_strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
9049 const char *zFN
= 0; /* Pointer to constant filename */
9050 char *zNewFilename
= 0; /* Name of the database file to open */
9051 int iName
= 1; /* Index in azArg[] of the filename */
9052 int newFlag
= 0; /* True to delete file before opening */
9053 int openMode
= SHELL_OPEN_UNSPEC
;
9055 /* Check for command-line arguments */
9056 for(iName
=1; iName
<nArg
; iName
++){
9057 const char *z
= azArg
[iName
];
9058 #ifndef SQLITE_SHELL_FIDDLE
9059 if( optionMatch(z
,"new") ){
9061 #ifdef SQLITE_HAVE_ZLIB
9062 }else if( optionMatch(z
, "zip") ){
9063 openMode
= SHELL_OPEN_ZIPFILE
;
9065 }else if( optionMatch(z
, "append") ){
9066 openMode
= SHELL_OPEN_APPENDVFS
;
9067 }else if( optionMatch(z
, "readonly") ){
9068 openMode
= SHELL_OPEN_READONLY
;
9069 }else if( optionMatch(z
, "nofollow") ){
9070 p
->openFlags
|= SQLITE_OPEN_NOFOLLOW
;
9071 #ifndef SQLITE_OMIT_DESERIALIZE
9072 }else if( optionMatch(z
, "deserialize") ){
9073 openMode
= SHELL_OPEN_DESERIALIZE
;
9074 }else if( optionMatch(z
, "hexdb") ){
9075 openMode
= SHELL_OPEN_HEXDB
;
9076 }else if( optionMatch(z
, "maxsize") && iName
+1<nArg
){
9077 p
->szMax
= integerValue(azArg
[++iName
]);
9078 #endif /* SQLITE_OMIT_DESERIALIZE */
9080 #endif /* !SQLITE_SHELL_FIDDLE */
9082 utf8_printf(stderr
, "unknown option: %s\n", z
);
9084 goto meta_command_exit
;
9086 utf8_printf(stderr
, "extra argument: \"%s\"\n", z
);
9088 goto meta_command_exit
;
9094 /* Close the existing database */
9095 session_close_all(p
, -1);
9098 p
->pAuxDb
->zDbFilename
= 0;
9099 sqlite3_free(p
->pAuxDb
->zFreeOnClose
);
9100 p
->pAuxDb
->zFreeOnClose
= 0;
9101 p
->openMode
= openMode
;
9105 /* If a filename is specified, try to open it first */
9106 if( zFN
|| p
->openMode
==SHELL_OPEN_HEXDB
){
9107 if( newFlag
&& zFN
&& !p
->bSafeMode
) shellDeleteFile(zFN
);
9108 #ifndef SQLITE_SHELL_FIDDLE
9110 && p
->openMode
!=SHELL_OPEN_HEXDB
9112 && cli_strcmp(zFN
,":memory:")!=0
9114 failIfSafeMode(p
, "cannot open disk-based database files in safe mode");
9117 /* WASM mode has its own sandboxed pseudo-filesystem. */
9120 zNewFilename
= sqlite3_mprintf("%s", zFN
);
9121 shell_check_oom(zNewFilename
);
9125 p
->pAuxDb
->zDbFilename
= zNewFilename
;
9126 open_db(p
, OPEN_DB_KEEPALIVE
);
9128 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
9129 sqlite3_free(zNewFilename
);
9131 p
->pAuxDb
->zFreeOnClose
= zNewFilename
;
9135 /* As a fall-back open a TEMP database */
9136 p
->pAuxDb
->zDbFilename
= 0;
9141 #ifndef SQLITE_SHELL_FIDDLE
9143 && (cli_strncmp(azArg
[0], "output", n
)==0
9144 || cli_strncmp(azArg
[0], "once", n
)==0))
9145 || (c
=='e' && n
==5 && cli_strcmp(azArg
[0],"excel")==0)
9151 int bOnce
= 0; /* 0: .output, 1: .once, 2: .excel */
9152 unsigned char zBOM
[4]; /* Byte-order mark to using if --bom is present */
9155 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
9159 }else if( cli_strncmp(azArg
[0],"once",n
)==0 ){
9162 for(i
=1; i
<nArg
; i
++){
9165 if( z
[1]=='-' ) z
++;
9166 if( cli_strcmp(z
,"-bom")==0 ){
9171 }else if( c
!='e' && cli_strcmp(z
,"-x")==0 ){
9172 eMode
= 'x'; /* spreadsheet */
9173 }else if( c
!='e' && cli_strcmp(z
,"-e")==0 ){
9174 eMode
= 'e'; /* text editor */
9176 utf8_printf(p
->out
, "ERROR: unknown option: \"%s\". Usage:\n",
9178 showHelp(p
->out
, azArg
[0]);
9180 goto meta_command_exit
;
9182 }else if( zFile
==0 && eMode
!='e' && eMode
!='x' ){
9183 zFile
= sqlite3_mprintf("%s", z
);
9184 if( zFile
&& zFile
[0]=='|' ){
9185 while( i
+1<nArg
) zFile
= sqlite3_mprintf("%z %s", zFile
, azArg
[++i
]);
9189 utf8_printf(p
->out
,"ERROR: extra parameter: \"%s\". Usage:\n",
9191 showHelp(p
->out
, azArg
[0]);
9193 sqlite3_free(zFile
);
9194 goto meta_command_exit
;
9198 zFile
= sqlite3_mprintf("stdout");
9206 #ifndef SQLITE_NOHAVE_SYSTEM
9207 if( eMode
=='e' || eMode
=='x' ){
9211 /* spreadsheet mode. Output as CSV. */
9212 newTempFile(p
, "csv");
9213 ShellClearFlag(p
, SHFLG_Echo
);
9215 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
9216 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
9218 /* text editor mode */
9219 newTempFile(p
, "txt");
9222 sqlite3_free(zFile
);
9223 zFile
= sqlite3_mprintf("%s", p
->zTempFile
);
9225 #endif /* SQLITE_NOHAVE_SYSTEM */
9226 shell_check_oom(zFile
);
9227 if( zFile
[0]=='|' ){
9228 #ifdef SQLITE_OMIT_POPEN
9229 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
9233 p
->out
= popen(zFile
+ 1, "w");
9235 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
9239 if( zBOM
[0] ) fwrite(zBOM
, 1, 3, p
->out
);
9240 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9244 p
->out
= output_file_open(zFile
, bTxtMode
);
9246 if( cli_strcmp(zFile
,"off")!=0 ){
9247 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
9252 if( zBOM
[0] ) fwrite(zBOM
, 1, 3, p
->out
);
9253 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
9256 sqlite3_free(zFile
);
9258 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9260 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "parameter", n
)==0 ){
9262 if( nArg
<=1 ) goto parameter_syntax_error
;
9265 ** Clear all bind parameters by dropping the TEMP table that holds them.
9267 if( nArg
==2 && cli_strcmp(azArg
[1],"clear")==0 ){
9268 sqlite3_exec(p
->db
, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9273 ** List all bind parameters.
9275 if( nArg
==2 && cli_strcmp(azArg
[1],"list")==0 ){
9276 sqlite3_stmt
*pStmt
= 0;
9279 rx
= sqlite3_prepare_v2(p
->db
,
9280 "SELECT max(length(key)) "
9281 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9282 if( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9283 len
= sqlite3_column_int(pStmt
, 0);
9284 if( len
>40 ) len
= 40;
9286 sqlite3_finalize(pStmt
);
9289 rx
= sqlite3_prepare_v2(p
->db
,
9290 "SELECT key, quote(value) "
9291 "FROM temp.sqlite_parameters;", -1, &pStmt
, 0);
9292 while( rx
==SQLITE_OK
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
9293 utf8_printf(p
->out
, "%-*s %s\n", len
, sqlite3_column_text(pStmt
,0),
9294 sqlite3_column_text(pStmt
,1));
9296 sqlite3_finalize(pStmt
);
9301 ** Make sure the TEMP table used to hold bind parameters exists.
9302 ** Create it if necessary.
9304 if( nArg
==2 && cli_strcmp(azArg
[1],"init")==0 ){
9308 /* .parameter set NAME VALUE
9309 ** Set or reset a bind parameter. NAME should be the full parameter
9310 ** name exactly as it appears in the query. (ex: $abc, @def). The
9311 ** VALUE can be in either SQL literal notation, or if not it will be
9312 ** understood to be a text string.
9314 if( nArg
==4 && cli_strcmp(azArg
[1],"set")==0 ){
9317 sqlite3_stmt
*pStmt
;
9318 const char *zKey
= azArg
[2];
9319 const char *zValue
= azArg
[3];
9321 zSql
= sqlite3_mprintf(
9322 "REPLACE INTO temp.sqlite_parameters(key,value)"
9323 "VALUES(%Q,%s);", zKey
, zValue
);
9324 shell_check_oom(zSql
);
9326 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9328 if( rx
!=SQLITE_OK
){
9329 sqlite3_finalize(pStmt
);
9331 zSql
= sqlite3_mprintf(
9332 "REPLACE INTO temp.sqlite_parameters(key,value)"
9333 "VALUES(%Q,%Q);", zKey
, zValue
);
9334 shell_check_oom(zSql
);
9335 rx
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
9337 if( rx
!=SQLITE_OK
){
9338 utf8_printf(p
->out
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9339 sqlite3_finalize(pStmt
);
9344 sqlite3_step(pStmt
);
9345 sqlite3_finalize(pStmt
);
9348 /* .parameter unset NAME
9349 ** Remove the NAME binding from the parameter binding table, if it
9352 if( nArg
==3 && cli_strcmp(azArg
[1],"unset")==0 ){
9353 char *zSql
= sqlite3_mprintf(
9354 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg
[2]);
9355 shell_check_oom(zSql
);
9356 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
9359 /* If no command name matches, show a syntax error */
9360 parameter_syntax_error
:
9361 showHelp(p
->out
, "parameter");
9364 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "print", n
)==0 ){
9366 for(i
=1; i
<nArg
; i
++){
9367 if( i
>1 ) raw_printf(p
->out
, " ");
9368 utf8_printf(p
->out
, "%s", azArg
[i
]);
9370 raw_printf(p
->out
, "\n");
9373 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9374 if( c
=='p' && n
>=3 && cli_strncmp(azArg
[0], "progress", n
)==0 ){
9380 for(i
=1; i
<nArg
; i
++){
9381 const char *z
= azArg
[i
];
9384 if( z
[0]=='-' ) z
++;
9385 if( cli_strcmp(z
,"quiet")==0 || cli_strcmp(z
,"q")==0 ){
9386 p
->flgProgress
|= SHELL_PROGRESS_QUIET
;
9389 if( cli_strcmp(z
,"reset")==0 ){
9390 p
->flgProgress
|= SHELL_PROGRESS_RESET
;
9393 if( cli_strcmp(z
,"once")==0 ){
9394 p
->flgProgress
|= SHELL_PROGRESS_ONCE
;
9397 if( cli_strcmp(z
,"limit")==0 ){
9399 utf8_printf(stderr
, "Error: missing argument on --limit\n");
9401 goto meta_command_exit
;
9403 p
->mxProgress
= (int)integerValue(azArg
[++i
]);
9407 utf8_printf(stderr
, "Error: unknown option: \"%s\"\n", azArg
[i
]);
9409 goto meta_command_exit
;
9411 nn
= (int)integerValue(z
);
9415 sqlite3_progress_handler(p
->db
, nn
, progress_handler
, p
);
9417 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9419 if( c
=='p' && cli_strncmp(azArg
[0], "prompt", n
)==0 ){
9421 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
9424 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
9428 #ifndef SQLITE_SHELL_FIDDLE
9429 if( c
=='q' && cli_strncmp(azArg
[0], "quit", n
)==0 ){
9434 #ifndef SQLITE_SHELL_FIDDLE
9435 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "read", n
)==0 ){
9436 FILE *inSaved
= p
->in
;
9437 int savedLineno
= p
->lineno
;
9438 failIfSafeMode(p
, "cannot run .read in safe mode");
9440 raw_printf(stderr
, "Usage: .read FILE\n");
9442 goto meta_command_exit
;
9444 if( azArg
[1][0]=='|' ){
9445 #ifdef SQLITE_OMIT_POPEN
9446 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
9450 p
->in
= popen(azArg
[1]+1, "r");
9452 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
9455 rc
= process_input(p
);
9459 }else if( (p
->in
= openChrSource(azArg
[1]))==0 ){
9460 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
9463 rc
= process_input(p
);
9467 p
->lineno
= savedLineno
;
9469 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9471 #ifndef SQLITE_SHELL_FIDDLE
9472 if( c
=='r' && n
>=3 && cli_strncmp(azArg
[0], "restore", n
)==0 ){
9473 const char *zSrcFile
;
9476 sqlite3_backup
*pBackup
;
9479 failIfSafeMode(p
, "cannot run .restore in safe mode");
9481 zSrcFile
= azArg
[1];
9483 }else if( nArg
==3 ){
9484 zSrcFile
= azArg
[2];
9487 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
9489 goto meta_command_exit
;
9491 rc
= sqlite3_open(zSrcFile
, &pSrc
);
9492 if( rc
!=SQLITE_OK
){
9493 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
9498 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
9500 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9504 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
9505 || rc
==SQLITE_BUSY
){
9506 if( rc
==SQLITE_BUSY
){
9507 if( nTimeout
++ >= 3 ) break;
9511 sqlite3_backup_finish(pBackup
);
9512 if( rc
==SQLITE_DONE
){
9514 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
9515 raw_printf(stderr
, "Error: source database is busy\n");
9518 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9523 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
9525 if( c
=='s' && cli_strncmp(azArg
[0], "scanstats", n
)==0 ){
9527 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
9528 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9529 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
9532 raw_printf(stderr
, "Usage: .scanstats on|off\n");
9537 if( c
=='s' && cli_strncmp(azArg
[0], "schema", n
)==0 ){
9541 const char *zDiv
= "(";
9542 const char *zName
= 0;
9545 int bNoSystemTabs
= 0;
9549 memcpy(&data
, p
, sizeof(data
));
9550 data
.showHeader
= 0;
9551 data
.cMode
= data
.mode
= MODE_Semi
;
9553 for(ii
=1; ii
<nArg
; ii
++){
9554 if( optionMatch(azArg
[ii
],"indent") ){
9555 data
.cMode
= data
.mode
= MODE_Pretty
;
9556 }else if( optionMatch(azArg
[ii
],"debug") ){
9558 }else if( optionMatch(azArg
[ii
],"nosys") ){
9560 }else if( azArg
[ii
][0]=='-' ){
9561 utf8_printf(stderr
, "Unknown option: \"%s\"\n", azArg
[ii
]);
9563 goto meta_command_exit
;
9564 }else if( zName
==0 ){
9567 raw_printf(stderr
, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9569 goto meta_command_exit
;
9573 int isSchema
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0
9574 || sqlite3_strlike(zName
, "sqlite_schema", '\\')==0
9575 || sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0
9576 || sqlite3_strlike(zName
,"sqlite_temp_schema", '\\')==0;
9578 char *new_argv
[2], *new_colv
[2];
9579 new_argv
[0] = sqlite3_mprintf(
9580 "CREATE TABLE %s (\n"
9584 " rootpage integer,\n"
9587 shell_check_oom(new_argv
[0]);
9589 new_colv
[0] = "sql";
9591 callback(&data
, 1, new_argv
, new_colv
);
9592 sqlite3_free(new_argv
[0]);
9596 sqlite3_stmt
*pStmt
= 0;
9597 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
9600 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
9601 sqlite3_finalize(pStmt
);
9603 goto meta_command_exit
;
9605 appendText(&sSelect
, "SELECT sql FROM", 0);
9607 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
9608 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
9610 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
9611 appendText(&sSelect
, zDiv
, 0);
9612 zDiv
= " UNION ALL ";
9613 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
9614 if( sqlite3_stricmp(zDb
, "main")!=0 ){
9615 appendText(&sSelect
, zDb
, '\'');
9617 appendText(&sSelect
, "NULL", 0);
9619 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9620 appendText(&sSelect
, zScNum
, 0);
9621 appendText(&sSelect
, " AS snum, ", 0);
9622 appendText(&sSelect
, zDb
, '\'');
9623 appendText(&sSelect
, " AS sname FROM ", 0);
9624 appendText(&sSelect
, zDb
, quoteChar(zDb
));
9625 appendText(&sSelect
, ".sqlite_schema", 0);
9627 sqlite3_finalize(pStmt
);
9628 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9630 appendText(&sSelect
,
9631 " UNION ALL SELECT shell_module_schema(name),"
9632 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9636 appendText(&sSelect
, ") WHERE ", 0);
9638 char *zQarg
= sqlite3_mprintf("%Q", zName
);
9640 shell_check_oom(zQarg
);
9641 bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
9642 strchr(zName
, '[') != 0;
9643 if( strchr(zName
, '.') ){
9644 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
9646 appendText(&sSelect
, "lower(tbl_name)", 0);
9648 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
9649 appendText(&sSelect
, zQarg
, 0);
9651 appendText(&sSelect
, " ESCAPE '\\' ", 0);
9653 appendText(&sSelect
, " AND ", 0);
9654 sqlite3_free(zQarg
);
9656 if( bNoSystemTabs
){
9657 appendText(&sSelect
, "name NOT LIKE 'sqlite_%%' AND ", 0);
9659 appendText(&sSelect
, "sql IS NOT NULL"
9660 " ORDER BY snum, rowid", 0);
9662 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
9664 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
9669 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
9670 sqlite3_free(zErrMsg
);
9672 }else if( rc
!= SQLITE_OK
){
9673 raw_printf(stderr
,"Error: querying schema information\n");
9680 if( (c
=='s' && n
==11 && cli_strncmp(azArg
[0], "selecttrace", n
)==0)
9681 || (c
=='t' && n
==9 && cli_strncmp(azArg
[0], "treetrace", n
)==0)
9683 unsigned int x
= nArg
>=2 ? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
9684 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 1, &x
);
9687 #if defined(SQLITE_ENABLE_SESSION)
9688 if( c
=='s' && cli_strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
9689 struct AuxDb
*pAuxDb
= p
->pAuxDb
;
9690 OpenSession
*pSession
= &pAuxDb
->aSession
[0];
9691 char **azCmd
= &azArg
[1];
9693 int nCmd
= nArg
- 1;
9695 if( nArg
<=1 ) goto session_syntax_error
;
9698 for(iSes
=0; iSes
<pAuxDb
->nSession
; iSes
++){
9699 if( cli_strcmp(pAuxDb
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
9701 if( iSes
<pAuxDb
->nSession
){
9702 pSession
= &pAuxDb
->aSession
[iSes
];
9706 pSession
= &pAuxDb
->aSession
[0];
9711 /* .session attach TABLE
9712 ** Invoke the sqlite3session_attach() interface to attach a particular
9713 ** table so that it is never filtered.
9715 if( cli_strcmp(azCmd
[0],"attach")==0 ){
9716 if( nCmd
!=2 ) goto session_syntax_error
;
9717 if( pSession
->p
==0 ){
9719 raw_printf(stderr
, "ERROR: No sessions are open\n");
9721 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
9723 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
9729 /* .session changeset FILE
9730 ** .session patchset FILE
9731 ** Write a changeset or patchset into a file. The file is overwritten.
9733 if( cli_strcmp(azCmd
[0],"changeset")==0
9734 || cli_strcmp(azCmd
[0],"patchset")==0
9737 failIfSafeMode(p
, "cannot run \".session %s\" in safe mode", azCmd
[0]);
9738 if( nCmd
!=2 ) goto session_syntax_error
;
9739 if( pSession
->p
==0 ) goto session_not_open
;
9740 out
= fopen(azCmd
[1], "wb");
9742 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n",
9747 if( azCmd
[0][0]=='c' ){
9748 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
9750 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
9753 printf("Error: error code %d\n", rc
);
9757 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
9758 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
9761 sqlite3_free(pChng
);
9767 ** Close the identified session
9769 if( cli_strcmp(azCmd
[0], "close")==0 ){
9770 if( nCmd
!=1 ) goto session_syntax_error
;
9771 if( pAuxDb
->nSession
){
9772 session_close(pSession
);
9773 pAuxDb
->aSession
[iSes
] = pAuxDb
->aSession
[--pAuxDb
->nSession
];
9777 /* .session enable ?BOOLEAN?
9778 ** Query or set the enable flag
9780 if( cli_strcmp(azCmd
[0], "enable")==0 ){
9782 if( nCmd
>2 ) goto session_syntax_error
;
9783 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
9784 if( pAuxDb
->nSession
){
9785 ii
= sqlite3session_enable(pSession
->p
, ii
);
9786 utf8_printf(p
->out
, "session %s enable flag = %d\n",
9787 pSession
->zName
, ii
);
9791 /* .session filter GLOB ....
9792 ** Set a list of GLOB patterns of table names to be excluded.
9794 if( cli_strcmp(azCmd
[0], "filter")==0 ){
9796 if( nCmd
<2 ) goto session_syntax_error
;
9797 if( pAuxDb
->nSession
){
9798 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
9799 sqlite3_free(pSession
->azFilter
[ii
]);
9801 sqlite3_free(pSession
->azFilter
);
9802 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
9803 pSession
->azFilter
= sqlite3_malloc( nByte
);
9804 if( pSession
->azFilter
==0 ){
9805 raw_printf(stderr
, "Error: out or memory\n");
9808 for(ii
=1; ii
<nCmd
; ii
++){
9809 char *x
= pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
9812 pSession
->nFilter
= ii
-1;
9816 /* .session indirect ?BOOLEAN?
9817 ** Query or set the indirect flag
9819 if( cli_strcmp(azCmd
[0], "indirect")==0 ){
9821 if( nCmd
>2 ) goto session_syntax_error
;
9822 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
9823 if( pAuxDb
->nSession
){
9824 ii
= sqlite3session_indirect(pSession
->p
, ii
);
9825 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
9826 pSession
->zName
, ii
);
9831 ** Determine if the session is empty
9833 if( cli_strcmp(azCmd
[0], "isempty")==0 ){
9835 if( nCmd
!=1 ) goto session_syntax_error
;
9836 if( pAuxDb
->nSession
){
9837 ii
= sqlite3session_isempty(pSession
->p
);
9838 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
9839 pSession
->zName
, ii
);
9844 ** List all currently open sessions
9846 if( cli_strcmp(azCmd
[0],"list")==0 ){
9847 for(i
=0; i
<pAuxDb
->nSession
; i
++){
9848 utf8_printf(p
->out
, "%d %s\n", i
, pAuxDb
->aSession
[i
].zName
);
9852 /* .session open DB NAME
9853 ** Open a new session called NAME on the attached database DB.
9854 ** DB is normally "main".
9856 if( cli_strcmp(azCmd
[0],"open")==0 ){
9858 if( nCmd
!=3 ) goto session_syntax_error
;
9860 if( zName
[0]==0 ) goto session_syntax_error
;
9861 for(i
=0; i
<pAuxDb
->nSession
; i
++){
9862 if( cli_strcmp(pAuxDb
->aSession
[i
].zName
,zName
)==0 ){
9863 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
9864 goto meta_command_exit
;
9867 if( pAuxDb
->nSession
>=ArraySize(pAuxDb
->aSession
) ){
9868 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(pAuxDb
->aSession
));
9869 goto meta_command_exit
;
9871 pSession
= &pAuxDb
->aSession
[pAuxDb
->nSession
];
9872 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
9874 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
9876 goto meta_command_exit
;
9878 pSession
->nFilter
= 0;
9879 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
9881 pSession
->zName
= sqlite3_mprintf("%s", zName
);
9882 shell_check_oom(pSession
->zName
);
9884 /* If no command name matches, show a syntax error */
9885 session_syntax_error
:
9886 showHelp(p
->out
, "session");
9891 /* Undocumented commands for internal testing. Subject to change
9892 ** without notice. */
9893 if( c
=='s' && n
>=10 && cli_strncmp(azArg
[0], "selftest-", 9)==0 ){
9894 if( cli_strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
9896 for(i
=1; i
<nArg
; i
++){
9897 v
= booleanValue(azArg
[i
]);
9898 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
9901 if( cli_strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
9902 int i
; sqlite3_int64 v
;
9903 for(i
=1; i
<nArg
; i
++){
9905 v
= integerValue(azArg
[i
]);
9906 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
9907 utf8_printf(p
->out
, "%s", zBuf
);
9913 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"selftest",n
)==0 ){
9914 int bIsInit
= 0; /* True to initialize the SELFTEST table */
9915 int bVerbose
= 0; /* Verbose output */
9916 int bSelftestExists
; /* True if SELFTEST already exists */
9917 int i
, k
; /* Loop counters */
9918 int nTest
= 0; /* Number of tests runs */
9919 int nErr
= 0; /* Number of errors seen */
9920 ShellText str
; /* Answer for a query */
9921 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
9924 for(i
=1; i
<nArg
; i
++){
9925 const char *z
= azArg
[i
];
9926 if( z
[0]=='-' && z
[1]=='-' ) z
++;
9927 if( cli_strcmp(z
,"-init")==0 ){
9930 if( cli_strcmp(z
,"-v")==0 ){
9934 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
9935 azArg
[i
], azArg
[0]);
9936 raw_printf(stderr
, "Should be one of: --init -v\n");
9938 goto meta_command_exit
;
9941 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
9943 bSelftestExists
= 0;
9945 bSelftestExists
= 1;
9948 createSelftestTable(p
);
9949 bSelftestExists
= 1;
9952 appendText(&str
, "x", 0);
9953 for(k
=bSelftestExists
; k
>=0; k
--){
9955 rc
= sqlite3_prepare_v2(p
->db
,
9956 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9959 rc
= sqlite3_prepare_v2(p
->db
,
9960 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9961 " (1,'run','PRAGMA integrity_check','ok')",
9965 raw_printf(stderr
, "Error querying the selftest table\n");
9967 sqlite3_finalize(pStmt
);
9968 goto meta_command_exit
;
9970 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
9971 int tno
= sqlite3_column_int(pStmt
, 0);
9972 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
9973 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
9974 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
9976 if( zOp
==0 ) continue;
9977 if( zSql
==0 ) continue;
9978 if( zAns
==0 ) continue;
9981 printf("%d: %s %s\n", tno
, zOp
, zSql
);
9983 if( cli_strcmp(zOp
,"memo")==0 ){
9984 utf8_printf(p
->out
, "%s\n", zSql
);
9986 if( cli_strcmp(zOp
,"run")==0 ){
9990 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
9993 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
9995 if( rc
|| zErrMsg
){
9998 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
9999 sqlite3_free(zErrMsg
);
10000 }else if( cli_strcmp(zAns
,str
.z
)!=0 ){
10003 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
10004 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
10008 utf8_printf(stderr
,
10009 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
10013 } /* End loop over rows of content from SELFTEST */
10014 sqlite3_finalize(pStmt
);
10015 } /* End loop over k */
10017 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
10020 if( c
=='s' && cli_strncmp(azArg
[0], "separator", n
)==0 ){
10021 if( nArg
<2 || nArg
>3 ){
10022 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
10026 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
10027 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
10030 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
10031 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
10035 if( c
=='s' && n
>=4 && cli_strncmp(azArg
[0],"sha3sum",n
)==0 ){
10036 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
10037 int i
; /* Loop counter */
10038 int bSchema
= 0; /* Also hash the schema */
10039 int bSeparate
= 0; /* Hash each table separately */
10040 int iSize
= 224; /* Hash algorithm to use */
10041 int bDebug
= 0; /* Only show the query that would have run */
10042 sqlite3_stmt
*pStmt
; /* For querying tables names */
10043 char *zSql
; /* SQL to be run */
10044 char *zSep
; /* Separator */
10045 ShellText sSql
; /* Complete SQL for the query to run the hash */
10046 ShellText sQuery
; /* Set of queries used to read all content */
10048 for(i
=1; i
<nArg
; i
++){
10049 const char *z
= azArg
[i
];
10052 if( z
[0]=='-' ) z
++;
10053 if( cli_strcmp(z
,"schema")==0 ){
10056 if( cli_strcmp(z
,"sha3-224")==0 || cli_strcmp(z
,"sha3-256")==0
10057 || cli_strcmp(z
,"sha3-384")==0 || cli_strcmp(z
,"sha3-512")==0
10059 iSize
= atoi(&z
[5]);
10061 if( cli_strcmp(z
,"debug")==0 ){
10065 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
10066 azArg
[i
], azArg
[0]);
10067 showHelp(p
->out
, azArg
[0]);
10069 goto meta_command_exit
;
10072 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10074 goto meta_command_exit
;
10078 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
10082 zSql
= "SELECT lower(name) FROM sqlite_schema"
10083 " WHERE type='table' AND coalesce(rootpage,0)>1"
10084 " UNION ALL SELECT 'sqlite_schema'"
10085 " ORDER BY 1 collate nocase";
10087 zSql
= "SELECT lower(name) FROM sqlite_schema"
10088 " WHERE type='table' AND coalesce(rootpage,0)>1"
10089 " AND name NOT LIKE 'sqlite_%'"
10090 " ORDER BY 1 collate nocase";
10092 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
10095 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
10097 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
10098 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
10099 if( zTab
==0 ) continue;
10100 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
10101 if( cli_strncmp(zTab
, "sqlite_",7)!=0 ){
10102 appendText(&sQuery
,"SELECT * FROM ", 0);
10103 appendText(&sQuery
,zTab
,'"');
10104 appendText(&sQuery
," NOT INDEXED;", 0);
10105 }else if( cli_strcmp(zTab
, "sqlite_schema")==0 ){
10106 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10107 " ORDER BY name;", 0);
10108 }else if( cli_strcmp(zTab
, "sqlite_sequence")==0 ){
10109 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
10110 " ORDER BY name;", 0);
10111 }else if( cli_strcmp(zTab
, "sqlite_stat1")==0 ){
10112 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
10113 " ORDER BY tbl,idx;", 0);
10114 }else if( cli_strcmp(zTab
, "sqlite_stat4")==0 ){
10115 appendText(&sQuery
, "SELECT * FROM ", 0);
10116 appendText(&sQuery
, zTab
, 0);
10117 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
10119 appendText(&sSql
, zSep
, 0);
10120 appendText(&sSql
, sQuery
.z
, '\'');
10122 appendText(&sSql
, ",", 0);
10123 appendText(&sSql
, zTab
, '\'');
10126 sqlite3_finalize(pStmt
);
10128 zSql
= sqlite3_mprintf(
10130 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10131 " FROM [sha3sum$query]",
10134 zSql
= sqlite3_mprintf(
10136 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10137 " FROM [sha3sum$query]",
10140 shell_check_oom(zSql
);
10144 utf8_printf(p
->out
, "%s\n", zSql
);
10146 shell_exec(p
, zSql
, 0);
10148 sqlite3_free(zSql
);
10151 #if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10153 && (cli_strncmp(azArg
[0], "shell", n
)==0
10154 || cli_strncmp(azArg
[0],"system",n
)==0)
10158 failIfSafeMode(p
, "cannot run .%s in safe mode", azArg
[0]);
10160 raw_printf(stderr
, "Usage: .system COMMAND\n");
10162 goto meta_command_exit
;
10164 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
10165 for(i
=2; i
<nArg
&& zCmd
!=0; i
++){
10166 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
10169 x
= zCmd
!=0 ? system(zCmd
) : 1;
10170 sqlite3_free(zCmd
);
10171 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
10173 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10175 if( c
=='s' && cli_strncmp(azArg
[0], "show", n
)==0 ){
10176 static const char *azBool
[] = { "off", "on", "trigger", "full"};
10180 raw_printf(stderr
, "Usage: .show\n");
10182 goto meta_command_exit
;
10184 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
10185 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
10186 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
10187 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
10188 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
10189 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
10190 if( p
->mode
==MODE_Column
10191 || (p
->mode
>=MODE_Markdown
&& p
->mode
<=MODE_Box
)
10194 (p
->out
, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10195 modeDescr
[p
->mode
], p
->cmOpts
.iWrap
,
10196 p
->cmOpts
.bWordWrap
? "on" : "off",
10197 p
->cmOpts
.bQuote
? "" : "no");
10199 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
10201 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
10202 output_c_string(p
->out
, p
->nullValue
);
10203 raw_printf(p
->out
, "\n");
10204 utf8_printf(p
->out
,"%12.12s: %s\n","output",
10205 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
10206 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
10207 output_c_string(p
->out
, p
->colSeparator
);
10208 raw_printf(p
->out
, "\n");
10209 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
10210 output_c_string(p
->out
, p
->rowSeparator
);
10211 raw_printf(p
->out
, "\n");
10212 switch( p
->statsOn
){
10213 case 0: zOut
= "off"; break;
10214 default: zOut
= "on"; break;
10215 case 2: zOut
= "stmt"; break;
10216 case 3: zOut
= "vmstep"; break;
10218 utf8_printf(p
->out
, "%12.12s: %s\n","stats", zOut
);
10219 utf8_printf(p
->out
, "%12.12s: ", "width");
10220 for (i
=0;i
<p
->nWidth
;i
++) {
10221 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
10223 raw_printf(p
->out
, "\n");
10224 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
10225 p
->pAuxDb
->zDbFilename
? p
->pAuxDb
->zDbFilename
: "");
10228 if( c
=='s' && cli_strncmp(azArg
[0], "stats", n
)==0 ){
10230 if( cli_strcmp(azArg
[1],"stmt")==0 ){
10232 }else if( cli_strcmp(azArg
[1],"vmstep")==0 ){
10235 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
10237 }else if( nArg
==1 ){
10238 display_stats(p
->db
, p
, 0);
10240 raw_printf(stderr
, "Usage: .stats ?on|off|stmt|vmstep?\n");
10245 if( (c
=='t' && n
>1 && cli_strncmp(azArg
[0], "tables", n
)==0)
10246 || (c
=='i' && (cli_strncmp(azArg
[0], "indices", n
)==0
10247 || cli_strncmp(azArg
[0], "indexes", n
)==0) )
10249 sqlite3_stmt
*pStmt
;
10256 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
10258 sqlite3_finalize(pStmt
);
10259 return shellDatabaseError(p
->db
);
10262 if( nArg
>2 && c
=='i' ){
10263 /* It is an historical accident that the .indexes command shows an error
10264 ** when called with the wrong number of arguments whereas the .tables
10265 ** command does not. */
10266 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
10268 sqlite3_finalize(pStmt
);
10269 goto meta_command_exit
;
10271 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
10272 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
10273 if( zDbName
==0 ) continue;
10274 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
10275 if( sqlite3_stricmp(zDbName
, "main")==0 ){
10276 appendText(&s
, "SELECT name FROM ", 0);
10278 appendText(&s
, "SELECT ", 0);
10279 appendText(&s
, zDbName
, '\'');
10280 appendText(&s
, "||'.'||name FROM ", 0);
10282 appendText(&s
, zDbName
, '"');
10283 appendText(&s
, ".sqlite_schema ", 0);
10285 appendText(&s
," WHERE type IN ('table','view')"
10286 " AND name NOT LIKE 'sqlite_%'"
10287 " AND name LIKE ?1", 0);
10289 appendText(&s
," WHERE type='index'"
10290 " AND tbl_name LIKE ?1", 0);
10293 rc
= sqlite3_finalize(pStmt
);
10294 if( rc
==SQLITE_OK
){
10295 appendText(&s
, " ORDER BY 1", 0);
10296 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
10299 if( rc
) return shellDatabaseError(p
->db
);
10301 /* Run the SQL statement prepared by the above block. Store the results
10302 ** as an array of nul-terminated strings in azResult[]. */
10306 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
10308 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
10310 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
10311 if( nRow
>=nAlloc
){
10313 int n2
= nAlloc
*2 + 10;
10314 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
10315 shell_check_oom(azNew
);
10319 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
10320 shell_check_oom(azResult
[nRow
]);
10323 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
10324 rc
= shellDatabaseError(p
->db
);
10327 /* Pretty-print the contents of array azResult[] to the output */
10328 if( rc
==0 && nRow
>0 ){
10329 int len
, maxlen
= 0;
10331 int nPrintCol
, nPrintRow
;
10332 for(i
=0; i
<nRow
; i
++){
10333 len
= strlen30(azResult
[i
]);
10334 if( len
>maxlen
) maxlen
= len
;
10336 nPrintCol
= 80/(maxlen
+2);
10337 if( nPrintCol
<1 ) nPrintCol
= 1;
10338 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
10339 for(i
=0; i
<nPrintRow
; i
++){
10340 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
10341 char *zSp
= j
<nPrintRow
? "" : " ";
10342 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
10343 azResult
[j
] ? azResult
[j
]:"");
10345 raw_printf(p
->out
, "\n");
10349 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
10350 sqlite3_free(azResult
);
10353 #ifndef SQLITE_SHELL_FIDDLE
10354 /* Begin redirecting output to the file "testcase-out.txt" */
10355 if( c
=='t' && cli_strcmp(azArg
[0],"testcase")==0 ){
10357 p
->out
= output_file_open("testcase-out.txt", 0);
10359 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
10362 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
10364 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
10367 #endif /* !defined(SQLITE_SHELL_FIDDLE) */
10369 #ifndef SQLITE_UNTESTABLE
10370 if( c
=='t' && n
>=8 && cli_strncmp(azArg
[0], "testctrl", n
)==0 ){
10371 static const struct {
10372 const char *zCtrlName
; /* Name of a test-control option */
10373 int ctrlCode
; /* Integer code for that option */
10374 int unSafe
; /* Not valid for --safe mode */
10375 const char *zUsage
; /* Usage notes */
10377 { "always", SQLITE_TESTCTRL_ALWAYS
, 1, "BOOLEAN" },
10378 { "assert", SQLITE_TESTCTRL_ASSERT
, 1, "BOOLEAN" },
10379 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/
10380 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/
10381 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, 0, "" },
10382 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS
,0,"BOOLEAN" },
10383 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
10384 { "imposter", SQLITE_TESTCTRL_IMPOSTER
,1,"SCHEMA ON/OFF ROOTPAGE"},
10385 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
,0,"" },
10386 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,0,"BOOLEAN" },
10387 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
,1, "BOOLEAN" },
10388 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
,0,"DISABLE-MASK" },
10390 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
,0,"" },
10392 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
,0, "OFFSET " },
10393 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
,0, "" },
10394 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, 0, "" },
10395 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED
, 0, "SEED ?db?" },
10396 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT
, 0, "" },
10397 { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP
, 0, "NMAX" },
10398 { "tune", SQLITE_TESTCTRL_TUNE
, 1, "ID VALUE" },
10402 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
10405 const char *zCmd
= 0;
10408 zCmd
= nArg
>=2 ? azArg
[1] : "help";
10410 /* The argument can optionally begin with "-" or "--" */
10411 if( zCmd
[0]=='-' && zCmd
[1] ){
10413 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
10416 /* --help lists all test-controls */
10417 if( cli_strcmp(zCmd
,"help")==0 ){
10418 utf8_printf(p
->out
, "Available test-controls:\n");
10419 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10420 utf8_printf(p
->out
, " .testctrl %s %s\n",
10421 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
10424 goto meta_command_exit
;
10427 /* convert testctrl text option to value. allow any unique prefix
10428 ** of the option name, or a numerical value. */
10429 n2
= strlen30(zCmd
);
10430 for(i
=0; i
<ArraySize(aCtrl
); i
++){
10431 if( cli_strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
10433 testctrl
= aCtrl
[i
].ctrlCode
;
10436 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
10437 "Use \".testctrl --help\" for help\n", zCmd
);
10439 goto meta_command_exit
;
10444 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
10445 "Use \".testctrl --help\" for help\n", zCmd
);
10446 }else if( aCtrl
[iCtrl
].unSafe
&& p
->bSafeMode
){
10447 utf8_printf(stderr
,
10448 "line %d: \".testctrl %s\" may not be used in safe mode\n",
10449 p
->lineno
, aCtrl
[iCtrl
].zCtrlName
);
10454 /* sqlite3_test_control(int, db, int) */
10455 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
10457 unsigned int opt
= (unsigned int)strtol(azArg
[2], 0, 0);
10458 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
10463 /* sqlite3_test_control(int) */
10464 case SQLITE_TESTCTRL_PRNG_SAVE
:
10465 case SQLITE_TESTCTRL_PRNG_RESTORE
:
10466 case SQLITE_TESTCTRL_BYTEORDER
:
10468 rc2
= sqlite3_test_control(testctrl
);
10469 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
10473 /* sqlite3_test_control(int, uint) */
10474 case SQLITE_TESTCTRL_PENDING_BYTE
:
10476 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
10477 rc2
= sqlite3_test_control(testctrl
, opt
);
10482 /* sqlite3_test_control(int, int, sqlite3*) */
10483 case SQLITE_TESTCTRL_PRNG_SEED
:
10484 if( nArg
==3 || nArg
==4 ){
10485 int ii
= (int)integerValue(azArg
[2]);
10487 if( ii
==0 && cli_strcmp(azArg
[2],"random")==0 ){
10488 sqlite3_randomness(sizeof(ii
),&ii
);
10489 printf("-- random seed: %d\n", ii
);
10495 /* Make sure the schema has been loaded */
10496 sqlite3_table_column_metadata(db
, 0, "x", 0, 0, 0, 0, 0, 0);
10498 rc2
= sqlite3_test_control(testctrl
, ii
, db
);
10503 /* sqlite3_test_control(int, int) */
10504 case SQLITE_TESTCTRL_ASSERT
:
10505 case SQLITE_TESTCTRL_ALWAYS
:
10507 int opt
= booleanValue(azArg
[2]);
10508 rc2
= sqlite3_test_control(testctrl
, opt
);
10513 /* sqlite3_test_control(int, int) */
10514 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
10515 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
10517 int opt
= booleanValue(azArg
[2]);
10518 rc2
= sqlite3_test_control(testctrl
, opt
);
10523 /* sqlite3_test_control(sqlite3*) */
10524 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
:
10525 rc2
= sqlite3_test_control(testctrl
, p
->db
);
10529 case SQLITE_TESTCTRL_IMPOSTER
:
10531 rc2
= sqlite3_test_control(testctrl
, p
->db
,
10533 integerValue(azArg
[3]),
10534 integerValue(azArg
[4]));
10539 case SQLITE_TESTCTRL_SEEK_COUNT
: {
10541 rc2
= sqlite3_test_control(testctrl
, p
->db
, &x
);
10542 utf8_printf(p
->out
, "%llu\n", x
);
10548 case SQLITE_TESTCTRL_PARSER_COVERAGE
: {
10550 sqlite3_test_control(testctrl
, p
->out
);
10556 #ifdef SQLITE_DEBUG
10557 case SQLITE_TESTCTRL_TUNE
: {
10559 int id
= (int)integerValue(azArg
[2]);
10560 int val
= (int)integerValue(azArg
[3]);
10561 sqlite3_test_control(testctrl
, id
, &val
);
10563 }else if( nArg
==3 ){
10564 int id
= (int)integerValue(azArg
[2]);
10565 sqlite3_test_control(testctrl
, -id
, &rc2
);
10567 }else if( nArg
==2 ){
10571 rc2
= sqlite3_test_control(testctrl
, -id
, &val
);
10572 if( rc2
!=SQLITE_OK
) break;
10573 if( id
>1 ) utf8_printf(p
->out
, " ");
10574 utf8_printf(p
->out
, "%d: %d", id
, val
);
10577 if( id
>1 ) utf8_printf(p
->out
, "\n");
10583 case SQLITE_TESTCTRL_SORTER_MMAP
:
10585 int opt
= (unsigned int)integerValue(azArg
[2]);
10586 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
10592 if( isOk
==0 && iCtrl
>=0 ){
10593 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
,aCtrl
[iCtrl
].zUsage
);
10595 }else if( isOk
==1 ){
10596 raw_printf(p
->out
, "%d\n", rc2
);
10597 }else if( isOk
==2 ){
10598 raw_printf(p
->out
, "0x%08x\n", rc2
);
10601 #endif /* !defined(SQLITE_UNTESTABLE) */
10603 if( c
=='t' && n
>4 && cli_strncmp(azArg
[0], "timeout", n
)==0 ){
10605 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
10608 if( c
=='t' && n
>=5 && cli_strncmp(azArg
[0], "timer", n
)==0 ){
10610 enableTimer
= booleanValue(azArg
[1]);
10611 if( enableTimer
&& !HAS_TIMER
){
10612 raw_printf(stderr
, "Error: timer not available on this system.\n");
10616 raw_printf(stderr
, "Usage: .timer on|off\n");
10621 #ifndef SQLITE_OMIT_TRACE
10622 if( c
=='t' && cli_strncmp(azArg
[0], "trace", n
)==0 ){
10626 for(jj
=1; jj
<nArg
; jj
++){
10627 const char *z
= azArg
[jj
];
10629 if( optionMatch(z
, "expanded") ){
10630 p
->eTraceType
= SHELL_TRACE_EXPANDED
;
10632 #ifdef SQLITE_ENABLE_NORMALIZE
10633 else if( optionMatch(z
, "normalized") ){
10634 p
->eTraceType
= SHELL_TRACE_NORMALIZED
;
10637 else if( optionMatch(z
, "plain") ){
10638 p
->eTraceType
= SHELL_TRACE_PLAIN
;
10640 else if( optionMatch(z
, "profile") ){
10641 mType
|= SQLITE_TRACE_PROFILE
;
10643 else if( optionMatch(z
, "row") ){
10644 mType
|= SQLITE_TRACE_ROW
;
10646 else if( optionMatch(z
, "stmt") ){
10647 mType
|= SQLITE_TRACE_STMT
;
10649 else if( optionMatch(z
, "close") ){
10650 mType
|= SQLITE_TRACE_CLOSE
;
10653 raw_printf(stderr
, "Unknown option \"%s\" on \".trace\"\n", z
);
10655 goto meta_command_exit
;
10658 output_file_close(p
->traceOut
);
10659 p
->traceOut
= output_file_open(azArg
[1], 0);
10662 if( p
->traceOut
==0 ){
10663 sqlite3_trace_v2(p
->db
, 0, 0, 0);
10665 if( mType
==0 ) mType
= SQLITE_TRACE_STMT
;
10666 sqlite3_trace_v2(p
->db
, mType
, sql_trace_callback
, p
);
10669 #endif /* !defined(SQLITE_OMIT_TRACE) */
10671 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10672 if( c
=='u' && cli_strncmp(azArg
[0], "unmodule", n
)==0 ){
10677 raw_printf(stderr
, "Usage: .unmodule [--allexcept] NAME ...\n");
10679 goto meta_command_exit
;
10683 if( zOpt
[0]=='-' && zOpt
[1]=='-' && zOpt
[2]!=0 ) zOpt
++;
10684 lenOpt
= (int)strlen(zOpt
);
10685 if( lenOpt
>=3 && cli_strncmp(zOpt
, "-allexcept",lenOpt
)==0 ){
10686 assert( azArg
[nArg
]==0 );
10687 sqlite3_drop_modules(p
->db
, nArg
>2 ? (const char**)(azArg
+2) : 0);
10689 for(ii
=1; ii
<nArg
; ii
++){
10690 sqlite3_create_module(p
->db
, azArg
[ii
], 0, 0);
10696 #if SQLITE_USER_AUTHENTICATION
10697 if( c
=='u' && cli_strncmp(azArg
[0], "user", n
)==0 ){
10699 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
10701 goto meta_command_exit
;
10704 if( cli_strcmp(azArg
[1],"login")==0 ){
10706 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
10708 goto meta_command_exit
;
10710 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
10711 strlen30(azArg
[3]));
10713 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
10716 }else if( cli_strcmp(azArg
[1],"add")==0 ){
10718 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
10720 goto meta_command_exit
;
10722 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
10723 booleanValue(azArg
[4]));
10725 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
10728 }else if( cli_strcmp(azArg
[1],"edit")==0 ){
10730 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
10732 goto meta_command_exit
;
10734 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
10735 booleanValue(azArg
[4]));
10737 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
10740 }else if( cli_strcmp(azArg
[1],"delete")==0 ){
10742 raw_printf(stderr
, "Usage: .user delete USER\n");
10744 goto meta_command_exit
;
10746 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
10748 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
10752 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
10754 goto meta_command_exit
;
10757 #endif /* SQLITE_USER_AUTHENTICATION */
10759 if( c
=='v' && cli_strncmp(azArg
[0], "version", n
)==0 ){
10760 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
10761 sqlite3_libversion(), sqlite3_sourceid());
10762 #if SQLITE_HAVE_ZLIB
10763 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
10765 #define CTIMEOPT_VAL_(opt) #opt
10766 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10767 #if defined(__clang__) && defined(__clang_major__)
10768 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
10769 CTIMEOPT_VAL(__clang_minor__
) "."
10770 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
10771 #elif defined(_MSC_VER)
10772 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
10773 #elif defined(__GNUC__) && defined(__VERSION__)
10774 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
10778 if( c
=='v' && cli_strncmp(azArg
[0], "vfsinfo", n
)==0 ){
10779 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
10780 sqlite3_vfs
*pVfs
= 0;
10782 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
10784 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
10785 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
10786 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
10787 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
10792 if( c
=='v' && cli_strncmp(azArg
[0], "vfslist", n
)==0 ){
10794 sqlite3_vfs
*pCurrent
= 0;
10796 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
10798 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
10799 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
10800 pVfs
==pCurrent
? " <--- CURRENT" : "");
10801 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
10802 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
10803 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
10805 raw_printf(p
->out
, "-----------------------------------\n");
10810 if( c
=='v' && cli_strncmp(azArg
[0], "vfsname", n
)==0 ){
10811 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
10812 char *zVfsName
= 0;
10814 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
10816 utf8_printf(p
->out
, "%s\n", zVfsName
);
10817 sqlite3_free(zVfsName
);
10822 if( c
=='w' && cli_strncmp(azArg
[0], "wheretrace", n
)==0 ){
10823 unsigned int x
= nArg
>=2 ? (unsigned int)integerValue(azArg
[1]) : 0xffffffff;
10824 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS
, 3, &x
);
10827 if( c
=='w' && cli_strncmp(azArg
[0], "width", n
)==0 ){
10829 assert( nArg
<=ArraySize(azArg
) );
10830 p
->nWidth
= nArg
-1;
10831 p
->colWidth
= realloc(p
->colWidth
, (p
->nWidth
+1)*sizeof(int)*2);
10832 if( p
->colWidth
==0 && p
->nWidth
>0 ) shell_out_of_memory();
10833 if( p
->nWidth
) p
->actualWidth
= &p
->colWidth
[p
->nWidth
];
10834 for(j
=1; j
<nArg
; j
++){
10835 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
10840 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
10841 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
10848 if( p
->outCount
==0 ) output_reset(p
);
10850 p
->bSafeMode
= p
->bSafeModePersist
;
10854 /* Line scan result and intermediate states (supporting scan resumption)
10857 # define CHAR_BIT 8
10860 QSS_HasDark
= 1<<CHAR_BIT
, QSS_EndingSemi
= 2<<CHAR_BIT
,
10861 QSS_CharMask
= (1<<CHAR_BIT
)-1, QSS_ScanMask
= 3<<CHAR_BIT
,
10864 #define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10865 #define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10866 #define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10867 #define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10868 #define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10871 ** Scan line for classification to guide shell's handling.
10872 ** The scan is resumable for subsequent lines when prior
10873 ** return values are passed as the 2nd argument.
10875 static QuickScanState
quickscan(char *zLine
, QuickScanState qss
){
10877 char cWait
= (char)qss
; /* intentional narrowing loss */
10880 assert( cWait
==0 );
10881 while( (cin
= *zLine
++)!=0 ){
10888 while((cin
= *++zLine
)!=0 )
10893 qss
|= QSS_EndingSemi
;
10899 qss
= QSS_SETV(qss
, cWait
);
10906 case '`': case '\'': case '"':
10908 qss
= QSS_HasDark
| cWait
;
10913 qss
= (qss
& ~QSS_EndingSemi
) | QSS_HasDark
;
10917 while( (cin
= *zLine
++)!=0 ){
10921 if( *zLine
!= '/' )
10925 qss
= QSS_SETV(qss
, 0);
10927 case '`': case '\'': case '"':
10935 qss
= QSS_SETV(qss
, 0);
10937 default: assert(0);
10946 ** Return TRUE if the line typed in is an SQL command terminator other
10947 ** than a semi-colon. The SQL Server style "go" command is understood
10948 ** as is the Oracle "/".
10950 static int line_is_command_terminator(char *zLine
){
10951 while( IsSpace(zLine
[0]) ){ zLine
++; };
10952 if( zLine
[0]=='/' )
10953 zLine
+= 1; /* Oracle */
10954 else if ( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o' )
10955 zLine
+= 2; /* SQL Server */
10958 return quickscan(zLine
, QSS_Start
)==QSS_Start
;
10962 ** We need a default sqlite3_complete() implementation to use in case
10963 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
10964 ** any arbitrary text is a complete SQL statement. This is not very
10965 ** user-friendly, but it does seem to work.
10967 #ifdef SQLITE_OMIT_COMPLETE
10968 #define sqlite3_complete(x) 1
10972 ** Return true if zSql is a complete SQL statement. Return false if it
10973 ** ends in the middle of a string literal or C-style comment.
10975 static int line_is_complete(char *zSql
, int nSql
){
10977 if( zSql
==0 ) return 1;
10980 rc
= sqlite3_complete(zSql
);
10986 ** Run a single line of SQL. Return the number of errors.
10988 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
10993 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
10994 if( p
->flgProgress
& SHELL_PROGRESS_RESET
) p
->nProgress
= 0;
10996 rc
= shell_exec(p
, zSql
, &zErrMsg
);
10998 if( rc
|| zErrMsg
){
11000 const char *zErrorTail
;
11001 const char *zErrorType
;
11003 zErrorType
= "Error";
11004 zErrorTail
= sqlite3_errmsg(p
->db
);
11005 }else if( cli_strncmp(zErrMsg
, "in prepare, ",12)==0 ){
11006 zErrorType
= "Parse error";
11007 zErrorTail
= &zErrMsg
[12];
11008 }else if( cli_strncmp(zErrMsg
, "stepping, ", 10)==0 ){
11009 zErrorType
= "Runtime error";
11010 zErrorTail
= &zErrMsg
[10];
11012 zErrorType
= "Error";
11013 zErrorTail
= zErrMsg
;
11015 if( in
!=0 || !stdin_is_interactive
){
11016 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
11017 "%s near line %d:", zErrorType
, startline
);
11019 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "%s:", zErrorType
);
11021 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrorTail
);
11022 sqlite3_free(zErrMsg
);
11025 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
11026 char zLineBuf
[2000];
11027 sqlite3_snprintf(sizeof(zLineBuf
), zLineBuf
,
11028 "changes: %lld total_changes: %lld",
11029 sqlite3_changes64(p
->db
), sqlite3_total_changes64(p
->db
));
11030 raw_printf(p
->out
, "%s\n", zLineBuf
);
11035 static void echo_group_input(ShellState
*p
, const char *zDo
){
11036 if( ShellHasFlag(p
, SHFLG_Echo
) ) utf8_printf(p
->out
, "%s\n", zDo
);
11039 #ifdef SQLITE_SHELL_FIDDLE
11041 ** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11042 ** because we need the global shellState and cannot access it from that function
11043 ** without moving lots of code around (creating a larger/messier diff).
11045 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
11046 /* Parse the next line from shellState.wasm.zInput. */
11047 const char *zBegin
= shellState
.wasm
.zPos
;
11048 const char *z
= zBegin
;
11052 UNUSED_PARAMETER(in
);
11053 UNUSED_PARAMETER(isContinuation
);
11057 while(*z
&& isspace(*z
)) ++z
;
11059 for(; *z
&& '\n'!=*z
; ++nZ
, ++z
){}
11060 if(nZ
>0 && '\r'==zBegin
[nZ
-1]){
11063 shellState
.wasm
.zPos
= z
;
11064 zLine
= realloc(zPrior
, nZ
+1);
11065 shell_check_oom(zLine
);
11066 memcpy(zLine
, zBegin
, nZ
);
11070 #endif /* SQLITE_SHELL_FIDDLE */
11073 ** Read input from *in and process it. If *in==0 then input
11074 ** is interactive - the user is typing it it. Otherwise, input
11075 ** is coming from a file or device. A prompt is issued and history
11076 ** is saved only if input is interactive. An interrupt signal will
11077 ** cause this routine to exit immediately, unless input is interactive.
11079 ** Return the number of errors.
11081 static int process_input(ShellState
*p
){
11082 char *zLine
= 0; /* A single input line */
11083 char *zSql
= 0; /* Accumulated SQL text */
11084 i64 nLine
; /* Length of current line */
11085 i64 nSql
= 0; /* Bytes of zSql[] used */
11086 i64 nAlloc
= 0; /* Allocated zSql[] space */
11087 int rc
; /* Error code */
11088 int errCnt
= 0; /* Number of errors seen */
11089 i64 startline
= 0; /* Line number for start of current input */
11090 QuickScanState qss
= QSS_Start
; /* Accumulated line status (so far) */
11092 if( p
->inputNesting
==MAX_INPUT_NESTING
){
11093 /* This will be more informative in a later version. */
11094 utf8_printf(stderr
,"Input nesting limit (%d) reached at line %d."
11095 " Check recursion.\n", MAX_INPUT_NESTING
, p
->lineno
);
11100 while( errCnt
==0 || !bail_on_error
|| (p
->in
==0 && stdin_is_interactive
) ){
11102 zLine
= one_input_line(p
->in
, zLine
, nSql
>0);
11105 if( p
->in
==0 && stdin_is_interactive
) printf("\n");
11108 if( seenInterrupt
){
11109 if( p
->in
!=0 ) break;
11113 if( QSS_INPLAIN(qss
)
11114 && line_is_command_terminator(zLine
)
11115 && line_is_complete(zSql
, nSql
) ){
11116 memcpy(zLine
,";",2);
11118 qss
= quickscan(zLine
, qss
);
11119 if( QSS_PLAINWHITE(qss
) && nSql
==0 ){
11120 /* Just swallow single-line whitespace */
11121 echo_group_input(p
, zLine
);
11125 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
11126 echo_group_input(p
, zLine
);
11127 if( zLine
[0]=='.' ){
11128 rc
= do_meta_command(zLine
, p
);
11129 if( rc
==2 ){ /* exit requested */
11138 /* No single-line dispositions remain; accumulate line(s). */
11139 nLine
= strlen(zLine
);
11140 if( nSql
+nLine
+2>=nAlloc
){
11141 /* Grow buffer by half-again increments when big. */
11142 nAlloc
= nSql
+(nSql
>>1)+nLine
+100;
11143 zSql
= realloc(zSql
, nAlloc
);
11144 shell_check_oom(zSql
);
11148 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
11149 assert( nAlloc
>0 && zSql
!=0 );
11150 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
11151 startline
= p
->lineno
;
11154 zSql
[nSql
++] = '\n';
11155 memcpy(zSql
+nSql
, zLine
, nLine
+1);
11158 if( nSql
&& QSS_SEMITERM(qss
) && sqlite3_complete(zSql
) ){
11159 echo_group_input(p
, zSql
);
11160 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11168 p
->bSafeMode
= p
->bSafeModePersist
;
11170 }else if( nSql
&& QSS_PLAINWHITE(qss
) ){
11171 echo_group_input(p
, zSql
);
11177 /* This may be incomplete. Let the SQL parser deal with that. */
11178 echo_group_input(p
, zSql
);
11179 errCnt
+= runOneSqlLine(p
, zSql
, p
->in
, startline
);
11188 ** Return a pathname which is the user's home directory. A
11189 ** 0 return indicates an error of some kind.
11191 static char *find_home_dir(int clearFlag
){
11192 static char *home_dir
= NULL
;
11198 if( home_dir
) return home_dir
;
11200 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11201 && !defined(__RTP__) && !defined(_WRS_KERNEL)
11203 struct passwd
*pwent
;
11204 uid_t uid
= getuid();
11205 if( (pwent
=getpwuid(uid
)) != NULL
) {
11206 home_dir
= pwent
->pw_dir
;
11211 #if defined(_WIN32_WCE)
11212 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11217 #if defined(_WIN32) || defined(WIN32)
11219 home_dir
= getenv("USERPROFILE");
11224 home_dir
= getenv("HOME");
11227 #if defined(_WIN32) || defined(WIN32)
11229 char *zDrive
, *zPath
;
11231 zDrive
= getenv("HOMEDRIVE");
11232 zPath
= getenv("HOMEPATH");
11233 if( zDrive
&& zPath
){
11234 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
11235 home_dir
= malloc( n
);
11236 if( home_dir
==0 ) return 0;
11237 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
11244 #endif /* !_WIN32_WCE */
11247 i64 n
= strlen(home_dir
) + 1;
11248 char *z
= malloc( n
);
11249 if( z
) memcpy(z
, home_dir
, n
);
11257 ** Read input from the file given by sqliterc_override. Or if that
11258 ** parameter is NULL, take input from ~/.sqliterc
11260 ** Returns the number of errors.
11262 static void process_sqliterc(
11263 ShellState
*p
, /* Configuration data */
11264 const char *sqliterc_override
/* Name of config file. NULL to use default */
11266 char *home_dir
= NULL
;
11267 const char *sqliterc
= sqliterc_override
;
11269 FILE *inSaved
= p
->in
;
11270 int savedLineno
= p
->lineno
;
11272 if (sqliterc
== NULL
) {
11273 home_dir
= find_home_dir(0);
11275 raw_printf(stderr
, "-- warning: cannot find home directory;"
11276 " cannot read ~/.sqliterc\n");
11279 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
11280 shell_check_oom(zBuf
);
11283 p
->in
= fopen(sqliterc
,"rb");
11285 if( stdin_is_interactive
){
11286 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
11288 if( process_input(p
) && bail_on_error
) exit(1);
11290 }else if( sqliterc_override
!=0 ){
11291 utf8_printf(stderr
,"cannot open: \"%s\"\n", sqliterc
);
11292 if( bail_on_error
) exit(1);
11295 p
->lineno
= savedLineno
;
11296 sqlite3_free(zBuf
);
11300 ** Show available command line options
11302 static const char zOptions
[] =
11303 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11304 " -A ARGS... run \".archive ARGS\" and exit\n"
11306 " -append append the database to the end of the file\n"
11307 " -ascii set output mode to 'ascii'\n"
11308 " -bail stop after hitting an error\n"
11309 " -batch force batch I/O\n"
11310 " -box set output mode to 'box'\n"
11311 " -column set output mode to 'column'\n"
11312 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
11313 " -csv set output mode to 'csv'\n"
11314 #if !defined(SQLITE_OMIT_DESERIALIZE)
11315 " -deserialize open the database using sqlite3_deserialize()\n"
11317 " -echo print inputs before execution\n"
11318 " -init FILENAME read/process named file\n"
11319 " -[no]header turn headers on or off\n"
11320 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11321 " -heap SIZE Size of heap for memsys3 or memsys5\n"
11323 " -help show this message\n"
11324 " -html set output mode to HTML\n"
11325 " -interactive force interactive I/O\n"
11326 " -json set output mode to 'json'\n"
11327 " -line set output mode to 'line'\n"
11328 " -list set output mode to 'list'\n"
11329 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
11330 " -markdown set output mode to 'markdown'\n"
11331 #if !defined(SQLITE_OMIT_DESERIALIZE)
11332 " -maxsize N maximum size for a --deserialize database\n"
11334 " -memtrace trace all memory allocations and deallocations\n"
11335 " -mmap N default mmap size set to N\n"
11336 #ifdef SQLITE_ENABLE_MULTIPLEX
11337 " -multiplex enable the multiplexor VFS\n"
11339 " -newline SEP set output row separator. Default: '\\n'\n"
11340 " -nofollow refuse to open symbolic links to database files\n"
11341 " -nonce STRING set the safe-mode escape nonce\n"
11342 " -nullvalue TEXT set text string for NULL values. Default ''\n"
11343 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
11344 " -quote set output mode to 'quote'\n"
11345 " -readonly open the database read-only\n"
11346 " -safe enable safe-mode\n"
11347 " -separator SEP set output column separator. Default: '|'\n"
11348 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11349 " -sorterref SIZE sorter references threshold size\n"
11351 " -stats print memory stats before each finalize\n"
11352 " -table set output mode to 'table'\n"
11353 " -tabs set output mode to 'tabs'\n"
11354 " -version show SQLite version\n"
11355 " -vfs NAME use NAME as the default VFS\n"
11356 #ifdef SQLITE_ENABLE_VFSTRACE
11357 " -vfstrace enable tracing of all VFS calls\n"
11359 #ifdef SQLITE_HAVE_ZLIB
11360 " -zip open the file as a ZIP Archive\n"
11363 static void usage(int showDetail
){
11364 utf8_printf(stderr
,
11365 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11366 "FILENAME is the name of an SQLite database. A new database is created\n"
11367 "if the file does not previously exist.\n", Argv0
);
11369 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
11371 raw_printf(stderr
, "Use the -help option for additional information\n");
11377 ** Internal check: Verify that the SQLite is uninitialized. Print a
11378 ** error message if it is initialized.
11380 static void verify_uninitialized(void){
11381 if( sqlite3_config(-1)==SQLITE_MISUSE
){
11382 utf8_printf(stdout
, "WARNING: attempt to configure SQLite after"
11383 " initialization.\n");
11388 ** Initialize the state information in data
11390 static void main_init(ShellState
*data
) {
11391 memset(data
, 0, sizeof(*data
));
11392 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
11393 data
->autoExplain
= 1;
11394 data
->pAuxDb
= &data
->aAuxDb
[0];
11395 memcpy(data
->colSeparator
,SEP_Column
, 2);
11396 memcpy(data
->rowSeparator
,SEP_Row
, 2);
11397 data
->showHeader
= 0;
11398 data
->shellFlgs
= SHFLG_Lookaside
;
11399 verify_uninitialized();
11400 sqlite3_config(SQLITE_CONFIG_URI
, 1);
11401 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
11402 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
11403 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
11404 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
11408 ** Output text to the console in a font that attracts extra attention.
11411 static void printBold(const char *zText
){
11412 #if !SQLITE_OS_WINRT
11413 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
11414 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
11415 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
11416 SetConsoleTextAttribute(out
,
11417 FOREGROUND_RED
|FOREGROUND_INTENSITY
11420 printf("%s", zText
);
11421 #if !SQLITE_OS_WINRT
11422 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
11426 static void printBold(const char *zText
){
11427 printf("\033[1m%s\033[0m", zText
);
11432 ** Get the argument to an --option. Throw an error and die if no argument
11435 static char *cmdline_option_value(int argc
, char **argv
, int i
){
11437 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
11438 argv
[0], argv
[argc
-1]);
11444 #ifndef SQLITE_SHELL_IS_UTF8
11445 # if (defined(_WIN32) || defined(WIN32)) \
11446 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11447 # define SQLITE_SHELL_IS_UTF8 (0)
11449 # define SQLITE_SHELL_IS_UTF8 (1)
11453 #ifdef SQLITE_SHELL_FIDDLE
11454 # define main fiddle_main
11457 #if SQLITE_SHELL_IS_UTF8
11458 int SQLITE_CDECL
main(int argc
, char **argv
){
11460 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
11463 #ifdef SQLITE_DEBUG
11464 sqlite3_int64 mem_main_enter
= sqlite3_memory_used();
11467 #ifdef SQLITE_SHELL_FIDDLE
11468 # define data shellState
11472 const char *zInitFile
= 0;
11475 int warnInmemoryDb
= 0;
11479 const char *zVfs
= 0; /* Value of -vfs command-line option */
11480 #if !SQLITE_SHELL_IS_UTF8
11481 char **argvToFree
= 0;
11482 int argcToFree
= 0;
11485 setBinaryMode(stdin
, 0);
11486 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
11487 #ifdef SQLITE_SHELL_FIDDLE
11488 stdin_is_interactive
= 0;
11489 stdout_is_console
= 1;
11490 data
.wasm
.zDefaultDbName
= "/fiddle.sqlite3";
11492 stdin_is_interactive
= isatty(0);
11493 stdout_is_console
= isatty(1);
11496 #if !defined(_WIN32_WCE)
11497 if( getenv("SQLITE_DEBUG_BREAK") ){
11498 if( isatty(0) && isatty(2) ){
11500 "attach debugger to process %d and press any key to continue.\n",
11504 #if defined(_WIN32) || defined(WIN32)
11505 #if SQLITE_OS_WINRT
11510 #elif defined(SIGTRAP)
11517 #if USE_SYSTEM_SQLITE+0!=1
11518 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
11519 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
11520 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
11526 /* On Windows, we must translate command-line arguments into UTF-8.
11527 ** The SQLite memory allocator subsystem has to be enabled in order to
11528 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
11529 ** subsequent sqlite3_config() calls will work. So copy all results into
11530 ** memory that does not come from the SQLite memory allocator.
11532 #if !SQLITE_SHELL_IS_UTF8
11533 sqlite3_initialize();
11534 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
11535 shell_check_oom(argvToFree
);
11537 argv
= argvToFree
+ argc
;
11538 for(i
=0; i
<argc
; i
++){
11539 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
11541 shell_check_oom(z
);
11543 argv
[i
] = malloc( n
+1 );
11544 shell_check_oom(argv
[i
]);
11545 memcpy(argv
[i
], z
, n
+1);
11546 argvToFree
[i
] = argv
[i
];
11549 sqlite3_shutdown();
11552 assert( argc
>=1 && argv
&& argv
[0] );
11555 /* Make sure we have a valid signal handler early, before anything
11559 signal(SIGINT
, interrupt_handler
);
11560 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11561 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
11564 #ifdef SQLITE_SHELL_DBNAME_PROC
11566 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11567 ** of a C-function that will provide the name of the database file. Use
11568 ** this compile-time option to embed this shell program in larger
11569 ** applications. */
11570 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11571 SQLITE_SHELL_DBNAME_PROC(&data
.pAuxDb
->zDbFilename
);
11572 warnInmemoryDb
= 0;
11576 /* Do an initial pass through the command-line argument to locate
11577 ** the name of the database file, the name of the initialization file,
11578 ** the size of the alternative malloc heap,
11579 ** and the first command to execute.
11581 verify_uninitialized();
11582 for(i
=1; i
<argc
; i
++){
11586 if( data
.aAuxDb
->zDbFilename
==0 ){
11587 data
.aAuxDb
->zDbFilename
= z
;
11589 /* Excesss arguments are interpreted as SQL (or dot-commands) and
11590 ** mean that nothing is read from stdin */
11593 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
11594 shell_check_oom(azCmd
);
11598 if( z
[1]=='-' ) z
++;
11599 if( cli_strcmp(z
,"-separator")==0
11600 || cli_strcmp(z
,"-nullvalue")==0
11601 || cli_strcmp(z
,"-newline")==0
11602 || cli_strcmp(z
,"-cmd")==0
11604 (void)cmdline_option_value(argc
, argv
, ++i
);
11605 }else if( cli_strcmp(z
,"-init")==0 ){
11606 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
11607 }else if( cli_strcmp(z
,"-batch")==0 ){
11608 /* Need to check for batch mode here to so we can avoid printing
11609 ** informational messages (like from process_sqliterc) before
11610 ** we do the actual processing of arguments later in a second pass.
11612 stdin_is_interactive
= 0;
11613 }else if( cli_strcmp(z
,"-heap")==0 ){
11614 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11616 sqlite3_int64 szHeap
;
11618 zSize
= cmdline_option_value(argc
, argv
, ++i
);
11619 szHeap
= integerValue(zSize
);
11620 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
11621 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
11623 (void)cmdline_option_value(argc
, argv
, ++i
);
11625 }else if( cli_strcmp(z
,"-pagecache")==0 ){
11626 sqlite3_int64 n
, sz
;
11627 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
11628 if( sz
>70000 ) sz
= 70000;
11630 n
= integerValue(cmdline_option_value(argc
,argv
,++i
));
11631 if( sz
>0 && n
>0 && 0xffffffffffffLL
/sz
<n
){
11632 n
= 0xffffffffffffLL
/sz
;
11634 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
11635 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
11636 data
.shellFlgs
|= SHFLG_Pagecache
;
11637 }else if( cli_strcmp(z
,"-lookaside")==0 ){
11639 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
11641 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
11643 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
11644 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
11645 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
11647 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
11649 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD
); break;
11650 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD
); break;
11651 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED
); break;
11653 #ifdef SQLITE_ENABLE_VFSTRACE
11654 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
11655 extern int vfstrace_register(
11656 const char *zTraceName
,
11657 const char *zOldVfsName
,
11658 int (*xOut
)(const char*,void*),
11662 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
11664 #ifdef SQLITE_ENABLE_MULTIPLEX
11665 }else if( cli_strcmp(z
,"-multiplex")==0 ){
11666 extern int sqlite3_multiple_initialize(const char*,int);
11667 sqlite3_multiplex_initialize(0, 1);
11669 }else if( cli_strcmp(z
,"-mmap")==0 ){
11670 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
11671 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
11672 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11673 }else if( cli_strcmp(z
,"-sorterref")==0 ){
11674 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
11675 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
11677 }else if( cli_strcmp(z
,"-vfs")==0 ){
11678 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
11679 #ifdef SQLITE_HAVE_ZLIB
11680 }else if( cli_strcmp(z
,"-zip")==0 ){
11681 data
.openMode
= SHELL_OPEN_ZIPFILE
;
11683 }else if( cli_strcmp(z
,"-append")==0 ){
11684 data
.openMode
= SHELL_OPEN_APPENDVFS
;
11685 #ifndef SQLITE_OMIT_DESERIALIZE
11686 }else if( cli_strcmp(z
,"-deserialize")==0 ){
11687 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
11688 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
11689 data
.szMax
= integerValue(argv
[++i
]);
11691 }else if( cli_strcmp(z
,"-readonly")==0 ){
11692 data
.openMode
= SHELL_OPEN_READONLY
;
11693 }else if( cli_strcmp(z
,"-nofollow")==0 ){
11694 data
.openFlags
= SQLITE_OPEN_NOFOLLOW
;
11695 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11696 }else if( cli_strncmp(z
, "-A",2)==0 ){
11697 /* All remaining command-line arguments are passed to the ".archive"
11698 ** command, so ignore them */
11701 }else if( cli_strcmp(z
, "-memtrace")==0 ){
11702 sqlite3MemTraceActivate(stderr
);
11703 }else if( cli_strcmp(z
,"-bail")==0 ){
11705 }else if( cli_strcmp(z
,"-nonce")==0 ){
11707 data
.zNonce
= strdup(argv
[++i
]);
11708 }else if( cli_strcmp(z
,"-safe")==0 ){
11709 /* no-op - catch this on the second pass */
11712 verify_uninitialized();
11715 #ifdef SQLITE_SHELL_INIT_PROC
11717 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11718 ** of a C-function that will perform initialization actions on SQLite that
11719 ** occur just before or after sqlite3_initialize(). Use this compile-time
11720 ** option to embed this shell program in larger applications. */
11721 extern void SQLITE_SHELL_INIT_PROC(void);
11722 SQLITE_SHELL_INIT_PROC();
11725 /* All the sqlite3_config() calls have now been made. So it is safe
11726 ** to call sqlite3_initialize() and process any command line -vfs option. */
11727 sqlite3_initialize();
11731 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
11733 sqlite3_vfs_register(pVfs
, 1);
11735 utf8_printf(stderr
, "no such VFS: \"%s\"\n", zVfs
);
11740 if( data
.pAuxDb
->zDbFilename
==0 ){
11741 #ifndef SQLITE_OMIT_MEMORYDB
11742 data
.pAuxDb
->zDbFilename
= ":memory:";
11743 warnInmemoryDb
= argc
==1;
11745 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
11750 #ifndef SQLITE_SHELL_FIDDLE
11751 sqlite3_appendvfs_init(0,0,0);
11754 /* Go ahead and open the database file if it already exists. If the
11755 ** file does not exist, delay opening it. This prevents empty database
11756 ** files from being created if a user mistypes the database name argument
11757 ** to the sqlite command-line tool.
11759 if( access(data
.pAuxDb
->zDbFilename
, 0)==0 ){
11763 /* Process the initialization file if there is one. If no -init option
11764 ** is given on the command line, look for a file named ~/.sqliterc and
11765 ** try to process it.
11767 process_sqliterc(&data
,zInitFile
);
11769 /* Make a second pass through the command-line argument and set
11770 ** options. This second pass is delayed until after the initialization
11771 ** file is processed so that the command-line arguments will override
11772 ** settings in the initialization file.
11774 for(i
=1; i
<argc
; i
++){
11776 if( z
[0]!='-' ) continue;
11777 if( z
[1]=='-' ){ z
++; }
11778 if( cli_strcmp(z
,"-init")==0 ){
11780 }else if( cli_strcmp(z
,"-html")==0 ){
11781 data
.mode
= MODE_Html
;
11782 }else if( cli_strcmp(z
,"-list")==0 ){
11783 data
.mode
= MODE_List
;
11784 }else if( cli_strcmp(z
,"-quote")==0 ){
11785 data
.mode
= MODE_Quote
;
11786 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
, SEP_Comma
);
11787 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
, SEP_Row
);
11788 }else if( cli_strcmp(z
,"-line")==0 ){
11789 data
.mode
= MODE_Line
;
11790 }else if( cli_strcmp(z
,"-column")==0 ){
11791 data
.mode
= MODE_Column
;
11792 }else if( cli_strcmp(z
,"-json")==0 ){
11793 data
.mode
= MODE_Json
;
11794 }else if( cli_strcmp(z
,"-markdown")==0 ){
11795 data
.mode
= MODE_Markdown
;
11796 }else if( cli_strcmp(z
,"-table")==0 ){
11797 data
.mode
= MODE_Table
;
11798 }else if( cli_strcmp(z
,"-box")==0 ){
11799 data
.mode
= MODE_Box
;
11800 }else if( cli_strcmp(z
,"-csv")==0 ){
11801 data
.mode
= MODE_Csv
;
11802 memcpy(data
.colSeparator
,",",2);
11803 #ifdef SQLITE_HAVE_ZLIB
11804 }else if( cli_strcmp(z
,"-zip")==0 ){
11805 data
.openMode
= SHELL_OPEN_ZIPFILE
;
11807 }else if( cli_strcmp(z
,"-append")==0 ){
11808 data
.openMode
= SHELL_OPEN_APPENDVFS
;
11809 #ifndef SQLITE_OMIT_DESERIALIZE
11810 }else if( cli_strcmp(z
,"-deserialize")==0 ){
11811 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
11812 }else if( cli_strcmp(z
,"-maxsize")==0 && i
+1<argc
){
11813 data
.szMax
= integerValue(argv
[++i
]);
11815 }else if( cli_strcmp(z
,"-readonly")==0 ){
11816 data
.openMode
= SHELL_OPEN_READONLY
;
11817 }else if( cli_strcmp(z
,"-nofollow")==0 ){
11818 data
.openFlags
|= SQLITE_OPEN_NOFOLLOW
;
11819 }else if( cli_strcmp(z
,"-ascii")==0 ){
11820 data
.mode
= MODE_Ascii
;
11821 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
, SEP_Unit
);
11822 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
, SEP_Record
);
11823 }else if( cli_strcmp(z
,"-tabs")==0 ){
11824 data
.mode
= MODE_List
;
11825 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
, SEP_Tab
);
11826 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
, SEP_Row
);
11827 }else if( cli_strcmp(z
,"-separator")==0 ){
11828 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
11829 "%s",cmdline_option_value(argc
,argv
,++i
));
11830 }else if( cli_strcmp(z
,"-newline")==0 ){
11831 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
11832 "%s",cmdline_option_value(argc
,argv
,++i
));
11833 }else if( cli_strcmp(z
,"-nullvalue")==0 ){
11834 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
11835 "%s",cmdline_option_value(argc
,argv
,++i
));
11836 }else if( cli_strcmp(z
,"-header")==0 ){
11837 data
.showHeader
= 1;
11838 ShellSetFlag(&data
, SHFLG_HeaderSet
);
11839 }else if( cli_strcmp(z
,"-noheader")==0 ){
11840 data
.showHeader
= 0;
11841 ShellSetFlag(&data
, SHFLG_HeaderSet
);
11842 }else if( cli_strcmp(z
,"-echo")==0 ){
11843 ShellSetFlag(&data
, SHFLG_Echo
);
11844 }else if( cli_strcmp(z
,"-eqp")==0 ){
11845 data
.autoEQP
= AUTOEQP_on
;
11846 }else if( cli_strcmp(z
,"-eqpfull")==0 ){
11847 data
.autoEQP
= AUTOEQP_full
;
11848 }else if( cli_strcmp(z
,"-stats")==0 ){
11850 }else if( cli_strcmp(z
,"-scanstats")==0 ){
11851 data
.scanstatsOn
= 1;
11852 }else if( cli_strcmp(z
,"-backslash")==0 ){
11853 /* Undocumented command-line option: -backslash
11854 ** Causes C-style backslash escapes to be evaluated in SQL statements
11855 ** prior to sending the SQL into SQLite. Useful for injecting
11856 ** crazy bytes in the middle of SQL statements for testing and debugging.
11858 ShellSetFlag(&data
, SHFLG_Backslash
);
11859 }else if( cli_strcmp(z
,"-bail")==0 ){
11860 /* No-op. The bail_on_error flag should already be set. */
11861 }else if( cli_strcmp(z
,"-version")==0 ){
11862 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11864 }else if( cli_strcmp(z
,"-interactive")==0 ){
11865 stdin_is_interactive
= 1;
11866 }else if( cli_strcmp(z
,"-batch")==0 ){
11867 stdin_is_interactive
= 0;
11868 }else if( cli_strcmp(z
,"-heap")==0 ){
11870 }else if( cli_strcmp(z
,"-pagecache")==0 ){
11872 }else if( cli_strcmp(z
,"-lookaside")==0 ){
11874 }else if( cli_strcmp(z
,"-threadsafe")==0 ){
11876 }else if( cli_strcmp(z
,"-nonce")==0 ){
11878 }else if( cli_strcmp(z
,"-mmap")==0 ){
11880 }else if( cli_strcmp(z
,"-memtrace")==0 ){
11882 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
11883 }else if( cli_strcmp(z
,"-sorterref")==0 ){
11886 }else if( cli_strcmp(z
,"-vfs")==0 ){
11888 #ifdef SQLITE_ENABLE_VFSTRACE
11889 }else if( cli_strcmp(z
,"-vfstrace")==0 ){
11892 #ifdef SQLITE_ENABLE_MULTIPLEX
11893 }else if( cli_strcmp(z
,"-multiplex")==0 ){
11896 }else if( cli_strcmp(z
,"-help")==0 ){
11898 }else if( cli_strcmp(z
,"-cmd")==0 ){
11899 /* Run commands that follow -cmd first and separately from commands
11900 ** that simply appear on the command-line. This seems goofy. It would
11901 ** be better if all commands ran in the order that they appear. But
11902 ** we retain the goofy behavior for historical compatibility. */
11903 if( i
==argc
-1 ) break;
11904 z
= cmdline_option_value(argc
,argv
,++i
);
11906 rc
= do_meta_command(z
, &data
);
11907 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
11910 rc
= shell_exec(&data
, z
, &zErrMsg
);
11912 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
11913 if( bail_on_error
) return rc
!=0 ? rc
: 1;
11915 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
11916 if( bail_on_error
) return rc
;
11919 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11920 }else if( cli_strncmp(z
, "-A", 2)==0 ){
11922 utf8_printf(stderr
, "Error: cannot mix regular SQL or dot-commands"
11923 " with \"%s\"\n", z
);
11926 open_db(&data
, OPEN_DB_ZIPFILE
);
11929 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
11931 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
11936 }else if( cli_strcmp(z
,"-safe")==0 ){
11937 data
.bSafeMode
= data
.bSafeModePersist
= 1;
11939 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
11940 raw_printf(stderr
,"Use -help for a list of options.\n");
11943 data
.cMode
= data
.mode
;
11947 /* Run all arguments that do not begin with '-' as if they were separate
11948 ** command-line inputs, except for the argToSkip argument which contains
11949 ** the database filename.
11951 for(i
=0; i
<nCmd
; i
++){
11952 if( azCmd
[i
][0]=='.' ){
11953 rc
= do_meta_command(azCmd
[i
], &data
);
11956 return rc
==2 ? 0 : rc
;
11960 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
11961 if( zErrMsg
|| rc
){
11963 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
11965 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
11967 sqlite3_free(zErrMsg
);
11969 return rc
!=0 ? rc
: 1;
11974 /* Run commands received from standard input
11976 if( stdin_is_interactive
){
11981 "SQLite version %s %.19s\n" /*extra-version-info*/
11982 "Enter \".help\" for usage hints.\n",
11983 sqlite3_libversion(), sqlite3_sourceid()
11985 if( warnInmemoryDb
){
11986 printf("Connected to a ");
11987 printBold("transient in-memory database");
11988 printf(".\nUse \".open FILENAME\" to reopen on a "
11989 "persistent database.\n");
11991 zHistory
= getenv("SQLITE_HISTORY");
11993 zHistory
= strdup(zHistory
);
11994 }else if( (zHome
= find_home_dir(0))!=0 ){
11995 nHistory
= strlen30(zHome
) + 20;
11996 if( (zHistory
= malloc(nHistory
))!=0 ){
11997 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
12000 if( zHistory
){ shell_read_history(zHistory
); }
12001 #if HAVE_READLINE || HAVE_EDITLINE
12002 rl_attempted_completion_function
= readline_completion
;
12003 #elif HAVE_LINENOISE
12004 linenoiseSetCompletionCallback(linenoise_completion
);
12007 rc
= process_input(&data
);
12009 shell_stifle_history(2000);
12010 shell_write_history(zHistory
);
12015 rc
= process_input(&data
);
12018 #ifndef SQLITE_SHELL_FIDDLE
12019 /* In WASM mode we have to leave the db state in place so that
12020 ** client code can "push" SQL into it after this call returns. */
12022 set_table_name(&data
, 0);
12024 session_close_all(&data
, -1);
12027 for(i
=0; i
<ArraySize(data
.aAuxDb
); i
++){
12028 sqlite3_free(data
.aAuxDb
[i
].zFreeOnClose
);
12029 if( data
.aAuxDb
[i
].db
){
12030 session_close_all(&data
, i
);
12031 close_db(data
.aAuxDb
[i
].db
);
12035 output_reset(&data
);
12036 data
.doXdgOpen
= 0;
12037 clearTempFile(&data
);
12038 #if !SQLITE_SHELL_IS_UTF8
12039 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
12042 free(data
.colWidth
);
12044 /* Clear the global data structure so that valgrind will detect memory
12046 memset(&data
, 0, sizeof(data
));
12047 #ifdef SQLITE_DEBUG
12048 if( sqlite3_memory_used()>mem_main_enter
){
12049 utf8_printf(stderr
, "Memory leaked: %u bytes\n",
12050 (unsigned int)(sqlite3_memory_used()-mem_main_enter
));
12053 #endif /* !SQLITE_SHELL_FIDDLE */
12058 #ifdef SQLITE_SHELL_FIDDLE
12059 /* Only for emcc experimentation purposes. */
12060 int fiddle_experiment(int a
,int b
){
12065 ** Returns a pointer to the current DB handle.
12067 sqlite3
* fiddle_db_handle(){
12072 ** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12073 ** "main" is assumed. Returns 0 if no db with the given name is
12076 sqlite3_vfs
* fiddle_db_vfs(const char *zDbName
){
12077 sqlite3_vfs
* pVfs
= 0;
12079 sqlite3_file_control(globalDb
, zDbName
? zDbName
: "main",
12080 SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
12085 /* Only for emcc experimentation purposes. */
12086 sqlite3
* fiddle_db_arg(sqlite3
*arg
){
12087 printf("fiddle_db_arg(%p)\n", (const void*)arg
);
12092 ** Intended to be called via a SharedWorker() while a separate
12093 ** SharedWorker() (which manages the wasm module) is performing work
12094 ** which should be interrupted. Unfortunately, SharedWorker is not
12095 ** portable enough to make real use of.
12097 void fiddle_interrupt(void){
12098 if( globalDb
) sqlite3_interrupt(globalDb
);
12102 ** Returns the filename of the given db name, assuming "main" if
12103 ** zDbName is NULL. Returns NULL if globalDb is not opened.
12105 const char * fiddle_db_filename(const char * zDbName
){
12107 ? sqlite3_db_filename(globalDb
, zDbName
? zDbName
: "main")
12112 ** Completely wipes out the contents of the currently-opened database
12113 ** but leaves its storage intact for reuse.
12115 void fiddle_reset_db(void){
12117 int rc
= sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 1, 0);
12118 if( 0==rc
) rc
= sqlite3_exec(globalDb
, "VACUUM", 0, 0, 0);
12119 sqlite3_db_config(globalDb
, SQLITE_DBCONFIG_RESET_DATABASE
, 0, 0);
12124 ** Uses the current database's VFS xRead to stream the db file's
12125 ** contents out to the given callback. The callback gets a single
12126 ** chunk of size n (its 2nd argument) on each call and must return 0
12127 ** on success, non-0 on error. This function returns 0 on success,
12128 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12129 ** code from the callback. Note that this is not thread-friendly: it
12130 ** expects that it will be the only thread reading the db file and
12131 ** takes no measures to ensure that is the case.
12133 int fiddle_export_db( int (*xCallback
)(unsigned const char *zOut
, int n
) ){
12134 sqlite3_int64 nSize
= 0;
12135 sqlite3_int64 nPos
= 0;
12136 sqlite3_file
* pFile
= 0;
12137 unsigned char buf
[1024 * 8];
12138 int nBuf
= (int)sizeof(buf
);
12139 int rc
= shellState
.db
12140 ? sqlite3_file_control(shellState
.db
, "main",
12141 SQLITE_FCNTL_FILE_POINTER
, &pFile
)
12143 if( rc
) return rc
;
12144 rc
= pFile
->pMethods
->xFileSize(pFile
, &nSize
);
12145 if( rc
) return rc
;
12147 /* DB size is not an even multiple of the buffer size. Reduce
12148 ** buffer size so that we do not unduly inflate the db size when
12150 if(0 == nSize
% 4096) nBuf
= 4096;
12151 else if(0 == nSize
% 2048) nBuf
= 2048;
12152 else if(0 == nSize
% 1024) nBuf
= 1024;
12155 for( ; 0==rc
&& nPos
<nSize
; nPos
+= nBuf
){
12156 rc
= pFile
->pMethods
->xRead(pFile
, buf
, nBuf
, nPos
);
12157 if(SQLITE_IOERR_SHORT_READ
== rc
){
12158 rc
= (nPos
+ nBuf
) < nSize
? rc
: 0/*assume EOF*/;
12160 if( 0==rc
) rc
= xCallback(buf
, nBuf
);
12166 ** Trivial exportable function for emscripten. It processes zSql as if
12167 ** it were input to the sqlite3 shell and redirects all output to the
12168 ** wasm binding. fiddle_main() must have been called before this
12169 ** is called, or results are undefined.
12171 void fiddle_exec(const char * zSql
){
12173 if('.'==*zSql
) puts(zSql
);
12174 shellState
.wasm
.zInput
= zSql
;
12175 shellState
.wasm
.zPos
= zSql
;
12176 process_input(&shellState
);
12177 shellState
.wasm
.zInput
= shellState
.wasm
.zPos
= 0;
12180 #endif /* SQLITE_SHELL_FIDDLE */