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 #if SQLITE_USER_AUTHENTICATION
65 # include "sqlite3userauth.h"
70 #if !defined(_WIN32) && !defined(WIN32)
72 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
76 # include <sys/types.h>
80 # include <readline/readline.h>
81 # include <readline/history.h>
85 # include <editline/readline.h>
88 #if HAVE_EDITLINE || HAVE_READLINE
90 # define shell_add_history(X) add_history(X)
91 # define shell_read_history(X) read_history(X)
92 # define shell_write_history(X) write_history(X)
93 # define shell_stifle_history(X) stifle_history(X)
94 # define shell_readline(X) readline(X)
98 # include "linenoise.h"
99 # define shell_add_history(X) linenoiseHistoryAdd(X)
100 # define shell_read_history(X) linenoiseHistoryLoad(X)
101 # define shell_write_history(X) linenoiseHistorySave(X)
102 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103 # define shell_readline(X) linenoise(X)
107 # define shell_read_history(X)
108 # define shell_write_history(X)
109 # define shell_stifle_history(X)
111 # define SHELL_USE_LOCAL_GETLINE 1
115 #if defined(_WIN32) || defined(WIN32)
118 # define isatty(h) _isatty(h)
120 # define access(f,m) _access((f),(m))
123 # define popen _popen
125 # define pclose _pclose
127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
130 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
131 /* popen and pclose are not C89 functions and so are
132 ** sometimes omitted from the <stdio.h> header */
133 extern FILE *popen(const char*,const char*);
134 extern int pclose(FILE*);
136 # define SQLITE_OMIT_POPEN 1
140 #if defined(_WIN32_WCE)
141 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
148 /* ctype macros that work with signed characters */
149 #define IsSpace(X) isspace((unsigned char)X)
150 #define IsDigit(X) isdigit((unsigned char)X)
151 #define ToLower(X) (char)tolower((unsigned char)X)
153 #if defined(_WIN32) || defined(WIN32)
156 /* string conversion routines only needed on Win32 */
157 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
158 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
160 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
163 /* On Windows, we normally run with output mode of TEXT so that \n characters
164 ** are automatically translated into \r\n. However, this behavior needs
165 ** to be disabled in some cases (ex: when generating CSV output and when
166 ** rendering quoted strings that contain \n characters). The following
167 ** routines take care of that.
169 #if defined(_WIN32) || defined(WIN32)
170 static void setBinaryMode(FILE *file
, int isOutput
){
171 if( isOutput
) fflush(file
);
172 _setmode(_fileno(file
), _O_BINARY
);
174 static void setTextMode(FILE *file
, int isOutput
){
175 if( isOutput
) fflush(file
);
176 _setmode(_fileno(file
), _O_TEXT
);
179 # define setBinaryMode(X,Y)
180 # define setTextMode(X,Y)
184 /* True if the timer is enabled */
185 static int enableTimer
= 0;
187 /* Return the current wall-clock time */
188 static sqlite3_int64
timeOfDay(void){
189 static sqlite3_vfs
*clockVfs
= 0;
191 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
192 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
193 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
196 clockVfs
->xCurrentTime(clockVfs
, &r
);
197 t
= (sqlite3_int64
)(r
*86400000.0);
202 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
203 #include <sys/time.h>
204 #include <sys/resource.h>
206 /* VxWorks does not support getrusage() as far as we can determine */
207 #if defined(_WRS_KERNEL) || defined(__RTP__)
209 struct timeval ru_utime
; /* user CPU time used */
210 struct timeval ru_stime
; /* system CPU time used */
212 #define getrusage(A,B) memset(B,0,sizeof(*B))
215 /* Saved resource information for the beginning of an operation */
216 static struct rusage sBegin
; /* CPU time at start */
217 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
220 ** Begin timing an operation
222 static void beginTimer(void){
224 getrusage(RUSAGE_SELF
, &sBegin
);
225 iBegin
= timeOfDay();
229 /* Return the difference of two time_structs in seconds */
230 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
231 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
232 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
236 ** Print the timing results.
238 static void endTimer(void){
240 sqlite3_int64 iEnd
= timeOfDay();
242 getrusage(RUSAGE_SELF
, &sEnd
);
243 printf("Run Time: real %.3f user %f sys %f\n",
244 (iEnd
- iBegin
)*0.001,
245 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
246 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
250 #define BEGIN_TIMER beginTimer()
251 #define END_TIMER endTimer()
254 #elif (defined(_WIN32) || defined(WIN32))
256 /* Saved resource information for the beginning of an operation */
257 static HANDLE hProcess
;
258 static FILETIME ftKernelBegin
;
259 static FILETIME ftUserBegin
;
260 static sqlite3_int64 ftWallBegin
;
261 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
262 LPFILETIME
, LPFILETIME
);
263 static GETPROCTIMES getProcessTimesAddr
= NULL
;
266 ** Check to see if we have timer support. Return 1 if necessary
267 ** support found (or found previously).
269 static int hasTimer(void){
270 if( getProcessTimesAddr
){
273 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274 ** versions. See if the version we are running on has it, and if it
275 ** does, save off a pointer to it and the current process handle.
277 hProcess
= GetCurrentProcess();
279 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
280 if( NULL
!= hinstLib
){
281 getProcessTimesAddr
=
282 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
283 if( NULL
!= getProcessTimesAddr
){
286 FreeLibrary(hinstLib
);
294 ** Begin timing an operation
296 static void beginTimer(void){
297 if( enableTimer
&& getProcessTimesAddr
){
298 FILETIME ftCreation
, ftExit
;
299 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
300 &ftKernelBegin
,&ftUserBegin
);
301 ftWallBegin
= timeOfDay();
305 /* Return the difference of two FILETIME structs in seconds */
306 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
307 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
308 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
309 return (double) ((i64End
- i64Start
) / 10000000.0);
313 ** Print the timing results.
315 static void endTimer(void){
316 if( enableTimer
&& getProcessTimesAddr
){
317 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
318 sqlite3_int64 ftWallEnd
= timeOfDay();
319 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
320 printf("Run Time: real %.3f user %f sys %f\n",
321 (ftWallEnd
- ftWallBegin
)*0.001,
322 timeDiff(&ftUserBegin
, &ftUserEnd
),
323 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
327 #define BEGIN_TIMER beginTimer()
328 #define END_TIMER endTimer()
329 #define HAS_TIMER hasTimer()
338 ** Used to prevent warnings about unused parameters
340 #define UNUSED_PARAMETER(x) (void)(x)
343 ** If the following flag is set, then command execution stops
344 ** at an error if we are not interactive.
346 static int bail_on_error
= 0;
349 ** Threat stdin as an interactive input if the following variable
350 ** is true. Otherwise, assume stdin is connected to a file or pipe.
352 static int stdin_is_interactive
= 1;
355 ** On Windows systems we have to know if standard output is a console
356 ** in order to translate UTF-8 into MBCS. The following variable is
357 ** true if translation is required.
359 static int stdout_is_console
= 1;
362 ** The following is the open SQLite database. We make a pointer
363 ** to this database a static variable so that it can be accessed
364 ** by the SIGINT handler to interrupt database processing.
366 static sqlite3
*globalDb
= 0;
369 ** True if an interrupt (Control-C) has been received.
371 static volatile int seenInterrupt
= 0;
374 ** This is the name of our program. It is set in main(), used
375 ** in a number of other places, mostly for error messages.
380 ** Prompt strings. Initialized in main. Settable with
381 ** .prompt main continue
383 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
384 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
387 ** Render output like fprintf(). Except, if the output is going to the
388 ** console and if this is running on a Windows machine, translate the
389 ** output from UTF-8 into MBCS.
391 #if defined(_WIN32) || defined(WIN32)
392 void utf8_printf(FILE *out
, const char *zFormat
, ...){
394 va_start(ap
, zFormat
);
395 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
396 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
397 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
402 vfprintf(out
, zFormat
, ap
);
406 #elif !defined(utf8_printf)
407 # define utf8_printf fprintf
411 ** Render output like fprintf(). This should not be used on anything that
412 ** includes string formatting (e.g. "%s").
414 #if !defined(raw_printf)
415 # define raw_printf fprintf
419 ** Write I/O traces to the following stream.
421 #ifdef SQLITE_ENABLE_IOTRACE
422 static FILE *iotrace
= 0;
426 ** This routine works like printf in that its first argument is a
427 ** format string and subsequent arguments are values to be substituted
428 ** in place of % fields. The result of formatting this string
429 ** is written to iotrace.
431 #ifdef SQLITE_ENABLE_IOTRACE
432 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
435 if( iotrace
==0 ) return;
436 va_start(ap
, zFormat
);
437 z
= sqlite3_vmprintf(zFormat
, ap
);
439 utf8_printf(iotrace
, "%s", z
);
445 ** Output string zUtf to stream pOut as w characters. If w is negative,
446 ** then right-justify the text. W is the width in UTF-8 characters, not
447 ** in bytes. This is different from the %*.*s specification in printf
448 ** since with %*.*s the width is measured in bytes, not characters.
450 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
453 int aw
= w
<0 ? -w
: w
;
455 if( aw
>(int)sizeof(zBuf
)/3 ) aw
= (int)sizeof(zBuf
)/3;
456 for(i
=n
=0; zUtf
[i
]; i
++){
457 if( (zUtf
[i
]&0xc0)!=0x80 ){
460 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
466 utf8_printf(pOut
, "%.*s", i
, zUtf
);
468 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
470 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
476 ** Determines if a string is a number of not.
478 static int isNumber(const char *z
, int *realnum
){
479 if( *z
=='-' || *z
=='+' ) z
++;
484 if( realnum
) *realnum
= 0;
485 while( IsDigit(*z
) ){ z
++; }
488 if( !IsDigit(*z
) ) return 0;
489 while( IsDigit(*z
) ){ z
++; }
490 if( realnum
) *realnum
= 1;
492 if( *z
=='e' || *z
=='E' ){
494 if( *z
=='+' || *z
=='-' ) z
++;
495 if( !IsDigit(*z
) ) return 0;
496 while( IsDigit(*z
) ){ z
++; }
497 if( realnum
) *realnum
= 1;
503 ** Compute a string length that is limited to what can be stored in
504 ** lower 30 bits of a 32-bit signed integer.
506 static int strlen30(const char *z
){
508 while( *z2
){ z2
++; }
509 return 0x3fffffff & (int)(z2
- z
);
513 ** Return the length of a string in characters. Multibyte UTF8 characters
514 ** count as a single character.
516 static int strlenChar(const char *z
){
519 if( (0xc0&*(z
++))!=0x80 ) n
++;
525 ** This routine reads a line of text from FILE in, stores
526 ** the text in memory obtained from malloc() and returns a pointer
527 ** to the text. NULL is returned at end of file, or if malloc()
530 ** If zLine is not NULL then it is a malloced buffer returned from
531 ** a previous call to this routine that may be reused.
533 static char *local_getline(char *zLine
, FILE *in
){
534 int nLine
= zLine
==0 ? 0 : 100;
539 nLine
= nLine
*2 + 100;
540 zLine
= realloc(zLine
, nLine
);
541 if( zLine
==0 ) return 0;
543 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
551 while( zLine
[n
] ) n
++;
552 if( n
>0 && zLine
[n
-1]=='\n' ){
554 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
559 #if defined(_WIN32) || defined(WIN32)
560 /* For interactive input on Windows systems, translate the
561 ** multi-byte characterset characters into UTF-8. */
562 if( stdin_is_interactive
&& in
==stdin
){
563 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
565 int nTrans
= strlen30(zTrans
)+1;
567 zLine
= realloc(zLine
, nTrans
);
569 sqlite3_free(zTrans
);
573 memcpy(zLine
, zTrans
, nTrans
);
574 sqlite3_free(zTrans
);
577 #endif /* defined(_WIN32) || defined(WIN32) */
582 ** Retrieve a single line of input text.
584 ** If in==0 then read from standard input and prompt before each line.
585 ** If isContinuation is true, then a continuation prompt is appropriate.
586 ** If isContinuation is zero, then the main prompt should be used.
588 ** If zPrior is not NULL then it is a buffer from a prior call to this
589 ** routine that can be reused.
591 ** The result is stored in space obtained from malloc() and must either
592 ** be freed by the caller or else passed back into this routine via the
593 ** zPrior argument for reuse.
595 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
599 zResult
= local_getline(zPrior
, in
);
601 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
602 #if SHELL_USE_LOCAL_GETLINE
603 printf("%s", zPrompt
);
605 zResult
= local_getline(zPrior
, stdin
);
608 zResult
= shell_readline(zPrompt
);
609 if( zResult
&& *zResult
) shell_add_history(zResult
);
615 ** A variable length string to which one can append text.
617 typedef struct ShellText ShellText
;
625 ** Initialize and destroy a ShellText object
627 static void initText(ShellText
*p
){
628 memset(p
, 0, sizeof(*p
));
630 static void freeText(ShellText
*p
){
635 /* zIn is either a pointer to a NULL-terminated string in memory obtained
636 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637 ** added to zIn, and the result returned in memory obtained from malloc().
638 ** zIn, if it was not NULL, is freed.
640 ** If the third argument, quote, is not '\0', then it is used as a
641 ** quote character for zAppend.
643 static void appendText(ShellText
*p
, char const *zAppend
, char quote
){
646 int nAppend
= strlen30(zAppend
);
648 len
= nAppend
+p
->n
+1;
651 for(i
=0; i
<nAppend
; i
++){
652 if( zAppend
[i
]==quote
) len
++;
656 if( p
->n
+len
>=p
->nAlloc
){
657 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
658 p
->z
= realloc(p
->z
, p
->nAlloc
);
660 memset(p
, 0, sizeof(*p
));
666 char *zCsr
= p
->z
+p
->n
;
668 for(i
=0; i
<nAppend
; i
++){
669 *zCsr
++ = zAppend
[i
];
670 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
673 p
->n
= (int)(zCsr
- p
->z
);
676 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
683 ** Attempt to determine if identifier zName needs to be quoted, either
684 ** because it contains non-alphanumeric characters, or because it is an
685 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
686 ** that quoting is required.
688 ** Return '"' if quoting is required. Return 0 if no quoting is required.
690 static char quoteChar(const char *zName
){
691 /* All SQLite keywords, in alphabetical order */
692 static const char *azKeywords
[] = {
693 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
712 int i
, lwr
, upr
, mid
, c
;
713 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
714 for(i
=0; zName
[i
]; i
++){
715 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
718 upr
= sizeof(azKeywords
)/sizeof(azKeywords
[0]) - 1;
721 c
= sqlite3_stricmp(azKeywords
[mid
], zName
);
722 if( c
==0 ) return '"';
733 ** SQL function: shell_add_schema(S,X)
735 ** Add the schema name X to the CREATE statement in S and return the result.
738 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
743 ** CREATE UNIQUE INDEX
746 ** CREATE VIRTUAL TABLE
748 ** This UDF is used by the .schema command to insert the schema name of
749 ** attached databases into the middle of the sqlite_master.sql field.
751 static void shellAddSchemaName(
752 sqlite3_context
*pCtx
,
754 sqlite3_value
**apVal
756 static const char *aPrefix
[] = {
765 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
766 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
768 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
769 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
770 int n
= strlen30(aPrefix
[i
]);
771 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
772 char cQuote
= quoteChar(zSchema
);
775 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
777 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
779 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
784 sqlite3_result_value(pCtx
, apVal
[0]);
788 ** The source code for several run-time loadable extensions is inserted
789 ** below by the ../tool/mkshellc.tcl script. Before processing that included
790 ** code, we need to override some macros to make the included program code
791 ** work here in the middle of this regular program.
793 #define SQLITE_EXTENSION_INIT1
794 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
796 INCLUDE
../ext
/misc
/shathree
.c
797 INCLUDE
../ext
/misc
/fileio
.c
798 INCLUDE
../ext
/misc
/completion
.c
800 #if defined(SQLITE_ENABLE_SESSION)
802 ** State information for a single open session
804 typedef struct OpenSession OpenSession
;
806 char *zName
; /* Symbolic name for this session */
807 int nFilter
; /* Number of xFilter rejection GLOB patterns */
808 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
809 sqlite3_session
*p
; /* The open session */
814 ** Shell output mode information from before ".explain on",
815 ** saved so that it can be restored by ".explain off"
817 typedef struct SavedModeInfo SavedModeInfo
;
818 struct SavedModeInfo
{
819 int valid
; /* Is there legit data in here? */
820 int mode
; /* Mode prior to ".explain on" */
821 int showHeader
; /* The ".header" setting prior to ".explain on" */
822 int colWidth
[100]; /* Column widths prior to ".explain on" */
826 ** State information about the database connection is contained in an
827 ** instance of the following structure.
829 typedef struct ShellState ShellState
;
831 sqlite3
*db
; /* The database */
832 int autoExplain
; /* Automatically turn on .explain mode */
833 int autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
834 int statsOn
; /* True to display memory stats before each finalize */
835 int scanstatsOn
; /* True to display scan stats before each finalize */
836 int outCount
; /* Revert to stdout when reaching zero */
837 int cnt
; /* Number of records displayed so far */
838 FILE *out
; /* Write results here */
839 FILE *traceOut
; /* Output for sqlite3_trace() */
840 int nErr
; /* Number of errors seen */
841 int mode
; /* An output mode setting */
842 int cMode
; /* temporary output mode for the current query */
843 int normalMode
; /* Output mode before ".explain on" */
844 int writableSchema
; /* True if PRAGMA writable_schema=ON */
845 int showHeader
; /* True to show column names in List or Column mode */
846 int nCheck
; /* Number of ".check" commands run */
847 unsigned shellFlgs
; /* Various flags */
848 char *zDestTable
; /* Name of destination table when MODE_Insert */
849 char zTestcase
[30]; /* Name of current test case */
850 char colSeparator
[20]; /* Column separator character for several modes */
851 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
852 int colWidth
[100]; /* Requested width of each column when in column mode*/
853 int actualWidth
[100]; /* Actual width of each column */
854 char nullValue
[20]; /* The text to print when a NULL comes back from
856 char outfile
[FILENAME_MAX
]; /* Filename for *out */
857 const char *zDbFilename
; /* name of the database file */
858 char *zFreeOnClose
; /* Filename to free when closing */
859 const char *zVfs
; /* Name of VFS to use */
860 sqlite3_stmt
*pStmt
; /* Current statement if any. */
861 FILE *pLog
; /* Write log output here */
862 int *aiIndent
; /* Array of indents used in MODE_Explain */
863 int nIndent
; /* Size of array aiIndent[] */
864 int iIndent
; /* Index of current op in aiIndent[] */
865 #if defined(SQLITE_ENABLE_SESSION)
866 int nSession
; /* Number of active sessions */
867 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
872 ** These are the allowed shellFlgs values
874 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
875 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
876 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
877 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
878 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
879 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
880 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
883 ** Macros for testing and setting shellFlgs
885 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
886 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
887 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
890 ** These are the allowed modes.
892 #define MODE_Line 0 /* One column per line. Blank line between records */
893 #define MODE_Column 1 /* One record per line in neat columns */
894 #define MODE_List 2 /* One record per line with a separator */
895 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
896 #define MODE_Html 4 /* Generate an XHTML table */
897 #define MODE_Insert 5 /* Generate SQL "insert" statements */
898 #define MODE_Quote 6 /* Quote values as for SQL */
899 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
900 #define MODE_Csv 8 /* Quote strings, numbers are plain */
901 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
902 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
903 #define MODE_Pretty 11 /* Pretty-print schemas */
905 static const char *modeDescr
[] = {
921 ** These are the column/row/line separators used by the various
922 ** import/export modes.
924 #define SEP_Column "|"
927 #define SEP_Space " "
928 #define SEP_Comma ","
929 #define SEP_CrLf "\r\n"
930 #define SEP_Unit "\x1F"
931 #define SEP_Record "\x1E"
934 ** Number of elements in an array
936 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
939 ** A callback for the sqlite3_log() interface.
941 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
942 ShellState
*p
= (ShellState
*)pArg
;
943 if( p
->pLog
==0 ) return;
944 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
949 ** Output the given string as a hex-encoded blob (eg. X'1234' )
951 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
953 char *zBlob
= (char *)pBlob
;
954 raw_printf(out
,"X'");
955 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
960 ** Find a string that is not found anywhere in z[]. Return a pointer
963 ** Try to use zA and zB first. If both of those are already found in z[]
964 ** then make up some string and store it in the buffer zBuf.
966 static const char *unused_string(
967 const char *z
, /* Result must not appear anywhere in z */
968 const char *zA
, const char *zB
, /* Try these first */
969 char *zBuf
/* Space to store a generated string */
972 if( strstr(z
, zA
)==0 ) return zA
;
973 if( strstr(z
, zB
)==0 ) return zB
;
975 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
976 }while( strstr(z
,zBuf
)!=0 );
981 ** Output the given string as a quoted string using SQL quoting conventions.
983 ** See also: output_quoted_escaped_string()
985 static void output_quoted_string(FILE *out
, const char *z
){
988 setBinaryMode(out
, 1);
989 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
991 utf8_printf(out
,"'%s'",z
);
993 raw_printf(out
, "'");
995 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
998 utf8_printf(out
, "%.*s", i
, z
);
1002 raw_printf(out
, "'");
1010 raw_printf(out
, "'");
1012 setTextMode(out
, 1);
1016 ** Output the given string as a quoted string using SQL quoting conventions.
1017 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1018 ** get corrupted by end-of-line translation facilities in some operating
1021 ** This is like output_quoted_string() but with the addition of the \r\n
1022 ** escape mechanism.
1024 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1027 setBinaryMode(out
, 1);
1028 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1030 utf8_printf(out
,"'%s'",z
);
1032 const char *zNL
= 0;
1033 const char *zCR
= 0;
1036 char zBuf1
[20], zBuf2
[20];
1037 for(i
=0; z
[i
]; i
++){
1038 if( z
[i
]=='\n' ) nNL
++;
1039 if( z
[i
]=='\r' ) nCR
++;
1042 raw_printf(out
, "replace(");
1043 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1046 raw_printf(out
, "replace(");
1047 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1049 raw_printf(out
, "'");
1051 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1054 utf8_printf(out
, "%.*s", i
, z
);
1058 raw_printf(out
, "'");
1066 raw_printf(out
, "%s", zNL
);
1069 raw_printf(out
, "%s", zCR
);
1071 raw_printf(out
, "'");
1073 raw_printf(out
, ",'%s',char(13))", zCR
);
1076 raw_printf(out
, ",'%s',char(10))", zNL
);
1079 setTextMode(out
, 1);
1083 ** Output the given string as a quoted according to C or TCL quoting rules.
1085 static void output_c_string(FILE *out
, const char *z
){
1088 while( (c
= *(z
++))!=0 ){
1095 }else if( c
=='\t' ){
1098 }else if( c
=='\n' ){
1101 }else if( c
=='\r' ){
1104 }else if( !isprint(c
&0xff) ){
1105 raw_printf(out
, "\\%03o", c
&0xff);
1114 ** Output the given string with characters that are special to
1117 static void output_html_string(FILE *out
, const char *z
){
1129 utf8_printf(out
,"%.*s",i
,z
);
1132 raw_printf(out
,"<");
1133 }else if( z
[i
]=='&' ){
1134 raw_printf(out
,"&");
1135 }else if( z
[i
]=='>' ){
1136 raw_printf(out
,">");
1137 }else if( z
[i
]=='\"' ){
1138 raw_printf(out
,""");
1139 }else if( z
[i
]=='\'' ){
1140 raw_printf(out
,"'");
1149 ** If a field contains any character identified by a 1 in the following
1150 ** array, then the string must be quoted for CSV.
1152 static const char needCsvQuote
[] = {
1153 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1154 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1155 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1156 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1157 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1158 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1159 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1160 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1162 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1163 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1164 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1165 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1166 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1167 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1168 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1172 ** Output a single term of CSV. Actually, p->colSeparator is used for
1173 ** the separator, which may or may not be a comma. p->nullValue is
1174 ** the null value. Strings are quoted if necessary. The separator
1175 ** is only issued if bSep is true.
1177 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1180 utf8_printf(out
,"%s",p
->nullValue
);
1183 int nSep
= strlen30(p
->colSeparator
);
1184 for(i
=0; z
[i
]; i
++){
1185 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1186 || (z
[i
]==p
->colSeparator
[0] &&
1187 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1194 for(i
=0; z
[i
]; i
++){
1195 if( z
[i
]=='"' ) putc('"', out
);
1200 utf8_printf(out
, "%s", z
);
1204 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1209 ** This routine runs when the user presses Ctrl-C
1211 static void interrupt_handler(int NotUsed
){
1212 UNUSED_PARAMETER(NotUsed
);
1214 if( seenInterrupt
>2 ) exit(1);
1215 if( globalDb
) sqlite3_interrupt(globalDb
);
1218 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1220 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1222 static BOOL WINAPI
ConsoleCtrlHandler(
1223 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1225 if( dwCtrlType
==CTRL_C_EVENT
){
1226 interrupt_handler(0);
1233 #ifndef SQLITE_OMIT_AUTHORIZATION
1235 ** When the ".auth ON" is set, the following authorizer callback is
1236 ** invoked. It always returns SQLITE_OK.
1238 static int shellAuth(
1246 ShellState
*p
= (ShellState
*)pClientData
;
1247 static const char *azAction
[] = { 0,
1248 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1249 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1250 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1251 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1252 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1253 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1254 "PRAGMA", "READ", "SELECT",
1255 "TRANSACTION", "UPDATE", "ATTACH",
1256 "DETACH", "ALTER_TABLE", "REINDEX",
1257 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1258 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1266 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1268 raw_printf(p
->out
, " ");
1270 output_c_string(p
->out
, az
[i
]);
1272 raw_printf(p
->out
, "NULL");
1275 raw_printf(p
->out
, "\n");
1281 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1283 ** This routine converts some CREATE TABLE statements for shadow tables
1284 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1286 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1287 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1288 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1290 utf8_printf(out
, "%s%s", z
, zTail
);
1293 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1296 printSchemaLine(out
, z
, zTail
);
1301 ** This is the callback routine that the shell
1302 ** invokes for each row of a query result.
1304 static int shell_callback(
1306 int nArg
, /* Number of result columns */
1307 char **azArg
, /* Text of each result column */
1308 char **azCol
, /* Column names */
1309 int *aiType
/* Column types */
1312 ShellState
*p
= (ShellState
*)pArg
;
1314 if( azArg
==0 ) return 0;
1318 if( azArg
==0 ) break;
1319 for(i
=0; i
<nArg
; i
++){
1320 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1321 if( len
>w
) w
= len
;
1323 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1324 for(i
=0; i
<nArg
; i
++){
1325 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1326 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1332 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1333 const int *colWidth
;
1336 if( p
->cMode
==MODE_Column
){
1337 colWidth
= p
->colWidth
;
1338 showHdr
= p
->showHeader
;
1339 rowSep
= p
->rowSeparator
;
1341 colWidth
= aExplainWidths
;
1346 for(i
=0; i
<nArg
; i
++){
1348 if( i
<ArraySize(p
->colWidth
) ){
1354 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1356 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1359 if( i
<ArraySize(p
->actualWidth
) ){
1360 p
->actualWidth
[i
] = w
;
1363 utf8_width_print(p
->out
, w
, azCol
[i
]);
1364 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1368 for(i
=0; i
<nArg
; i
++){
1370 if( i
<ArraySize(p
->actualWidth
) ){
1371 w
= p
->actualWidth
[i
];
1376 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1377 "----------------------------------------------------------"
1378 "----------------------------------------------------------",
1379 i
==nArg
-1 ? rowSep
: " ");
1383 if( azArg
==0 ) break;
1384 for(i
=0; i
<nArg
; i
++){
1386 if( i
<ArraySize(p
->actualWidth
) ){
1387 w
= p
->actualWidth
[i
];
1391 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1392 w
= strlenChar(azArg
[i
]);
1394 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1395 if( p
->iIndent
<p
->nIndent
){
1396 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1400 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1401 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1405 case MODE_Semi
: { /* .schema and .fullschema output */
1406 printSchemaLine(p
->out
, azArg
[0], ";\n");
1409 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1417 if( azArg
[0]==0 ) break;
1418 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1419 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1421 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1424 z
= sqlite3_mprintf("%s", azArg
[0]);
1426 for(i
=0; IsSpace(z
[i
]); i
++){}
1427 for(; (c
= z
[i
])!=0; i
++){
1429 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1430 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1431 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1436 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1438 if( strlen30(z
)>=79 ){
1439 for(i
=j
=0; (c
= z
[i
])!=0; i
++){
1442 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1450 if( nLine
>0 && nParen
==0 && j
>0 ){
1451 printSchemaLineN(p
->out
, z
, j
, "\n");
1456 if( nParen
==1 && (c
=='(' || c
==',' || c
=='\n') ){
1458 printSchemaLineN(p
->out
, z
, j
, "\n ");
1461 while( IsSpace(z
[i
+1]) ){ i
++; }
1466 printSchemaLine(p
->out
, z
, ";\n");
1471 if( p
->cnt
++==0 && p
->showHeader
){
1472 for(i
=0; i
<nArg
; i
++){
1473 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1474 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1477 if( azArg
==0 ) break;
1478 for(i
=0; i
<nArg
; i
++){
1480 if( z
==0 ) z
= p
->nullValue
;
1481 utf8_printf(p
->out
, "%s", z
);
1483 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1485 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1491 if( p
->cnt
++==0 && p
->showHeader
){
1492 raw_printf(p
->out
,"<TR>");
1493 for(i
=0; i
<nArg
; i
++){
1494 raw_printf(p
->out
,"<TH>");
1495 output_html_string(p
->out
, azCol
[i
]);
1496 raw_printf(p
->out
,"</TH>\n");
1498 raw_printf(p
->out
,"</TR>\n");
1500 if( azArg
==0 ) break;
1501 raw_printf(p
->out
,"<TR>");
1502 for(i
=0; i
<nArg
; i
++){
1503 raw_printf(p
->out
,"<TD>");
1504 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1505 raw_printf(p
->out
,"</TD>\n");
1507 raw_printf(p
->out
,"</TR>\n");
1511 if( p
->cnt
++==0 && p
->showHeader
){
1512 for(i
=0; i
<nArg
; i
++){
1513 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1514 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1516 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1518 if( azArg
==0 ) break;
1519 for(i
=0; i
<nArg
; i
++){
1520 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1521 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1523 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1527 setBinaryMode(p
->out
, 1);
1528 if( p
->cnt
++==0 && p
->showHeader
){
1529 for(i
=0; i
<nArg
; i
++){
1530 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
1532 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1535 for(i
=0; i
<nArg
; i
++){
1536 output_csv(p
, azArg
[i
], i
<nArg
-1);
1538 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1540 setTextMode(p
->out
, 1);
1544 if( azArg
==0 ) break;
1545 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
1546 if( p
->showHeader
){
1547 raw_printf(p
->out
,"(");
1548 for(i
=0; i
<nArg
; i
++){
1549 if( i
>0 ) raw_printf(p
->out
, ",");
1550 if( quoteChar(azCol
[i
]) ){
1551 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
1552 utf8_printf(p
->out
, "%s", z
);
1555 raw_printf(p
->out
, "%s", azCol
[i
]);
1558 raw_printf(p
->out
,")");
1561 for(i
=0; i
<nArg
; i
++){
1562 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
1563 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1564 utf8_printf(p
->out
,"NULL");
1565 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1566 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1567 output_quoted_string(p
->out
, azArg
[i
]);
1569 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1571 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1572 utf8_printf(p
->out
,"%s", azArg
[i
]);
1573 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1575 double r
= sqlite3_column_double(p
->pStmt
, i
);
1576 sqlite3_snprintf(50,z
,"%!.20g", r
);
1577 raw_printf(p
->out
, "%s", z
);
1578 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1579 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1580 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1581 output_hex_blob(p
->out
, pBlob
, nBlob
);
1582 }else if( isNumber(azArg
[i
], 0) ){
1583 utf8_printf(p
->out
,"%s", azArg
[i
]);
1584 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1585 output_quoted_string(p
->out
, azArg
[i
]);
1587 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1590 raw_printf(p
->out
,");\n");
1594 if( azArg
==0 ) break;
1595 if( p
->cnt
==0 && p
->showHeader
){
1596 for(i
=0; i
<nArg
; i
++){
1597 if( i
>0 ) raw_printf(p
->out
, ",");
1598 output_quoted_string(p
->out
, azCol
[i
]);
1600 raw_printf(p
->out
,"\n");
1603 for(i
=0; i
<nArg
; i
++){
1604 if( i
>0 ) raw_printf(p
->out
, ",");
1605 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1606 utf8_printf(p
->out
,"NULL");
1607 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1608 output_quoted_string(p
->out
, azArg
[i
]);
1609 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1610 utf8_printf(p
->out
,"%s", azArg
[i
]);
1611 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1613 double r
= sqlite3_column_double(p
->pStmt
, i
);
1614 sqlite3_snprintf(50,z
,"%!.20g", r
);
1615 raw_printf(p
->out
, "%s", z
);
1616 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1617 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1618 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1619 output_hex_blob(p
->out
, pBlob
, nBlob
);
1620 }else if( isNumber(azArg
[i
], 0) ){
1621 utf8_printf(p
->out
,"%s", azArg
[i
]);
1623 output_quoted_string(p
->out
, azArg
[i
]);
1626 raw_printf(p
->out
,"\n");
1630 if( p
->cnt
++==0 && p
->showHeader
){
1631 for(i
=0; i
<nArg
; i
++){
1632 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1633 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
1635 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1637 if( azArg
==0 ) break;
1638 for(i
=0; i
<nArg
; i
++){
1639 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1640 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1642 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1650 ** This is the callback routine that the SQLite library
1651 ** invokes for each row of a query result.
1653 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
1654 /* since we don't have type info, call the shell_callback with a NULL value */
1655 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
1659 ** This is the callback routine from sqlite3_exec() that appends all
1660 ** output onto the end of a ShellText object.
1662 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
1663 ShellText
*p
= (ShellText
*)pArg
;
1665 UNUSED_PARAMETER(az
);
1666 if( azArg
==0 ) return 0;
1667 if( p
->n
) appendText(p
, "|", 0);
1668 for(i
=0; i
<nArg
; i
++){
1669 if( i
) appendText(p
, ",", 0);
1670 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
1676 ** Generate an appropriate SELFTEST table in the main database.
1678 static void createSelftestTable(ShellState
*p
){
1681 "SAVEPOINT selftest_init;\n"
1682 "CREATE TABLE IF NOT EXISTS selftest(\n"
1683 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1684 " op TEXT,\n" /* Operator: memo run */
1685 " cmd TEXT,\n" /* Command text */
1686 " ans TEXT\n" /* Desired answer */
1688 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1689 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1690 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1691 " 'memo','Tests generated by --init');\n"
1692 "INSERT INTO [_shell$self]\n"
1694 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1695 "FROM sqlite_master ORDER BY 2'',224))',\n"
1696 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1697 "FROM sqlite_master ORDER BY 2',224));\n"
1698 "INSERT INTO [_shell$self]\n"
1700 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1701 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1702 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1704 " SELECT name FROM sqlite_master\n"
1705 " WHERE type='table'\n"
1706 " AND name<>'selftest'\n"
1707 " AND coalesce(rootpage,0)>0\n"
1710 "INSERT INTO [_shell$self]\n"
1711 " VALUES('run','PRAGMA integrity_check','ok');\n"
1712 "INSERT INTO selftest(tno,op,cmd,ans)"
1713 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1714 "DROP TABLE [_shell$self];"
1717 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
1718 sqlite3_free(zErrMsg
);
1720 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
1725 ** Set the destination table field of the ShellState structure to
1726 ** the name of the table given. Escape any quote characters in the
1729 static void set_table_name(ShellState
*p
, const char *zName
){
1734 if( p
->zDestTable
){
1735 free(p
->zDestTable
);
1738 if( zName
==0 ) return;
1739 cQuote
= quoteChar(zName
);
1740 n
= strlen30(zName
);
1741 if( cQuote
) n
+= n
+2;
1742 z
= p
->zDestTable
= malloc( n
+1 );
1744 raw_printf(stderr
,"Error: out of memory\n");
1748 if( cQuote
) z
[n
++] = cQuote
;
1749 for(i
=0; zName
[i
]; i
++){
1751 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
1753 if( cQuote
) z
[n
++] = cQuote
;
1759 ** Execute a query statement that will generate SQL output. Print
1760 ** the result columns, comma-separated, on a line and then add a
1761 ** semicolon terminator to the end of that line.
1763 ** If the number of columns is 1 and that column contains text "--"
1764 ** then write the semicolon on a separate line. That way, if a
1765 ** "--" comment occurs at the end of the statement, the comment
1766 ** won't consume the semicolon terminator.
1768 static int run_table_dump_query(
1769 ShellState
*p
, /* Query context */
1770 const char *zSelect
, /* SELECT statement to extract content */
1771 const char *zFirstRow
/* Print before first row, if not NULL */
1773 sqlite3_stmt
*pSelect
;
1778 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
1779 if( rc
!=SQLITE_OK
|| !pSelect
){
1780 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
1781 sqlite3_errmsg(p
->db
));
1782 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
1785 rc
= sqlite3_step(pSelect
);
1786 nResult
= sqlite3_column_count(pSelect
);
1787 while( rc
==SQLITE_ROW
){
1789 utf8_printf(p
->out
, "%s", zFirstRow
);
1792 z
= (const char*)sqlite3_column_text(pSelect
, 0);
1793 utf8_printf(p
->out
, "%s", z
);
1794 for(i
=1; i
<nResult
; i
++){
1795 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
1798 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
1800 raw_printf(p
->out
, "\n;\n");
1802 raw_printf(p
->out
, ";\n");
1804 rc
= sqlite3_step(pSelect
);
1806 rc
= sqlite3_finalize(pSelect
);
1807 if( rc
!=SQLITE_OK
){
1808 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
1809 sqlite3_errmsg(p
->db
));
1810 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
1816 ** Allocate space and save off current error string.
1818 static char *save_err_msg(
1819 sqlite3
*db
/* Database to query */
1821 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
1822 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
1824 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
1831 ** Attempt to display I/O stats on Linux using /proc/PID/io
1833 static void displayLinuxIoStats(FILE *out
){
1836 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
1837 in
= fopen(z
, "rb");
1839 while( fgets(z
, sizeof(z
), in
)!=0 ){
1840 static const struct {
1841 const char *zPattern
;
1844 { "rchar: ", "Bytes received by read():" },
1845 { "wchar: ", "Bytes sent to write():" },
1846 { "syscr: ", "Read() system calls:" },
1847 { "syscw: ", "Write() system calls:" },
1848 { "read_bytes: ", "Bytes read from storage:" },
1849 { "write_bytes: ", "Bytes written to storage:" },
1850 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1853 for(i
=0; i
<ArraySize(aTrans
); i
++){
1854 int n
= (int)strlen(aTrans
[i
].zPattern
);
1855 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
1856 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
1866 ** Display a single line of status using 64-bit values.
1868 static void displayStatLine(
1869 ShellState
*p
, /* The shell context */
1870 char *zLabel
, /* Label for this one line */
1871 char *zFormat
, /* Format for the result */
1872 int iStatusCtrl
, /* Which status to display */
1873 int bReset
/* True to reset the stats */
1875 sqlite3_int64 iCur
= -1;
1876 sqlite3_int64 iHiwtr
= -1;
1879 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
1880 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
1881 if( zFormat
[i
]=='%' ) nPercent
++;
1884 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
1886 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
1888 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
1892 ** Display memory stats.
1894 static int display_stats(
1895 sqlite3
*db
, /* Database to query */
1896 ShellState
*pArg
, /* Pointer to ShellState */
1897 int bReset
/* True to reset the stats */
1902 if( pArg
&& pArg
->out
){
1903 displayStatLine(pArg
, "Memory Used:",
1904 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
1905 displayStatLine(pArg
, "Number of Outstanding Allocations:",
1906 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
1907 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
1908 displayStatLine(pArg
, "Number of Pcache Pages Used:",
1909 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
1911 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
1912 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
1913 displayStatLine(pArg
, "Largest Allocation:",
1914 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
1915 displayStatLine(pArg
, "Largest Pcache Allocation:",
1916 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
1917 #ifdef YYTRACKMAXSTACKDEPTH
1918 displayStatLine(pArg
, "Deepest Parser Stack:",
1919 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
1923 if( pArg
&& pArg
->out
&& db
){
1924 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
1926 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
1927 &iCur
, &iHiwtr
, bReset
);
1928 raw_printf(pArg
->out
,
1929 "Lookaside Slots Used: %d (max %d)\n",
1931 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
1932 &iCur
, &iHiwtr
, bReset
);
1933 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
1935 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
1936 &iCur
, &iHiwtr
, bReset
);
1937 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
1939 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
1940 &iCur
, &iHiwtr
, bReset
);
1941 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
1945 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
1946 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
1949 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
1950 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
1952 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
1953 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
1955 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
1956 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
1958 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
1959 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
1962 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
1963 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
1967 if( pArg
&& pArg
->out
&& db
&& pArg
->pStmt
){
1968 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
1970 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
1971 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
1972 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
1973 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
1974 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
1975 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
1976 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
1980 displayLinuxIoStats(pArg
->out
);
1983 /* Do not remove this machine readable comment: extra-stats-output-here */
1989 ** Display scan stats.
1991 static void display_scanstats(
1992 sqlite3
*db
, /* Database to query */
1993 ShellState
*pArg
/* Pointer to ShellState */
1995 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
1996 UNUSED_PARAMETER(db
);
1997 UNUSED_PARAMETER(pArg
);
2000 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2002 for(k
=0; k
<=mx
; k
++){
2003 double rEstLoop
= 1.0;
2005 sqlite3_stmt
*p
= pArg
->pStmt
;
2006 sqlite3_int64 nLoop
, nVisit
;
2009 const char *zExplain
;
2010 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2013 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2014 if( iSid
>mx
) mx
= iSid
;
2015 if( iSid
!=k
) continue;
2017 rEstLoop
= (double)nLoop
;
2018 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2021 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2022 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2023 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2024 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2026 raw_printf(pArg
->out
,
2027 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2028 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2032 raw_printf(pArg
->out
, "---------------------------\n");
2037 ** Parameter azArray points to a zero-terminated array of strings. zStr
2038 ** points to a single nul-terminated string. Return non-zero if zStr
2039 ** is equal, according to strcmp(), to any of the strings in the array.
2040 ** Otherwise, return zero.
2042 static int str_in_array(const char *zStr
, const char **azArray
){
2044 for(i
=0; azArray
[i
]; i
++){
2045 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2051 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2052 ** and populate the ShellState.aiIndent[] array with the number of
2053 ** spaces each opcode should be indented before it is output.
2055 ** The indenting rules are:
2057 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2058 ** all opcodes that occur between the p2 jump destination and the opcode
2059 ** itself by 2 spaces.
2061 ** * For each "Goto", if the jump destination is earlier in the program
2062 ** and ends on one of:
2063 ** Yield SeekGt SeekLt RowSetRead Rewind
2064 ** or if the P1 parameter is one instead of zero,
2065 ** then indent all opcodes between the earlier instruction
2066 ** and "Goto" by 2 spaces.
2068 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2069 const char *zSql
; /* The text of the SQL statement */
2070 const char *z
; /* Used to check if this is an EXPLAIN */
2071 int *abYield
= 0; /* True if op is an OP_Yield */
2072 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2073 int iOp
; /* Index of operation in p->aiIndent[] */
2075 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2076 "NextIfOpen", "PrevIfOpen", 0 };
2077 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2079 const char *azGoto
[] = { "Goto", 0 };
2081 /* Try to figure out if this is really an EXPLAIN statement. If this
2082 ** cannot be verified, return early. */
2083 if( sqlite3_column_count(pSql
)!=8 ){
2087 zSql
= sqlite3_sql(pSql
);
2088 if( zSql
==0 ) return;
2089 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2090 if( sqlite3_strnicmp(z
, "explain", 7) ){
2095 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2097 int iAddr
= sqlite3_column_int(pSql
, 0);
2098 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2100 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2101 ** p2 is an instruction address, set variable p2op to the index of that
2102 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2103 ** the current instruction is part of a sub-program generated by an
2104 ** SQL trigger or foreign key. */
2105 int p2
= sqlite3_column_int(pSql
, 3);
2106 int p2op
= (p2
+ (iOp
-iAddr
));
2108 /* Grow the p->aiIndent array as required */
2111 /* Do further verfication that this is explain output. Abort if
2113 static const char *explainCols
[] = {
2114 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2116 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2117 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2119 sqlite3_reset(pSql
);
2125 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2126 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2128 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2129 p
->aiIndent
[iOp
] = 0;
2132 if( str_in_array(zOp
, azNext
) ){
2133 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2135 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2136 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2138 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2143 sqlite3_free(abYield
);
2144 sqlite3_reset(pSql
);
2148 ** Free the array allocated by explain_data_prepare().
2150 static void explain_data_delete(ShellState
*p
){
2151 sqlite3_free(p
->aiIndent
);
2158 ** Disable and restore .wheretrace and .selecttrace settings.
2160 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2161 extern int sqlite3SelectTrace
;
2162 static int savedSelectTrace
;
2164 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2165 extern int sqlite3WhereTrace
;
2166 static int savedWhereTrace
;
2168 static void disable_debug_trace_modes(void){
2169 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2170 savedSelectTrace
= sqlite3SelectTrace
;
2171 sqlite3SelectTrace
= 0;
2173 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2174 savedWhereTrace
= sqlite3WhereTrace
;
2175 sqlite3WhereTrace
= 0;
2178 static void restore_debug_trace_modes(void){
2179 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2180 sqlite3SelectTrace
= savedSelectTrace
;
2182 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2183 sqlite3WhereTrace
= savedWhereTrace
;
2188 ** Run a prepared statement
2190 static void exec_prepared_stmt(
2191 ShellState
*pArg
, /* Pointer to ShellState */
2192 sqlite3_stmt
*pStmt
, /* Statment to run */
2193 int (*xCallback
)(void*,int,char**,char**,int*) /* Callback function */
2197 /* perform the first step. this will tell us if we
2198 ** have a result set or not and how wide it is.
2200 rc
= sqlite3_step(pStmt
);
2201 /* if we have a result set... */
2202 if( SQLITE_ROW
== rc
){
2203 /* if we have a callback... */
2205 /* allocate space for col name ptr, value ptr, and type */
2206 int nCol
= sqlite3_column_count(pStmt
);
2207 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2211 char **azCols
= (char **)pData
; /* Names of result columns */
2212 char **azVals
= &azCols
[nCol
]; /* Results */
2213 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2215 assert(sizeof(int) <= sizeof(char *));
2216 /* save off ptrs to column names */
2217 for(i
=0; i
<nCol
; i
++){
2218 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2221 /* extract the data and data types */
2222 for(i
=0; i
<nCol
; i
++){
2223 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2224 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2227 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2229 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2231 break; /* from for */
2235 /* if data and types extracted successfully... */
2236 if( SQLITE_ROW
== rc
){
2237 /* call the supplied callback with the result row data */
2238 if( xCallback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2241 rc
= sqlite3_step(pStmt
);
2244 } while( SQLITE_ROW
== rc
);
2245 sqlite3_free(pData
);
2249 rc
= sqlite3_step(pStmt
);
2250 } while( rc
== SQLITE_ROW
);
2256 ** Execute a statement or set of statements. Print
2257 ** any result rows/columns depending on the current mode
2258 ** set via the supplied callback.
2260 ** This is very similar to SQLite's built-in sqlite3_exec()
2261 ** function except it takes a slightly different callback
2262 ** and callback data argument.
2264 static int shell_exec(
2265 sqlite3
*db
, /* An open database */
2266 const char *zSql
, /* SQL to be evaluated */
2267 int (*xCallback
)(void*,int,char**,char**,int*), /* Callback function */
2268 /* (not the same as sqlite3_exec) */
2269 ShellState
*pArg
, /* Pointer to ShellState */
2270 char **pzErrMsg
/* Error msg written here */
2272 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2273 int rc
= SQLITE_OK
; /* Return Code */
2275 const char *zLeftover
; /* Tail of unprocessed SQL */
2281 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2282 static const char *zStmtSql
;
2283 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2284 if( SQLITE_OK
!= rc
){
2286 *pzErrMsg
= save_err_msg(db
);
2290 /* this happens for a comment or white-space */
2292 while( IsSpace(zSql
[0]) ) zSql
++;
2295 zStmtSql
= sqlite3_sql(pStmt
);
2296 if( zStmtSql
==0 ) zStmtSql
= "";
2297 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2299 /* save off the prepared statment handle and reset row count */
2301 pArg
->pStmt
= pStmt
;
2305 /* echo the sql statement if echo on */
2306 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2307 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2310 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2311 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2312 sqlite3_stmt
*pExplain
;
2314 disable_debug_trace_modes();
2315 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2316 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2317 if( rc
==SQLITE_OK
){
2318 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2319 raw_printf(pArg
->out
,"--EQP-- %d,",sqlite3_column_int(pExplain
, 0));
2320 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 1));
2321 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 2));
2322 utf8_printf(pArg
->out
,"%s\n", sqlite3_column_text(pExplain
, 3));
2325 sqlite3_finalize(pExplain
);
2327 if( pArg
->autoEQP
>=2 ){
2328 /* Also do an EXPLAIN for ".eqp full" mode */
2329 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2330 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2331 if( rc
==SQLITE_OK
){
2332 pArg
->cMode
= MODE_Explain
;
2333 explain_data_prepare(pArg
, pExplain
);
2334 exec_prepared_stmt(pArg
, pExplain
, xCallback
);
2335 explain_data_delete(pArg
);
2337 sqlite3_finalize(pExplain
);
2340 restore_debug_trace_modes();
2344 pArg
->cMode
= pArg
->mode
;
2345 if( pArg
->autoExplain
2346 && sqlite3_column_count(pStmt
)==8
2347 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
2349 pArg
->cMode
= MODE_Explain
;
2352 /* If the shell is currently in ".explain" mode, gather the extra
2353 ** data required to add indents to the output.*/
2354 if( pArg
->cMode
==MODE_Explain
){
2355 explain_data_prepare(pArg
, pStmt
);
2359 exec_prepared_stmt(pArg
, pStmt
, xCallback
);
2360 explain_data_delete(pArg
);
2362 /* print usage stats if stats on */
2363 if( pArg
&& pArg
->statsOn
){
2364 display_stats(db
, pArg
, 0);
2367 /* print loop-counters if required */
2368 if( pArg
&& pArg
->scanstatsOn
){
2369 display_scanstats(db
, pArg
);
2372 /* Finalize the statement just executed. If this fails, save a
2373 ** copy of the error message. Otherwise, set zSql to point to the
2374 ** next statement to execute. */
2375 rc2
= sqlite3_finalize(pStmt
);
2376 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
2377 if( rc
==SQLITE_OK
){
2379 while( IsSpace(zSql
[0]) ) zSql
++;
2380 }else if( pzErrMsg
){
2381 *pzErrMsg
= save_err_msg(db
);
2384 /* clear saved stmt handle */
2395 ** Release memory previously allocated by tableColumnList().
2397 static void freeColumnList(char **azCol
){
2399 for(i
=1; azCol
[i
]; i
++){
2400 sqlite3_free(azCol
[i
]);
2402 /* azCol[0] is a static string */
2403 sqlite3_free(azCol
);
2407 ** Return a list of pointers to strings which are the names of all
2408 ** columns in table zTab. The memory to hold the names is dynamically
2409 ** allocated and must be released by the caller using a subsequent call
2410 ** to freeColumnList().
2412 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2413 ** value that needs to be preserved, then azCol[0] is filled in with the
2414 ** name of the rowid column.
2416 ** The first regular column in the table is azCol[1]. The list is terminated
2417 ** by an entry with azCol[i]==0.
2419 static char **tableColumnList(ShellState
*p
, const char *zTab
){
2421 sqlite3_stmt
*pStmt
;
2425 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
2426 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
2427 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
2430 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
2431 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2434 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2435 if( nCol
>=nAlloc
-2 ){
2436 nAlloc
= nAlloc
*2 + nCol
+ 10;
2437 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
2439 raw_printf(stderr
, "Error: out of memory\n");
2443 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
2444 if( sqlite3_column_int(pStmt
, 5) ){
2447 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
2456 sqlite3_finalize(pStmt
);
2457 if( azCol
==0 ) return 0;
2461 /* The decision of whether or not a rowid really needs to be preserved
2462 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2463 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2464 ** rowids on tables where the rowid is inaccessible because there are other
2465 ** columns in the table named "rowid", "_rowid_", and "oid".
2467 if( preserveRowid
&& isIPK
){
2468 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2469 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2470 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2471 ** ROWID aliases. To distinguish these cases, check to see if
2472 ** there is a "pk" entry in "PRAGMA index_list". There will be
2473 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2475 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2476 " WHERE origin='pk'", zTab
);
2477 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2480 freeColumnList(azCol
);
2483 rc
= sqlite3_step(pStmt
);
2484 sqlite3_finalize(pStmt
);
2485 preserveRowid
= rc
==SQLITE_ROW
;
2487 if( preserveRowid
){
2488 /* Only preserve the rowid if we can find a name to use for the
2490 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
2493 for(i
=1; i
<=nCol
; i
++){
2494 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
2497 /* At this point, we know that azRowid[j] is not the name of any
2498 ** ordinary column in the table. Verify that azRowid[j] is a valid
2499 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2500 ** tables will fail this last check */
2501 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
2502 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
2511 ** Toggle the reverse_unordered_selects setting.
2513 static void toggleSelectOrder(sqlite3
*db
){
2514 sqlite3_stmt
*pStmt
= 0;
2517 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
2518 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
2519 iSetting
= sqlite3_column_int(pStmt
, 0);
2521 sqlite3_finalize(pStmt
);
2522 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
2523 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
2524 sqlite3_exec(db
, zStmt
, 0, 0, 0);
2528 ** This is a different callback routine used for dumping the database.
2529 ** Each row received by this callback consists of a table name,
2530 ** the table type ("index" or "table") and SQL to create the table.
2531 ** This routine should print text sufficient to recreate the table.
2533 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
2538 ShellState
*p
= (ShellState
*)pArg
;
2540 UNUSED_PARAMETER(azNotUsed
);
2541 if( nArg
!=3 || azArg
==0 ) return 0;
2546 if( strcmp(zTable
, "sqlite_sequence")==0 ){
2547 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
2548 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
2549 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
2550 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
2552 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
2554 if( !p
->writableSchema
){
2555 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
2556 p
->writableSchema
= 1;
2558 zIns
= sqlite3_mprintf(
2559 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2560 "VALUES('table','%q','%q',0,'%q');",
2561 zTable
, zTable
, zSql
);
2562 utf8_printf(p
->out
, "%s\n", zIns
);
2566 printSchemaLine(p
->out
, zSql
, ";\n");
2569 if( strcmp(zType
, "table")==0 ){
2574 char *savedDestTable
;
2577 azCol
= tableColumnList(p
, zTable
);
2583 /* Always quote the table name, even if it appears to be pure ascii,
2584 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2586 appendText(&sTable
, zTable
, quoteChar(zTable
));
2587 /* If preserving the rowid, add a column list after the table name.
2588 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2589 ** instead of the usual "INSERT INTO tab VALUES(...)".
2592 appendText(&sTable
, "(", 0);
2593 appendText(&sTable
, azCol
[0], 0);
2594 for(i
=1; azCol
[i
]; i
++){
2595 appendText(&sTable
, ",", 0);
2596 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
2598 appendText(&sTable
, ")", 0);
2601 /* Build an appropriate SELECT statement */
2603 appendText(&sSelect
, "SELECT ", 0);
2605 appendText(&sSelect
, azCol
[0], 0);
2606 appendText(&sSelect
, ",", 0);
2608 for(i
=1; azCol
[i
]; i
++){
2609 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
2611 appendText(&sSelect
, ",", 0);
2614 freeColumnList(azCol
);
2615 appendText(&sSelect
, " FROM ", 0);
2616 appendText(&sSelect
, zTable
, quoteChar(zTable
));
2618 savedDestTable
= p
->zDestTable
;
2619 savedMode
= p
->mode
;
2620 p
->zDestTable
= sTable
.z
;
2621 p
->mode
= p
->cMode
= MODE_Insert
;
2622 rc
= shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
2623 if( (rc
&0xff)==SQLITE_CORRUPT
){
2624 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
2625 toggleSelectOrder(p
->db
);
2626 shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
2627 toggleSelectOrder(p
->db
);
2629 p
->zDestTable
= savedDestTable
;
2630 p
->mode
= savedMode
;
2639 ** Run zQuery. Use dump_callback() as the callback routine so that
2640 ** the contents of the query are output as SQL statements.
2642 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
2643 ** "ORDER BY rowid DESC" to the end.
2645 static int run_schema_dump_query(
2651 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
2652 if( rc
==SQLITE_CORRUPT
){
2654 int len
= strlen30(zQuery
);
2655 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
2657 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
2661 zQ2
= malloc( len
+100 );
2662 if( zQ2
==0 ) return rc
;
2663 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
2664 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
2666 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
2668 rc
= SQLITE_CORRUPT
;
2677 ** Text of a help message
2679 static char zHelp
[] =
2680 #ifndef SQLITE_OMIT_AUTHORIZATION
2681 ".auth ON|OFF Show authorizer callbacks\n"
2683 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2684 ".bail on|off Stop after hitting an error. Default OFF\n"
2685 ".binary on|off Turn binary output on or off. Default OFF\n"
2686 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
2687 ".changes on|off Show number of rows changed by SQL\n"
2688 ".check GLOB Fail if output since .testcase does not match\n"
2689 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2690 ".databases List names and files of attached databases\n"
2691 ".dbinfo ?DB? Show status information about the database\n"
2692 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2693 " If TABLE specified, only dump tables matching\n"
2694 " LIKE pattern TABLE.\n"
2695 ".echo on|off Turn command echo on or off\n"
2696 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2697 ".exit Exit this program\n"
2698 /* Because explain mode comes on automatically now, the ".explain" mode
2699 ** is removed from the help screen. It is still supported for legacy, however */
2700 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2701 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2702 ".headers on|off Turn display of headers on or off\n"
2703 ".help Show this message\n"
2704 ".import FILE TABLE Import data from FILE into TABLE\n"
2705 #ifndef SQLITE_OMIT_TEST_CONTROL
2706 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
2708 ".indexes ?TABLE? Show names of all indexes\n"
2709 " If TABLE specified, only show indexes for tables\n"
2710 " matching LIKE pattern TABLE.\n"
2711 #ifdef SQLITE_ENABLE_IOTRACE
2712 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2714 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2715 ".lint OPTIONS Report potential schema issues. Options:\n"
2716 " fkey-indexes Find missing foreign key indexes\n"
2717 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2718 ".load FILE ?ENTRY? Load an extension library\n"
2720 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2721 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2722 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2723 " csv Comma-separated values\n"
2724 " column Left-aligned columns. (See .width)\n"
2725 " html HTML <table> code\n"
2726 " insert SQL insert statements for TABLE\n"
2727 " line One value per line\n"
2728 " list Values delimited by \"|\"\n"
2729 " quote Escape answers as for SQL\n"
2730 " tabs Tab-separated values\n"
2731 " tcl TCL list elements\n"
2732 ".nullvalue STRING Use STRING in place of NULL values\n"
2733 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2734 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2735 " The --new option starts with an empty file\n"
2736 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2737 ".print STRING... Print literal STRING\n"
2738 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2739 ".quit Exit this program\n"
2740 ".read FILENAME Execute SQL in FILENAME\n"
2741 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2742 ".save FILE Write in-memory database into FILE\n"
2743 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2744 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2745 " Add --indent for pretty-printing\n"
2746 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
2747 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2748 " separator for both the output mode and .import\n"
2749 #if defined(SQLITE_ENABLE_SESSION)
2750 ".session CMD ... Create or control sessions\n"
2752 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
2753 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2754 ".show Show the current values for various settings\n"
2755 ".stats ?on|off? Show stats or turn stats on or off\n"
2756 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2757 ".tables ?TABLE? List names of tables\n"
2758 " If TABLE specified, only list tables matching\n"
2759 " LIKE pattern TABLE.\n"
2760 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2761 ".timeout MS Try opening locked tables for MS milliseconds\n"
2762 ".timer on|off Turn SQL timer on or off\n"
2763 ".trace FILE|off Output each SQL statement as it is run\n"
2764 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2765 ".vfslist List all available VFSes\n"
2766 ".vfsname ?AUX? Print the name of the VFS stack\n"
2767 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2768 " Negative values right-justify\n"
2771 #if defined(SQLITE_ENABLE_SESSION)
2773 ** Print help information for the ".sessions" command
2775 void session_help(ShellState
*p
){
2777 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2778 "If ?NAME? is omitted, the first defined session is used.\n"
2780 " attach TABLE Attach TABLE\n"
2781 " changeset FILE Write a changeset into FILE\n"
2782 " close Close one session\n"
2783 " enable ?BOOLEAN? Set or query the enable bit\n"
2784 " filter GLOB... Reject tables matching GLOBs\n"
2785 " indirect ?BOOLEAN? Mark or query the indirect status\n"
2786 " isempty Query whether the session is empty\n"
2787 " list List currently open session names\n"
2788 " open DB NAME Open a new session on DB\n"
2789 " patchset FILE Write a patchset into FILE\n"
2795 /* Forward reference */
2796 static int process_input(ShellState
*p
, FILE *in
);
2799 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
2800 ** and return a pointer to the buffer. The caller is responsible for freeing
2803 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
2806 ** For convenience, a nul-terminator byte is always appended to the data read
2807 ** from the file before the buffer is returned. This byte is not included in
2808 ** the final value of (*pnByte), if applicable.
2810 ** NULL is returned if any error is encountered. The final value of *pnByte
2811 ** is undefined in this case.
2813 static char *readFile(const char *zName
, int *pnByte
){
2814 FILE *in
= fopen(zName
, "rb");
2818 if( in
==0 ) return 0;
2819 fseek(in
, 0, SEEK_END
);
2822 pBuf
= sqlite3_malloc64( nIn
+1 );
2823 if( pBuf
==0 ) return 0;
2824 nRead
= fread(pBuf
, nIn
, 1, in
);
2831 if( pnByte
) *pnByte
= nIn
;
2835 #if defined(SQLITE_ENABLE_SESSION)
2837 ** Close a single OpenSession object and release all of its associated
2840 static void session_close(OpenSession
*pSession
){
2842 sqlite3session_delete(pSession
->p
);
2843 sqlite3_free(pSession
->zName
);
2844 for(i
=0; i
<pSession
->nFilter
; i
++){
2845 sqlite3_free(pSession
->azFilter
[i
]);
2847 sqlite3_free(pSession
->azFilter
);
2848 memset(pSession
, 0, sizeof(OpenSession
));
2853 ** Close all OpenSession objects and release all associated resources.
2855 #if defined(SQLITE_ENABLE_SESSION)
2856 static void session_close_all(ShellState
*p
){
2858 for(i
=0; i
<p
->nSession
; i
++){
2859 session_close(&p
->aSession
[i
]);
2864 # define session_close_all(X)
2868 ** Implementation of the xFilter function for an open session. Omit
2869 ** any tables named by ".session filter" but let all other table through.
2871 #if defined(SQLITE_ENABLE_SESSION)
2872 static int session_filter(void *pCtx
, const char *zTab
){
2873 OpenSession
*pSession
= (OpenSession
*)pCtx
;
2875 for(i
=0; i
<pSession
->nFilter
; i
++){
2876 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
2883 ** Make sure the database is open. If it is not, then open it. If
2884 ** the database fails to open, print an error message and exit.
2886 static void open_db(ShellState
*p
, int keepAlive
){
2888 sqlite3_initialize();
2889 sqlite3_open(p
->zDbFilename
, &p
->db
);
2891 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
2892 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
2893 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
2894 if( keepAlive
) return;
2897 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2898 sqlite3_enable_load_extension(p
->db
, 1);
2900 sqlite3_fileio_init(p
->db
, 0, 0);
2901 sqlite3_shathree_init(p
->db
, 0, 0);
2902 sqlite3_completion_init(p
->db
, 0, 0);
2903 sqlite3_create_function(p
->db
, "shell_add_schema", 2, SQLITE_UTF8
, 0,
2904 shellAddSchemaName
, 0, 0);
2908 #if HAVE_READLINE || HAVE_EDITLINE
2910 ** Readline completion callbacks
2912 static char *readline_completion_generator(const char *text
, int state
){
2913 static sqlite3_stmt
*pStmt
= 0;
2917 sqlite3_finalize(pStmt
);
2918 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
2919 " FROM completion(%Q) ORDER BY 1", text
);
2920 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
2923 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
2924 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
2926 sqlite3_finalize(pStmt
);
2932 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
2933 rl_attempted_completion_over
= 1;
2934 return rl_completion_matches(zText
, readline_completion_generator
);
2937 #elif HAVE_LINENOISE
2939 ** Linenoise completion callback
2941 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
2942 int nLine
= (int)strlen(zLine
);
2944 sqlite3_stmt
*pStmt
= 0;
2948 if( nLine
>sizeof(zBuf
)-30 ) return;
2949 if( zLine
[0]=='.' ) return;
2950 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
2951 if( i
==nLine
-1 ) return;
2953 memcpy(zBuf
, zLine
, iStart
);
2954 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
2955 " FROM completion(%Q,%Q) ORDER BY 1",
2956 &zLine
[iStart
], zLine
);
2957 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
2959 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
2960 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2961 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
2962 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
2963 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
2964 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
2965 linenoiseAddCompletion(lc
, zBuf
);
2968 sqlite3_finalize(pStmt
);
2973 ** Do C-language style dequoting.
2979 ** \v -> vertical tab
2981 ** \r -> carriage return
2986 ** \NNN -> ascii character NNN in octal
2988 static void resolve_backslashes(char *z
){
2991 while( *z
&& *z
!='\\' ) z
++;
2992 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
2993 if( c
=='\\' && z
[i
+1]!=0 ){
3011 }else if( c
=='\'' ){
3013 }else if( c
=='\\' ){
3015 }else if( c
>='0' && c
<='7' ){
3017 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3019 c
= (c
<<3) + z
[i
] - '0';
3020 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3022 c
= (c
<<3) + z
[i
] - '0';
3033 ** Return the value of a hexadecimal digit. Return -1 if the input
3034 ** is not a hex digit.
3036 static int hexDigitValue(char c
){
3037 if( c
>='0' && c
<='9' ) return c
- '0';
3038 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
3039 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
3044 ** Interpret zArg as an integer value, possibly with suffixes.
3046 static sqlite3_int64
integerValue(const char *zArg
){
3047 sqlite3_int64 v
= 0;
3048 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
3050 { "MiB", 1024*1024 },
3051 { "GiB", 1024*1024*1024 },
3054 { "GB", 1000000000 },
3057 { "G", 1000000000 },
3064 }else if( zArg
[0]=='+' ){
3067 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3070 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
3075 while( IsDigit(zArg
[0]) ){
3076 v
= v
*10 + zArg
[0] - '0';
3080 for(i
=0; i
<ArraySize(aMult
); i
++){
3081 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
3082 v
*= aMult
[i
].iMult
;
3086 return isNeg
? -v
: v
;
3090 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3091 ** for TRUE and FALSE. Return the integer value if appropriate.
3093 static int booleanValue(const char *zArg
){
3095 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3096 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3098 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3100 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3101 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3104 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3107 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3113 ** Set or clear a shell flag according to a boolean value.
3115 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3116 if( booleanValue(zArg
) ){
3117 ShellSetFlag(p
, mFlag
);
3119 ShellClearFlag(p
, mFlag
);
3124 ** Close an output file, assuming it is not stderr or stdout
3126 static void output_file_close(FILE *f
){
3127 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3131 ** Try to open an output file. The names "stdout" and "stderr" are
3132 ** recognized and do the right thing. NULL is returned if the output
3133 ** filename is "off".
3135 static FILE *output_file_open(const char *zFile
){
3137 if( strcmp(zFile
,"stdout")==0 ){
3139 }else if( strcmp(zFile
, "stderr")==0 ){
3141 }else if( strcmp(zFile
, "off")==0 ){
3144 f
= fopen(zFile
, "wb");
3146 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3152 #if !defined(SQLITE_UNTESTABLE)
3153 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3155 ** A routine for handling output from sqlite3_trace().
3157 static int sql_trace_callback(
3163 FILE *f
= (FILE*)pArg
;
3164 UNUSED_PARAMETER(mType
);
3165 UNUSED_PARAMETER(pP
);
3167 const char *z
= (const char*)pX
;
3168 int i
= (int)strlen(z
);
3169 while( i
>0 && z
[i
-1]==';' ){ i
--; }
3170 utf8_printf(f
, "%.*s;\n", i
, z
);
3178 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3179 ** a useful spot to set a debugger breakpoint.
3181 static void test_breakpoint(void){
3182 static int nCall
= 0;
3187 ** An object used to read a CSV and other files for import.
3189 typedef struct ImportCtx ImportCtx
;
3191 const char *zFile
; /* Name of the input file */
3192 FILE *in
; /* Read the CSV text from this input stream */
3193 char *z
; /* Accumulated text for a field */
3194 int n
; /* Number of bytes in z */
3195 int nAlloc
; /* Space allocated for z[] */
3196 int nLine
; /* Current line number */
3197 int bNotFirst
; /* True if one or more bytes already read */
3198 int cTerm
; /* Character that terminated the most recent field */
3199 int cColSep
; /* The column separator character. (Usually ",") */
3200 int cRowSep
; /* The row separator character. (Usually "\n") */
3203 /* Append a single byte to z[] */
3204 static void import_append_char(ImportCtx
*p
, int c
){
3205 if( p
->n
+1>=p
->nAlloc
){
3206 p
->nAlloc
+= p
->nAlloc
+ 100;
3207 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
3209 raw_printf(stderr
, "out of memory\n");
3213 p
->z
[p
->n
++] = (char)c
;
3216 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3217 ** with the option of having a separator other than ",".
3219 ** + Input comes from p->in.
3220 ** + Store results in p->z of length p->n. Space to hold p->z comes
3221 ** from sqlite3_malloc64().
3222 ** + Use p->cSep as the column separator. The default is ",".
3223 ** + Use p->rSep as the row separator. The default is "\n".
3224 ** + Keep track of the line number in p->nLine.
3225 ** + Store the character that terminates the field in p->cTerm. Store
3226 ** EOF on end-of-file.
3227 ** + Report syntax errors on stderr
3229 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
3231 int cSep
= p
->cColSep
;
3232 int rSep
= p
->cRowSep
;
3235 if( c
==EOF
|| seenInterrupt
){
3241 int startLine
= p
->nLine
;
3246 if( c
==rSep
) p
->nLine
++;
3253 if( (c
==cSep
&& pc
==cQuote
)
3254 || (c
==rSep
&& pc
==cQuote
)
3255 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
3256 || (c
==EOF
&& pc
==cQuote
)
3258 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
3262 if( pc
==cQuote
&& c
!='\r' ){
3263 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
3264 p
->zFile
, p
->nLine
, cQuote
);
3267 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
3268 p
->zFile
, startLine
, cQuote
);
3272 import_append_char(p
, c
);
3277 /* If this is the first field being parsed and it begins with the
3278 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3279 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
3280 import_append_char(p
, c
);
3282 if( (c
&0xff)==0xbb ){
3283 import_append_char(p
, c
);
3285 if( (c
&0xff)==0xbf ){
3288 return csv_read_one_field(p
);
3292 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3293 import_append_char(p
, c
);
3298 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
3302 if( p
->z
) p
->z
[p
->n
] = 0;
3307 /* Read a single field of ASCII delimited text.
3309 ** + Input comes from p->in.
3310 ** + Store results in p->z of length p->n. Space to hold p->z comes
3311 ** from sqlite3_malloc64().
3312 ** + Use p->cSep as the column separator. The default is "\x1F".
3313 ** + Use p->rSep as the row separator. The default is "\x1E".
3314 ** + Keep track of the row number in p->nLine.
3315 ** + Store the character that terminates the field in p->cTerm. Store
3316 ** EOF on end-of-file.
3317 ** + Report syntax errors on stderr
3319 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
3321 int cSep
= p
->cColSep
;
3322 int rSep
= p
->cRowSep
;
3325 if( c
==EOF
|| seenInterrupt
){
3329 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3330 import_append_char(p
, c
);
3337 if( p
->z
) p
->z
[p
->n
] = 0;
3342 ** Try to transfer data for table zTable. If an error is seen while
3343 ** moving forward, try to go backwards. The backwards movement won't
3344 ** work for WITHOUT ROWID tables.
3346 static void tryToCloneData(
3351 sqlite3_stmt
*pQuery
= 0;
3352 sqlite3_stmt
*pInsert
= 0;
3357 int nTable
= (int)strlen(zTable
);
3360 const int spinRate
= 10000;
3362 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
3363 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3365 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3366 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3370 n
= sqlite3_column_count(pQuery
);
3371 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
3373 raw_printf(stderr
, "out of memory\n");
3376 sqlite3_snprintf(200+nTable
,zInsert
,
3377 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
3378 i
= (int)strlen(zInsert
);
3380 memcpy(zInsert
+i
, ",?", 2);
3383 memcpy(zInsert
+i
, ");", 3);
3384 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
3386 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3387 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
3392 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3394 switch( sqlite3_column_type(pQuery
, i
) ){
3396 sqlite3_bind_null(pInsert
, i
+1);
3399 case SQLITE_INTEGER
: {
3400 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
3403 case SQLITE_FLOAT
: {
3404 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
3408 sqlite3_bind_text(pInsert
, i
+1,
3409 (const char*)sqlite3_column_text(pQuery
,i
),
3414 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
3415 sqlite3_column_bytes(pQuery
,i
),
3421 rc
= sqlite3_step(pInsert
);
3422 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
3423 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
3424 sqlite3_errmsg(newDb
));
3426 sqlite3_reset(pInsert
);
3428 if( (cnt
%spinRate
)==0 ){
3429 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
3433 if( rc
==SQLITE_DONE
) break;
3434 sqlite3_finalize(pQuery
);
3435 sqlite3_free(zQuery
);
3436 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3438 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3440 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
3443 } /* End for(k=0...) */
3446 sqlite3_finalize(pQuery
);
3447 sqlite3_finalize(pInsert
);
3448 sqlite3_free(zQuery
);
3449 sqlite3_free(zInsert
);
3454 ** Try to transfer all rows of the schema that match zWhere. For
3455 ** each row, invoke xForEach() on the object defined by that row.
3456 ** If an error is encountered while moving forward through the
3457 ** sqlite_master table, try again moving backwards.
3459 static void tryToCloneSchema(
3463 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
3465 sqlite3_stmt
*pQuery
= 0;
3468 const unsigned char *zName
;
3469 const unsigned char *zSql
;
3472 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3473 " WHERE %s", zWhere
);
3474 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3476 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
3477 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3479 goto end_schema_xfer
;
3481 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3482 zName
= sqlite3_column_text(pQuery
, 0);
3483 zSql
= sqlite3_column_text(pQuery
, 1);
3484 printf("%s... ", zName
); fflush(stdout
);
3485 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
3487 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
3488 sqlite3_free(zErrMsg
);
3492 xForEach(p
, newDb
, (const char*)zName
);
3496 if( rc
!=SQLITE_DONE
){
3497 sqlite3_finalize(pQuery
);
3498 sqlite3_free(zQuery
);
3499 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3500 " WHERE %s ORDER BY rowid DESC", zWhere
);
3501 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3503 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
3504 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3506 goto end_schema_xfer
;
3508 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3509 zName
= sqlite3_column_text(pQuery
, 0);
3510 zSql
= sqlite3_column_text(pQuery
, 1);
3511 printf("%s... ", zName
); fflush(stdout
);
3512 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
3514 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
3515 sqlite3_free(zErrMsg
);
3519 xForEach(p
, newDb
, (const char*)zName
);
3525 sqlite3_finalize(pQuery
);
3526 sqlite3_free(zQuery
);
3530 ** Open a new database file named "zNewDb". Try to recover as much information
3531 ** as possible out of the main database (which might be corrupt) and write it
3534 static void tryToClone(ShellState
*p
, const char *zNewDb
){
3537 if( access(zNewDb
,0)==0 ){
3538 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
3541 rc
= sqlite3_open(zNewDb
, &newDb
);
3543 utf8_printf(stderr
, "Cannot create output database: %s\n",
3544 sqlite3_errmsg(newDb
));
3546 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
3547 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
3548 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
3549 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
3550 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
3551 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3553 sqlite3_close(newDb
);
3557 ** Change the output file back to stdout
3559 static void output_reset(ShellState
*p
){
3560 if( p
->outfile
[0]=='|' ){
3561 #ifndef SQLITE_OMIT_POPEN
3565 output_file_close(p
->out
);
3572 ** Run an SQL command and return the single integer result.
3574 static int db_int(ShellState
*p
, const char *zSql
){
3575 sqlite3_stmt
*pStmt
;
3577 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3578 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
3579 res
= sqlite3_column_int(pStmt
,0);
3581 sqlite3_finalize(pStmt
);
3586 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3588 static unsigned int get2byteInt(unsigned char *a
){
3589 return (a
[0]<<8) + a
[1];
3591 static unsigned int get4byteInt(unsigned char *a
){
3592 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
3596 ** Implementation of the ".info" command.
3598 ** Return 1 on error, 2 to exit, and 0 otherwise.
3600 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
3601 static const struct { const char *zName
; int ofst
; } aField
[] = {
3602 { "file change counter:", 24 },
3603 { "database page count:", 28 },
3604 { "freelist page count:", 36 },
3605 { "schema cookie:", 40 },
3606 { "schema format:", 44 },
3607 { "default cache size:", 48 },
3608 { "autovacuum top root:", 52 },
3609 { "incremental vacuum:", 64 },
3610 { "text encoding:", 56 },
3611 { "user version:", 60 },
3612 { "application id:", 68 },
3613 { "software version:", 96 },
3615 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
3616 { "number of tables:",
3617 "SELECT count(*) FROM %s WHERE type='table'" },
3618 { "number of indexes:",
3619 "SELECT count(*) FROM %s WHERE type='index'" },
3620 { "number of triggers:",
3621 "SELECT count(*) FROM %s WHERE type='trigger'" },
3622 { "number of views:",
3623 "SELECT count(*) FROM %s WHERE type='view'" },
3625 "SELECT total(length(sql)) FROM %s" },
3629 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
3630 sqlite3_stmt
*pStmt
= 0;
3631 unsigned char aHdr
[100];
3633 if( p
->db
==0 ) return 1;
3634 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
3636 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
3637 if( sqlite3_step(pStmt
)==SQLITE_ROW
3638 && sqlite3_column_bytes(pStmt
,0)>100
3640 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
3641 sqlite3_finalize(pStmt
);
3643 raw_printf(stderr
, "unable to read database header\n");
3644 sqlite3_finalize(pStmt
);
3647 i
= get2byteInt(aHdr
+16);
3648 if( i
==1 ) i
= 65536;
3649 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
3650 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
3651 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
3652 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
3653 for(i
=0; i
<ArraySize(aField
); i
++){
3654 int ofst
= aField
[i
].ofst
;
3655 unsigned int val
= get4byteInt(aHdr
+ ofst
);
3656 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
3659 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
3660 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
3661 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
3664 raw_printf(p
->out
, "\n");
3667 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
3668 }else if( strcmp(zDb
,"temp")==0 ){
3669 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
3671 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
3673 for(i
=0; i
<ArraySize(aQuery
); i
++){
3674 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
3675 int val
= db_int(p
, zSql
);
3677 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
3679 sqlite3_free(zSchemaTab
);
3684 ** Print the current sqlite3_errmsg() value to stderr and return 1.
3686 static int shellDatabaseError(sqlite3
*db
){
3687 const char *zErr
= sqlite3_errmsg(db
);
3688 utf8_printf(stderr
, "Error: %s\n", zErr
);
3693 ** Print an out-of-memory message to stderr and return 1.
3695 static int shellNomemError(void){
3696 raw_printf(stderr
, "Error: out of memory\n");
3701 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3702 ** if they match and FALSE (0) if they do not match.
3706 ** '*' Matches any sequence of zero or more characters.
3708 ** '?' Matches exactly one character.
3710 ** [...] Matches one character from the enclosed list of
3713 ** [^...] Matches one character not in the enclosed list.
3715 ** '#' Matches any sequence of one or more digits with an
3716 ** optional + or - sign in front
3718 ** ' ' Any span of whitespace matches any other span of
3721 ** Extra whitespace at the end of z[] is ignored.
3723 static int testcase_glob(const char *zGlob
, const char *z
){
3728 while( (c
= (*(zGlob
++)))!=0 ){
3730 if( !IsSpace(*z
) ) return 0;
3731 while( IsSpace(*zGlob
) ) zGlob
++;
3732 while( IsSpace(*z
) ) z
++;
3734 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
3735 if( c
=='?' && (*(z
++))==0 ) return 0;
3740 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
3745 while( (c2
= (*(z
++)))!=0 ){
3748 if( c2
==0 ) return 0;
3750 if( testcase_glob(zGlob
,z
) ) return 1;
3754 if( (*(z
++))==0 ) return 0;
3760 if( c
==0 ) return 0;
3767 if( c
==']' ) seen
= 1;
3770 while( c2
&& c2
!=']' ){
3771 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
3773 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
3783 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
3785 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
3786 if( !IsDigit(z
[0]) ) return 0;
3788 while( IsDigit(z
[0]) ){ z
++; }
3790 if( c
!=(*(z
++)) ) return 0;
3793 while( IsSpace(*z
) ){ z
++; }
3799 ** Compare the string as a command-line option with either one or two
3800 ** initial "-" characters.
3802 static int optionMatch(const char *zStr
, const char *zOpt
){
3803 if( zStr
[0]!='-' ) return 0;
3805 if( zStr
[0]=='-' ) zStr
++;
3806 return strcmp(zStr
, zOpt
)==0;
3812 int shellDeleteFile(const char *zFilename
){
3815 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
3819 rc
= unlink(zFilename
);
3826 ** The implementation of SQL scalar function fkey_collate_clause(), used
3827 ** by the ".lint fkey-indexes" command. This scalar function is always
3828 ** called with four arguments - the parent table name, the parent column name,
3829 ** the child table name and the child column name.
3831 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
3833 ** If either of the named tables or columns do not exist, this function
3834 ** returns an empty string. An empty string is also returned if both tables
3835 ** and columns exist but have the same default collation sequence. Or,
3836 ** if both exist but the default collation sequences are different, this
3837 ** function returns the string " COLLATE <parent-collation>", where
3838 ** <parent-collation> is the default collation sequence of the parent column.
3840 static void shellFkeyCollateClause(
3841 sqlite3_context
*pCtx
,
3843 sqlite3_value
**apVal
3845 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
3846 const char *zParent
;
3847 const char *zParentCol
;
3848 const char *zParentSeq
;
3850 const char *zChildCol
;
3851 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
3855 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
3856 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
3857 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
3858 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
3860 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
3861 rc
= sqlite3_table_column_metadata(
3862 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
3864 if( rc
==SQLITE_OK
){
3865 rc
= sqlite3_table_column_metadata(
3866 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
3870 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
3871 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
3872 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
3879 ** The implementation of dot-command ".lint fkey-indexes".
3881 static int lintFkeyIndexes(
3882 ShellState
*pState
, /* Current shell tool state */
3883 char **azArg
, /* Array of arguments passed to dot command */
3884 int nArg
/* Number of entries in azArg[] */
3886 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
3887 FILE *out
= pState
->out
; /* Stream to write non-error output to */
3888 int bVerbose
= 0; /* If -verbose is present */
3889 int bGroupByParent
= 0; /* If -groupbyparent is present */
3890 int i
; /* To iterate through azArg[] */
3891 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
3892 int rc
; /* Return code */
3893 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
3896 ** This SELECT statement returns one row for each foreign key constraint
3897 ** in the schema of the main database. The column values are:
3899 ** 0. The text of an SQL statement similar to:
3901 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
3903 ** This is the same SELECT that the foreign keys implementation needs
3904 ** to run internally on child tables. If there is an index that can
3905 ** be used to optimize this query, then it can also be used by the FK
3906 ** implementation to optimize DELETE or UPDATE statements on the parent
3909 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
3910 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
3911 ** contains an index that can be used to optimize the query.
3913 ** 2. Human readable text that describes the child table and columns. e.g.
3915 ** "child_table(child_key1, child_key2)"
3917 ** 3. Human readable text that describes the parent table and columns. e.g.
3919 ** "parent_table(parent_key1, parent_key2)"
3921 ** 4. A full CREATE INDEX statement for an index that could be used to
3922 ** optimize DELETE or UPDATE statements on the parent table. e.g.
3924 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
3926 ** 5. The name of the parent table.
3928 ** These six values are used by the C logic below to generate the report.
3932 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
3933 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
3934 " || fkey_collate_clause("
3935 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
3937 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
3938 " || group_concat('*=?', ' AND ') || ')'"
3940 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
3942 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
3944 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
3945 " || ' ON ' || quote(s.name) || '('"
3946 " || group_concat(quote(f.[from]) ||"
3947 " fkey_collate_clause("
3948 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
3952 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
3953 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
3954 "GROUP BY s.name, f.id "
3955 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
3957 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
3959 for(i
=2; i
<nArg
; i
++){
3960 int n
= (int)strlen(azArg
[i
]);
3961 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
3964 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
3969 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
3972 return SQLITE_ERROR
;
3976 /* Register the fkey_collate_clause() SQL function */
3977 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
3978 0, shellFkeyCollateClause
, 0, 0
3982 if( rc
==SQLITE_OK
){
3983 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
3985 if( rc
==SQLITE_OK
){
3986 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
3989 if( rc
==SQLITE_OK
){
3992 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
3994 sqlite3_stmt
*pExplain
= 0;
3995 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
3996 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
3997 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
3998 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
3999 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4000 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4002 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4003 if( rc
!=SQLITE_OK
) break;
4004 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4005 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4007 0==sqlite3_strglob(zGlob
, zPlan
)
4008 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4011 rc
= sqlite3_finalize(pExplain
);
4012 if( rc
!=SQLITE_OK
) break;
4015 raw_printf(stderr
, "Error: internal error");
4019 && (bVerbose
|| res
==0)
4020 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4022 raw_printf(out
, "-- Parent table %s\n", zParent
);
4023 sqlite3_free(zPrev
);
4024 zPrev
= sqlite3_mprintf("%s", zParent
);
4028 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4029 }else if( bVerbose
){
4030 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4031 zIndent
, zFrom
, zTarget
4036 sqlite3_free(zPrev
);
4038 if( rc
!=SQLITE_OK
){
4039 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4042 rc2
= sqlite3_finalize(pSql
);
4043 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4045 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4048 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4055 ** Implementation of ".lint" dot command.
4057 static int lintDotCommand(
4058 ShellState
*pState
, /* Current shell tool state */
4059 char **azArg
, /* Array of arguments passed to dot command */
4060 int nArg
/* Number of entries in azArg[] */
4063 n
= (nArg
>=2 ? (int)strlen(azArg
[1]) : 0);
4064 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4065 return lintFkeyIndexes(pState
, azArg
, nArg
);
4068 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4069 raw_printf(stderr
, "Where sub-commands are:\n");
4070 raw_printf(stderr
, " fkey-indexes\n");
4071 return SQLITE_ERROR
;
4076 ** If an input line begins with "." then invoke this routine to
4077 ** process that line.
4079 ** Return 1 on error, 2 to exit, and 0 otherwise.
4081 static int do_meta_command(char *zLine
, ShellState
*p
){
4088 /* Parse the input line into tokens.
4090 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
4091 while( IsSpace(zLine
[h
]) ){ h
++; }
4092 if( zLine
[h
]==0 ) break;
4093 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
4094 int delim
= zLine
[h
++];
4095 azArg
[nArg
++] = &zLine
[h
];
4096 while( zLine
[h
] && zLine
[h
]!=delim
){
4097 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
4100 if( zLine
[h
]==delim
){
4103 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
4105 azArg
[nArg
++] = &zLine
[h
];
4106 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
4107 if( zLine
[h
] ) zLine
[h
++] = 0;
4108 resolve_backslashes(azArg
[nArg
-1]);
4112 /* Process the input line.
4114 if( nArg
==0 ) return 0; /* no tokens, no error */
4115 n
= strlen30(azArg
[0]);
4118 #ifndef SQLITE_OMIT_AUTHORIZATION
4119 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
4121 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
4123 goto meta_command_exit
;
4126 if( booleanValue(azArg
[1]) ){
4127 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
4129 sqlite3_set_authorizer(p
->db
, 0, 0);
4134 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
4135 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
4137 const char *zDestFile
= 0;
4138 const char *zDb
= 0;
4140 sqlite3_backup
*pBackup
;
4142 for(j
=1; j
<nArg
; j
++){
4143 const char *z
= azArg
[j
];
4145 while( z
[0]=='-' ) z
++;
4146 /* No options to process at this time */
4148 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
4151 }else if( zDestFile
==0 ){
4152 zDestFile
= azArg
[j
];
4155 zDestFile
= azArg
[j
];
4157 raw_printf(stderr
, "too many arguments to .backup\n");
4162 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
4165 if( zDb
==0 ) zDb
= "main";
4166 rc
= sqlite3_open(zDestFile
, &pDest
);
4167 if( rc
!=SQLITE_OK
){
4168 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
4169 sqlite3_close(pDest
);
4173 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
4175 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
4176 sqlite3_close(pDest
);
4179 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
4180 sqlite3_backup_finish(pBackup
);
4181 if( rc
==SQLITE_DONE
){
4184 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
4187 sqlite3_close(pDest
);
4190 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
4192 bail_on_error
= booleanValue(azArg
[1]);
4194 raw_printf(stderr
, "Usage: .bail on|off\n");
4199 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
4201 if( booleanValue(azArg
[1]) ){
4202 setBinaryMode(p
->out
, 1);
4204 setTextMode(p
->out
, 1);
4207 raw_printf(stderr
, "Usage: .binary on|off\n");
4212 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
4214 #if defined(_WIN32) || defined(WIN32)
4215 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
4216 rc
= !SetCurrentDirectoryW(z
);
4219 rc
= chdir(azArg
[1]);
4222 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
4226 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
4231 /* The undocumented ".breakpoint" command causes a call to the no-op
4232 ** routine named test_breakpoint().
4234 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
4238 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
4240 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
4242 raw_printf(stderr
, "Usage: .changes on|off\n");
4247 /* Cancel output redirection, if it is currently set (by .testcase)
4248 ** Then read the content of the testcase-out.txt file and compare against
4249 ** azArg[1]. If there are differences, report an error and exit.
4251 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
4255 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
4257 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
4258 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
4260 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
4262 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4263 p
->zTestcase
, azArg
[1], zRes
);
4266 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
4272 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
4274 tryToClone(p
, azArg
[1]);
4276 raw_printf(stderr
, "Usage: .clone FILENAME\n");
4281 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
4285 memcpy(&data
, p
, sizeof(data
));
4286 data
.showHeader
= 0;
4287 data
.cMode
= data
.mode
= MODE_List
;
4288 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
4290 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
4291 callback
, &data
, &zErrMsg
);
4293 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
4294 sqlite3_free(zErrMsg
);
4299 if( c
=='d' && strncmp(azArg
[0], "dbinfo", n
)==0 ){
4300 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
4303 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
4304 const char *zLike
= 0;
4306 int savedShowHeader
= p
->showHeader
;
4307 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
);
4308 for(i
=1; i
<nArg
; i
++){
4309 if( azArg
[i
][0]=='-' ){
4310 const char *z
= azArg
[i
]+1;
4311 if( z
[0]=='-' ) z
++;
4312 if( strcmp(z
,"preserve-rowids")==0 ){
4313 #ifdef SQLITE_OMIT_VIRTUALTABLE
4314 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
4315 " with SQLITE_OMIT_VIRTUALTABLE\n");
4317 goto meta_command_exit
;
4319 ShellSetFlag(p
, SHFLG_PreserveRowid
);
4322 if( strcmp(z
,"newlines")==0 ){
4323 ShellSetFlag(p
, SHFLG_Newlines
);
4326 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
4328 goto meta_command_exit
;
4331 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
4332 "?--newlines? ?LIKE-PATTERN?\n");
4334 goto meta_command_exit
;
4340 /* When playing back a "dump", the content might appear in an order
4341 ** which causes immediate foreign key constraints to be violated.
4342 ** So disable foreign-key constraint enforcement to prevent problems. */
4343 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
4344 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
4345 p
->writableSchema
= 0;
4347 /* Set writable_schema=ON since doing so forces SQLite to initialize
4348 ** as much of the schema as it can even if the sqlite_master table is
4350 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4353 run_schema_dump_query(p
,
4354 "SELECT name, type, sql FROM sqlite_master "
4355 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4357 run_schema_dump_query(p
,
4358 "SELECT name, type, sql FROM sqlite_master "
4359 "WHERE name=='sqlite_sequence'"
4361 run_table_dump_query(p
,
4362 "SELECT sql FROM sqlite_master "
4363 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4367 zSql
= sqlite3_mprintf(
4368 "SELECT name, type, sql FROM sqlite_master "
4369 "WHERE tbl_name LIKE %Q AND type=='table'"
4370 " AND sql NOT NULL", zLike
);
4371 run_schema_dump_query(p
,zSql
);
4373 zSql
= sqlite3_mprintf(
4374 "SELECT sql FROM sqlite_master "
4375 "WHERE sql NOT NULL"
4376 " AND type IN ('index','trigger','view')"
4377 " AND tbl_name LIKE %Q", zLike
);
4378 run_table_dump_query(p
, zSql
, 0);
4381 if( p
->writableSchema
){
4382 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
4383 p
->writableSchema
= 0;
4385 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4386 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
4387 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4388 p
->showHeader
= savedShowHeader
;
4391 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
4393 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
4395 raw_printf(stderr
, "Usage: .echo on|off\n");
4400 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
4402 if( strcmp(azArg
[1],"full")==0 ){
4405 p
->autoEQP
= booleanValue(azArg
[1]);
4408 raw_printf(stderr
, "Usage: .eqp on|off|full\n");
4413 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
4414 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
4418 /* The ".explain" command is automatic now. It is largely pointless. It
4419 ** retained purely for backwards compatibility */
4420 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
4423 if( strcmp(azArg
[1],"auto")==0 ){
4426 val
= booleanValue(azArg
[1]);
4429 if( val
==1 && p
->mode
!=MODE_Explain
){
4430 p
->normalMode
= p
->mode
;
4431 p
->mode
= MODE_Explain
;
4434 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
4436 }else if( val
==99 ){
4437 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
4442 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
4446 memcpy(&data
, p
, sizeof(data
));
4447 data
.showHeader
= 0;
4448 data
.cMode
= data
.mode
= MODE_Semi
;
4449 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
4450 data
.cMode
= data
.mode
= MODE_Pretty
;
4454 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
4456 goto meta_command_exit
;
4459 rc
= sqlite3_exec(p
->db
,
4461 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4462 " FROM sqlite_master UNION ALL"
4463 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4464 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4466 callback
, &data
, &zErrMsg
4468 if( rc
==SQLITE_OK
){
4469 sqlite3_stmt
*pStmt
;
4470 rc
= sqlite3_prepare_v2(p
->db
,
4471 "SELECT rowid FROM sqlite_master"
4472 " WHERE name GLOB 'sqlite_stat[134]'",
4474 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
4475 sqlite3_finalize(pStmt
);
4478 raw_printf(p
->out
, "/* No STAT tables available */\n");
4480 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
4481 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
4482 callback
, &data
, &zErrMsg
);
4483 data
.cMode
= data
.mode
= MODE_Insert
;
4484 data
.zDestTable
= "sqlite_stat1";
4485 shell_exec(p
->db
, "SELECT * FROM sqlite_stat1",
4486 shell_callback
, &data
,&zErrMsg
);
4487 data
.zDestTable
= "sqlite_stat3";
4488 shell_exec(p
->db
, "SELECT * FROM sqlite_stat3",
4489 shell_callback
, &data
,&zErrMsg
);
4490 data
.zDestTable
= "sqlite_stat4";
4491 shell_exec(p
->db
, "SELECT * FROM sqlite_stat4",
4492 shell_callback
, &data
, &zErrMsg
);
4493 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
4497 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
4499 p
->showHeader
= booleanValue(azArg
[1]);
4501 raw_printf(stderr
, "Usage: .headers on|off\n");
4506 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
4507 utf8_printf(p
->out
, "%s", zHelp
);
4510 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
4511 char *zTable
; /* Insert data into this table */
4512 char *zFile
; /* Name of file to extra content from */
4513 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
4514 int nCol
; /* Number of columns in the table */
4515 int nByte
; /* Number of bytes in an SQL string */
4516 int i
, j
; /* Loop counters */
4517 int needCommit
; /* True to COMMIT or ROLLBACK at end */
4518 int nSep
; /* Number of bytes in p->colSeparator[] */
4519 char *zSql
; /* An SQL statement */
4520 ImportCtx sCtx
; /* Reader context */
4521 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
4522 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
4525 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
4526 goto meta_command_exit
;
4531 memset(&sCtx
, 0, sizeof(sCtx
));
4533 nSep
= strlen30(p
->colSeparator
);
4536 "Error: non-null column separator required for import\n");
4540 raw_printf(stderr
, "Error: multi-character column separators not allowed"
4544 nSep
= strlen30(p
->rowSeparator
);
4546 raw_printf(stderr
, "Error: non-null row separator required for import\n");
4549 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
4550 /* When importing CSV (only), if the row separator is set to the
4551 ** default output row separator, change it to the default input
4552 ** row separator. This avoids having to maintain different input
4553 ** and output row separators. */
4554 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
4555 nSep
= strlen30(p
->rowSeparator
);
4558 raw_printf(stderr
, "Error: multi-character row separators not allowed"
4564 if( sCtx
.zFile
[0]=='|' ){
4565 #ifdef SQLITE_OMIT_POPEN
4566 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
4569 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
4570 sCtx
.zFile
= "<pipe>";
4574 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
4577 if( p
->mode
==MODE_Ascii
){
4578 xRead
= ascii_read_one_field
;
4580 xRead
= csv_read_one_field
;
4583 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
4586 sCtx
.cColSep
= p
->colSeparator
[0];
4587 sCtx
.cRowSep
= p
->rowSeparator
[0];
4588 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
4590 raw_printf(stderr
, "Error: out of memory\n");
4594 nByte
= strlen30(zSql
);
4595 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4596 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
4597 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
4598 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
4600 while( xRead(&sCtx
) ){
4601 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
4603 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
4606 sqlite3_free(zCreate
);
4607 sqlite3_free(sCtx
.z
);
4609 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
4612 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
4613 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
4614 sqlite3_free(zCreate
);
4616 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
4617 sqlite3_errmsg(p
->db
));
4618 sqlite3_free(sCtx
.z
);
4622 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4626 if (pStmt
) sqlite3_finalize(pStmt
);
4627 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
4631 nCol
= sqlite3_column_count(pStmt
);
4632 sqlite3_finalize(pStmt
);
4634 if( nCol
==0 ) return 0; /* no columns, no error */
4635 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
4637 raw_printf(stderr
, "Error: out of memory\n");
4641 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
4643 for(i
=1; i
<nCol
; i
++){
4649 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4652 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
4653 if (pStmt
) sqlite3_finalize(pStmt
);
4657 needCommit
= sqlite3_get_autocommit(p
->db
);
4658 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
4660 int startLine
= sCtx
.nLine
;
4661 for(i
=0; i
<nCol
; i
++){
4662 char *z
= xRead(&sCtx
);
4664 ** Did we reach end-of-file before finding any columns?
4665 ** If so, stop instead of NULL filling the remaining columns.
4667 if( z
==0 && i
==0 ) break;
4669 ** Did we reach end-of-file OR end-of-line before finding any
4670 ** columns in ASCII mode? If so, stop instead of NULL filling
4671 ** the remaining columns.
4673 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
4674 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
4675 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
4676 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
4677 "filling the rest with NULL\n",
4678 sCtx
.zFile
, startLine
, nCol
, i
+1);
4680 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
4683 if( sCtx
.cTerm
==sCtx
.cColSep
){
4687 }while( sCtx
.cTerm
==sCtx
.cColSep
);
4688 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
4690 sCtx
.zFile
, startLine
, nCol
, i
);
4693 sqlite3_step(pStmt
);
4694 rc
= sqlite3_reset(pStmt
);
4695 if( rc
!=SQLITE_OK
){
4696 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
4697 startLine
, sqlite3_errmsg(p
->db
));
4700 }while( sCtx
.cTerm
!=EOF
);
4703 sqlite3_free(sCtx
.z
);
4704 sqlite3_finalize(pStmt
);
4705 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
4708 #ifndef SQLITE_UNTESTABLE
4709 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
4712 sqlite3_stmt
*pStmt
;
4716 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n");
4718 goto meta_command_exit
;
4721 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
4722 " WHERE name='%q' AND type='index'", azArg
[1]);
4723 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4725 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
4726 tnum
= sqlite3_column_int(pStmt
, 0);
4728 sqlite3_finalize(pStmt
);
4730 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
4732 goto meta_command_exit
;
4734 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
4735 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4738 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4740 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
4743 if( sqlite3_column_int(pStmt
,1)==-1 ){
4746 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
4751 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
4753 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
4756 sqlite3_finalize(pStmt
);
4757 zSql
= sqlite3_mprintf(
4758 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
4759 azArg
[2], zCollist
, zCollist
);
4760 sqlite3_free(zCollist
);
4761 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
4762 if( rc
==SQLITE_OK
){
4763 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
4764 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
4766 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
4768 utf8_printf(stdout
, "%s;\n", zSql
);
4770 "WARNING: writing to an imposter table will corrupt the index!\n"
4774 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
4779 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
4781 #ifdef SQLITE_ENABLE_IOTRACE
4782 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
4783 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
4784 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
4788 }else if( strcmp(azArg
[1], "-")==0 ){
4789 sqlite3IoTrace
= iotracePrintf
;
4792 iotrace
= fopen(azArg
[1], "w");
4794 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
4798 sqlite3IoTrace
= iotracePrintf
;
4804 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
4805 static const struct {
4806 const char *zLimitName
; /* Name of a limit */
4807 int limitCode
; /* Integer code for that limit */
4809 { "length", SQLITE_LIMIT_LENGTH
},
4810 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
4811 { "column", SQLITE_LIMIT_COLUMN
},
4812 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
4813 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
4814 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
4815 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
4816 { "attached", SQLITE_LIMIT_ATTACHED
},
4817 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
4818 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
4819 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
4820 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
4825 for(i
=0; i
<ArraySize(aLimit
); i
++){
4826 printf("%20s %d\n", aLimit
[i
].zLimitName
,
4827 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
4830 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
4832 goto meta_command_exit
;
4835 n2
= strlen30(azArg
[1]);
4836 for(i
=0; i
<ArraySize(aLimit
); i
++){
4837 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
4841 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
4843 goto meta_command_exit
;
4848 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
4849 "enter \".limits\" with no arguments for a list.\n",
4852 goto meta_command_exit
;
4855 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
4856 (int)integerValue(azArg
[2]));
4858 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
4859 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
4863 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
4865 lintDotCommand(p
, azArg
, nArg
);
4868 #ifndef SQLITE_OMIT_LOAD_EXTENSION
4869 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
4870 const char *zFile
, *zProc
;
4873 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
4875 goto meta_command_exit
;
4878 zProc
= nArg
>=3 ? azArg
[2] : 0;
4880 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
4881 if( rc
!=SQLITE_OK
){
4882 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
4883 sqlite3_free(zErrMsg
);
4889 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
4891 raw_printf(stderr
, "Usage: .log FILENAME\n");
4894 const char *zFile
= azArg
[1];
4895 output_file_close(p
->pLog
);
4896 p
->pLog
= output_file_open(zFile
);
4900 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
4901 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
4902 int n2
= (int)strlen(zMode
);
4904 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
4905 p
->mode
= MODE_Line
;
4906 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
4907 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
4908 p
->mode
= MODE_Column
;
4909 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
4910 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
4911 p
->mode
= MODE_List
;
4912 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
4913 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
4914 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
4915 p
->mode
= MODE_Html
;
4916 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
4918 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
4919 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
4920 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
4922 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
4923 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
4924 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
4925 p
->mode
= MODE_List
;
4926 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
4927 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
4928 p
->mode
= MODE_Insert
;
4929 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
4930 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
4931 p
->mode
= MODE_Quote
;
4932 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
4933 p
->mode
= MODE_Ascii
;
4934 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
4935 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
4936 }else if( nArg
==1 ){
4937 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
4939 raw_printf(stderr
, "Error: mode should be one of: "
4940 "ascii column csv html insert line list quote tabs tcl\n");
4946 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
4948 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
4949 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
4951 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
4956 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
4957 char *zNewFilename
; /* Name of the database file to open */
4958 int iName
= 1; /* Index in azArg[] of the filename */
4959 int newFlag
= 0; /* True to delete file before opening */
4960 /* Close the existing database */
4961 session_close_all(p
);
4962 sqlite3_close(p
->db
);
4965 sqlite3_free(p
->zFreeOnClose
);
4966 p
->zFreeOnClose
= 0;
4967 /* Check for command-line arguments */
4968 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
4969 const char *z
= azArg
[iName
];
4970 if( optionMatch(z
,"new") ){
4972 }else if( z
[0]=='-' ){
4973 utf8_printf(stderr
, "unknown option: %s\n", z
);
4975 goto meta_command_exit
;
4978 /* If a filename is specified, try to open it first */
4979 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
4981 if( newFlag
) shellDeleteFile(zNewFilename
);
4982 p
->zDbFilename
= zNewFilename
;
4985 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
4986 sqlite3_free(zNewFilename
);
4988 p
->zFreeOnClose
= zNewFilename
;
4992 /* As a fall-back open a TEMP database */
4999 && (strncmp(azArg
[0], "output", n
)==0 || strncmp(azArg
[0], "once", n
)==0)
5001 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
5003 utf8_printf(stderr
, "Usage: .%s FILE\n", azArg
[0]);
5005 goto meta_command_exit
;
5007 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
5009 raw_printf(stderr
, "Usage: .once FILE\n");
5011 goto meta_command_exit
;
5018 if( zFile
[0]=='|' ){
5019 #ifdef SQLITE_OMIT_POPEN
5020 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
5024 p
->out
= popen(zFile
+ 1, "w");
5026 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
5030 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
5034 p
->out
= output_file_open(zFile
);
5036 if( strcmp(zFile
,"off")!=0 ){
5037 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
5042 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
5047 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
5049 for(i
=1; i
<nArg
; i
++){
5050 if( i
>1 ) raw_printf(p
->out
, " ");
5051 utf8_printf(p
->out
, "%s", azArg
[i
]);
5053 raw_printf(p
->out
, "\n");
5056 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
5058 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
5061 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
5065 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
5069 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
5072 raw_printf(stderr
, "Usage: .read FILE\n");
5074 goto meta_command_exit
;
5076 alt
= fopen(azArg
[1], "rb");
5078 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
5081 rc
= process_input(p
, alt
);
5086 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
5087 const char *zSrcFile
;
5090 sqlite3_backup
*pBackup
;
5094 zSrcFile
= azArg
[1];
5096 }else if( nArg
==3 ){
5097 zSrcFile
= azArg
[2];
5100 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
5102 goto meta_command_exit
;
5104 rc
= sqlite3_open(zSrcFile
, &pSrc
);
5105 if( rc
!=SQLITE_OK
){
5106 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
5107 sqlite3_close(pSrc
);
5111 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
5113 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5114 sqlite3_close(pSrc
);
5117 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
5118 || rc
==SQLITE_BUSY
){
5119 if( rc
==SQLITE_BUSY
){
5120 if( nTimeout
++ >= 3 ) break;
5124 sqlite3_backup_finish(pBackup
);
5125 if( rc
==SQLITE_DONE
){
5127 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
5128 raw_printf(stderr
, "Error: source database is busy\n");
5131 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5134 sqlite3_close(pSrc
);
5138 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
5140 p
->scanstatsOn
= booleanValue(azArg
[1]);
5141 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5142 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
5145 raw_printf(stderr
, "Usage: .scanstats on|off\n");
5150 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
5154 const char *zDiv
= 0;
5158 memcpy(&data
, p
, sizeof(data
));
5159 data
.showHeader
= 0;
5160 data
.cMode
= data
.mode
= MODE_Semi
;
5162 if( nArg
>=2 && optionMatch(azArg
[1], "indent") ){
5163 data
.cMode
= data
.mode
= MODE_Pretty
;
5165 if( nArg
==2 ) azArg
[1] = azArg
[2];
5167 if( nArg
==2 && azArg
[1][0]!='-' ){
5169 for(i
=0; azArg
[1][i
]; i
++) azArg
[1][i
] = ToLower(azArg
[1][i
]);
5170 if( strcmp(azArg
[1],"sqlite_master")==0 ){
5171 char *new_argv
[2], *new_colv
[2];
5172 new_argv
[0] = "CREATE TABLE sqlite_master (\n"
5176 " rootpage integer,\n"
5180 new_colv
[0] = "sql";
5182 callback(&data
, 1, new_argv
, new_colv
);
5184 }else if( strcmp(azArg
[1],"sqlite_temp_master")==0 ){
5185 char *new_argv
[2], *new_colv
[2];
5186 new_argv
[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5190 " rootpage integer,\n"
5194 new_colv
[0] = "sql";
5196 callback(&data
, 1, new_argv
, new_colv
);
5201 }else if( nArg
==1 ){
5204 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5206 goto meta_command_exit
;
5209 sqlite3_stmt
*pStmt
= 0;
5210 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
5213 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5214 sqlite3_finalize(pStmt
);
5216 goto meta_command_exit
;
5218 appendText(&sSelect
, "SELECT sql FROM", 0);
5220 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5221 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
5223 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
5224 appendText(&sSelect
, zDiv
, 0);
5225 zDiv
= " UNION ALL ";
5226 if( strcmp(zDb
, "main")!=0 ){
5227 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
5228 appendText(&sSelect
, zDb
, '"');
5229 appendText(&sSelect
, ") AS sql, type, tbl_name, name, rowid,", 0);
5230 appendText(&sSelect
, zScNum
, 0);
5231 appendText(&sSelect
, " AS snum, ", 0);
5232 appendText(&sSelect
, zDb
, '\'');
5233 appendText(&sSelect
, " AS sname FROM ", 0);
5234 appendText(&sSelect
, zDb
, '"');
5235 appendText(&sSelect
, ".sqlite_master", 0);
5237 appendText(&sSelect
, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5238 appendText(&sSelect
, zScNum
, 0);
5239 appendText(&sSelect
, " AS snum, 'main' AS sname FROM sqlite_master",0);
5242 sqlite3_finalize(pStmt
);
5243 appendText(&sSelect
, ") WHERE ", 0);
5245 char *zQarg
= sqlite3_mprintf("%Q", azArg
[1]);
5246 if( strchr(azArg
[1], '.') ){
5247 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
5249 appendText(&sSelect
, "lower(tbl_name)", 0);
5251 appendText(&sSelect
, strchr(azArg
[1], '*') ? " GLOB " : " LIKE ", 0);
5252 appendText(&sSelect
, zQarg
, 0);
5253 appendText(&sSelect
, " AND ", 0);
5254 sqlite3_free(zQarg
);
5256 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
5257 " ORDER BY snum, rowid", 0);
5258 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
5262 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5263 sqlite3_free(zErrMsg
);
5265 }else if( rc
!= SQLITE_OK
){
5266 raw_printf(stderr
,"Error: querying schema information\n");
5273 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5274 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
5275 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
5279 #if defined(SQLITE_ENABLE_SESSION)
5280 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
5281 OpenSession
*pSession
= &p
->aSession
[0];
5282 char **azCmd
= &azArg
[1];
5284 int nCmd
= nArg
- 1;
5286 if( nArg
<=1 ) goto session_syntax_error
;
5289 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
5290 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
5292 if( iSes
<p
->nSession
){
5293 pSession
= &p
->aSession
[iSes
];
5297 pSession
= &p
->aSession
[0];
5302 /* .session attach TABLE
5303 ** Invoke the sqlite3session_attach() interface to attach a particular
5304 ** table so that it is never filtered.
5306 if( strcmp(azCmd
[0],"attach")==0 ){
5307 if( nCmd
!=2 ) goto session_syntax_error
;
5308 if( pSession
->p
==0 ){
5310 raw_printf(stderr
, "ERROR: No sessions are open\n");
5312 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
5314 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
5320 /* .session changeset FILE
5321 ** .session patchset FILE
5322 ** Write a changeset or patchset into a file. The file is overwritten.
5324 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
5326 if( nCmd
!=2 ) goto session_syntax_error
;
5327 if( pSession
->p
==0 ) goto session_not_open
;
5328 out
= fopen(azCmd
[1], "wb");
5330 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
5334 if( azCmd
[0][0]=='c' ){
5335 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
5337 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
5340 printf("Error: error code %d\n", rc
);
5344 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
5345 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
5348 sqlite3_free(pChng
);
5354 ** Close the identified session
5356 if( strcmp(azCmd
[0], "close")==0 ){
5357 if( nCmd
!=1 ) goto session_syntax_error
;
5359 session_close(pSession
);
5360 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
5364 /* .session enable ?BOOLEAN?
5365 ** Query or set the enable flag
5367 if( strcmp(azCmd
[0], "enable")==0 ){
5369 if( nCmd
>2 ) goto session_syntax_error
;
5370 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
5372 ii
= sqlite3session_enable(pSession
->p
, ii
);
5373 utf8_printf(p
->out
, "session %s enable flag = %d\n",
5374 pSession
->zName
, ii
);
5378 /* .session filter GLOB ....
5379 ** Set a list of GLOB patterns of table names to be excluded.
5381 if( strcmp(azCmd
[0], "filter")==0 ){
5383 if( nCmd
<2 ) goto session_syntax_error
;
5385 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
5386 sqlite3_free(pSession
->azFilter
[ii
]);
5388 sqlite3_free(pSession
->azFilter
);
5389 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
5390 pSession
->azFilter
= sqlite3_malloc( nByte
);
5391 if( pSession
->azFilter
==0 ){
5392 raw_printf(stderr
, "Error: out or memory\n");
5395 for(ii
=1; ii
<nCmd
; ii
++){
5396 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
5398 pSession
->nFilter
= ii
-1;
5402 /* .session indirect ?BOOLEAN?
5403 ** Query or set the indirect flag
5405 if( strcmp(azCmd
[0], "indirect")==0 ){
5407 if( nCmd
>2 ) goto session_syntax_error
;
5408 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
5410 ii
= sqlite3session_indirect(pSession
->p
, ii
);
5411 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
5412 pSession
->zName
, ii
);
5417 ** Determine if the session is empty
5419 if( strcmp(azCmd
[0], "isempty")==0 ){
5421 if( nCmd
!=1 ) goto session_syntax_error
;
5423 ii
= sqlite3session_isempty(pSession
->p
);
5424 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
5425 pSession
->zName
, ii
);
5430 ** List all currently open sessions
5432 if( strcmp(azCmd
[0],"list")==0 ){
5433 for(i
=0; i
<p
->nSession
; i
++){
5434 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
5438 /* .session open DB NAME
5439 ** Open a new session called NAME on the attached database DB.
5440 ** DB is normally "main".
5442 if( strcmp(azCmd
[0],"open")==0 ){
5444 if( nCmd
!=3 ) goto session_syntax_error
;
5446 if( zName
[0]==0 ) goto session_syntax_error
;
5447 for(i
=0; i
<p
->nSession
; i
++){
5448 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
5449 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
5450 goto meta_command_exit
;
5453 if( p
->nSession
>=ArraySize(p
->aSession
) ){
5454 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
5455 goto meta_command_exit
;
5457 pSession
= &p
->aSession
[p
->nSession
];
5458 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
5460 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
5462 goto meta_command_exit
;
5464 pSession
->nFilter
= 0;
5465 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
5467 pSession
->zName
= sqlite3_mprintf("%s", zName
);
5469 /* If no command name matches, show a syntax error */
5470 session_syntax_error
:
5476 /* Undocumented commands for internal testing. Subject to change
5477 ** without notice. */
5478 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
5479 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
5481 for(i
=1; i
<nArg
; i
++){
5482 v
= booleanValue(azArg
[i
]);
5483 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
5486 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
5487 int i
; sqlite3_int64 v
;
5488 for(i
=1; i
<nArg
; i
++){
5490 v
= integerValue(azArg
[i
]);
5491 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
5492 utf8_printf(p
->out
, "%s", zBuf
);
5498 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
5499 int bIsInit
= 0; /* True to initialize the SELFTEST table */
5500 int bVerbose
= 0; /* Verbose output */
5501 int bSelftestExists
; /* True if SELFTEST already exists */
5502 int i
, k
; /* Loop counters */
5503 int nTest
= 0; /* Number of tests runs */
5504 int nErr
= 0; /* Number of errors seen */
5505 ShellText str
; /* Answer for a query */
5506 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
5509 for(i
=1; i
<nArg
; i
++){
5510 const char *z
= azArg
[i
];
5511 if( z
[0]=='-' && z
[1]=='-' ) z
++;
5512 if( strcmp(z
,"-init")==0 ){
5515 if( strcmp(z
,"-v")==0 ){
5519 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
5520 azArg
[i
], azArg
[0]);
5521 raw_printf(stderr
, "Should be one of: --init -v\n");
5523 goto meta_command_exit
;
5526 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
5528 bSelftestExists
= 0;
5530 bSelftestExists
= 1;
5533 createSelftestTable(p
);
5534 bSelftestExists
= 1;
5537 appendText(&str
, "x", 0);
5538 for(k
=bSelftestExists
; k
>=0; k
--){
5540 rc
= sqlite3_prepare_v2(p
->db
,
5541 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5544 rc
= sqlite3_prepare_v2(p
->db
,
5545 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
5546 " (1,'run','PRAGMA integrity_check','ok')",
5550 raw_printf(stderr
, "Error querying the selftest table\n");
5552 sqlite3_finalize(pStmt
);
5553 goto meta_command_exit
;
5555 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
5556 int tno
= sqlite3_column_int(pStmt
, 0);
5557 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
5558 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
5559 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
5563 char *zQuote
= sqlite3_mprintf("%q", zSql
);
5564 printf("%d: %s %s\n", tno
, zOp
, zSql
);
5565 sqlite3_free(zQuote
);
5567 if( strcmp(zOp
,"memo")==0 ){
5568 utf8_printf(p
->out
, "%s\n", zSql
);
5570 if( strcmp(zOp
,"run")==0 ){
5574 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
5577 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
5579 if( rc
|| zErrMsg
){
5582 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
5583 sqlite3_free(zErrMsg
);
5584 }else if( strcmp(zAns
,str
.z
)!=0 ){
5587 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
5588 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
5593 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
5597 } /* End loop over rows of content from SELFTEST */
5598 sqlite3_finalize(pStmt
);
5599 } /* End loop over k */
5601 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
5604 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
5605 if( nArg
<2 || nArg
>3 ){
5606 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
5610 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
5611 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
5614 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
5615 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
5619 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
5620 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
5621 int i
; /* Loop counter */
5622 int bSchema
= 0; /* Also hash the schema */
5623 int bSeparate
= 0; /* Hash each table separately */
5624 int iSize
= 224; /* Hash algorithm to use */
5625 int bDebug
= 0; /* Only show the query that would have run */
5626 sqlite3_stmt
*pStmt
; /* For querying tables names */
5627 char *zSql
; /* SQL to be run */
5628 char *zSep
; /* Separator */
5629 ShellText sSql
; /* Complete SQL for the query to run the hash */
5630 ShellText sQuery
; /* Set of queries used to read all content */
5632 for(i
=1; i
<nArg
; i
++){
5633 const char *z
= azArg
[i
];
5636 if( z
[0]=='-' ) z
++;
5637 if( strcmp(z
,"schema")==0 ){
5640 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
5641 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
5643 iSize
= atoi(&z
[5]);
5645 if( strcmp(z
,"debug")==0 ){
5649 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
5650 azArg
[i
], azArg
[0]);
5651 raw_printf(stderr
, "Should be one of: --schema"
5652 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5654 goto meta_command_exit
;
5657 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5659 goto meta_command_exit
;
5663 if( sqlite3_strlike("sqlite_%", zLike
, 0)==0 ) bSchema
= 1;
5667 zSql
= "SELECT lower(name) FROM sqlite_master"
5668 " WHERE type='table' AND coalesce(rootpage,0)>1"
5669 " UNION ALL SELECT 'sqlite_master'"
5670 " ORDER BY 1 collate nocase";
5672 zSql
= "SELECT lower(name) FROM sqlite_master"
5673 " WHERE type='table' AND coalesce(rootpage,0)>1"
5674 " AND name NOT LIKE 'sqlite_%'"
5675 " ORDER BY 1 collate nocase";
5677 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5680 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
5682 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
5683 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
5684 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
5685 if( strncmp(zTab
, "sqlite_",7)!=0 ){
5686 appendText(&sQuery
,"SELECT * FROM ", 0);
5687 appendText(&sQuery
,zTab
,'"');
5688 appendText(&sQuery
," NOT INDEXED;", 0);
5689 }else if( strcmp(zTab
, "sqlite_master")==0 ){
5690 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
5691 " ORDER BY name;", 0);
5692 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
5693 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
5694 " ORDER BY name;", 0);
5695 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
5696 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
5697 " ORDER BY tbl,idx;", 0);
5698 }else if( strcmp(zTab
, "sqlite_stat3")==0
5699 || strcmp(zTab
, "sqlite_stat4")==0 ){
5700 appendText(&sQuery
, "SELECT * FROM ", 0);
5701 appendText(&sQuery
, zTab
, 0);
5702 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
5704 appendText(&sSql
, zSep
, 0);
5705 appendText(&sSql
, sQuery
.z
, '\'');
5707 appendText(&sSql
, ",", 0);
5708 appendText(&sSql
, zTab
, '\'');
5711 sqlite3_finalize(pStmt
);
5713 zSql
= sqlite3_mprintf(
5715 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
5716 " FROM [sha3sum$query]",
5719 zSql
= sqlite3_mprintf(
5721 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
5722 " FROM [sha3sum$query]",
5728 utf8_printf(p
->out
, "%s\n", zSql
);
5730 shell_exec(p
->db
, zSql
, shell_callback
, p
, 0);
5736 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
5741 raw_printf(stderr
, "Usage: .system COMMAND\n");
5743 goto meta_command_exit
;
5745 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
5746 for(i
=2; i
<nArg
; i
++){
5747 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
5752 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
5755 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
5756 static const char *azBool
[] = { "off", "on", "full", "unk" };
5759 raw_printf(stderr
, "Usage: .show\n");
5761 goto meta_command_exit
;
5763 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
5764 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
5765 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
5766 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
5767 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
5768 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
5769 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
5770 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
5771 output_c_string(p
->out
, p
->nullValue
);
5772 raw_printf(p
->out
, "\n");
5773 utf8_printf(p
->out
,"%12.12s: %s\n","output",
5774 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
5775 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
5776 output_c_string(p
->out
, p
->colSeparator
);
5777 raw_printf(p
->out
, "\n");
5778 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
5779 output_c_string(p
->out
, p
->rowSeparator
);
5780 raw_printf(p
->out
, "\n");
5781 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
5782 utf8_printf(p
->out
, "%12.12s: ", "width");
5783 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
5784 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
5786 raw_printf(p
->out
, "\n");
5787 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
5788 p
->zDbFilename
? p
->zDbFilename
: "");
5791 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
5793 p
->statsOn
= booleanValue(azArg
[1]);
5794 }else if( nArg
==1 ){
5795 display_stats(p
->db
, p
, 0);
5797 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
5802 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
5803 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
5804 || strncmp(azArg
[0], "indexes", n
)==0) )
5806 sqlite3_stmt
*pStmt
;
5813 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
5814 if( rc
) return shellDatabaseError(p
->db
);
5816 if( nArg
>2 && c
=='i' ){
5817 /* It is an historical accident that the .indexes command shows an error
5818 ** when called with the wrong number of arguments whereas the .tables
5819 ** command does not. */
5820 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
5822 goto meta_command_exit
;
5824 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
5825 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
5826 if( zDbName
==0 ) continue;
5827 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
5828 if( sqlite3_stricmp(zDbName
, "main")==0 ){
5829 appendText(&s
, "SELECT name FROM ", 0);
5831 appendText(&s
, "SELECT ", 0);
5832 appendText(&s
, zDbName
, '\'');
5833 appendText(&s
, "||'.'||name FROM ", 0);
5835 appendText(&s
, zDbName
, '"');
5836 appendText(&s
, ".sqlite_master ", 0);
5838 appendText(&s
," WHERE type IN ('table','view')"
5839 " AND name NOT LIKE 'sqlite_%'"
5840 " AND name LIKE ?1", 0);
5842 appendText(&s
," WHERE type='index'"
5843 " AND tbl_name LIKE ?1", 0);
5846 rc
= sqlite3_finalize(pStmt
);
5847 appendText(&s
, " ORDER BY 1", 0);
5848 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
5850 if( rc
) return shellDatabaseError(p
->db
);
5852 /* Run the SQL statement prepared by the above block. Store the results
5853 ** as an array of nul-terminated strings in azResult[]. */
5857 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
5859 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
5861 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5864 int n2
= nAlloc
*2 + 10;
5865 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
5867 rc
= shellNomemError();
5873 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
5874 if( 0==azResult
[nRow
] ){
5875 rc
= shellNomemError();
5880 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
5881 rc
= shellDatabaseError(p
->db
);
5884 /* Pretty-print the contents of array azResult[] to the output */
5885 if( rc
==0 && nRow
>0 ){
5886 int len
, maxlen
= 0;
5888 int nPrintCol
, nPrintRow
;
5889 for(i
=0; i
<nRow
; i
++){
5890 len
= strlen30(azResult
[i
]);
5891 if( len
>maxlen
) maxlen
= len
;
5893 nPrintCol
= 80/(maxlen
+2);
5894 if( nPrintCol
<1 ) nPrintCol
= 1;
5895 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
5896 for(i
=0; i
<nPrintRow
; i
++){
5897 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
5898 char *zSp
= j
<nPrintRow
? "" : " ";
5899 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
5900 azResult
[j
] ? azResult
[j
]:"");
5902 raw_printf(p
->out
, "\n");
5906 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
5907 sqlite3_free(azResult
);
5910 /* Begin redirecting output to the file "testcase-out.txt" */
5911 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
5913 p
->out
= output_file_open("testcase-out.txt");
5915 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
5918 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
5920 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
5924 #ifndef SQLITE_UNTESTABLE
5925 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
5926 static const struct {
5927 const char *zCtrlName
; /* Name of a test-control option */
5928 int ctrlCode
; /* Integer code for that option */
5929 const char *zUsage
; /* Usage notes */
5931 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
5932 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
5933 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
5934 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
5935 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
5936 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
5937 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
5938 #ifdef SQLITE_N_KEYWORD
5939 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD
, "IDENTIFIER" },
5941 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
5942 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
5943 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
5944 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
5945 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
5946 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
5947 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
5948 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
5952 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
5956 const char *zCmd
= nArg
>=2 ? azArg
[1] : "help";
5958 /* The argument can optionally begin with "-" or "--" */
5959 if( zCmd
[0]=='-' && zCmd
[1] ){
5961 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
5964 /* --help lists all test-controls */
5965 if( strcmp(zCmd
,"help")==0 ){
5966 utf8_printf(p
->out
, "Available test-controls:\n");
5967 for(i
=0; i
<ArraySize(aCtrl
); i
++){
5968 utf8_printf(p
->out
, " .testctrl %s %s\n",
5969 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
5972 goto meta_command_exit
;
5975 /* convert testctrl text option to value. allow any unique prefix
5976 ** of the option name, or a numerical value. */
5977 n2
= strlen30(zCmd
);
5978 for(i
=0; i
<ArraySize(aCtrl
); i
++){
5979 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
5981 testctrl
= aCtrl
[i
].ctrlCode
;
5984 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
5985 "Use \".testctrl --help\" for help\n", zCmd
);
5987 goto meta_command_exit
;
5992 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
5993 "Use \".testctrl --help\" for help\n", zCmd
);
5997 /* sqlite3_test_control(int, db, int) */
5998 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
5999 case SQLITE_TESTCTRL_RESERVE
:
6001 int opt
= (int)strtol(azArg
[2], 0, 0);
6002 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
6007 /* sqlite3_test_control(int) */
6008 case SQLITE_TESTCTRL_PRNG_SAVE
:
6009 case SQLITE_TESTCTRL_PRNG_RESTORE
:
6010 case SQLITE_TESTCTRL_PRNG_RESET
:
6011 case SQLITE_TESTCTRL_BYTEORDER
:
6013 rc2
= sqlite3_test_control(testctrl
);
6014 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
6018 /* sqlite3_test_control(int, uint) */
6019 case SQLITE_TESTCTRL_PENDING_BYTE
:
6021 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
6022 rc2
= sqlite3_test_control(testctrl
, opt
);
6027 /* sqlite3_test_control(int, int) */
6028 case SQLITE_TESTCTRL_ASSERT
:
6029 case SQLITE_TESTCTRL_ALWAYS
:
6031 int opt
= booleanValue(azArg
[2]);
6032 rc2
= sqlite3_test_control(testctrl
, opt
);
6037 /* sqlite3_test_control(int, int) */
6038 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
6039 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
6041 int opt
= booleanValue(azArg
[2]);
6042 rc2
= sqlite3_test_control(testctrl
, opt
);
6047 /* sqlite3_test_control(int, char *) */
6048 #ifdef SQLITE_N_KEYWORD
6049 case SQLITE_TESTCTRL_ISKEYWORD
:
6051 const char *opt
= azArg
[2];
6052 rc2
= sqlite3_test_control(testctrl
, opt
);
6058 case SQLITE_TESTCTRL_IMPOSTER
:
6060 rc2
= sqlite3_test_control(testctrl
, p
->db
,
6062 integerValue(azArg
[3]),
6063 integerValue(azArg
[4]));
6069 if( isOk
==0 && iCtrl
>=0 ){
6070 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
6072 }else if( isOk
==1 ){
6073 raw_printf(p
->out
, "%d\n", rc2
);
6074 }else if( isOk
==2 ){
6075 raw_printf(p
->out
, "0x%08x\n", rc2
);
6078 #endif /* !defined(SQLITE_UNTESTABLE) */
6080 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
6082 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
6085 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
6087 enableTimer
= booleanValue(azArg
[1]);
6088 if( enableTimer
&& !HAS_TIMER
){
6089 raw_printf(stderr
, "Error: timer not available on this system.\n");
6093 raw_printf(stderr
, "Usage: .timer on|off\n");
6098 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
6101 raw_printf(stderr
, "Usage: .trace FILE|off\n");
6103 goto meta_command_exit
;
6105 output_file_close(p
->traceOut
);
6106 p
->traceOut
= output_file_open(azArg
[1]);
6107 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6108 if( p
->traceOut
==0 ){
6109 sqlite3_trace_v2(p
->db
, 0, 0, 0);
6111 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
6116 #if SQLITE_USER_AUTHENTICATION
6117 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
6119 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
6121 goto meta_command_exit
;
6124 if( strcmp(azArg
[1],"login")==0 ){
6126 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
6128 goto meta_command_exit
;
6130 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
6131 (int)strlen(azArg
[3]));
6133 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
6136 }else if( strcmp(azArg
[1],"add")==0 ){
6138 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
6140 goto meta_command_exit
;
6142 rc
= sqlite3_user_add(p
->db
, azArg
[2],
6143 azArg
[3], (int)strlen(azArg
[3]),
6144 booleanValue(azArg
[4]));
6146 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
6149 }else if( strcmp(azArg
[1],"edit")==0 ){
6151 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
6153 goto meta_command_exit
;
6155 rc
= sqlite3_user_change(p
->db
, azArg
[2],
6156 azArg
[3], (int)strlen(azArg
[3]),
6157 booleanValue(azArg
[4]));
6159 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
6162 }else if( strcmp(azArg
[1],"delete")==0 ){
6164 raw_printf(stderr
, "Usage: .user delete USER\n");
6166 goto meta_command_exit
;
6168 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
6170 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
6174 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
6176 goto meta_command_exit
;
6179 #endif /* SQLITE_USER_AUTHENTICATION */
6181 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
6182 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
6183 sqlite3_libversion(), sqlite3_sourceid());
6186 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
6187 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
6188 sqlite3_vfs
*pVfs
= 0;
6190 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
6192 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
6193 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
6194 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
6195 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
6200 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
6202 sqlite3_vfs
*pCurrent
= 0;
6204 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
6206 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
6207 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
6208 pVfs
==pCurrent
? " <--- CURRENT" : "");
6209 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
6210 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
6211 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
6213 raw_printf(p
->out
, "-----------------------------------\n");
6218 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
6219 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
6222 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
6224 utf8_printf(p
->out
, "%s\n", zVfsName
);
6225 sqlite3_free(zVfsName
);
6230 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6231 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
6232 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
6236 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
6238 assert( nArg
<=ArraySize(azArg
) );
6239 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
6240 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
6245 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
6246 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
6253 if( p
->outCount
==0 ) output_reset(p
);
6259 ** Return TRUE if a semicolon occurs anywhere in the first N characters
6262 static int line_contains_semicolon(const char *z
, int N
){
6264 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
6269 ** Test to see if a line consists entirely of whitespace.
6271 static int _all_whitespace(const char *z
){
6273 if( IsSpace(z
[0]) ) continue;
6274 if( *z
=='/' && z
[1]=='*' ){
6276 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
6277 if( *z
==0 ) return 0;
6281 if( *z
=='-' && z
[1]=='-' ){
6283 while( *z
&& *z
!='\n' ){ z
++; }
6284 if( *z
==0 ) return 1;
6293 ** Return TRUE if the line typed in is an SQL command terminator other
6294 ** than a semi-colon. The SQL Server style "go" command is understood
6295 ** as is the Oracle "/".
6297 static int line_is_command_terminator(const char *zLine
){
6298 while( IsSpace(zLine
[0]) ){ zLine
++; };
6299 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
6300 return 1; /* Oracle */
6302 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
6303 && _all_whitespace(&zLine
[2]) ){
6304 return 1; /* SQL Server */
6310 ** Return true if zSql is a complete SQL statement. Return false if it
6311 ** ends in the middle of a string literal or C-style comment.
6313 static int line_is_complete(char *zSql
, int nSql
){
6315 if( zSql
==0 ) return 1;
6318 rc
= sqlite3_complete(zSql
);
6324 ** Run a single line of SQL
6326 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
6331 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
6333 rc
= shell_exec(p
->db
, zSql
, shell_callback
, p
, &zErrMsg
);
6335 if( rc
|| zErrMsg
){
6337 if( in
!=0 || !stdin_is_interactive
){
6338 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
6339 "Error: near line %d:", startline
);
6341 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
6344 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
6345 sqlite3_free(zErrMsg
);
6348 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
6351 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
6352 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
6353 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
6360 ** Read input from *in and process it. If *in==0 then input
6361 ** is interactive - the user is typing it it. Otherwise, input
6362 ** is coming from a file or device. A prompt is issued and history
6363 ** is saved only if input is interactive. An interrupt signal will
6364 ** cause this routine to exit immediately, unless input is interactive.
6366 ** Return the number of errors.
6368 static int process_input(ShellState
*p
, FILE *in
){
6369 char *zLine
= 0; /* A single input line */
6370 char *zSql
= 0; /* Accumulated SQL text */
6371 int nLine
; /* Length of current line */
6372 int nSql
= 0; /* Bytes of zSql[] used */
6373 int nAlloc
= 0; /* Allocated zSql[] space */
6374 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
6375 int rc
; /* Error code */
6376 int errCnt
= 0; /* Number of errors seen */
6377 int lineno
= 0; /* Current line number */
6378 int startline
= 0; /* Line number for start of current input */
6380 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
6382 zLine
= one_input_line(in
, zLine
, nSql
>0);
6385 if( in
==0 && stdin_is_interactive
) printf("\n");
6388 if( seenInterrupt
){
6393 if( nSql
==0 && _all_whitespace(zLine
) ){
6394 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
6397 if( zLine
&& zLine
[0]=='.' && nSql
==0 ){
6398 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
6399 rc
= do_meta_command(zLine
, p
);
6400 if( rc
==2 ){ /* exit requested */
6407 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
6408 memcpy(zLine
,";",2);
6410 nLine
= strlen30(zLine
);
6411 if( nSql
+nLine
+2>=nAlloc
){
6412 nAlloc
= nSql
+nLine
+100;
6413 zSql
= realloc(zSql
, nAlloc
);
6415 raw_printf(stderr
, "Error: out of memory\n");
6422 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
6423 assert( nAlloc
>0 && zSql
!=0 );
6424 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
6428 zSql
[nSql
++] = '\n';
6429 memcpy(zSql
+nSql
, zLine
, nLine
+1);
6432 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
6433 && sqlite3_complete(zSql
) ){
6434 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
6440 }else if( nSql
&& _all_whitespace(zSql
) ){
6441 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
6445 if( nSql
&& !_all_whitespace(zSql
) ){
6446 runOneSqlLine(p
, zSql
, in
, startline
);
6454 ** Return a pathname which is the user's home directory. A
6455 ** 0 return indicates an error of some kind.
6457 static char *find_home_dir(int clearFlag
){
6458 static char *home_dir
= NULL
;
6464 if( home_dir
) return home_dir
;
6466 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6467 && !defined(__RTP__) && !defined(_WRS_KERNEL)
6469 struct passwd
*pwent
;
6470 uid_t uid
= getuid();
6471 if( (pwent
=getpwuid(uid
)) != NULL
) {
6472 home_dir
= pwent
->pw_dir
;
6477 #if defined(_WIN32_WCE)
6478 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6483 #if defined(_WIN32) || defined(WIN32)
6485 home_dir
= getenv("USERPROFILE");
6490 home_dir
= getenv("HOME");
6493 #if defined(_WIN32) || defined(WIN32)
6495 char *zDrive
, *zPath
;
6497 zDrive
= getenv("HOMEDRIVE");
6498 zPath
= getenv("HOMEPATH");
6499 if( zDrive
&& zPath
){
6500 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
6501 home_dir
= malloc( n
);
6502 if( home_dir
==0 ) return 0;
6503 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
6510 #endif /* !_WIN32_WCE */
6513 int n
= strlen30(home_dir
) + 1;
6514 char *z
= malloc( n
);
6515 if( z
) memcpy(z
, home_dir
, n
);
6523 ** Read input from the file given by sqliterc_override. Or if that
6524 ** parameter is NULL, take input from ~/.sqliterc
6526 ** Returns the number of errors.
6528 static void process_sqliterc(
6529 ShellState
*p
, /* Configuration data */
6530 const char *sqliterc_override
/* Name of config file. NULL to use default */
6532 char *home_dir
= NULL
;
6533 const char *sqliterc
= sqliterc_override
;
6537 if (sqliterc
== NULL
) {
6538 home_dir
= find_home_dir(0);
6540 raw_printf(stderr
, "-- warning: cannot find home directory;"
6541 " cannot read ~/.sqliterc\n");
6544 sqlite3_initialize();
6545 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
6548 in
= fopen(sqliterc
,"rb");
6550 if( stdin_is_interactive
){
6551 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
6553 process_input(p
,in
);
6560 ** Show available command line options
6562 static const char zOptions
[] =
6563 " -ascii set output mode to 'ascii'\n"
6564 " -bail stop after hitting an error\n"
6565 " -batch force batch I/O\n"
6566 " -column set output mode to 'column'\n"
6567 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
6568 " -csv set output mode to 'csv'\n"
6569 " -echo print commands before execution\n"
6570 " -init FILENAME read/process named file\n"
6571 " -[no]header turn headers on or off\n"
6572 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6573 " -heap SIZE Size of heap for memsys3 or memsys5\n"
6575 " -help show this message\n"
6576 " -html set output mode to HTML\n"
6577 " -interactive force interactive I/O\n"
6578 " -line set output mode to 'line'\n"
6579 " -list set output mode to 'list'\n"
6580 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
6581 " -mmap N default mmap size set to N\n"
6582 #ifdef SQLITE_ENABLE_MULTIPLEX
6583 " -multiplex enable the multiplexor VFS\n"
6585 " -newline SEP set output row separator. Default: '\\n'\n"
6586 " -nullvalue TEXT set text string for NULL values. Default ''\n"
6587 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
6588 " -quote set output mode to 'quote'\n"
6589 " -separator SEP set output column separator. Default: '|'\n"
6590 " -stats print memory stats before each finalize\n"
6591 " -version show SQLite version\n"
6592 " -vfs NAME use NAME as the default VFS\n"
6593 #ifdef SQLITE_ENABLE_VFSTRACE
6594 " -vfstrace enable tracing of all VFS calls\n"
6597 static void usage(int showDetail
){
6599 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6600 "FILENAME is the name of an SQLite database. A new database is created\n"
6601 "if the file does not previously exist.\n", Argv0
);
6603 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
6605 raw_printf(stderr
, "Use the -help option for additional information\n");
6611 ** Initialize the state information in data
6613 static void main_init(ShellState
*data
) {
6614 memset(data
, 0, sizeof(*data
));
6615 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
6616 data
->autoExplain
= 1;
6617 memcpy(data
->colSeparator
,SEP_Column
, 2);
6618 memcpy(data
->rowSeparator
,SEP_Row
, 2);
6619 data
->showHeader
= 0;
6620 data
->shellFlgs
= SHFLG_Lookaside
;
6621 sqlite3_config(SQLITE_CONFIG_URI
, 1);
6622 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
6623 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
6624 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
6625 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
6629 ** Output text to the console in a font that attracts extra attention.
6632 static void printBold(const char *zText
){
6633 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
6634 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
6635 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
6636 SetConsoleTextAttribute(out
,
6637 FOREGROUND_RED
|FOREGROUND_INTENSITY
6639 printf("%s", zText
);
6640 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
6643 static void printBold(const char *zText
){
6644 printf("\033[1m%s\033[0m", zText
);
6649 ** Get the argument to an --option. Throw an error and die if no argument
6652 static char *cmdline_option_value(int argc
, char **argv
, int i
){
6654 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
6655 argv
[0], argv
[argc
-1]);
6661 #ifndef SQLITE_SHELL_IS_UTF8
6662 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6663 # define SQLITE_SHELL_IS_UTF8 (0)
6665 # define SQLITE_SHELL_IS_UTF8 (1)
6669 #if SQLITE_SHELL_IS_UTF8
6670 int SQLITE_CDECL
main(int argc
, char **argv
){
6672 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
6677 const char *zInitFile
= 0;
6680 int warnInmemoryDb
= 0;
6685 setBinaryMode(stdin
, 0);
6686 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
6687 stdin_is_interactive
= isatty(0);
6688 stdout_is_console
= isatty(1);
6690 #if USE_SYSTEM_SQLITE+0!=1
6691 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
6692 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
6693 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
6698 #if !SQLITE_SHELL_IS_UTF8
6699 sqlite3_initialize();
6700 argv
= sqlite3_malloc64(sizeof(argv
[0])*argc
);
6702 raw_printf(stderr
, "out of memory\n");
6705 for(i
=0; i
<argc
; i
++){
6706 argv
[i
] = sqlite3_win32_unicode_to_utf8(wargv
[i
]);
6708 raw_printf(stderr
, "out of memory\n");
6713 assert( argc
>=1 && argv
&& argv
[0] );
6716 /* Make sure we have a valid signal handler early, before anything
6720 signal(SIGINT
, interrupt_handler
);
6721 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
6722 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
6725 #ifdef SQLITE_SHELL_DBNAME_PROC
6727 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
6728 ** of a C-function that will provide the name of the database file. Use
6729 ** this compile-time option to embed this shell program in larger
6731 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
6732 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
6737 /* Do an initial pass through the command-line argument to locate
6738 ** the name of the database file, the name of the initialization file,
6739 ** the size of the alternative malloc heap,
6740 ** and the first command to execute.
6742 for(i
=1; i
<argc
; i
++){
6746 if( data
.zDbFilename
==0 ){
6747 data
.zDbFilename
= z
;
6749 /* Excesss arguments are interpreted as SQL (or dot-commands) and
6750 ** mean that nothing is read from stdin */
6753 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
6755 raw_printf(stderr
, "out of memory\n");
6761 if( z
[1]=='-' ) z
++;
6762 if( strcmp(z
,"-separator")==0
6763 || strcmp(z
,"-nullvalue")==0
6764 || strcmp(z
,"-newline")==0
6765 || strcmp(z
,"-cmd")==0
6767 (void)cmdline_option_value(argc
, argv
, ++i
);
6768 }else if( strcmp(z
,"-init")==0 ){
6769 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
6770 }else if( strcmp(z
,"-batch")==0 ){
6771 /* Need to check for batch mode here to so we can avoid printing
6772 ** informational messages (like from process_sqliterc) before
6773 ** we do the actual processing of arguments later in a second pass.
6775 stdin_is_interactive
= 0;
6776 }else if( strcmp(z
,"-heap")==0 ){
6777 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6779 sqlite3_int64 szHeap
;
6781 zSize
= cmdline_option_value(argc
, argv
, ++i
);
6782 szHeap
= integerValue(zSize
);
6783 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
6784 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
6786 (void)cmdline_option_value(argc
, argv
, ++i
);
6788 }else if( strcmp(z
,"-pagecache")==0 ){
6790 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
6791 if( sz
>70000 ) sz
= 70000;
6793 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
6794 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
6795 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
6796 data
.shellFlgs
|= SHFLG_Pagecache
;
6797 }else if( strcmp(z
,"-lookaside")==0 ){
6799 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
6801 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
6803 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
6804 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
6805 #ifdef SQLITE_ENABLE_VFSTRACE
6806 }else if( strcmp(z
,"-vfstrace")==0 ){
6807 extern int vfstrace_register(
6808 const char *zTraceName
,
6809 const char *zOldVfsName
,
6810 int (*xOut
)(const char*,void*),
6814 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
6816 #ifdef SQLITE_ENABLE_MULTIPLEX
6817 }else if( strcmp(z
,"-multiplex")==0 ){
6818 extern int sqlite3_multiple_initialize(const char*,int);
6819 sqlite3_multiplex_initialize(0, 1);
6821 }else if( strcmp(z
,"-mmap")==0 ){
6822 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
6823 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
6824 }else if( strcmp(z
,"-vfs")==0 ){
6825 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(cmdline_option_value(argc
,argv
,++i
));
6827 sqlite3_vfs_register(pVfs
, 1);
6829 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
6834 if( data
.zDbFilename
==0 ){
6835 #ifndef SQLITE_OMIT_MEMORYDB
6836 data
.zDbFilename
= ":memory:";
6837 warnInmemoryDb
= argc
==1;
6839 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
6845 /* Go ahead and open the database file if it already exists. If the
6846 ** file does not exist, delay opening it. This prevents empty database
6847 ** files from being created if a user mistypes the database name argument
6848 ** to the sqlite command-line tool.
6850 if( access(data
.zDbFilename
, 0)==0 ){
6854 /* Process the initialization file if there is one. If no -init option
6855 ** is given on the command line, look for a file named ~/.sqliterc and
6856 ** try to process it.
6858 process_sqliterc(&data
,zInitFile
);
6860 /* Make a second pass through the command-line argument and set
6861 ** options. This second pass is delayed until after the initialization
6862 ** file is processed so that the command-line arguments will override
6863 ** settings in the initialization file.
6865 for(i
=1; i
<argc
; i
++){
6867 if( z
[0]!='-' ) continue;
6868 if( z
[1]=='-' ){ z
++; }
6869 if( strcmp(z
,"-init")==0 ){
6871 }else if( strcmp(z
,"-html")==0 ){
6872 data
.mode
= MODE_Html
;
6873 }else if( strcmp(z
,"-list")==0 ){
6874 data
.mode
= MODE_List
;
6875 }else if( strcmp(z
,"-quote")==0 ){
6876 data
.mode
= MODE_Quote
;
6877 }else if( strcmp(z
,"-line")==0 ){
6878 data
.mode
= MODE_Line
;
6879 }else if( strcmp(z
,"-column")==0 ){
6880 data
.mode
= MODE_Column
;
6881 }else if( strcmp(z
,"-csv")==0 ){
6882 data
.mode
= MODE_Csv
;
6883 memcpy(data
.colSeparator
,",",2);
6884 }else if( strcmp(z
,"-ascii")==0 ){
6885 data
.mode
= MODE_Ascii
;
6886 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
6888 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
6890 }else if( strcmp(z
,"-separator")==0 ){
6891 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
6892 "%s",cmdline_option_value(argc
,argv
,++i
));
6893 }else if( strcmp(z
,"-newline")==0 ){
6894 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
6895 "%s",cmdline_option_value(argc
,argv
,++i
));
6896 }else if( strcmp(z
,"-nullvalue")==0 ){
6897 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
6898 "%s",cmdline_option_value(argc
,argv
,++i
));
6899 }else if( strcmp(z
,"-header")==0 ){
6900 data
.showHeader
= 1;
6901 }else if( strcmp(z
,"-noheader")==0 ){
6902 data
.showHeader
= 0;
6903 }else if( strcmp(z
,"-echo")==0 ){
6904 ShellSetFlag(&data
, SHFLG_Echo
);
6905 }else if( strcmp(z
,"-eqp")==0 ){
6907 }else if( strcmp(z
,"-eqpfull")==0 ){
6909 }else if( strcmp(z
,"-stats")==0 ){
6911 }else if( strcmp(z
,"-scanstats")==0 ){
6912 data
.scanstatsOn
= 1;
6913 }else if( strcmp(z
,"-backslash")==0 ){
6914 /* Undocumented command-line option: -backslash
6915 ** Causes C-style backslash escapes to be evaluated in SQL statements
6916 ** prior to sending the SQL into SQLite. Useful for injecting
6917 ** crazy bytes in the middle of SQL statements for testing and debugging.
6919 ShellSetFlag(&data
, SHFLG_Backslash
);
6920 }else if( strcmp(z
,"-bail")==0 ){
6922 }else if( strcmp(z
,"-version")==0 ){
6923 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
6925 }else if( strcmp(z
,"-interactive")==0 ){
6926 stdin_is_interactive
= 1;
6927 }else if( strcmp(z
,"-batch")==0 ){
6928 stdin_is_interactive
= 0;
6929 }else if( strcmp(z
,"-heap")==0 ){
6931 }else if( strcmp(z
,"-pagecache")==0 ){
6933 }else if( strcmp(z
,"-lookaside")==0 ){
6935 }else if( strcmp(z
,"-mmap")==0 ){
6937 }else if( strcmp(z
,"-vfs")==0 ){
6939 #ifdef SQLITE_ENABLE_VFSTRACE
6940 }else if( strcmp(z
,"-vfstrace")==0 ){
6943 #ifdef SQLITE_ENABLE_MULTIPLEX
6944 }else if( strcmp(z
,"-multiplex")==0 ){
6947 }else if( strcmp(z
,"-help")==0 ){
6949 }else if( strcmp(z
,"-cmd")==0 ){
6950 /* Run commands that follow -cmd first and separately from commands
6951 ** that simply appear on the command-line. This seems goofy. It would
6952 ** be better if all commands ran in the order that they appear. But
6953 ** we retain the goofy behavior for historical compatibility. */
6954 if( i
==argc
-1 ) break;
6955 z
= cmdline_option_value(argc
,argv
,++i
);
6957 rc
= do_meta_command(z
, &data
);
6958 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
6961 rc
= shell_exec(data
.db
, z
, shell_callback
, &data
, &zErrMsg
);
6963 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
6964 if( bail_on_error
) return rc
!=0 ? rc
: 1;
6966 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
6967 if( bail_on_error
) return rc
;
6971 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
6972 raw_printf(stderr
,"Use -help for a list of options.\n");
6975 data
.cMode
= data
.mode
;
6979 /* Run all arguments that do not begin with '-' as if they were separate
6980 ** command-line inputs, except for the argToSkip argument which contains
6981 ** the database filename.
6983 for(i
=0; i
<nCmd
; i
++){
6984 if( azCmd
[i
][0]=='.' ){
6985 rc
= do_meta_command(azCmd
[i
], &data
);
6986 if( rc
) return rc
==2 ? 0 : rc
;
6989 rc
= shell_exec(data
.db
, azCmd
[i
], shell_callback
, &data
, &zErrMsg
);
6991 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
6992 return rc
!=0 ? rc
: 1;
6994 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
7001 /* Run commands received from standard input
7003 if( stdin_is_interactive
){
7008 "SQLite version %s %.19s\n" /*extra-version-info*/
7009 "Enter \".help\" for usage hints.\n",
7010 sqlite3_libversion(), sqlite3_sourceid()
7012 if( warnInmemoryDb
){
7013 printf("Connected to a ");
7014 printBold("transient in-memory database");
7015 printf(".\nUse \".open FILENAME\" to reopen on a "
7016 "persistent database.\n");
7018 zHome
= find_home_dir(0);
7020 nHistory
= strlen30(zHome
) + 20;
7021 if( (zHistory
= malloc(nHistory
))!=0 ){
7022 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
7025 if( zHistory
){ shell_read_history(zHistory
); }
7026 #if HAVE_READLINE || HAVE_EDITLINE
7027 rl_attempted_completion_function
= readline_completion
;
7028 #elif HAVE_LINENOISE
7029 linenoiseSetCompletionCallback(linenoise_completion
);
7031 rc
= process_input(&data
, 0);
7033 shell_stifle_history(2000);
7034 shell_write_history(zHistory
);
7038 rc
= process_input(&data
, stdin
);
7041 set_table_name(&data
, 0);
7043 session_close_all(&data
);
7044 sqlite3_close(data
.db
);
7046 sqlite3_free(data
.zFreeOnClose
);
7048 #if !SQLITE_SHELL_IS_UTF8
7049 for(i
=0; i
<argc
; i
++) sqlite3_free(argv
[i
]);