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
21 ** Warning pragmas copied from msvc.h in the core.
24 #pragma warning(disable : 4054)
25 #pragma warning(disable : 4055)
26 #pragma warning(disable : 4100)
27 #pragma warning(disable : 4127)
28 #pragma warning(disable : 4130)
29 #pragma warning(disable : 4152)
30 #pragma warning(disable : 4189)
31 #pragma warning(disable : 4206)
32 #pragma warning(disable : 4210)
33 #pragma warning(disable : 4232)
34 #pragma warning(disable : 4244)
35 #pragma warning(disable : 4305)
36 #pragma warning(disable : 4306)
37 #pragma warning(disable : 4702)
38 #pragma warning(disable : 4706)
39 #endif /* defined(_MSC_VER) */
42 ** No support for loadable extensions in VxWorks.
44 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45 # define SQLITE_OMIT_LOAD_EXTENSION 1
49 ** Enable large-file support for fopen() and friends on unix.
51 #ifndef SQLITE_DISABLE_LFS
52 # define _LARGE_FILE 1
53 # ifndef _FILE_OFFSET_BITS
54 # define _FILE_OFFSET_BITS 64
56 # define _LARGEFILE_SOURCE 1
64 typedef sqlite3_int64 i64
;
65 typedef sqlite3_uint64 u64
;
66 typedef unsigned char u8
;
67 #if SQLITE_USER_AUTHENTICATION
68 # include "sqlite3userauth.h"
73 #if !defined(_WIN32) && !defined(WIN32)
75 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
79 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
82 # define GETPID getpid
83 # if defined(__MINGW32__)
84 # define DIRENT dirent
86 # define S_ISLNK(mode) (0)
90 # define GETPID (int)GetCurrentProcessId
92 #include <sys/types.h>
96 # include <readline/readline.h>
97 # include <readline/history.h>
101 # include <editline/readline.h>
104 #if HAVE_EDITLINE || HAVE_READLINE
106 # define shell_add_history(X) add_history(X)
107 # define shell_read_history(X) read_history(X)
108 # define shell_write_history(X) write_history(X)
109 # define shell_stifle_history(X) stifle_history(X)
110 # define shell_readline(X) readline(X)
114 # include "linenoise.h"
115 # define shell_add_history(X) linenoiseHistoryAdd(X)
116 # define shell_read_history(X) linenoiseHistoryLoad(X)
117 # define shell_write_history(X) linenoiseHistorySave(X)
118 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119 # define shell_readline(X) linenoise(X)
123 # define shell_read_history(X)
124 # define shell_write_history(X)
125 # define shell_stifle_history(X)
127 # define SHELL_USE_LOCAL_GETLINE 1
131 #if defined(_WIN32) || defined(WIN32)
134 # define isatty(h) _isatty(h)
136 # define access(f,m) _access((f),(m))
139 # define unlink _unlink
142 # define popen _popen
144 # define pclose _pclose
146 /* Make sure isatty() has a prototype. */
147 extern int isatty(int);
149 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
150 /* popen and pclose are not C89 functions and so are
151 ** sometimes omitted from the <stdio.h> header */
152 extern FILE *popen(const char*,const char*);
153 extern int pclose(FILE*);
155 # define SQLITE_OMIT_POPEN 1
159 #if defined(_WIN32_WCE)
160 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
161 * thus we always assume that we have a console. That can be
162 * overridden with the -batch command line option.
167 /* ctype macros that work with signed characters */
168 #define IsSpace(X) isspace((unsigned char)X)
169 #define IsDigit(X) isdigit((unsigned char)X)
170 #define ToLower(X) (char)tolower((unsigned char)X)
172 #if defined(_WIN32) || defined(WIN32)
175 /* string conversion routines only needed on Win32 */
176 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
177 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
178 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
179 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
182 /* On Windows, we normally run with output mode of TEXT so that \n characters
183 ** are automatically translated into \r\n. However, this behavior needs
184 ** to be disabled in some cases (ex: when generating CSV output and when
185 ** rendering quoted strings that contain \n characters). The following
186 ** routines take care of that.
188 #if defined(_WIN32) || defined(WIN32)
189 static void setBinaryMode(FILE *file
, int isOutput
){
190 if( isOutput
) fflush(file
);
191 _setmode(_fileno(file
), _O_BINARY
);
193 static void setTextMode(FILE *file
, int isOutput
){
194 if( isOutput
) fflush(file
);
195 _setmode(_fileno(file
), _O_TEXT
);
198 # define setBinaryMode(X,Y)
199 # define setTextMode(X,Y)
203 /* True if the timer is enabled */
204 static int enableTimer
= 0;
206 /* Return the current wall-clock time */
207 static sqlite3_int64
timeOfDay(void){
208 static sqlite3_vfs
*clockVfs
= 0;
210 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
211 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
212 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
215 clockVfs
->xCurrentTime(clockVfs
, &r
);
216 t
= (sqlite3_int64
)(r
*86400000.0);
221 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
222 #include <sys/time.h>
223 #include <sys/resource.h>
225 /* VxWorks does not support getrusage() as far as we can determine */
226 #if defined(_WRS_KERNEL) || defined(__RTP__)
228 struct timeval ru_utime
; /* user CPU time used */
229 struct timeval ru_stime
; /* system CPU time used */
231 #define getrusage(A,B) memset(B,0,sizeof(*B))
234 /* Saved resource information for the beginning of an operation */
235 static struct rusage sBegin
; /* CPU time at start */
236 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
239 ** Begin timing an operation
241 static void beginTimer(void){
243 getrusage(RUSAGE_SELF
, &sBegin
);
244 iBegin
= timeOfDay();
248 /* Return the difference of two time_structs in seconds */
249 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
250 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
251 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
255 ** Print the timing results.
257 static void endTimer(void){
259 sqlite3_int64 iEnd
= timeOfDay();
261 getrusage(RUSAGE_SELF
, &sEnd
);
262 printf("Run Time: real %.3f user %f sys %f\n",
263 (iEnd
- iBegin
)*0.001,
264 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
265 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
269 #define BEGIN_TIMER beginTimer()
270 #define END_TIMER endTimer()
273 #elif (defined(_WIN32) || defined(WIN32))
275 /* Saved resource information for the beginning of an operation */
276 static HANDLE hProcess
;
277 static FILETIME ftKernelBegin
;
278 static FILETIME ftUserBegin
;
279 static sqlite3_int64 ftWallBegin
;
280 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
281 LPFILETIME
, LPFILETIME
);
282 static GETPROCTIMES getProcessTimesAddr
= NULL
;
285 ** Check to see if we have timer support. Return 1 if necessary
286 ** support found (or found previously).
288 static int hasTimer(void){
289 if( getProcessTimesAddr
){
292 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
293 ** versions. See if the version we are running on has it, and if it
294 ** does, save off a pointer to it and the current process handle.
296 hProcess
= GetCurrentProcess();
298 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
299 if( NULL
!= hinstLib
){
300 getProcessTimesAddr
=
301 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
302 if( NULL
!= getProcessTimesAddr
){
305 FreeLibrary(hinstLib
);
313 ** Begin timing an operation
315 static void beginTimer(void){
316 if( enableTimer
&& getProcessTimesAddr
){
317 FILETIME ftCreation
, ftExit
;
318 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
319 &ftKernelBegin
,&ftUserBegin
);
320 ftWallBegin
= timeOfDay();
324 /* Return the difference of two FILETIME structs in seconds */
325 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
326 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
327 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
328 return (double) ((i64End
- i64Start
) / 10000000.0);
332 ** Print the timing results.
334 static void endTimer(void){
335 if( enableTimer
&& getProcessTimesAddr
){
336 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
337 sqlite3_int64 ftWallEnd
= timeOfDay();
338 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
339 printf("Run Time: real %.3f user %f sys %f\n",
340 (ftWallEnd
- ftWallBegin
)*0.001,
341 timeDiff(&ftUserBegin
, &ftUserEnd
),
342 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
346 #define BEGIN_TIMER beginTimer()
347 #define END_TIMER endTimer()
348 #define HAS_TIMER hasTimer()
357 ** Used to prevent warnings about unused parameters
359 #define UNUSED_PARAMETER(x) (void)(x)
362 ** Number of elements in an array
364 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
367 ** If the following flag is set, then command execution stops
368 ** at an error if we are not interactive.
370 static int bail_on_error
= 0;
373 ** Threat stdin as an interactive input if the following variable
374 ** is true. Otherwise, assume stdin is connected to a file or pipe.
376 static int stdin_is_interactive
= 1;
379 ** On Windows systems we have to know if standard output is a console
380 ** in order to translate UTF-8 into MBCS. The following variable is
381 ** true if translation is required.
383 static int stdout_is_console
= 1;
386 ** The following is the open SQLite database. We make a pointer
387 ** to this database a static variable so that it can be accessed
388 ** by the SIGINT handler to interrupt database processing.
390 static sqlite3
*globalDb
= 0;
393 ** True if an interrupt (Control-C) has been received.
395 static volatile int seenInterrupt
= 0;
398 ** This is the name of our program. It is set in main(), used
399 ** in a number of other places, mostly for error messages.
404 ** Prompt strings. Initialized in main. Settable with
405 ** .prompt main continue
407 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
408 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
411 ** Render output like fprintf(). Except, if the output is going to the
412 ** console and if this is running on a Windows machine, translate the
413 ** output from UTF-8 into MBCS.
415 #if defined(_WIN32) || defined(WIN32)
416 void utf8_printf(FILE *out
, const char *zFormat
, ...){
418 va_start(ap
, zFormat
);
419 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
420 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
421 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
426 vfprintf(out
, zFormat
, ap
);
430 #elif !defined(utf8_printf)
431 # define utf8_printf fprintf
435 ** Render output like fprintf(). This should not be used on anything that
436 ** includes string formatting (e.g. "%s").
438 #if !defined(raw_printf)
439 # define raw_printf fprintf
442 /* Indicate out-of-memory and exit. */
443 static void shell_out_of_memory(void){
444 raw_printf(stderr
,"Error: out of memory\n");
449 ** Write I/O traces to the following stream.
451 #ifdef SQLITE_ENABLE_IOTRACE
452 static FILE *iotrace
= 0;
456 ** This routine works like printf in that its first argument is a
457 ** format string and subsequent arguments are values to be substituted
458 ** in place of % fields. The result of formatting this string
459 ** is written to iotrace.
461 #ifdef SQLITE_ENABLE_IOTRACE
462 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
465 if( iotrace
==0 ) return;
466 va_start(ap
, zFormat
);
467 z
= sqlite3_vmprintf(zFormat
, ap
);
469 utf8_printf(iotrace
, "%s", z
);
475 ** Output string zUtf to stream pOut as w characters. If w is negative,
476 ** then right-justify the text. W is the width in UTF-8 characters, not
477 ** in bytes. This is different from the %*.*s specification in printf
478 ** since with %*.*s the width is measured in bytes, not characters.
480 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
483 int aw
= w
<0 ? -w
: w
;
485 if( aw
>(int)sizeof(zBuf
)/3 ) aw
= (int)sizeof(zBuf
)/3;
486 for(i
=n
=0; zUtf
[i
]; i
++){
487 if( (zUtf
[i
]&0xc0)!=0x80 ){
490 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
496 utf8_printf(pOut
, "%.*s", i
, zUtf
);
498 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
500 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
506 ** Determines if a string is a number of not.
508 static int isNumber(const char *z
, int *realnum
){
509 if( *z
=='-' || *z
=='+' ) z
++;
514 if( realnum
) *realnum
= 0;
515 while( IsDigit(*z
) ){ z
++; }
518 if( !IsDigit(*z
) ) return 0;
519 while( IsDigit(*z
) ){ z
++; }
520 if( realnum
) *realnum
= 1;
522 if( *z
=='e' || *z
=='E' ){
524 if( *z
=='+' || *z
=='-' ) z
++;
525 if( !IsDigit(*z
) ) return 0;
526 while( IsDigit(*z
) ){ z
++; }
527 if( realnum
) *realnum
= 1;
533 ** Compute a string length that is limited to what can be stored in
534 ** lower 30 bits of a 32-bit signed integer.
536 static int strlen30(const char *z
){
538 while( *z2
){ z2
++; }
539 return 0x3fffffff & (int)(z2
- z
);
543 ** Return the length of a string in characters. Multibyte UTF8 characters
544 ** count as a single character.
546 static int strlenChar(const char *z
){
549 if( (0xc0&*(z
++))!=0x80 ) n
++;
555 ** This routine reads a line of text from FILE in, stores
556 ** the text in memory obtained from malloc() and returns a pointer
557 ** to the text. NULL is returned at end of file, or if malloc()
560 ** If zLine is not NULL then it is a malloced buffer returned from
561 ** a previous call to this routine that may be reused.
563 static char *local_getline(char *zLine
, FILE *in
){
564 int nLine
= zLine
==0 ? 0 : 100;
569 nLine
= nLine
*2 + 100;
570 zLine
= realloc(zLine
, nLine
);
571 if( zLine
==0 ) shell_out_of_memory();
573 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
581 while( zLine
[n
] ) n
++;
582 if( n
>0 && zLine
[n
-1]=='\n' ){
584 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
589 #if defined(_WIN32) || defined(WIN32)
590 /* For interactive input on Windows systems, translate the
591 ** multi-byte characterset characters into UTF-8. */
592 if( stdin_is_interactive
&& in
==stdin
){
593 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
595 int nTrans
= strlen30(zTrans
)+1;
597 zLine
= realloc(zLine
, nTrans
);
598 if( zLine
==0 ) shell_out_of_memory();
600 memcpy(zLine
, zTrans
, nTrans
);
601 sqlite3_free(zTrans
);
604 #endif /* defined(_WIN32) || defined(WIN32) */
609 ** Retrieve a single line of input text.
611 ** If in==0 then read from standard input and prompt before each line.
612 ** If isContinuation is true, then a continuation prompt is appropriate.
613 ** If isContinuation is zero, then the main prompt should be used.
615 ** If zPrior is not NULL then it is a buffer from a prior call to this
616 ** routine that can be reused.
618 ** The result is stored in space obtained from malloc() and must either
619 ** be freed by the caller or else passed back into this routine via the
620 ** zPrior argument for reuse.
622 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
626 zResult
= local_getline(zPrior
, in
);
628 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
629 #if SHELL_USE_LOCAL_GETLINE
630 printf("%s", zPrompt
);
632 zResult
= local_getline(zPrior
, stdin
);
635 zResult
= shell_readline(zPrompt
);
636 /* BEGIN SQLCIPHER */
637 #ifdef SQLITE_HAS_CODEC
638 /* Simplistic filtering of input lines to prevent PRAGKA key and
639 PRAGMA rekey statements from being stored in readline history.
640 Note that this will only prevent single line statements, but that
641 will be sufficient for common cases. */
642 if(sqlite3_strlike("%pragma%key%=%", zResult
, 0)==0) return zResult
;
645 if( zResult
&& *zResult
) shell_add_history(zResult
);
653 ** Return the value of a hexadecimal digit. Return -1 if the input
654 ** is not a hex digit.
656 static int hexDigitValue(char c
){
657 if( c
>='0' && c
<='9' ) return c
- '0';
658 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
659 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
664 ** Interpret zArg as an integer value, possibly with suffixes.
666 static sqlite3_int64
integerValue(const char *zArg
){
668 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
670 { "MiB", 1024*1024 },
671 { "GiB", 1024*1024*1024 },
674 { "GB", 1000000000 },
684 }else if( zArg
[0]=='+' ){
687 if( zArg
[0]=='0' && zArg
[1]=='x' ){
690 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
695 while( IsDigit(zArg
[0]) ){
696 v
= v
*10 + zArg
[0] - '0';
700 for(i
=0; i
<ArraySize(aMult
); i
++){
701 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
706 return isNeg
? -v
: v
;
710 ** A variable length string to which one can append text.
712 typedef struct ShellText ShellText
;
720 ** Initialize and destroy a ShellText object
722 static void initText(ShellText
*p
){
723 memset(p
, 0, sizeof(*p
));
725 static void freeText(ShellText
*p
){
730 /* zIn is either a pointer to a NULL-terminated string in memory obtained
731 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
732 ** added to zIn, and the result returned in memory obtained from malloc().
733 ** zIn, if it was not NULL, is freed.
735 ** If the third argument, quote, is not '\0', then it is used as a
736 ** quote character for zAppend.
738 static void appendText(ShellText
*p
, char const *zAppend
, char quote
){
741 int nAppend
= strlen30(zAppend
);
743 len
= nAppend
+p
->n
+1;
746 for(i
=0; i
<nAppend
; i
++){
747 if( zAppend
[i
]==quote
) len
++;
751 if( p
->n
+len
>=p
->nAlloc
){
752 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
753 p
->z
= realloc(p
->z
, p
->nAlloc
);
754 if( p
->z
==0 ) shell_out_of_memory();
758 char *zCsr
= p
->z
+p
->n
;
760 for(i
=0; i
<nAppend
; i
++){
761 *zCsr
++ = zAppend
[i
];
762 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
765 p
->n
= (int)(zCsr
- p
->z
);
768 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
775 ** Attempt to determine if identifier zName needs to be quoted, either
776 ** because it contains non-alphanumeric characters, or because it is an
777 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
778 ** that quoting is required.
780 ** Return '"' if quoting is required. Return 0 if no quoting is required.
782 static char quoteChar(const char *zName
){
784 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
785 for(i
=0; zName
[i
]; i
++){
786 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
788 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
792 ** Construct a fake object name and column list to describe the structure
793 ** of the view, virtual table, or table valued function zSchema.zName.
795 static char *shellFakeSchema(
796 sqlite3
*db
, /* The database connection containing the vtab */
797 const char *zSchema
, /* Schema of the database holding the vtab */
798 const char *zName
/* The name of the virtual table */
800 sqlite3_stmt
*pStmt
= 0;
807 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
808 zSchema
? zSchema
: "main", zName
);
809 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
813 cQuote
= quoteChar(zSchema
);
814 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
815 appendText(&s
, zSchema
, cQuote
);
816 appendText(&s
, ".", 0);
818 cQuote
= quoteChar(zName
);
819 appendText(&s
, zName
, cQuote
);
820 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
821 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
823 appendText(&s
, zDiv
, 0);
825 cQuote
= quoteChar(zCol
);
826 appendText(&s
, zCol
, cQuote
);
828 appendText(&s
, ")", 0);
829 sqlite3_finalize(pStmt
);
838 ** SQL function: shell_module_schema(X)
840 ** Return a fake schema for the table-valued function or eponymous virtual
843 static void shellModuleSchema(
844 sqlite3_context
*pCtx
,
846 sqlite3_value
**apVal
848 const char *zName
= (const char*)sqlite3_value_text(apVal
[0]);
849 char *zFake
= shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
);
850 UNUSED_PARAMETER(nVal
);
852 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
859 ** SQL function: shell_add_schema(S,X)
861 ** Add the schema name X to the CREATE statement in S and return the result.
864 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
869 ** CREATE UNIQUE INDEX
872 ** CREATE VIRTUAL TABLE
874 ** This UDF is used by the .schema command to insert the schema name of
875 ** attached databases into the middle of the sqlite_master.sql field.
877 static void shellAddSchemaName(
878 sqlite3_context
*pCtx
,
880 sqlite3_value
**apVal
882 static const char *aPrefix
[] = {
891 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
892 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
893 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
894 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
895 UNUSED_PARAMETER(nVal
);
896 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
897 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
898 int n
= strlen30(aPrefix
[i
]);
899 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
903 char cQuote
= quoteChar(zSchema
);
904 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
905 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
907 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
911 && aPrefix
[i
][0]=='V'
912 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
915 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
917 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
922 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
928 sqlite3_result_value(pCtx
, apVal
[0]);
932 ** The source code for several run-time loadable extensions is inserted
933 ** below by the ../tool/mkshellc.tcl script. Before processing that included
934 ** code, we need to override some macros to make the included program code
935 ** work here in the middle of this regular program.
937 #define SQLITE_EXTENSION_INIT1
938 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
940 #if defined(_WIN32) && defined(_MSC_VER)
941 INCLUDE test_windirent
.h
942 INCLUDE test_windirent
.c
943 #define dirent DIRENT
945 INCLUDE
../ext
/misc
/shathree
.c
946 INCLUDE
../ext
/misc
/fileio
.c
947 INCLUDE
../ext
/misc
/completion
.c
948 INCLUDE
../ext
/misc
/appendvfs
.c
949 #ifdef SQLITE_HAVE_ZLIB
950 INCLUDE
../ext
/misc
/zipfile
.c
951 INCLUDE
../ext
/misc
/sqlar
.c
953 INCLUDE
../ext
/expert
/sqlite3expert
.h
954 INCLUDE
../ext
/expert
/sqlite3expert
.c
956 #if defined(SQLITE_ENABLE_SESSION)
958 ** State information for a single open session
960 typedef struct OpenSession OpenSession
;
962 char *zName
; /* Symbolic name for this session */
963 int nFilter
; /* Number of xFilter rejection GLOB patterns */
964 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
965 sqlite3_session
*p
; /* The open session */
970 ** Shell output mode information from before ".explain on",
971 ** saved so that it can be restored by ".explain off"
973 typedef struct SavedModeInfo SavedModeInfo
;
974 struct SavedModeInfo
{
975 int valid
; /* Is there legit data in here? */
976 int mode
; /* Mode prior to ".explain on" */
977 int showHeader
; /* The ".header" setting prior to ".explain on" */
978 int colWidth
[100]; /* Column widths prior to ".explain on" */
981 typedef struct ExpertInfo ExpertInfo
;
983 sqlite3expert
*pExpert
;
987 /* A single line in the EQP output */
988 typedef struct EQPGraphRow EQPGraphRow
;
990 int iEqpId
; /* ID for this row */
991 int iParentId
; /* ID of the parent row */
992 EQPGraphRow
*pNext
; /* Next row in sequence */
993 char zText
[1]; /* Text to display for this row */
996 /* All EQP output is collected into an instance of the following */
997 typedef struct EQPGraph EQPGraph
;
999 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
1000 EQPGraphRow
*pLast
; /* Last element of the pRow list */
1001 char zPrefix
[100]; /* Graph prefix */
1005 ** State information about the database connection is contained in an
1006 ** instance of the following structure.
1008 typedef struct ShellState ShellState
;
1010 sqlite3
*db
; /* The database */
1011 u8 autoExplain
; /* Automatically turn on .explain mode */
1012 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1013 u8 autoEQPtest
; /* autoEQP is in test mode */
1014 u8 statsOn
; /* True to display memory stats before each finalize */
1015 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1016 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1017 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1018 u8 nEqpLevel
; /* Depth of the EQP output graph */
1019 unsigned mEqpLines
; /* Mask of veritical lines in the EQP output graph */
1020 int outCount
; /* Revert to stdout when reaching zero */
1021 int cnt
; /* Number of records displayed so far */
1022 FILE *out
; /* Write results here */
1023 FILE *traceOut
; /* Output for sqlite3_trace() */
1024 int nErr
; /* Number of errors seen */
1025 int mode
; /* An output mode setting */
1026 int modePrior
; /* Saved mode */
1027 int cMode
; /* temporary output mode for the current query */
1028 int normalMode
; /* Output mode before ".explain on" */
1029 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1030 int showHeader
; /* True to show column names in List or Column mode */
1031 int nCheck
; /* Number of ".check" commands run */
1032 unsigned shellFlgs
; /* Various flags */
1033 char *zDestTable
; /* Name of destination table when MODE_Insert */
1034 char *zTempFile
; /* Temporary file that might need deleting */
1035 char zTestcase
[30]; /* Name of current test case */
1036 char colSeparator
[20]; /* Column separator character for several modes */
1037 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1038 char colSepPrior
[20]; /* Saved column separator */
1039 char rowSepPrior
[20]; /* Saved row separator */
1040 int colWidth
[100]; /* Requested width of each column when in column mode*/
1041 int actualWidth
[100]; /* Actual width of each column */
1042 char nullValue
[20]; /* The text to print when a NULL comes back from
1044 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1045 const char *zDbFilename
; /* name of the database file */
1046 char *zFreeOnClose
; /* Filename to free when closing */
1047 const char *zVfs
; /* Name of VFS to use */
1048 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1049 FILE *pLog
; /* Write log output here */
1050 int *aiIndent
; /* Array of indents used in MODE_Explain */
1051 int nIndent
; /* Size of array aiIndent[] */
1052 int iIndent
; /* Index of current op in aiIndent[] */
1053 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1054 #if defined(SQLITE_ENABLE_SESSION)
1055 int nSession
; /* Number of active sessions */
1056 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1058 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1062 /* Allowed values for ShellState.autoEQP
1064 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1065 #define AUTOEQP_on 1 /* Automatic EQP is on */
1066 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1067 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1069 /* Allowed values for ShellState.openMode
1071 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1072 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1073 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1074 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1075 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1078 ** These are the allowed shellFlgs values
1080 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1081 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1082 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1083 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1084 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1085 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1086 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1089 ** Macros for testing and setting shellFlgs
1091 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1092 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1093 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1096 ** These are the allowed modes.
1098 #define MODE_Line 0 /* One column per line. Blank line between records */
1099 #define MODE_Column 1 /* One record per line in neat columns */
1100 #define MODE_List 2 /* One record per line with a separator */
1101 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1102 #define MODE_Html 4 /* Generate an XHTML table */
1103 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1104 #define MODE_Quote 6 /* Quote values as for SQL */
1105 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1106 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1107 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1108 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1109 #define MODE_Pretty 11 /* Pretty-print schemas */
1110 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1112 static const char *modeDescr
[] = {
1129 ** These are the column/row/line separators used by the various
1130 ** import/export modes.
1132 #define SEP_Column "|"
1133 #define SEP_Row "\n"
1134 #define SEP_Tab "\t"
1135 #define SEP_Space " "
1136 #define SEP_Comma ","
1137 #define SEP_CrLf "\r\n"
1138 #define SEP_Unit "\x1F"
1139 #define SEP_Record "\x1E"
1142 ** A callback for the sqlite3_log() interface.
1144 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1145 ShellState
*p
= (ShellState
*)pArg
;
1146 if( p
->pLog
==0 ) return;
1147 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1152 ** SQL function: shell_putsnl(X)
1154 ** Write the text X to the screen (or whatever output is being directed)
1155 ** adding a newline at the end, and then return X.
1157 static void shellPutsFunc(
1158 sqlite3_context
*pCtx
,
1160 sqlite3_value
**apVal
1162 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1164 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1165 sqlite3_result_value(pCtx
, apVal
[0]);
1169 ** SQL function: edit(VALUE)
1170 ** edit(VALUE,EDITOR)
1174 ** (1) Write VALUE into a temporary file.
1175 ** (2) Run program EDITOR on that temporary file.
1176 ** (3) Read the temporary file back and return its content as the result.
1177 ** (4) Delete the temporary file
1179 ** If the EDITOR argument is omitted, use the value in the VISUAL
1180 ** environment variable. If still there is no EDITOR, through an error.
1182 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1184 #ifndef SQLITE_NOHAVE_SYSTEM
1185 static void editFunc(
1186 sqlite3_context
*context
,
1188 sqlite3_value
**argv
1190 const char *zEditor
;
1191 char *zTempFile
= 0;
1200 unsigned char *p
= 0;
1203 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1205 zEditor
= getenv("VISUAL");
1208 sqlite3_result_error(context
, "no editor for edit()", -1);
1211 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1212 sqlite3_result_error(context
, "NULL input to edit()", -1);
1215 db
= sqlite3_context_db_handle(context
);
1217 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1219 sqlite3_uint64 r
= 0;
1220 sqlite3_randomness(sizeof(r
), &r
);
1221 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1223 sqlite3_result_error_nomem(context
);
1227 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1228 /* When writing the file to be edited, do \n to \r\n conversions on systems
1229 ** that want \r\n line endings */
1230 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1232 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1235 sz
= sqlite3_value_bytes(argv
[0]);
1237 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, sz
, f
);
1239 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
1240 /* Remember whether or not the value originally contained \r\n */
1241 if( z
&& strstr(z
,"\r\n")!=0 ) hasCRNL
= 1;
1242 x
= fwrite(sqlite3_value_text(argv
[0]), 1, sz
, f
);
1247 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1250 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1252 sqlite3_result_error_nomem(context
);
1258 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1261 f
= fopen(zTempFile
, "rb");
1263 sqlite3_result_error(context
,
1264 "edit() cannot reopen temp file after edit", -1);
1267 fseek(f
, 0, SEEK_END
);
1270 p
= sqlite3_malloc64( sz
+(bBin
==0) );
1272 sqlite3_result_error_nomem(context
);
1275 x
= fread(p
, 1, sz
, f
);
1279 sqlite3_result_error(context
, "could not read back the whole file", -1);
1283 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1287 /* If the original contains \r\n then do no conversions back to \n */
1290 /* If the file did not originally contain \r\n then convert any new
1291 ** \r\n back into \n */
1292 for(i
=j
=0; i
<sz
; i
++){
1293 if( p
[i
]=='\r' && p
[i
+1]=='\n' ) i
++;
1299 sqlite3_result_text64(context
, (const char*)p
, sz
,
1300 sqlite3_free
, SQLITE_UTF8
);
1307 sqlite3_free(zTempFile
);
1310 #endif /* SQLITE_NOHAVE_SYSTEM */
1313 ** Save or restore the current output mode
1315 static void outputModePush(ShellState
*p
){
1316 p
->modePrior
= p
->mode
;
1317 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1318 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1320 static void outputModePop(ShellState
*p
){
1321 p
->mode
= p
->modePrior
;
1322 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1323 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1327 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1329 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1331 char *zBlob
= (char *)pBlob
;
1332 raw_printf(out
,"X'");
1333 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
1334 raw_printf(out
,"'");
1338 ** Find a string that is not found anywhere in z[]. Return a pointer
1341 ** Try to use zA and zB first. If both of those are already found in z[]
1342 ** then make up some string and store it in the buffer zBuf.
1344 static const char *unused_string(
1345 const char *z
, /* Result must not appear anywhere in z */
1346 const char *zA
, const char *zB
, /* Try these first */
1347 char *zBuf
/* Space to store a generated string */
1350 if( strstr(z
, zA
)==0 ) return zA
;
1351 if( strstr(z
, zB
)==0 ) return zB
;
1353 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1354 }while( strstr(z
,zBuf
)!=0 );
1359 ** Output the given string as a quoted string using SQL quoting conventions.
1361 ** See also: output_quoted_escaped_string()
1363 static void output_quoted_string(FILE *out
, const char *z
){
1366 setBinaryMode(out
, 1);
1367 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1369 utf8_printf(out
,"'%s'",z
);
1371 raw_printf(out
, "'");
1373 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1376 utf8_printf(out
, "%.*s", i
, z
);
1380 raw_printf(out
, "'");
1388 raw_printf(out
, "'");
1390 setTextMode(out
, 1);
1394 ** Output the given string as a quoted string using SQL quoting conventions.
1395 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1396 ** get corrupted by end-of-line translation facilities in some operating
1399 ** This is like output_quoted_string() but with the addition of the \r\n
1400 ** escape mechanism.
1402 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1405 setBinaryMode(out
, 1);
1406 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1408 utf8_printf(out
,"'%s'",z
);
1410 const char *zNL
= 0;
1411 const char *zCR
= 0;
1414 char zBuf1
[20], zBuf2
[20];
1415 for(i
=0; z
[i
]; i
++){
1416 if( z
[i
]=='\n' ) nNL
++;
1417 if( z
[i
]=='\r' ) nCR
++;
1420 raw_printf(out
, "replace(");
1421 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1424 raw_printf(out
, "replace(");
1425 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1427 raw_printf(out
, "'");
1429 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1432 utf8_printf(out
, "%.*s", i
, z
);
1436 raw_printf(out
, "'");
1444 raw_printf(out
, "%s", zNL
);
1447 raw_printf(out
, "%s", zCR
);
1449 raw_printf(out
, "'");
1451 raw_printf(out
, ",'%s',char(13))", zCR
);
1454 raw_printf(out
, ",'%s',char(10))", zNL
);
1457 setTextMode(out
, 1);
1461 ** Output the given string as a quoted according to C or TCL quoting rules.
1463 static void output_c_string(FILE *out
, const char *z
){
1466 while( (c
= *(z
++))!=0 ){
1473 }else if( c
=='\t' ){
1476 }else if( c
=='\n' ){
1479 }else if( c
=='\r' ){
1482 }else if( !isprint(c
&0xff) ){
1483 raw_printf(out
, "\\%03o", c
&0xff);
1492 ** Output the given string with characters that are special to
1495 static void output_html_string(FILE *out
, const char *z
){
1507 utf8_printf(out
,"%.*s",i
,z
);
1510 raw_printf(out
,"<");
1511 }else if( z
[i
]=='&' ){
1512 raw_printf(out
,"&");
1513 }else if( z
[i
]=='>' ){
1514 raw_printf(out
,">");
1515 }else if( z
[i
]=='\"' ){
1516 raw_printf(out
,""");
1517 }else if( z
[i
]=='\'' ){
1518 raw_printf(out
,"'");
1527 ** If a field contains any character identified by a 1 in the following
1528 ** array, then the string must be quoted for CSV.
1530 static const char needCsvQuote
[] = {
1531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1532 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1533 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1534 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1535 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1536 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1537 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1538 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1539 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1540 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1541 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1542 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1543 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1544 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1545 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1546 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1550 ** Output a single term of CSV. Actually, p->colSeparator is used for
1551 ** the separator, which may or may not be a comma. p->nullValue is
1552 ** the null value. Strings are quoted if necessary. The separator
1553 ** is only issued if bSep is true.
1555 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1558 utf8_printf(out
,"%s",p
->nullValue
);
1561 int nSep
= strlen30(p
->colSeparator
);
1562 for(i
=0; z
[i
]; i
++){
1563 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1564 || (z
[i
]==p
->colSeparator
[0] &&
1565 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1571 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1572 utf8_printf(out
, "%s", zQuoted
);
1573 sqlite3_free(zQuoted
);
1575 utf8_printf(out
, "%s", z
);
1579 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1584 ** This routine runs when the user presses Ctrl-C
1586 static void interrupt_handler(int NotUsed
){
1587 UNUSED_PARAMETER(NotUsed
);
1589 if( seenInterrupt
>2 ) exit(1);
1590 if( globalDb
) sqlite3_interrupt(globalDb
);
1593 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1595 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1597 static BOOL WINAPI
ConsoleCtrlHandler(
1598 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1600 if( dwCtrlType
==CTRL_C_EVENT
){
1601 interrupt_handler(0);
1608 #ifndef SQLITE_OMIT_AUTHORIZATION
1610 ** When the ".auth ON" is set, the following authorizer callback is
1611 ** invoked. It always returns SQLITE_OK.
1613 static int shellAuth(
1621 ShellState
*p
= (ShellState
*)pClientData
;
1622 static const char *azAction
[] = { 0,
1623 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1624 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1625 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1626 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1627 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1628 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1629 "PRAGMA", "READ", "SELECT",
1630 "TRANSACTION", "UPDATE", "ATTACH",
1631 "DETACH", "ALTER_TABLE", "REINDEX",
1632 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1633 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1641 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1643 raw_printf(p
->out
, " ");
1645 output_c_string(p
->out
, az
[i
]);
1647 raw_printf(p
->out
, "NULL");
1650 raw_printf(p
->out
, "\n");
1656 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1658 ** This routine converts some CREATE TABLE statements for shadow tables
1659 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1661 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1662 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1663 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1665 utf8_printf(out
, "%s%s", z
, zTail
);
1668 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1671 printSchemaLine(out
, z
, zTail
);
1676 ** Return true if string z[] has nothing but whitespace and comments to the
1677 ** end of the first line.
1679 static int wsToEol(const char *z
){
1681 for(i
=0; z
[i
]; i
++){
1682 if( z
[i
]=='\n' ) return 1;
1683 if( IsSpace(z
[i
]) ) continue;
1684 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
1691 ** Add a new entry to the EXPLAIN QUERY PLAN data
1693 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
1695 int nText
= strlen30(zText
);
1696 if( p
->autoEQPtest
){
1697 utf8_printf(p
->out
, "%d,%d,%s\n", iEqpId
, p2
, zText
);
1699 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
1700 if( pNew
==0 ) shell_out_of_memory();
1701 pNew
->iEqpId
= iEqpId
;
1702 pNew
->iParentId
= p2
;
1703 memcpy(pNew
->zText
, zText
, nText
+1);
1705 if( p
->sGraph
.pLast
){
1706 p
->sGraph
.pLast
->pNext
= pNew
;
1708 p
->sGraph
.pRow
= pNew
;
1710 p
->sGraph
.pLast
= pNew
;
1714 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1717 static void eqp_reset(ShellState
*p
){
1718 EQPGraphRow
*pRow
, *pNext
;
1719 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
1720 pNext
= pRow
->pNext
;
1723 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
1726 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1727 ** pOld, or return the first such line if pOld is NULL
1729 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
1730 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
1731 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
1735 /* Render a single level of the graph that has iEqpId as its parent. Called
1736 ** recursively to render sublevels.
1738 static void eqp_render_level(ShellState
*p
, int iEqpId
){
1739 EQPGraphRow
*pRow
, *pNext
;
1740 int n
= strlen30(p
->sGraph
.zPrefix
);
1742 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
1743 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
1745 utf8_printf(p
->out
, "%s%s%s\n", p
->sGraph
.zPrefix
, pNext
? "|--" : "`--", z
);
1746 if( n
<(int)sizeof(p
->sGraph
.zPrefix
)-7 ){
1747 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
1748 eqp_render_level(p
, pRow
->iEqpId
);
1749 p
->sGraph
.zPrefix
[n
] = 0;
1755 ** Display and reset the EXPLAIN QUERY PLAN data
1757 static void eqp_render(ShellState
*p
){
1758 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
1760 if( pRow
->zText
[0]=='-' ){
1761 if( pRow
->pNext
==0 ){
1765 utf8_printf(p
->out
, "%s\n", pRow
->zText
+3);
1766 p
->sGraph
.pRow
= pRow
->pNext
;
1769 utf8_printf(p
->out
, "QUERY PLAN\n");
1771 p
->sGraph
.zPrefix
[0] = 0;
1772 eqp_render_level(p
, 0);
1778 ** This is the callback routine that the shell
1779 ** invokes for each row of a query result.
1781 static int shell_callback(
1783 int nArg
, /* Number of result columns */
1784 char **azArg
, /* Text of each result column */
1785 char **azCol
, /* Column names */
1786 int *aiType
/* Column types */
1789 ShellState
*p
= (ShellState
*)pArg
;
1791 if( azArg
==0 ) return 0;
1795 if( azArg
==0 ) break;
1796 for(i
=0; i
<nArg
; i
++){
1797 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1798 if( len
>w
) w
= len
;
1800 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1801 for(i
=0; i
<nArg
; i
++){
1802 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1803 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1809 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1810 const int *colWidth
;
1813 if( p
->cMode
==MODE_Column
){
1814 colWidth
= p
->colWidth
;
1815 showHdr
= p
->showHeader
;
1816 rowSep
= p
->rowSeparator
;
1818 colWidth
= aExplainWidths
;
1823 for(i
=0; i
<nArg
; i
++){
1825 if( i
<ArraySize(p
->colWidth
) ){
1831 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1833 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1836 if( i
<ArraySize(p
->actualWidth
) ){
1837 p
->actualWidth
[i
] = w
;
1840 utf8_width_print(p
->out
, w
, azCol
[i
]);
1841 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1845 for(i
=0; i
<nArg
; i
++){
1847 if( i
<ArraySize(p
->actualWidth
) ){
1848 w
= p
->actualWidth
[i
];
1853 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1854 "----------------------------------------------------------"
1855 "----------------------------------------------------------",
1856 i
==nArg
-1 ? rowSep
: " ");
1860 if( azArg
==0 ) break;
1861 for(i
=0; i
<nArg
; i
++){
1863 if( i
<ArraySize(p
->actualWidth
) ){
1864 w
= p
->actualWidth
[i
];
1868 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1869 w
= strlenChar(azArg
[i
]);
1871 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1872 if( p
->iIndent
<p
->nIndent
){
1873 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1877 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1878 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1882 case MODE_Semi
: { /* .schema and .fullschema output */
1883 printSchemaLine(p
->out
, azArg
[0], ";\n");
1886 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1894 if( azArg
[0]==0 ) break;
1895 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1896 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1898 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1901 z
= sqlite3_mprintf("%s", azArg
[0]);
1903 for(i
=0; IsSpace(z
[i
]); i
++){}
1904 for(; (c
= z
[i
])!=0; i
++){
1906 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1907 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1908 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1913 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1915 if( strlen30(z
)>=79 ){
1916 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy changes from z[i] back to z[j] */
1919 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1923 }else if( c
=='-' && z
[i
+1]=='-' ){
1929 if( nLine
>0 && nParen
==0 && j
>0 ){
1930 printSchemaLineN(p
->out
, z
, j
, "\n");
1935 if( nParen
==1 && cEnd
==0
1936 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
1939 printSchemaLineN(p
->out
, z
, j
, "\n ");
1942 while( IsSpace(z
[i
+1]) ){ i
++; }
1947 printSchemaLine(p
->out
, z
, ";\n");
1952 if( p
->cnt
++==0 && p
->showHeader
){
1953 for(i
=0; i
<nArg
; i
++){
1954 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1955 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1958 if( azArg
==0 ) break;
1959 for(i
=0; i
<nArg
; i
++){
1961 if( z
==0 ) z
= p
->nullValue
;
1962 utf8_printf(p
->out
, "%s", z
);
1964 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1966 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1972 if( p
->cnt
++==0 && p
->showHeader
){
1973 raw_printf(p
->out
,"<TR>");
1974 for(i
=0; i
<nArg
; i
++){
1975 raw_printf(p
->out
,"<TH>");
1976 output_html_string(p
->out
, azCol
[i
]);
1977 raw_printf(p
->out
,"</TH>\n");
1979 raw_printf(p
->out
,"</TR>\n");
1981 if( azArg
==0 ) break;
1982 raw_printf(p
->out
,"<TR>");
1983 for(i
=0; i
<nArg
; i
++){
1984 raw_printf(p
->out
,"<TD>");
1985 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1986 raw_printf(p
->out
,"</TD>\n");
1988 raw_printf(p
->out
,"</TR>\n");
1992 if( p
->cnt
++==0 && p
->showHeader
){
1993 for(i
=0; i
<nArg
; i
++){
1994 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1995 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1997 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1999 if( azArg
==0 ) break;
2000 for(i
=0; i
<nArg
; i
++){
2001 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2002 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2004 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2008 setBinaryMode(p
->out
, 1);
2009 if( p
->cnt
++==0 && p
->showHeader
){
2010 for(i
=0; i
<nArg
; i
++){
2011 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
2013 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2016 for(i
=0; i
<nArg
; i
++){
2017 output_csv(p
, azArg
[i
], i
<nArg
-1);
2019 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2021 setTextMode(p
->out
, 1);
2025 if( azArg
==0 ) break;
2026 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
2027 if( p
->showHeader
){
2028 raw_printf(p
->out
,"(");
2029 for(i
=0; i
<nArg
; i
++){
2030 if( i
>0 ) raw_printf(p
->out
, ",");
2031 if( quoteChar(azCol
[i
]) ){
2032 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2033 utf8_printf(p
->out
, "%s", z
);
2036 raw_printf(p
->out
, "%s", azCol
[i
]);
2039 raw_printf(p
->out
,")");
2042 for(i
=0; i
<nArg
; i
++){
2043 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
2044 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2045 utf8_printf(p
->out
,"NULL");
2046 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2047 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2048 output_quoted_string(p
->out
, azArg
[i
]);
2050 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2052 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2053 utf8_printf(p
->out
,"%s", azArg
[i
]);
2054 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2056 double r
= sqlite3_column_double(p
->pStmt
, i
);
2058 memcpy(&ur
,&r
,sizeof(r
));
2059 if( ur
==0x7ff0000000000000LL
){
2060 raw_printf(p
->out
, "1e999");
2061 }else if( ur
==0xfff0000000000000LL
){
2062 raw_printf(p
->out
, "-1e999");
2064 sqlite3_snprintf(50,z
,"%!.20g", r
);
2065 raw_printf(p
->out
, "%s", z
);
2067 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2068 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2069 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2070 output_hex_blob(p
->out
, pBlob
, nBlob
);
2071 }else if( isNumber(azArg
[i
], 0) ){
2072 utf8_printf(p
->out
,"%s", azArg
[i
]);
2073 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2074 output_quoted_string(p
->out
, azArg
[i
]);
2076 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2079 raw_printf(p
->out
,");\n");
2083 if( azArg
==0 ) break;
2084 if( p
->cnt
==0 && p
->showHeader
){
2085 for(i
=0; i
<nArg
; i
++){
2086 if( i
>0 ) raw_printf(p
->out
, ",");
2087 output_quoted_string(p
->out
, azCol
[i
]);
2089 raw_printf(p
->out
,"\n");
2092 for(i
=0; i
<nArg
; i
++){
2093 if( i
>0 ) raw_printf(p
->out
, ",");
2094 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2095 utf8_printf(p
->out
,"NULL");
2096 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2097 output_quoted_string(p
->out
, azArg
[i
]);
2098 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2099 utf8_printf(p
->out
,"%s", azArg
[i
]);
2100 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2102 double r
= sqlite3_column_double(p
->pStmt
, i
);
2103 sqlite3_snprintf(50,z
,"%!.20g", r
);
2104 raw_printf(p
->out
, "%s", z
);
2105 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2106 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2107 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2108 output_hex_blob(p
->out
, pBlob
, nBlob
);
2109 }else if( isNumber(azArg
[i
], 0) ){
2110 utf8_printf(p
->out
,"%s", azArg
[i
]);
2112 output_quoted_string(p
->out
, azArg
[i
]);
2115 raw_printf(p
->out
,"\n");
2119 if( p
->cnt
++==0 && p
->showHeader
){
2120 for(i
=0; i
<nArg
; i
++){
2121 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2122 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2124 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2126 if( azArg
==0 ) break;
2127 for(i
=0; i
<nArg
; i
++){
2128 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2129 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2131 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2135 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2143 ** This is the callback routine that the SQLite library
2144 ** invokes for each row of a query result.
2146 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2147 /* since we don't have type info, call the shell_callback with a NULL value */
2148 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2152 ** This is the callback routine from sqlite3_exec() that appends all
2153 ** output onto the end of a ShellText object.
2155 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2156 ShellText
*p
= (ShellText
*)pArg
;
2158 UNUSED_PARAMETER(az
);
2159 if( azArg
==0 ) return 0;
2160 if( p
->n
) appendText(p
, "|", 0);
2161 for(i
=0; i
<nArg
; i
++){
2162 if( i
) appendText(p
, ",", 0);
2163 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2169 ** Generate an appropriate SELFTEST table in the main database.
2171 static void createSelftestTable(ShellState
*p
){
2174 "SAVEPOINT selftest_init;\n"
2175 "CREATE TABLE IF NOT EXISTS selftest(\n"
2176 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2177 " op TEXT,\n" /* Operator: memo run */
2178 " cmd TEXT,\n" /* Command text */
2179 " ans TEXT\n" /* Desired answer */
2181 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2182 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2183 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2184 " 'memo','Tests generated by --init');\n"
2185 "INSERT INTO [_shell$self]\n"
2187 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2188 "FROM sqlite_master ORDER BY 2'',224))',\n"
2189 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2190 "FROM sqlite_master ORDER BY 2',224));\n"
2191 "INSERT INTO [_shell$self]\n"
2193 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2194 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2195 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2197 " SELECT name FROM sqlite_master\n"
2198 " WHERE type='table'\n"
2199 " AND name<>'selftest'\n"
2200 " AND coalesce(rootpage,0)>0\n"
2203 "INSERT INTO [_shell$self]\n"
2204 " VALUES('run','PRAGMA integrity_check','ok');\n"
2205 "INSERT INTO selftest(tno,op,cmd,ans)"
2206 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2207 "DROP TABLE [_shell$self];"
2210 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2211 sqlite3_free(zErrMsg
);
2213 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2218 ** Set the destination table field of the ShellState structure to
2219 ** the name of the table given. Escape any quote characters in the
2222 static void set_table_name(ShellState
*p
, const char *zName
){
2227 if( p
->zDestTable
){
2228 free(p
->zDestTable
);
2231 if( zName
==0 ) return;
2232 cQuote
= quoteChar(zName
);
2233 n
= strlen30(zName
);
2234 if( cQuote
) n
+= n
+2;
2235 z
= p
->zDestTable
= malloc( n
+1 );
2236 if( z
==0 ) shell_out_of_memory();
2238 if( cQuote
) z
[n
++] = cQuote
;
2239 for(i
=0; zName
[i
]; i
++){
2241 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2243 if( cQuote
) z
[n
++] = cQuote
;
2249 ** Execute a query statement that will generate SQL output. Print
2250 ** the result columns, comma-separated, on a line and then add a
2251 ** semicolon terminator to the end of that line.
2253 ** If the number of columns is 1 and that column contains text "--"
2254 ** then write the semicolon on a separate line. That way, if a
2255 ** "--" comment occurs at the end of the statement, the comment
2256 ** won't consume the semicolon terminator.
2258 static int run_table_dump_query(
2259 ShellState
*p
, /* Query context */
2260 const char *zSelect
, /* SELECT statement to extract content */
2261 const char *zFirstRow
/* Print before first row, if not NULL */
2263 sqlite3_stmt
*pSelect
;
2268 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2269 if( rc
!=SQLITE_OK
|| !pSelect
){
2270 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2271 sqlite3_errmsg(p
->db
));
2272 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2275 rc
= sqlite3_step(pSelect
);
2276 nResult
= sqlite3_column_count(pSelect
);
2277 while( rc
==SQLITE_ROW
){
2279 utf8_printf(p
->out
, "%s", zFirstRow
);
2282 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2283 utf8_printf(p
->out
, "%s", z
);
2284 for(i
=1; i
<nResult
; i
++){
2285 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2288 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2290 raw_printf(p
->out
, "\n;\n");
2292 raw_printf(p
->out
, ";\n");
2294 rc
= sqlite3_step(pSelect
);
2296 rc
= sqlite3_finalize(pSelect
);
2297 if( rc
!=SQLITE_OK
){
2298 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2299 sqlite3_errmsg(p
->db
));
2300 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2306 ** Allocate space and save off current error string.
2308 static char *save_err_msg(
2309 sqlite3
*db
/* Database to query */
2311 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
2312 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
2314 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
2321 ** Attempt to display I/O stats on Linux using /proc/PID/io
2323 static void displayLinuxIoStats(FILE *out
){
2326 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2327 in
= fopen(z
, "rb");
2329 while( fgets(z
, sizeof(z
), in
)!=0 ){
2330 static const struct {
2331 const char *zPattern
;
2334 { "rchar: ", "Bytes received by read():" },
2335 { "wchar: ", "Bytes sent to write():" },
2336 { "syscr: ", "Read() system calls:" },
2337 { "syscw: ", "Write() system calls:" },
2338 { "read_bytes: ", "Bytes read from storage:" },
2339 { "write_bytes: ", "Bytes written to storage:" },
2340 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2343 for(i
=0; i
<ArraySize(aTrans
); i
++){
2344 int n
= strlen30(aTrans
[i
].zPattern
);
2345 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2346 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2356 ** Display a single line of status using 64-bit values.
2358 static void displayStatLine(
2359 ShellState
*p
, /* The shell context */
2360 char *zLabel
, /* Label for this one line */
2361 char *zFormat
, /* Format for the result */
2362 int iStatusCtrl
, /* Which status to display */
2363 int bReset
/* True to reset the stats */
2365 sqlite3_int64 iCur
= -1;
2366 sqlite3_int64 iHiwtr
= -1;
2369 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2370 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2371 if( zFormat
[i
]=='%' ) nPercent
++;
2374 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2376 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2378 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2382 ** Display memory stats.
2384 static int display_stats(
2385 sqlite3
*db
, /* Database to query */
2386 ShellState
*pArg
, /* Pointer to ShellState */
2387 int bReset
/* True to reset the stats */
2392 if( pArg
==0 || pArg
->out
==0 ) return 0;
2395 if( pArg
->pStmt
&& (pArg
->statsOn
& 2) ){
2397 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
2399 nCol
= sqlite3_column_count(pStmt
);
2400 raw_printf(out
, "%-36s %d\n", "Number of output columns:", nCol
);
2401 for(i
=0; i
<nCol
; i
++){
2402 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
2403 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
2404 #ifndef SQLITE_OMIT_DECLTYPE
2405 sqlite3_snprintf(30, z
+x
, "declared type:");
2406 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
2408 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2409 sqlite3_snprintf(30, z
+x
, "database name:");
2410 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
2411 sqlite3_snprintf(30, z
+x
, "table name:");
2412 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
2413 sqlite3_snprintf(30, z
+x
, "origin name:");
2414 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
2419 displayStatLine(pArg
, "Memory Used:",
2420 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
2421 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2422 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2423 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2424 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2425 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2427 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2428 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2429 displayStatLine(pArg
, "Largest Allocation:",
2430 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2431 displayStatLine(pArg
, "Largest Pcache Allocation:",
2432 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2433 #ifdef YYTRACKMAXSTACKDEPTH
2434 displayStatLine(pArg
, "Deepest Parser Stack:",
2435 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2439 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2441 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2442 &iCur
, &iHiwtr
, bReset
);
2443 raw_printf(pArg
->out
,
2444 "Lookaside Slots Used: %d (max %d)\n",
2446 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2447 &iCur
, &iHiwtr
, bReset
);
2448 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2450 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2451 &iCur
, &iHiwtr
, bReset
);
2452 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2454 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2455 &iCur
, &iHiwtr
, bReset
);
2456 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2460 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2461 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2464 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2465 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2467 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2468 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2470 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2471 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2473 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
2474 raw_printf(pArg
->out
, "Page cache spills: %d\n", iCur
);
2476 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2477 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2480 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2481 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2486 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2488 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2489 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2490 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2491 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2492 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2493 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2494 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2495 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
, bReset
);
2496 raw_printf(pArg
->out
, "Reprepare operations: %d\n", iCur
);
2497 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
2498 raw_printf(pArg
->out
, "Number of times run: %d\n", iCur
);
2499 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
2500 raw_printf(pArg
->out
, "Memory used by prepared stmt: %d\n", iCur
);
2504 displayLinuxIoStats(pArg
->out
);
2507 /* Do not remove this machine readable comment: extra-stats-output-here */
2513 ** Display scan stats.
2515 static void display_scanstats(
2516 sqlite3
*db
, /* Database to query */
2517 ShellState
*pArg
/* Pointer to ShellState */
2519 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2520 UNUSED_PARAMETER(db
);
2521 UNUSED_PARAMETER(pArg
);
2524 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2526 for(k
=0; k
<=mx
; k
++){
2527 double rEstLoop
= 1.0;
2529 sqlite3_stmt
*p
= pArg
->pStmt
;
2530 sqlite3_int64 nLoop
, nVisit
;
2533 const char *zExplain
;
2534 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2537 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2538 if( iSid
>mx
) mx
= iSid
;
2539 if( iSid
!=k
) continue;
2541 rEstLoop
= (double)nLoop
;
2542 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2545 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2546 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2547 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2548 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2550 raw_printf(pArg
->out
,
2551 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2552 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2556 raw_printf(pArg
->out
, "---------------------------\n");
2561 ** Parameter azArray points to a zero-terminated array of strings. zStr
2562 ** points to a single nul-terminated string. Return non-zero if zStr
2563 ** is equal, according to strcmp(), to any of the strings in the array.
2564 ** Otherwise, return zero.
2566 static int str_in_array(const char *zStr
, const char **azArray
){
2568 for(i
=0; azArray
[i
]; i
++){
2569 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2575 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2576 ** and populate the ShellState.aiIndent[] array with the number of
2577 ** spaces each opcode should be indented before it is output.
2579 ** The indenting rules are:
2581 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2582 ** all opcodes that occur between the p2 jump destination and the opcode
2583 ** itself by 2 spaces.
2585 ** * For each "Goto", if the jump destination is earlier in the program
2586 ** and ends on one of:
2587 ** Yield SeekGt SeekLt RowSetRead Rewind
2588 ** or if the P1 parameter is one instead of zero,
2589 ** then indent all opcodes between the earlier instruction
2590 ** and "Goto" by 2 spaces.
2592 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2593 const char *zSql
; /* The text of the SQL statement */
2594 const char *z
; /* Used to check if this is an EXPLAIN */
2595 int *abYield
= 0; /* True if op is an OP_Yield */
2596 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2597 int iOp
; /* Index of operation in p->aiIndent[] */
2599 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2600 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2602 const char *azGoto
[] = { "Goto", 0 };
2604 /* Try to figure out if this is really an EXPLAIN statement. If this
2605 ** cannot be verified, return early. */
2606 if( sqlite3_column_count(pSql
)!=8 ){
2610 zSql
= sqlite3_sql(pSql
);
2611 if( zSql
==0 ) return;
2612 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2613 if( sqlite3_strnicmp(z
, "explain", 7) ){
2618 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2620 int iAddr
= sqlite3_column_int(pSql
, 0);
2621 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2623 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2624 ** p2 is an instruction address, set variable p2op to the index of that
2625 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2626 ** the current instruction is part of a sub-program generated by an
2627 ** SQL trigger or foreign key. */
2628 int p2
= sqlite3_column_int(pSql
, 3);
2629 int p2op
= (p2
+ (iOp
-iAddr
));
2631 /* Grow the p->aiIndent array as required */
2634 /* Do further verfication that this is explain output. Abort if
2636 static const char *explainCols
[] = {
2637 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2639 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2640 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2642 sqlite3_reset(pSql
);
2648 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2649 if( p
->aiIndent
==0 ) shell_out_of_memory();
2650 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2651 if( abYield
==0 ) shell_out_of_memory();
2653 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2654 p
->aiIndent
[iOp
] = 0;
2657 if( str_in_array(zOp
, azNext
) ){
2658 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2660 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2661 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2663 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2668 sqlite3_free(abYield
);
2669 sqlite3_reset(pSql
);
2673 ** Free the array allocated by explain_data_prepare().
2675 static void explain_data_delete(ShellState
*p
){
2676 sqlite3_free(p
->aiIndent
);
2683 ** Disable and restore .wheretrace and .selecttrace settings.
2685 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2686 extern int sqlite3SelectTrace
;
2687 static int savedSelectTrace
;
2689 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2690 extern int sqlite3WhereTrace
;
2691 static int savedWhereTrace
;
2693 static void disable_debug_trace_modes(void){
2694 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2695 savedSelectTrace
= sqlite3SelectTrace
;
2696 sqlite3SelectTrace
= 0;
2698 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2699 savedWhereTrace
= sqlite3WhereTrace
;
2700 sqlite3WhereTrace
= 0;
2703 static void restore_debug_trace_modes(void){
2704 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2705 sqlite3SelectTrace
= savedSelectTrace
;
2707 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2708 sqlite3WhereTrace
= savedWhereTrace
;
2713 ** Run a prepared statement
2715 static void exec_prepared_stmt(
2716 ShellState
*pArg
, /* Pointer to ShellState */
2717 sqlite3_stmt
*pStmt
/* Statment to run */
2721 /* perform the first step. this will tell us if we
2722 ** have a result set or not and how wide it is.
2724 rc
= sqlite3_step(pStmt
);
2725 /* if we have a result set... */
2726 if( SQLITE_ROW
== rc
){
2727 /* allocate space for col name ptr, value ptr, and type */
2728 int nCol
= sqlite3_column_count(pStmt
);
2729 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2733 char **azCols
= (char **)pData
; /* Names of result columns */
2734 char **azVals
= &azCols
[nCol
]; /* Results */
2735 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2737 assert(sizeof(int) <= sizeof(char *));
2738 /* save off ptrs to column names */
2739 for(i
=0; i
<nCol
; i
++){
2740 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2743 /* extract the data and data types */
2744 for(i
=0; i
<nCol
; i
++){
2745 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2746 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2749 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2751 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2753 break; /* from for */
2757 /* if data and types extracted successfully... */
2758 if( SQLITE_ROW
== rc
){
2759 /* call the supplied callback with the result row data */
2760 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2763 rc
= sqlite3_step(pStmt
);
2766 } while( SQLITE_ROW
== rc
);
2767 sqlite3_free(pData
);
2772 #ifndef SQLITE_OMIT_VIRTUALTABLE
2774 ** This function is called to process SQL if the previous shell command
2775 ** was ".expert". It passes the SQL in the second argument directly to
2776 ** the sqlite3expert object.
2778 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2779 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2780 ** an English language error message. It is the responsibility of the
2781 ** caller to eventually free this buffer using sqlite3_free().
2783 static int expertHandleSQL(
2788 assert( pState
->expert
.pExpert
);
2789 assert( pzErr
==0 || *pzErr
==0 );
2790 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
2794 ** This function is called either to silently clean up the object
2795 ** created by the ".expert" command (if bCancel==1), or to generate a
2796 ** report from it and then clean it up (if bCancel==0).
2798 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2799 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2800 ** an English language error message. It is the responsibility of the
2801 ** caller to eventually free this buffer using sqlite3_free().
2803 static int expertFinish(
2809 sqlite3expert
*p
= pState
->expert
.pExpert
;
2811 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
2813 FILE *out
= pState
->out
;
2814 int bVerbose
= pState
->expert
.bVerbose
;
2816 rc
= sqlite3_expert_analyze(p
, pzErr
);
2817 if( rc
==SQLITE_OK
){
2818 int nQuery
= sqlite3_expert_count(p
);
2822 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
2823 raw_printf(out
, "-- Candidates -----------------------------\n");
2824 raw_printf(out
, "%s\n", zCand
);
2826 for(i
=0; i
<nQuery
; i
++){
2827 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
2828 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
2829 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
2830 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
2832 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
2833 raw_printf(out
, "%s\n\n", zSql
);
2835 raw_printf(out
, "%s\n", zIdx
);
2836 raw_printf(out
, "%s\n", zEQP
);
2840 sqlite3_expert_destroy(p
);
2841 pState
->expert
.pExpert
= 0;
2846 ** Implementation of ".expert" dot command.
2848 static int expertDotCommand(
2849 ShellState
*pState
, /* Current shell tool state */
2850 char **azArg
, /* Array of arguments passed to dot command */
2851 int nArg
/* Number of entries in azArg[] */
2858 assert( pState
->expert
.pExpert
==0 );
2859 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
2861 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
2864 if( z
[0]=='-' && z
[1]=='-' ) z
++;
2866 if( n
>=2 && 0==strncmp(z
, "-verbose", n
) ){
2867 pState
->expert
.bVerbose
= 1;
2869 else if( n
>=2 && 0==strncmp(z
, "-sample", n
) ){
2871 raw_printf(stderr
, "option requires an argument: %s\n", z
);
2874 iSample
= (int)integerValue(azArg
[++i
]);
2875 if( iSample
<0 || iSample
>100 ){
2876 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
2882 raw_printf(stderr
, "unknown option: %s\n", z
);
2887 if( rc
==SQLITE_OK
){
2888 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
2889 if( pState
->expert
.pExpert
==0 ){
2890 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
);
2893 sqlite3_expert_config(
2894 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
2901 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2904 ** Execute a statement or set of statements. Print
2905 ** any result rows/columns depending on the current mode
2906 ** set via the supplied callback.
2908 ** This is very similar to SQLite's built-in sqlite3_exec()
2909 ** function except it takes a slightly different callback
2910 ** and callback data argument.
2912 static int shell_exec(
2913 ShellState
*pArg
, /* Pointer to ShellState */
2914 const char *zSql
, /* SQL to be evaluated */
2915 char **pzErrMsg
/* Error msg written here */
2917 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2918 int rc
= SQLITE_OK
; /* Return Code */
2920 const char *zLeftover
; /* Tail of unprocessed SQL */
2921 sqlite3
*db
= pArg
->db
;
2927 #ifndef SQLITE_OMIT_VIRTUALTABLE
2928 if( pArg
->expert
.pExpert
){
2929 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
2930 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
2934 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2935 static const char *zStmtSql
;
2936 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2937 if( SQLITE_OK
!= rc
){
2939 *pzErrMsg
= save_err_msg(db
);
2943 /* this happens for a comment or white-space */
2945 while( IsSpace(zSql
[0]) ) zSql
++;
2948 zStmtSql
= sqlite3_sql(pStmt
);
2949 if( zStmtSql
==0 ) zStmtSql
= "";
2950 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2952 /* save off the prepared statment handle and reset row count */
2954 pArg
->pStmt
= pStmt
;
2958 /* echo the sql statement if echo on */
2959 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2960 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2963 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2964 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2965 sqlite3_stmt
*pExplain
;
2968 disable_debug_trace_modes();
2969 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
2970 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
2971 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
2973 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2974 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2975 if( rc
==SQLITE_OK
){
2976 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2977 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
2978 int iEqpId
= sqlite3_column_int(pExplain
, 0);
2979 int iParentId
= sqlite3_column_int(pExplain
, 1);
2980 if( zEQPLine
[0]=='-' ) eqp_render(pArg
);
2981 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
2985 sqlite3_finalize(pExplain
);
2987 if( pArg
->autoEQP
>=AUTOEQP_full
){
2988 /* Also do an EXPLAIN for ".eqp full" mode */
2989 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2990 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2991 if( rc
==SQLITE_OK
){
2992 pArg
->cMode
= MODE_Explain
;
2993 explain_data_prepare(pArg
, pExplain
);
2994 exec_prepared_stmt(pArg
, pExplain
);
2995 explain_data_delete(pArg
);
2997 sqlite3_finalize(pExplain
);
3000 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
3001 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
3002 /* Reprepare pStmt before reactiving trace modes */
3003 sqlite3_finalize(pStmt
);
3004 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
3005 if( pArg
) pArg
->pStmt
= pStmt
;
3007 restore_debug_trace_modes();
3011 pArg
->cMode
= pArg
->mode
;
3012 if( pArg
->autoExplain
){
3013 if( sqlite3_column_count(pStmt
)==8
3014 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
3016 pArg
->cMode
= MODE_Explain
;
3018 if( sqlite3_column_count(pStmt
)==4
3019 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql
,0)==0 ){
3020 pArg
->cMode
= MODE_EQP
;
3024 /* If the shell is currently in ".explain" mode, gather the extra
3025 ** data required to add indents to the output.*/
3026 if( pArg
->cMode
==MODE_Explain
){
3027 explain_data_prepare(pArg
, pStmt
);
3031 exec_prepared_stmt(pArg
, pStmt
);
3032 explain_data_delete(pArg
);
3035 /* print usage stats if stats on */
3036 if( pArg
&& pArg
->statsOn
){
3037 display_stats(db
, pArg
, 0);
3040 /* print loop-counters if required */
3041 if( pArg
&& pArg
->scanstatsOn
){
3042 display_scanstats(db
, pArg
);
3045 /* Finalize the statement just executed. If this fails, save a
3046 ** copy of the error message. Otherwise, set zSql to point to the
3047 ** next statement to execute. */
3048 rc2
= sqlite3_finalize(pStmt
);
3049 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
3050 if( rc
==SQLITE_OK
){
3052 while( IsSpace(zSql
[0]) ) zSql
++;
3053 }else if( pzErrMsg
){
3054 *pzErrMsg
= save_err_msg(db
);
3057 /* clear saved stmt handle */
3068 ** Release memory previously allocated by tableColumnList().
3070 static void freeColumnList(char **azCol
){
3072 for(i
=1; azCol
[i
]; i
++){
3073 sqlite3_free(azCol
[i
]);
3075 /* azCol[0] is a static string */
3076 sqlite3_free(azCol
);
3080 ** Return a list of pointers to strings which are the names of all
3081 ** columns in table zTab. The memory to hold the names is dynamically
3082 ** allocated and must be released by the caller using a subsequent call
3083 ** to freeColumnList().
3085 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3086 ** value that needs to be preserved, then azCol[0] is filled in with the
3087 ** name of the rowid column.
3089 ** The first regular column in the table is azCol[1]. The list is terminated
3090 ** by an entry with azCol[i]==0.
3092 static char **tableColumnList(ShellState
*p
, const char *zTab
){
3094 sqlite3_stmt
*pStmt
;
3098 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
3099 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
3100 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
3103 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
3104 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3107 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3108 if( nCol
>=nAlloc
-2 ){
3109 nAlloc
= nAlloc
*2 + nCol
+ 10;
3110 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
3111 if( azCol
==0 ) shell_out_of_memory();
3113 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
3114 if( sqlite3_column_int(pStmt
, 5) ){
3117 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
3126 sqlite3_finalize(pStmt
);
3127 if( azCol
==0 ) return 0;
3131 /* The decision of whether or not a rowid really needs to be preserved
3132 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3133 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3134 ** rowids on tables where the rowid is inaccessible because there are other
3135 ** columns in the table named "rowid", "_rowid_", and "oid".
3137 if( preserveRowid
&& isIPK
){
3138 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3139 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3140 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3141 ** ROWID aliases. To distinguish these cases, check to see if
3142 ** there is a "pk" entry in "PRAGMA index_list". There will be
3143 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3145 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3146 " WHERE origin='pk'", zTab
);
3147 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3150 freeColumnList(azCol
);
3153 rc
= sqlite3_step(pStmt
);
3154 sqlite3_finalize(pStmt
);
3155 preserveRowid
= rc
==SQLITE_ROW
;
3157 if( preserveRowid
){
3158 /* Only preserve the rowid if we can find a name to use for the
3160 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
3163 for(i
=1; i
<=nCol
; i
++){
3164 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
3167 /* At this point, we know that azRowid[j] is not the name of any
3168 ** ordinary column in the table. Verify that azRowid[j] is a valid
3169 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3170 ** tables will fail this last check */
3171 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
3172 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
3181 ** Toggle the reverse_unordered_selects setting.
3183 static void toggleSelectOrder(sqlite3
*db
){
3184 sqlite3_stmt
*pStmt
= 0;
3187 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
3188 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3189 iSetting
= sqlite3_column_int(pStmt
, 0);
3191 sqlite3_finalize(pStmt
);
3192 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
3193 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
3194 sqlite3_exec(db
, zStmt
, 0, 0, 0);
3198 ** This is a different callback routine used for dumping the database.
3199 ** Each row received by this callback consists of a table name,
3200 ** the table type ("index" or "table") and SQL to create the table.
3201 ** This routine should print text sufficient to recreate the table.
3203 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
3208 ShellState
*p
= (ShellState
*)pArg
;
3210 UNUSED_PARAMETER(azNotUsed
);
3211 if( nArg
!=3 || azArg
==0 ) return 0;
3216 if( strcmp(zTable
, "sqlite_sequence")==0 ){
3217 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
3218 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
3219 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
3220 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
3222 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
3224 if( !p
->writableSchema
){
3225 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
3226 p
->writableSchema
= 1;
3228 zIns
= sqlite3_mprintf(
3229 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3230 "VALUES('table','%q','%q',0,'%q');",
3231 zTable
, zTable
, zSql
);
3232 utf8_printf(p
->out
, "%s\n", zIns
);
3236 printSchemaLine(p
->out
, zSql
, ";\n");
3239 if( strcmp(zType
, "table")==0 ){
3244 char *savedDestTable
;
3247 azCol
= tableColumnList(p
, zTable
);
3253 /* Always quote the table name, even if it appears to be pure ascii,
3254 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3256 appendText(&sTable
, zTable
, quoteChar(zTable
));
3257 /* If preserving the rowid, add a column list after the table name.
3258 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3259 ** instead of the usual "INSERT INTO tab VALUES(...)".
3262 appendText(&sTable
, "(", 0);
3263 appendText(&sTable
, azCol
[0], 0);
3264 for(i
=1; azCol
[i
]; i
++){
3265 appendText(&sTable
, ",", 0);
3266 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
3268 appendText(&sTable
, ")", 0);
3271 /* Build an appropriate SELECT statement */
3273 appendText(&sSelect
, "SELECT ", 0);
3275 appendText(&sSelect
, azCol
[0], 0);
3276 appendText(&sSelect
, ",", 0);
3278 for(i
=1; azCol
[i
]; i
++){
3279 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
3281 appendText(&sSelect
, ",", 0);
3284 freeColumnList(azCol
);
3285 appendText(&sSelect
, " FROM ", 0);
3286 appendText(&sSelect
, zTable
, quoteChar(zTable
));
3288 savedDestTable
= p
->zDestTable
;
3289 savedMode
= p
->mode
;
3290 p
->zDestTable
= sTable
.z
;
3291 p
->mode
= p
->cMode
= MODE_Insert
;
3292 rc
= shell_exec(p
, sSelect
.z
, 0);
3293 if( (rc
&0xff)==SQLITE_CORRUPT
){
3294 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3295 toggleSelectOrder(p
->db
);
3296 shell_exec(p
, sSelect
.z
, 0);
3297 toggleSelectOrder(p
->db
);
3299 p
->zDestTable
= savedDestTable
;
3300 p
->mode
= savedMode
;
3309 ** Run zQuery. Use dump_callback() as the callback routine so that
3310 ** the contents of the query are output as SQL statements.
3312 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3313 ** "ORDER BY rowid DESC" to the end.
3315 static int run_schema_dump_query(
3321 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
3322 if( rc
==SQLITE_CORRUPT
){
3324 int len
= strlen30(zQuery
);
3325 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3327 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
3331 zQ2
= malloc( len
+100 );
3332 if( zQ2
==0 ) return rc
;
3333 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
3334 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
3336 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
3338 rc
= SQLITE_CORRUPT
;
3347 ** Text of a help message
3349 static char zHelp
[] =
3350 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3351 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3353 #ifndef SQLITE_OMIT_AUTHORIZATION
3354 ".auth ON|OFF Show authorizer callbacks\n"
3356 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3357 " Add \"--append\" to open using appendvfs.\n"
3358 ".bail on|off Stop after hitting an error. Default OFF\n"
3359 ".binary on|off Turn binary output on or off. Default OFF\n"
3360 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3361 ".changes on|off Show number of rows changed by SQL\n"
3362 ".check GLOB Fail if output since .testcase does not match\n"
3363 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3364 ".databases List names and files of attached databases\n"
3365 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options\n"
3366 ".dbinfo ?DB? Show status information about the database\n"
3367 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3368 " If TABLE specified, only dump tables matching\n"
3369 " LIKE pattern TABLE.\n"
3370 ".echo on|off Turn command echo on or off\n"
3371 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3372 ".excel Display the output of next command in a spreadsheet\n"
3373 ".exit Exit this program\n"
3374 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
3375 /* Because explain mode comes on automatically now, the ".explain" mode
3376 ** is removed from the help screen. It is still supported for legacy, however */
3377 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3378 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3379 ".headers on|off Turn display of headers on or off\n"
3380 ".help Show this message\n"
3381 ".import FILE TABLE Import data from FILE into TABLE\n"
3382 #ifndef SQLITE_OMIT_TEST_CONTROL
3383 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3385 ".indexes ?TABLE? Show names of all indexes\n"
3386 " If TABLE specified, only show indexes for tables\n"
3387 " matching LIKE pattern TABLE.\n"
3388 #ifdef SQLITE_ENABLE_IOTRACE
3389 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3391 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3392 ".lint OPTIONS Report potential schema issues. Options:\n"
3393 " fkey-indexes Find missing foreign key indexes\n"
3394 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3395 ".load FILE ?ENTRY? Load an extension library\n"
3397 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3398 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3399 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3400 " csv Comma-separated values\n"
3401 " column Left-aligned columns. (See .width)\n"
3402 " html HTML <table> code\n"
3403 " insert SQL insert statements for TABLE\n"
3404 " line One value per line\n"
3405 " list Values delimited by \"|\"\n"
3406 " quote Escape answers as for SQL\n"
3407 " tabs Tab-separated values\n"
3408 " tcl TCL list elements\n"
3409 ".nullvalue STRING Use STRING in place of NULL values\n"
3410 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
3411 " or invoke system text editor (-e) or spreadsheet (-x)\n"
3413 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3414 " The --new option starts with an empty file\n"
3415 " Other options: --readonly --append --zip\n"
3416 ".output ?FILE? Send output to FILE or stdout\n"
3417 ".print STRING... Print literal STRING\n"
3418 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3419 ".quit Exit this program\n"
3420 ".read FILENAME Execute SQL in FILENAME\n"
3421 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3422 ".save FILE Write in-memory database into FILE\n"
3423 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3424 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3425 " Add --indent for pretty-printing\n"
3426 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3427 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3428 " separator for both the output mode and .import\n"
3429 #if defined(SQLITE_ENABLE_SESSION)
3430 ".session CMD ... Create or control sessions\n"
3432 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3433 #ifndef SQLITE_NOHAVE_SYSTEM
3434 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3436 ".show Show the current values for various settings\n"
3437 ".stats ?on|off? Show stats or turn stats on or off\n"
3438 #ifndef SQLITE_NOHAVE_SYSTEM
3439 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3441 ".tables ?TABLE? List names of tables\n"
3442 " If TABLE specified, only list tables matching\n"
3443 " LIKE pattern TABLE.\n"
3444 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3445 ".timeout MS Try opening locked tables for MS milliseconds\n"
3446 ".timer on|off Turn SQL timer on or off\n"
3447 ".trace FILE|off Output each SQL statement as it is run\n"
3448 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3449 ".vfslist List all available VFSes\n"
3450 ".vfsname ?AUX? Print the name of the VFS stack\n"
3451 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3452 " Negative values right-justify\n"
3455 #if defined(SQLITE_ENABLE_SESSION)
3457 ** Print help information for the ".sessions" command
3459 void session_help(ShellState
*p
){
3461 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3462 "If ?NAME? is omitted, the first defined session is used.\n"
3464 " attach TABLE Attach TABLE\n"
3465 " changeset FILE Write a changeset into FILE\n"
3466 " close Close one session\n"
3467 " enable ?BOOLEAN? Set or query the enable bit\n"
3468 " filter GLOB... Reject tables matching GLOBs\n"
3469 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3470 " isempty Query whether the session is empty\n"
3471 " list List currently open session names\n"
3472 " open DB NAME Open a new session on DB\n"
3473 " patchset FILE Write a patchset into FILE\n"
3479 /* Forward reference */
3480 static int process_input(ShellState
*p
, FILE *in
);
3483 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3484 ** and return a pointer to the buffer. The caller is responsible for freeing
3487 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3490 ** For convenience, a nul-terminator byte is always appended to the data read
3491 ** from the file before the buffer is returned. This byte is not included in
3492 ** the final value of (*pnByte), if applicable.
3494 ** NULL is returned if any error is encountered. The final value of *pnByte
3495 ** is undefined in this case.
3497 static char *readFile(const char *zName
, int *pnByte
){
3498 FILE *in
= fopen(zName
, "rb");
3502 if( in
==0 ) return 0;
3503 fseek(in
, 0, SEEK_END
);
3506 pBuf
= sqlite3_malloc64( nIn
+1 );
3507 if( pBuf
==0 ) return 0;
3508 nRead
= fread(pBuf
, nIn
, 1, in
);
3515 if( pnByte
) *pnByte
= nIn
;
3519 #if defined(SQLITE_ENABLE_SESSION)
3521 ** Close a single OpenSession object and release all of its associated
3524 static void session_close(OpenSession
*pSession
){
3526 sqlite3session_delete(pSession
->p
);
3527 sqlite3_free(pSession
->zName
);
3528 for(i
=0; i
<pSession
->nFilter
; i
++){
3529 sqlite3_free(pSession
->azFilter
[i
]);
3531 sqlite3_free(pSession
->azFilter
);
3532 memset(pSession
, 0, sizeof(OpenSession
));
3537 ** Close all OpenSession objects and release all associated resources.
3539 #if defined(SQLITE_ENABLE_SESSION)
3540 static void session_close_all(ShellState
*p
){
3542 for(i
=0; i
<p
->nSession
; i
++){
3543 session_close(&p
->aSession
[i
]);
3548 # define session_close_all(X)
3552 ** Implementation of the xFilter function for an open session. Omit
3553 ** any tables named by ".session filter" but let all other table through.
3555 #if defined(SQLITE_ENABLE_SESSION)
3556 static int session_filter(void *pCtx
, const char *zTab
){
3557 OpenSession
*pSession
= (OpenSession
*)pCtx
;
3559 for(i
=0; i
<pSession
->nFilter
; i
++){
3560 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
3567 ** Try to deduce the type of file for zName based on its content. Return
3568 ** one of the SHELL_OPEN_* constants.
3570 ** If the file does not exist or is empty but its name looks like a ZIP
3571 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3572 ** Otherwise, assume an ordinary database regardless of the filename if
3573 ** the type cannot be determined from content.
3575 int deduceDatabaseType(const char *zName
, int dfltZip
){
3576 FILE *f
= fopen(zName
, "rb");
3578 int rc
= SHELL_OPEN_UNSPEC
;
3581 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
3582 return SHELL_OPEN_ZIPFILE
;
3584 return SHELL_OPEN_NORMAL
;
3587 fseek(f
, -25, SEEK_END
);
3588 n
= fread(zBuf
, 25, 1, f
);
3589 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
3590 rc
= SHELL_OPEN_APPENDVFS
;
3592 fseek(f
, -22, SEEK_END
);
3593 n
= fread(zBuf
, 22, 1, f
);
3594 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
3596 rc
= SHELL_OPEN_ZIPFILE
;
3597 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
3598 rc
= SHELL_OPEN_ZIPFILE
;
3605 /* Flags for open_db().
3607 ** The default behavior of open_db() is to exit(1) if the database fails to
3608 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3609 ** but still returns without calling exit.
3611 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3612 ** ZIP archive if the file does not exist or is empty and its name matches
3613 ** the *.zip pattern.
3615 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3616 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3619 ** Make sure the database is open. If it is not, then open it. If
3620 ** the database fails to open, print an error message and exit.
3622 static void open_db(ShellState
*p
, int openFlags
){
3624 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
3625 if( p
->zDbFilename
==0 || p
->zDbFilename
[0]==0 ){
3626 p
->openMode
= SHELL_OPEN_NORMAL
;
3628 p
->openMode
= (u8
)deduceDatabaseType(p
->zDbFilename
,
3629 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
3632 switch( p
->openMode
){
3633 case SHELL_OPEN_APPENDVFS
: {
3634 sqlite3_open_v2(p
->zDbFilename
, &p
->db
,
3635 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, "apndvfs");
3638 case SHELL_OPEN_ZIPFILE
: {
3639 sqlite3_open(":memory:", &p
->db
);
3642 case SHELL_OPEN_READONLY
: {
3643 sqlite3_open_v2(p
->zDbFilename
, &p
->db
, SQLITE_OPEN_READONLY
, 0);
3646 case SHELL_OPEN_UNSPEC
:
3647 case SHELL_OPEN_NORMAL
: {
3648 sqlite3_open(p
->zDbFilename
, &p
->db
);
3653 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3654 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
3655 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
3656 if( openFlags
& OPEN_DB_KEEPALIVE
) return;
3659 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3660 sqlite3_enable_load_extension(p
->db
, 1);
3662 sqlite3_fileio_init(p
->db
, 0, 0);
3663 sqlite3_shathree_init(p
->db
, 0, 0);
3664 sqlite3_completion_init(p
->db
, 0, 0);
3665 #ifdef SQLITE_HAVE_ZLIB
3666 sqlite3_zipfile_init(p
->db
, 0, 0);
3667 sqlite3_sqlar_init(p
->db
, 0, 0);
3669 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
3670 shellAddSchemaName
, 0, 0);
3671 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
3672 shellModuleSchema
, 0, 0);
3673 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
3674 shellPutsFunc
, 0, 0);
3675 #ifndef SQLITE_NOHAVE_SYSTEM
3676 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
3678 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
3681 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
3682 char *zSql
= sqlite3_mprintf(
3683 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p
->zDbFilename
);
3684 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
3691 ** Attempt to close the databaes connection. Report errors.
3693 void close_db(sqlite3
*db
){
3694 int rc
= sqlite3_close(db
);
3696 utf8_printf(stderr
, "Error: sqlite3_close() returns %d: %s\n",
3697 rc
, sqlite3_errmsg(db
));
3701 #if HAVE_READLINE || HAVE_EDITLINE
3703 ** Readline completion callbacks
3705 static char *readline_completion_generator(const char *text
, int state
){
3706 static sqlite3_stmt
*pStmt
= 0;
3710 sqlite3_finalize(pStmt
);
3711 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3712 " FROM completion(%Q) ORDER BY 1", text
);
3713 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3716 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3717 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
3719 sqlite3_finalize(pStmt
);
3725 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
3726 rl_attempted_completion_over
= 1;
3727 return rl_completion_matches(zText
, readline_completion_generator
);
3730 #elif HAVE_LINENOISE
3732 ** Linenoise completion callback
3734 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
3735 int nLine
= strlen30(zLine
);
3737 sqlite3_stmt
*pStmt
= 0;
3741 if( nLine
>sizeof(zBuf
)-30 ) return;
3742 if( zLine
[0]=='.' || zLine
[0]=='#') return;
3743 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
3744 if( i
==nLine
-1 ) return;
3746 memcpy(zBuf
, zLine
, iStart
);
3747 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3748 " FROM completion(%Q,%Q) ORDER BY 1",
3749 &zLine
[iStart
], zLine
);
3750 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3752 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3753 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3754 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
3755 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
3756 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
3757 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
3758 linenoiseAddCompletion(lc
, zBuf
);
3761 sqlite3_finalize(pStmt
);
3766 ** Do C-language style dequoting.
3772 ** \v -> vertical tab
3774 ** \r -> carriage return
3779 ** \NNN -> ascii character NNN in octal
3781 static void resolve_backslashes(char *z
){
3784 while( *z
&& *z
!='\\' ) z
++;
3785 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
3786 if( c
=='\\' && z
[i
+1]!=0 ){
3804 }else if( c
=='\'' ){
3806 }else if( c
=='\\' ){
3808 }else if( c
>='0' && c
<='7' ){
3810 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3812 c
= (c
<<3) + z
[i
] - '0';
3813 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3815 c
= (c
<<3) + z
[i
] - '0';
3826 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3827 ** for TRUE and FALSE. Return the integer value if appropriate.
3829 static int booleanValue(const char *zArg
){
3831 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3832 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3834 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3836 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3837 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3840 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3843 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3849 ** Set or clear a shell flag according to a boolean value.
3851 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3852 if( booleanValue(zArg
) ){
3853 ShellSetFlag(p
, mFlag
);
3855 ShellClearFlag(p
, mFlag
);
3860 ** Close an output file, assuming it is not stderr or stdout
3862 static void output_file_close(FILE *f
){
3863 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3867 ** Try to open an output file. The names "stdout" and "stderr" are
3868 ** recognized and do the right thing. NULL is returned if the output
3869 ** filename is "off".
3871 static FILE *output_file_open(const char *zFile
, int bTextMode
){
3873 if( strcmp(zFile
,"stdout")==0 ){
3875 }else if( strcmp(zFile
, "stderr")==0 ){
3877 }else if( strcmp(zFile
, "off")==0 ){
3880 f
= fopen(zFile
, bTextMode
? "w" : "wb");
3882 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3888 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3890 ** A routine for handling output from sqlite3_trace().
3892 static int sql_trace_callback(
3898 FILE *f
= (FILE*)pArg
;
3899 UNUSED_PARAMETER(mType
);
3900 UNUSED_PARAMETER(pP
);
3902 const char *z
= (const char*)pX
;
3903 int i
= strlen30(z
);
3904 while( i
>0 && z
[i
-1]==';' ){ i
--; }
3905 utf8_printf(f
, "%.*s;\n", i
, z
);
3912 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3913 ** a useful spot to set a debugger breakpoint.
3915 static void test_breakpoint(void){
3916 static int nCall
= 0;
3921 ** An object used to read a CSV and other files for import.
3923 typedef struct ImportCtx ImportCtx
;
3925 const char *zFile
; /* Name of the input file */
3926 FILE *in
; /* Read the CSV text from this input stream */
3927 char *z
; /* Accumulated text for a field */
3928 int n
; /* Number of bytes in z */
3929 int nAlloc
; /* Space allocated for z[] */
3930 int nLine
; /* Current line number */
3931 int bNotFirst
; /* True if one or more bytes already read */
3932 int cTerm
; /* Character that terminated the most recent field */
3933 int cColSep
; /* The column separator character. (Usually ",") */
3934 int cRowSep
; /* The row separator character. (Usually "\n") */
3937 /* Append a single byte to z[] */
3938 static void import_append_char(ImportCtx
*p
, int c
){
3939 if( p
->n
+1>=p
->nAlloc
){
3940 p
->nAlloc
+= p
->nAlloc
+ 100;
3941 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
3942 if( p
->z
==0 ) shell_out_of_memory();
3944 p
->z
[p
->n
++] = (char)c
;
3947 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3948 ** with the option of having a separator other than ",".
3950 ** + Input comes from p->in.
3951 ** + Store results in p->z of length p->n. Space to hold p->z comes
3952 ** from sqlite3_malloc64().
3953 ** + Use p->cSep as the column separator. The default is ",".
3954 ** + Use p->rSep as the row separator. The default is "\n".
3955 ** + Keep track of the line number in p->nLine.
3956 ** + Store the character that terminates the field in p->cTerm. Store
3957 ** EOF on end-of-file.
3958 ** + Report syntax errors on stderr
3960 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
3962 int cSep
= p
->cColSep
;
3963 int rSep
= p
->cRowSep
;
3966 if( c
==EOF
|| seenInterrupt
){
3972 int startLine
= p
->nLine
;
3977 if( c
==rSep
) p
->nLine
++;
3984 if( (c
==cSep
&& pc
==cQuote
)
3985 || (c
==rSep
&& pc
==cQuote
)
3986 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
3987 || (c
==EOF
&& pc
==cQuote
)
3989 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
3993 if( pc
==cQuote
&& c
!='\r' ){
3994 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
3995 p
->zFile
, p
->nLine
, cQuote
);
3998 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
3999 p
->zFile
, startLine
, cQuote
);
4003 import_append_char(p
, c
);
4008 /* If this is the first field being parsed and it begins with the
4009 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4010 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
4011 import_append_char(p
, c
);
4013 if( (c
&0xff)==0xbb ){
4014 import_append_char(p
, c
);
4016 if( (c
&0xff)==0xbf ){
4019 return csv_read_one_field(p
);
4023 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
4024 import_append_char(p
, c
);
4029 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
4033 if( p
->z
) p
->z
[p
->n
] = 0;
4038 /* Read a single field of ASCII delimited text.
4040 ** + Input comes from p->in.
4041 ** + Store results in p->z of length p->n. Space to hold p->z comes
4042 ** from sqlite3_malloc64().
4043 ** + Use p->cSep as the column separator. The default is "\x1F".
4044 ** + Use p->rSep as the row separator. The default is "\x1E".
4045 ** + Keep track of the row number in p->nLine.
4046 ** + Store the character that terminates the field in p->cTerm. Store
4047 ** EOF on end-of-file.
4048 ** + Report syntax errors on stderr
4050 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
4052 int cSep
= p
->cColSep
;
4053 int rSep
= p
->cRowSep
;
4056 if( c
==EOF
|| seenInterrupt
){
4060 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
4061 import_append_char(p
, c
);
4068 if( p
->z
) p
->z
[p
->n
] = 0;
4073 ** Try to transfer data for table zTable. If an error is seen while
4074 ** moving forward, try to go backwards. The backwards movement won't
4075 ** work for WITHOUT ROWID tables.
4077 static void tryToCloneData(
4082 sqlite3_stmt
*pQuery
= 0;
4083 sqlite3_stmt
*pInsert
= 0;
4088 int nTable
= strlen30(zTable
);
4091 const int spinRate
= 10000;
4093 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
4094 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4096 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
4097 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4101 n
= sqlite3_column_count(pQuery
);
4102 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
4103 if( zInsert
==0 ) shell_out_of_memory();
4104 sqlite3_snprintf(200+nTable
,zInsert
,
4105 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
4106 i
= strlen30(zInsert
);
4108 memcpy(zInsert
+i
, ",?", 2);
4111 memcpy(zInsert
+i
, ");", 3);
4112 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
4114 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
4115 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
4120 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4122 switch( sqlite3_column_type(pQuery
, i
) ){
4124 sqlite3_bind_null(pInsert
, i
+1);
4127 case SQLITE_INTEGER
: {
4128 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
4131 case SQLITE_FLOAT
: {
4132 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
4136 sqlite3_bind_text(pInsert
, i
+1,
4137 (const char*)sqlite3_column_text(pQuery
,i
),
4142 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
4143 sqlite3_column_bytes(pQuery
,i
),
4149 rc
= sqlite3_step(pInsert
);
4150 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
4151 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
4152 sqlite3_errmsg(newDb
));
4154 sqlite3_reset(pInsert
);
4156 if( (cnt
%spinRate
)==0 ){
4157 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
4161 if( rc
==SQLITE_DONE
) break;
4162 sqlite3_finalize(pQuery
);
4163 sqlite3_free(zQuery
);
4164 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4166 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4168 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
4171 } /* End for(k=0...) */
4174 sqlite3_finalize(pQuery
);
4175 sqlite3_finalize(pInsert
);
4176 sqlite3_free(zQuery
);
4177 sqlite3_free(zInsert
);
4182 ** Try to transfer all rows of the schema that match zWhere. For
4183 ** each row, invoke xForEach() on the object defined by that row.
4184 ** If an error is encountered while moving forward through the
4185 ** sqlite_master table, try again moving backwards.
4187 static void tryToCloneSchema(
4191 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
4193 sqlite3_stmt
*pQuery
= 0;
4196 const unsigned char *zName
;
4197 const unsigned char *zSql
;
4200 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4201 " WHERE %s", zWhere
);
4202 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4204 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4205 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4207 goto end_schema_xfer
;
4209 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4210 zName
= sqlite3_column_text(pQuery
, 0);
4211 zSql
= sqlite3_column_text(pQuery
, 1);
4212 printf("%s... ", zName
); fflush(stdout
);
4213 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4215 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4216 sqlite3_free(zErrMsg
);
4220 xForEach(p
, newDb
, (const char*)zName
);
4224 if( rc
!=SQLITE_DONE
){
4225 sqlite3_finalize(pQuery
);
4226 sqlite3_free(zQuery
);
4227 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4228 " WHERE %s ORDER BY rowid DESC", zWhere
);
4229 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4231 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4232 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4234 goto end_schema_xfer
;
4236 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4237 zName
= sqlite3_column_text(pQuery
, 0);
4238 zSql
= sqlite3_column_text(pQuery
, 1);
4239 printf("%s... ", zName
); fflush(stdout
);
4240 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4242 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4243 sqlite3_free(zErrMsg
);
4247 xForEach(p
, newDb
, (const char*)zName
);
4253 sqlite3_finalize(pQuery
);
4254 sqlite3_free(zQuery
);
4258 ** Open a new database file named "zNewDb". Try to recover as much information
4259 ** as possible out of the main database (which might be corrupt) and write it
4262 static void tryToClone(ShellState
*p
, const char *zNewDb
){
4265 if( access(zNewDb
,0)==0 ){
4266 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
4269 rc
= sqlite3_open(zNewDb
, &newDb
);
4271 utf8_printf(stderr
, "Cannot create output database: %s\n",
4272 sqlite3_errmsg(newDb
));
4274 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
4275 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
4276 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
4277 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
4278 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
4279 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4285 ** Change the output file back to stdout.
4287 ** If the p->doXdgOpen flag is set, that means the output was being
4288 ** redirected to a temporary file named by p->zTempFile. In that case,
4289 ** launch start/open/xdg-open on that temporary file.
4291 static void output_reset(ShellState
*p
){
4292 if( p
->outfile
[0]=='|' ){
4293 #ifndef SQLITE_OMIT_POPEN
4297 output_file_close(p
->out
);
4298 #ifndef SQLITE_NOHAVE_SYSTEM
4300 const char *zXdgOpenCmd
=
4303 #elif defined(__APPLE__)
4309 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
4311 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
4317 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4324 ** Run an SQL command and return the single integer result.
4326 static int db_int(ShellState
*p
, const char *zSql
){
4327 sqlite3_stmt
*pStmt
;
4329 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4330 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
4331 res
= sqlite3_column_int(pStmt
,0);
4333 sqlite3_finalize(pStmt
);
4338 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
4340 static unsigned int get2byteInt(unsigned char *a
){
4341 return (a
[0]<<8) + a
[1];
4343 static unsigned int get4byteInt(unsigned char *a
){
4344 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
4348 ** Implementation of the ".info" command.
4350 ** Return 1 on error, 2 to exit, and 0 otherwise.
4352 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
4353 static const struct { const char *zName
; int ofst
; } aField
[] = {
4354 { "file change counter:", 24 },
4355 { "database page count:", 28 },
4356 { "freelist page count:", 36 },
4357 { "schema cookie:", 40 },
4358 { "schema format:", 44 },
4359 { "default cache size:", 48 },
4360 { "autovacuum top root:", 52 },
4361 { "incremental vacuum:", 64 },
4362 { "text encoding:", 56 },
4363 { "user version:", 60 },
4364 { "application id:", 68 },
4365 { "software version:", 96 },
4367 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
4368 { "number of tables:",
4369 "SELECT count(*) FROM %s WHERE type='table'" },
4370 { "number of indexes:",
4371 "SELECT count(*) FROM %s WHERE type='index'" },
4372 { "number of triggers:",
4373 "SELECT count(*) FROM %s WHERE type='trigger'" },
4374 { "number of views:",
4375 "SELECT count(*) FROM %s WHERE type='view'" },
4377 "SELECT total(length(sql)) FROM %s" },
4380 unsigned iDataVersion
;
4382 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
4383 sqlite3_stmt
*pStmt
= 0;
4384 unsigned char aHdr
[100];
4386 if( p
->db
==0 ) return 1;
4387 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4389 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
4390 if( sqlite3_step(pStmt
)==SQLITE_ROW
4391 && sqlite3_column_bytes(pStmt
,0)>100
4393 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
4394 sqlite3_finalize(pStmt
);
4396 raw_printf(stderr
, "unable to read database header\n");
4397 sqlite3_finalize(pStmt
);
4400 i
= get2byteInt(aHdr
+16);
4401 if( i
==1 ) i
= 65536;
4402 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
4403 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
4404 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
4405 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
4406 for(i
=0; i
<ArraySize(aField
); i
++){
4407 int ofst
= aField
[i
].ofst
;
4408 unsigned int val
= get4byteInt(aHdr
+ ofst
);
4409 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
4412 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
4413 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
4414 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
4417 raw_printf(p
->out
, "\n");
4420 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
4421 }else if( strcmp(zDb
,"temp")==0 ){
4422 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
4424 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
4426 for(i
=0; i
<ArraySize(aQuery
); i
++){
4427 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
4428 int val
= db_int(p
, zSql
);
4430 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
4432 sqlite3_free(zSchemaTab
);
4433 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_DATA_VERSION
, &iDataVersion
);
4434 utf8_printf(p
->out
, "%-20s %u\n", "data version", iDataVersion
);
4439 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4441 static int shellDatabaseError(sqlite3
*db
){
4442 const char *zErr
= sqlite3_errmsg(db
);
4443 utf8_printf(stderr
, "Error: %s\n", zErr
);
4448 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4449 ** if they match and FALSE (0) if they do not match.
4453 ** '*' Matches any sequence of zero or more characters.
4455 ** '?' Matches exactly one character.
4457 ** [...] Matches one character from the enclosed list of
4460 ** [^...] Matches one character not in the enclosed list.
4462 ** '#' Matches any sequence of one or more digits with an
4463 ** optional + or - sign in front
4465 ** ' ' Any span of whitespace matches any other span of
4468 ** Extra whitespace at the end of z[] is ignored.
4470 static int testcase_glob(const char *zGlob
, const char *z
){
4475 while( (c
= (*(zGlob
++)))!=0 ){
4477 if( !IsSpace(*z
) ) return 0;
4478 while( IsSpace(*zGlob
) ) zGlob
++;
4479 while( IsSpace(*z
) ) z
++;
4481 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
4482 if( c
=='?' && (*(z
++))==0 ) return 0;
4487 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
4492 while( (c2
= (*(z
++)))!=0 ){
4495 if( c2
==0 ) return 0;
4497 if( testcase_glob(zGlob
,z
) ) return 1;
4501 if( (*(z
++))==0 ) return 0;
4507 if( c
==0 ) return 0;
4514 if( c
==']' ) seen
= 1;
4517 while( c2
&& c2
!=']' ){
4518 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
4520 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
4530 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
4532 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
4533 if( !IsDigit(z
[0]) ) return 0;
4535 while( IsDigit(z
[0]) ){ z
++; }
4537 if( c
!=(*(z
++)) ) return 0;
4540 while( IsSpace(*z
) ){ z
++; }
4546 ** Compare the string as a command-line option with either one or two
4547 ** initial "-" characters.
4549 static int optionMatch(const char *zStr
, const char *zOpt
){
4550 if( zStr
[0]!='-' ) return 0;
4552 if( zStr
[0]=='-' ) zStr
++;
4553 return strcmp(zStr
, zOpt
)==0;
4559 int shellDeleteFile(const char *zFilename
){
4562 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
4566 rc
= unlink(zFilename
);
4572 ** Try to delete the temporary file (if there is one) and free the
4573 ** memory used to hold the name of the temp file.
4575 static void clearTempFile(ShellState
*p
){
4576 if( p
->zTempFile
==0 ) return;
4577 if( p
->doXdgOpen
) return;
4578 if( shellDeleteFile(p
->zTempFile
) ) return;
4579 sqlite3_free(p
->zTempFile
);
4584 ** Create a new temp file name with the given suffix.
4586 static void newTempFile(ShellState
*p
, const char *zSuffix
){
4588 sqlite3_free(p
->zTempFile
);
4591 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
4593 if( p
->zTempFile
==0 ){
4595 sqlite3_randomness(sizeof(r
), &r
);
4596 p
->zTempFile
= sqlite3_mprintf("temp%llx.%s", r
, zSuffix
);
4598 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
4600 if( p
->zTempFile
==0 ){
4601 raw_printf(stderr
, "out of memory\n");
4608 ** The implementation of SQL scalar function fkey_collate_clause(), used
4609 ** by the ".lint fkey-indexes" command. This scalar function is always
4610 ** called with four arguments - the parent table name, the parent column name,
4611 ** the child table name and the child column name.
4613 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4615 ** If either of the named tables or columns do not exist, this function
4616 ** returns an empty string. An empty string is also returned if both tables
4617 ** and columns exist but have the same default collation sequence. Or,
4618 ** if both exist but the default collation sequences are different, this
4619 ** function returns the string " COLLATE <parent-collation>", where
4620 ** <parent-collation> is the default collation sequence of the parent column.
4622 static void shellFkeyCollateClause(
4623 sqlite3_context
*pCtx
,
4625 sqlite3_value
**apVal
4627 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
4628 const char *zParent
;
4629 const char *zParentCol
;
4630 const char *zParentSeq
;
4632 const char *zChildCol
;
4633 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
4637 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
4638 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
4639 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
4640 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
4642 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
4643 rc
= sqlite3_table_column_metadata(
4644 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
4646 if( rc
==SQLITE_OK
){
4647 rc
= sqlite3_table_column_metadata(
4648 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
4652 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
4653 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
4654 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
4661 ** The implementation of dot-command ".lint fkey-indexes".
4663 static int lintFkeyIndexes(
4664 ShellState
*pState
, /* Current shell tool state */
4665 char **azArg
, /* Array of arguments passed to dot command */
4666 int nArg
/* Number of entries in azArg[] */
4668 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
4669 FILE *out
= pState
->out
; /* Stream to write non-error output to */
4670 int bVerbose
= 0; /* If -verbose is present */
4671 int bGroupByParent
= 0; /* If -groupbyparent is present */
4672 int i
; /* To iterate through azArg[] */
4673 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
4674 int rc
; /* Return code */
4675 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
4678 ** This SELECT statement returns one row for each foreign key constraint
4679 ** in the schema of the main database. The column values are:
4681 ** 0. The text of an SQL statement similar to:
4683 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4685 ** This SELECT is similar to the one that the foreign keys implementation
4686 ** needs to run internally on child tables. If there is an index that can
4687 ** be used to optimize this query, then it can also be used by the FK
4688 ** implementation to optimize DELETE or UPDATE statements on the parent
4691 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4692 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4693 ** contains an index that can be used to optimize the query.
4695 ** 2. Human readable text that describes the child table and columns. e.g.
4697 ** "child_table(child_key1, child_key2)"
4699 ** 3. Human readable text that describes the parent table and columns. e.g.
4701 ** "parent_table(parent_key1, parent_key2)"
4703 ** 4. A full CREATE INDEX statement for an index that could be used to
4704 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4706 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4708 ** 5. The name of the parent table.
4710 ** These six values are used by the C logic below to generate the report.
4714 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4715 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4716 " || fkey_collate_clause("
4717 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4719 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4720 " || group_concat('*=?', ' AND ') || ')'"
4722 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4724 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4726 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4727 " || ' ON ' || quote(s.name) || '('"
4728 " || group_concat(quote(f.[from]) ||"
4729 " fkey_collate_clause("
4730 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4734 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4735 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4736 "GROUP BY s.name, f.id "
4737 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4739 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4741 for(i
=2; i
<nArg
; i
++){
4742 int n
= strlen30(azArg
[i
]);
4743 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
4746 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
4751 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4754 return SQLITE_ERROR
;
4758 /* Register the fkey_collate_clause() SQL function */
4759 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
4760 0, shellFkeyCollateClause
, 0, 0
4764 if( rc
==SQLITE_OK
){
4765 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
4767 if( rc
==SQLITE_OK
){
4768 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
4771 if( rc
==SQLITE_OK
){
4774 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
4776 sqlite3_stmt
*pExplain
= 0;
4777 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
4778 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
4779 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
4780 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
4781 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4782 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4784 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4785 if( rc
!=SQLITE_OK
) break;
4786 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4787 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4789 0==sqlite3_strglob(zGlob
, zPlan
)
4790 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4793 rc
= sqlite3_finalize(pExplain
);
4794 if( rc
!=SQLITE_OK
) break;
4797 raw_printf(stderr
, "Error: internal error");
4801 && (bVerbose
|| res
==0)
4802 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4804 raw_printf(out
, "-- Parent table %s\n", zParent
);
4805 sqlite3_free(zPrev
);
4806 zPrev
= sqlite3_mprintf("%s", zParent
);
4810 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4811 }else if( bVerbose
){
4812 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4813 zIndent
, zFrom
, zTarget
4818 sqlite3_free(zPrev
);
4820 if( rc
!=SQLITE_OK
){
4821 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4824 rc2
= sqlite3_finalize(pSql
);
4825 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4827 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4830 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4837 ** Implementation of ".lint" dot command.
4839 static int lintDotCommand(
4840 ShellState
*pState
, /* Current shell tool state */
4841 char **azArg
, /* Array of arguments passed to dot command */
4842 int nArg
/* Number of entries in azArg[] */
4845 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
4846 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4847 return lintFkeyIndexes(pState
, azArg
, nArg
);
4850 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4851 raw_printf(stderr
, "Where sub-commands are:\n");
4852 raw_printf(stderr
, " fkey-indexes\n");
4853 return SQLITE_ERROR
;
4856 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4857 /*********************************************************************************
4858 ** The ".archive" or ".ar" command.
4860 static void shellPrepare(
4864 sqlite3_stmt
**ppStmt
4867 if( *pRc
==SQLITE_OK
){
4868 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
4869 if( rc
!=SQLITE_OK
){
4870 raw_printf(stderr
, "sql error: %s (%d)\n",
4871 sqlite3_errmsg(db
), sqlite3_errcode(db
)
4878 static void shellPreparePrintf(
4881 sqlite3_stmt
**ppStmt
,
4886 if( *pRc
==SQLITE_OK
){
4890 z
= sqlite3_vmprintf(zFmt
, ap
);
4892 *pRc
= SQLITE_NOMEM
;
4894 shellPrepare(db
, pRc
, z
, ppStmt
);
4900 static void shellFinalize(
4905 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4906 int rc
= sqlite3_finalize(pStmt
);
4907 if( *pRc
==SQLITE_OK
){
4908 if( rc
!=SQLITE_OK
){
4909 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4916 static void shellReset(
4920 int rc
= sqlite3_reset(pStmt
);
4921 if( *pRc
==SQLITE_OK
){
4922 if( rc
!=SQLITE_OK
){
4923 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4924 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4930 ** Structure representing a single ".ar" command.
4932 typedef struct ArCommand ArCommand
;
4934 u8 eCmd
; /* An AR_CMD_* value */
4935 u8 bVerbose
; /* True if --verbose */
4936 u8 bZip
; /* True if the archive is a ZIP */
4937 u8 bDryRun
; /* True if --dry-run */
4938 u8 bAppend
; /* True if --append */
4939 u8 fromCmdLine
; /* Run from -A instead of .archive */
4940 int nArg
; /* Number of command arguments */
4941 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
4942 const char *zFile
; /* --file argument, or NULL */
4943 const char *zDir
; /* --directory argument, or NULL */
4944 char **azArg
; /* Array of command arguments */
4945 ShellState
*p
; /* Shell state */
4946 sqlite3
*db
; /* Database containing the archive */
4950 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4952 static int arUsage(FILE *f
){
4955 "Usage: .ar [OPTION...] [FILE...]\n"
4956 "The .ar command manages sqlar archives.\n"
4959 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4960 " .ar -tf archive.sar # List members of archive.sar\n"
4961 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4963 "Each command line must feature exactly one command option:\n"
4964 " -c, --create Create a new archive\n"
4965 " -u, --update Update or add files to an existing archive\n"
4966 " -t, --list List contents of archive\n"
4967 " -x, --extract Extract files from archive\n"
4969 "And zero or more optional options:\n"
4970 " -v, --verbose Print each filename as it is processed\n"
4971 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4972 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
4973 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4974 " -n, --dryrun Show the SQL that would have occurred\n"
4976 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4979 return SQLITE_ERROR
;
4983 ** Print an error message for the .ar command to stderr and return
4986 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
4990 z
= sqlite3_vmprintf(zFmt
, ap
);
4992 utf8_printf(stderr
, "Error: %s\n", z
);
4993 if( pAr
->fromCmdLine
){
4994 utf8_printf(stderr
, "Use \"-A\" for more help\n");
4996 utf8_printf(stderr
, "Use \".archive --help\" for more help\n");
4999 return SQLITE_ERROR
;
5003 ** Values for ArCommand.eCmd.
5005 #define AR_CMD_CREATE 1
5006 #define AR_CMD_EXTRACT 2
5007 #define AR_CMD_LIST 3
5008 #define AR_CMD_UPDATE 4
5009 #define AR_CMD_HELP 5
5012 ** Other (non-command) switches.
5014 #define AR_SWITCH_VERBOSE 6
5015 #define AR_SWITCH_FILE 7
5016 #define AR_SWITCH_DIRECTORY 8
5017 #define AR_SWITCH_APPEND 9
5018 #define AR_SWITCH_DRYRUN 10
5020 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
5023 case AR_CMD_EXTRACT
:
5028 return arErrorMsg(pAr
, "multiple command options");
5030 pAr
->eCmd
= eSwitch
;
5033 case AR_SWITCH_DRYRUN
:
5036 case AR_SWITCH_VERBOSE
:
5039 case AR_SWITCH_APPEND
:
5041 /* Fall thru into --file */
5042 case AR_SWITCH_FILE
:
5045 case AR_SWITCH_DIRECTORY
:
5054 ** Parse the command line for an ".ar" command. The results are written into
5055 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5056 ** successfully, otherwise an error message is written to stderr and
5057 ** SQLITE_ERROR returned.
5059 static int arParseCommand(
5060 char **azArg
, /* Array of arguments passed to dot command */
5061 int nArg
, /* Number of entries in azArg[] */
5062 ArCommand
*pAr
/* Populate this object */
5070 { "create", 'c', AR_CMD_CREATE
, 0 },
5071 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
5072 { "list", 't', AR_CMD_LIST
, 0 },
5073 { "update", 'u', AR_CMD_UPDATE
, 0 },
5074 { "help", 'h', AR_CMD_HELP
, 0 },
5075 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
5076 { "file", 'f', AR_SWITCH_FILE
, 1 },
5077 { "append", 'a', AR_SWITCH_APPEND
, 1 },
5078 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
5079 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
5081 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
5082 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
5085 return arUsage(stderr
);
5089 /* Traditional style [tar] invocation */
5092 for(i
=0; z
[i
]; i
++){
5093 const char *zArg
= 0;
5094 struct ArSwitch
*pOpt
;
5095 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5096 if( z
[i
]==pOpt
->cShort
) break;
5099 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
5103 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
5105 zArg
= azArg
[iArg
++];
5107 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5109 pAr
->nArg
= nArg
-iArg
;
5111 pAr
->azArg
= &azArg
[iArg
];
5114 /* Non-traditional invocation */
5116 for(iArg
=1; iArg
<nArg
; iArg
++){
5120 /* All remaining command line words are command arguments. */
5121 pAr
->azArg
= &azArg
[iArg
];
5122 pAr
->nArg
= nArg
-iArg
;
5129 /* One or more short options */
5131 const char *zArg
= 0;
5132 struct ArSwitch
*pOpt
;
5133 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5134 if( z
[i
]==pOpt
->cShort
) break;
5137 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
5144 if( iArg
>=(nArg
-1) ){
5145 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
5147 zArg
= azArg
[++iArg
];
5150 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5152 }else if( z
[2]=='\0' ){
5153 /* A -- option, indicating that all remaining command line words
5154 ** are command arguments. */
5155 pAr
->azArg
= &azArg
[iArg
+1];
5156 pAr
->nArg
= nArg
-iArg
-1;
5160 const char *zArg
= 0; /* Argument for option, if any */
5161 struct ArSwitch
*pMatch
= 0; /* Matching option */
5162 struct ArSwitch
*pOpt
; /* Iterator */
5163 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5164 const char *zLong
= pOpt
->zLong
;
5165 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
5167 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
5175 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
5178 if( iArg
>=(nArg
-1) ){
5179 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
5181 zArg
= azArg
[++iArg
];
5183 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5193 ** This function assumes that all arguments within the ArCommand.azArg[]
5194 ** array refer to archive members, as for the --extract or --list commands.
5195 ** It checks that each of them are present. If any specified file is not
5196 ** present in the archive, an error is printed to stderr and an error
5197 ** code returned. Otherwise, if all specified arguments are present in
5198 ** the archive, SQLITE_OK is returned.
5200 ** This function strips any trailing '/' characters from each argument.
5201 ** This is consistent with the way the [tar] command seems to work on
5204 static int arCheckEntries(ArCommand
*pAr
){
5208 sqlite3_stmt
*pTest
= 0;
5210 shellPreparePrintf(pAr
->db
, &rc
, &pTest
,
5211 "SELECT name FROM %s WHERE name=$name",
5214 j
= sqlite3_bind_parameter_index(pTest
, "$name");
5215 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5216 char *z
= pAr
->azArg
[i
];
5217 int n
= strlen30(z
);
5219 while( n
>0 && z
[n
-1]=='/' ) n
--;
5221 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
5222 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
5225 shellReset(&rc
, pTest
);
5226 if( rc
==SQLITE_OK
&& bOk
==0 ){
5227 utf8_printf(stderr
, "not found in archive: %s\n", z
);
5231 shellFinalize(&rc
, pTest
);
5237 ** Format a WHERE clause that can be used against the "sqlar" table to
5238 ** identify all archive members that match the command arguments held
5239 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5240 ** The caller is responsible for eventually calling sqlite3_free() on
5241 ** any non-NULL (*pzWhere) value.
5243 static void arWhereClause(
5246 char **pzWhere
/* OUT: New WHERE clause */
5249 if( *pRc
==SQLITE_OK
){
5251 zWhere
= sqlite3_mprintf("1");
5254 const char *zSep
= "";
5255 for(i
=0; i
<pAr
->nArg
; i
++){
5256 const char *z
= pAr
->azArg
[i
];
5257 zWhere
= sqlite3_mprintf(
5258 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5259 zWhere
, zSep
, z
, strlen30(z
)+1, z
5262 *pRc
= SQLITE_NOMEM
;
5273 ** Implementation of .ar "lisT" command.
5275 static int arListCommand(ArCommand
*pAr
){
5276 const char *zSql
= "SELECT %s FROM %s WHERE %s";
5277 const char *azCols
[] = {
5279 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5283 sqlite3_stmt
*pSql
= 0;
5286 rc
= arCheckEntries(pAr
);
5287 arWhereClause(&rc
, pAr
, &zWhere
);
5289 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
5290 pAr
->zSrcTable
, zWhere
);
5292 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5294 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5295 if( pAr
->bVerbose
){
5296 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
5297 sqlite3_column_text(pSql
, 0),
5298 sqlite3_column_int(pSql
, 1),
5299 sqlite3_column_text(pSql
, 2),
5300 sqlite3_column_text(pSql
, 3)
5303 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5307 shellFinalize(&rc
, pSql
);
5308 sqlite3_free(zWhere
);
5314 ** Implementation of .ar "eXtract" command.
5316 static int arExtractCommand(ArCommand
*pAr
){
5320 " writefile(($dir || name), %s, mode, mtime) "
5321 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5322 " AND name NOT GLOB '*..[/\\]*'";
5324 const char *azExtraArg
[] = {
5325 "sqlar_uncompress(data, sz)",
5329 sqlite3_stmt
*pSql
= 0;
5335 /* If arguments are specified, check that they actually exist within
5336 ** the archive before proceeding. And formulate a WHERE clause to
5338 rc
= arCheckEntries(pAr
);
5339 arWhereClause(&rc
, pAr
, &zWhere
);
5341 if( rc
==SQLITE_OK
){
5343 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
5345 zDir
= sqlite3_mprintf("");
5347 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
5350 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
5351 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
5354 if( rc
==SQLITE_OK
){
5355 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
5356 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
5358 /* Run the SELECT statement twice. The first time, writefile() is called
5359 ** for all archive members that should be extracted. The second time,
5360 ** only for the directories. This is because the timestamps for
5361 ** extracted directories must be reset after they are populated (as
5362 ** populating them changes the timestamp). */
5364 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
5365 sqlite3_bind_int(pSql
, j
, i
);
5367 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5369 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5370 if( i
==0 && pAr
->bVerbose
){
5371 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5375 shellReset(&rc
, pSql
);
5377 shellFinalize(&rc
, pSql
);
5381 sqlite3_free(zWhere
);
5386 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5388 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
5391 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
5395 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
5397 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
5406 ** Implementation of .ar "create" and "update" commands.
5408 ** Create the "sqlar" table in the database if it does not already exist.
5409 ** Then add each file in the azFile[] array to the archive. Directories
5410 ** are added recursively. If argument bVerbose is non-zero, a message is
5411 ** printed on stdout for each file archived.
5413 ** The create command is the same as update, except that it drops
5414 ** any existing "sqlar" table before beginning.
5416 static int arCreateOrUpdateCommand(
5417 ArCommand
*pAr
, /* Command arguments and options */
5418 int bUpdate
/* true for a --create. false for --update */
5420 const char *zCreate
=
5421 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5422 " name TEXT PRIMARY KEY, -- name of the file\n"
5423 " mode INT, -- access permissions\n"
5424 " mtime INT, -- last modification time\n"
5425 " sz INT, -- original file size\n"
5426 " data BLOB -- compressed content\n"
5428 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
5429 const char *zInsertFmt
[2] = {
5430 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
5435 " CASE substr(lsmode(mode),1,1)\n"
5436 " WHEN '-' THEN length(data)\n"
5437 " WHEN 'd' THEN 0\n"
5439 " sqlar_compress(data)\n"
5440 " FROM fsdir(%Q,%Q)\n"
5441 " WHERE lsmode(mode) NOT LIKE '?%%';",
5442 "REPLACE INTO %s(name,mode,mtime,data)\n"
5448 " FROM fsdir(%Q,%Q)\n"
5449 " WHERE lsmode(mode) NOT LIKE '?%%';"
5451 int i
; /* For iterating through azFile[] */
5452 int rc
; /* Return code */
5453 const char *zTab
= 0; /* SQL table into which to insert */
5457 arExecSql(pAr
, "PRAGMA page_size=512");
5458 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
5459 if( rc
!=SQLITE_OK
) return rc
;
5462 /* Initialize the zipfile virtual table, if necessary */
5465 sqlite3_randomness(sizeof(r
),&r
);
5466 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
5468 zSql
= sqlite3_mprintf(
5469 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5472 rc
= arExecSql(pAr
, zSql
);
5478 /* Initialize the table for an SQLAR */
5481 rc
= arExecSql(pAr
, zDrop
);
5482 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
5484 rc
= arExecSql(pAr
, zCreate
);
5486 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5487 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
5488 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
5489 pAr
->azArg
[i
], pAr
->zDir
);
5490 rc
= arExecSql(pAr
, zSql2
);
5491 sqlite3_free(zSql2
);
5494 if( rc
!=SQLITE_OK
){
5495 arExecSql(pAr
, "ROLLBACK TO ar; RELEASE ar;");
5497 rc
= arExecSql(pAr
, "RELEASE ar;");
5498 if( pAr
->bZip
&& pAr
->zFile
){
5499 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
5500 arExecSql(pAr
, zSql
);
5508 ** Implementation of ".ar" dot command.
5510 static int arDotCommand(
5511 ShellState
*pState
, /* Current shell tool state */
5512 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
5513 char **azArg
, /* Array of arguments passed to dot command */
5514 int nArg
/* Number of entries in azArg[] */
5518 memset(&cmd
, 0, sizeof(cmd
));
5519 cmd
.fromCmdLine
= fromCmdLine
;
5520 rc
= arParseCommand(azArg
, nArg
, &cmd
);
5521 if( rc
==SQLITE_OK
){
5522 int eDbType
= SHELL_OPEN_UNSPEC
;
5524 cmd
.db
= pState
->db
;
5526 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
5528 eDbType
= pState
->openMode
;
5530 if( eDbType
==SHELL_OPEN_ZIPFILE
){
5531 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
5533 cmd
.zSrcTable
= sqlite3_mprintf("zip");
5535 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
5539 }else if( cmd
.zFile
){
5541 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
5542 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5543 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
5545 flags
= SQLITE_OPEN_READONLY
;
5549 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
5550 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
5552 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
5553 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
5554 if( rc
!=SQLITE_OK
){
5555 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
5556 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
5558 goto end_ar_command
;
5560 sqlite3_fileio_init(cmd
.db
, 0, 0);
5561 sqlite3_sqlar_init(cmd
.db
, 0, 0);
5562 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
5563 shellPutsFunc
, 0, 0);
5566 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
5567 if( cmd
.eCmd
!=AR_CMD_CREATE
5568 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
5570 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
5572 goto end_ar_command
;
5574 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
5579 rc
= arCreateOrUpdateCommand(&cmd
, 0);
5582 case AR_CMD_EXTRACT
:
5583 rc
= arExtractCommand(&cmd
);
5587 rc
= arListCommand(&cmd
);
5591 arUsage(pState
->out
);
5595 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
5596 rc
= arCreateOrUpdateCommand(&cmd
, 1);
5601 if( cmd
.db
!=pState
->db
){
5604 sqlite3_free(cmd
.zSrcTable
);
5608 /* End of the ".archive" or ".ar" command logic
5609 **********************************************************************************/
5610 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5614 ** If an input line begins with "." then invoke this routine to
5615 ** process that line.
5617 ** Return 1 on error, 2 to exit, and 0 otherwise.
5619 static int do_meta_command(char *zLine
, ShellState
*p
){
5626 #ifndef SQLITE_OMIT_VIRTUALTABLE
5627 if( p
->expert
.pExpert
){
5628 expertFinish(p
, 1, 0);
5632 /* Parse the input line into tokens.
5634 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
5635 while( IsSpace(zLine
[h
]) ){ h
++; }
5636 if( zLine
[h
]==0 ) break;
5637 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
5638 int delim
= zLine
[h
++];
5639 azArg
[nArg
++] = &zLine
[h
];
5640 while( zLine
[h
] && zLine
[h
]!=delim
){
5641 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
5644 if( zLine
[h
]==delim
){
5647 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
5649 azArg
[nArg
++] = &zLine
[h
];
5650 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
5651 if( zLine
[h
] ) zLine
[h
++] = 0;
5652 resolve_backslashes(azArg
[nArg
-1]);
5656 /* Process the input line.
5658 if( nArg
==0 ) return 0; /* no tokens, no error */
5659 n
= strlen30(azArg
[0]);
5663 #ifndef SQLITE_OMIT_AUTHORIZATION
5664 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
5666 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
5668 goto meta_command_exit
;
5671 if( booleanValue(azArg
[1]) ){
5672 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
5674 sqlite3_set_authorizer(p
->db
, 0, 0);
5679 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5680 if( c
=='a' && strncmp(azArg
[0], "archive", n
)==0 ){
5682 rc
= arDotCommand(p
, 0, azArg
, nArg
);
5686 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
5687 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
5689 const char *zDestFile
= 0;
5690 const char *zDb
= 0;
5692 sqlite3_backup
*pBackup
;
5694 const char *zVfs
= 0;
5695 for(j
=1; j
<nArg
; j
++){
5696 const char *z
= azArg
[j
];
5698 if( z
[1]=='-' ) z
++;
5699 if( strcmp(z
, "-append")==0 ){
5703 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
5706 }else if( zDestFile
==0 ){
5707 zDestFile
= azArg
[j
];
5710 zDestFile
= azArg
[j
];
5712 raw_printf(stderr
, "Usage: .backup ?DB? ?--append? FILENAME\n");
5717 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
5720 if( zDb
==0 ) zDb
= "main";
5721 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
5722 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
5723 if( rc
!=SQLITE_OK
){
5724 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
5729 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
5731 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5735 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
5736 sqlite3_backup_finish(pBackup
);
5737 if( rc
==SQLITE_DONE
){
5740 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5746 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
5748 bail_on_error
= booleanValue(azArg
[1]);
5750 raw_printf(stderr
, "Usage: .bail on|off\n");
5755 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
5757 if( booleanValue(azArg
[1]) ){
5758 setBinaryMode(p
->out
, 1);
5760 setTextMode(p
->out
, 1);
5763 raw_printf(stderr
, "Usage: .binary on|off\n");
5768 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
5770 #if defined(_WIN32) || defined(WIN32)
5771 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
5772 rc
= !SetCurrentDirectoryW(z
);
5775 rc
= chdir(azArg
[1]);
5778 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
5782 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
5787 /* The undocumented ".breakpoint" command causes a call to the no-op
5788 ** routine named test_breakpoint().
5790 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
5794 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
5796 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
5798 raw_printf(stderr
, "Usage: .changes on|off\n");
5803 /* Cancel output redirection, if it is currently set (by .testcase)
5804 ** Then read the content of the testcase-out.txt file and compare against
5805 ** azArg[1]. If there are differences, report an error and exit.
5807 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
5811 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
5813 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
5814 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
5816 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
5818 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5819 p
->zTestcase
, azArg
[1], zRes
);
5822 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
5828 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
5830 tryToClone(p
, azArg
[1]);
5832 raw_printf(stderr
, "Usage: .clone FILENAME\n");
5837 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
5841 memcpy(&data
, p
, sizeof(data
));
5842 data
.showHeader
= 0;
5843 data
.cMode
= data
.mode
= MODE_List
;
5844 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
5846 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
5847 callback
, &data
, &zErrMsg
);
5849 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5850 sqlite3_free(zErrMsg
);
5855 if( c
=='d' && n
>=3 && strncmp(azArg
[0], "dbconfig", n
)==0 ){
5856 static const struct DbConfigChoices
{const char *zName
; int op
;} aDbConfig
[] = {
5857 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
5858 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
5859 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
5860 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
5861 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
5862 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
5863 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
5864 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
5868 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
5869 if( nArg
>1 && strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
5871 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
5873 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
5874 utf8_printf(p
->out
, "%18s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
5877 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
5878 utf8_printf(stderr
, "Error: unknown dbconfig \"%s\"\n", azArg
[1]);
5879 utf8_printf(stderr
, "Enter \".dbconfig\" with no arguments for a list\n");
5883 if( c
=='d' && n
>=3 && strncmp(azArg
[0], "dbinfo", n
)==0 ){
5884 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
5887 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
5888 const char *zLike
= 0;
5890 int savedShowHeader
= p
->showHeader
;
5891 int savedShellFlags
= p
->shellFlgs
;
5892 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
);
5893 for(i
=1; i
<nArg
; i
++){
5894 if( azArg
[i
][0]=='-' ){
5895 const char *z
= azArg
[i
]+1;
5896 if( z
[0]=='-' ) z
++;
5897 if( strcmp(z
,"preserve-rowids")==0 ){
5898 #ifdef SQLITE_OMIT_VIRTUALTABLE
5899 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
5900 " with SQLITE_OMIT_VIRTUALTABLE\n");
5902 goto meta_command_exit
;
5904 ShellSetFlag(p
, SHFLG_PreserveRowid
);
5907 if( strcmp(z
,"newlines")==0 ){
5908 ShellSetFlag(p
, SHFLG_Newlines
);
5911 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
5913 goto meta_command_exit
;
5916 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
5917 "?--newlines? ?LIKE-PATTERN?\n");
5919 goto meta_command_exit
;
5925 /* When playing back a "dump", the content might appear in an order
5926 ** which causes immediate foreign key constraints to be violated.
5927 ** So disable foreign-key constraint enforcement to prevent problems. */
5928 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
5929 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
5930 p
->writableSchema
= 0;
5932 /* Set writable_schema=ON since doing so forces SQLite to initialize
5933 ** as much of the schema as it can even if the sqlite_master table is
5935 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5938 run_schema_dump_query(p
,
5939 "SELECT name, type, sql FROM sqlite_master "
5940 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5942 run_schema_dump_query(p
,
5943 "SELECT name, type, sql FROM sqlite_master "
5944 "WHERE name=='sqlite_sequence'"
5946 run_table_dump_query(p
,
5947 "SELECT sql FROM sqlite_master "
5948 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5952 zSql
= sqlite3_mprintf(
5953 "SELECT name, type, sql FROM sqlite_master "
5954 "WHERE tbl_name LIKE %Q AND type=='table'"
5955 " AND sql NOT NULL", zLike
);
5956 run_schema_dump_query(p
,zSql
);
5958 zSql
= sqlite3_mprintf(
5959 "SELECT sql FROM sqlite_master "
5960 "WHERE sql NOT NULL"
5961 " AND type IN ('index','trigger','view')"
5962 " AND tbl_name LIKE %Q", zLike
);
5963 run_table_dump_query(p
, zSql
, 0);
5966 if( p
->writableSchema
){
5967 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
5968 p
->writableSchema
= 0;
5970 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5971 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
5972 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5973 p
->showHeader
= savedShowHeader
;
5974 p
->shellFlgs
= savedShellFlags
;
5977 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
5979 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
5981 raw_printf(stderr
, "Usage: .echo on|off\n");
5986 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
5989 if( strcmp(azArg
[1],"full")==0 ){
5990 p
->autoEQP
= AUTOEQP_full
;
5991 }else if( strcmp(azArg
[1],"trigger")==0 ){
5992 p
->autoEQP
= AUTOEQP_trigger
;
5993 }else if( strcmp(azArg
[1],"test")==0 ){
5994 p
->autoEQP
= AUTOEQP_on
;
5997 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
6000 raw_printf(stderr
, "Usage: .eqp off|on|trigger|full\n");
6005 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
6006 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
6010 /* The ".explain" command is automatic now. It is largely pointless. It
6011 ** retained purely for backwards compatibility */
6012 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
6015 if( strcmp(azArg
[1],"auto")==0 ){
6018 val
= booleanValue(azArg
[1]);
6021 if( val
==1 && p
->mode
!=MODE_Explain
){
6022 p
->normalMode
= p
->mode
;
6023 p
->mode
= MODE_Explain
;
6026 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
6028 }else if( val
==99 ){
6029 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
6034 #ifndef SQLITE_OMIT_VIRTUALTABLE
6035 if( c
=='e' && strncmp(azArg
[0], "expert", n
)==0 ){
6037 expertDotCommand(p
, azArg
, nArg
);
6041 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
6045 memcpy(&data
, p
, sizeof(data
));
6046 data
.showHeader
= 0;
6047 data
.cMode
= data
.mode
= MODE_Semi
;
6048 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
6049 data
.cMode
= data
.mode
= MODE_Pretty
;
6053 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
6055 goto meta_command_exit
;
6058 rc
= sqlite3_exec(p
->db
,
6060 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6061 " FROM sqlite_master UNION ALL"
6062 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6063 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6065 callback
, &data
, &zErrMsg
6067 if( rc
==SQLITE_OK
){
6068 sqlite3_stmt
*pStmt
;
6069 rc
= sqlite3_prepare_v2(p
->db
,
6070 "SELECT rowid FROM sqlite_master"
6071 " WHERE name GLOB 'sqlite_stat[134]'",
6073 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
6074 sqlite3_finalize(pStmt
);
6077 raw_printf(p
->out
, "/* No STAT tables available */\n");
6079 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
6080 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
6081 callback
, &data
, &zErrMsg
);
6082 data
.cMode
= data
.mode
= MODE_Insert
;
6083 data
.zDestTable
= "sqlite_stat1";
6084 shell_exec(&data
, "SELECT * FROM sqlite_stat1", &zErrMsg
);
6085 data
.zDestTable
= "sqlite_stat3";
6086 shell_exec(&data
, "SELECT * FROM sqlite_stat3", &zErrMsg
);
6087 data
.zDestTable
= "sqlite_stat4";
6088 shell_exec(&data
, "SELECT * FROM sqlite_stat4", &zErrMsg
);
6089 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
6093 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
6095 p
->showHeader
= booleanValue(azArg
[1]);
6097 raw_printf(stderr
, "Usage: .headers on|off\n");
6102 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
6103 utf8_printf(p
->out
, "%s", zHelp
);
6106 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
6107 char *zTable
; /* Insert data into this table */
6108 char *zFile
; /* Name of file to extra content from */
6109 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
6110 int nCol
; /* Number of columns in the table */
6111 int nByte
; /* Number of bytes in an SQL string */
6112 int i
, j
; /* Loop counters */
6113 int needCommit
; /* True to COMMIT or ROLLBACK at end */
6114 int nSep
; /* Number of bytes in p->colSeparator[] */
6115 char *zSql
; /* An SQL statement */
6116 ImportCtx sCtx
; /* Reader context */
6117 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
6118 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
6121 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
6122 goto meta_command_exit
;
6127 memset(&sCtx
, 0, sizeof(sCtx
));
6129 nSep
= strlen30(p
->colSeparator
);
6132 "Error: non-null column separator required for import\n");
6136 raw_printf(stderr
, "Error: multi-character column separators not allowed"
6140 nSep
= strlen30(p
->rowSeparator
);
6142 raw_printf(stderr
, "Error: non-null row separator required for import\n");
6145 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
6146 /* When importing CSV (only), if the row separator is set to the
6147 ** default output row separator, change it to the default input
6148 ** row separator. This avoids having to maintain different input
6149 ** and output row separators. */
6150 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6151 nSep
= strlen30(p
->rowSeparator
);
6154 raw_printf(stderr
, "Error: multi-character row separators not allowed"
6160 if( sCtx
.zFile
[0]=='|' ){
6161 #ifdef SQLITE_OMIT_POPEN
6162 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6165 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
6166 sCtx
.zFile
= "<pipe>";
6170 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
6173 if( p
->mode
==MODE_Ascii
){
6174 xRead
= ascii_read_one_field
;
6176 xRead
= csv_read_one_field
;
6179 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
6182 sCtx
.cColSep
= p
->colSeparator
[0];
6183 sCtx
.cRowSep
= p
->rowSeparator
[0];
6184 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
6187 shell_out_of_memory();
6189 nByte
= strlen30(zSql
);
6190 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6191 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
6192 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
6193 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
6195 while( xRead(&sCtx
) ){
6196 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
6198 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
6201 sqlite3_free(zCreate
);
6202 sqlite3_free(sCtx
.z
);
6204 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
6207 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
6208 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
6209 sqlite3_free(zCreate
);
6211 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
6212 sqlite3_errmsg(p
->db
));
6213 sqlite3_free(sCtx
.z
);
6217 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6221 if (pStmt
) sqlite3_finalize(pStmt
);
6222 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
6226 nCol
= sqlite3_column_count(pStmt
);
6227 sqlite3_finalize(pStmt
);
6229 if( nCol
==0 ) return 0; /* no columns, no error */
6230 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
6233 shell_out_of_memory();
6235 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
6237 for(i
=1; i
<nCol
; i
++){
6243 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6246 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6247 if (pStmt
) sqlite3_finalize(pStmt
);
6251 needCommit
= sqlite3_get_autocommit(p
->db
);
6252 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
6254 int startLine
= sCtx
.nLine
;
6255 for(i
=0; i
<nCol
; i
++){
6256 char *z
= xRead(&sCtx
);
6258 ** Did we reach end-of-file before finding any columns?
6259 ** If so, stop instead of NULL filling the remaining columns.
6261 if( z
==0 && i
==0 ) break;
6263 ** Did we reach end-of-file OR end-of-line before finding any
6264 ** columns in ASCII mode? If so, stop instead of NULL filling
6265 ** the remaining columns.
6267 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
6268 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
6269 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
6270 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6271 "filling the rest with NULL\n",
6272 sCtx
.zFile
, startLine
, nCol
, i
+1);
6274 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
6277 if( sCtx
.cTerm
==sCtx
.cColSep
){
6281 }while( sCtx
.cTerm
==sCtx
.cColSep
);
6282 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6284 sCtx
.zFile
, startLine
, nCol
, i
);
6287 sqlite3_step(pStmt
);
6288 rc
= sqlite3_reset(pStmt
);
6289 if( rc
!=SQLITE_OK
){
6290 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
6291 startLine
, sqlite3_errmsg(p
->db
));
6294 }while( sCtx
.cTerm
!=EOF
);
6297 sqlite3_free(sCtx
.z
);
6298 sqlite3_finalize(pStmt
);
6299 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
6302 #ifndef SQLITE_UNTESTABLE
6303 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
6306 sqlite3_stmt
*pStmt
;
6309 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
6310 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n"
6311 " .imposter off\n");
6313 goto meta_command_exit
;
6317 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
6318 goto meta_command_exit
;
6320 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6321 " WHERE name='%q' AND type='index'", azArg
[1]);
6322 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6324 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
6325 tnum
= sqlite3_column_int(pStmt
, 0);
6327 sqlite3_finalize(pStmt
);
6329 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
6331 goto meta_command_exit
;
6333 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
6334 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6337 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6339 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
6342 if( sqlite3_column_int(pStmt
,1)==-1 ){
6345 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
6350 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
6352 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
6355 sqlite3_finalize(pStmt
);
6356 zSql
= sqlite3_mprintf(
6357 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6358 azArg
[2], zCollist
, zCollist
);
6359 sqlite3_free(zCollist
);
6360 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
6361 if( rc
==SQLITE_OK
){
6362 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
6363 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
6365 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
6367 utf8_printf(stdout
, "%s;\n", zSql
);
6369 "WARNING: writing to an imposter table will corrupt the index!\n"
6373 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
6378 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6380 #ifdef SQLITE_ENABLE_IOTRACE
6381 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
6382 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
6383 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
6387 }else if( strcmp(azArg
[1], "-")==0 ){
6388 sqlite3IoTrace
= iotracePrintf
;
6391 iotrace
= fopen(azArg
[1], "w");
6393 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
6397 sqlite3IoTrace
= iotracePrintf
;
6403 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
6404 static const struct {
6405 const char *zLimitName
; /* Name of a limit */
6406 int limitCode
; /* Integer code for that limit */
6408 { "length", SQLITE_LIMIT_LENGTH
},
6409 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
6410 { "column", SQLITE_LIMIT_COLUMN
},
6411 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
6412 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
6413 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
6414 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
6415 { "attached", SQLITE_LIMIT_ATTACHED
},
6416 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
6417 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
6418 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
6419 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
6424 for(i
=0; i
<ArraySize(aLimit
); i
++){
6425 printf("%20s %d\n", aLimit
[i
].zLimitName
,
6426 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
6429 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
6431 goto meta_command_exit
;
6434 n2
= strlen30(azArg
[1]);
6435 for(i
=0; i
<ArraySize(aLimit
); i
++){
6436 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
6440 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
6442 goto meta_command_exit
;
6447 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
6448 "enter \".limits\" with no arguments for a list.\n",
6451 goto meta_command_exit
;
6454 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
6455 (int)integerValue(azArg
[2]));
6457 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
6458 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
6462 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
6464 lintDotCommand(p
, azArg
, nArg
);
6467 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6468 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
6469 const char *zFile
, *zProc
;
6472 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
6474 goto meta_command_exit
;
6477 zProc
= nArg
>=3 ? azArg
[2] : 0;
6479 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
6480 if( rc
!=SQLITE_OK
){
6481 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
6482 sqlite3_free(zErrMsg
);
6488 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
6490 raw_printf(stderr
, "Usage: .log FILENAME\n");
6493 const char *zFile
= azArg
[1];
6494 output_file_close(p
->pLog
);
6495 p
->pLog
= output_file_open(zFile
, 0);
6499 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
6500 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
6501 int n2
= strlen30(zMode
);
6503 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
6504 p
->mode
= MODE_Line
;
6505 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6506 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
6507 p
->mode
= MODE_Column
;
6508 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6509 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
6510 p
->mode
= MODE_List
;
6511 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
6512 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6513 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
6514 p
->mode
= MODE_Html
;
6515 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
6517 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
6518 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6519 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
6521 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6522 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6523 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
6524 p
->mode
= MODE_List
;
6525 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
6526 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
6527 p
->mode
= MODE_Insert
;
6528 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
6529 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
6530 p
->mode
= MODE_Quote
;
6531 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
6532 p
->mode
= MODE_Ascii
;
6533 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
6534 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
6535 }else if( nArg
==1 ){
6536 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
6538 raw_printf(stderr
, "Error: mode should be one of: "
6539 "ascii column csv html insert line list quote tabs tcl\n");
6545 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
6547 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
6548 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
6550 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
6555 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
6556 char *zNewFilename
; /* Name of the database file to open */
6557 int iName
= 1; /* Index in azArg[] of the filename */
6558 int newFlag
= 0; /* True to delete file before opening */
6559 /* Close the existing database */
6560 session_close_all(p
);
6564 sqlite3_free(p
->zFreeOnClose
);
6565 p
->zFreeOnClose
= 0;
6566 p
->openMode
= SHELL_OPEN_UNSPEC
;
6567 /* Check for command-line arguments */
6568 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
6569 const char *z
= azArg
[iName
];
6570 if( optionMatch(z
,"new") ){
6572 #ifdef SQLITE_HAVE_ZLIB
6573 }else if( optionMatch(z
, "zip") ){
6574 p
->openMode
= SHELL_OPEN_ZIPFILE
;
6576 }else if( optionMatch(z
, "append") ){
6577 p
->openMode
= SHELL_OPEN_APPENDVFS
;
6578 }else if( optionMatch(z
, "readonly") ){
6579 p
->openMode
= SHELL_OPEN_READONLY
;
6580 }else if( z
[0]=='-' ){
6581 utf8_printf(stderr
, "unknown option: %s\n", z
);
6583 goto meta_command_exit
;
6586 /* If a filename is specified, try to open it first */
6587 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
6589 if( newFlag
) shellDeleteFile(zNewFilename
);
6590 p
->zDbFilename
= zNewFilename
;
6591 open_db(p
, OPEN_DB_KEEPALIVE
);
6593 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
6594 sqlite3_free(zNewFilename
);
6596 p
->zFreeOnClose
= zNewFilename
;
6600 /* As a fall-back open a TEMP database */
6607 && (strncmp(azArg
[0], "output", n
)==0||strncmp(azArg
[0], "once", n
)==0))
6608 || (c
=='e' && n
==5 && strcmp(azArg
[0],"excel")==0)
6610 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
6612 if( azArg
[0][0]=='e' ){
6613 /* Transform the ".excel" command into ".once -x" */
6616 zFile
= azArg
[1] = "-x";
6620 utf8_printf(stderr
, "Usage: .%s [-e|-x|FILE]\n", azArg
[0]);
6622 goto meta_command_exit
;
6624 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
6626 raw_printf(stderr
, "Usage: .once (-e|-x|FILE)\n");
6628 goto meta_command_exit
;
6635 if( zFile
[0]=='-' && zFile
[1]=='-' ) zFile
++;
6636 #ifndef SQLITE_NOHAVE_SYSTEM
6637 if( strcmp(zFile
, "-e")==0 || strcmp(zFile
, "-x")==0 ){
6640 if( zFile
[1]=='x' ){
6641 newTempFile(p
, "csv");
6643 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6644 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6646 newTempFile(p
, "txt");
6649 zFile
= p
->zTempFile
;
6651 #endif /* SQLITE_NOHAVE_SYSTEM */
6652 if( zFile
[0]=='|' ){
6653 #ifdef SQLITE_OMIT_POPEN
6654 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6658 p
->out
= popen(zFile
+ 1, "w");
6660 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
6664 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6668 p
->out
= output_file_open(zFile
, bTxtMode
);
6670 if( strcmp(zFile
,"off")!=0 ){
6671 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
6676 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6681 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
6683 for(i
=1; i
<nArg
; i
++){
6684 if( i
>1 ) raw_printf(p
->out
, " ");
6685 utf8_printf(p
->out
, "%s", azArg
[i
]);
6687 raw_printf(p
->out
, "\n");
6690 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
6692 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
6695 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
6699 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
6703 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
6706 raw_printf(stderr
, "Usage: .read FILE\n");
6708 goto meta_command_exit
;
6710 alt
= fopen(azArg
[1], "rb");
6712 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
6715 rc
= process_input(p
, alt
);
6720 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
6721 const char *zSrcFile
;
6724 sqlite3_backup
*pBackup
;
6728 zSrcFile
= azArg
[1];
6730 }else if( nArg
==3 ){
6731 zSrcFile
= azArg
[2];
6734 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
6736 goto meta_command_exit
;
6738 rc
= sqlite3_open(zSrcFile
, &pSrc
);
6739 if( rc
!=SQLITE_OK
){
6740 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
6745 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
6747 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6751 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
6752 || rc
==SQLITE_BUSY
){
6753 if( rc
==SQLITE_BUSY
){
6754 if( nTimeout
++ >= 3 ) break;
6758 sqlite3_backup_finish(pBackup
);
6759 if( rc
==SQLITE_DONE
){
6761 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
6762 raw_printf(stderr
, "Error: source database is busy\n");
6765 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6771 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
6773 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
6774 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6775 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
6778 raw_printf(stderr
, "Usage: .scanstats on|off\n");
6783 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
6787 const char *zDiv
= "(";
6788 const char *zName
= 0;
6794 memcpy(&data
, p
, sizeof(data
));
6795 data
.showHeader
= 0;
6796 data
.cMode
= data
.mode
= MODE_Semi
;
6798 for(ii
=1; ii
<nArg
; ii
++){
6799 if( optionMatch(azArg
[ii
],"indent") ){
6800 data
.cMode
= data
.mode
= MODE_Pretty
;
6801 }else if( optionMatch(azArg
[ii
],"debug") ){
6803 }else if( zName
==0 ){
6806 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6808 goto meta_command_exit
;
6812 int isMaster
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0;
6813 if( isMaster
|| sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0 ){
6814 char *new_argv
[2], *new_colv
[2];
6815 new_argv
[0] = sqlite3_mprintf(
6816 "CREATE TABLE %s (\n"
6820 " rootpage integer,\n"
6822 ")", isMaster
? "sqlite_master" : "sqlite_temp_master");
6824 new_colv
[0] = "sql";
6826 callback(&data
, 1, new_argv
, new_colv
);
6827 sqlite3_free(new_argv
[0]);
6831 sqlite3_stmt
*pStmt
= 0;
6832 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
6835 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6836 sqlite3_finalize(pStmt
);
6838 goto meta_command_exit
;
6840 appendText(&sSelect
, "SELECT sql FROM", 0);
6842 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6843 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
6845 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
6846 appendText(&sSelect
, zDiv
, 0);
6847 zDiv
= " UNION ALL ";
6848 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
6849 if( sqlite3_stricmp(zDb
, "main")!=0 ){
6850 appendText(&sSelect
, zDb
, '"');
6852 appendText(&sSelect
, "NULL", 0);
6854 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6855 appendText(&sSelect
, zScNum
, 0);
6856 appendText(&sSelect
, " AS snum, ", 0);
6857 appendText(&sSelect
, zDb
, '\'');
6858 appendText(&sSelect
, " AS sname FROM ", 0);
6859 appendText(&sSelect
, zDb
, '"');
6860 appendText(&sSelect
, ".sqlite_master", 0);
6862 sqlite3_finalize(pStmt
);
6863 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6865 appendText(&sSelect
,
6866 " UNION ALL SELECT shell_module_schema(name),"
6867 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6870 appendText(&sSelect
, ") WHERE ", 0);
6872 char *zQarg
= sqlite3_mprintf("%Q", zName
);
6873 int bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
6874 strchr(zName
, '[') != 0;
6875 if( strchr(zName
, '.') ){
6876 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
6878 appendText(&sSelect
, "lower(tbl_name)", 0);
6880 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
6881 appendText(&sSelect
, zQarg
, 0);
6883 appendText(&sSelect
, " ESCAPE '\\' ", 0);
6885 appendText(&sSelect
, " AND ", 0);
6886 sqlite3_free(zQarg
);
6888 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
6889 " ORDER BY snum, rowid", 0);
6891 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
6893 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
6898 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
6899 sqlite3_free(zErrMsg
);
6901 }else if( rc
!= SQLITE_OK
){
6902 raw_printf(stderr
,"Error: querying schema information\n");
6909 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6910 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
6911 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
6915 #if defined(SQLITE_ENABLE_SESSION)
6916 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
6917 OpenSession
*pSession
= &p
->aSession
[0];
6918 char **azCmd
= &azArg
[1];
6920 int nCmd
= nArg
- 1;
6922 if( nArg
<=1 ) goto session_syntax_error
;
6925 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
6926 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
6928 if( iSes
<p
->nSession
){
6929 pSession
= &p
->aSession
[iSes
];
6933 pSession
= &p
->aSession
[0];
6938 /* .session attach TABLE
6939 ** Invoke the sqlite3session_attach() interface to attach a particular
6940 ** table so that it is never filtered.
6942 if( strcmp(azCmd
[0],"attach")==0 ){
6943 if( nCmd
!=2 ) goto session_syntax_error
;
6944 if( pSession
->p
==0 ){
6946 raw_printf(stderr
, "ERROR: No sessions are open\n");
6948 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
6950 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
6956 /* .session changeset FILE
6957 ** .session patchset FILE
6958 ** Write a changeset or patchset into a file. The file is overwritten.
6960 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
6962 if( nCmd
!=2 ) goto session_syntax_error
;
6963 if( pSession
->p
==0 ) goto session_not_open
;
6964 out
= fopen(azCmd
[1], "wb");
6966 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
6970 if( azCmd
[0][0]=='c' ){
6971 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
6973 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
6976 printf("Error: error code %d\n", rc
);
6980 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
6981 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
6984 sqlite3_free(pChng
);
6990 ** Close the identified session
6992 if( strcmp(azCmd
[0], "close")==0 ){
6993 if( nCmd
!=1 ) goto session_syntax_error
;
6995 session_close(pSession
);
6996 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
7000 /* .session enable ?BOOLEAN?
7001 ** Query or set the enable flag
7003 if( strcmp(azCmd
[0], "enable")==0 ){
7005 if( nCmd
>2 ) goto session_syntax_error
;
7006 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
7008 ii
= sqlite3session_enable(pSession
->p
, ii
);
7009 utf8_printf(p
->out
, "session %s enable flag = %d\n",
7010 pSession
->zName
, ii
);
7014 /* .session filter GLOB ....
7015 ** Set a list of GLOB patterns of table names to be excluded.
7017 if( strcmp(azCmd
[0], "filter")==0 ){
7019 if( nCmd
<2 ) goto session_syntax_error
;
7021 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
7022 sqlite3_free(pSession
->azFilter
[ii
]);
7024 sqlite3_free(pSession
->azFilter
);
7025 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
7026 pSession
->azFilter
= sqlite3_malloc( nByte
);
7027 if( pSession
->azFilter
==0 ){
7028 raw_printf(stderr
, "Error: out or memory\n");
7031 for(ii
=1; ii
<nCmd
; ii
++){
7032 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
7034 pSession
->nFilter
= ii
-1;
7038 /* .session indirect ?BOOLEAN?
7039 ** Query or set the indirect flag
7041 if( strcmp(azCmd
[0], "indirect")==0 ){
7043 if( nCmd
>2 ) goto session_syntax_error
;
7044 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
7046 ii
= sqlite3session_indirect(pSession
->p
, ii
);
7047 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
7048 pSession
->zName
, ii
);
7053 ** Determine if the session is empty
7055 if( strcmp(azCmd
[0], "isempty")==0 ){
7057 if( nCmd
!=1 ) goto session_syntax_error
;
7059 ii
= sqlite3session_isempty(pSession
->p
);
7060 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
7061 pSession
->zName
, ii
);
7066 ** List all currently open sessions
7068 if( strcmp(azCmd
[0],"list")==0 ){
7069 for(i
=0; i
<p
->nSession
; i
++){
7070 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
7074 /* .session open DB NAME
7075 ** Open a new session called NAME on the attached database DB.
7076 ** DB is normally "main".
7078 if( strcmp(azCmd
[0],"open")==0 ){
7080 if( nCmd
!=3 ) goto session_syntax_error
;
7082 if( zName
[0]==0 ) goto session_syntax_error
;
7083 for(i
=0; i
<p
->nSession
; i
++){
7084 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
7085 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
7086 goto meta_command_exit
;
7089 if( p
->nSession
>=ArraySize(p
->aSession
) ){
7090 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
7091 goto meta_command_exit
;
7093 pSession
= &p
->aSession
[p
->nSession
];
7094 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
7096 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
7098 goto meta_command_exit
;
7100 pSession
->nFilter
= 0;
7101 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
7103 pSession
->zName
= sqlite3_mprintf("%s", zName
);
7105 /* If no command name matches, show a syntax error */
7106 session_syntax_error
:
7112 /* Undocumented commands for internal testing. Subject to change
7113 ** without notice. */
7114 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
7115 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
7117 for(i
=1; i
<nArg
; i
++){
7118 v
= booleanValue(azArg
[i
]);
7119 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
7122 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
7123 int i
; sqlite3_int64 v
;
7124 for(i
=1; i
<nArg
; i
++){
7126 v
= integerValue(azArg
[i
]);
7127 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
7128 utf8_printf(p
->out
, "%s", zBuf
);
7134 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
7135 int bIsInit
= 0; /* True to initialize the SELFTEST table */
7136 int bVerbose
= 0; /* Verbose output */
7137 int bSelftestExists
; /* True if SELFTEST already exists */
7138 int i
, k
; /* Loop counters */
7139 int nTest
= 0; /* Number of tests runs */
7140 int nErr
= 0; /* Number of errors seen */
7141 ShellText str
; /* Answer for a query */
7142 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
7145 for(i
=1; i
<nArg
; i
++){
7146 const char *z
= azArg
[i
];
7147 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7148 if( strcmp(z
,"-init")==0 ){
7151 if( strcmp(z
,"-v")==0 ){
7155 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7156 azArg
[i
], azArg
[0]);
7157 raw_printf(stderr
, "Should be one of: --init -v\n");
7159 goto meta_command_exit
;
7162 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
7164 bSelftestExists
= 0;
7166 bSelftestExists
= 1;
7169 createSelftestTable(p
);
7170 bSelftestExists
= 1;
7173 appendText(&str
, "x", 0);
7174 for(k
=bSelftestExists
; k
>=0; k
--){
7176 rc
= sqlite3_prepare_v2(p
->db
,
7177 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7180 rc
= sqlite3_prepare_v2(p
->db
,
7181 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7182 " (1,'run','PRAGMA integrity_check','ok')",
7186 raw_printf(stderr
, "Error querying the selftest table\n");
7188 sqlite3_finalize(pStmt
);
7189 goto meta_command_exit
;
7191 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
7192 int tno
= sqlite3_column_int(pStmt
, 0);
7193 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
7194 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
7195 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
7199 char *zQuote
= sqlite3_mprintf("%q", zSql
);
7200 printf("%d: %s %s\n", tno
, zOp
, zSql
);
7201 sqlite3_free(zQuote
);
7203 if( strcmp(zOp
,"memo")==0 ){
7204 utf8_printf(p
->out
, "%s\n", zSql
);
7206 if( strcmp(zOp
,"run")==0 ){
7210 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
7213 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
7215 if( rc
|| zErrMsg
){
7218 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
7219 sqlite3_free(zErrMsg
);
7220 }else if( strcmp(zAns
,str
.z
)!=0 ){
7223 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
7224 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
7229 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
7233 } /* End loop over rows of content from SELFTEST */
7234 sqlite3_finalize(pStmt
);
7235 } /* End loop over k */
7237 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
7240 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
7241 if( nArg
<2 || nArg
>3 ){
7242 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
7246 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
7247 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
7250 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
7251 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
7255 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
7256 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
7257 int i
; /* Loop counter */
7258 int bSchema
= 0; /* Also hash the schema */
7259 int bSeparate
= 0; /* Hash each table separately */
7260 int iSize
= 224; /* Hash algorithm to use */
7261 int bDebug
= 0; /* Only show the query that would have run */
7262 sqlite3_stmt
*pStmt
; /* For querying tables names */
7263 char *zSql
; /* SQL to be run */
7264 char *zSep
; /* Separator */
7265 ShellText sSql
; /* Complete SQL for the query to run the hash */
7266 ShellText sQuery
; /* Set of queries used to read all content */
7268 for(i
=1; i
<nArg
; i
++){
7269 const char *z
= azArg
[i
];
7272 if( z
[0]=='-' ) z
++;
7273 if( strcmp(z
,"schema")==0 ){
7276 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
7277 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
7279 iSize
= atoi(&z
[5]);
7281 if( strcmp(z
,"debug")==0 ){
7285 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7286 azArg
[i
], azArg
[0]);
7287 raw_printf(stderr
, "Should be one of: --schema"
7288 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
7290 goto meta_command_exit
;
7293 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7295 goto meta_command_exit
;
7299 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
7303 zSql
= "SELECT lower(name) FROM sqlite_master"
7304 " WHERE type='table' AND coalesce(rootpage,0)>1"
7305 " UNION ALL SELECT 'sqlite_master'"
7306 " ORDER BY 1 collate nocase";
7308 zSql
= "SELECT lower(name) FROM sqlite_master"
7309 " WHERE type='table' AND coalesce(rootpage,0)>1"
7310 " AND name NOT LIKE 'sqlite_%'"
7311 " ORDER BY 1 collate nocase";
7313 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
7316 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
7318 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
7319 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
7320 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
7321 if( strncmp(zTab
, "sqlite_",7)!=0 ){
7322 appendText(&sQuery
,"SELECT * FROM ", 0);
7323 appendText(&sQuery
,zTab
,'"');
7324 appendText(&sQuery
," NOT INDEXED;", 0);
7325 }else if( strcmp(zTab
, "sqlite_master")==0 ){
7326 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7327 " ORDER BY name;", 0);
7328 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
7329 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
7330 " ORDER BY name;", 0);
7331 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
7332 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
7333 " ORDER BY tbl,idx;", 0);
7334 }else if( strcmp(zTab
, "sqlite_stat3")==0
7335 || strcmp(zTab
, "sqlite_stat4")==0 ){
7336 appendText(&sQuery
, "SELECT * FROM ", 0);
7337 appendText(&sQuery
, zTab
, 0);
7338 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
7340 appendText(&sSql
, zSep
, 0);
7341 appendText(&sSql
, sQuery
.z
, '\'');
7343 appendText(&sSql
, ",", 0);
7344 appendText(&sSql
, zTab
, '\'');
7347 sqlite3_finalize(pStmt
);
7349 zSql
= sqlite3_mprintf(
7351 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7352 " FROM [sha3sum$query]",
7355 zSql
= sqlite3_mprintf(
7357 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7358 " FROM [sha3sum$query]",
7364 utf8_printf(p
->out
, "%s\n", zSql
);
7366 shell_exec(p
, zSql
, 0);
7371 #ifndef SQLITE_NOHAVE_SYSTEM
7373 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
7378 raw_printf(stderr
, "Usage: .system COMMAND\n");
7380 goto meta_command_exit
;
7382 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
7383 for(i
=2; i
<nArg
; i
++){
7384 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
7389 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
7391 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
7393 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
7394 static const char *azBool
[] = { "off", "on", "trigger", "full"};
7397 raw_printf(stderr
, "Usage: .show\n");
7399 goto meta_command_exit
;
7401 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
7402 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
7403 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
7404 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
7405 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
7406 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
7407 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
7408 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
7409 output_c_string(p
->out
, p
->nullValue
);
7410 raw_printf(p
->out
, "\n");
7411 utf8_printf(p
->out
,"%12.12s: %s\n","output",
7412 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
7413 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
7414 output_c_string(p
->out
, p
->colSeparator
);
7415 raw_printf(p
->out
, "\n");
7416 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
7417 output_c_string(p
->out
, p
->rowSeparator
);
7418 raw_printf(p
->out
, "\n");
7419 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
7420 utf8_printf(p
->out
, "%12.12s: ", "width");
7421 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
7422 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
7424 raw_printf(p
->out
, "\n");
7425 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
7426 p
->zDbFilename
? p
->zDbFilename
: "");
7429 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
7431 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
7432 }else if( nArg
==1 ){
7433 display_stats(p
->db
, p
, 0);
7435 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
7440 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
7441 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
7442 || strncmp(azArg
[0], "indexes", n
)==0) )
7444 sqlite3_stmt
*pStmt
;
7451 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
7453 sqlite3_finalize(pStmt
);
7454 return shellDatabaseError(p
->db
);
7457 if( nArg
>2 && c
=='i' ){
7458 /* It is an historical accident that the .indexes command shows an error
7459 ** when called with the wrong number of arguments whereas the .tables
7460 ** command does not. */
7461 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
7463 sqlite3_finalize(pStmt
);
7464 goto meta_command_exit
;
7466 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
7467 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
7468 if( zDbName
==0 ) continue;
7469 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
7470 if( sqlite3_stricmp(zDbName
, "main")==0 ){
7471 appendText(&s
, "SELECT name FROM ", 0);
7473 appendText(&s
, "SELECT ", 0);
7474 appendText(&s
, zDbName
, '\'');
7475 appendText(&s
, "||'.'||name FROM ", 0);
7477 appendText(&s
, zDbName
, '"');
7478 appendText(&s
, ".sqlite_master ", 0);
7480 appendText(&s
," WHERE type IN ('table','view')"
7481 " AND name NOT LIKE 'sqlite_%'"
7482 " AND name LIKE ?1", 0);
7484 appendText(&s
," WHERE type='index'"
7485 " AND tbl_name LIKE ?1", 0);
7488 rc
= sqlite3_finalize(pStmt
);
7489 appendText(&s
, " ORDER BY 1", 0);
7490 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
7492 if( rc
) return shellDatabaseError(p
->db
);
7494 /* Run the SQL statement prepared by the above block. Store the results
7495 ** as an array of nul-terminated strings in azResult[]. */
7499 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
7501 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
7503 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
7506 int n2
= nAlloc
*2 + 10;
7507 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
7508 if( azNew
==0 ) shell_out_of_memory();
7512 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7513 if( 0==azResult
[nRow
] ) shell_out_of_memory();
7516 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
7517 rc
= shellDatabaseError(p
->db
);
7520 /* Pretty-print the contents of array azResult[] to the output */
7521 if( rc
==0 && nRow
>0 ){
7522 int len
, maxlen
= 0;
7524 int nPrintCol
, nPrintRow
;
7525 for(i
=0; i
<nRow
; i
++){
7526 len
= strlen30(azResult
[i
]);
7527 if( len
>maxlen
) maxlen
= len
;
7529 nPrintCol
= 80/(maxlen
+2);
7530 if( nPrintCol
<1 ) nPrintCol
= 1;
7531 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
7532 for(i
=0; i
<nPrintRow
; i
++){
7533 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
7534 char *zSp
= j
<nPrintRow
? "" : " ";
7535 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
7536 azResult
[j
] ? azResult
[j
]:"");
7538 raw_printf(p
->out
, "\n");
7542 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
7543 sqlite3_free(azResult
);
7546 /* Begin redirecting output to the file "testcase-out.txt" */
7547 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
7549 p
->out
= output_file_open("testcase-out.txt", 0);
7551 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
7554 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
7556 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
7560 #ifndef SQLITE_UNTESTABLE
7561 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
7562 static const struct {
7563 const char *zCtrlName
; /* Name of a test-control option */
7564 int ctrlCode
; /* Integer code for that option */
7565 const char *zUsage
; /* Usage notes */
7567 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
7568 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
7569 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7570 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7571 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
7572 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7573 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
7574 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
7575 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
7576 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
7578 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
, "" },
7580 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
7581 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
7582 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
7583 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
7584 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
7588 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7591 const char *zCmd
= 0;
7594 zCmd
= nArg
>=2 ? azArg
[1] : "help";
7596 /* The argument can optionally begin with "-" or "--" */
7597 if( zCmd
[0]=='-' && zCmd
[1] ){
7599 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
7602 /* --help lists all test-controls */
7603 if( strcmp(zCmd
,"help")==0 ){
7604 utf8_printf(p
->out
, "Available test-controls:\n");
7605 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7606 utf8_printf(p
->out
, " .testctrl %s %s\n",
7607 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
7610 goto meta_command_exit
;
7613 /* convert testctrl text option to value. allow any unique prefix
7614 ** of the option name, or a numerical value. */
7615 n2
= strlen30(zCmd
);
7616 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7617 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
7619 testctrl
= aCtrl
[i
].ctrlCode
;
7622 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
7623 "Use \".testctrl --help\" for help\n", zCmd
);
7625 goto meta_command_exit
;
7630 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
7631 "Use \".testctrl --help\" for help\n", zCmd
);
7635 /* sqlite3_test_control(int, db, int) */
7636 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
7637 case SQLITE_TESTCTRL_RESERVE
:
7639 int opt
= (int)strtol(azArg
[2], 0, 0);
7640 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
7645 /* sqlite3_test_control(int) */
7646 case SQLITE_TESTCTRL_PRNG_SAVE
:
7647 case SQLITE_TESTCTRL_PRNG_RESTORE
:
7648 case SQLITE_TESTCTRL_PRNG_RESET
:
7649 case SQLITE_TESTCTRL_BYTEORDER
:
7651 rc2
= sqlite3_test_control(testctrl
);
7652 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
7656 /* sqlite3_test_control(int, uint) */
7657 case SQLITE_TESTCTRL_PENDING_BYTE
:
7659 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
7660 rc2
= sqlite3_test_control(testctrl
, opt
);
7665 /* sqlite3_test_control(int, int) */
7666 case SQLITE_TESTCTRL_ASSERT
:
7667 case SQLITE_TESTCTRL_ALWAYS
:
7669 int opt
= booleanValue(azArg
[2]);
7670 rc2
= sqlite3_test_control(testctrl
, opt
);
7675 /* sqlite3_test_control(int, int) */
7676 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
7677 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
7679 int opt
= booleanValue(azArg
[2]);
7680 rc2
= sqlite3_test_control(testctrl
, opt
);
7685 case SQLITE_TESTCTRL_IMPOSTER
:
7687 rc2
= sqlite3_test_control(testctrl
, p
->db
,
7689 integerValue(azArg
[3]),
7690 integerValue(azArg
[4]));
7696 case SQLITE_TESTCTRL_PARSER_COVERAGE
:
7698 sqlite3_test_control(testctrl
, p
->out
);
7704 if( isOk
==0 && iCtrl
>=0 ){
7705 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
7707 }else if( isOk
==1 ){
7708 raw_printf(p
->out
, "%d\n", rc2
);
7709 }else if( isOk
==2 ){
7710 raw_printf(p
->out
, "0x%08x\n", rc2
);
7713 #endif /* !defined(SQLITE_UNTESTABLE) */
7715 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
7717 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
7720 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
7722 enableTimer
= booleanValue(azArg
[1]);
7723 if( enableTimer
&& !HAS_TIMER
){
7724 raw_printf(stderr
, "Error: timer not available on this system.\n");
7728 raw_printf(stderr
, "Usage: .timer on|off\n");
7733 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
7736 raw_printf(stderr
, "Usage: .trace FILE|off\n");
7738 goto meta_command_exit
;
7740 output_file_close(p
->traceOut
);
7741 p
->traceOut
= output_file_open(azArg
[1], 0);
7742 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7743 if( p
->traceOut
==0 ){
7744 sqlite3_trace_v2(p
->db
, 0, 0, 0);
7746 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
7751 #if SQLITE_USER_AUTHENTICATION
7752 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
7754 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
7756 goto meta_command_exit
;
7759 if( strcmp(azArg
[1],"login")==0 ){
7761 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
7763 goto meta_command_exit
;
7765 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]));
7767 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
7770 }else if( strcmp(azArg
[1],"add")==0 ){
7772 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
7774 goto meta_command_exit
;
7776 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7777 booleanValue(azArg
[4]));
7779 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
7782 }else if( strcmp(azArg
[1],"edit")==0 ){
7784 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
7786 goto meta_command_exit
;
7788 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7789 booleanValue(azArg
[4]));
7791 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
7794 }else if( strcmp(azArg
[1],"delete")==0 ){
7796 raw_printf(stderr
, "Usage: .user delete USER\n");
7798 goto meta_command_exit
;
7800 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
7802 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
7806 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
7808 goto meta_command_exit
;
7811 #endif /* SQLITE_USER_AUTHENTICATION */
7813 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
7814 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
7815 sqlite3_libversion(), sqlite3_sourceid());
7816 #if SQLITE_HAVE_ZLIB
7817 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
7819 #define CTIMEOPT_VAL_(opt) #opt
7820 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7821 #if defined(__clang__) && defined(__clang_major__)
7822 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
7823 CTIMEOPT_VAL(__clang_minor__
) "."
7824 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
7825 #elif defined(_MSC_VER)
7826 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
7827 #elif defined(__GNUC__) && defined(__VERSION__)
7828 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
7832 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
7833 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7834 sqlite3_vfs
*pVfs
= 0;
7836 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
7838 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
7839 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7840 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7841 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7846 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
7848 sqlite3_vfs
*pCurrent
= 0;
7850 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
7852 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
7853 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
7854 pVfs
==pCurrent
? " <--- CURRENT" : "");
7855 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7856 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7857 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7859 raw_printf(p
->out
, "-----------------------------------\n");
7864 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
7865 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7868 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
7870 utf8_printf(p
->out
, "%s\n", zVfsName
);
7871 sqlite3_free(zVfsName
);
7876 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7877 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
7878 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
7882 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
7884 assert( nArg
<=ArraySize(azArg
) );
7885 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
7886 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
7891 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
7892 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
7899 if( p
->outCount
==0 ) output_reset(p
);
7905 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7908 static int line_contains_semicolon(const char *z
, int N
){
7910 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
7915 ** Test to see if a line consists entirely of whitespace.
7917 static int _all_whitespace(const char *z
){
7919 if( IsSpace(z
[0]) ) continue;
7920 if( *z
=='/' && z
[1]=='*' ){
7922 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
7923 if( *z
==0 ) return 0;
7927 if( *z
=='-' && z
[1]=='-' ){
7929 while( *z
&& *z
!='\n' ){ z
++; }
7930 if( *z
==0 ) return 1;
7939 ** Return TRUE if the line typed in is an SQL command terminator other
7940 ** than a semi-colon. The SQL Server style "go" command is understood
7941 ** as is the Oracle "/".
7943 static int line_is_command_terminator(const char *zLine
){
7944 while( IsSpace(zLine
[0]) ){ zLine
++; };
7945 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
7946 return 1; /* Oracle */
7948 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
7949 && _all_whitespace(&zLine
[2]) ){
7950 return 1; /* SQL Server */
7956 ** We need a default sqlite3_complete() implementation to use in case
7957 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
7958 ** any arbitrary text is a complete SQL statement. This is not very
7959 ** user-friendly, but it does seem to work.
7961 #ifdef SQLITE_OMIT_COMPLETE
7962 int sqlite3_complete(const char *zSql
){ return 1; }
7966 ** Return true if zSql is a complete SQL statement. Return false if it
7967 ** ends in the middle of a string literal or C-style comment.
7969 static int line_is_complete(char *zSql
, int nSql
){
7971 if( zSql
==0 ) return 1;
7974 rc
= sqlite3_complete(zSql
);
7980 ** Run a single line of SQL. Return the number of errors.
7982 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
7987 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
7989 rc
= shell_exec(p
, zSql
, &zErrMsg
);
7991 if( rc
|| zErrMsg
){
7993 if( in
!=0 || !stdin_is_interactive
){
7994 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
7995 "Error: near line %d:", startline
);
7997 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
8000 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
8001 sqlite3_free(zErrMsg
);
8004 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
8007 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
8008 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
8009 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
8016 ** Read input from *in and process it. If *in==0 then input
8017 ** is interactive - the user is typing it it. Otherwise, input
8018 ** is coming from a file or device. A prompt is issued and history
8019 ** is saved only if input is interactive. An interrupt signal will
8020 ** cause this routine to exit immediately, unless input is interactive.
8022 ** Return the number of errors.
8024 static int process_input(ShellState
*p
, FILE *in
){
8025 char *zLine
= 0; /* A single input line */
8026 char *zSql
= 0; /* Accumulated SQL text */
8027 int nLine
; /* Length of current line */
8028 int nSql
= 0; /* Bytes of zSql[] used */
8029 int nAlloc
= 0; /* Allocated zSql[] space */
8030 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
8031 int rc
; /* Error code */
8032 int errCnt
= 0; /* Number of errors seen */
8033 int lineno
= 0; /* Current line number */
8034 int startline
= 0; /* Line number for start of current input */
8036 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
8038 zLine
= one_input_line(in
, zLine
, nSql
>0);
8041 if( in
==0 && stdin_is_interactive
) printf("\n");
8044 if( seenInterrupt
){
8049 if( nSql
==0 && _all_whitespace(zLine
) ){
8050 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
8053 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
8054 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
8055 if( zLine
[0]=='.' ){
8056 rc
= do_meta_command(zLine
, p
);
8057 if( rc
==2 ){ /* exit requested */
8065 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
8066 memcpy(zLine
,";",2);
8068 nLine
= strlen30(zLine
);
8069 if( nSql
+nLine
+2>=nAlloc
){
8070 nAlloc
= nSql
+nLine
+100;
8071 zSql
= realloc(zSql
, nAlloc
);
8072 if( zSql
==0 ) shell_out_of_memory();
8077 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
8078 assert( nAlloc
>0 && zSql
!=0 );
8079 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
8083 zSql
[nSql
++] = '\n';
8084 memcpy(zSql
+nSql
, zLine
, nLine
+1);
8087 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
8088 && sqlite3_complete(zSql
) ){
8089 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
8097 }else if( nSql
&& _all_whitespace(zSql
) ){
8098 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
8102 if( nSql
&& !_all_whitespace(zSql
) ){
8103 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
8111 ** Return a pathname which is the user's home directory. A
8112 ** 0 return indicates an error of some kind.
8114 static char *find_home_dir(int clearFlag
){
8115 static char *home_dir
= NULL
;
8121 if( home_dir
) return home_dir
;
8123 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8124 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8126 struct passwd
*pwent
;
8127 uid_t uid
= getuid();
8128 if( (pwent
=getpwuid(uid
)) != NULL
) {
8129 home_dir
= pwent
->pw_dir
;
8134 #if defined(_WIN32_WCE)
8135 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8140 #if defined(_WIN32) || defined(WIN32)
8142 home_dir
= getenv("USERPROFILE");
8147 home_dir
= getenv("HOME");
8150 #if defined(_WIN32) || defined(WIN32)
8152 char *zDrive
, *zPath
;
8154 zDrive
= getenv("HOMEDRIVE");
8155 zPath
= getenv("HOMEPATH");
8156 if( zDrive
&& zPath
){
8157 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
8158 home_dir
= malloc( n
);
8159 if( home_dir
==0 ) return 0;
8160 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
8167 #endif /* !_WIN32_WCE */
8170 int n
= strlen30(home_dir
) + 1;
8171 char *z
= malloc( n
);
8172 if( z
) memcpy(z
, home_dir
, n
);
8180 ** Read input from the file given by sqliterc_override. Or if that
8181 ** parameter is NULL, take input from ~/.sqliterc
8183 ** Returns the number of errors.
8185 static void process_sqliterc(
8186 ShellState
*p
, /* Configuration data */
8187 const char *sqliterc_override
/* Name of config file. NULL to use default */
8189 char *home_dir
= NULL
;
8190 const char *sqliterc
= sqliterc_override
;
8194 if (sqliterc
== NULL
) {
8195 home_dir
= find_home_dir(0);
8197 raw_printf(stderr
, "-- warning: cannot find home directory;"
8198 " cannot read ~/.sqliterc\n");
8201 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
8204 in
= fopen(sqliterc
,"rb");
8206 if( stdin_is_interactive
){
8207 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
8209 process_input(p
,in
);
8216 ** Show available command line options
8218 static const char zOptions
[] =
8219 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
8220 " -A ARGS... run \".archive ARGS\" and exit\n"
8222 " -append append the database to the end of the file\n"
8223 " -ascii set output mode to 'ascii'\n"
8224 " -bail stop after hitting an error\n"
8225 " -batch force batch I/O\n"
8226 " -column set output mode to 'column'\n"
8227 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8228 " -csv set output mode to 'csv'\n"
8229 " -echo print commands before execution\n"
8230 " -init FILENAME read/process named file\n"
8231 " -[no]header turn headers on or off\n"
8232 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8233 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8235 " -help show this message\n"
8236 " -html set output mode to HTML\n"
8237 " -interactive force interactive I/O\n"
8238 " -line set output mode to 'line'\n"
8239 " -list set output mode to 'list'\n"
8240 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8241 " -mmap N default mmap size set to N\n"
8242 #ifdef SQLITE_ENABLE_MULTIPLEX
8243 " -multiplex enable the multiplexor VFS\n"
8245 " -newline SEP set output row separator. Default: '\\n'\n"
8246 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8247 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8248 " -quote set output mode to 'quote'\n"
8249 " -readonly open the database read-only\n"
8250 " -separator SEP set output column separator. Default: '|'\n"
8251 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8252 " -sorterref SIZE sorter references threshold size\n"
8254 " -stats print memory stats before each finalize\n"
8255 " -version show SQLite version\n"
8256 " -vfs NAME use NAME as the default VFS\n"
8257 #ifdef SQLITE_ENABLE_VFSTRACE
8258 " -vfstrace enable tracing of all VFS calls\n"
8260 #ifdef SQLITE_HAVE_ZLIB
8261 " -zip open the file as a ZIP Archive\n"
8264 static void usage(int showDetail
){
8266 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8267 "FILENAME is the name of an SQLite database. A new database is created\n"
8268 "if the file does not previously exist.\n", Argv0
);
8270 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
8272 raw_printf(stderr
, "Use the -help option for additional information\n");
8278 ** Internal check: Verify that the SQLite is uninitialized. Print a
8279 ** error message if it is initialized.
8281 static void verify_uninitialized(void){
8282 if( sqlite3_config(-1)==SQLITE_MISUSE
){
8283 utf8_printf(stdout
, "WARNING: attempt to configure SQLite after"
8284 " initialization.\n");
8289 ** Initialize the state information in data
8291 static void main_init(ShellState
*data
) {
8292 memset(data
, 0, sizeof(*data
));
8293 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
8294 data
->autoExplain
= 1;
8295 memcpy(data
->colSeparator
,SEP_Column
, 2);
8296 memcpy(data
->rowSeparator
,SEP_Row
, 2);
8297 data
->showHeader
= 0;
8298 data
->shellFlgs
= SHFLG_Lookaside
;
8299 verify_uninitialized();
8300 sqlite3_config(SQLITE_CONFIG_URI
, 1);
8301 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
8302 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
8303 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
8304 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
8308 ** Output text to the console in a font that attracts extra attention.
8311 static void printBold(const char *zText
){
8312 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
8313 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
8314 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
8315 SetConsoleTextAttribute(out
,
8316 FOREGROUND_RED
|FOREGROUND_INTENSITY
8318 printf("%s", zText
);
8319 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
8322 static void printBold(const char *zText
){
8323 printf("\033[1m%s\033[0m", zText
);
8328 ** Get the argument to an --option. Throw an error and die if no argument
8331 static char *cmdline_option_value(int argc
, char **argv
, int i
){
8333 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
8334 argv
[0], argv
[argc
-1]);
8340 #ifndef SQLITE_SHELL_IS_UTF8
8341 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8342 # define SQLITE_SHELL_IS_UTF8 (0)
8344 # define SQLITE_SHELL_IS_UTF8 (1)
8348 #if SQLITE_SHELL_IS_UTF8
8349 int SQLITE_CDECL
main(int argc
, char **argv
){
8351 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
8356 const char *zInitFile
= 0;
8359 int warnInmemoryDb
= 0;
8363 const char *zVfs
= 0; /* Value of -vfs command-line option */
8364 #if !SQLITE_SHELL_IS_UTF8
8365 char **argvToFree
= 0;
8369 setBinaryMode(stdin
, 0);
8370 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
8371 stdin_is_interactive
= isatty(0);
8372 stdout_is_console
= isatty(1);
8374 #if !defined(_WIN32_WCE)
8375 if( getenv("SQLITE_DEBUG_BREAK") ){
8376 if( isatty(0) && isatty(2) ){
8378 "attach debugger to process %d and press any key to continue.\n",
8382 #if defined(_WIN32) || defined(WIN32)
8384 #elif defined(SIGTRAP)
8391 #if USE_SYSTEM_SQLITE+0!=1
8392 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
8393 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
8394 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
8400 /* On Windows, we must translate command-line arguments into UTF-8.
8401 ** The SQLite memory allocator subsystem has to be enabled in order to
8402 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8403 ** subsequent sqlite3_config() calls will work. So copy all results into
8404 ** memory that does not come from the SQLite memory allocator.
8406 #if !SQLITE_SHELL_IS_UTF8
8407 sqlite3_initialize();
8408 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
8410 argv
= argvToFree
+ argc
;
8411 if( argv
==0 ) shell_out_of_memory();
8412 for(i
=0; i
<argc
; i
++){
8413 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
8415 if( z
==0 ) shell_out_of_memory();
8417 argv
[i
] = malloc( n
+1 );
8418 if( argv
[i
]==0 ) shell_out_of_memory();
8419 memcpy(argv
[i
], z
, n
+1);
8420 argvToFree
[i
] = argv
[i
];
8426 assert( argc
>=1 && argv
&& argv
[0] );
8429 /* Make sure we have a valid signal handler early, before anything
8433 signal(SIGINT
, interrupt_handler
);
8434 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8435 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
8438 #ifdef SQLITE_SHELL_DBNAME_PROC
8440 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8441 ** of a C-function that will provide the name of the database file. Use
8442 ** this compile-time option to embed this shell program in larger
8444 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8445 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
8450 /* Do an initial pass through the command-line argument to locate
8451 ** the name of the database file, the name of the initialization file,
8452 ** the size of the alternative malloc heap,
8453 ** and the first command to execute.
8455 verify_uninitialized();
8456 for(i
=1; i
<argc
; i
++){
8460 if( data
.zDbFilename
==0 ){
8461 data
.zDbFilename
= z
;
8463 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8464 ** mean that nothing is read from stdin */
8467 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
8468 if( azCmd
==0 ) shell_out_of_memory();
8472 if( z
[1]=='-' ) z
++;
8473 if( strcmp(z
,"-separator")==0
8474 || strcmp(z
,"-nullvalue")==0
8475 || strcmp(z
,"-newline")==0
8476 || strcmp(z
,"-cmd")==0
8478 (void)cmdline_option_value(argc
, argv
, ++i
);
8479 }else if( strcmp(z
,"-init")==0 ){
8480 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
8481 }else if( strcmp(z
,"-batch")==0 ){
8482 /* Need to check for batch mode here to so we can avoid printing
8483 ** informational messages (like from process_sqliterc) before
8484 ** we do the actual processing of arguments later in a second pass.
8486 stdin_is_interactive
= 0;
8487 }else if( strcmp(z
,"-heap")==0 ){
8488 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8490 sqlite3_int64 szHeap
;
8492 zSize
= cmdline_option_value(argc
, argv
, ++i
);
8493 szHeap
= integerValue(zSize
);
8494 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
8495 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
8497 (void)cmdline_option_value(argc
, argv
, ++i
);
8499 }else if( strcmp(z
,"-pagecache")==0 ){
8501 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8502 if( sz
>70000 ) sz
= 70000;
8504 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8505 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
8506 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
8507 data
.shellFlgs
|= SHFLG_Pagecache
;
8508 }else if( strcmp(z
,"-lookaside")==0 ){
8510 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8512 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8514 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
8515 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
8516 #ifdef SQLITE_ENABLE_VFSTRACE
8517 }else if( strcmp(z
,"-vfstrace")==0 ){
8518 extern int vfstrace_register(
8519 const char *zTraceName
,
8520 const char *zOldVfsName
,
8521 int (*xOut
)(const char*,void*),
8525 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
8527 #ifdef SQLITE_ENABLE_MULTIPLEX
8528 }else if( strcmp(z
,"-multiplex")==0 ){
8529 extern int sqlite3_multiple_initialize(const char*,int);
8530 sqlite3_multiplex_initialize(0, 1);
8532 }else if( strcmp(z
,"-mmap")==0 ){
8533 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8534 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
8535 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8536 }else if( strcmp(z
,"-sorterref")==0 ){
8537 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8538 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
8540 }else if( strcmp(z
,"-vfs")==0 ){
8541 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
8542 #ifdef SQLITE_HAVE_ZLIB
8543 }else if( strcmp(z
,"-zip")==0 ){
8544 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8546 }else if( strcmp(z
,"-append")==0 ){
8547 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8548 }else if( strcmp(z
,"-readonly")==0 ){
8549 data
.openMode
= SHELL_OPEN_READONLY
;
8550 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8551 }else if( strncmp(z
, "-A",2)==0 ){
8552 /* All remaining command-line arguments are passed to the ".archive"
8553 ** command, so ignore them */
8558 verify_uninitialized();
8561 #ifdef SQLITE_SHELL_INIT_PROC
8563 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8564 ** of a C-function that will perform initialization actions on SQLite that
8565 ** occur just before or after sqlite3_initialize(). Use this compile-time
8566 ** option to embed this shell program in larger applications. */
8567 extern void SQLITE_SHELL_INIT_PROC(void);
8568 SQLITE_SHELL_INIT_PROC();
8571 /* All the sqlite3_config() calls have now been made. So it is safe
8572 ** to call sqlite3_initialize() and process any command line -vfs option. */
8573 sqlite3_initialize();
8577 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
8579 sqlite3_vfs_register(pVfs
, 1);
8581 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
8586 if( data
.zDbFilename
==0 ){
8587 #ifndef SQLITE_OMIT_MEMORYDB
8588 data
.zDbFilename
= ":memory:";
8589 warnInmemoryDb
= argc
==1;
8591 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
8596 sqlite3_appendvfs_init(0,0,0);
8598 /* Go ahead and open the database file if it already exists. If the
8599 ** file does not exist, delay opening it. This prevents empty database
8600 ** files from being created if a user mistypes the database name argument
8601 ** to the sqlite command-line tool.
8603 if( access(data
.zDbFilename
, 0)==0 ){
8607 /* Process the initialization file if there is one. If no -init option
8608 ** is given on the command line, look for a file named ~/.sqliterc and
8609 ** try to process it.
8611 process_sqliterc(&data
,zInitFile
);
8613 /* Make a second pass through the command-line argument and set
8614 ** options. This second pass is delayed until after the initialization
8615 ** file is processed so that the command-line arguments will override
8616 ** settings in the initialization file.
8618 for(i
=1; i
<argc
; i
++){
8620 if( z
[0]!='-' ) continue;
8621 if( z
[1]=='-' ){ z
++; }
8622 if( strcmp(z
,"-init")==0 ){
8624 }else if( strcmp(z
,"-html")==0 ){
8625 data
.mode
= MODE_Html
;
8626 }else if( strcmp(z
,"-list")==0 ){
8627 data
.mode
= MODE_List
;
8628 }else if( strcmp(z
,"-quote")==0 ){
8629 data
.mode
= MODE_Quote
;
8630 }else if( strcmp(z
,"-line")==0 ){
8631 data
.mode
= MODE_Line
;
8632 }else if( strcmp(z
,"-column")==0 ){
8633 data
.mode
= MODE_Column
;
8634 }else if( strcmp(z
,"-csv")==0 ){
8635 data
.mode
= MODE_Csv
;
8636 memcpy(data
.colSeparator
,",",2);
8637 #ifdef SQLITE_HAVE_ZLIB
8638 }else if( strcmp(z
,"-zip")==0 ){
8639 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8641 }else if( strcmp(z
,"-append")==0 ){
8642 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8643 }else if( strcmp(z
,"-readonly")==0 ){
8644 data
.openMode
= SHELL_OPEN_READONLY
;
8645 }else if( strcmp(z
,"-ascii")==0 ){
8646 data
.mode
= MODE_Ascii
;
8647 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8649 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8651 }else if( strcmp(z
,"-separator")==0 ){
8652 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8653 "%s",cmdline_option_value(argc
,argv
,++i
));
8654 }else if( strcmp(z
,"-newline")==0 ){
8655 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8656 "%s",cmdline_option_value(argc
,argv
,++i
));
8657 }else if( strcmp(z
,"-nullvalue")==0 ){
8658 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
8659 "%s",cmdline_option_value(argc
,argv
,++i
));
8660 }else if( strcmp(z
,"-header")==0 ){
8661 data
.showHeader
= 1;
8662 }else if( strcmp(z
,"-noheader")==0 ){
8663 data
.showHeader
= 0;
8664 }else if( strcmp(z
,"-echo")==0 ){
8665 ShellSetFlag(&data
, SHFLG_Echo
);
8666 }else if( strcmp(z
,"-eqp")==0 ){
8667 data
.autoEQP
= AUTOEQP_on
;
8668 }else if( strcmp(z
,"-eqpfull")==0 ){
8669 data
.autoEQP
= AUTOEQP_full
;
8670 }else if( strcmp(z
,"-stats")==0 ){
8672 }else if( strcmp(z
,"-scanstats")==0 ){
8673 data
.scanstatsOn
= 1;
8674 }else if( strcmp(z
,"-backslash")==0 ){
8675 /* Undocumented command-line option: -backslash
8676 ** Causes C-style backslash escapes to be evaluated in SQL statements
8677 ** prior to sending the SQL into SQLite. Useful for injecting
8678 ** crazy bytes in the middle of SQL statements for testing and debugging.
8680 ShellSetFlag(&data
, SHFLG_Backslash
);
8681 }else if( strcmp(z
,"-bail")==0 ){
8683 }else if( strcmp(z
,"-version")==0 ){
8684 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8686 }else if( strcmp(z
,"-interactive")==0 ){
8687 stdin_is_interactive
= 1;
8688 }else if( strcmp(z
,"-batch")==0 ){
8689 stdin_is_interactive
= 0;
8690 }else if( strcmp(z
,"-heap")==0 ){
8692 }else if( strcmp(z
,"-pagecache")==0 ){
8694 }else if( strcmp(z
,"-lookaside")==0 ){
8696 }else if( strcmp(z
,"-mmap")==0 ){
8698 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8699 }else if( strcmp(z
,"-sorterref")==0 ){
8702 }else if( strcmp(z
,"-vfs")==0 ){
8704 #ifdef SQLITE_ENABLE_VFSTRACE
8705 }else if( strcmp(z
,"-vfstrace")==0 ){
8708 #ifdef SQLITE_ENABLE_MULTIPLEX
8709 }else if( strcmp(z
,"-multiplex")==0 ){
8712 }else if( strcmp(z
,"-help")==0 ){
8714 }else if( strcmp(z
,"-cmd")==0 ){
8715 /* Run commands that follow -cmd first and separately from commands
8716 ** that simply appear on the command-line. This seems goofy. It would
8717 ** be better if all commands ran in the order that they appear. But
8718 ** we retain the goofy behavior for historical compatibility. */
8719 if( i
==argc
-1 ) break;
8720 z
= cmdline_option_value(argc
,argv
,++i
);
8722 rc
= do_meta_command(z
, &data
);
8723 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
8726 rc
= shell_exec(&data
, z
, &zErrMsg
);
8728 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8729 if( bail_on_error
) return rc
!=0 ? rc
: 1;
8731 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
8732 if( bail_on_error
) return rc
;
8735 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8736 }else if( strncmp(z
, "-A", 2)==0 ){
8738 utf8_printf(stderr
, "Error: cannot mix regular SQL or dot-commands"
8739 " with \"%s\"\n", z
);
8742 open_db(&data
, OPEN_DB_ZIPFILE
);
8745 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
8747 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
8753 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
8754 raw_printf(stderr
,"Use -help for a list of options.\n");
8757 data
.cMode
= data
.mode
;
8761 /* Run all arguments that do not begin with '-' as if they were separate
8762 ** command-line inputs, except for the argToSkip argument which contains
8763 ** the database filename.
8765 for(i
=0; i
<nCmd
; i
++){
8766 if( azCmd
[i
][0]=='.' ){
8767 rc
= do_meta_command(azCmd
[i
], &data
);
8768 if( rc
) return rc
==2 ? 0 : rc
;
8771 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
8773 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8774 return rc
!=0 ? rc
: 1;
8776 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
8783 /* Run commands received from standard input
8785 if( stdin_is_interactive
){
8790 /* BEGIN SQLCIPHER */
8791 #ifdef SQLITE_HAS_CODEC
8792 "SQLCipher version %s %.19s\n" /*extra-version-info*/
8794 "SQLite version %s %.19s\n" /*extra-version-info*/
8797 "Enter \".help\" for usage hints.\n",
8798 sqlite3_libversion(), sqlite3_sourceid()
8800 if( warnInmemoryDb
){
8801 printf("Connected to a ");
8802 printBold("transient in-memory database");
8803 printf(".\nUse \".open FILENAME\" to reopen on a "
8804 "persistent database.\n");
8806 zHome
= find_home_dir(0);
8808 nHistory
= strlen30(zHome
) + 20;
8809 if( (zHistory
= malloc(nHistory
))!=0 ){
8810 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
8813 if( zHistory
){ shell_read_history(zHistory
); }
8814 #if HAVE_READLINE || HAVE_EDITLINE
8815 rl_attempted_completion_function
= readline_completion
;
8816 #elif HAVE_LINENOISE
8817 linenoiseSetCompletionCallback(linenoise_completion
);
8819 rc
= process_input(&data
, 0);
8821 shell_stifle_history(2000);
8822 shell_write_history(zHistory
);
8826 rc
= process_input(&data
, stdin
);
8829 set_table_name(&data
, 0);
8831 session_close_all(&data
);
8834 sqlite3_free(data
.zFreeOnClose
);
8836 output_reset(&data
);
8838 clearTempFile(&data
);
8839 #if !SQLITE_SHELL_IS_UTF8
8840 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
8843 /* Clear the global data structure so that valgrind will detect memory
8845 memset(&data
, 0, sizeof(data
));