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 # if defined(__MINGW32__)
83 # define DIRENT dirent
85 # define S_ISLNK(mode) (0)
89 #include <sys/types.h>
93 # include <readline/readline.h>
94 # include <readline/history.h>
98 # include <editline/readline.h>
101 #if HAVE_EDITLINE || HAVE_READLINE
103 # define shell_add_history(X) add_history(X)
104 # define shell_read_history(X) read_history(X)
105 # define shell_write_history(X) write_history(X)
106 # define shell_stifle_history(X) stifle_history(X)
107 # define shell_readline(X) readline(X)
111 # include "linenoise.h"
112 # define shell_add_history(X) linenoiseHistoryAdd(X)
113 # define shell_read_history(X) linenoiseHistoryLoad(X)
114 # define shell_write_history(X) linenoiseHistorySave(X)
115 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
116 # define shell_readline(X) linenoise(X)
120 # define shell_read_history(X)
121 # define shell_write_history(X)
122 # define shell_stifle_history(X)
124 # define SHELL_USE_LOCAL_GETLINE 1
128 #if defined(_WIN32) || defined(WIN32)
131 # define isatty(h) _isatty(h)
133 # define access(f,m) _access((f),(m))
136 # define unlink _unlink
139 # define popen _popen
141 # define pclose _pclose
143 /* Make sure isatty() has a prototype. */
144 extern int isatty(int);
146 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
147 /* popen and pclose are not C89 functions and so are
148 ** sometimes omitted from the <stdio.h> header */
149 extern FILE *popen(const char*,const char*);
150 extern int pclose(FILE*);
152 # define SQLITE_OMIT_POPEN 1
156 #if defined(_WIN32_WCE)
157 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
158 * thus we always assume that we have a console. That can be
159 * overridden with the -batch command line option.
164 /* ctype macros that work with signed characters */
165 #define IsSpace(X) isspace((unsigned char)X)
166 #define IsDigit(X) isdigit((unsigned char)X)
167 #define ToLower(X) (char)tolower((unsigned char)X)
169 #if defined(_WIN32) || defined(WIN32)
172 /* string conversion routines only needed on Win32 */
173 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
174 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
175 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
176 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
179 /* On Windows, we normally run with output mode of TEXT so that \n characters
180 ** are automatically translated into \r\n. However, this behavior needs
181 ** to be disabled in some cases (ex: when generating CSV output and when
182 ** rendering quoted strings that contain \n characters). The following
183 ** routines take care of that.
185 #if defined(_WIN32) || defined(WIN32)
186 static void setBinaryMode(FILE *file
, int isOutput
){
187 if( isOutput
) fflush(file
);
188 _setmode(_fileno(file
), _O_BINARY
);
190 static void setTextMode(FILE *file
, int isOutput
){
191 if( isOutput
) fflush(file
);
192 _setmode(_fileno(file
), _O_TEXT
);
195 # define setBinaryMode(X,Y)
196 # define setTextMode(X,Y)
200 /* True if the timer is enabled */
201 static int enableTimer
= 0;
203 /* Return the current wall-clock time */
204 static sqlite3_int64
timeOfDay(void){
205 static sqlite3_vfs
*clockVfs
= 0;
207 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
208 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
209 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
212 clockVfs
->xCurrentTime(clockVfs
, &r
);
213 t
= (sqlite3_int64
)(r
*86400000.0);
218 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
219 #include <sys/time.h>
220 #include <sys/resource.h>
222 /* VxWorks does not support getrusage() as far as we can determine */
223 #if defined(_WRS_KERNEL) || defined(__RTP__)
225 struct timeval ru_utime
; /* user CPU time used */
226 struct timeval ru_stime
; /* system CPU time used */
228 #define getrusage(A,B) memset(B,0,sizeof(*B))
231 /* Saved resource information for the beginning of an operation */
232 static struct rusage sBegin
; /* CPU time at start */
233 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
236 ** Begin timing an operation
238 static void beginTimer(void){
240 getrusage(RUSAGE_SELF
, &sBegin
);
241 iBegin
= timeOfDay();
245 /* Return the difference of two time_structs in seconds */
246 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
247 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
248 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
252 ** Print the timing results.
254 static void endTimer(void){
256 sqlite3_int64 iEnd
= timeOfDay();
258 getrusage(RUSAGE_SELF
, &sEnd
);
259 printf("Run Time: real %.3f user %f sys %f\n",
260 (iEnd
- iBegin
)*0.001,
261 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
262 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
266 #define BEGIN_TIMER beginTimer()
267 #define END_TIMER endTimer()
270 #elif (defined(_WIN32) || defined(WIN32))
272 /* Saved resource information for the beginning of an operation */
273 static HANDLE hProcess
;
274 static FILETIME ftKernelBegin
;
275 static FILETIME ftUserBegin
;
276 static sqlite3_int64 ftWallBegin
;
277 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
278 LPFILETIME
, LPFILETIME
);
279 static GETPROCTIMES getProcessTimesAddr
= NULL
;
282 ** Check to see if we have timer support. Return 1 if necessary
283 ** support found (or found previously).
285 static int hasTimer(void){
286 if( getProcessTimesAddr
){
289 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
290 ** versions. See if the version we are running on has it, and if it
291 ** does, save off a pointer to it and the current process handle.
293 hProcess
= GetCurrentProcess();
295 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
296 if( NULL
!= hinstLib
){
297 getProcessTimesAddr
=
298 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
299 if( NULL
!= getProcessTimesAddr
){
302 FreeLibrary(hinstLib
);
310 ** Begin timing an operation
312 static void beginTimer(void){
313 if( enableTimer
&& getProcessTimesAddr
){
314 FILETIME ftCreation
, ftExit
;
315 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
316 &ftKernelBegin
,&ftUserBegin
);
317 ftWallBegin
= timeOfDay();
321 /* Return the difference of two FILETIME structs in seconds */
322 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
323 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
324 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
325 return (double) ((i64End
- i64Start
) / 10000000.0);
329 ** Print the timing results.
331 static void endTimer(void){
332 if( enableTimer
&& getProcessTimesAddr
){
333 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
334 sqlite3_int64 ftWallEnd
= timeOfDay();
335 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
336 printf("Run Time: real %.3f user %f sys %f\n",
337 (ftWallEnd
- ftWallBegin
)*0.001,
338 timeDiff(&ftUserBegin
, &ftUserEnd
),
339 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
343 #define BEGIN_TIMER beginTimer()
344 #define END_TIMER endTimer()
345 #define HAS_TIMER hasTimer()
354 ** Used to prevent warnings about unused parameters
356 #define UNUSED_PARAMETER(x) (void)(x)
359 ** Number of elements in an array
361 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
364 ** If the following flag is set, then command execution stops
365 ** at an error if we are not interactive.
367 static int bail_on_error
= 0;
370 ** Threat stdin as an interactive input if the following variable
371 ** is true. Otherwise, assume stdin is connected to a file or pipe.
373 static int stdin_is_interactive
= 1;
376 ** On Windows systems we have to know if standard output is a console
377 ** in order to translate UTF-8 into MBCS. The following variable is
378 ** true if translation is required.
380 static int stdout_is_console
= 1;
383 ** The following is the open SQLite database. We make a pointer
384 ** to this database a static variable so that it can be accessed
385 ** by the SIGINT handler to interrupt database processing.
387 static sqlite3
*globalDb
= 0;
390 ** True if an interrupt (Control-C) has been received.
392 static volatile int seenInterrupt
= 0;
395 ** This is the name of our program. It is set in main(), used
396 ** in a number of other places, mostly for error messages.
401 ** Prompt strings. Initialized in main. Settable with
402 ** .prompt main continue
404 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
405 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
408 ** Render output like fprintf(). Except, if the output is going to the
409 ** console and if this is running on a Windows machine, translate the
410 ** output from UTF-8 into MBCS.
412 #if defined(_WIN32) || defined(WIN32)
413 void utf8_printf(FILE *out
, const char *zFormat
, ...){
415 va_start(ap
, zFormat
);
416 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
417 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
418 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
423 vfprintf(out
, zFormat
, ap
);
427 #elif !defined(utf8_printf)
428 # define utf8_printf fprintf
432 ** Render output like fprintf(). This should not be used on anything that
433 ** includes string formatting (e.g. "%s").
435 #if !defined(raw_printf)
436 # define raw_printf fprintf
439 /* Indicate out-of-memory and exit. */
440 static void shell_out_of_memory(void){
441 raw_printf(stderr
,"Error: out of memory\n");
446 ** Write I/O traces to the following stream.
448 #ifdef SQLITE_ENABLE_IOTRACE
449 static FILE *iotrace
= 0;
453 ** This routine works like printf in that its first argument is a
454 ** format string and subsequent arguments are values to be substituted
455 ** in place of % fields. The result of formatting this string
456 ** is written to iotrace.
458 #ifdef SQLITE_ENABLE_IOTRACE
459 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
462 if( iotrace
==0 ) return;
463 va_start(ap
, zFormat
);
464 z
= sqlite3_vmprintf(zFormat
, ap
);
466 utf8_printf(iotrace
, "%s", z
);
472 ** Output string zUtf to stream pOut as w characters. If w is negative,
473 ** then right-justify the text. W is the width in UTF-8 characters, not
474 ** in bytes. This is different from the %*.*s specification in printf
475 ** since with %*.*s the width is measured in bytes, not characters.
477 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
480 int aw
= w
<0 ? -w
: w
;
482 if( aw
>(int)sizeof(zBuf
)/3 ) aw
= (int)sizeof(zBuf
)/3;
483 for(i
=n
=0; zUtf
[i
]; i
++){
484 if( (zUtf
[i
]&0xc0)!=0x80 ){
487 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
493 utf8_printf(pOut
, "%.*s", i
, zUtf
);
495 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
497 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
503 ** Determines if a string is a number of not.
505 static int isNumber(const char *z
, int *realnum
){
506 if( *z
=='-' || *z
=='+' ) z
++;
511 if( realnum
) *realnum
= 0;
512 while( IsDigit(*z
) ){ z
++; }
515 if( !IsDigit(*z
) ) return 0;
516 while( IsDigit(*z
) ){ z
++; }
517 if( realnum
) *realnum
= 1;
519 if( *z
=='e' || *z
=='E' ){
521 if( *z
=='+' || *z
=='-' ) z
++;
522 if( !IsDigit(*z
) ) return 0;
523 while( IsDigit(*z
) ){ z
++; }
524 if( realnum
) *realnum
= 1;
530 ** Compute a string length that is limited to what can be stored in
531 ** lower 30 bits of a 32-bit signed integer.
533 static int strlen30(const char *z
){
535 while( *z2
){ z2
++; }
536 return 0x3fffffff & (int)(z2
- z
);
540 ** Return the length of a string in characters. Multibyte UTF8 characters
541 ** count as a single character.
543 static int strlenChar(const char *z
){
546 if( (0xc0&*(z
++))!=0x80 ) n
++;
552 ** This routine reads a line of text from FILE in, stores
553 ** the text in memory obtained from malloc() and returns a pointer
554 ** to the text. NULL is returned at end of file, or if malloc()
557 ** If zLine is not NULL then it is a malloced buffer returned from
558 ** a previous call to this routine that may be reused.
560 static char *local_getline(char *zLine
, FILE *in
){
561 int nLine
= zLine
==0 ? 0 : 100;
566 nLine
= nLine
*2 + 100;
567 zLine
= realloc(zLine
, nLine
);
568 if( zLine
==0 ) return 0;
570 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
578 while( zLine
[n
] ) n
++;
579 if( n
>0 && zLine
[n
-1]=='\n' ){
581 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
586 #if defined(_WIN32) || defined(WIN32)
587 /* For interactive input on Windows systems, translate the
588 ** multi-byte characterset characters into UTF-8. */
589 if( stdin_is_interactive
&& in
==stdin
){
590 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
592 int nTrans
= strlen30(zTrans
)+1;
594 zLine
= realloc(zLine
, nTrans
);
596 sqlite3_free(zTrans
);
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 if( zResult
&& *zResult
) shell_add_history(zResult
);
644 ** Return the value of a hexadecimal digit. Return -1 if the input
645 ** is not a hex digit.
647 static int hexDigitValue(char c
){
648 if( c
>='0' && c
<='9' ) return c
- '0';
649 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
650 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
655 ** Interpret zArg as an integer value, possibly with suffixes.
657 static sqlite3_int64
integerValue(const char *zArg
){
659 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
661 { "MiB", 1024*1024 },
662 { "GiB", 1024*1024*1024 },
665 { "GB", 1000000000 },
675 }else if( zArg
[0]=='+' ){
678 if( zArg
[0]=='0' && zArg
[1]=='x' ){
681 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
686 while( IsDigit(zArg
[0]) ){
687 v
= v
*10 + zArg
[0] - '0';
691 for(i
=0; i
<ArraySize(aMult
); i
++){
692 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
697 return isNeg
? -v
: v
;
701 ** A variable length string to which one can append text.
703 typedef struct ShellText ShellText
;
711 ** Initialize and destroy a ShellText object
713 static void initText(ShellText
*p
){
714 memset(p
, 0, sizeof(*p
));
716 static void freeText(ShellText
*p
){
721 /* zIn is either a pointer to a NULL-terminated string in memory obtained
722 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
723 ** added to zIn, and the result returned in memory obtained from malloc().
724 ** zIn, if it was not NULL, is freed.
726 ** If the third argument, quote, is not '\0', then it is used as a
727 ** quote character for zAppend.
729 static void appendText(ShellText
*p
, char const *zAppend
, char quote
){
732 int nAppend
= strlen30(zAppend
);
734 len
= nAppend
+p
->n
+1;
737 for(i
=0; i
<nAppend
; i
++){
738 if( zAppend
[i
]==quote
) len
++;
742 if( p
->n
+len
>=p
->nAlloc
){
743 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
744 p
->z
= realloc(p
->z
, p
->nAlloc
);
746 memset(p
, 0, sizeof(*p
));
752 char *zCsr
= p
->z
+p
->n
;
754 for(i
=0; i
<nAppend
; i
++){
755 *zCsr
++ = zAppend
[i
];
756 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
759 p
->n
= (int)(zCsr
- p
->z
);
762 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
769 ** Attempt to determine if identifier zName needs to be quoted, either
770 ** because it contains non-alphanumeric characters, or because it is an
771 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
772 ** that quoting is required.
774 ** Return '"' if quoting is required. Return 0 if no quoting is required.
776 static char quoteChar(const char *zName
){
778 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
779 for(i
=0; zName
[i
]; i
++){
780 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
782 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
786 ** Construct a fake object name and column list to describe the structure
787 ** of the view, virtual table, or table valued function zSchema.zName.
789 static char *shellFakeSchema(
790 sqlite3
*db
, /* The database connection containing the vtab */
791 const char *zSchema
, /* Schema of the database holding the vtab */
792 const char *zName
/* The name of the virtual table */
794 sqlite3_stmt
*pStmt
= 0;
801 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802 zSchema
? zSchema
: "main", zName
);
803 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
807 cQuote
= quoteChar(zSchema
);
808 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
809 appendText(&s
, zSchema
, cQuote
);
810 appendText(&s
, ".", 0);
812 cQuote
= quoteChar(zName
);
813 appendText(&s
, zName
, cQuote
);
814 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
815 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
817 appendText(&s
, zDiv
, 0);
819 cQuote
= quoteChar(zCol
);
820 appendText(&s
, zCol
, cQuote
);
822 appendText(&s
, ")", 0);
823 sqlite3_finalize(pStmt
);
832 ** SQL function: shell_module_schema(X)
834 ** Return a fake schema for the table-valued function or eponymous virtual
837 static void shellModuleSchema(
838 sqlite3_context
*pCtx
,
840 sqlite3_value
**apVal
842 const char *zName
= (const char*)sqlite3_value_text(apVal
[0]);
843 char *zFake
= shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
);
844 UNUSED_PARAMETER(nVal
);
846 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
853 ** SQL function: shell_add_schema(S,X)
855 ** Add the schema name X to the CREATE statement in S and return the result.
858 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
863 ** CREATE UNIQUE INDEX
866 ** CREATE VIRTUAL TABLE
868 ** This UDF is used by the .schema command to insert the schema name of
869 ** attached databases into the middle of the sqlite_master.sql field.
871 static void shellAddSchemaName(
872 sqlite3_context
*pCtx
,
874 sqlite3_value
**apVal
876 static const char *aPrefix
[] = {
885 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
886 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
887 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
888 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
889 UNUSED_PARAMETER(nVal
);
890 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
891 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
892 int n
= strlen30(aPrefix
[i
]);
893 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
897 char cQuote
= quoteChar(zSchema
);
898 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
899 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
901 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
905 && aPrefix
[i
][0]=='V'
906 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
909 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
911 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
916 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
922 sqlite3_result_value(pCtx
, apVal
[0]);
926 ** The source code for several run-time loadable extensions is inserted
927 ** below by the ../tool/mkshellc.tcl script. Before processing that included
928 ** code, we need to override some macros to make the included program code
929 ** work here in the middle of this regular program.
931 #define SQLITE_EXTENSION_INIT1
932 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
934 #if defined(_WIN32) && defined(_MSC_VER)
935 INCLUDE test_windirent
.h
936 INCLUDE test_windirent
.c
937 #define dirent DIRENT
939 INCLUDE
../ext
/misc
/shathree
.c
940 INCLUDE
../ext
/misc
/fileio
.c
941 INCLUDE
../ext
/misc
/completion
.c
942 INCLUDE
../ext
/misc
/appendvfs
.c
943 #ifdef SQLITE_HAVE_ZLIB
944 INCLUDE
../ext
/misc
/zipfile
.c
945 INCLUDE
../ext
/misc
/sqlar
.c
947 INCLUDE
../ext
/expert
/sqlite3expert
.h
948 INCLUDE
../ext
/expert
/sqlite3expert
.c
950 #if defined(SQLITE_ENABLE_SESSION)
952 ** State information for a single open session
954 typedef struct OpenSession OpenSession
;
956 char *zName
; /* Symbolic name for this session */
957 int nFilter
; /* Number of xFilter rejection GLOB patterns */
958 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
959 sqlite3_session
*p
; /* The open session */
964 ** Shell output mode information from before ".explain on",
965 ** saved so that it can be restored by ".explain off"
967 typedef struct SavedModeInfo SavedModeInfo
;
968 struct SavedModeInfo
{
969 int valid
; /* Is there legit data in here? */
970 int mode
; /* Mode prior to ".explain on" */
971 int showHeader
; /* The ".header" setting prior to ".explain on" */
972 int colWidth
[100]; /* Column widths prior to ".explain on" */
975 typedef struct ExpertInfo ExpertInfo
;
977 sqlite3expert
*pExpert
;
981 /* A single line in the EQP output */
982 typedef struct EQPGraphRow EQPGraphRow
;
984 int iEqpId
; /* ID for this row */
985 int iParentId
; /* ID of the parent row */
986 EQPGraphRow
*pNext
; /* Next row in sequence */
987 char zText
[1]; /* Text to display for this row */
990 /* All EQP output is collected into an instance of the following */
991 typedef struct EQPGraph EQPGraph
;
993 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
994 EQPGraphRow
*pLast
; /* Last element of the pRow list */
995 char zPrefix
[100]; /* Graph prefix */
999 ** State information about the database connection is contained in an
1000 ** instance of the following structure.
1002 typedef struct ShellState ShellState
;
1004 sqlite3
*db
; /* The database */
1005 u8 autoExplain
; /* Automatically turn on .explain mode */
1006 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1007 u8 autoEQPtest
; /* autoEQP is in test mode */
1008 u8 statsOn
; /* True to display memory stats before each finalize */
1009 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1010 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1011 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1012 u8 nEqpLevel
; /* Depth of the EQP output graph */
1013 unsigned mEqpLines
; /* Mask of veritical lines in the EQP output graph */
1014 int outCount
; /* Revert to stdout when reaching zero */
1015 int cnt
; /* Number of records displayed so far */
1016 FILE *out
; /* Write results here */
1017 FILE *traceOut
; /* Output for sqlite3_trace() */
1018 int nErr
; /* Number of errors seen */
1019 int mode
; /* An output mode setting */
1020 int modePrior
; /* Saved mode */
1021 int cMode
; /* temporary output mode for the current query */
1022 int normalMode
; /* Output mode before ".explain on" */
1023 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1024 int showHeader
; /* True to show column names in List or Column mode */
1025 int nCheck
; /* Number of ".check" commands run */
1026 unsigned shellFlgs
; /* Various flags */
1027 char *zDestTable
; /* Name of destination table when MODE_Insert */
1028 char *zTempFile
; /* Temporary file that might need deleting */
1029 char zTestcase
[30]; /* Name of current test case */
1030 char colSeparator
[20]; /* Column separator character for several modes */
1031 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1032 char colSepPrior
[20]; /* Saved column separator */
1033 char rowSepPrior
[20]; /* Saved row separator */
1034 int colWidth
[100]; /* Requested width of each column when in column mode*/
1035 int actualWidth
[100]; /* Actual width of each column */
1036 char nullValue
[20]; /* The text to print when a NULL comes back from
1038 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1039 const char *zDbFilename
; /* name of the database file */
1040 char *zFreeOnClose
; /* Filename to free when closing */
1041 const char *zVfs
; /* Name of VFS to use */
1042 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1043 FILE *pLog
; /* Write log output here */
1044 int *aiIndent
; /* Array of indents used in MODE_Explain */
1045 int nIndent
; /* Size of array aiIndent[] */
1046 int iIndent
; /* Index of current op in aiIndent[] */
1047 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1048 #if defined(SQLITE_ENABLE_SESSION)
1049 int nSession
; /* Number of active sessions */
1050 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1052 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1056 /* Allowed values for ShellState.autoEQP
1058 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1059 #define AUTOEQP_on 1 /* Automatic EQP is on */
1060 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1061 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1063 /* Allowed values for ShellState.openMode
1065 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1066 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1067 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1068 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1069 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1072 ** These are the allowed shellFlgs values
1074 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1075 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1076 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1077 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1078 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1079 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1080 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1083 ** Macros for testing and setting shellFlgs
1085 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1086 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1087 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1090 ** These are the allowed modes.
1092 #define MODE_Line 0 /* One column per line. Blank line between records */
1093 #define MODE_Column 1 /* One record per line in neat columns */
1094 #define MODE_List 2 /* One record per line with a separator */
1095 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1096 #define MODE_Html 4 /* Generate an XHTML table */
1097 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1098 #define MODE_Quote 6 /* Quote values as for SQL */
1099 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1100 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1101 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1102 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1103 #define MODE_Pretty 11 /* Pretty-print schemas */
1104 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1106 static const char *modeDescr
[] = {
1123 ** These are the column/row/line separators used by the various
1124 ** import/export modes.
1126 #define SEP_Column "|"
1127 #define SEP_Row "\n"
1128 #define SEP_Tab "\t"
1129 #define SEP_Space " "
1130 #define SEP_Comma ","
1131 #define SEP_CrLf "\r\n"
1132 #define SEP_Unit "\x1F"
1133 #define SEP_Record "\x1E"
1136 ** A callback for the sqlite3_log() interface.
1138 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1139 ShellState
*p
= (ShellState
*)pArg
;
1140 if( p
->pLog
==0 ) return;
1141 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1146 ** SQL function: shell_putsnl(X)
1148 ** Write the text X to the screen (or whatever output is being directed)
1149 ** adding a newline at the end, and then return X.
1151 static void shellPutsFunc(
1152 sqlite3_context
*pCtx
,
1154 sqlite3_value
**apVal
1156 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1158 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1159 sqlite3_result_value(pCtx
, apVal
[0]);
1163 ** SQL function: edit(VALUE)
1164 ** edit(VALUE,EDITOR)
1168 ** (1) Write VALUE into a temporary file.
1169 ** (2) Run program EDITOR on that temporary file.
1170 ** (3) Read the temporary file back and return its content as the result.
1171 ** (4) Delete the temporary file
1173 ** If the EDITOR argument is omitted, use the value in the VISUAL
1174 ** environment variable. If still there is no EDITOR, through an error.
1176 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1178 #ifndef SQLITE_NOHAVE_SYSTEM
1179 static void editFunc(
1180 sqlite3_context
*context
,
1182 sqlite3_value
**argv
1184 const char *zEditor
;
1185 char *zTempFile
= 0;
1193 unsigned char *p
= 0;
1196 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1198 zEditor
= getenv("VISUAL");
1201 sqlite3_result_error(context
, "no editor for edit()", -1);
1204 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1205 sqlite3_result_error(context
, "NULL input to edit()", -1);
1208 db
= sqlite3_context_db_handle(context
);
1210 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1212 sqlite3_uint64 r
= 0;
1213 sqlite3_randomness(sizeof(r
), &r
);
1214 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1216 sqlite3_result_error_nomem(context
);
1220 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1221 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1223 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1226 sz
= sqlite3_value_bytes(argv
[0]);
1228 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, sz
, f
);
1230 x
= fwrite(sqlite3_value_text(argv
[0]), 1, sz
, f
);
1235 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1238 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1240 sqlite3_result_error_nomem(context
);
1246 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1249 f
= fopen(zTempFile
, bBin
? "rb" : "r");
1251 sqlite3_result_error(context
,
1252 "edit() cannot reopen temp file after edit", -1);
1255 fseek(f
, 0, SEEK_END
);
1258 p
= sqlite3_malloc64( sz
+(bBin
==0) );
1260 sqlite3_result_error_nomem(context
);
1264 x
= fread(p
, 1, sz
, f
);
1266 x
= fread(p
, 1, sz
, f
);
1272 sqlite3_result_error(context
, "could not read back the whole file", -1);
1276 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1278 sqlite3_result_text64(context
, (const char*)p
, sz
,
1279 sqlite3_free
, SQLITE_UTF8
);
1286 sqlite3_free(zTempFile
);
1289 #endif /* SQLITE_NOHAVE_SYSTEM */
1292 ** Save or restore the current output mode
1294 static void outputModePush(ShellState
*p
){
1295 p
->modePrior
= p
->mode
;
1296 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1297 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1299 static void outputModePop(ShellState
*p
){
1300 p
->mode
= p
->modePrior
;
1301 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1302 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1306 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1308 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1310 char *zBlob
= (char *)pBlob
;
1311 raw_printf(out
,"X'");
1312 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
1313 raw_printf(out
,"'");
1317 ** Find a string that is not found anywhere in z[]. Return a pointer
1320 ** Try to use zA and zB first. If both of those are already found in z[]
1321 ** then make up some string and store it in the buffer zBuf.
1323 static const char *unused_string(
1324 const char *z
, /* Result must not appear anywhere in z */
1325 const char *zA
, const char *zB
, /* Try these first */
1326 char *zBuf
/* Space to store a generated string */
1329 if( strstr(z
, zA
)==0 ) return zA
;
1330 if( strstr(z
, zB
)==0 ) return zB
;
1332 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1333 }while( strstr(z
,zBuf
)!=0 );
1338 ** Output the given string as a quoted string using SQL quoting conventions.
1340 ** See also: output_quoted_escaped_string()
1342 static void output_quoted_string(FILE *out
, const char *z
){
1345 setBinaryMode(out
, 1);
1346 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1348 utf8_printf(out
,"'%s'",z
);
1350 raw_printf(out
, "'");
1352 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1355 utf8_printf(out
, "%.*s", i
, z
);
1359 raw_printf(out
, "'");
1367 raw_printf(out
, "'");
1369 setTextMode(out
, 1);
1373 ** Output the given string as a quoted string using SQL quoting conventions.
1374 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1375 ** get corrupted by end-of-line translation facilities in some operating
1378 ** This is like output_quoted_string() but with the addition of the \r\n
1379 ** escape mechanism.
1381 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1384 setBinaryMode(out
, 1);
1385 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1387 utf8_printf(out
,"'%s'",z
);
1389 const char *zNL
= 0;
1390 const char *zCR
= 0;
1393 char zBuf1
[20], zBuf2
[20];
1394 for(i
=0; z
[i
]; i
++){
1395 if( z
[i
]=='\n' ) nNL
++;
1396 if( z
[i
]=='\r' ) nCR
++;
1399 raw_printf(out
, "replace(");
1400 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1403 raw_printf(out
, "replace(");
1404 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1406 raw_printf(out
, "'");
1408 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1411 utf8_printf(out
, "%.*s", i
, z
);
1415 raw_printf(out
, "'");
1423 raw_printf(out
, "%s", zNL
);
1426 raw_printf(out
, "%s", zCR
);
1428 raw_printf(out
, "'");
1430 raw_printf(out
, ",'%s',char(13))", zCR
);
1433 raw_printf(out
, ",'%s',char(10))", zNL
);
1436 setTextMode(out
, 1);
1440 ** Output the given string as a quoted according to C or TCL quoting rules.
1442 static void output_c_string(FILE *out
, const char *z
){
1445 while( (c
= *(z
++))!=0 ){
1452 }else if( c
=='\t' ){
1455 }else if( c
=='\n' ){
1458 }else if( c
=='\r' ){
1461 }else if( !isprint(c
&0xff) ){
1462 raw_printf(out
, "\\%03o", c
&0xff);
1471 ** Output the given string with characters that are special to
1474 static void output_html_string(FILE *out
, const char *z
){
1486 utf8_printf(out
,"%.*s",i
,z
);
1489 raw_printf(out
,"<");
1490 }else if( z
[i
]=='&' ){
1491 raw_printf(out
,"&");
1492 }else if( z
[i
]=='>' ){
1493 raw_printf(out
,">");
1494 }else if( z
[i
]=='\"' ){
1495 raw_printf(out
,""");
1496 }else if( z
[i
]=='\'' ){
1497 raw_printf(out
,"'");
1506 ** If a field contains any character identified by a 1 in the following
1507 ** array, then the string must be quoted for CSV.
1509 static const char needCsvQuote
[] = {
1510 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1511 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1512 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1513 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1514 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1515 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1516 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1518 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1519 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1520 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1529 ** Output a single term of CSV. Actually, p->colSeparator is used for
1530 ** the separator, which may or may not be a comma. p->nullValue is
1531 ** the null value. Strings are quoted if necessary. The separator
1532 ** is only issued if bSep is true.
1534 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1537 utf8_printf(out
,"%s",p
->nullValue
);
1540 int nSep
= strlen30(p
->colSeparator
);
1541 for(i
=0; z
[i
]; i
++){
1542 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1543 || (z
[i
]==p
->colSeparator
[0] &&
1544 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1550 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1551 utf8_printf(out
, "%s", zQuoted
);
1552 sqlite3_free(zQuoted
);
1554 utf8_printf(out
, "%s", z
);
1558 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1563 ** This routine runs when the user presses Ctrl-C
1565 static void interrupt_handler(int NotUsed
){
1566 UNUSED_PARAMETER(NotUsed
);
1568 if( seenInterrupt
>2 ) exit(1);
1569 if( globalDb
) sqlite3_interrupt(globalDb
);
1572 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1574 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1576 static BOOL WINAPI
ConsoleCtrlHandler(
1577 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1579 if( dwCtrlType
==CTRL_C_EVENT
){
1580 interrupt_handler(0);
1587 #ifndef SQLITE_OMIT_AUTHORIZATION
1589 ** When the ".auth ON" is set, the following authorizer callback is
1590 ** invoked. It always returns SQLITE_OK.
1592 static int shellAuth(
1600 ShellState
*p
= (ShellState
*)pClientData
;
1601 static const char *azAction
[] = { 0,
1602 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1603 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1604 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1605 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1606 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1607 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1608 "PRAGMA", "READ", "SELECT",
1609 "TRANSACTION", "UPDATE", "ATTACH",
1610 "DETACH", "ALTER_TABLE", "REINDEX",
1611 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1612 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1620 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1622 raw_printf(p
->out
, " ");
1624 output_c_string(p
->out
, az
[i
]);
1626 raw_printf(p
->out
, "NULL");
1629 raw_printf(p
->out
, "\n");
1635 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1637 ** This routine converts some CREATE TABLE statements for shadow tables
1638 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1640 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1641 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1642 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1644 utf8_printf(out
, "%s%s", z
, zTail
);
1647 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1650 printSchemaLine(out
, z
, zTail
);
1655 ** Return true if string z[] has nothing but whitespace and comments to the
1656 ** end of the first line.
1658 static int wsToEol(const char *z
){
1660 for(i
=0; z
[i
]; i
++){
1661 if( z
[i
]=='\n' ) return 1;
1662 if( IsSpace(z
[i
]) ) continue;
1663 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
1670 ** Add a new entry to the EXPLAIN QUERY PLAN data
1672 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
1674 int nText
= strlen30(zText
);
1675 if( p
->autoEQPtest
){
1676 utf8_printf(p
->out
, "%d,%d,%s\n", iEqpId
, p2
, zText
);
1678 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
1679 if( pNew
==0 ) shell_out_of_memory();
1680 pNew
->iEqpId
= iEqpId
;
1681 pNew
->iParentId
= p2
;
1682 memcpy(pNew
->zText
, zText
, nText
+1);
1684 if( p
->sGraph
.pLast
){
1685 p
->sGraph
.pLast
->pNext
= pNew
;
1687 p
->sGraph
.pRow
= pNew
;
1689 p
->sGraph
.pLast
= pNew
;
1693 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1696 static void eqp_reset(ShellState
*p
){
1697 EQPGraphRow
*pRow
, *pNext
;
1698 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
1699 pNext
= pRow
->pNext
;
1702 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
1705 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1706 ** pOld, or return the first such line if pOld is NULL
1708 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
1709 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
1710 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
1714 /* Render a single level of the graph that has iEqpId as its parent. Called
1715 ** recursively to render sublevels.
1717 static void eqp_render_level(ShellState
*p
, int iEqpId
){
1718 EQPGraphRow
*pRow
, *pNext
;
1719 int n
= strlen30(p
->sGraph
.zPrefix
);
1721 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
1722 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
1724 utf8_printf(p
->out
, "%s%s%s\n", p
->sGraph
.zPrefix
, pNext
? "|--" : "`--", z
);
1725 if( n
<(int)sizeof(p
->sGraph
.zPrefix
)-7 ){
1726 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
1727 eqp_render_level(p
, pRow
->iEqpId
);
1728 p
->sGraph
.zPrefix
[n
] = 0;
1734 ** Display and reset the EXPLAIN QUERY PLAN data
1736 static void eqp_render(ShellState
*p
){
1737 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
1739 if( pRow
->zText
[0]=='-' ){
1740 if( pRow
->pNext
==0 ){
1744 utf8_printf(p
->out
, "%s\n", pRow
->zText
+3);
1745 p
->sGraph
.pRow
= pRow
->pNext
;
1748 utf8_printf(p
->out
, "QUERY PLAN\n");
1750 p
->sGraph
.zPrefix
[0] = 0;
1751 eqp_render_level(p
, 0);
1757 ** This is the callback routine that the shell
1758 ** invokes for each row of a query result.
1760 static int shell_callback(
1762 int nArg
, /* Number of result columns */
1763 char **azArg
, /* Text of each result column */
1764 char **azCol
, /* Column names */
1765 int *aiType
/* Column types */
1768 ShellState
*p
= (ShellState
*)pArg
;
1770 if( azArg
==0 ) return 0;
1774 if( azArg
==0 ) break;
1775 for(i
=0; i
<nArg
; i
++){
1776 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1777 if( len
>w
) w
= len
;
1779 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1780 for(i
=0; i
<nArg
; i
++){
1781 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1782 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1788 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1789 const int *colWidth
;
1792 if( p
->cMode
==MODE_Column
){
1793 colWidth
= p
->colWidth
;
1794 showHdr
= p
->showHeader
;
1795 rowSep
= p
->rowSeparator
;
1797 colWidth
= aExplainWidths
;
1802 for(i
=0; i
<nArg
; i
++){
1804 if( i
<ArraySize(p
->colWidth
) ){
1810 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1812 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1815 if( i
<ArraySize(p
->actualWidth
) ){
1816 p
->actualWidth
[i
] = w
;
1819 utf8_width_print(p
->out
, w
, azCol
[i
]);
1820 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1824 for(i
=0; i
<nArg
; i
++){
1826 if( i
<ArraySize(p
->actualWidth
) ){
1827 w
= p
->actualWidth
[i
];
1832 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1833 "----------------------------------------------------------"
1834 "----------------------------------------------------------",
1835 i
==nArg
-1 ? rowSep
: " ");
1839 if( azArg
==0 ) break;
1840 for(i
=0; i
<nArg
; i
++){
1842 if( i
<ArraySize(p
->actualWidth
) ){
1843 w
= p
->actualWidth
[i
];
1847 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1848 w
= strlenChar(azArg
[i
]);
1850 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1851 if( p
->iIndent
<p
->nIndent
){
1852 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1856 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1857 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1861 case MODE_Semi
: { /* .schema and .fullschema output */
1862 printSchemaLine(p
->out
, azArg
[0], ";\n");
1865 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1873 if( azArg
[0]==0 ) break;
1874 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1875 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1877 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1880 z
= sqlite3_mprintf("%s", azArg
[0]);
1882 for(i
=0; IsSpace(z
[i
]); i
++){}
1883 for(; (c
= z
[i
])!=0; i
++){
1885 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1886 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1887 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1892 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1894 if( strlen30(z
)>=79 ){
1895 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy changes from z[i] back to z[j] */
1898 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1902 }else if( c
=='-' && z
[i
+1]=='-' ){
1908 if( nLine
>0 && nParen
==0 && j
>0 ){
1909 printSchemaLineN(p
->out
, z
, j
, "\n");
1914 if( nParen
==1 && cEnd
==0
1915 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
1918 printSchemaLineN(p
->out
, z
, j
, "\n ");
1921 while( IsSpace(z
[i
+1]) ){ i
++; }
1926 printSchemaLine(p
->out
, z
, ";\n");
1931 if( p
->cnt
++==0 && p
->showHeader
){
1932 for(i
=0; i
<nArg
; i
++){
1933 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1934 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1937 if( azArg
==0 ) break;
1938 for(i
=0; i
<nArg
; i
++){
1940 if( z
==0 ) z
= p
->nullValue
;
1941 utf8_printf(p
->out
, "%s", z
);
1943 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1945 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1951 if( p
->cnt
++==0 && p
->showHeader
){
1952 raw_printf(p
->out
,"<TR>");
1953 for(i
=0; i
<nArg
; i
++){
1954 raw_printf(p
->out
,"<TH>");
1955 output_html_string(p
->out
, azCol
[i
]);
1956 raw_printf(p
->out
,"</TH>\n");
1958 raw_printf(p
->out
,"</TR>\n");
1960 if( azArg
==0 ) break;
1961 raw_printf(p
->out
,"<TR>");
1962 for(i
=0; i
<nArg
; i
++){
1963 raw_printf(p
->out
,"<TD>");
1964 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1965 raw_printf(p
->out
,"</TD>\n");
1967 raw_printf(p
->out
,"</TR>\n");
1971 if( p
->cnt
++==0 && p
->showHeader
){
1972 for(i
=0; i
<nArg
; i
++){
1973 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1974 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1976 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1978 if( azArg
==0 ) break;
1979 for(i
=0; i
<nArg
; i
++){
1980 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1981 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1983 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1987 setBinaryMode(p
->out
, 1);
1988 if( p
->cnt
++==0 && p
->showHeader
){
1989 for(i
=0; i
<nArg
; i
++){
1990 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
1992 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1995 for(i
=0; i
<nArg
; i
++){
1996 output_csv(p
, azArg
[i
], i
<nArg
-1);
1998 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2000 setTextMode(p
->out
, 1);
2004 if( azArg
==0 ) break;
2005 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
2006 if( p
->showHeader
){
2007 raw_printf(p
->out
,"(");
2008 for(i
=0; i
<nArg
; i
++){
2009 if( i
>0 ) raw_printf(p
->out
, ",");
2010 if( quoteChar(azCol
[i
]) ){
2011 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2012 utf8_printf(p
->out
, "%s", z
);
2015 raw_printf(p
->out
, "%s", azCol
[i
]);
2018 raw_printf(p
->out
,")");
2021 for(i
=0; i
<nArg
; i
++){
2022 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
2023 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2024 utf8_printf(p
->out
,"NULL");
2025 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2026 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2027 output_quoted_string(p
->out
, azArg
[i
]);
2029 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2031 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2032 utf8_printf(p
->out
,"%s", azArg
[i
]);
2033 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2035 double r
= sqlite3_column_double(p
->pStmt
, i
);
2037 memcpy(&ur
,&r
,sizeof(r
));
2038 if( ur
==0x7ff0000000000000LL
){
2039 raw_printf(p
->out
, "1e999");
2040 }else if( ur
==0xfff0000000000000LL
){
2041 raw_printf(p
->out
, "-1e999");
2043 sqlite3_snprintf(50,z
,"%!.20g", r
);
2044 raw_printf(p
->out
, "%s", z
);
2046 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2047 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2048 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2049 output_hex_blob(p
->out
, pBlob
, nBlob
);
2050 }else if( isNumber(azArg
[i
], 0) ){
2051 utf8_printf(p
->out
,"%s", azArg
[i
]);
2052 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2053 output_quoted_string(p
->out
, azArg
[i
]);
2055 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2058 raw_printf(p
->out
,");\n");
2062 if( azArg
==0 ) break;
2063 if( p
->cnt
==0 && p
->showHeader
){
2064 for(i
=0; i
<nArg
; i
++){
2065 if( i
>0 ) raw_printf(p
->out
, ",");
2066 output_quoted_string(p
->out
, azCol
[i
]);
2068 raw_printf(p
->out
,"\n");
2071 for(i
=0; i
<nArg
; i
++){
2072 if( i
>0 ) raw_printf(p
->out
, ",");
2073 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2074 utf8_printf(p
->out
,"NULL");
2075 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2076 output_quoted_string(p
->out
, azArg
[i
]);
2077 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2078 utf8_printf(p
->out
,"%s", azArg
[i
]);
2079 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2081 double r
= sqlite3_column_double(p
->pStmt
, i
);
2082 sqlite3_snprintf(50,z
,"%!.20g", r
);
2083 raw_printf(p
->out
, "%s", z
);
2084 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2085 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2086 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2087 output_hex_blob(p
->out
, pBlob
, nBlob
);
2088 }else if( isNumber(azArg
[i
], 0) ){
2089 utf8_printf(p
->out
,"%s", azArg
[i
]);
2091 output_quoted_string(p
->out
, azArg
[i
]);
2094 raw_printf(p
->out
,"\n");
2098 if( p
->cnt
++==0 && p
->showHeader
){
2099 for(i
=0; i
<nArg
; i
++){
2100 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2101 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2103 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2105 if( azArg
==0 ) break;
2106 for(i
=0; i
<nArg
; i
++){
2107 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2108 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2110 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2114 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2122 ** This is the callback routine that the SQLite library
2123 ** invokes for each row of a query result.
2125 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2126 /* since we don't have type info, call the shell_callback with a NULL value */
2127 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2131 ** This is the callback routine from sqlite3_exec() that appends all
2132 ** output onto the end of a ShellText object.
2134 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2135 ShellText
*p
= (ShellText
*)pArg
;
2137 UNUSED_PARAMETER(az
);
2138 if( azArg
==0 ) return 0;
2139 if( p
->n
) appendText(p
, "|", 0);
2140 for(i
=0; i
<nArg
; i
++){
2141 if( i
) appendText(p
, ",", 0);
2142 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2148 ** Generate an appropriate SELFTEST table in the main database.
2150 static void createSelftestTable(ShellState
*p
){
2153 "SAVEPOINT selftest_init;\n"
2154 "CREATE TABLE IF NOT EXISTS selftest(\n"
2155 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2156 " op TEXT,\n" /* Operator: memo run */
2157 " cmd TEXT,\n" /* Command text */
2158 " ans TEXT\n" /* Desired answer */
2160 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2161 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2162 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2163 " 'memo','Tests generated by --init');\n"
2164 "INSERT INTO [_shell$self]\n"
2166 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2167 "FROM sqlite_master ORDER BY 2'',224))',\n"
2168 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2169 "FROM sqlite_master ORDER BY 2',224));\n"
2170 "INSERT INTO [_shell$self]\n"
2172 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2173 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2174 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2176 " SELECT name FROM sqlite_master\n"
2177 " WHERE type='table'\n"
2178 " AND name<>'selftest'\n"
2179 " AND coalesce(rootpage,0)>0\n"
2182 "INSERT INTO [_shell$self]\n"
2183 " VALUES('run','PRAGMA integrity_check','ok');\n"
2184 "INSERT INTO selftest(tno,op,cmd,ans)"
2185 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2186 "DROP TABLE [_shell$self];"
2189 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2190 sqlite3_free(zErrMsg
);
2192 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2197 ** Set the destination table field of the ShellState structure to
2198 ** the name of the table given. Escape any quote characters in the
2201 static void set_table_name(ShellState
*p
, const char *zName
){
2206 if( p
->zDestTable
){
2207 free(p
->zDestTable
);
2210 if( zName
==0 ) return;
2211 cQuote
= quoteChar(zName
);
2212 n
= strlen30(zName
);
2213 if( cQuote
) n
+= n
+2;
2214 z
= p
->zDestTable
= malloc( n
+1 );
2215 if( z
==0 ) shell_out_of_memory();
2217 if( cQuote
) z
[n
++] = cQuote
;
2218 for(i
=0; zName
[i
]; i
++){
2220 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2222 if( cQuote
) z
[n
++] = cQuote
;
2228 ** Execute a query statement that will generate SQL output. Print
2229 ** the result columns, comma-separated, on a line and then add a
2230 ** semicolon terminator to the end of that line.
2232 ** If the number of columns is 1 and that column contains text "--"
2233 ** then write the semicolon on a separate line. That way, if a
2234 ** "--" comment occurs at the end of the statement, the comment
2235 ** won't consume the semicolon terminator.
2237 static int run_table_dump_query(
2238 ShellState
*p
, /* Query context */
2239 const char *zSelect
, /* SELECT statement to extract content */
2240 const char *zFirstRow
/* Print before first row, if not NULL */
2242 sqlite3_stmt
*pSelect
;
2247 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2248 if( rc
!=SQLITE_OK
|| !pSelect
){
2249 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2250 sqlite3_errmsg(p
->db
));
2251 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2254 rc
= sqlite3_step(pSelect
);
2255 nResult
= sqlite3_column_count(pSelect
);
2256 while( rc
==SQLITE_ROW
){
2258 utf8_printf(p
->out
, "%s", zFirstRow
);
2261 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2262 utf8_printf(p
->out
, "%s", z
);
2263 for(i
=1; i
<nResult
; i
++){
2264 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2267 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2269 raw_printf(p
->out
, "\n;\n");
2271 raw_printf(p
->out
, ";\n");
2273 rc
= sqlite3_step(pSelect
);
2275 rc
= sqlite3_finalize(pSelect
);
2276 if( rc
!=SQLITE_OK
){
2277 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2278 sqlite3_errmsg(p
->db
));
2279 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2285 ** Allocate space and save off current error string.
2287 static char *save_err_msg(
2288 sqlite3
*db
/* Database to query */
2290 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
2291 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
2293 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
2300 ** Attempt to display I/O stats on Linux using /proc/PID/io
2302 static void displayLinuxIoStats(FILE *out
){
2305 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2306 in
= fopen(z
, "rb");
2308 while( fgets(z
, sizeof(z
), in
)!=0 ){
2309 static const struct {
2310 const char *zPattern
;
2313 { "rchar: ", "Bytes received by read():" },
2314 { "wchar: ", "Bytes sent to write():" },
2315 { "syscr: ", "Read() system calls:" },
2316 { "syscw: ", "Write() system calls:" },
2317 { "read_bytes: ", "Bytes read from storage:" },
2318 { "write_bytes: ", "Bytes written to storage:" },
2319 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2322 for(i
=0; i
<ArraySize(aTrans
); i
++){
2323 int n
= strlen30(aTrans
[i
].zPattern
);
2324 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2325 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2335 ** Display a single line of status using 64-bit values.
2337 static void displayStatLine(
2338 ShellState
*p
, /* The shell context */
2339 char *zLabel
, /* Label for this one line */
2340 char *zFormat
, /* Format for the result */
2341 int iStatusCtrl
, /* Which status to display */
2342 int bReset
/* True to reset the stats */
2344 sqlite3_int64 iCur
= -1;
2345 sqlite3_int64 iHiwtr
= -1;
2348 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2349 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2350 if( zFormat
[i
]=='%' ) nPercent
++;
2353 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2355 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2357 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2361 ** Display memory stats.
2363 static int display_stats(
2364 sqlite3
*db
, /* Database to query */
2365 ShellState
*pArg
, /* Pointer to ShellState */
2366 int bReset
/* True to reset the stats */
2371 if( pArg
==0 || pArg
->out
==0 ) return 0;
2374 if( pArg
->pStmt
&& (pArg
->statsOn
& 2) ){
2376 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
2378 nCol
= sqlite3_column_count(pStmt
);
2379 raw_printf(out
, "%-36s %d\n", "Number of output columns:", nCol
);
2380 for(i
=0; i
<nCol
; i
++){
2381 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
2382 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
2383 #ifndef SQLITE_OMIT_DECLTYPE
2384 sqlite3_snprintf(30, z
+x
, "declared type:");
2385 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
2387 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2388 sqlite3_snprintf(30, z
+x
, "database name:");
2389 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
2390 sqlite3_snprintf(30, z
+x
, "table name:");
2391 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
2392 sqlite3_snprintf(30, z
+x
, "origin name:");
2393 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
2398 displayStatLine(pArg
, "Memory Used:",
2399 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
2400 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2401 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2402 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2403 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2404 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2406 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2407 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2408 displayStatLine(pArg
, "Largest Allocation:",
2409 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2410 displayStatLine(pArg
, "Largest Pcache Allocation:",
2411 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2412 #ifdef YYTRACKMAXSTACKDEPTH
2413 displayStatLine(pArg
, "Deepest Parser Stack:",
2414 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2418 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2420 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2421 &iCur
, &iHiwtr
, bReset
);
2422 raw_printf(pArg
->out
,
2423 "Lookaside Slots Used: %d (max %d)\n",
2425 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2426 &iCur
, &iHiwtr
, bReset
);
2427 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2429 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2430 &iCur
, &iHiwtr
, bReset
);
2431 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2433 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2434 &iCur
, &iHiwtr
, bReset
);
2435 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2439 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2440 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2443 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2444 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2446 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2447 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2449 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2450 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2452 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
2453 raw_printf(pArg
->out
, "Page cache spills: %d\n", iCur
);
2455 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2456 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2459 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2460 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2465 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2467 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2468 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2469 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2470 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2471 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2472 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2473 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2474 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
, bReset
);
2475 raw_printf(pArg
->out
, "Reprepare operations: %d\n", iCur
);
2476 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
2477 raw_printf(pArg
->out
, "Number of times run: %d\n", iCur
);
2478 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
2479 raw_printf(pArg
->out
, "Memory used by prepared stmt: %d\n", iCur
);
2483 displayLinuxIoStats(pArg
->out
);
2486 /* Do not remove this machine readable comment: extra-stats-output-here */
2492 ** Display scan stats.
2494 static void display_scanstats(
2495 sqlite3
*db
, /* Database to query */
2496 ShellState
*pArg
/* Pointer to ShellState */
2498 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2499 UNUSED_PARAMETER(db
);
2500 UNUSED_PARAMETER(pArg
);
2503 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2505 for(k
=0; k
<=mx
; k
++){
2506 double rEstLoop
= 1.0;
2508 sqlite3_stmt
*p
= pArg
->pStmt
;
2509 sqlite3_int64 nLoop
, nVisit
;
2512 const char *zExplain
;
2513 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2516 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2517 if( iSid
>mx
) mx
= iSid
;
2518 if( iSid
!=k
) continue;
2520 rEstLoop
= (double)nLoop
;
2521 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2524 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2525 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2526 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2527 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2529 raw_printf(pArg
->out
,
2530 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2531 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2535 raw_printf(pArg
->out
, "---------------------------\n");
2540 ** Parameter azArray points to a zero-terminated array of strings. zStr
2541 ** points to a single nul-terminated string. Return non-zero if zStr
2542 ** is equal, according to strcmp(), to any of the strings in the array.
2543 ** Otherwise, return zero.
2545 static int str_in_array(const char *zStr
, const char **azArray
){
2547 for(i
=0; azArray
[i
]; i
++){
2548 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2554 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2555 ** and populate the ShellState.aiIndent[] array with the number of
2556 ** spaces each opcode should be indented before it is output.
2558 ** The indenting rules are:
2560 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2561 ** all opcodes that occur between the p2 jump destination and the opcode
2562 ** itself by 2 spaces.
2564 ** * For each "Goto", if the jump destination is earlier in the program
2565 ** and ends on one of:
2566 ** Yield SeekGt SeekLt RowSetRead Rewind
2567 ** or if the P1 parameter is one instead of zero,
2568 ** then indent all opcodes between the earlier instruction
2569 ** and "Goto" by 2 spaces.
2571 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2572 const char *zSql
; /* The text of the SQL statement */
2573 const char *z
; /* Used to check if this is an EXPLAIN */
2574 int *abYield
= 0; /* True if op is an OP_Yield */
2575 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2576 int iOp
; /* Index of operation in p->aiIndent[] */
2578 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2579 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2581 const char *azGoto
[] = { "Goto", 0 };
2583 /* Try to figure out if this is really an EXPLAIN statement. If this
2584 ** cannot be verified, return early. */
2585 if( sqlite3_column_count(pSql
)!=8 ){
2589 zSql
= sqlite3_sql(pSql
);
2590 if( zSql
==0 ) return;
2591 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2592 if( sqlite3_strnicmp(z
, "explain", 7) ){
2597 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2599 int iAddr
= sqlite3_column_int(pSql
, 0);
2600 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2602 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2603 ** p2 is an instruction address, set variable p2op to the index of that
2604 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2605 ** the current instruction is part of a sub-program generated by an
2606 ** SQL trigger or foreign key. */
2607 int p2
= sqlite3_column_int(pSql
, 3);
2608 int p2op
= (p2
+ (iOp
-iAddr
));
2610 /* Grow the p->aiIndent array as required */
2613 /* Do further verfication that this is explain output. Abort if
2615 static const char *explainCols
[] = {
2616 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2618 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2619 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2621 sqlite3_reset(pSql
);
2627 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2628 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2630 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2631 p
->aiIndent
[iOp
] = 0;
2634 if( str_in_array(zOp
, azNext
) ){
2635 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2637 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2638 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2640 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2645 sqlite3_free(abYield
);
2646 sqlite3_reset(pSql
);
2650 ** Free the array allocated by explain_data_prepare().
2652 static void explain_data_delete(ShellState
*p
){
2653 sqlite3_free(p
->aiIndent
);
2660 ** Disable and restore .wheretrace and .selecttrace settings.
2662 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2663 extern int sqlite3SelectTrace
;
2664 static int savedSelectTrace
;
2666 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2667 extern int sqlite3WhereTrace
;
2668 static int savedWhereTrace
;
2670 static void disable_debug_trace_modes(void){
2671 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2672 savedSelectTrace
= sqlite3SelectTrace
;
2673 sqlite3SelectTrace
= 0;
2675 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2676 savedWhereTrace
= sqlite3WhereTrace
;
2677 sqlite3WhereTrace
= 0;
2680 static void restore_debug_trace_modes(void){
2681 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2682 sqlite3SelectTrace
= savedSelectTrace
;
2684 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2685 sqlite3WhereTrace
= savedWhereTrace
;
2690 ** Run a prepared statement
2692 static void exec_prepared_stmt(
2693 ShellState
*pArg
, /* Pointer to ShellState */
2694 sqlite3_stmt
*pStmt
/* Statment to run */
2698 /* perform the first step. this will tell us if we
2699 ** have a result set or not and how wide it is.
2701 rc
= sqlite3_step(pStmt
);
2702 /* if we have a result set... */
2703 if( SQLITE_ROW
== rc
){
2704 /* allocate space for col name ptr, value ptr, and type */
2705 int nCol
= sqlite3_column_count(pStmt
);
2706 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2710 char **azCols
= (char **)pData
; /* Names of result columns */
2711 char **azVals
= &azCols
[nCol
]; /* Results */
2712 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2714 assert(sizeof(int) <= sizeof(char *));
2715 /* save off ptrs to column names */
2716 for(i
=0; i
<nCol
; i
++){
2717 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2720 /* extract the data and data types */
2721 for(i
=0; i
<nCol
; i
++){
2722 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2723 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2726 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2728 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2730 break; /* from for */
2734 /* if data and types extracted successfully... */
2735 if( SQLITE_ROW
== rc
){
2736 /* call the supplied callback with the result row data */
2737 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2740 rc
= sqlite3_step(pStmt
);
2743 } while( SQLITE_ROW
== rc
);
2744 sqlite3_free(pData
);
2749 #ifndef SQLITE_OMIT_VIRTUALTABLE
2751 ** This function is called to process SQL if the previous shell command
2752 ** was ".expert". It passes the SQL in the second argument directly to
2753 ** the sqlite3expert object.
2755 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2756 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2757 ** an English language error message. It is the responsibility of the
2758 ** caller to eventually free this buffer using sqlite3_free().
2760 static int expertHandleSQL(
2765 assert( pState
->expert
.pExpert
);
2766 assert( pzErr
==0 || *pzErr
==0 );
2767 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
2771 ** This function is called either to silently clean up the object
2772 ** created by the ".expert" command (if bCancel==1), or to generate a
2773 ** report from it and then clean it up (if bCancel==0).
2775 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2776 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2777 ** an English language error message. It is the responsibility of the
2778 ** caller to eventually free this buffer using sqlite3_free().
2780 static int expertFinish(
2786 sqlite3expert
*p
= pState
->expert
.pExpert
;
2788 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
2790 FILE *out
= pState
->out
;
2791 int bVerbose
= pState
->expert
.bVerbose
;
2793 rc
= sqlite3_expert_analyze(p
, pzErr
);
2794 if( rc
==SQLITE_OK
){
2795 int nQuery
= sqlite3_expert_count(p
);
2799 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
2800 raw_printf(out
, "-- Candidates -----------------------------\n");
2801 raw_printf(out
, "%s\n", zCand
);
2803 for(i
=0; i
<nQuery
; i
++){
2804 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
2805 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
2806 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
2807 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
2809 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
2810 raw_printf(out
, "%s\n\n", zSql
);
2812 raw_printf(out
, "%s\n", zIdx
);
2813 raw_printf(out
, "%s\n", zEQP
);
2817 sqlite3_expert_destroy(p
);
2818 pState
->expert
.pExpert
= 0;
2823 ** Implementation of ".expert" dot command.
2825 static int expertDotCommand(
2826 ShellState
*pState
, /* Current shell tool state */
2827 char **azArg
, /* Array of arguments passed to dot command */
2828 int nArg
/* Number of entries in azArg[] */
2835 assert( pState
->expert
.pExpert
==0 );
2836 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
2838 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
2841 if( z
[0]=='-' && z
[1]=='-' ) z
++;
2843 if( n
>=2 && 0==strncmp(z
, "-verbose", n
) ){
2844 pState
->expert
.bVerbose
= 1;
2846 else if( n
>=2 && 0==strncmp(z
, "-sample", n
) ){
2848 raw_printf(stderr
, "option requires an argument: %s\n", z
);
2851 iSample
= (int)integerValue(azArg
[++i
]);
2852 if( iSample
<0 || iSample
>100 ){
2853 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
2859 raw_printf(stderr
, "unknown option: %s\n", z
);
2864 if( rc
==SQLITE_OK
){
2865 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
2866 if( pState
->expert
.pExpert
==0 ){
2867 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
);
2870 sqlite3_expert_config(
2871 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
2878 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2881 ** Execute a statement or set of statements. Print
2882 ** any result rows/columns depending on the current mode
2883 ** set via the supplied callback.
2885 ** This is very similar to SQLite's built-in sqlite3_exec()
2886 ** function except it takes a slightly different callback
2887 ** and callback data argument.
2889 static int shell_exec(
2890 ShellState
*pArg
, /* Pointer to ShellState */
2891 const char *zSql
, /* SQL to be evaluated */
2892 char **pzErrMsg
/* Error msg written here */
2894 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2895 int rc
= SQLITE_OK
; /* Return Code */
2897 const char *zLeftover
; /* Tail of unprocessed SQL */
2898 sqlite3
*db
= pArg
->db
;
2904 #ifndef SQLITE_OMIT_VIRTUALTABLE
2905 if( pArg
->expert
.pExpert
){
2906 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
2907 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
2911 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2912 static const char *zStmtSql
;
2913 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2914 if( SQLITE_OK
!= rc
){
2916 *pzErrMsg
= save_err_msg(db
);
2920 /* this happens for a comment or white-space */
2922 while( IsSpace(zSql
[0]) ) zSql
++;
2925 zStmtSql
= sqlite3_sql(pStmt
);
2926 if( zStmtSql
==0 ) zStmtSql
= "";
2927 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2929 /* save off the prepared statment handle and reset row count */
2931 pArg
->pStmt
= pStmt
;
2935 /* echo the sql statement if echo on */
2936 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2937 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2940 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2941 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2942 sqlite3_stmt
*pExplain
;
2945 disable_debug_trace_modes();
2946 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
2947 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
2948 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
2950 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2951 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2952 if( rc
==SQLITE_OK
){
2953 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2954 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
2955 int iEqpId
= sqlite3_column_int(pExplain
, 0);
2956 int iParentId
= sqlite3_column_int(pExplain
, 1);
2957 if( zEQPLine
[0]=='-' ) eqp_render(pArg
);
2958 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
2962 sqlite3_finalize(pExplain
);
2964 if( pArg
->autoEQP
>=AUTOEQP_full
){
2965 /* Also do an EXPLAIN for ".eqp full" mode */
2966 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2967 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2968 if( rc
==SQLITE_OK
){
2969 pArg
->cMode
= MODE_Explain
;
2970 explain_data_prepare(pArg
, pExplain
);
2971 exec_prepared_stmt(pArg
, pExplain
);
2972 explain_data_delete(pArg
);
2974 sqlite3_finalize(pExplain
);
2977 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
2978 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
2979 /* Reprepare pStmt before reactiving trace modes */
2980 sqlite3_finalize(pStmt
);
2981 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
2982 if( pArg
) pArg
->pStmt
= pStmt
;
2984 restore_debug_trace_modes();
2988 pArg
->cMode
= pArg
->mode
;
2989 if( pArg
->autoExplain
){
2990 if( sqlite3_column_count(pStmt
)==8
2991 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
2993 pArg
->cMode
= MODE_Explain
;
2995 if( sqlite3_column_count(pStmt
)==4
2996 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql
,0)==0 ){
2997 pArg
->cMode
= MODE_EQP
;
3001 /* If the shell is currently in ".explain" mode, gather the extra
3002 ** data required to add indents to the output.*/
3003 if( pArg
->cMode
==MODE_Explain
){
3004 explain_data_prepare(pArg
, pStmt
);
3008 exec_prepared_stmt(pArg
, pStmt
);
3009 explain_data_delete(pArg
);
3012 /* print usage stats if stats on */
3013 if( pArg
&& pArg
->statsOn
){
3014 display_stats(db
, pArg
, 0);
3017 /* print loop-counters if required */
3018 if( pArg
&& pArg
->scanstatsOn
){
3019 display_scanstats(db
, pArg
);
3022 /* Finalize the statement just executed. If this fails, save a
3023 ** copy of the error message. Otherwise, set zSql to point to the
3024 ** next statement to execute. */
3025 rc2
= sqlite3_finalize(pStmt
);
3026 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
3027 if( rc
==SQLITE_OK
){
3029 while( IsSpace(zSql
[0]) ) zSql
++;
3030 }else if( pzErrMsg
){
3031 *pzErrMsg
= save_err_msg(db
);
3034 /* clear saved stmt handle */
3045 ** Release memory previously allocated by tableColumnList().
3047 static void freeColumnList(char **azCol
){
3049 for(i
=1; azCol
[i
]; i
++){
3050 sqlite3_free(azCol
[i
]);
3052 /* azCol[0] is a static string */
3053 sqlite3_free(azCol
);
3057 ** Return a list of pointers to strings which are the names of all
3058 ** columns in table zTab. The memory to hold the names is dynamically
3059 ** allocated and must be released by the caller using a subsequent call
3060 ** to freeColumnList().
3062 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3063 ** value that needs to be preserved, then azCol[0] is filled in with the
3064 ** name of the rowid column.
3066 ** The first regular column in the table is azCol[1]. The list is terminated
3067 ** by an entry with azCol[i]==0.
3069 static char **tableColumnList(ShellState
*p
, const char *zTab
){
3071 sqlite3_stmt
*pStmt
;
3075 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
3076 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
3077 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
3080 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
3081 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3084 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3085 if( nCol
>=nAlloc
-2 ){
3086 nAlloc
= nAlloc
*2 + nCol
+ 10;
3087 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
3088 if( azCol
==0 ) shell_out_of_memory();
3090 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
3091 if( sqlite3_column_int(pStmt
, 5) ){
3094 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
3103 sqlite3_finalize(pStmt
);
3104 if( azCol
==0 ) return 0;
3108 /* The decision of whether or not a rowid really needs to be preserved
3109 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3110 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3111 ** rowids on tables where the rowid is inaccessible because there are other
3112 ** columns in the table named "rowid", "_rowid_", and "oid".
3114 if( preserveRowid
&& isIPK
){
3115 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3116 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3117 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3118 ** ROWID aliases. To distinguish these cases, check to see if
3119 ** there is a "pk" entry in "PRAGMA index_list". There will be
3120 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3122 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3123 " WHERE origin='pk'", zTab
);
3124 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3127 freeColumnList(azCol
);
3130 rc
= sqlite3_step(pStmt
);
3131 sqlite3_finalize(pStmt
);
3132 preserveRowid
= rc
==SQLITE_ROW
;
3134 if( preserveRowid
){
3135 /* Only preserve the rowid if we can find a name to use for the
3137 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
3140 for(i
=1; i
<=nCol
; i
++){
3141 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
3144 /* At this point, we know that azRowid[j] is not the name of any
3145 ** ordinary column in the table. Verify that azRowid[j] is a valid
3146 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3147 ** tables will fail this last check */
3148 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
3149 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
3158 ** Toggle the reverse_unordered_selects setting.
3160 static void toggleSelectOrder(sqlite3
*db
){
3161 sqlite3_stmt
*pStmt
= 0;
3164 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
3165 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3166 iSetting
= sqlite3_column_int(pStmt
, 0);
3168 sqlite3_finalize(pStmt
);
3169 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
3170 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
3171 sqlite3_exec(db
, zStmt
, 0, 0, 0);
3175 ** This is a different callback routine used for dumping the database.
3176 ** Each row received by this callback consists of a table name,
3177 ** the table type ("index" or "table") and SQL to create the table.
3178 ** This routine should print text sufficient to recreate the table.
3180 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
3185 ShellState
*p
= (ShellState
*)pArg
;
3187 UNUSED_PARAMETER(azNotUsed
);
3188 if( nArg
!=3 || azArg
==0 ) return 0;
3193 if( strcmp(zTable
, "sqlite_sequence")==0 ){
3194 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
3195 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
3196 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
3197 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
3199 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
3201 if( !p
->writableSchema
){
3202 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
3203 p
->writableSchema
= 1;
3205 zIns
= sqlite3_mprintf(
3206 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3207 "VALUES('table','%q','%q',0,'%q');",
3208 zTable
, zTable
, zSql
);
3209 utf8_printf(p
->out
, "%s\n", zIns
);
3213 printSchemaLine(p
->out
, zSql
, ";\n");
3216 if( strcmp(zType
, "table")==0 ){
3221 char *savedDestTable
;
3224 azCol
= tableColumnList(p
, zTable
);
3230 /* Always quote the table name, even if it appears to be pure ascii,
3231 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3233 appendText(&sTable
, zTable
, quoteChar(zTable
));
3234 /* If preserving the rowid, add a column list after the table name.
3235 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3236 ** instead of the usual "INSERT INTO tab VALUES(...)".
3239 appendText(&sTable
, "(", 0);
3240 appendText(&sTable
, azCol
[0], 0);
3241 for(i
=1; azCol
[i
]; i
++){
3242 appendText(&sTable
, ",", 0);
3243 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
3245 appendText(&sTable
, ")", 0);
3248 /* Build an appropriate SELECT statement */
3250 appendText(&sSelect
, "SELECT ", 0);
3252 appendText(&sSelect
, azCol
[0], 0);
3253 appendText(&sSelect
, ",", 0);
3255 for(i
=1; azCol
[i
]; i
++){
3256 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
3258 appendText(&sSelect
, ",", 0);
3261 freeColumnList(azCol
);
3262 appendText(&sSelect
, " FROM ", 0);
3263 appendText(&sSelect
, zTable
, quoteChar(zTable
));
3265 savedDestTable
= p
->zDestTable
;
3266 savedMode
= p
->mode
;
3267 p
->zDestTable
= sTable
.z
;
3268 p
->mode
= p
->cMode
= MODE_Insert
;
3269 rc
= shell_exec(p
, sSelect
.z
, 0);
3270 if( (rc
&0xff)==SQLITE_CORRUPT
){
3271 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3272 toggleSelectOrder(p
->db
);
3273 shell_exec(p
, sSelect
.z
, 0);
3274 toggleSelectOrder(p
->db
);
3276 p
->zDestTable
= savedDestTable
;
3277 p
->mode
= savedMode
;
3286 ** Run zQuery. Use dump_callback() as the callback routine so that
3287 ** the contents of the query are output as SQL statements.
3289 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3290 ** "ORDER BY rowid DESC" to the end.
3292 static int run_schema_dump_query(
3298 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
3299 if( rc
==SQLITE_CORRUPT
){
3301 int len
= strlen30(zQuery
);
3302 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3304 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
3308 zQ2
= malloc( len
+100 );
3309 if( zQ2
==0 ) return rc
;
3310 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
3311 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
3313 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
3315 rc
= SQLITE_CORRUPT
;
3324 ** Text of a help message
3326 static char zHelp
[] =
3327 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3328 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3330 #ifndef SQLITE_OMIT_AUTHORIZATION
3331 ".auth ON|OFF Show authorizer callbacks\n"
3333 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3334 " Add \"--append\" to open using appendvfs.\n"
3335 ".bail on|off Stop after hitting an error. Default OFF\n"
3336 ".binary on|off Turn binary output on or off. Default OFF\n"
3337 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3338 ".changes on|off Show number of rows changed by SQL\n"
3339 ".check GLOB Fail if output since .testcase does not match\n"
3340 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3341 ".databases List names and files of attached databases\n"
3342 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options\n"
3343 ".dbinfo ?DB? Show status information about the database\n"
3344 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3345 " If TABLE specified, only dump tables matching\n"
3346 " LIKE pattern TABLE.\n"
3347 ".echo on|off Turn command echo on or off\n"
3348 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3349 ".excel Display the output of next command in a spreadsheet\n"
3350 ".exit Exit this program\n"
3351 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
3352 /* Because explain mode comes on automatically now, the ".explain" mode
3353 ** is removed from the help screen. It is still supported for legacy, however */
3354 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3355 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3356 ".headers on|off Turn display of headers on or off\n"
3357 ".help Show this message\n"
3358 ".import FILE TABLE Import data from FILE into TABLE\n"
3359 #ifndef SQLITE_OMIT_TEST_CONTROL
3360 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3362 ".indexes ?TABLE? Show names of all indexes\n"
3363 " If TABLE specified, only show indexes for tables\n"
3364 " matching LIKE pattern TABLE.\n"
3365 #ifdef SQLITE_ENABLE_IOTRACE
3366 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3368 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3369 ".lint OPTIONS Report potential schema issues. Options:\n"
3370 " fkey-indexes Find missing foreign key indexes\n"
3371 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3372 ".load FILE ?ENTRY? Load an extension library\n"
3374 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3375 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3376 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3377 " csv Comma-separated values\n"
3378 " column Left-aligned columns. (See .width)\n"
3379 " html HTML <table> code\n"
3380 " insert SQL insert statements for TABLE\n"
3381 " line One value per line\n"
3382 " list Values delimited by \"|\"\n"
3383 " quote Escape answers as for SQL\n"
3384 " tabs Tab-separated values\n"
3385 " tcl TCL list elements\n"
3386 ".nullvalue STRING Use STRING in place of NULL values\n"
3387 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
3388 " or invoke system text editor (-e) or spreadsheet (-x)\n"
3390 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3391 " The --new option starts with an empty file\n"
3392 " Other options: --readonly --append --zip\n"
3393 ".output ?FILE? Send output to FILE or stdout\n"
3394 ".print STRING... Print literal STRING\n"
3395 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3396 ".quit Exit this program\n"
3397 ".read FILENAME Execute SQL in FILENAME\n"
3398 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3399 ".save FILE Write in-memory database into FILE\n"
3400 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3401 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3402 " Add --indent for pretty-printing\n"
3403 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3404 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3405 " separator for both the output mode and .import\n"
3406 #if defined(SQLITE_ENABLE_SESSION)
3407 ".session CMD ... Create or control sessions\n"
3409 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3410 #ifndef SQLITE_NOHAVE_SYSTEM
3411 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3413 ".show Show the current values for various settings\n"
3414 ".stats ?on|off? Show stats or turn stats on or off\n"
3415 #ifndef SQLITE_NOHAVE_SYSTEM
3416 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3418 ".tables ?TABLE? List names of tables\n"
3419 " If TABLE specified, only list tables matching\n"
3420 " LIKE pattern TABLE.\n"
3421 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3422 ".timeout MS Try opening locked tables for MS milliseconds\n"
3423 ".timer on|off Turn SQL timer on or off\n"
3424 ".trace FILE|off Output each SQL statement as it is run\n"
3425 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3426 ".vfslist List all available VFSes\n"
3427 ".vfsname ?AUX? Print the name of the VFS stack\n"
3428 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3429 " Negative values right-justify\n"
3432 #if defined(SQLITE_ENABLE_SESSION)
3434 ** Print help information for the ".sessions" command
3436 void session_help(ShellState
*p
){
3438 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3439 "If ?NAME? is omitted, the first defined session is used.\n"
3441 " attach TABLE Attach TABLE\n"
3442 " changeset FILE Write a changeset into FILE\n"
3443 " close Close one session\n"
3444 " enable ?BOOLEAN? Set or query the enable bit\n"
3445 " filter GLOB... Reject tables matching GLOBs\n"
3446 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3447 " isempty Query whether the session is empty\n"
3448 " list List currently open session names\n"
3449 " open DB NAME Open a new session on DB\n"
3450 " patchset FILE Write a patchset into FILE\n"
3456 /* Forward reference */
3457 static int process_input(ShellState
*p
, FILE *in
);
3460 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3461 ** and return a pointer to the buffer. The caller is responsible for freeing
3464 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3467 ** For convenience, a nul-terminator byte is always appended to the data read
3468 ** from the file before the buffer is returned. This byte is not included in
3469 ** the final value of (*pnByte), if applicable.
3471 ** NULL is returned if any error is encountered. The final value of *pnByte
3472 ** is undefined in this case.
3474 static char *readFile(const char *zName
, int *pnByte
){
3475 FILE *in
= fopen(zName
, "rb");
3479 if( in
==0 ) return 0;
3480 fseek(in
, 0, SEEK_END
);
3483 pBuf
= sqlite3_malloc64( nIn
+1 );
3484 if( pBuf
==0 ) return 0;
3485 nRead
= fread(pBuf
, nIn
, 1, in
);
3492 if( pnByte
) *pnByte
= nIn
;
3496 #if defined(SQLITE_ENABLE_SESSION)
3498 ** Close a single OpenSession object and release all of its associated
3501 static void session_close(OpenSession
*pSession
){
3503 sqlite3session_delete(pSession
->p
);
3504 sqlite3_free(pSession
->zName
);
3505 for(i
=0; i
<pSession
->nFilter
; i
++){
3506 sqlite3_free(pSession
->azFilter
[i
]);
3508 sqlite3_free(pSession
->azFilter
);
3509 memset(pSession
, 0, sizeof(OpenSession
));
3514 ** Close all OpenSession objects and release all associated resources.
3516 #if defined(SQLITE_ENABLE_SESSION)
3517 static void session_close_all(ShellState
*p
){
3519 for(i
=0; i
<p
->nSession
; i
++){
3520 session_close(&p
->aSession
[i
]);
3525 # define session_close_all(X)
3529 ** Implementation of the xFilter function for an open session. Omit
3530 ** any tables named by ".session filter" but let all other table through.
3532 #if defined(SQLITE_ENABLE_SESSION)
3533 static int session_filter(void *pCtx
, const char *zTab
){
3534 OpenSession
*pSession
= (OpenSession
*)pCtx
;
3536 for(i
=0; i
<pSession
->nFilter
; i
++){
3537 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
3544 ** Try to deduce the type of file for zName based on its content. Return
3545 ** one of the SHELL_OPEN_* constants.
3547 ** If the file does not exist or is empty but its name looks like a ZIP
3548 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3549 ** Otherwise, assume an ordinary database regardless of the filename if
3550 ** the type cannot be determined from content.
3552 int deduceDatabaseType(const char *zName
, int dfltZip
){
3553 FILE *f
= fopen(zName
, "rb");
3555 int rc
= SHELL_OPEN_UNSPEC
;
3558 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
3559 return SHELL_OPEN_ZIPFILE
;
3561 return SHELL_OPEN_NORMAL
;
3564 fseek(f
, -25, SEEK_END
);
3565 n
= fread(zBuf
, 25, 1, f
);
3566 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
3567 rc
= SHELL_OPEN_APPENDVFS
;
3569 fseek(f
, -22, SEEK_END
);
3570 n
= fread(zBuf
, 22, 1, f
);
3571 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
3573 rc
= SHELL_OPEN_ZIPFILE
;
3574 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
3575 rc
= SHELL_OPEN_ZIPFILE
;
3582 /* Flags for open_db().
3584 ** The default behavior of open_db() is to exit(1) if the database fails to
3585 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3586 ** but still returns without calling exit.
3588 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3589 ** ZIP archive if the file does not exist or is empty and its name matches
3590 ** the *.zip pattern.
3592 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3593 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3596 ** Make sure the database is open. If it is not, then open it. If
3597 ** the database fails to open, print an error message and exit.
3599 static void open_db(ShellState
*p
, int openFlags
){
3601 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
3602 if( p
->zDbFilename
==0 || p
->zDbFilename
[0]==0 ){
3603 p
->openMode
= SHELL_OPEN_NORMAL
;
3605 p
->openMode
= (u8
)deduceDatabaseType(p
->zDbFilename
,
3606 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
3609 switch( p
->openMode
){
3610 case SHELL_OPEN_APPENDVFS
: {
3611 sqlite3_open_v2(p
->zDbFilename
, &p
->db
,
3612 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, "apndvfs");
3615 case SHELL_OPEN_ZIPFILE
: {
3616 sqlite3_open(":memory:", &p
->db
);
3619 case SHELL_OPEN_READONLY
: {
3620 sqlite3_open_v2(p
->zDbFilename
, &p
->db
, SQLITE_OPEN_READONLY
, 0);
3623 case SHELL_OPEN_UNSPEC
:
3624 case SHELL_OPEN_NORMAL
: {
3625 sqlite3_open(p
->zDbFilename
, &p
->db
);
3630 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3631 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
3632 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
3633 if( openFlags
& OPEN_DB_KEEPALIVE
) return;
3636 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3637 sqlite3_enable_load_extension(p
->db
, 1);
3639 sqlite3_fileio_init(p
->db
, 0, 0);
3640 sqlite3_shathree_init(p
->db
, 0, 0);
3641 sqlite3_completion_init(p
->db
, 0, 0);
3642 #ifdef SQLITE_HAVE_ZLIB
3643 sqlite3_zipfile_init(p
->db
, 0, 0);
3644 sqlite3_sqlar_init(p
->db
, 0, 0);
3646 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
3647 shellAddSchemaName
, 0, 0);
3648 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
3649 shellModuleSchema
, 0, 0);
3650 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
3651 shellPutsFunc
, 0, 0);
3652 #ifndef SQLITE_NOHAVE_SYSTEM
3653 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
3655 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
3658 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
3659 char *zSql
= sqlite3_mprintf(
3660 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p
->zDbFilename
);
3661 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
3668 ** Attempt to close the databaes connection. Report errors.
3670 void close_db(sqlite3
*db
){
3671 int rc
= sqlite3_close(db
);
3673 utf8_printf(stderr
, "Error: sqlite3_close() returns %d: %s\n",
3674 rc
, sqlite3_errmsg(db
));
3678 #if HAVE_READLINE || HAVE_EDITLINE
3680 ** Readline completion callbacks
3682 static char *readline_completion_generator(const char *text
, int state
){
3683 static sqlite3_stmt
*pStmt
= 0;
3687 sqlite3_finalize(pStmt
);
3688 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3689 " FROM completion(%Q) ORDER BY 1", text
);
3690 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3693 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3694 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
3696 sqlite3_finalize(pStmt
);
3702 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
3703 rl_attempted_completion_over
= 1;
3704 return rl_completion_matches(zText
, readline_completion_generator
);
3707 #elif HAVE_LINENOISE
3709 ** Linenoise completion callback
3711 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
3712 int nLine
= strlen30(zLine
);
3714 sqlite3_stmt
*pStmt
= 0;
3718 if( nLine
>sizeof(zBuf
)-30 ) return;
3719 if( zLine
[0]=='.' || zLine
[0]=='#') return;
3720 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
3721 if( i
==nLine
-1 ) return;
3723 memcpy(zBuf
, zLine
, iStart
);
3724 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3725 " FROM completion(%Q,%Q) ORDER BY 1",
3726 &zLine
[iStart
], zLine
);
3727 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3729 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3730 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3731 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
3732 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
3733 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
3734 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
3735 linenoiseAddCompletion(lc
, zBuf
);
3738 sqlite3_finalize(pStmt
);
3743 ** Do C-language style dequoting.
3749 ** \v -> vertical tab
3751 ** \r -> carriage return
3756 ** \NNN -> ascii character NNN in octal
3758 static void resolve_backslashes(char *z
){
3761 while( *z
&& *z
!='\\' ) z
++;
3762 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
3763 if( c
=='\\' && z
[i
+1]!=0 ){
3781 }else if( c
=='\'' ){
3783 }else if( c
=='\\' ){
3785 }else if( c
>='0' && c
<='7' ){
3787 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3789 c
= (c
<<3) + z
[i
] - '0';
3790 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3792 c
= (c
<<3) + z
[i
] - '0';
3803 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3804 ** for TRUE and FALSE. Return the integer value if appropriate.
3806 static int booleanValue(const char *zArg
){
3808 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3809 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3811 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3813 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3814 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3817 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3820 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3826 ** Set or clear a shell flag according to a boolean value.
3828 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3829 if( booleanValue(zArg
) ){
3830 ShellSetFlag(p
, mFlag
);
3832 ShellClearFlag(p
, mFlag
);
3837 ** Close an output file, assuming it is not stderr or stdout
3839 static void output_file_close(FILE *f
){
3840 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3844 ** Try to open an output file. The names "stdout" and "stderr" are
3845 ** recognized and do the right thing. NULL is returned if the output
3846 ** filename is "off".
3848 static FILE *output_file_open(const char *zFile
, int bTextMode
){
3850 if( strcmp(zFile
,"stdout")==0 ){
3852 }else if( strcmp(zFile
, "stderr")==0 ){
3854 }else if( strcmp(zFile
, "off")==0 ){
3857 f
= fopen(zFile
, bTextMode
? "w" : "wb");
3859 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3865 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3867 ** A routine for handling output from sqlite3_trace().
3869 static int sql_trace_callback(
3875 FILE *f
= (FILE*)pArg
;
3876 UNUSED_PARAMETER(mType
);
3877 UNUSED_PARAMETER(pP
);
3879 const char *z
= (const char*)pX
;
3880 int i
= strlen30(z
);
3881 while( i
>0 && z
[i
-1]==';' ){ i
--; }
3882 utf8_printf(f
, "%.*s;\n", i
, z
);
3889 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3890 ** a useful spot to set a debugger breakpoint.
3892 static void test_breakpoint(void){
3893 static int nCall
= 0;
3898 ** An object used to read a CSV and other files for import.
3900 typedef struct ImportCtx ImportCtx
;
3902 const char *zFile
; /* Name of the input file */
3903 FILE *in
; /* Read the CSV text from this input stream */
3904 char *z
; /* Accumulated text for a field */
3905 int n
; /* Number of bytes in z */
3906 int nAlloc
; /* Space allocated for z[] */
3907 int nLine
; /* Current line number */
3908 int bNotFirst
; /* True if one or more bytes already read */
3909 int cTerm
; /* Character that terminated the most recent field */
3910 int cColSep
; /* The column separator character. (Usually ",") */
3911 int cRowSep
; /* The row separator character. (Usually "\n") */
3914 /* Append a single byte to z[] */
3915 static void import_append_char(ImportCtx
*p
, int c
){
3916 if( p
->n
+1>=p
->nAlloc
){
3917 p
->nAlloc
+= p
->nAlloc
+ 100;
3918 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
3919 if( p
->z
==0 ) shell_out_of_memory();
3921 p
->z
[p
->n
++] = (char)c
;
3924 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3925 ** with the option of having a separator other than ",".
3927 ** + Input comes from p->in.
3928 ** + Store results in p->z of length p->n. Space to hold p->z comes
3929 ** from sqlite3_malloc64().
3930 ** + Use p->cSep as the column separator. The default is ",".
3931 ** + Use p->rSep as the row separator. The default is "\n".
3932 ** + Keep track of the line number in p->nLine.
3933 ** + Store the character that terminates the field in p->cTerm. Store
3934 ** EOF on end-of-file.
3935 ** + Report syntax errors on stderr
3937 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
3939 int cSep
= p
->cColSep
;
3940 int rSep
= p
->cRowSep
;
3943 if( c
==EOF
|| seenInterrupt
){
3949 int startLine
= p
->nLine
;
3954 if( c
==rSep
) p
->nLine
++;
3961 if( (c
==cSep
&& pc
==cQuote
)
3962 || (c
==rSep
&& pc
==cQuote
)
3963 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
3964 || (c
==EOF
&& pc
==cQuote
)
3966 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
3970 if( pc
==cQuote
&& c
!='\r' ){
3971 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
3972 p
->zFile
, p
->nLine
, cQuote
);
3975 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
3976 p
->zFile
, startLine
, cQuote
);
3980 import_append_char(p
, c
);
3985 /* If this is the first field being parsed and it begins with the
3986 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3987 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
3988 import_append_char(p
, c
);
3990 if( (c
&0xff)==0xbb ){
3991 import_append_char(p
, c
);
3993 if( (c
&0xff)==0xbf ){
3996 return csv_read_one_field(p
);
4000 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
4001 import_append_char(p
, c
);
4006 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
4010 if( p
->z
) p
->z
[p
->n
] = 0;
4015 /* Read a single field of ASCII delimited text.
4017 ** + Input comes from p->in.
4018 ** + Store results in p->z of length p->n. Space to hold p->z comes
4019 ** from sqlite3_malloc64().
4020 ** + Use p->cSep as the column separator. The default is "\x1F".
4021 ** + Use p->rSep as the row separator. The default is "\x1E".
4022 ** + Keep track of the row number in p->nLine.
4023 ** + Store the character that terminates the field in p->cTerm. Store
4024 ** EOF on end-of-file.
4025 ** + Report syntax errors on stderr
4027 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
4029 int cSep
= p
->cColSep
;
4030 int rSep
= p
->cRowSep
;
4033 if( c
==EOF
|| seenInterrupt
){
4037 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
4038 import_append_char(p
, c
);
4045 if( p
->z
) p
->z
[p
->n
] = 0;
4050 ** Try to transfer data for table zTable. If an error is seen while
4051 ** moving forward, try to go backwards. The backwards movement won't
4052 ** work for WITHOUT ROWID tables.
4054 static void tryToCloneData(
4059 sqlite3_stmt
*pQuery
= 0;
4060 sqlite3_stmt
*pInsert
= 0;
4065 int nTable
= strlen30(zTable
);
4068 const int spinRate
= 10000;
4070 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
4071 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4073 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
4074 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4078 n
= sqlite3_column_count(pQuery
);
4079 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
4080 if( zInsert
==0 ) shell_out_of_memory();
4081 sqlite3_snprintf(200+nTable
,zInsert
,
4082 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
4083 i
= strlen30(zInsert
);
4085 memcpy(zInsert
+i
, ",?", 2);
4088 memcpy(zInsert
+i
, ");", 3);
4089 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
4091 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
4092 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
4097 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4099 switch( sqlite3_column_type(pQuery
, i
) ){
4101 sqlite3_bind_null(pInsert
, i
+1);
4104 case SQLITE_INTEGER
: {
4105 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
4108 case SQLITE_FLOAT
: {
4109 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
4113 sqlite3_bind_text(pInsert
, i
+1,
4114 (const char*)sqlite3_column_text(pQuery
,i
),
4119 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
4120 sqlite3_column_bytes(pQuery
,i
),
4126 rc
= sqlite3_step(pInsert
);
4127 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
4128 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
4129 sqlite3_errmsg(newDb
));
4131 sqlite3_reset(pInsert
);
4133 if( (cnt
%spinRate
)==0 ){
4134 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
4138 if( rc
==SQLITE_DONE
) break;
4139 sqlite3_finalize(pQuery
);
4140 sqlite3_free(zQuery
);
4141 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4143 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4145 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
4148 } /* End for(k=0...) */
4151 sqlite3_finalize(pQuery
);
4152 sqlite3_finalize(pInsert
);
4153 sqlite3_free(zQuery
);
4154 sqlite3_free(zInsert
);
4159 ** Try to transfer all rows of the schema that match zWhere. For
4160 ** each row, invoke xForEach() on the object defined by that row.
4161 ** If an error is encountered while moving forward through the
4162 ** sqlite_master table, try again moving backwards.
4164 static void tryToCloneSchema(
4168 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
4170 sqlite3_stmt
*pQuery
= 0;
4173 const unsigned char *zName
;
4174 const unsigned char *zSql
;
4177 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4178 " WHERE %s", zWhere
);
4179 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4181 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4182 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4184 goto end_schema_xfer
;
4186 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4187 zName
= sqlite3_column_text(pQuery
, 0);
4188 zSql
= sqlite3_column_text(pQuery
, 1);
4189 printf("%s... ", zName
); fflush(stdout
);
4190 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4192 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4193 sqlite3_free(zErrMsg
);
4197 xForEach(p
, newDb
, (const char*)zName
);
4201 if( rc
!=SQLITE_DONE
){
4202 sqlite3_finalize(pQuery
);
4203 sqlite3_free(zQuery
);
4204 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4205 " WHERE %s ORDER BY rowid DESC", zWhere
);
4206 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4208 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4209 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4211 goto end_schema_xfer
;
4213 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4214 zName
= sqlite3_column_text(pQuery
, 0);
4215 zSql
= sqlite3_column_text(pQuery
, 1);
4216 printf("%s... ", zName
); fflush(stdout
);
4217 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4219 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4220 sqlite3_free(zErrMsg
);
4224 xForEach(p
, newDb
, (const char*)zName
);
4230 sqlite3_finalize(pQuery
);
4231 sqlite3_free(zQuery
);
4235 ** Open a new database file named "zNewDb". Try to recover as much information
4236 ** as possible out of the main database (which might be corrupt) and write it
4239 static void tryToClone(ShellState
*p
, const char *zNewDb
){
4242 if( access(zNewDb
,0)==0 ){
4243 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
4246 rc
= sqlite3_open(zNewDb
, &newDb
);
4248 utf8_printf(stderr
, "Cannot create output database: %s\n",
4249 sqlite3_errmsg(newDb
));
4251 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
4252 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
4253 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
4254 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
4255 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
4256 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4262 ** Change the output file back to stdout.
4264 ** If the p->doXdgOpen flag is set, that means the output was being
4265 ** redirected to a temporary file named by p->zTempFile. In that case,
4266 ** launch start/open/xdg-open on that temporary file.
4268 static void output_reset(ShellState
*p
){
4269 if( p
->outfile
[0]=='|' ){
4270 #ifndef SQLITE_OMIT_POPEN
4274 output_file_close(p
->out
);
4275 #ifndef SQLITE_NOHAVE_SYSTEM
4277 const char *zXdgOpenCmd
=
4280 #elif defined(__APPLE__)
4286 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
4288 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
4294 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4301 ** Run an SQL command and return the single integer result.
4303 static int db_int(ShellState
*p
, const char *zSql
){
4304 sqlite3_stmt
*pStmt
;
4306 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4307 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
4308 res
= sqlite3_column_int(pStmt
,0);
4310 sqlite3_finalize(pStmt
);
4315 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
4317 static unsigned int get2byteInt(unsigned char *a
){
4318 return (a
[0]<<8) + a
[1];
4320 static unsigned int get4byteInt(unsigned char *a
){
4321 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
4325 ** Implementation of the ".info" command.
4327 ** Return 1 on error, 2 to exit, and 0 otherwise.
4329 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
4330 static const struct { const char *zName
; int ofst
; } aField
[] = {
4331 { "file change counter:", 24 },
4332 { "database page count:", 28 },
4333 { "freelist page count:", 36 },
4334 { "schema cookie:", 40 },
4335 { "schema format:", 44 },
4336 { "default cache size:", 48 },
4337 { "autovacuum top root:", 52 },
4338 { "incremental vacuum:", 64 },
4339 { "text encoding:", 56 },
4340 { "user version:", 60 },
4341 { "application id:", 68 },
4342 { "software version:", 96 },
4344 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
4345 { "number of tables:",
4346 "SELECT count(*) FROM %s WHERE type='table'" },
4347 { "number of indexes:",
4348 "SELECT count(*) FROM %s WHERE type='index'" },
4349 { "number of triggers:",
4350 "SELECT count(*) FROM %s WHERE type='trigger'" },
4351 { "number of views:",
4352 "SELECT count(*) FROM %s WHERE type='view'" },
4354 "SELECT total(length(sql)) FROM %s" },
4358 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
4359 sqlite3_stmt
*pStmt
= 0;
4360 unsigned char aHdr
[100];
4362 if( p
->db
==0 ) return 1;
4363 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4365 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
4366 if( sqlite3_step(pStmt
)==SQLITE_ROW
4367 && sqlite3_column_bytes(pStmt
,0)>100
4369 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
4370 sqlite3_finalize(pStmt
);
4372 raw_printf(stderr
, "unable to read database header\n");
4373 sqlite3_finalize(pStmt
);
4376 i
= get2byteInt(aHdr
+16);
4377 if( i
==1 ) i
= 65536;
4378 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
4379 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
4380 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
4381 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
4382 for(i
=0; i
<ArraySize(aField
); i
++){
4383 int ofst
= aField
[i
].ofst
;
4384 unsigned int val
= get4byteInt(aHdr
+ ofst
);
4385 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
4388 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
4389 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
4390 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
4393 raw_printf(p
->out
, "\n");
4396 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
4397 }else if( strcmp(zDb
,"temp")==0 ){
4398 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
4400 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
4402 for(i
=0; i
<ArraySize(aQuery
); i
++){
4403 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
4404 int val
= db_int(p
, zSql
);
4406 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
4408 sqlite3_free(zSchemaTab
);
4413 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4415 static int shellDatabaseError(sqlite3
*db
){
4416 const char *zErr
= sqlite3_errmsg(db
);
4417 utf8_printf(stderr
, "Error: %s\n", zErr
);
4422 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4423 ** if they match and FALSE (0) if they do not match.
4427 ** '*' Matches any sequence of zero or more characters.
4429 ** '?' Matches exactly one character.
4431 ** [...] Matches one character from the enclosed list of
4434 ** [^...] Matches one character not in the enclosed list.
4436 ** '#' Matches any sequence of one or more digits with an
4437 ** optional + or - sign in front
4439 ** ' ' Any span of whitespace matches any other span of
4442 ** Extra whitespace at the end of z[] is ignored.
4444 static int testcase_glob(const char *zGlob
, const char *z
){
4449 while( (c
= (*(zGlob
++)))!=0 ){
4451 if( !IsSpace(*z
) ) return 0;
4452 while( IsSpace(*zGlob
) ) zGlob
++;
4453 while( IsSpace(*z
) ) z
++;
4455 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
4456 if( c
=='?' && (*(z
++))==0 ) return 0;
4461 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
4466 while( (c2
= (*(z
++)))!=0 ){
4469 if( c2
==0 ) return 0;
4471 if( testcase_glob(zGlob
,z
) ) return 1;
4475 if( (*(z
++))==0 ) return 0;
4481 if( c
==0 ) return 0;
4488 if( c
==']' ) seen
= 1;
4491 while( c2
&& c2
!=']' ){
4492 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
4494 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
4504 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
4506 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
4507 if( !IsDigit(z
[0]) ) return 0;
4509 while( IsDigit(z
[0]) ){ z
++; }
4511 if( c
!=(*(z
++)) ) return 0;
4514 while( IsSpace(*z
) ){ z
++; }
4520 ** Compare the string as a command-line option with either one or two
4521 ** initial "-" characters.
4523 static int optionMatch(const char *zStr
, const char *zOpt
){
4524 if( zStr
[0]!='-' ) return 0;
4526 if( zStr
[0]=='-' ) zStr
++;
4527 return strcmp(zStr
, zOpt
)==0;
4533 int shellDeleteFile(const char *zFilename
){
4536 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
4540 rc
= unlink(zFilename
);
4546 ** Try to delete the temporary file (if there is one) and free the
4547 ** memory used to hold the name of the temp file.
4549 static void clearTempFile(ShellState
*p
){
4550 if( p
->zTempFile
==0 ) return;
4551 if( p
->doXdgOpen
) return;
4552 if( shellDeleteFile(p
->zTempFile
) ) return;
4553 sqlite3_free(p
->zTempFile
);
4558 ** Create a new temp file name with the given suffix.
4560 static void newTempFile(ShellState
*p
, const char *zSuffix
){
4562 sqlite3_free(p
->zTempFile
);
4565 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
4567 if( p
->zTempFile
==0 ){
4569 sqlite3_randomness(sizeof(r
), &r
);
4570 p
->zTempFile
= sqlite3_mprintf("temp%llx.%s", r
, zSuffix
);
4572 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
4574 if( p
->zTempFile
==0 ){
4575 raw_printf(stderr
, "out of memory\n");
4582 ** The implementation of SQL scalar function fkey_collate_clause(), used
4583 ** by the ".lint fkey-indexes" command. This scalar function is always
4584 ** called with four arguments - the parent table name, the parent column name,
4585 ** the child table name and the child column name.
4587 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4589 ** If either of the named tables or columns do not exist, this function
4590 ** returns an empty string. An empty string is also returned if both tables
4591 ** and columns exist but have the same default collation sequence. Or,
4592 ** if both exist but the default collation sequences are different, this
4593 ** function returns the string " COLLATE <parent-collation>", where
4594 ** <parent-collation> is the default collation sequence of the parent column.
4596 static void shellFkeyCollateClause(
4597 sqlite3_context
*pCtx
,
4599 sqlite3_value
**apVal
4601 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
4602 const char *zParent
;
4603 const char *zParentCol
;
4604 const char *zParentSeq
;
4606 const char *zChildCol
;
4607 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
4611 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
4612 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
4613 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
4614 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
4616 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
4617 rc
= sqlite3_table_column_metadata(
4618 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
4620 if( rc
==SQLITE_OK
){
4621 rc
= sqlite3_table_column_metadata(
4622 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
4626 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
4627 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
4628 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
4635 ** The implementation of dot-command ".lint fkey-indexes".
4637 static int lintFkeyIndexes(
4638 ShellState
*pState
, /* Current shell tool state */
4639 char **azArg
, /* Array of arguments passed to dot command */
4640 int nArg
/* Number of entries in azArg[] */
4642 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
4643 FILE *out
= pState
->out
; /* Stream to write non-error output to */
4644 int bVerbose
= 0; /* If -verbose is present */
4645 int bGroupByParent
= 0; /* If -groupbyparent is present */
4646 int i
; /* To iterate through azArg[] */
4647 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
4648 int rc
; /* Return code */
4649 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
4652 ** This SELECT statement returns one row for each foreign key constraint
4653 ** in the schema of the main database. The column values are:
4655 ** 0. The text of an SQL statement similar to:
4657 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4659 ** This SELECT is similar to the one that the foreign keys implementation
4660 ** needs to run internally on child tables. If there is an index that can
4661 ** be used to optimize this query, then it can also be used by the FK
4662 ** implementation to optimize DELETE or UPDATE statements on the parent
4665 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4666 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4667 ** contains an index that can be used to optimize the query.
4669 ** 2. Human readable text that describes the child table and columns. e.g.
4671 ** "child_table(child_key1, child_key2)"
4673 ** 3. Human readable text that describes the parent table and columns. e.g.
4675 ** "parent_table(parent_key1, parent_key2)"
4677 ** 4. A full CREATE INDEX statement for an index that could be used to
4678 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4680 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4682 ** 5. The name of the parent table.
4684 ** These six values are used by the C logic below to generate the report.
4688 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4689 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4690 " || fkey_collate_clause("
4691 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4693 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4694 " || group_concat('*=?', ' AND ') || ')'"
4696 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4698 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4700 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4701 " || ' ON ' || quote(s.name) || '('"
4702 " || group_concat(quote(f.[from]) ||"
4703 " fkey_collate_clause("
4704 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4708 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4709 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4710 "GROUP BY s.name, f.id "
4711 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4713 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4715 for(i
=2; i
<nArg
; i
++){
4716 int n
= strlen30(azArg
[i
]);
4717 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
4720 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
4725 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4728 return SQLITE_ERROR
;
4732 /* Register the fkey_collate_clause() SQL function */
4733 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
4734 0, shellFkeyCollateClause
, 0, 0
4738 if( rc
==SQLITE_OK
){
4739 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
4741 if( rc
==SQLITE_OK
){
4742 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
4745 if( rc
==SQLITE_OK
){
4748 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
4750 sqlite3_stmt
*pExplain
= 0;
4751 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
4752 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
4753 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
4754 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
4755 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4756 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4758 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4759 if( rc
!=SQLITE_OK
) break;
4760 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4761 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4763 0==sqlite3_strglob(zGlob
, zPlan
)
4764 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4767 rc
= sqlite3_finalize(pExplain
);
4768 if( rc
!=SQLITE_OK
) break;
4771 raw_printf(stderr
, "Error: internal error");
4775 && (bVerbose
|| res
==0)
4776 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4778 raw_printf(out
, "-- Parent table %s\n", zParent
);
4779 sqlite3_free(zPrev
);
4780 zPrev
= sqlite3_mprintf("%s", zParent
);
4784 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4785 }else if( bVerbose
){
4786 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4787 zIndent
, zFrom
, zTarget
4792 sqlite3_free(zPrev
);
4794 if( rc
!=SQLITE_OK
){
4795 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4798 rc2
= sqlite3_finalize(pSql
);
4799 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4801 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4804 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4811 ** Implementation of ".lint" dot command.
4813 static int lintDotCommand(
4814 ShellState
*pState
, /* Current shell tool state */
4815 char **azArg
, /* Array of arguments passed to dot command */
4816 int nArg
/* Number of entries in azArg[] */
4819 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
4820 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4821 return lintFkeyIndexes(pState
, azArg
, nArg
);
4824 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4825 raw_printf(stderr
, "Where sub-commands are:\n");
4826 raw_printf(stderr
, " fkey-indexes\n");
4827 return SQLITE_ERROR
;
4830 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4831 /*********************************************************************************
4832 ** The ".archive" or ".ar" command.
4834 static void shellPrepare(
4838 sqlite3_stmt
**ppStmt
4841 if( *pRc
==SQLITE_OK
){
4842 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
4843 if( rc
!=SQLITE_OK
){
4844 raw_printf(stderr
, "sql error: %s (%d)\n",
4845 sqlite3_errmsg(db
), sqlite3_errcode(db
)
4852 static void shellPreparePrintf(
4855 sqlite3_stmt
**ppStmt
,
4860 if( *pRc
==SQLITE_OK
){
4864 z
= sqlite3_vmprintf(zFmt
, ap
);
4866 *pRc
= SQLITE_NOMEM
;
4868 shellPrepare(db
, pRc
, z
, ppStmt
);
4874 static void shellFinalize(
4879 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4880 int rc
= sqlite3_finalize(pStmt
);
4881 if( *pRc
==SQLITE_OK
){
4882 if( rc
!=SQLITE_OK
){
4883 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4890 static void shellReset(
4894 int rc
= sqlite3_reset(pStmt
);
4895 if( *pRc
==SQLITE_OK
){
4896 if( rc
!=SQLITE_OK
){
4897 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4898 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4904 ** Structure representing a single ".ar" command.
4906 typedef struct ArCommand ArCommand
;
4908 u8 eCmd
; /* An AR_CMD_* value */
4909 u8 bVerbose
; /* True if --verbose */
4910 u8 bZip
; /* True if the archive is a ZIP */
4911 u8 bDryRun
; /* True if --dry-run */
4912 u8 bAppend
; /* True if --append */
4913 u8 fromCmdLine
; /* Run from -A instead of .archive */
4914 int nArg
; /* Number of command arguments */
4915 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
4916 const char *zFile
; /* --file argument, or NULL */
4917 const char *zDir
; /* --directory argument, or NULL */
4918 char **azArg
; /* Array of command arguments */
4919 ShellState
*p
; /* Shell state */
4920 sqlite3
*db
; /* Database containing the archive */
4924 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4926 static int arUsage(FILE *f
){
4929 "Usage: .ar [OPTION...] [FILE...]\n"
4930 "The .ar command manages sqlar archives.\n"
4933 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4934 " .ar -tf archive.sar # List members of archive.sar\n"
4935 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4937 "Each command line must feature exactly one command option:\n"
4938 " -c, --create Create a new archive\n"
4939 " -u, --update Update or add files to an existing archive\n"
4940 " -t, --list List contents of archive\n"
4941 " -x, --extract Extract files from archive\n"
4943 "And zero or more optional options:\n"
4944 " -v, --verbose Print each filename as it is processed\n"
4945 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4946 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
4947 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4948 " -n, --dryrun Show the SQL that would have occurred\n"
4950 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4953 return SQLITE_ERROR
;
4957 ** Print an error message for the .ar command to stderr and return
4960 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
4964 z
= sqlite3_vmprintf(zFmt
, ap
);
4966 utf8_printf(stderr
, "Error: %s\n", z
);
4967 if( pAr
->fromCmdLine
){
4968 utf8_printf(stderr
, "Use \"-A\" for more help\n");
4970 utf8_printf(stderr
, "Use \".archive --help\" for more help\n");
4973 return SQLITE_ERROR
;
4977 ** Values for ArCommand.eCmd.
4979 #define AR_CMD_CREATE 1
4980 #define AR_CMD_EXTRACT 2
4981 #define AR_CMD_LIST 3
4982 #define AR_CMD_UPDATE 4
4983 #define AR_CMD_HELP 5
4986 ** Other (non-command) switches.
4988 #define AR_SWITCH_VERBOSE 6
4989 #define AR_SWITCH_FILE 7
4990 #define AR_SWITCH_DIRECTORY 8
4991 #define AR_SWITCH_APPEND 9
4992 #define AR_SWITCH_DRYRUN 10
4994 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
4997 case AR_CMD_EXTRACT
:
5002 return arErrorMsg(pAr
, "multiple command options");
5004 pAr
->eCmd
= eSwitch
;
5007 case AR_SWITCH_DRYRUN
:
5010 case AR_SWITCH_VERBOSE
:
5013 case AR_SWITCH_APPEND
:
5015 /* Fall thru into --file */
5016 case AR_SWITCH_FILE
:
5019 case AR_SWITCH_DIRECTORY
:
5028 ** Parse the command line for an ".ar" command. The results are written into
5029 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5030 ** successfully, otherwise an error message is written to stderr and
5031 ** SQLITE_ERROR returned.
5033 static int arParseCommand(
5034 char **azArg
, /* Array of arguments passed to dot command */
5035 int nArg
, /* Number of entries in azArg[] */
5036 ArCommand
*pAr
/* Populate this object */
5044 { "create", 'c', AR_CMD_CREATE
, 0 },
5045 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
5046 { "list", 't', AR_CMD_LIST
, 0 },
5047 { "update", 'u', AR_CMD_UPDATE
, 0 },
5048 { "help", 'h', AR_CMD_HELP
, 0 },
5049 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
5050 { "file", 'f', AR_SWITCH_FILE
, 1 },
5051 { "append", 'a', AR_SWITCH_APPEND
, 1 },
5052 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
5053 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
5055 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
5056 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
5059 return arUsage(stderr
);
5063 /* Traditional style [tar] invocation */
5066 for(i
=0; z
[i
]; i
++){
5067 const char *zArg
= 0;
5068 struct ArSwitch
*pOpt
;
5069 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5070 if( z
[i
]==pOpt
->cShort
) break;
5073 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
5077 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
5079 zArg
= azArg
[iArg
++];
5081 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5083 pAr
->nArg
= nArg
-iArg
;
5085 pAr
->azArg
= &azArg
[iArg
];
5088 /* Non-traditional invocation */
5090 for(iArg
=1; iArg
<nArg
; iArg
++){
5094 /* All remaining command line words are command arguments. */
5095 pAr
->azArg
= &azArg
[iArg
];
5096 pAr
->nArg
= nArg
-iArg
;
5103 /* One or more short options */
5105 const char *zArg
= 0;
5106 struct ArSwitch
*pOpt
;
5107 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5108 if( z
[i
]==pOpt
->cShort
) break;
5111 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
5118 if( iArg
>=(nArg
-1) ){
5119 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
5121 zArg
= azArg
[++iArg
];
5124 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5126 }else if( z
[2]=='\0' ){
5127 /* A -- option, indicating that all remaining command line words
5128 ** are command arguments. */
5129 pAr
->azArg
= &azArg
[iArg
+1];
5130 pAr
->nArg
= nArg
-iArg
-1;
5134 const char *zArg
= 0; /* Argument for option, if any */
5135 struct ArSwitch
*pMatch
= 0; /* Matching option */
5136 struct ArSwitch
*pOpt
; /* Iterator */
5137 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5138 const char *zLong
= pOpt
->zLong
;
5139 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
5141 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
5149 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
5152 if( iArg
>=(nArg
-1) ){
5153 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
5155 zArg
= azArg
[++iArg
];
5157 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5167 ** This function assumes that all arguments within the ArCommand.azArg[]
5168 ** array refer to archive members, as for the --extract or --list commands.
5169 ** It checks that each of them are present. If any specified file is not
5170 ** present in the archive, an error is printed to stderr and an error
5171 ** code returned. Otherwise, if all specified arguments are present in
5172 ** the archive, SQLITE_OK is returned.
5174 ** This function strips any trailing '/' characters from each argument.
5175 ** This is consistent with the way the [tar] command seems to work on
5178 static int arCheckEntries(ArCommand
*pAr
){
5182 sqlite3_stmt
*pTest
= 0;
5184 shellPreparePrintf(pAr
->db
, &rc
, &pTest
,
5185 "SELECT name FROM %s WHERE name=$name",
5188 j
= sqlite3_bind_parameter_index(pTest
, "$name");
5189 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5190 char *z
= pAr
->azArg
[i
];
5191 int n
= strlen30(z
);
5193 while( n
>0 && z
[n
-1]=='/' ) n
--;
5195 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
5196 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
5199 shellReset(&rc
, pTest
);
5200 if( rc
==SQLITE_OK
&& bOk
==0 ){
5201 utf8_printf(stderr
, "not found in archive: %s\n", z
);
5205 shellFinalize(&rc
, pTest
);
5211 ** Format a WHERE clause that can be used against the "sqlar" table to
5212 ** identify all archive members that match the command arguments held
5213 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5214 ** The caller is responsible for eventually calling sqlite3_free() on
5215 ** any non-NULL (*pzWhere) value.
5217 static void arWhereClause(
5220 char **pzWhere
/* OUT: New WHERE clause */
5223 if( *pRc
==SQLITE_OK
){
5225 zWhere
= sqlite3_mprintf("1");
5228 const char *zSep
= "";
5229 for(i
=0; i
<pAr
->nArg
; i
++){
5230 const char *z
= pAr
->azArg
[i
];
5231 zWhere
= sqlite3_mprintf(
5232 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5233 zWhere
, zSep
, z
, strlen30(z
)+1, z
5236 *pRc
= SQLITE_NOMEM
;
5247 ** Implementation of .ar "lisT" command.
5249 static int arListCommand(ArCommand
*pAr
){
5250 const char *zSql
= "SELECT %s FROM %s WHERE %s";
5251 const char *azCols
[] = {
5253 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5257 sqlite3_stmt
*pSql
= 0;
5260 rc
= arCheckEntries(pAr
);
5261 arWhereClause(&rc
, pAr
, &zWhere
);
5263 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
5264 pAr
->zSrcTable
, zWhere
);
5266 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5268 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5269 if( pAr
->bVerbose
){
5270 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
5271 sqlite3_column_text(pSql
, 0),
5272 sqlite3_column_int(pSql
, 1),
5273 sqlite3_column_text(pSql
, 2),
5274 sqlite3_column_text(pSql
, 3)
5277 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5281 shellFinalize(&rc
, pSql
);
5282 sqlite3_free(zWhere
);
5288 ** Implementation of .ar "eXtract" command.
5290 static int arExtractCommand(ArCommand
*pAr
){
5294 " writefile(($dir || name), %s, mode, mtime) "
5295 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5296 " AND name NOT GLOB '*..[/\\]*'";
5298 const char *azExtraArg
[] = {
5299 "sqlar_uncompress(data, sz)",
5303 sqlite3_stmt
*pSql
= 0;
5309 /* If arguments are specified, check that they actually exist within
5310 ** the archive before proceeding. And formulate a WHERE clause to
5312 rc
= arCheckEntries(pAr
);
5313 arWhereClause(&rc
, pAr
, &zWhere
);
5315 if( rc
==SQLITE_OK
){
5317 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
5319 zDir
= sqlite3_mprintf("");
5321 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
5324 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
5325 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
5328 if( rc
==SQLITE_OK
){
5329 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
5330 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
5332 /* Run the SELECT statement twice. The first time, writefile() is called
5333 ** for all archive members that should be extracted. The second time,
5334 ** only for the directories. This is because the timestamps for
5335 ** extracted directories must be reset after they are populated (as
5336 ** populating them changes the timestamp). */
5338 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
5339 sqlite3_bind_int(pSql
, j
, i
);
5341 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5343 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5344 if( i
==0 && pAr
->bVerbose
){
5345 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5349 shellReset(&rc
, pSql
);
5351 shellFinalize(&rc
, pSql
);
5355 sqlite3_free(zWhere
);
5360 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5362 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
5365 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
5369 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
5371 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
5380 ** Implementation of .ar "create" and "update" commands.
5382 ** Create the "sqlar" table in the database if it does not already exist.
5383 ** Then add each file in the azFile[] array to the archive. Directories
5384 ** are added recursively. If argument bVerbose is non-zero, a message is
5385 ** printed on stdout for each file archived.
5387 ** The create command is the same as update, except that it drops
5388 ** any existing "sqlar" table before beginning.
5390 static int arCreateOrUpdateCommand(
5391 ArCommand
*pAr
, /* Command arguments and options */
5392 int bUpdate
/* true for a --create. false for --update */
5394 const char *zCreate
=
5395 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5396 " name TEXT PRIMARY KEY, -- name of the file\n"
5397 " mode INT, -- access permissions\n"
5398 " mtime INT, -- last modification time\n"
5399 " sz INT, -- original file size\n"
5400 " data BLOB -- compressed content\n"
5402 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
5403 const char *zInsertFmt
[2] = {
5404 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
5409 " CASE substr(lsmode(mode),1,1)\n"
5410 " WHEN '-' THEN length(data)\n"
5411 " WHEN 'd' THEN 0\n"
5413 " sqlar_compress(data)\n"
5414 " FROM fsdir(%Q,%Q)\n"
5415 " WHERE lsmode(mode) NOT LIKE '?%%';",
5416 "REPLACE INTO %s(name,mode,mtime,data)\n"
5422 " FROM fsdir(%Q,%Q)\n"
5423 " WHERE lsmode(mode) NOT LIKE '?%%';"
5425 int i
; /* For iterating through azFile[] */
5426 int rc
; /* Return code */
5427 const char *zTab
= 0; /* SQL table into which to insert */
5431 arExecSql(pAr
, "PRAGMA page_size=512");
5432 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
5433 if( rc
!=SQLITE_OK
) return rc
;
5436 /* Initialize the zipfile virtual table, if necessary */
5439 sqlite3_randomness(sizeof(r
),&r
);
5440 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
5442 zSql
= sqlite3_mprintf(
5443 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5446 rc
= arExecSql(pAr
, zSql
);
5452 /* Initialize the table for an SQLAR */
5455 rc
= arExecSql(pAr
, zDrop
);
5456 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
5458 rc
= arExecSql(pAr
, zCreate
);
5460 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5461 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
5462 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
5463 pAr
->azArg
[i
], pAr
->zDir
);
5464 rc
= arExecSql(pAr
, zSql2
);
5465 sqlite3_free(zSql2
);
5468 if( rc
!=SQLITE_OK
){
5469 arExecSql(pAr
, "ROLLBACK TO ar; RELEASE ar;");
5471 rc
= arExecSql(pAr
, "RELEASE ar;");
5472 if( pAr
->bZip
&& pAr
->zFile
){
5473 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
5474 arExecSql(pAr
, zSql
);
5482 ** Implementation of ".ar" dot command.
5484 static int arDotCommand(
5485 ShellState
*pState
, /* Current shell tool state */
5486 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
5487 char **azArg
, /* Array of arguments passed to dot command */
5488 int nArg
/* Number of entries in azArg[] */
5492 memset(&cmd
, 0, sizeof(cmd
));
5493 cmd
.fromCmdLine
= fromCmdLine
;
5494 rc
= arParseCommand(azArg
, nArg
, &cmd
);
5495 if( rc
==SQLITE_OK
){
5496 int eDbType
= SHELL_OPEN_UNSPEC
;
5498 cmd
.db
= pState
->db
;
5500 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
5502 eDbType
= pState
->openMode
;
5504 if( eDbType
==SHELL_OPEN_ZIPFILE
){
5505 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
5507 cmd
.zSrcTable
= sqlite3_mprintf("zip");
5509 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
5513 }else if( cmd
.zFile
){
5515 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
5516 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5517 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
5519 flags
= SQLITE_OPEN_READONLY
;
5523 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
5524 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
5526 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
5527 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
5528 if( rc
!=SQLITE_OK
){
5529 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
5530 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
5532 goto end_ar_command
;
5534 sqlite3_fileio_init(cmd
.db
, 0, 0);
5535 sqlite3_sqlar_init(cmd
.db
, 0, 0);
5536 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
5537 shellPutsFunc
, 0, 0);
5540 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
5541 if( cmd
.eCmd
!=AR_CMD_CREATE
5542 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
5544 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
5546 goto end_ar_command
;
5548 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
5553 rc
= arCreateOrUpdateCommand(&cmd
, 0);
5556 case AR_CMD_EXTRACT
:
5557 rc
= arExtractCommand(&cmd
);
5561 rc
= arListCommand(&cmd
);
5565 arUsage(pState
->out
);
5569 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
5570 rc
= arCreateOrUpdateCommand(&cmd
, 1);
5575 if( cmd
.db
!=pState
->db
){
5578 sqlite3_free(cmd
.zSrcTable
);
5582 /* End of the ".archive" or ".ar" command logic
5583 **********************************************************************************/
5584 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5588 ** If an input line begins with "." then invoke this routine to
5589 ** process that line.
5591 ** Return 1 on error, 2 to exit, and 0 otherwise.
5593 static int do_meta_command(char *zLine
, ShellState
*p
){
5600 #ifndef SQLITE_OMIT_VIRTUALTABLE
5601 if( p
->expert
.pExpert
){
5602 expertFinish(p
, 1, 0);
5606 /* Parse the input line into tokens.
5608 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
5609 while( IsSpace(zLine
[h
]) ){ h
++; }
5610 if( zLine
[h
]==0 ) break;
5611 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
5612 int delim
= zLine
[h
++];
5613 azArg
[nArg
++] = &zLine
[h
];
5614 while( zLine
[h
] && zLine
[h
]!=delim
){
5615 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
5618 if( zLine
[h
]==delim
){
5621 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
5623 azArg
[nArg
++] = &zLine
[h
];
5624 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
5625 if( zLine
[h
] ) zLine
[h
++] = 0;
5626 resolve_backslashes(azArg
[nArg
-1]);
5630 /* Process the input line.
5632 if( nArg
==0 ) return 0; /* no tokens, no error */
5633 n
= strlen30(azArg
[0]);
5637 #ifndef SQLITE_OMIT_AUTHORIZATION
5638 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
5640 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
5642 goto meta_command_exit
;
5645 if( booleanValue(azArg
[1]) ){
5646 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
5648 sqlite3_set_authorizer(p
->db
, 0, 0);
5653 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5654 if( c
=='a' && strncmp(azArg
[0], "archive", n
)==0 ){
5656 rc
= arDotCommand(p
, 0, azArg
, nArg
);
5660 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
5661 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
5663 const char *zDestFile
= 0;
5664 const char *zDb
= 0;
5666 sqlite3_backup
*pBackup
;
5668 const char *zVfs
= 0;
5669 for(j
=1; j
<nArg
; j
++){
5670 const char *z
= azArg
[j
];
5672 if( z
[1]=='-' ) z
++;
5673 if( strcmp(z
, "-append")==0 ){
5677 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
5680 }else if( zDestFile
==0 ){
5681 zDestFile
= azArg
[j
];
5684 zDestFile
= azArg
[j
];
5686 raw_printf(stderr
, "Usage: .backup ?DB? ?--append? FILENAME\n");
5691 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
5694 if( zDb
==0 ) zDb
= "main";
5695 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
5696 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
5697 if( rc
!=SQLITE_OK
){
5698 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
5703 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
5705 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5709 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
5710 sqlite3_backup_finish(pBackup
);
5711 if( rc
==SQLITE_DONE
){
5714 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5720 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
5722 bail_on_error
= booleanValue(azArg
[1]);
5724 raw_printf(stderr
, "Usage: .bail on|off\n");
5729 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
5731 if( booleanValue(azArg
[1]) ){
5732 setBinaryMode(p
->out
, 1);
5734 setTextMode(p
->out
, 1);
5737 raw_printf(stderr
, "Usage: .binary on|off\n");
5742 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
5744 #if defined(_WIN32) || defined(WIN32)
5745 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
5746 rc
= !SetCurrentDirectoryW(z
);
5749 rc
= chdir(azArg
[1]);
5752 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
5756 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
5761 /* The undocumented ".breakpoint" command causes a call to the no-op
5762 ** routine named test_breakpoint().
5764 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
5768 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
5770 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
5772 raw_printf(stderr
, "Usage: .changes on|off\n");
5777 /* Cancel output redirection, if it is currently set (by .testcase)
5778 ** Then read the content of the testcase-out.txt file and compare against
5779 ** azArg[1]. If there are differences, report an error and exit.
5781 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
5785 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
5787 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
5788 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
5790 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
5792 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5793 p
->zTestcase
, azArg
[1], zRes
);
5796 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
5802 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
5804 tryToClone(p
, azArg
[1]);
5806 raw_printf(stderr
, "Usage: .clone FILENAME\n");
5811 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
5815 memcpy(&data
, p
, sizeof(data
));
5816 data
.showHeader
= 0;
5817 data
.cMode
= data
.mode
= MODE_List
;
5818 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
5820 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
5821 callback
, &data
, &zErrMsg
);
5823 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5824 sqlite3_free(zErrMsg
);
5829 if( c
=='d' && n
>=3 && strncmp(azArg
[0], "dbconfig", n
)==0 ){
5830 static const struct DbConfigChoices
{const char *zName
; int op
;} aDbConfig
[] = {
5831 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
5832 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
5833 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
5834 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
5835 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
5836 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
5837 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
5838 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
5842 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
5843 if( nArg
>1 && strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
5845 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
5847 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
5848 utf8_printf(p
->out
, "%18s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
5851 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
5852 utf8_printf(stderr
, "Error: unknown dbconfig \"%s\"\n", azArg
[1]);
5853 utf8_printf(stderr
, "Enter \".dbconfig\" with no arguments for a list\n");
5857 if( c
=='d' && n
>=3 && strncmp(azArg
[0], "dbinfo", n
)==0 ){
5858 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
5861 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
5862 const char *zLike
= 0;
5864 int savedShowHeader
= p
->showHeader
;
5865 int savedShellFlags
= p
->shellFlgs
;
5866 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
);
5867 for(i
=1; i
<nArg
; i
++){
5868 if( azArg
[i
][0]=='-' ){
5869 const char *z
= azArg
[i
]+1;
5870 if( z
[0]=='-' ) z
++;
5871 if( strcmp(z
,"preserve-rowids")==0 ){
5872 #ifdef SQLITE_OMIT_VIRTUALTABLE
5873 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
5874 " with SQLITE_OMIT_VIRTUALTABLE\n");
5876 goto meta_command_exit
;
5878 ShellSetFlag(p
, SHFLG_PreserveRowid
);
5881 if( strcmp(z
,"newlines")==0 ){
5882 ShellSetFlag(p
, SHFLG_Newlines
);
5885 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
5887 goto meta_command_exit
;
5890 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
5891 "?--newlines? ?LIKE-PATTERN?\n");
5893 goto meta_command_exit
;
5899 /* When playing back a "dump", the content might appear in an order
5900 ** which causes immediate foreign key constraints to be violated.
5901 ** So disable foreign-key constraint enforcement to prevent problems. */
5902 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
5903 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
5904 p
->writableSchema
= 0;
5906 /* Set writable_schema=ON since doing so forces SQLite to initialize
5907 ** as much of the schema as it can even if the sqlite_master table is
5909 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5912 run_schema_dump_query(p
,
5913 "SELECT name, type, sql FROM sqlite_master "
5914 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5916 run_schema_dump_query(p
,
5917 "SELECT name, type, sql FROM sqlite_master "
5918 "WHERE name=='sqlite_sequence'"
5920 run_table_dump_query(p
,
5921 "SELECT sql FROM sqlite_master "
5922 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5926 zSql
= sqlite3_mprintf(
5927 "SELECT name, type, sql FROM sqlite_master "
5928 "WHERE tbl_name LIKE %Q AND type=='table'"
5929 " AND sql NOT NULL", zLike
);
5930 run_schema_dump_query(p
,zSql
);
5932 zSql
= sqlite3_mprintf(
5933 "SELECT sql FROM sqlite_master "
5934 "WHERE sql NOT NULL"
5935 " AND type IN ('index','trigger','view')"
5936 " AND tbl_name LIKE %Q", zLike
);
5937 run_table_dump_query(p
, zSql
, 0);
5940 if( p
->writableSchema
){
5941 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
5942 p
->writableSchema
= 0;
5944 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5945 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
5946 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5947 p
->showHeader
= savedShowHeader
;
5948 p
->shellFlgs
= savedShellFlags
;
5951 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
5953 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
5955 raw_printf(stderr
, "Usage: .echo on|off\n");
5960 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
5963 if( strcmp(azArg
[1],"full")==0 ){
5964 p
->autoEQP
= AUTOEQP_full
;
5965 }else if( strcmp(azArg
[1],"trigger")==0 ){
5966 p
->autoEQP
= AUTOEQP_trigger
;
5967 }else if( strcmp(azArg
[1],"test")==0 ){
5968 p
->autoEQP
= AUTOEQP_on
;
5971 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
5974 raw_printf(stderr
, "Usage: .eqp off|on|trigger|full\n");
5979 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
5980 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
5984 /* The ".explain" command is automatic now. It is largely pointless. It
5985 ** retained purely for backwards compatibility */
5986 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
5989 if( strcmp(azArg
[1],"auto")==0 ){
5992 val
= booleanValue(azArg
[1]);
5995 if( val
==1 && p
->mode
!=MODE_Explain
){
5996 p
->normalMode
= p
->mode
;
5997 p
->mode
= MODE_Explain
;
6000 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
6002 }else if( val
==99 ){
6003 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
6008 #ifndef SQLITE_OMIT_VIRTUALTABLE
6009 if( c
=='e' && strncmp(azArg
[0], "expert", n
)==0 ){
6011 expertDotCommand(p
, azArg
, nArg
);
6015 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
6019 memcpy(&data
, p
, sizeof(data
));
6020 data
.showHeader
= 0;
6021 data
.cMode
= data
.mode
= MODE_Semi
;
6022 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
6023 data
.cMode
= data
.mode
= MODE_Pretty
;
6027 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
6029 goto meta_command_exit
;
6032 rc
= sqlite3_exec(p
->db
,
6034 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6035 " FROM sqlite_master UNION ALL"
6036 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6037 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6039 callback
, &data
, &zErrMsg
6041 if( rc
==SQLITE_OK
){
6042 sqlite3_stmt
*pStmt
;
6043 rc
= sqlite3_prepare_v2(p
->db
,
6044 "SELECT rowid FROM sqlite_master"
6045 " WHERE name GLOB 'sqlite_stat[134]'",
6047 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
6048 sqlite3_finalize(pStmt
);
6051 raw_printf(p
->out
, "/* No STAT tables available */\n");
6053 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
6054 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
6055 callback
, &data
, &zErrMsg
);
6056 data
.cMode
= data
.mode
= MODE_Insert
;
6057 data
.zDestTable
= "sqlite_stat1";
6058 shell_exec(&data
, "SELECT * FROM sqlite_stat1", &zErrMsg
);
6059 data
.zDestTable
= "sqlite_stat3";
6060 shell_exec(&data
, "SELECT * FROM sqlite_stat3", &zErrMsg
);
6061 data
.zDestTable
= "sqlite_stat4";
6062 shell_exec(&data
, "SELECT * FROM sqlite_stat4", &zErrMsg
);
6063 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
6067 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
6069 p
->showHeader
= booleanValue(azArg
[1]);
6071 raw_printf(stderr
, "Usage: .headers on|off\n");
6076 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
6077 utf8_printf(p
->out
, "%s", zHelp
);
6080 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
6081 char *zTable
; /* Insert data into this table */
6082 char *zFile
; /* Name of file to extra content from */
6083 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
6084 int nCol
; /* Number of columns in the table */
6085 int nByte
; /* Number of bytes in an SQL string */
6086 int i
, j
; /* Loop counters */
6087 int needCommit
; /* True to COMMIT or ROLLBACK at end */
6088 int nSep
; /* Number of bytes in p->colSeparator[] */
6089 char *zSql
; /* An SQL statement */
6090 ImportCtx sCtx
; /* Reader context */
6091 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
6092 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
6095 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
6096 goto meta_command_exit
;
6101 memset(&sCtx
, 0, sizeof(sCtx
));
6103 nSep
= strlen30(p
->colSeparator
);
6106 "Error: non-null column separator required for import\n");
6110 raw_printf(stderr
, "Error: multi-character column separators not allowed"
6114 nSep
= strlen30(p
->rowSeparator
);
6116 raw_printf(stderr
, "Error: non-null row separator required for import\n");
6119 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
6120 /* When importing CSV (only), if the row separator is set to the
6121 ** default output row separator, change it to the default input
6122 ** row separator. This avoids having to maintain different input
6123 ** and output row separators. */
6124 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6125 nSep
= strlen30(p
->rowSeparator
);
6128 raw_printf(stderr
, "Error: multi-character row separators not allowed"
6134 if( sCtx
.zFile
[0]=='|' ){
6135 #ifdef SQLITE_OMIT_POPEN
6136 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6139 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
6140 sCtx
.zFile
= "<pipe>";
6144 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
6147 if( p
->mode
==MODE_Ascii
){
6148 xRead
= ascii_read_one_field
;
6150 xRead
= csv_read_one_field
;
6153 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
6156 sCtx
.cColSep
= p
->colSeparator
[0];
6157 sCtx
.cRowSep
= p
->rowSeparator
[0];
6158 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
6161 shell_out_of_memory();
6163 nByte
= strlen30(zSql
);
6164 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6165 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
6166 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
6167 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
6169 while( xRead(&sCtx
) ){
6170 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
6172 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
6175 sqlite3_free(zCreate
);
6176 sqlite3_free(sCtx
.z
);
6178 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
6181 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
6182 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
6183 sqlite3_free(zCreate
);
6185 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
6186 sqlite3_errmsg(p
->db
));
6187 sqlite3_free(sCtx
.z
);
6191 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6195 if (pStmt
) sqlite3_finalize(pStmt
);
6196 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
6200 nCol
= sqlite3_column_count(pStmt
);
6201 sqlite3_finalize(pStmt
);
6203 if( nCol
==0 ) return 0; /* no columns, no error */
6204 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
6207 shell_out_of_memory();
6209 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
6211 for(i
=1; i
<nCol
; i
++){
6217 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6220 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6221 if (pStmt
) sqlite3_finalize(pStmt
);
6225 needCommit
= sqlite3_get_autocommit(p
->db
);
6226 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
6228 int startLine
= sCtx
.nLine
;
6229 for(i
=0; i
<nCol
; i
++){
6230 char *z
= xRead(&sCtx
);
6232 ** Did we reach end-of-file before finding any columns?
6233 ** If so, stop instead of NULL filling the remaining columns.
6235 if( z
==0 && i
==0 ) break;
6237 ** Did we reach end-of-file OR end-of-line before finding any
6238 ** columns in ASCII mode? If so, stop instead of NULL filling
6239 ** the remaining columns.
6241 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
6242 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
6243 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
6244 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6245 "filling the rest with NULL\n",
6246 sCtx
.zFile
, startLine
, nCol
, i
+1);
6248 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
6251 if( sCtx
.cTerm
==sCtx
.cColSep
){
6255 }while( sCtx
.cTerm
==sCtx
.cColSep
);
6256 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6258 sCtx
.zFile
, startLine
, nCol
, i
);
6261 sqlite3_step(pStmt
);
6262 rc
= sqlite3_reset(pStmt
);
6263 if( rc
!=SQLITE_OK
){
6264 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
6265 startLine
, sqlite3_errmsg(p
->db
));
6268 }while( sCtx
.cTerm
!=EOF
);
6271 sqlite3_free(sCtx
.z
);
6272 sqlite3_finalize(pStmt
);
6273 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
6276 #ifndef SQLITE_UNTESTABLE
6277 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
6280 sqlite3_stmt
*pStmt
;
6283 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
6284 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n"
6285 " .imposter off\n");
6287 goto meta_command_exit
;
6291 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
6292 goto meta_command_exit
;
6294 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6295 " WHERE name='%q' AND type='index'", azArg
[1]);
6296 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6298 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
6299 tnum
= sqlite3_column_int(pStmt
, 0);
6301 sqlite3_finalize(pStmt
);
6303 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
6305 goto meta_command_exit
;
6307 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
6308 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6311 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6313 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
6316 if( sqlite3_column_int(pStmt
,1)==-1 ){
6319 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
6324 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
6326 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
6329 sqlite3_finalize(pStmt
);
6330 zSql
= sqlite3_mprintf(
6331 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6332 azArg
[2], zCollist
, zCollist
);
6333 sqlite3_free(zCollist
);
6334 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
6335 if( rc
==SQLITE_OK
){
6336 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
6337 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
6339 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
6341 utf8_printf(stdout
, "%s;\n", zSql
);
6343 "WARNING: writing to an imposter table will corrupt the index!\n"
6347 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
6352 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6354 #ifdef SQLITE_ENABLE_IOTRACE
6355 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
6356 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
6357 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
6361 }else if( strcmp(azArg
[1], "-")==0 ){
6362 sqlite3IoTrace
= iotracePrintf
;
6365 iotrace
= fopen(azArg
[1], "w");
6367 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
6371 sqlite3IoTrace
= iotracePrintf
;
6377 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
6378 static const struct {
6379 const char *zLimitName
; /* Name of a limit */
6380 int limitCode
; /* Integer code for that limit */
6382 { "length", SQLITE_LIMIT_LENGTH
},
6383 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
6384 { "column", SQLITE_LIMIT_COLUMN
},
6385 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
6386 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
6387 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
6388 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
6389 { "attached", SQLITE_LIMIT_ATTACHED
},
6390 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
6391 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
6392 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
6393 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
6398 for(i
=0; i
<ArraySize(aLimit
); i
++){
6399 printf("%20s %d\n", aLimit
[i
].zLimitName
,
6400 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
6403 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
6405 goto meta_command_exit
;
6408 n2
= strlen30(azArg
[1]);
6409 for(i
=0; i
<ArraySize(aLimit
); i
++){
6410 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
6414 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
6416 goto meta_command_exit
;
6421 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
6422 "enter \".limits\" with no arguments for a list.\n",
6425 goto meta_command_exit
;
6428 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
6429 (int)integerValue(azArg
[2]));
6431 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
6432 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
6436 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
6438 lintDotCommand(p
, azArg
, nArg
);
6441 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6442 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
6443 const char *zFile
, *zProc
;
6446 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
6448 goto meta_command_exit
;
6451 zProc
= nArg
>=3 ? azArg
[2] : 0;
6453 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
6454 if( rc
!=SQLITE_OK
){
6455 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
6456 sqlite3_free(zErrMsg
);
6462 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
6464 raw_printf(stderr
, "Usage: .log FILENAME\n");
6467 const char *zFile
= azArg
[1];
6468 output_file_close(p
->pLog
);
6469 p
->pLog
= output_file_open(zFile
, 0);
6473 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
6474 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
6475 int n2
= strlen30(zMode
);
6477 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
6478 p
->mode
= MODE_Line
;
6479 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6480 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
6481 p
->mode
= MODE_Column
;
6482 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6483 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
6484 p
->mode
= MODE_List
;
6485 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
6486 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6487 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
6488 p
->mode
= MODE_Html
;
6489 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
6491 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
6492 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6493 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
6495 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6496 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6497 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
6498 p
->mode
= MODE_List
;
6499 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
6500 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
6501 p
->mode
= MODE_Insert
;
6502 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
6503 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
6504 p
->mode
= MODE_Quote
;
6505 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
6506 p
->mode
= MODE_Ascii
;
6507 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
6508 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
6509 }else if( nArg
==1 ){
6510 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
6512 raw_printf(stderr
, "Error: mode should be one of: "
6513 "ascii column csv html insert line list quote tabs tcl\n");
6519 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
6521 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
6522 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
6524 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
6529 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
6530 char *zNewFilename
; /* Name of the database file to open */
6531 int iName
= 1; /* Index in azArg[] of the filename */
6532 int newFlag
= 0; /* True to delete file before opening */
6533 /* Close the existing database */
6534 session_close_all(p
);
6538 sqlite3_free(p
->zFreeOnClose
);
6539 p
->zFreeOnClose
= 0;
6540 p
->openMode
= SHELL_OPEN_UNSPEC
;
6541 /* Check for command-line arguments */
6542 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
6543 const char *z
= azArg
[iName
];
6544 if( optionMatch(z
,"new") ){
6546 #ifdef SQLITE_HAVE_ZLIB
6547 }else if( optionMatch(z
, "zip") ){
6548 p
->openMode
= SHELL_OPEN_ZIPFILE
;
6550 }else if( optionMatch(z
, "append") ){
6551 p
->openMode
= SHELL_OPEN_APPENDVFS
;
6552 }else if( optionMatch(z
, "readonly") ){
6553 p
->openMode
= SHELL_OPEN_READONLY
;
6554 }else if( z
[0]=='-' ){
6555 utf8_printf(stderr
, "unknown option: %s\n", z
);
6557 goto meta_command_exit
;
6560 /* If a filename is specified, try to open it first */
6561 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
6563 if( newFlag
) shellDeleteFile(zNewFilename
);
6564 p
->zDbFilename
= zNewFilename
;
6565 open_db(p
, OPEN_DB_KEEPALIVE
);
6567 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
6568 sqlite3_free(zNewFilename
);
6570 p
->zFreeOnClose
= zNewFilename
;
6574 /* As a fall-back open a TEMP database */
6581 && (strncmp(azArg
[0], "output", n
)==0||strncmp(azArg
[0], "once", n
)==0))
6582 || (c
=='e' && n
==5 && strcmp(azArg
[0],"excel")==0)
6584 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
6586 if( azArg
[0][0]=='e' ){
6587 /* Transform the ".excel" command into ".once -x" */
6590 zFile
= azArg
[1] = "-x";
6594 utf8_printf(stderr
, "Usage: .%s [-e|-x|FILE]\n", azArg
[0]);
6596 goto meta_command_exit
;
6598 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
6600 raw_printf(stderr
, "Usage: .once (-e|-x|FILE)\n");
6602 goto meta_command_exit
;
6609 if( zFile
[0]=='-' && zFile
[1]=='-' ) zFile
++;
6610 #ifndef SQLITE_NOHAVE_SYSTEM
6611 if( strcmp(zFile
, "-e")==0 || strcmp(zFile
, "-x")==0 ){
6614 if( zFile
[1]=='x' ){
6615 newTempFile(p
, "csv");
6617 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6618 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6620 newTempFile(p
, "txt");
6623 zFile
= p
->zTempFile
;
6625 #endif /* SQLITE_NOHAVE_SYSTEM */
6626 if( zFile
[0]=='|' ){
6627 #ifdef SQLITE_OMIT_POPEN
6628 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6632 p
->out
= popen(zFile
+ 1, "w");
6634 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
6638 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6642 p
->out
= output_file_open(zFile
, bTxtMode
);
6644 if( strcmp(zFile
,"off")!=0 ){
6645 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
6650 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6655 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
6657 for(i
=1; i
<nArg
; i
++){
6658 if( i
>1 ) raw_printf(p
->out
, " ");
6659 utf8_printf(p
->out
, "%s", azArg
[i
]);
6661 raw_printf(p
->out
, "\n");
6664 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
6666 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
6669 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
6673 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
6677 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
6680 raw_printf(stderr
, "Usage: .read FILE\n");
6682 goto meta_command_exit
;
6684 alt
= fopen(azArg
[1], "rb");
6686 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
6689 rc
= process_input(p
, alt
);
6694 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
6695 const char *zSrcFile
;
6698 sqlite3_backup
*pBackup
;
6702 zSrcFile
= azArg
[1];
6704 }else if( nArg
==3 ){
6705 zSrcFile
= azArg
[2];
6708 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
6710 goto meta_command_exit
;
6712 rc
= sqlite3_open(zSrcFile
, &pSrc
);
6713 if( rc
!=SQLITE_OK
){
6714 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
6719 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
6721 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6725 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
6726 || rc
==SQLITE_BUSY
){
6727 if( rc
==SQLITE_BUSY
){
6728 if( nTimeout
++ >= 3 ) break;
6732 sqlite3_backup_finish(pBackup
);
6733 if( rc
==SQLITE_DONE
){
6735 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
6736 raw_printf(stderr
, "Error: source database is busy\n");
6739 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6745 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
6747 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
6748 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6749 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
6752 raw_printf(stderr
, "Usage: .scanstats on|off\n");
6757 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
6761 const char *zDiv
= "(";
6762 const char *zName
= 0;
6768 memcpy(&data
, p
, sizeof(data
));
6769 data
.showHeader
= 0;
6770 data
.cMode
= data
.mode
= MODE_Semi
;
6772 for(ii
=1; ii
<nArg
; ii
++){
6773 if( optionMatch(azArg
[ii
],"indent") ){
6774 data
.cMode
= data
.mode
= MODE_Pretty
;
6775 }else if( optionMatch(azArg
[ii
],"debug") ){
6777 }else if( zName
==0 ){
6780 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6782 goto meta_command_exit
;
6786 int isMaster
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0;
6787 if( isMaster
|| sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0 ){
6788 char *new_argv
[2], *new_colv
[2];
6789 new_argv
[0] = sqlite3_mprintf(
6790 "CREATE TABLE %s (\n"
6794 " rootpage integer,\n"
6796 ")", isMaster
? "sqlite_master" : "sqlite_temp_master");
6798 new_colv
[0] = "sql";
6800 callback(&data
, 1, new_argv
, new_colv
);
6801 sqlite3_free(new_argv
[0]);
6805 sqlite3_stmt
*pStmt
= 0;
6806 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
6809 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6810 sqlite3_finalize(pStmt
);
6812 goto meta_command_exit
;
6814 appendText(&sSelect
, "SELECT sql FROM", 0);
6816 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6817 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
6819 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
6820 appendText(&sSelect
, zDiv
, 0);
6821 zDiv
= " UNION ALL ";
6822 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
6823 if( sqlite3_stricmp(zDb
, "main")!=0 ){
6824 appendText(&sSelect
, zDb
, '"');
6826 appendText(&sSelect
, "NULL", 0);
6828 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6829 appendText(&sSelect
, zScNum
, 0);
6830 appendText(&sSelect
, " AS snum, ", 0);
6831 appendText(&sSelect
, zDb
, '\'');
6832 appendText(&sSelect
, " AS sname FROM ", 0);
6833 appendText(&sSelect
, zDb
, '"');
6834 appendText(&sSelect
, ".sqlite_master", 0);
6836 sqlite3_finalize(pStmt
);
6837 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6839 appendText(&sSelect
,
6840 " UNION ALL SELECT shell_module_schema(name),"
6841 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6844 appendText(&sSelect
, ") WHERE ", 0);
6846 char *zQarg
= sqlite3_mprintf("%Q", zName
);
6847 int bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
6848 strchr(zName
, '[') != 0;
6849 if( strchr(zName
, '.') ){
6850 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
6852 appendText(&sSelect
, "lower(tbl_name)", 0);
6854 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
6855 appendText(&sSelect
, zQarg
, 0);
6857 appendText(&sSelect
, " ESCAPE '\\' ", 0);
6859 appendText(&sSelect
, " AND ", 0);
6860 sqlite3_free(zQarg
);
6862 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
6863 " ORDER BY snum, rowid", 0);
6865 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
6867 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
6872 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
6873 sqlite3_free(zErrMsg
);
6875 }else if( rc
!= SQLITE_OK
){
6876 raw_printf(stderr
,"Error: querying schema information\n");
6883 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6884 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
6885 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
6889 #if defined(SQLITE_ENABLE_SESSION)
6890 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
6891 OpenSession
*pSession
= &p
->aSession
[0];
6892 char **azCmd
= &azArg
[1];
6894 int nCmd
= nArg
- 1;
6896 if( nArg
<=1 ) goto session_syntax_error
;
6899 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
6900 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
6902 if( iSes
<p
->nSession
){
6903 pSession
= &p
->aSession
[iSes
];
6907 pSession
= &p
->aSession
[0];
6912 /* .session attach TABLE
6913 ** Invoke the sqlite3session_attach() interface to attach a particular
6914 ** table so that it is never filtered.
6916 if( strcmp(azCmd
[0],"attach")==0 ){
6917 if( nCmd
!=2 ) goto session_syntax_error
;
6918 if( pSession
->p
==0 ){
6920 raw_printf(stderr
, "ERROR: No sessions are open\n");
6922 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
6924 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
6930 /* .session changeset FILE
6931 ** .session patchset FILE
6932 ** Write a changeset or patchset into a file. The file is overwritten.
6934 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
6936 if( nCmd
!=2 ) goto session_syntax_error
;
6937 if( pSession
->p
==0 ) goto session_not_open
;
6938 out
= fopen(azCmd
[1], "wb");
6940 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
6944 if( azCmd
[0][0]=='c' ){
6945 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
6947 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
6950 printf("Error: error code %d\n", rc
);
6954 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
6955 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
6958 sqlite3_free(pChng
);
6964 ** Close the identified session
6966 if( strcmp(azCmd
[0], "close")==0 ){
6967 if( nCmd
!=1 ) goto session_syntax_error
;
6969 session_close(pSession
);
6970 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
6974 /* .session enable ?BOOLEAN?
6975 ** Query or set the enable flag
6977 if( strcmp(azCmd
[0], "enable")==0 ){
6979 if( nCmd
>2 ) goto session_syntax_error
;
6980 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
6982 ii
= sqlite3session_enable(pSession
->p
, ii
);
6983 utf8_printf(p
->out
, "session %s enable flag = %d\n",
6984 pSession
->zName
, ii
);
6988 /* .session filter GLOB ....
6989 ** Set a list of GLOB patterns of table names to be excluded.
6991 if( strcmp(azCmd
[0], "filter")==0 ){
6993 if( nCmd
<2 ) goto session_syntax_error
;
6995 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
6996 sqlite3_free(pSession
->azFilter
[ii
]);
6998 sqlite3_free(pSession
->azFilter
);
6999 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
7000 pSession
->azFilter
= sqlite3_malloc( nByte
);
7001 if( pSession
->azFilter
==0 ){
7002 raw_printf(stderr
, "Error: out or memory\n");
7005 for(ii
=1; ii
<nCmd
; ii
++){
7006 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
7008 pSession
->nFilter
= ii
-1;
7012 /* .session indirect ?BOOLEAN?
7013 ** Query or set the indirect flag
7015 if( strcmp(azCmd
[0], "indirect")==0 ){
7017 if( nCmd
>2 ) goto session_syntax_error
;
7018 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
7020 ii
= sqlite3session_indirect(pSession
->p
, ii
);
7021 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
7022 pSession
->zName
, ii
);
7027 ** Determine if the session is empty
7029 if( strcmp(azCmd
[0], "isempty")==0 ){
7031 if( nCmd
!=1 ) goto session_syntax_error
;
7033 ii
= sqlite3session_isempty(pSession
->p
);
7034 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
7035 pSession
->zName
, ii
);
7040 ** List all currently open sessions
7042 if( strcmp(azCmd
[0],"list")==0 ){
7043 for(i
=0; i
<p
->nSession
; i
++){
7044 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
7048 /* .session open DB NAME
7049 ** Open a new session called NAME on the attached database DB.
7050 ** DB is normally "main".
7052 if( strcmp(azCmd
[0],"open")==0 ){
7054 if( nCmd
!=3 ) goto session_syntax_error
;
7056 if( zName
[0]==0 ) goto session_syntax_error
;
7057 for(i
=0; i
<p
->nSession
; i
++){
7058 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
7059 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
7060 goto meta_command_exit
;
7063 if( p
->nSession
>=ArraySize(p
->aSession
) ){
7064 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
7065 goto meta_command_exit
;
7067 pSession
= &p
->aSession
[p
->nSession
];
7068 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
7070 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
7072 goto meta_command_exit
;
7074 pSession
->nFilter
= 0;
7075 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
7077 pSession
->zName
= sqlite3_mprintf("%s", zName
);
7079 /* If no command name matches, show a syntax error */
7080 session_syntax_error
:
7086 /* Undocumented commands for internal testing. Subject to change
7087 ** without notice. */
7088 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
7089 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
7091 for(i
=1; i
<nArg
; i
++){
7092 v
= booleanValue(azArg
[i
]);
7093 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
7096 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
7097 int i
; sqlite3_int64 v
;
7098 for(i
=1; i
<nArg
; i
++){
7100 v
= integerValue(azArg
[i
]);
7101 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
7102 utf8_printf(p
->out
, "%s", zBuf
);
7108 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
7109 int bIsInit
= 0; /* True to initialize the SELFTEST table */
7110 int bVerbose
= 0; /* Verbose output */
7111 int bSelftestExists
; /* True if SELFTEST already exists */
7112 int i
, k
; /* Loop counters */
7113 int nTest
= 0; /* Number of tests runs */
7114 int nErr
= 0; /* Number of errors seen */
7115 ShellText str
; /* Answer for a query */
7116 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
7119 for(i
=1; i
<nArg
; i
++){
7120 const char *z
= azArg
[i
];
7121 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7122 if( strcmp(z
,"-init")==0 ){
7125 if( strcmp(z
,"-v")==0 ){
7129 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7130 azArg
[i
], azArg
[0]);
7131 raw_printf(stderr
, "Should be one of: --init -v\n");
7133 goto meta_command_exit
;
7136 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
7138 bSelftestExists
= 0;
7140 bSelftestExists
= 1;
7143 createSelftestTable(p
);
7144 bSelftestExists
= 1;
7147 appendText(&str
, "x", 0);
7148 for(k
=bSelftestExists
; k
>=0; k
--){
7150 rc
= sqlite3_prepare_v2(p
->db
,
7151 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7154 rc
= sqlite3_prepare_v2(p
->db
,
7155 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7156 " (1,'run','PRAGMA integrity_check','ok')",
7160 raw_printf(stderr
, "Error querying the selftest table\n");
7162 sqlite3_finalize(pStmt
);
7163 goto meta_command_exit
;
7165 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
7166 int tno
= sqlite3_column_int(pStmt
, 0);
7167 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
7168 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
7169 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
7173 char *zQuote
= sqlite3_mprintf("%q", zSql
);
7174 printf("%d: %s %s\n", tno
, zOp
, zSql
);
7175 sqlite3_free(zQuote
);
7177 if( strcmp(zOp
,"memo")==0 ){
7178 utf8_printf(p
->out
, "%s\n", zSql
);
7180 if( strcmp(zOp
,"run")==0 ){
7184 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
7187 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
7189 if( rc
|| zErrMsg
){
7192 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
7193 sqlite3_free(zErrMsg
);
7194 }else if( strcmp(zAns
,str
.z
)!=0 ){
7197 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
7198 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
7203 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
7207 } /* End loop over rows of content from SELFTEST */
7208 sqlite3_finalize(pStmt
);
7209 } /* End loop over k */
7211 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
7214 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
7215 if( nArg
<2 || nArg
>3 ){
7216 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
7220 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
7221 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
7224 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
7225 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
7229 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
7230 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
7231 int i
; /* Loop counter */
7232 int bSchema
= 0; /* Also hash the schema */
7233 int bSeparate
= 0; /* Hash each table separately */
7234 int iSize
= 224; /* Hash algorithm to use */
7235 int bDebug
= 0; /* Only show the query that would have run */
7236 sqlite3_stmt
*pStmt
; /* For querying tables names */
7237 char *zSql
; /* SQL to be run */
7238 char *zSep
; /* Separator */
7239 ShellText sSql
; /* Complete SQL for the query to run the hash */
7240 ShellText sQuery
; /* Set of queries used to read all content */
7242 for(i
=1; i
<nArg
; i
++){
7243 const char *z
= azArg
[i
];
7246 if( z
[0]=='-' ) z
++;
7247 if( strcmp(z
,"schema")==0 ){
7250 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
7251 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
7253 iSize
= atoi(&z
[5]);
7255 if( strcmp(z
,"debug")==0 ){
7259 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7260 azArg
[i
], azArg
[0]);
7261 raw_printf(stderr
, "Should be one of: --schema"
7262 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
7264 goto meta_command_exit
;
7267 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7269 goto meta_command_exit
;
7273 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
7277 zSql
= "SELECT lower(name) FROM sqlite_master"
7278 " WHERE type='table' AND coalesce(rootpage,0)>1"
7279 " UNION ALL SELECT 'sqlite_master'"
7280 " ORDER BY 1 collate nocase";
7282 zSql
= "SELECT lower(name) FROM sqlite_master"
7283 " WHERE type='table' AND coalesce(rootpage,0)>1"
7284 " AND name NOT LIKE 'sqlite_%'"
7285 " ORDER BY 1 collate nocase";
7287 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
7290 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
7292 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
7293 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
7294 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
7295 if( strncmp(zTab
, "sqlite_",7)!=0 ){
7296 appendText(&sQuery
,"SELECT * FROM ", 0);
7297 appendText(&sQuery
,zTab
,'"');
7298 appendText(&sQuery
," NOT INDEXED;", 0);
7299 }else if( strcmp(zTab
, "sqlite_master")==0 ){
7300 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7301 " ORDER BY name;", 0);
7302 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
7303 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
7304 " ORDER BY name;", 0);
7305 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
7306 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
7307 " ORDER BY tbl,idx;", 0);
7308 }else if( strcmp(zTab
, "sqlite_stat3")==0
7309 || strcmp(zTab
, "sqlite_stat4")==0 ){
7310 appendText(&sQuery
, "SELECT * FROM ", 0);
7311 appendText(&sQuery
, zTab
, 0);
7312 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
7314 appendText(&sSql
, zSep
, 0);
7315 appendText(&sSql
, sQuery
.z
, '\'');
7317 appendText(&sSql
, ",", 0);
7318 appendText(&sSql
, zTab
, '\'');
7321 sqlite3_finalize(pStmt
);
7323 zSql
= sqlite3_mprintf(
7325 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7326 " FROM [sha3sum$query]",
7329 zSql
= sqlite3_mprintf(
7331 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7332 " FROM [sha3sum$query]",
7338 utf8_printf(p
->out
, "%s\n", zSql
);
7340 shell_exec(p
, zSql
, 0);
7345 #ifndef SQLITE_NOHAVE_SYSTEM
7347 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
7352 raw_printf(stderr
, "Usage: .system COMMAND\n");
7354 goto meta_command_exit
;
7356 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
7357 for(i
=2; i
<nArg
; i
++){
7358 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
7363 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
7365 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
7367 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
7368 static const char *azBool
[] = { "off", "on", "trigger", "full"};
7371 raw_printf(stderr
, "Usage: .show\n");
7373 goto meta_command_exit
;
7375 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
7376 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
7377 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
7378 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
7379 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
7380 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
7381 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
7382 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
7383 output_c_string(p
->out
, p
->nullValue
);
7384 raw_printf(p
->out
, "\n");
7385 utf8_printf(p
->out
,"%12.12s: %s\n","output",
7386 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
7387 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
7388 output_c_string(p
->out
, p
->colSeparator
);
7389 raw_printf(p
->out
, "\n");
7390 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
7391 output_c_string(p
->out
, p
->rowSeparator
);
7392 raw_printf(p
->out
, "\n");
7393 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
7394 utf8_printf(p
->out
, "%12.12s: ", "width");
7395 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
7396 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
7398 raw_printf(p
->out
, "\n");
7399 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
7400 p
->zDbFilename
? p
->zDbFilename
: "");
7403 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
7405 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
7406 }else if( nArg
==1 ){
7407 display_stats(p
->db
, p
, 0);
7409 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
7414 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
7415 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
7416 || strncmp(azArg
[0], "indexes", n
)==0) )
7418 sqlite3_stmt
*pStmt
;
7425 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
7427 sqlite3_finalize(pStmt
);
7428 return shellDatabaseError(p
->db
);
7431 if( nArg
>2 && c
=='i' ){
7432 /* It is an historical accident that the .indexes command shows an error
7433 ** when called with the wrong number of arguments whereas the .tables
7434 ** command does not. */
7435 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
7437 sqlite3_finalize(pStmt
);
7438 goto meta_command_exit
;
7440 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
7441 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
7442 if( zDbName
==0 ) continue;
7443 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
7444 if( sqlite3_stricmp(zDbName
, "main")==0 ){
7445 appendText(&s
, "SELECT name FROM ", 0);
7447 appendText(&s
, "SELECT ", 0);
7448 appendText(&s
, zDbName
, '\'');
7449 appendText(&s
, "||'.'||name FROM ", 0);
7451 appendText(&s
, zDbName
, '"');
7452 appendText(&s
, ".sqlite_master ", 0);
7454 appendText(&s
," WHERE type IN ('table','view')"
7455 " AND name NOT LIKE 'sqlite_%'"
7456 " AND name LIKE ?1", 0);
7458 appendText(&s
," WHERE type='index'"
7459 " AND tbl_name LIKE ?1", 0);
7462 rc
= sqlite3_finalize(pStmt
);
7463 appendText(&s
, " ORDER BY 1", 0);
7464 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
7466 if( rc
) return shellDatabaseError(p
->db
);
7468 /* Run the SQL statement prepared by the above block. Store the results
7469 ** as an array of nul-terminated strings in azResult[]. */
7473 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
7475 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
7477 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
7480 int n2
= nAlloc
*2 + 10;
7481 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
7482 if( azNew
==0 ) shell_out_of_memory();
7486 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7487 if( 0==azResult
[nRow
] ) shell_out_of_memory();
7490 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
7491 rc
= shellDatabaseError(p
->db
);
7494 /* Pretty-print the contents of array azResult[] to the output */
7495 if( rc
==0 && nRow
>0 ){
7496 int len
, maxlen
= 0;
7498 int nPrintCol
, nPrintRow
;
7499 for(i
=0; i
<nRow
; i
++){
7500 len
= strlen30(azResult
[i
]);
7501 if( len
>maxlen
) maxlen
= len
;
7503 nPrintCol
= 80/(maxlen
+2);
7504 if( nPrintCol
<1 ) nPrintCol
= 1;
7505 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
7506 for(i
=0; i
<nPrintRow
; i
++){
7507 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
7508 char *zSp
= j
<nPrintRow
? "" : " ";
7509 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
7510 azResult
[j
] ? azResult
[j
]:"");
7512 raw_printf(p
->out
, "\n");
7516 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
7517 sqlite3_free(azResult
);
7520 /* Begin redirecting output to the file "testcase-out.txt" */
7521 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
7523 p
->out
= output_file_open("testcase-out.txt", 0);
7525 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
7528 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
7530 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
7534 #ifndef SQLITE_UNTESTABLE
7535 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
7536 static const struct {
7537 const char *zCtrlName
; /* Name of a test-control option */
7538 int ctrlCode
; /* Integer code for that option */
7539 const char *zUsage
; /* Usage notes */
7541 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
7542 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
7543 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7544 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7545 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
7546 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7547 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
7548 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
7549 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
7550 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
7552 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
, "" },
7554 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
7555 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
7556 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
7557 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
7558 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
7562 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7565 const char *zCmd
= 0;
7568 zCmd
= nArg
>=2 ? azArg
[1] : "help";
7570 /* The argument can optionally begin with "-" or "--" */
7571 if( zCmd
[0]=='-' && zCmd
[1] ){
7573 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
7576 /* --help lists all test-controls */
7577 if( strcmp(zCmd
,"help")==0 ){
7578 utf8_printf(p
->out
, "Available test-controls:\n");
7579 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7580 utf8_printf(p
->out
, " .testctrl %s %s\n",
7581 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
7584 goto meta_command_exit
;
7587 /* convert testctrl text option to value. allow any unique prefix
7588 ** of the option name, or a numerical value. */
7589 n2
= strlen30(zCmd
);
7590 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7591 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
7593 testctrl
= aCtrl
[i
].ctrlCode
;
7596 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
7597 "Use \".testctrl --help\" for help\n", zCmd
);
7599 goto meta_command_exit
;
7604 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
7605 "Use \".testctrl --help\" for help\n", zCmd
);
7609 /* sqlite3_test_control(int, db, int) */
7610 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
7611 case SQLITE_TESTCTRL_RESERVE
:
7613 int opt
= (int)strtol(azArg
[2], 0, 0);
7614 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
7619 /* sqlite3_test_control(int) */
7620 case SQLITE_TESTCTRL_PRNG_SAVE
:
7621 case SQLITE_TESTCTRL_PRNG_RESTORE
:
7622 case SQLITE_TESTCTRL_PRNG_RESET
:
7623 case SQLITE_TESTCTRL_BYTEORDER
:
7625 rc2
= sqlite3_test_control(testctrl
);
7626 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
7630 /* sqlite3_test_control(int, uint) */
7631 case SQLITE_TESTCTRL_PENDING_BYTE
:
7633 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
7634 rc2
= sqlite3_test_control(testctrl
, opt
);
7639 /* sqlite3_test_control(int, int) */
7640 case SQLITE_TESTCTRL_ASSERT
:
7641 case SQLITE_TESTCTRL_ALWAYS
:
7643 int opt
= booleanValue(azArg
[2]);
7644 rc2
= sqlite3_test_control(testctrl
, opt
);
7649 /* sqlite3_test_control(int, int) */
7650 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
7651 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
7653 int opt
= booleanValue(azArg
[2]);
7654 rc2
= sqlite3_test_control(testctrl
, opt
);
7659 case SQLITE_TESTCTRL_IMPOSTER
:
7661 rc2
= sqlite3_test_control(testctrl
, p
->db
,
7663 integerValue(azArg
[3]),
7664 integerValue(azArg
[4]));
7670 case SQLITE_TESTCTRL_PARSER_COVERAGE
:
7672 sqlite3_test_control(testctrl
, p
->out
);
7678 if( isOk
==0 && iCtrl
>=0 ){
7679 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
7681 }else if( isOk
==1 ){
7682 raw_printf(p
->out
, "%d\n", rc2
);
7683 }else if( isOk
==2 ){
7684 raw_printf(p
->out
, "0x%08x\n", rc2
);
7687 #endif /* !defined(SQLITE_UNTESTABLE) */
7689 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
7691 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
7694 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
7696 enableTimer
= booleanValue(azArg
[1]);
7697 if( enableTimer
&& !HAS_TIMER
){
7698 raw_printf(stderr
, "Error: timer not available on this system.\n");
7702 raw_printf(stderr
, "Usage: .timer on|off\n");
7707 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
7710 raw_printf(stderr
, "Usage: .trace FILE|off\n");
7712 goto meta_command_exit
;
7714 output_file_close(p
->traceOut
);
7715 p
->traceOut
= output_file_open(azArg
[1], 0);
7716 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7717 if( p
->traceOut
==0 ){
7718 sqlite3_trace_v2(p
->db
, 0, 0, 0);
7720 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
7725 #if SQLITE_USER_AUTHENTICATION
7726 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
7728 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
7730 goto meta_command_exit
;
7733 if( strcmp(azArg
[1],"login")==0 ){
7735 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
7737 goto meta_command_exit
;
7739 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]));
7741 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
7744 }else if( strcmp(azArg
[1],"add")==0 ){
7746 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
7748 goto meta_command_exit
;
7750 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7751 booleanValue(azArg
[4]));
7753 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
7756 }else if( strcmp(azArg
[1],"edit")==0 ){
7758 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
7760 goto meta_command_exit
;
7762 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7763 booleanValue(azArg
[4]));
7765 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
7768 }else if( strcmp(azArg
[1],"delete")==0 ){
7770 raw_printf(stderr
, "Usage: .user delete USER\n");
7772 goto meta_command_exit
;
7774 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
7776 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
7780 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
7782 goto meta_command_exit
;
7785 #endif /* SQLITE_USER_AUTHENTICATION */
7787 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
7788 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
7789 sqlite3_libversion(), sqlite3_sourceid());
7790 #if SQLITE_HAVE_ZLIB
7791 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
7793 #define CTIMEOPT_VAL_(opt) #opt
7794 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7795 #if defined(__clang__) && defined(__clang_major__)
7796 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
7797 CTIMEOPT_VAL(__clang_minor__
) "."
7798 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
7799 #elif defined(_MSC_VER)
7800 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
7801 #elif defined(__GNUC__) && defined(__VERSION__)
7802 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
7806 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
7807 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7808 sqlite3_vfs
*pVfs
= 0;
7810 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
7812 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
7813 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7814 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7815 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7820 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
7822 sqlite3_vfs
*pCurrent
= 0;
7824 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
7826 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
7827 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
7828 pVfs
==pCurrent
? " <--- CURRENT" : "");
7829 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7830 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7831 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7833 raw_printf(p
->out
, "-----------------------------------\n");
7838 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
7839 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7842 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
7844 utf8_printf(p
->out
, "%s\n", zVfsName
);
7845 sqlite3_free(zVfsName
);
7850 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7851 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
7852 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
7856 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
7858 assert( nArg
<=ArraySize(azArg
) );
7859 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
7860 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
7865 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
7866 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
7873 if( p
->outCount
==0 ) output_reset(p
);
7879 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7882 static int line_contains_semicolon(const char *z
, int N
){
7884 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
7889 ** Test to see if a line consists entirely of whitespace.
7891 static int _all_whitespace(const char *z
){
7893 if( IsSpace(z
[0]) ) continue;
7894 if( *z
=='/' && z
[1]=='*' ){
7896 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
7897 if( *z
==0 ) return 0;
7901 if( *z
=='-' && z
[1]=='-' ){
7903 while( *z
&& *z
!='\n' ){ z
++; }
7904 if( *z
==0 ) return 1;
7913 ** Return TRUE if the line typed in is an SQL command terminator other
7914 ** than a semi-colon. The SQL Server style "go" command is understood
7915 ** as is the Oracle "/".
7917 static int line_is_command_terminator(const char *zLine
){
7918 while( IsSpace(zLine
[0]) ){ zLine
++; };
7919 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
7920 return 1; /* Oracle */
7922 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
7923 && _all_whitespace(&zLine
[2]) ){
7924 return 1; /* SQL Server */
7930 ** We need a default sqlite3_complete() implementation to use in case
7931 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
7932 ** any arbitrary text is a complete SQL statement. This is not very
7933 ** user-friendly, but it does seem to work.
7935 #ifdef SQLITE_OMIT_COMPLETE
7936 int sqlite3_complete(const char *zSql
){ return 1; }
7940 ** Return true if zSql is a complete SQL statement. Return false if it
7941 ** ends in the middle of a string literal or C-style comment.
7943 static int line_is_complete(char *zSql
, int nSql
){
7945 if( zSql
==0 ) return 1;
7948 rc
= sqlite3_complete(zSql
);
7954 ** Run a single line of SQL. Return the number of errors.
7956 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
7961 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
7963 rc
= shell_exec(p
, zSql
, &zErrMsg
);
7965 if( rc
|| zErrMsg
){
7967 if( in
!=0 || !stdin_is_interactive
){
7968 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
7969 "Error: near line %d:", startline
);
7971 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
7974 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
7975 sqlite3_free(zErrMsg
);
7978 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
7981 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
7982 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
7983 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
7990 ** Read input from *in and process it. If *in==0 then input
7991 ** is interactive - the user is typing it it. Otherwise, input
7992 ** is coming from a file or device. A prompt is issued and history
7993 ** is saved only if input is interactive. An interrupt signal will
7994 ** cause this routine to exit immediately, unless input is interactive.
7996 ** Return the number of errors.
7998 static int process_input(ShellState
*p
, FILE *in
){
7999 char *zLine
= 0; /* A single input line */
8000 char *zSql
= 0; /* Accumulated SQL text */
8001 int nLine
; /* Length of current line */
8002 int nSql
= 0; /* Bytes of zSql[] used */
8003 int nAlloc
= 0; /* Allocated zSql[] space */
8004 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
8005 int rc
; /* Error code */
8006 int errCnt
= 0; /* Number of errors seen */
8007 int lineno
= 0; /* Current line number */
8008 int startline
= 0; /* Line number for start of current input */
8010 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
8012 zLine
= one_input_line(in
, zLine
, nSql
>0);
8015 if( in
==0 && stdin_is_interactive
) printf("\n");
8018 if( seenInterrupt
){
8023 if( nSql
==0 && _all_whitespace(zLine
) ){
8024 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
8027 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
8028 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
8029 if( zLine
[0]=='.' ){
8030 rc
= do_meta_command(zLine
, p
);
8031 if( rc
==2 ){ /* exit requested */
8039 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
8040 memcpy(zLine
,";",2);
8042 nLine
= strlen30(zLine
);
8043 if( nSql
+nLine
+2>=nAlloc
){
8044 nAlloc
= nSql
+nLine
+100;
8045 zSql
= realloc(zSql
, nAlloc
);
8046 if( zSql
==0 ) shell_out_of_memory();
8051 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
8052 assert( nAlloc
>0 && zSql
!=0 );
8053 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
8057 zSql
[nSql
++] = '\n';
8058 memcpy(zSql
+nSql
, zLine
, nLine
+1);
8061 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
8062 && sqlite3_complete(zSql
) ){
8063 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
8071 }else if( nSql
&& _all_whitespace(zSql
) ){
8072 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
8076 if( nSql
&& !_all_whitespace(zSql
) ){
8077 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
8085 ** Return a pathname which is the user's home directory. A
8086 ** 0 return indicates an error of some kind.
8088 static char *find_home_dir(int clearFlag
){
8089 static char *home_dir
= NULL
;
8095 if( home_dir
) return home_dir
;
8097 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8098 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8100 struct passwd
*pwent
;
8101 uid_t uid
= getuid();
8102 if( (pwent
=getpwuid(uid
)) != NULL
) {
8103 home_dir
= pwent
->pw_dir
;
8108 #if defined(_WIN32_WCE)
8109 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8114 #if defined(_WIN32) || defined(WIN32)
8116 home_dir
= getenv("USERPROFILE");
8121 home_dir
= getenv("HOME");
8124 #if defined(_WIN32) || defined(WIN32)
8126 char *zDrive
, *zPath
;
8128 zDrive
= getenv("HOMEDRIVE");
8129 zPath
= getenv("HOMEPATH");
8130 if( zDrive
&& zPath
){
8131 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
8132 home_dir
= malloc( n
);
8133 if( home_dir
==0 ) return 0;
8134 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
8141 #endif /* !_WIN32_WCE */
8144 int n
= strlen30(home_dir
) + 1;
8145 char *z
= malloc( n
);
8146 if( z
) memcpy(z
, home_dir
, n
);
8154 ** Read input from the file given by sqliterc_override. Or if that
8155 ** parameter is NULL, take input from ~/.sqliterc
8157 ** Returns the number of errors.
8159 static void process_sqliterc(
8160 ShellState
*p
, /* Configuration data */
8161 const char *sqliterc_override
/* Name of config file. NULL to use default */
8163 char *home_dir
= NULL
;
8164 const char *sqliterc
= sqliterc_override
;
8168 if (sqliterc
== NULL
) {
8169 home_dir
= find_home_dir(0);
8171 raw_printf(stderr
, "-- warning: cannot find home directory;"
8172 " cannot read ~/.sqliterc\n");
8175 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
8178 in
= fopen(sqliterc
,"rb");
8180 if( stdin_is_interactive
){
8181 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
8183 process_input(p
,in
);
8190 ** Show available command line options
8192 static const char zOptions
[] =
8193 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
8194 " -A ARGS... run \".archive ARGS\" and exit\n"
8196 " -append append the database to the end of the file\n"
8197 " -ascii set output mode to 'ascii'\n"
8198 " -bail stop after hitting an error\n"
8199 " -batch force batch I/O\n"
8200 " -column set output mode to 'column'\n"
8201 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8202 " -csv set output mode to 'csv'\n"
8203 " -echo print commands before execution\n"
8204 " -init FILENAME read/process named file\n"
8205 " -[no]header turn headers on or off\n"
8206 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8207 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8209 " -help show this message\n"
8210 " -html set output mode to HTML\n"
8211 " -interactive force interactive I/O\n"
8212 " -line set output mode to 'line'\n"
8213 " -list set output mode to 'list'\n"
8214 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8215 " -mmap N default mmap size set to N\n"
8216 #ifdef SQLITE_ENABLE_MULTIPLEX
8217 " -multiplex enable the multiplexor VFS\n"
8219 " -newline SEP set output row separator. Default: '\\n'\n"
8220 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8221 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8222 " -quote set output mode to 'quote'\n"
8223 " -readonly open the database read-only\n"
8224 " -separator SEP set output column separator. Default: '|'\n"
8225 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8226 " -sorterref SIZE sorter references threshold size\n"
8228 " -stats print memory stats before each finalize\n"
8229 " -version show SQLite version\n"
8230 " -vfs NAME use NAME as the default VFS\n"
8231 #ifdef SQLITE_ENABLE_VFSTRACE
8232 " -vfstrace enable tracing of all VFS calls\n"
8234 #ifdef SQLITE_HAVE_ZLIB
8235 " -zip open the file as a ZIP Archive\n"
8238 static void usage(int showDetail
){
8240 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8241 "FILENAME is the name of an SQLite database. A new database is created\n"
8242 "if the file does not previously exist.\n", Argv0
);
8244 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
8246 raw_printf(stderr
, "Use the -help option for additional information\n");
8252 ** Internal check: Verify that the SQLite is uninitialized. Print a
8253 ** error message if it is initialized.
8255 static void verify_uninitialized(void){
8256 if( sqlite3_config(-1)==SQLITE_MISUSE
){
8257 utf8_printf(stdout
, "WARNING: attempt to configure SQLite after"
8258 " initialization.\n");
8263 ** Initialize the state information in data
8265 static void main_init(ShellState
*data
) {
8266 memset(data
, 0, sizeof(*data
));
8267 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
8268 data
->autoExplain
= 1;
8269 memcpy(data
->colSeparator
,SEP_Column
, 2);
8270 memcpy(data
->rowSeparator
,SEP_Row
, 2);
8271 data
->showHeader
= 0;
8272 data
->shellFlgs
= SHFLG_Lookaside
;
8273 verify_uninitialized();
8274 sqlite3_config(SQLITE_CONFIG_URI
, 1);
8275 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
8276 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
8277 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
8278 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
8282 ** Output text to the console in a font that attracts extra attention.
8285 static void printBold(const char *zText
){
8286 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
8287 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
8288 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
8289 SetConsoleTextAttribute(out
,
8290 FOREGROUND_RED
|FOREGROUND_INTENSITY
8292 printf("%s", zText
);
8293 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
8296 static void printBold(const char *zText
){
8297 printf("\033[1m%s\033[0m", zText
);
8302 ** Get the argument to an --option. Throw an error and die if no argument
8305 static char *cmdline_option_value(int argc
, char **argv
, int i
){
8307 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
8308 argv
[0], argv
[argc
-1]);
8314 #ifndef SQLITE_SHELL_IS_UTF8
8315 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8316 # define SQLITE_SHELL_IS_UTF8 (0)
8318 # define SQLITE_SHELL_IS_UTF8 (1)
8322 #if SQLITE_SHELL_IS_UTF8
8323 int SQLITE_CDECL
main(int argc
, char **argv
){
8325 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
8330 const char *zInitFile
= 0;
8333 int warnInmemoryDb
= 0;
8337 const char *zVfs
= 0; /* Value of -vfs command-line option */
8338 #if !SQLITE_SHELL_IS_UTF8
8339 char **argvToFree
= 0;
8343 setBinaryMode(stdin
, 0);
8344 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
8345 stdin_is_interactive
= isatty(0);
8346 stdout_is_console
= isatty(1);
8348 #if USE_SYSTEM_SQLITE+0!=1
8349 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
8350 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
8351 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
8357 /* On Windows, we must translate command-line arguments into UTF-8.
8358 ** The SQLite memory allocator subsystem has to be enabled in order to
8359 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8360 ** subsequent sqlite3_config() calls will work. So copy all results into
8361 ** memory that does not come from the SQLite memory allocator.
8363 #if !SQLITE_SHELL_IS_UTF8
8364 sqlite3_initialize();
8365 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
8367 argv
= argvToFree
+ argc
;
8368 if( argv
==0 ) shell_out_of_memory();
8369 for(i
=0; i
<argc
; i
++){
8370 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
8372 if( z
==0 ) shell_out_of_memory();
8374 argv
[i
] = malloc( n
+1 );
8375 if( argv
[i
]==0 ) shell_out_of_memory();
8376 memcpy(argv
[i
], z
, n
+1);
8377 argvToFree
[i
] = argv
[i
];
8383 assert( argc
>=1 && argv
&& argv
[0] );
8386 /* Make sure we have a valid signal handler early, before anything
8390 signal(SIGINT
, interrupt_handler
);
8391 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8392 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
8395 #ifdef SQLITE_SHELL_DBNAME_PROC
8397 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8398 ** of a C-function that will provide the name of the database file. Use
8399 ** this compile-time option to embed this shell program in larger
8401 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8402 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
8407 /* Do an initial pass through the command-line argument to locate
8408 ** the name of the database file, the name of the initialization file,
8409 ** the size of the alternative malloc heap,
8410 ** and the first command to execute.
8412 verify_uninitialized();
8413 for(i
=1; i
<argc
; i
++){
8417 if( data
.zDbFilename
==0 ){
8418 data
.zDbFilename
= z
;
8420 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8421 ** mean that nothing is read from stdin */
8424 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
8425 if( azCmd
==0 ) shell_out_of_memory();
8429 if( z
[1]=='-' ) z
++;
8430 if( strcmp(z
,"-separator")==0
8431 || strcmp(z
,"-nullvalue")==0
8432 || strcmp(z
,"-newline")==0
8433 || strcmp(z
,"-cmd")==0
8435 (void)cmdline_option_value(argc
, argv
, ++i
);
8436 }else if( strcmp(z
,"-init")==0 ){
8437 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
8438 }else if( strcmp(z
,"-batch")==0 ){
8439 /* Need to check for batch mode here to so we can avoid printing
8440 ** informational messages (like from process_sqliterc) before
8441 ** we do the actual processing of arguments later in a second pass.
8443 stdin_is_interactive
= 0;
8444 }else if( strcmp(z
,"-heap")==0 ){
8445 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8447 sqlite3_int64 szHeap
;
8449 zSize
= cmdline_option_value(argc
, argv
, ++i
);
8450 szHeap
= integerValue(zSize
);
8451 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
8452 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
8454 (void)cmdline_option_value(argc
, argv
, ++i
);
8456 }else if( strcmp(z
,"-pagecache")==0 ){
8458 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8459 if( sz
>70000 ) sz
= 70000;
8461 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8462 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
8463 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
8464 data
.shellFlgs
|= SHFLG_Pagecache
;
8465 }else if( strcmp(z
,"-lookaside")==0 ){
8467 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8469 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8471 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
8472 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
8473 #ifdef SQLITE_ENABLE_VFSTRACE
8474 }else if( strcmp(z
,"-vfstrace")==0 ){
8475 extern int vfstrace_register(
8476 const char *zTraceName
,
8477 const char *zOldVfsName
,
8478 int (*xOut
)(const char*,void*),
8482 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
8484 #ifdef SQLITE_ENABLE_MULTIPLEX
8485 }else if( strcmp(z
,"-multiplex")==0 ){
8486 extern int sqlite3_multiple_initialize(const char*,int);
8487 sqlite3_multiplex_initialize(0, 1);
8489 }else if( strcmp(z
,"-mmap")==0 ){
8490 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8491 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
8492 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8493 }else if( strcmp(z
,"-sorterref")==0 ){
8494 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8495 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
8497 }else if( strcmp(z
,"-vfs")==0 ){
8498 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
8499 #ifdef SQLITE_HAVE_ZLIB
8500 }else if( strcmp(z
,"-zip")==0 ){
8501 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8503 }else if( strcmp(z
,"-append")==0 ){
8504 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8505 }else if( strcmp(z
,"-readonly")==0 ){
8506 data
.openMode
= SHELL_OPEN_READONLY
;
8507 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8508 }else if( strncmp(z
, "-A",2)==0 ){
8509 /* All remaining command-line arguments are passed to the ".archive"
8510 ** command, so ignore them */
8515 verify_uninitialized();
8518 #ifdef SQLITE_SHELL_INIT_PROC
8520 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8521 ** of a C-function that will perform initialization actions on SQLite that
8522 ** occur just before or after sqlite3_initialize(). Use this compile-time
8523 ** option to embed this shell program in larger applications. */
8524 extern void SQLITE_SHELL_INIT_PROC(void);
8525 SQLITE_SHELL_INIT_PROC();
8528 /* All the sqlite3_config() calls have now been made. So it is safe
8529 ** to call sqlite3_initialize() and process any command line -vfs option. */
8530 sqlite3_initialize();
8534 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
8536 sqlite3_vfs_register(pVfs
, 1);
8538 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
8543 if( data
.zDbFilename
==0 ){
8544 #ifndef SQLITE_OMIT_MEMORYDB
8545 data
.zDbFilename
= ":memory:";
8546 warnInmemoryDb
= argc
==1;
8548 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
8553 sqlite3_appendvfs_init(0,0,0);
8555 /* Go ahead and open the database file if it already exists. If the
8556 ** file does not exist, delay opening it. This prevents empty database
8557 ** files from being created if a user mistypes the database name argument
8558 ** to the sqlite command-line tool.
8560 if( access(data
.zDbFilename
, 0)==0 ){
8564 /* Process the initialization file if there is one. If no -init option
8565 ** is given on the command line, look for a file named ~/.sqliterc and
8566 ** try to process it.
8568 process_sqliterc(&data
,zInitFile
);
8570 /* Make a second pass through the command-line argument and set
8571 ** options. This second pass is delayed until after the initialization
8572 ** file is processed so that the command-line arguments will override
8573 ** settings in the initialization file.
8575 for(i
=1; i
<argc
; i
++){
8577 if( z
[0]!='-' ) continue;
8578 if( z
[1]=='-' ){ z
++; }
8579 if( strcmp(z
,"-init")==0 ){
8581 }else if( strcmp(z
,"-html")==0 ){
8582 data
.mode
= MODE_Html
;
8583 }else if( strcmp(z
,"-list")==0 ){
8584 data
.mode
= MODE_List
;
8585 }else if( strcmp(z
,"-quote")==0 ){
8586 data
.mode
= MODE_Quote
;
8587 }else if( strcmp(z
,"-line")==0 ){
8588 data
.mode
= MODE_Line
;
8589 }else if( strcmp(z
,"-column")==0 ){
8590 data
.mode
= MODE_Column
;
8591 }else if( strcmp(z
,"-csv")==0 ){
8592 data
.mode
= MODE_Csv
;
8593 memcpy(data
.colSeparator
,",",2);
8594 #ifdef SQLITE_HAVE_ZLIB
8595 }else if( strcmp(z
,"-zip")==0 ){
8596 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8598 }else if( strcmp(z
,"-append")==0 ){
8599 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8600 }else if( strcmp(z
,"-readonly")==0 ){
8601 data
.openMode
= SHELL_OPEN_READONLY
;
8602 }else if( strcmp(z
,"-ascii")==0 ){
8603 data
.mode
= MODE_Ascii
;
8604 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8606 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8608 }else if( strcmp(z
,"-separator")==0 ){
8609 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8610 "%s",cmdline_option_value(argc
,argv
,++i
));
8611 }else if( strcmp(z
,"-newline")==0 ){
8612 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8613 "%s",cmdline_option_value(argc
,argv
,++i
));
8614 }else if( strcmp(z
,"-nullvalue")==0 ){
8615 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
8616 "%s",cmdline_option_value(argc
,argv
,++i
));
8617 }else if( strcmp(z
,"-header")==0 ){
8618 data
.showHeader
= 1;
8619 }else if( strcmp(z
,"-noheader")==0 ){
8620 data
.showHeader
= 0;
8621 }else if( strcmp(z
,"-echo")==0 ){
8622 ShellSetFlag(&data
, SHFLG_Echo
);
8623 }else if( strcmp(z
,"-eqp")==0 ){
8624 data
.autoEQP
= AUTOEQP_on
;
8625 }else if( strcmp(z
,"-eqpfull")==0 ){
8626 data
.autoEQP
= AUTOEQP_full
;
8627 }else if( strcmp(z
,"-stats")==0 ){
8629 }else if( strcmp(z
,"-scanstats")==0 ){
8630 data
.scanstatsOn
= 1;
8631 }else if( strcmp(z
,"-backslash")==0 ){
8632 /* Undocumented command-line option: -backslash
8633 ** Causes C-style backslash escapes to be evaluated in SQL statements
8634 ** prior to sending the SQL into SQLite. Useful for injecting
8635 ** crazy bytes in the middle of SQL statements for testing and debugging.
8637 ShellSetFlag(&data
, SHFLG_Backslash
);
8638 }else if( strcmp(z
,"-bail")==0 ){
8640 }else if( strcmp(z
,"-version")==0 ){
8641 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8643 }else if( strcmp(z
,"-interactive")==0 ){
8644 stdin_is_interactive
= 1;
8645 }else if( strcmp(z
,"-batch")==0 ){
8646 stdin_is_interactive
= 0;
8647 }else if( strcmp(z
,"-heap")==0 ){
8649 }else if( strcmp(z
,"-pagecache")==0 ){
8651 }else if( strcmp(z
,"-lookaside")==0 ){
8653 }else if( strcmp(z
,"-mmap")==0 ){
8655 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8656 }else if( strcmp(z
,"-sorterref")==0 ){
8659 }else if( strcmp(z
,"-vfs")==0 ){
8661 #ifdef SQLITE_ENABLE_VFSTRACE
8662 }else if( strcmp(z
,"-vfstrace")==0 ){
8665 #ifdef SQLITE_ENABLE_MULTIPLEX
8666 }else if( strcmp(z
,"-multiplex")==0 ){
8669 }else if( strcmp(z
,"-help")==0 ){
8671 }else if( strcmp(z
,"-cmd")==0 ){
8672 /* Run commands that follow -cmd first and separately from commands
8673 ** that simply appear on the command-line. This seems goofy. It would
8674 ** be better if all commands ran in the order that they appear. But
8675 ** we retain the goofy behavior for historical compatibility. */
8676 if( i
==argc
-1 ) break;
8677 z
= cmdline_option_value(argc
,argv
,++i
);
8679 rc
= do_meta_command(z
, &data
);
8680 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
8683 rc
= shell_exec(&data
, z
, &zErrMsg
);
8685 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8686 if( bail_on_error
) return rc
!=0 ? rc
: 1;
8688 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
8689 if( bail_on_error
) return rc
;
8692 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8693 }else if( strncmp(z
, "-A", 2)==0 ){
8695 utf8_printf(stderr
, "Error: cannot mix regular SQL or dot-commands"
8696 " with \"%s\"\n", z
);
8699 open_db(&data
, OPEN_DB_ZIPFILE
);
8702 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
8704 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
8710 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
8711 raw_printf(stderr
,"Use -help for a list of options.\n");
8714 data
.cMode
= data
.mode
;
8718 /* Run all arguments that do not begin with '-' as if they were separate
8719 ** command-line inputs, except for the argToSkip argument which contains
8720 ** the database filename.
8722 for(i
=0; i
<nCmd
; i
++){
8723 if( azCmd
[i
][0]=='.' ){
8724 rc
= do_meta_command(azCmd
[i
], &data
);
8725 if( rc
) return rc
==2 ? 0 : rc
;
8728 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
8730 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8731 return rc
!=0 ? rc
: 1;
8733 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
8740 /* Run commands received from standard input
8742 if( stdin_is_interactive
){
8747 "SQLite version %s %.19s\n" /*extra-version-info*/
8748 "Enter \".help\" for usage hints.\n",
8749 sqlite3_libversion(), sqlite3_sourceid()
8751 if( warnInmemoryDb
){
8752 printf("Connected to a ");
8753 printBold("transient in-memory database");
8754 printf(".\nUse \".open FILENAME\" to reopen on a "
8755 "persistent database.\n");
8757 zHome
= find_home_dir(0);
8759 nHistory
= strlen30(zHome
) + 20;
8760 if( (zHistory
= malloc(nHistory
))!=0 ){
8761 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
8764 if( zHistory
){ shell_read_history(zHistory
); }
8765 #if HAVE_READLINE || HAVE_EDITLINE
8766 rl_attempted_completion_function
= readline_completion
;
8767 #elif HAVE_LINENOISE
8768 linenoiseSetCompletionCallback(linenoise_completion
);
8770 rc
= process_input(&data
, 0);
8772 shell_stifle_history(2000);
8773 shell_write_history(zHistory
);
8777 rc
= process_input(&data
, stdin
);
8780 set_table_name(&data
, 0);
8782 session_close_all(&data
);
8785 sqlite3_free(data
.zFreeOnClose
);
8787 output_reset(&data
);
8789 clearTempFile(&data
);
8790 #if !SQLITE_SHELL_IS_UTF8
8791 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
8794 /* Clear the global data structure so that valgrind will detect memory
8796 memset(&data
, 0, sizeof(data
));