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 ** If requested, include the SQLite compiler options file for MSVC.
23 #if defined(INCLUDE_MSVC_H)
28 ** No support for loadable extensions in VxWorks.
30 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
31 # define SQLITE_OMIT_LOAD_EXTENSION 1
35 ** Enable large-file support for fopen() and friends on unix.
37 #ifndef SQLITE_DISABLE_LFS
38 # define _LARGE_FILE 1
39 # ifndef _FILE_OFFSET_BITS
40 # define _FILE_OFFSET_BITS 64
42 # define _LARGEFILE_SOURCE 1
50 #if SQLITE_USER_AUTHENTICATION
51 # include "sqlite3userauth.h"
56 #if !defined(_WIN32) && !defined(WIN32)
58 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
62 # include <sys/types.h>
66 # include <readline/readline.h>
67 # include <readline/history.h>
71 # include <editline/readline.h>
74 #if HAVE_EDITLINE || HAVE_READLINE
76 # define shell_add_history(X) add_history(X)
77 # define shell_read_history(X) read_history(X)
78 # define shell_write_history(X) write_history(X)
79 # define shell_stifle_history(X) stifle_history(X)
80 # define shell_readline(X) readline(X)
84 # include "linenoise.h"
85 # define shell_add_history(X) linenoiseHistoryAdd(X)
86 # define shell_read_history(X) linenoiseHistoryLoad(X)
87 # define shell_write_history(X) linenoiseHistorySave(X)
88 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89 # define shell_readline(X) linenoise(X)
93 # define shell_read_history(X)
94 # define shell_write_history(X)
95 # define shell_stifle_history(X)
97 # define SHELL_USE_LOCAL_GETLINE 1
101 #if defined(_WIN32) || defined(WIN32)
104 # define isatty(h) _isatty(h)
106 # define access(f,m) _access((f),(m))
109 # define popen _popen
111 # define pclose _pclose
113 /* Make sure isatty() has a prototype. */
114 extern int isatty(int);
116 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
117 /* popen and pclose are not C89 functions and so are
118 ** sometimes omitted from the <stdio.h> header */
119 extern FILE *popen(const char*,const char*);
120 extern int pclose(FILE*);
122 # define SQLITE_OMIT_POPEN 1
126 #if defined(_WIN32_WCE)
127 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128 * thus we always assume that we have a console. That can be
129 * overridden with the -batch command line option.
134 /* ctype macros that work with signed characters */
135 #define IsSpace(X) isspace((unsigned char)X)
136 #define IsDigit(X) isdigit((unsigned char)X)
137 #define ToLower(X) (char)tolower((unsigned char)X)
139 #if defined(_WIN32) || defined(WIN32)
142 /* string conversion routines only needed on Win32 */
143 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
144 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
146 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
149 /* On Windows, we normally run with output mode of TEXT so that \n characters
150 ** are automatically translated into \r\n. However, this behavior needs
151 ** to be disabled in some cases (ex: when generating CSV output and when
152 ** rendering quoted strings that contain \n characters). The following
153 ** routines take care of that.
155 #if defined(_WIN32) || defined(WIN32)
156 static void setBinaryMode(FILE *file, int isOutput){
157 if( isOutput ) fflush(file);
158 _setmode(_fileno(file), _O_BINARY);
160 static void setTextMode(FILE *file, int isOutput){
161 if( isOutput ) fflush(file);
162 _setmode(_fileno(file), _O_TEXT);
165 # define setBinaryMode(X,Y)
166 # define setTextMode(X,Y)
170 /* True if the timer is enabled */
171 static int enableTimer = 0;
173 /* Return the current wall-clock time */
174 static sqlite3_int64 timeOfDay(void){
175 static sqlite3_vfs *clockVfs = 0;
177 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
178 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
179 clockVfs->xCurrentTimeInt64(clockVfs, &t);
182 clockVfs->xCurrentTime(clockVfs, &r);
183 t = (sqlite3_int64)(r*86400000.0);
188 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
189 #include <sys/time.h>
190 #include <sys/resource.h>
192 /* VxWorks does not support getrusage() as far as we can determine */
193 #if defined(_WRS_KERNEL) || defined(__RTP__)
195 struct timeval ru_utime; /* user CPU time used */
196 struct timeval ru_stime; /* system CPU time used */
198 #define getrusage(A,B) memset(B,0,sizeof(*B))
201 /* Saved resource information for the beginning of an operation */
202 static struct rusage sBegin; /* CPU time at start */
203 static sqlite3_int64 iBegin; /* Wall-clock time at start */
206 ** Begin timing an operation
208 static void beginTimer(void){
210 getrusage(RUSAGE_SELF, &sBegin);
211 iBegin = timeOfDay();
215 /* Return the difference of two time_structs in seconds */
216 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
217 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
218 (double)(pEnd->tv_sec - pStart->tv_sec);
222 ** Print the timing results.
224 static void endTimer(void){
226 sqlite3_int64 iEnd = timeOfDay();
228 getrusage(RUSAGE_SELF, &sEnd);
229 printf("Run Time: real %.3f user %f sys %f\n",
230 (iEnd - iBegin)*0.001,
231 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
232 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
236 #define BEGIN_TIMER beginTimer()
237 #define END_TIMER endTimer()
240 #elif (defined(_WIN32) || defined(WIN32))
242 /* Saved resource information for the beginning of an operation */
243 static HANDLE hProcess;
244 static FILETIME ftKernelBegin;
245 static FILETIME ftUserBegin;
246 static sqlite3_int64 ftWallBegin;
247 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
248 LPFILETIME, LPFILETIME);
249 static GETPROCTIMES getProcessTimesAddr = NULL;
252 ** Check to see if we have timer support. Return 1 if necessary
253 ** support found (or found previously).
255 static int hasTimer(void){
256 if( getProcessTimesAddr ){
259 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260 ** versions. See if the version we are running on has it, and if it
261 ** does, save off a pointer to it and the current process handle.
263 hProcess = GetCurrentProcess();
265 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
266 if( NULL != hinstLib ){
267 getProcessTimesAddr =
268 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
269 if( NULL != getProcessTimesAddr ){
272 FreeLibrary(hinstLib);
280 ** Begin timing an operation
282 static void beginTimer(void){
283 if( enableTimer && getProcessTimesAddr ){
284 FILETIME ftCreation, ftExit;
285 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
286 &ftKernelBegin,&ftUserBegin);
287 ftWallBegin = timeOfDay();
291 /* Return the difference of two FILETIME structs in seconds */
292 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
293 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
294 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
295 return (double) ((i64End - i64Start) / 10000000.0);
299 ** Print the timing results.
301 static void endTimer(void){
302 if( enableTimer && getProcessTimesAddr){
303 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
304 sqlite3_int64 ftWallEnd = timeOfDay();
305 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
306 printf("Run Time: real %.3f user %f sys %f\n",
307 (ftWallEnd - ftWallBegin)*0.001,
308 timeDiff(&ftUserBegin, &ftUserEnd),
309 timeDiff(&ftKernelBegin, &ftKernelEnd));
313 #define BEGIN_TIMER beginTimer()
314 #define END_TIMER endTimer()
315 #define HAS_TIMER hasTimer()
324 ** Used to prevent warnings about unused parameters
326 #define UNUSED_PARAMETER(x) (void)(x)
329 ** If the following flag is set, then command execution stops
330 ** at an error if we are not interactive.
332 static int bail_on_error = 0;
335 ** Threat stdin as an interactive input if the following variable
336 ** is true. Otherwise, assume stdin is connected to a file or pipe.
338 static int stdin_is_interactive = 1;
341 ** On Windows systems we have to know if standard output is a console
342 ** in order to translate UTF-8 into MBCS. The following variable is
343 ** true if translation is required.
345 static int stdout_is_console = 1;
348 ** The following is the open SQLite database. We make a pointer
349 ** to this database a static variable so that it can be accessed
350 ** by the SIGINT handler to interrupt database processing.
352 static sqlite3 *globalDb = 0;
355 ** True if an interrupt (Control-C) has been received.
357 static volatile int seenInterrupt = 0;
360 ** This is the name of our program. It is set in main(), used
361 ** in a number of other places, mostly for error messages.
366 ** Prompt strings. Initialized in main. Settable with
367 ** .prompt main continue
369 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
370 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
373 ** Render output like fprintf(). Except, if the output is going to the
374 ** console and if this is running on a Windows machine, translate the
375 ** output from UTF-8 into MBCS.
377 #if defined(_WIN32) || defined(WIN32)
378 void utf8_printf(FILE *out, const char *zFormat, ...){
380 va_start(ap, zFormat);
381 if( stdout_is_console && (out==stdout || out==stderr) ){
382 char *z1 = sqlite3_vmprintf(zFormat, ap);
383 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
388 vfprintf(out, zFormat, ap);
392 #elif !defined(utf8_printf)
393 # define utf8_printf fprintf
397 ** Render output like fprintf(). This should not be used on anything that
398 ** includes string formatting (e.g. "%s").
400 #if !defined(raw_printf)
401 # define raw_printf fprintf
405 ** Write I/O traces to the following stream.
407 #ifdef SQLITE_ENABLE_IOTRACE
408 static FILE *iotrace = 0;
412 ** This routine works like printf in that its first argument is a
413 ** format string and subsequent arguments are values to be substituted
414 ** in place of % fields. The result of formatting this string
415 ** is written to iotrace.
417 #ifdef SQLITE_ENABLE_IOTRACE
418 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
421 if( iotrace==0 ) return;
422 va_start(ap, zFormat);
423 z = sqlite3_vmprintf(zFormat, ap);
425 utf8_printf(iotrace, "%s", z);
432 ** Determines if a string is a number of not.
434 static int isNumber(const char *z, int *realnum){
435 if( *z=='-' || *z=='+' ) z++;
440 if( realnum ) *realnum = 0;
441 while( IsDigit(*z) ){ z++; }
444 if( !IsDigit(*z) ) return 0;
445 while( IsDigit(*z) ){ z++; }
446 if( realnum ) *realnum = 1;
448 if( *z=='e' || *z=='E' ){
450 if( *z=='+' || *z=='-' ) z++;
451 if( !IsDigit(*z) ) return 0;
452 while( IsDigit(*z) ){ z++; }
453 if( realnum ) *realnum = 1;
459 ** Compute a string length that is limited to what can be stored in
460 ** lower 30 bits of a 32-bit signed integer.
462 static int strlen30(const char *z){
464 while( *z2 ){ z2++; }
465 return 0x3fffffff & (int)(z2 - z);
469 ** This routine reads a line of text from FILE in, stores
470 ** the text in memory obtained from malloc() and returns a pointer
471 ** to the text. NULL is returned at end of file, or if malloc()
474 ** If zLine is not NULL then it is a malloced buffer returned from
475 ** a previous call to this routine that may be reused.
477 static char *local_getline(char *zLine, FILE *in){
478 int nLine = zLine==0 ? 0 : 100;
483 nLine = nLine*2 + 100;
484 zLine = realloc(zLine, nLine);
485 if( zLine==0 ) return 0;
487 if( fgets(&zLine[n], nLine - n, in)==0 ){
495 while( zLine[n] ) n++;
496 if( n>0 && zLine[n-1]=='\n' ){
498 if( n>0 && zLine[n-1]=='\r' ) n--;
503 #if defined(_WIN32) || defined(WIN32)
504 /* For interactive input on Windows systems, translate the
505 ** multi-byte characterset characters into UTF-8. */
506 if( stdin_is_interactive && in==stdin ){
507 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
509 int nTrans = strlen30(zTrans)+1;
511 zLine = realloc(zLine, nTrans);
513 sqlite3_free(zTrans);
517 memcpy(zLine, zTrans, nTrans);
518 sqlite3_free(zTrans);
521 #endif /* defined(_WIN32) || defined(WIN32) */
526 ** Retrieve a single line of input text.
528 ** If in==0 then read from standard input and prompt before each line.
529 ** If isContinuation is true, then a continuation prompt is appropriate.
530 ** If isContinuation is zero, then the main prompt should be used.
532 ** If zPrior is not NULL then it is a buffer from a prior call to this
533 ** routine that can be reused.
535 ** The result is stored in space obtained from malloc() and must either
536 ** be freed by the caller or else passed back into this routine via the
537 ** zPrior argument for reuse.
539 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
543 zResult = local_getline(zPrior, in);
545 zPrompt = isContinuation ? continuePrompt : mainPrompt;
546 #if SHELL_USE_LOCAL_GETLINE
547 printf("%s", zPrompt);
549 zResult = local_getline(zPrior, stdin);
552 zResult = shell_readline(zPrompt);
553 if( zResult && *zResult ) shell_add_history(zResult);
559 ** A variable length string to which one can append text.
561 typedef struct ShellText ShellText;
569 ** Initialize and destroy a ShellText object
571 static void initText(ShellText *p){
572 memset(p, 0, sizeof(*p));
574 static void freeText(ShellText *p){
579 /* zIn is either a pointer to a NULL-terminated string in memory obtained
580 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
581 ** added to zIn, and the result returned in memory obtained from malloc().
582 ** zIn, if it was not NULL, is freed.
584 ** If the third argument, quote, is not '\0', then it is used as a
585 ** quote character for zAppend.
587 static void appendText(ShellText *p, char const *zAppend, char quote){
590 int nAppend = strlen30(zAppend);
592 len = nAppend+p->n+1;
595 for(i=0; i<nAppend; i++){
596 if( zAppend[i]==quote ) len++;
600 if( p->n+len>=p->nAlloc ){
601 p->nAlloc = p->nAlloc*2 + len + 20;
602 p->z = realloc(p->z, p->nAlloc);
604 memset(p, 0, sizeof(*p));
610 char *zCsr = p->z+p->n;
612 for(i=0; i<nAppend; i++){
613 *zCsr++ = zAppend[i];
614 if( zAppend[i]==quote ) *zCsr++ = quote;
617 p->n = (int)(zCsr - p->z);
620 memcpy(p->z+p->n, zAppend, nAppend);
627 ** Attempt to determine if identifier zName needs to be quoted, either
628 ** because it contains non-alphanumeric characters, or because it is an
629 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
630 ** that quoting is required.
632 ** Return '"' if quoting is required. Return 0 if no quoting is required.
634 static char quoteChar(const char *zName){
635 /* All SQLite keywords, in alphabetical order */
636 static const char *azKeywords[] = {
637 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
638 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
639 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
640 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
641 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
642 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
643 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
644 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
645 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
646 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
647 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
648 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
649 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
650 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
651 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
652 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
653 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
656 int i, lwr, upr, mid, c;
657 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
658 for(i=0; zName[i]; i++){
659 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
662 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
665 c = sqlite3_stricmp(azKeywords[mid], zName);
666 if( c==0 ) return '"';
676 /******************************************************************************
677 ** SHA3 hash implementation copied from ../ext/misc/shathree.c
679 typedef sqlite3_uint64 u64;
681 ** Macros to determine whether the machine is big or little endian,
682 ** and whether or not that determination is run-time or compile-time.
684 ** For best performance, an attempt is made to guess at the byte-order
685 ** using C-preprocessor macros. If that is unsuccessful, or if
686 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
689 #ifndef SHA3_BYTEORDER
690 # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
691 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
692 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
694 # define SHA3_BYTEORDER 1234
695 # elif defined(sparc) || defined(__ppc__)
696 # define SHA3_BYTEORDER 4321
698 # define SHA3_BYTEORDER 0
704 ** State structure for a SHA3 hash in progress
706 typedef struct SHA3Context SHA3Context;
709 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
710 unsigned char x[1600]; /* ... or 1600 bytes */
712 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
713 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
714 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
718 ** A single step of the Keccak mixing function for a 1600-bit state
720 static void KeccakF1600Step(SHA3Context *p){
722 u64 B0, B1, B2, B3, B4;
723 u64 C0, C1, C2, C3, C4;
724 u64 D0, D1, D2, D3, D4;
725 static const u64 RC[] = {
726 0x0000000000000001ULL, 0x0000000000008082ULL,
727 0x800000000000808aULL, 0x8000000080008000ULL,
728 0x000000000000808bULL, 0x0000000080000001ULL,
729 0x8000000080008081ULL, 0x8000000000008009ULL,
730 0x000000000000008aULL, 0x0000000000000088ULL,
731 0x0000000080008009ULL, 0x000000008000000aULL,
732 0x000000008000808bULL, 0x800000000000008bULL,
733 0x8000000000008089ULL, 0x8000000000008003ULL,
734 0x8000000000008002ULL, 0x8000000000000080ULL,
735 0x000000000000800aULL, 0x800000008000000aULL,
736 0x8000000080008081ULL, 0x8000000000008080ULL,
737 0x0000000080000001ULL, 0x8000000080008008ULL
739 # define A00 (p->u.s[0])
740 # define A01 (p->u.s[1])
741 # define A02 (p->u.s[2])
742 # define A03 (p->u.s[3])
743 # define A04 (p->u.s[4])
744 # define A10 (p->u.s[5])
745 # define A11 (p->u.s[6])
746 # define A12 (p->u.s[7])
747 # define A13 (p->u.s[8])
748 # define A14 (p->u.s[9])
749 # define A20 (p->u.s[10])
750 # define A21 (p->u.s[11])
751 # define A22 (p->u.s[12])
752 # define A23 (p->u.s[13])
753 # define A24 (p->u.s[14])
754 # define A30 (p->u.s[15])
755 # define A31 (p->u.s[16])
756 # define A32 (p->u.s[17])
757 # define A33 (p->u.s[18])
758 # define A34 (p->u.s[19])
759 # define A40 (p->u.s[20])
760 # define A41 (p->u.s[21])
761 # define A42 (p->u.s[22])
762 # define A43 (p->u.s[23])
763 # define A44 (p->u.s[24])
764 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
766 for(i=0; i<24; i+=4){
767 C0 = A00^A10^A20^A30^A40;
768 C1 = A01^A11^A21^A31^A41;
769 C2 = A02^A12^A22^A32^A42;
770 C3 = A03^A13^A23^A33^A43;
771 C4 = A04^A14^A24^A34^A44;
772 D0 = C4^ROL64(C1, 1);
773 D1 = C0^ROL64(C2, 1);
774 D2 = C1^ROL64(C3, 1);
775 D3 = C2^ROL64(C4, 1);
776 D4 = C3^ROL64(C0, 1);
779 B1 = ROL64((A11^D1), 44);
780 B2 = ROL64((A22^D2), 43);
781 B3 = ROL64((A33^D3), 21);
782 B4 = ROL64((A44^D4), 14);
783 A00 = B0 ^((~B1)& B2 );
785 A11 = B1 ^((~B2)& B3 );
786 A22 = B2 ^((~B3)& B4 );
787 A33 = B3 ^((~B4)& B0 );
788 A44 = B4 ^((~B0)& B1 );
790 B2 = ROL64((A20^D0), 3);
791 B3 = ROL64((A31^D1), 45);
792 B4 = ROL64((A42^D2), 61);
793 B0 = ROL64((A03^D3), 28);
794 B1 = ROL64((A14^D4), 20);
795 A20 = B0 ^((~B1)& B2 );
796 A31 = B1 ^((~B2)& B3 );
797 A42 = B2 ^((~B3)& B4 );
798 A03 = B3 ^((~B4)& B0 );
799 A14 = B4 ^((~B0)& B1 );
801 B4 = ROL64((A40^D0), 18);
802 B0 = ROL64((A01^D1), 1);
803 B1 = ROL64((A12^D2), 6);
804 B2 = ROL64((A23^D3), 25);
805 B3 = ROL64((A34^D4), 8);
806 A40 = B0 ^((~B1)& B2 );
807 A01 = B1 ^((~B2)& B3 );
808 A12 = B2 ^((~B3)& B4 );
809 A23 = B3 ^((~B4)& B0 );
810 A34 = B4 ^((~B0)& B1 );
812 B1 = ROL64((A10^D0), 36);
813 B2 = ROL64((A21^D1), 10);
814 B3 = ROL64((A32^D2), 15);
815 B4 = ROL64((A43^D3), 56);
816 B0 = ROL64((A04^D4), 27);
817 A10 = B0 ^((~B1)& B2 );
818 A21 = B1 ^((~B2)& B3 );
819 A32 = B2 ^((~B3)& B4 );
820 A43 = B3 ^((~B4)& B0 );
821 A04 = B4 ^((~B0)& B1 );
823 B3 = ROL64((A30^D0), 41);
824 B4 = ROL64((A41^D1), 2);
825 B0 = ROL64((A02^D2), 62);
826 B1 = ROL64((A13^D3), 55);
827 B2 = ROL64((A24^D4), 39);
828 A30 = B0 ^((~B1)& B2 );
829 A41 = B1 ^((~B2)& B3 );
830 A02 = B2 ^((~B3)& B4 );
831 A13 = B3 ^((~B4)& B0 );
832 A24 = B4 ^((~B0)& B1 );
834 C0 = A00^A20^A40^A10^A30;
835 C1 = A11^A31^A01^A21^A41;
836 C2 = A22^A42^A12^A32^A02;
837 C3 = A33^A03^A23^A43^A13;
838 C4 = A44^A14^A34^A04^A24;
839 D0 = C4^ROL64(C1, 1);
840 D1 = C0^ROL64(C2, 1);
841 D2 = C1^ROL64(C3, 1);
842 D3 = C2^ROL64(C4, 1);
843 D4 = C3^ROL64(C0, 1);
846 B1 = ROL64((A31^D1), 44);
847 B2 = ROL64((A12^D2), 43);
848 B3 = ROL64((A43^D3), 21);
849 B4 = ROL64((A24^D4), 14);
850 A00 = B0 ^((~B1)& B2 );
852 A31 = B1 ^((~B2)& B3 );
853 A12 = B2 ^((~B3)& B4 );
854 A43 = B3 ^((~B4)& B0 );
855 A24 = B4 ^((~B0)& B1 );
857 B2 = ROL64((A40^D0), 3);
858 B3 = ROL64((A21^D1), 45);
859 B4 = ROL64((A02^D2), 61);
860 B0 = ROL64((A33^D3), 28);
861 B1 = ROL64((A14^D4), 20);
862 A40 = B0 ^((~B1)& B2 );
863 A21 = B1 ^((~B2)& B3 );
864 A02 = B2 ^((~B3)& B4 );
865 A33 = B3 ^((~B4)& B0 );
866 A14 = B4 ^((~B0)& B1 );
868 B4 = ROL64((A30^D0), 18);
869 B0 = ROL64((A11^D1), 1);
870 B1 = ROL64((A42^D2), 6);
871 B2 = ROL64((A23^D3), 25);
872 B3 = ROL64((A04^D4), 8);
873 A30 = B0 ^((~B1)& B2 );
874 A11 = B1 ^((~B2)& B3 );
875 A42 = B2 ^((~B3)& B4 );
876 A23 = B3 ^((~B4)& B0 );
877 A04 = B4 ^((~B0)& B1 );
879 B1 = ROL64((A20^D0), 36);
880 B2 = ROL64((A01^D1), 10);
881 B3 = ROL64((A32^D2), 15);
882 B4 = ROL64((A13^D3), 56);
883 B0 = ROL64((A44^D4), 27);
884 A20 = B0 ^((~B1)& B2 );
885 A01 = B1 ^((~B2)& B3 );
886 A32 = B2 ^((~B3)& B4 );
887 A13 = B3 ^((~B4)& B0 );
888 A44 = B4 ^((~B0)& B1 );
890 B3 = ROL64((A10^D0), 41);
891 B4 = ROL64((A41^D1), 2);
892 B0 = ROL64((A22^D2), 62);
893 B1 = ROL64((A03^D3), 55);
894 B2 = ROL64((A34^D4), 39);
895 A10 = B0 ^((~B1)& B2 );
896 A41 = B1 ^((~B2)& B3 );
897 A22 = B2 ^((~B3)& B4 );
898 A03 = B3 ^((~B4)& B0 );
899 A34 = B4 ^((~B0)& B1 );
901 C0 = A00^A40^A30^A20^A10;
902 C1 = A31^A21^A11^A01^A41;
903 C2 = A12^A02^A42^A32^A22;
904 C3 = A43^A33^A23^A13^A03;
905 C4 = A24^A14^A04^A44^A34;
906 D0 = C4^ROL64(C1, 1);
907 D1 = C0^ROL64(C2, 1);
908 D2 = C1^ROL64(C3, 1);
909 D3 = C2^ROL64(C4, 1);
910 D4 = C3^ROL64(C0, 1);
913 B1 = ROL64((A21^D1), 44);
914 B2 = ROL64((A42^D2), 43);
915 B3 = ROL64((A13^D3), 21);
916 B4 = ROL64((A34^D4), 14);
917 A00 = B0 ^((~B1)& B2 );
919 A21 = B1 ^((~B2)& B3 );
920 A42 = B2 ^((~B3)& B4 );
921 A13 = B3 ^((~B4)& B0 );
922 A34 = B4 ^((~B0)& B1 );
924 B2 = ROL64((A30^D0), 3);
925 B3 = ROL64((A01^D1), 45);
926 B4 = ROL64((A22^D2), 61);
927 B0 = ROL64((A43^D3), 28);
928 B1 = ROL64((A14^D4), 20);
929 A30 = B0 ^((~B1)& B2 );
930 A01 = B1 ^((~B2)& B3 );
931 A22 = B2 ^((~B3)& B4 );
932 A43 = B3 ^((~B4)& B0 );
933 A14 = B4 ^((~B0)& B1 );
935 B4 = ROL64((A10^D0), 18);
936 B0 = ROL64((A31^D1), 1);
937 B1 = ROL64((A02^D2), 6);
938 B2 = ROL64((A23^D3), 25);
939 B3 = ROL64((A44^D4), 8);
940 A10 = B0 ^((~B1)& B2 );
941 A31 = B1 ^((~B2)& B3 );
942 A02 = B2 ^((~B3)& B4 );
943 A23 = B3 ^((~B4)& B0 );
944 A44 = B4 ^((~B0)& B1 );
946 B1 = ROL64((A40^D0), 36);
947 B2 = ROL64((A11^D1), 10);
948 B3 = ROL64((A32^D2), 15);
949 B4 = ROL64((A03^D3), 56);
950 B0 = ROL64((A24^D4), 27);
951 A40 = B0 ^((~B1)& B2 );
952 A11 = B1 ^((~B2)& B3 );
953 A32 = B2 ^((~B3)& B4 );
954 A03 = B3 ^((~B4)& B0 );
955 A24 = B4 ^((~B0)& B1 );
957 B3 = ROL64((A20^D0), 41);
958 B4 = ROL64((A41^D1), 2);
959 B0 = ROL64((A12^D2), 62);
960 B1 = ROL64((A33^D3), 55);
961 B2 = ROL64((A04^D4), 39);
962 A20 = B0 ^((~B1)& B2 );
963 A41 = B1 ^((~B2)& B3 );
964 A12 = B2 ^((~B3)& B4 );
965 A33 = B3 ^((~B4)& B0 );
966 A04 = B4 ^((~B0)& B1 );
968 C0 = A00^A30^A10^A40^A20;
969 C1 = A21^A01^A31^A11^A41;
970 C2 = A42^A22^A02^A32^A12;
971 C3 = A13^A43^A23^A03^A33;
972 C4 = A34^A14^A44^A24^A04;
973 D0 = C4^ROL64(C1, 1);
974 D1 = C0^ROL64(C2, 1);
975 D2 = C1^ROL64(C3, 1);
976 D3 = C2^ROL64(C4, 1);
977 D4 = C3^ROL64(C0, 1);
980 B1 = ROL64((A01^D1), 44);
981 B2 = ROL64((A02^D2), 43);
982 B3 = ROL64((A03^D3), 21);
983 B4 = ROL64((A04^D4), 14);
984 A00 = B0 ^((~B1)& B2 );
986 A01 = B1 ^((~B2)& B3 );
987 A02 = B2 ^((~B3)& B4 );
988 A03 = B3 ^((~B4)& B0 );
989 A04 = B4 ^((~B0)& B1 );
991 B2 = ROL64((A10^D0), 3);
992 B3 = ROL64((A11^D1), 45);
993 B4 = ROL64((A12^D2), 61);
994 B0 = ROL64((A13^D3), 28);
995 B1 = ROL64((A14^D4), 20);
996 A10 = B0 ^((~B1)& B2 );
997 A11 = B1 ^((~B2)& B3 );
998 A12 = B2 ^((~B3)& B4 );
999 A13 = B3 ^((~B4)& B0 );
1000 A14 = B4 ^((~B0)& B1 );
1002 B4 = ROL64((A20^D0), 18);
1003 B0 = ROL64((A21^D1), 1);
1004 B1 = ROL64((A22^D2), 6);
1005 B2 = ROL64((A23^D3), 25);
1006 B3 = ROL64((A24^D4), 8);
1007 A20 = B0 ^((~B1)& B2 );
1008 A21 = B1 ^((~B2)& B3 );
1009 A22 = B2 ^((~B3)& B4 );
1010 A23 = B3 ^((~B4)& B0 );
1011 A24 = B4 ^((~B0)& B1 );
1013 B1 = ROL64((A30^D0), 36);
1014 B2 = ROL64((A31^D1), 10);
1015 B3 = ROL64((A32^D2), 15);
1016 B4 = ROL64((A33^D3), 56);
1017 B0 = ROL64((A34^D4), 27);
1018 A30 = B0 ^((~B1)& B2 );
1019 A31 = B1 ^((~B2)& B3 );
1020 A32 = B2 ^((~B3)& B4 );
1021 A33 = B3 ^((~B4)& B0 );
1022 A34 = B4 ^((~B0)& B1 );
1024 B3 = ROL64((A40^D0), 41);
1025 B4 = ROL64((A41^D1), 2);
1026 B0 = ROL64((A42^D2), 62);
1027 B1 = ROL64((A43^D3), 55);
1028 B2 = ROL64((A44^D4), 39);
1029 A40 = B0 ^((~B1)& B2 );
1030 A41 = B1 ^((~B2)& B3 );
1031 A42 = B2 ^((~B3)& B4 );
1032 A43 = B3 ^((~B4)& B0 );
1033 A44 = B4 ^((~B0)& B1 );
1038 ** Initialize a new hash. iSize determines the size of the hash
1039 ** in bits and should be one of 224, 256, 384, or 512. Or iSize
1040 ** can be zero to use the default hash size of 256 bits.
1042 static void SHA3Init(SHA3Context *p, int iSize){
1043 memset(p, 0, sizeof(*p));
1044 if( iSize>=128 && iSize<=512 ){
1045 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1047 p->nRate = (1600 - 2*256)/8;
1049 #if SHA3_BYTEORDER==1234
1050 /* Known to be little-endian at compile-time. No-op */
1051 #elif SHA3_BYTEORDER==4321
1052 p->ixMask = 7; /* Big-endian */
1055 static unsigned int one = 1;
1056 if( 1==*(unsigned char*)&one ){
1057 /* Little endian. No byte swapping. */
1060 /* Big endian. Byte swap. */
1068 ** Make consecutive calls to the SHA3Update function to add new content
1071 static void SHA3Update(
1073 const unsigned char *aData,
1077 #if SHA3_BYTEORDER==1234
1078 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1079 for(; i+7<nData; i+=8){
1080 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1082 if( p->nLoaded>=p->nRate ){
1089 for(; i<nData; i++){
1090 #if SHA3_BYTEORDER==1234
1091 p->u.x[p->nLoaded] ^= aData[i];
1092 #elif SHA3_BYTEORDER==4321
1093 p->u.x[p->nLoaded^0x07] ^= aData[i];
1095 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1098 if( p->nLoaded==p->nRate ){
1106 ** After all content has been added, invoke SHA3Final() to compute
1107 ** the final hash. The function returns a pointer to the binary
1110 static unsigned char *SHA3Final(SHA3Context *p){
1112 if( p->nLoaded==p->nRate-1 ){
1113 const unsigned char c1 = 0x86;
1114 SHA3Update(p, &c1, 1);
1116 const unsigned char c2 = 0x06;
1117 const unsigned char c3 = 0x80;
1118 SHA3Update(p, &c2, 1);
1119 p->nLoaded = p->nRate - 1;
1120 SHA3Update(p, &c3, 1);
1122 for(i=0; i<p->nRate; i++){
1123 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1125 return &p->u.x[p->nRate];
1129 ** Implementation of the sha3(X,SIZE) function.
1131 ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
1132 ** size is 256. If X is a BLOB, it is hashed as is.
1133 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1134 ** and the string is hashed without the trailing 0x00 terminator. The hash
1135 ** of a NULL value is NULL.
1137 static void sha3Func(
1138 sqlite3_context *context,
1140 sqlite3_value **argv
1143 int eType = sqlite3_value_type(argv[0]);
1144 int nByte = sqlite3_value_bytes(argv[0]);
1149 iSize = sqlite3_value_int(argv[1]);
1150 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1151 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1156 if( eType==SQLITE_NULL ) return;
1157 SHA3Init(&cx, iSize);
1158 if( eType==SQLITE_BLOB ){
1159 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1161 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1163 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1166 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1167 ** of 50 bytes and add it to the hash.
1169 static void hash_step_vformat(
1170 SHA3Context *p, /* Add content to this context */
1171 const char *zFormat,
1177 va_start(ap, zFormat);
1178 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1180 n = (int)strlen(zBuf);
1181 SHA3Update(p, (unsigned char*)zBuf, n);
1185 ** Implementation of the sha3_query(SQL,SIZE) function.
1187 ** This function compiles and runs the SQL statement(s) given in the
1188 ** argument. The results are hashed using a SIZE-bit SHA3. The default
1191 ** The format of the byte stream that is hashed is summarized as follows:
1201 ** <sql> is the original SQL text for each statement run and <n> is
1202 ** the size of that text. The SQL text is UTF-8. A single R character
1203 ** occurs before the start of each row. N means a NULL value.
1204 ** I mean an 8-byte little-endian integer <int>. F is a floating point
1205 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1206 ** B means blobs of <size> bytes. T means text rendered as <size>
1207 ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1210 ** For each SQL statement in the X input, there is one S segment. Each
1211 ** S segment is followed by zero or more R segments, one for each row in the
1212 ** result set. After each R, there are one or more N, I, F, B, or T segments,
1213 ** one for each column in the result set. Segments are concatentated directly
1214 ** with no delimiters of any kind.
1216 static void sha3QueryFunc(
1217 sqlite3_context *context,
1219 sqlite3_value **argv
1221 sqlite3 *db = sqlite3_context_db_handle(context);
1222 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1223 sqlite3_stmt *pStmt = 0;
1224 int nCol; /* Number of columns in the result set */
1225 int i; /* Loop counter */
1235 iSize = sqlite3_value_int(argv[1]);
1236 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1237 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1242 if( zSql==0 ) return;
1243 SHA3Init(&cx, iSize);
1245 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1247 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1248 zSql, sqlite3_errmsg(db));
1249 sqlite3_finalize(pStmt);
1250 sqlite3_result_error(context, zMsg, -1);
1254 if( !sqlite3_stmt_readonly(pStmt) ){
1255 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1256 sqlite3_finalize(pStmt);
1257 sqlite3_result_error(context, zMsg, -1);
1261 nCol = sqlite3_column_count(pStmt);
1262 z = sqlite3_sql(pStmt);
1264 sqlite3_finalize(pStmt);
1268 hash_step_vformat(&cx,"S%d:",n);
1269 SHA3Update(&cx,(unsigned char*)z,n);
1271 /* Compute a hash over the result of the query */
1272 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1273 SHA3Update(&cx,(const unsigned char*)"R",1);
1274 for(i=0; i<nCol; i++){
1275 switch( sqlite3_column_type(pStmt,i) ){
1277 SHA3Update(&cx, (const unsigned char*)"N",1);
1280 case SQLITE_INTEGER: {
1284 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1286 for(j=8; j>=1; j--){
1291 SHA3Update(&cx, x, 9);
1294 case SQLITE_FLOAT: {
1298 double r = sqlite3_column_double(pStmt,i);
1300 for(j=8; j>=1; j--){
1305 SHA3Update(&cx,x,9);
1309 int n2 = sqlite3_column_bytes(pStmt, i);
1310 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1311 hash_step_vformat(&cx,"T%d:",n2);
1312 SHA3Update(&cx, z2, n2);
1316 int n2 = sqlite3_column_bytes(pStmt, i);
1317 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1318 hash_step_vformat(&cx,"B%d:",n2);
1319 SHA3Update(&cx, z2, n2);
1325 sqlite3_finalize(pStmt);
1327 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1329 /* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1330 ********************************************************************************/
1332 #if defined(SQLITE_ENABLE_SESSION)
1334 ** State information for a single open session
1336 typedef struct OpenSession OpenSession;
1337 struct OpenSession {
1338 char *zName; /* Symbolic name for this session */
1339 int nFilter; /* Number of xFilter rejection GLOB patterns */
1340 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1341 sqlite3_session *p; /* The open session */
1346 ** Shell output mode information from before ".explain on",
1347 ** saved so that it can be restored by ".explain off"
1349 typedef struct SavedModeInfo SavedModeInfo;
1350 struct SavedModeInfo {
1351 int valid; /* Is there legit data in here? */
1352 int mode; /* Mode prior to ".explain on" */
1353 int showHeader; /* The ".header" setting prior to ".explain on" */
1354 int colWidth[100]; /* Column widths prior to ".explain on" */
1358 ** State information about the database connection is contained in an
1359 ** instance of the following structure.
1361 typedef struct ShellState ShellState;
1363 sqlite3 *db; /* The database */
1364 int autoExplain; /* Automatically turn on .explain mode */
1365 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1366 int statsOn; /* True to display memory stats before each finalize */
1367 int scanstatsOn; /* True to display scan stats before each finalize */
1368 int outCount; /* Revert to stdout when reaching zero */
1369 int cnt; /* Number of records displayed so far */
1370 FILE *out; /* Write results here */
1371 FILE *traceOut; /* Output for sqlite3_trace() */
1372 int nErr; /* Number of errors seen */
1373 int mode; /* An output mode setting */
1374 int cMode; /* temporary output mode for the current query */
1375 int normalMode; /* Output mode before ".explain on" */
1376 int writableSchema; /* True if PRAGMA writable_schema=ON */
1377 int showHeader; /* True to show column names in List or Column mode */
1378 int nCheck; /* Number of ".check" commands run */
1379 unsigned shellFlgs; /* Various flags */
1380 char *zDestTable; /* Name of destination table when MODE_Insert */
1381 char zTestcase[30]; /* Name of current test case */
1382 char colSeparator[20]; /* Column separator character for several modes */
1383 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1384 int colWidth[100]; /* Requested width of each column when in column mode*/
1385 int actualWidth[100]; /* Actual width of each column */
1386 char nullValue[20]; /* The text to print when a NULL comes back from
1388 char outfile[FILENAME_MAX]; /* Filename for *out */
1389 const char *zDbFilename; /* name of the database file */
1390 char *zFreeOnClose; /* Filename to free when closing */
1391 const char *zVfs; /* Name of VFS to use */
1392 sqlite3_stmt *pStmt; /* Current statement if any. */
1393 FILE *pLog; /* Write log output here */
1394 int *aiIndent; /* Array of indents used in MODE_Explain */
1395 int nIndent; /* Size of array aiIndent[] */
1396 int iIndent; /* Index of current op in aiIndent[] */
1397 #if defined(SQLITE_ENABLE_SESSION)
1398 int nSession; /* Number of active sessions */
1399 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1404 ** These are the allowed shellFlgs values
1406 #define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1407 #define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1408 #define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1409 #define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1410 #define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1411 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1412 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1415 ** Macros for testing and setting shellFlgs
1417 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1418 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1419 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1422 ** These are the allowed modes.
1424 #define MODE_Line 0 /* One column per line. Blank line between records */
1425 #define MODE_Column 1 /* One record per line in neat columns */
1426 #define MODE_List 2 /* One record per line with a separator */
1427 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1428 #define MODE_Html 4 /* Generate an XHTML table */
1429 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1430 #define MODE_Quote 6 /* Quote values as for SQL */
1431 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1432 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1433 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1434 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1435 #define MODE_Pretty 11 /* Pretty-print schemas */
1437 static const char *modeDescr[] = {
1453 ** These are the column/row/line separators used by the various
1454 ** import/export modes.
1456 #define SEP_Column "|"
1457 #define SEP_Row "\n"
1458 #define SEP_Tab "\t"
1459 #define SEP_Space " "
1460 #define SEP_Comma ","
1461 #define SEP_CrLf "\r\n"
1462 #define SEP_Unit "\x1F"
1463 #define SEP_Record "\x1E"
1466 ** Number of elements in an array
1468 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
1471 ** A callback for the sqlite3_log() interface.
1473 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1474 ShellState *p = (ShellState*)pArg;
1475 if( p->pLog==0 ) return;
1476 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1481 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1483 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1485 char *zBlob = (char *)pBlob;
1486 raw_printf(out,"X'");
1487 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1488 raw_printf(out,"'");
1492 ** Output the given string as a quoted string using SQL quoting conventions.
1494 ** The "\n" and "\r" characters are converted to char(10) and char(13)
1495 ** to prevent them from being transformed by end-of-line translators.
1497 static void output_quoted_string(FILE *out, const char *z){
1500 setBinaryMode(out, 1);
1501 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1503 utf8_printf(out,"'%s'",z);
1508 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1512 if( bStarted ) raw_printf(out, "||");
1513 raw_printf(out, "'");
1516 utf8_printf(out, "%.*s", i, z);
1521 raw_printf(out, "'");
1525 raw_printf(out, "'");
1531 for(i=0; (c = z[i])=='\r' || c=='\n'; i++){
1532 if( bStarted ) raw_printf(out, "||");
1533 raw_printf(out, "char(%d)", c);
1538 if( inQuote ) raw_printf(out, "'");
1540 setTextMode(out, 1);
1544 ** Output the given string as a quoted according to C or TCL quoting rules.
1546 static void output_c_string(FILE *out, const char *z){
1549 while( (c = *(z++))!=0 ){
1556 }else if( c=='\t' ){
1559 }else if( c=='\n' ){
1562 }else if( c=='\r' ){
1565 }else if( !isprint(c&0xff) ){
1566 raw_printf(out, "\\%03o", c&0xff);
1575 ** Output the given string with characters that are special to
1578 static void output_html_string(FILE *out, const char *z){
1590 utf8_printf(out,"%.*s",i,z);
1593 raw_printf(out,"<");
1594 }else if( z[i]=='&' ){
1595 raw_printf(out,"&");
1596 }else if( z[i]=='>' ){
1597 raw_printf(out,">");
1598 }else if( z[i]=='\"' ){
1599 raw_printf(out,""");
1600 }else if( z[i]=='\'' ){
1601 raw_printf(out,"'");
1610 ** If a field contains any character identified by a 1 in the following
1611 ** array, then the string must be quoted for CSV.
1613 static const char needCsvQuote[] = {
1614 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1615 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1616 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1617 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1618 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1619 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1620 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1621 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1622 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1623 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1624 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1625 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1626 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1627 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1628 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1629 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1633 ** Output a single term of CSV. Actually, p->colSeparator is used for
1634 ** the separator, which may or may not be a comma. p->nullValue is
1635 ** the null value. Strings are quoted if necessary. The separator
1636 ** is only issued if bSep is true.
1638 static void output_csv(ShellState *p, const char *z, int bSep){
1641 utf8_printf(out,"%s",p->nullValue);
1644 int nSep = strlen30(p->colSeparator);
1645 for(i=0; z[i]; i++){
1646 if( needCsvQuote[((unsigned char*)z)[i]]
1647 || (z[i]==p->colSeparator[0] &&
1648 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1655 for(i=0; z[i]; i++){
1656 if( z[i]=='"' ) putc('"', out);
1661 utf8_printf(out, "%s", z);
1665 utf8_printf(p->out, "%s", p->colSeparator);
1671 ** This routine runs when the user presses Ctrl-C
1673 static void interrupt_handler(int NotUsed){
1674 UNUSED_PARAMETER(NotUsed);
1676 if( seenInterrupt>2 ) exit(1);
1677 if( globalDb ) sqlite3_interrupt(globalDb);
1681 #ifndef SQLITE_OMIT_AUTHORIZATION
1683 ** When the ".auth ON" is set, the following authorizer callback is
1684 ** invoked. It always returns SQLITE_OK.
1686 static int shellAuth(
1694 ShellState *p = (ShellState*)pClientData;
1695 static const char *azAction[] = { 0,
1696 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1697 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1698 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1699 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1700 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1701 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1702 "PRAGMA", "READ", "SELECT",
1703 "TRANSACTION", "UPDATE", "ATTACH",
1704 "DETACH", "ALTER_TABLE", "REINDEX",
1705 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1706 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1714 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1716 raw_printf(p->out, " ");
1718 output_c_string(p->out, az[i]);
1720 raw_printf(p->out, "NULL");
1723 raw_printf(p->out, "\n");
1729 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1731 ** This routine converts some CREATE TABLE statements for shadow tables
1732 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1734 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1735 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1736 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1738 utf8_printf(out, "%s%s", z, zTail);
1741 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1744 printSchemaLine(out, z, zTail);
1749 ** This is the callback routine that the shell
1750 ** invokes for each row of a query result.
1752 static int shell_callback(
1754 int nArg, /* Number of result columns */
1755 char **azArg, /* Text of each result column */
1756 char **azCol, /* Column names */
1757 int *aiType /* Column types */
1760 ShellState *p = (ShellState*)pArg;
1765 if( azArg==0 ) break;
1766 for(i=0; i<nArg; i++){
1767 int len = strlen30(azCol[i] ? azCol[i] : "");
1768 if( len>w ) w = len;
1770 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1771 for(i=0; i<nArg; i++){
1772 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1773 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1779 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1780 const int *colWidth;
1783 if( p->cMode==MODE_Column ){
1784 colWidth = p->colWidth;
1785 showHdr = p->showHeader;
1786 rowSep = p->rowSeparator;
1788 colWidth = aExplainWidths;
1793 for(i=0; i<nArg; i++){
1795 if( i<ArraySize(p->colWidth) ){
1801 w = strlen30(azCol[i] ? azCol[i] : "");
1803 n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
1806 if( i<ArraySize(p->actualWidth) ){
1807 p->actualWidth[i] = w;
1811 utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
1812 i==nArg-1 ? rowSep : " ");
1814 utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
1815 i==nArg-1 ? rowSep : " ");
1820 for(i=0; i<nArg; i++){
1822 if( i<ArraySize(p->actualWidth) ){
1823 w = p->actualWidth[i];
1828 utf8_printf(p->out,"%-*.*s%s",w,w,
1829 "----------------------------------------------------------"
1830 "----------------------------------------------------------",
1831 i==nArg-1 ? rowSep : " ");
1835 if( azArg==0 ) break;
1836 for(i=0; i<nArg; i++){
1838 if( i<ArraySize(p->actualWidth) ){
1839 w = p->actualWidth[i];
1843 if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
1844 w = strlen30(azArg[i]);
1846 if( i==1 && p->aiIndent && p->pStmt ){
1847 if( p->iIndent<p->nIndent ){
1848 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1853 utf8_printf(p->out,"%*.*s%s",-w,-w,
1854 azArg[i] ? azArg[i] : p->nullValue,
1855 i==nArg-1 ? rowSep : " ");
1857 utf8_printf(p->out,"%-*.*s%s",w,w,
1858 azArg[i] ? azArg[i] : p->nullValue,
1859 i==nArg-1 ? rowSep : " ");
1864 case MODE_Semi: { /* .schema and .fullschema output */
1865 printSchemaLine(p->out, azArg[0], ";\n");
1868 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1876 if( azArg[0]==0 ) break;
1877 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1878 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1880 utf8_printf(p->out, "%s;\n", azArg[0]);
1883 z = sqlite3_mprintf("%s", azArg[0]);
1885 for(i=0; IsSpace(z[i]); i++){}
1886 for(; (c = z[i])!=0; i++){
1888 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1889 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1894 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1896 if( strlen30(z)>=79 ){
1897 for(i=j=0; (c = z[i])!=0; i++){
1900 }else if( c=='"' || c=='\'' || c=='`' ){
1908 if( nLine>0 && nParen==0 && j>0 ){
1909 printSchemaLineN(p->out, z, j, "\n");
1914 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1916 printSchemaLineN(p->out, z, j, "\n ");
1919 while( IsSpace(z[i+1]) ){ i++; }
1924 printSchemaLine(p->out, z, ";\n");
1929 if( p->cnt++==0 && p->showHeader ){
1930 for(i=0; i<nArg; i++){
1931 utf8_printf(p->out,"%s%s",azCol[i],
1932 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1935 if( azArg==0 ) break;
1936 for(i=0; i<nArg; i++){
1938 if( z==0 ) z = p->nullValue;
1939 utf8_printf(p->out, "%s", z);
1941 utf8_printf(p->out, "%s", p->colSeparator);
1943 utf8_printf(p->out, "%s", p->rowSeparator);
1949 if( p->cnt++==0 && p->showHeader ){
1950 raw_printf(p->out,"<TR>");
1951 for(i=0; i<nArg; i++){
1952 raw_printf(p->out,"<TH>");
1953 output_html_string(p->out, azCol[i]);
1954 raw_printf(p->out,"</TH>\n");
1956 raw_printf(p->out,"</TR>\n");
1958 if( azArg==0 ) break;
1959 raw_printf(p->out,"<TR>");
1960 for(i=0; i<nArg; i++){
1961 raw_printf(p->out,"<TD>");
1962 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1963 raw_printf(p->out,"</TD>\n");
1965 raw_printf(p->out,"</TR>\n");
1969 if( p->cnt++==0 && p->showHeader ){
1970 for(i=0; i<nArg; i++){
1971 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1972 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1974 utf8_printf(p->out, "%s", p->rowSeparator);
1976 if( azArg==0 ) break;
1977 for(i=0; i<nArg; i++){
1978 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1979 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1981 utf8_printf(p->out, "%s", p->rowSeparator);
1985 setBinaryMode(p->out, 1);
1986 if( p->cnt++==0 && p->showHeader ){
1987 for(i=0; i<nArg; i++){
1988 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1990 utf8_printf(p->out, "%s", p->rowSeparator);
1993 for(i=0; i<nArg; i++){
1994 output_csv(p, azArg[i], i<nArg-1);
1996 utf8_printf(p->out, "%s", p->rowSeparator);
1998 setTextMode(p->out, 1);
2003 if( azArg==0 ) break;
2004 if( p->cMode==MODE_Insert ){
2005 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2006 if( p->showHeader ){
2007 raw_printf(p->out,"(");
2008 for(i=0; i<nArg; i++){
2009 char *zSep = i>0 ? ",": "";
2010 utf8_printf(p->out, "%s%s", zSep, azCol[i]);
2012 raw_printf(p->out,")");
2014 raw_printf(p->out," VALUES(");
2015 }else if( p->cnt==0 && p->showHeader ){
2016 for(i=0; i<nArg; i++){
2017 if( i>0 ) raw_printf(p->out, ",");
2018 output_quoted_string(p->out, azCol[i]);
2020 raw_printf(p->out,"\n");
2023 for(i=0; i<nArg; i++){
2024 char *zSep = i>0 ? ",": "";
2025 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2026 utf8_printf(p->out,"%sNULL",zSep);
2027 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2028 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2029 output_quoted_string(p->out, azArg[i]);
2030 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2031 utf8_printf(p->out,"%s%s",zSep, azArg[i]);
2032 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2034 double r = sqlite3_column_double(p->pStmt, i);
2035 sqlite3_snprintf(50,z,"%!.20g", r);
2036 raw_printf(p->out, "%s%s", zSep, z);
2037 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2038 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2039 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2040 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2041 output_hex_blob(p->out, pBlob, nBlob);
2042 }else if( isNumber(azArg[i], 0) ){
2043 utf8_printf(p->out,"%s%s",zSep, azArg[i]);
2045 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2046 output_quoted_string(p->out, azArg[i]);
2049 raw_printf(p->out,p->cMode==MODE_Quote?"\n":");\n");
2053 if( p->cnt++==0 && p->showHeader ){
2054 for(i=0; i<nArg; i++){
2055 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2056 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2058 utf8_printf(p->out, "%s", p->rowSeparator);
2060 if( azArg==0 ) break;
2061 for(i=0; i<nArg; i++){
2062 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2063 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2065 utf8_printf(p->out, "%s", p->rowSeparator);
2073 ** This is the callback routine that the SQLite library
2074 ** invokes for each row of a query result.
2076 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2077 /* since we don't have type info, call the shell_callback with a NULL value */
2078 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2082 ** This is the callback routine from sqlite3_exec() that appends all
2083 ** output onto the end of a ShellText object.
2085 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2086 ShellText *p = (ShellText*)pArg;
2088 UNUSED_PARAMETER(az);
2089 if( p->n ) appendText(p, "|", 0);
2090 for(i=0; i<nArg; i++){
2091 if( i ) appendText(p, ",", 0);
2092 if( azArg[i] ) appendText(p, azArg[i], 0);
2098 ** Generate an appropriate SELFTEST table in the main database.
2100 static void createSelftestTable(ShellState *p){
2103 "SAVEPOINT selftest_init;\n"
2104 "CREATE TABLE IF NOT EXISTS selftest(\n"
2105 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2106 " op TEXT,\n" /* Operator: memo run */
2107 " cmd TEXT,\n" /* Command text */
2108 " ans TEXT\n" /* Desired answer */
2110 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2111 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2112 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2113 " 'memo','Tests generated by --init');\n"
2114 "INSERT INTO [_shell$self]\n"
2116 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2117 "FROM sqlite_master ORDER BY 2'',224))',\n"
2118 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2119 "FROM sqlite_master ORDER BY 2',224));\n"
2120 "INSERT INTO [_shell$self]\n"
2122 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2123 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2124 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2126 " SELECT name FROM sqlite_master\n"
2127 " WHERE type='table'\n"
2128 " AND name<>'selftest'\n"
2129 " AND coalesce(rootpage,0)>0\n"
2132 "INSERT INTO [_shell$self]\n"
2133 " VALUES('run','PRAGMA integrity_check','ok');\n"
2134 "INSERT INTO selftest(tno,op,cmd,ans)"
2135 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2136 "DROP TABLE [_shell$self];"
2139 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2140 sqlite3_free(zErrMsg);
2142 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2147 ** Set the destination table field of the ShellState structure to
2148 ** the name of the table given. Escape any quote characters in the
2151 static void set_table_name(ShellState *p, const char *zName){
2156 if( p->zDestTable ){
2157 free(p->zDestTable);
2160 if( zName==0 ) return;
2161 cQuote = quoteChar(zName);
2162 n = strlen30(zName);
2163 if( cQuote ) n += 2;
2164 z = p->zDestTable = malloc( n+1 );
2166 raw_printf(stderr,"Error: out of memory\n");
2170 if( cQuote ) z[n++] = cQuote;
2171 for(i=0; zName[i]; i++){
2173 if( zName[i]==cQuote ) z[n++] = cQuote;
2175 if( cQuote ) z[n++] = cQuote;
2181 ** Execute a query statement that will generate SQL output. Print
2182 ** the result columns, comma-separated, on a line and then add a
2183 ** semicolon terminator to the end of that line.
2185 ** If the number of columns is 1 and that column contains text "--"
2186 ** then write the semicolon on a separate line. That way, if a
2187 ** "--" comment occurs at the end of the statement, the comment
2188 ** won't consume the semicolon terminator.
2190 static int run_table_dump_query(
2191 ShellState *p, /* Query context */
2192 const char *zSelect, /* SELECT statement to extract content */
2193 const char *zFirstRow /* Print before first row, if not NULL */
2195 sqlite3_stmt *pSelect;
2200 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2201 if( rc!=SQLITE_OK || !pSelect ){
2202 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2203 sqlite3_errmsg(p->db));
2204 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2207 rc = sqlite3_step(pSelect);
2208 nResult = sqlite3_column_count(pSelect);
2209 while( rc==SQLITE_ROW ){
2211 utf8_printf(p->out, "%s", zFirstRow);
2214 z = (const char*)sqlite3_column_text(pSelect, 0);
2215 utf8_printf(p->out, "%s", z);
2216 for(i=1; i<nResult; i++){
2217 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2220 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2222 raw_printf(p->out, "\n;\n");
2224 raw_printf(p->out, ";\n");
2226 rc = sqlite3_step(pSelect);
2228 rc = sqlite3_finalize(pSelect);
2229 if( rc!=SQLITE_OK ){
2230 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2231 sqlite3_errmsg(p->db));
2232 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2238 ** Allocate space and save off current error string.
2240 static char *save_err_msg(
2241 sqlite3 *db /* Database to query */
2243 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2244 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2246 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2253 ** Attempt to display I/O stats on Linux using /proc/PID/io
2255 static void displayLinuxIoStats(FILE *out){
2258 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2259 in = fopen(z, "rb");
2261 while( fgets(z, sizeof(z), in)!=0 ){
2262 static const struct {
2263 const char *zPattern;
2266 { "rchar: ", "Bytes received by read():" },
2267 { "wchar: ", "Bytes sent to write():" },
2268 { "syscr: ", "Read() system calls:" },
2269 { "syscw: ", "Write() system calls:" },
2270 { "read_bytes: ", "Bytes read from storage:" },
2271 { "write_bytes: ", "Bytes written to storage:" },
2272 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2275 for(i=0; i<ArraySize(aTrans); i++){
2276 int n = (int)strlen(aTrans[i].zPattern);
2277 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2278 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2288 ** Display a single line of status using 64-bit values.
2290 static void displayStatLine(
2291 ShellState *p, /* The shell context */
2292 char *zLabel, /* Label for this one line */
2293 char *zFormat, /* Format for the result */
2294 int iStatusCtrl, /* Which status to display */
2295 int bReset /* True to reset the stats */
2297 sqlite3_int64 iCur = -1;
2298 sqlite3_int64 iHiwtr = -1;
2301 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2302 for(i=0, nPercent=0; zFormat[i]; i++){
2303 if( zFormat[i]=='%' ) nPercent++;
2306 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2308 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2310 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2314 ** Display memory stats.
2316 static int display_stats(
2317 sqlite3 *db, /* Database to query */
2318 ShellState *pArg, /* Pointer to ShellState */
2319 int bReset /* True to reset the stats */
2324 if( pArg && pArg->out ){
2325 displayStatLine(pArg, "Memory Used:",
2326 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2327 displayStatLine(pArg, "Number of Outstanding Allocations:",
2328 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2329 if( pArg->shellFlgs & SHFLG_Pagecache ){
2330 displayStatLine(pArg, "Number of Pcache Pages Used:",
2331 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2333 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2334 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2335 if( pArg->shellFlgs & SHFLG_Scratch ){
2336 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2337 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
2339 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2340 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2341 displayStatLine(pArg, "Largest Allocation:",
2342 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2343 displayStatLine(pArg, "Largest Pcache Allocation:",
2344 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2345 displayStatLine(pArg, "Largest Scratch Allocation:",
2346 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
2347 #ifdef YYTRACKMAXSTACKDEPTH
2348 displayStatLine(pArg, "Deepest Parser Stack:",
2349 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2353 if( pArg && pArg->out && db ){
2354 if( pArg->shellFlgs & SHFLG_Lookaside ){
2356 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2357 &iCur, &iHiwtr, bReset);
2358 raw_printf(pArg->out,
2359 "Lookaside Slots Used: %d (max %d)\n",
2361 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2362 &iCur, &iHiwtr, bReset);
2363 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2365 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2366 &iCur, &iHiwtr, bReset);
2367 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2369 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2370 &iCur, &iHiwtr, bReset);
2371 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2375 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2376 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2379 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2380 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2382 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2383 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2385 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2386 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2388 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2389 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2392 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2393 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2397 if( pArg && pArg->out && db && pArg->pStmt ){
2398 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2400 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2401 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2402 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2403 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2404 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2405 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2406 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2410 displayLinuxIoStats(pArg->out);
2413 /* Do not remove this machine readable comment: extra-stats-output-here */
2419 ** Display scan stats.
2421 static void display_scanstats(
2422 sqlite3 *db, /* Database to query */
2423 ShellState *pArg /* Pointer to ShellState */
2425 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2426 UNUSED_PARAMETER(db);
2427 UNUSED_PARAMETER(pArg);
2430 raw_printf(pArg->out, "-------- scanstats --------\n");
2432 for(k=0; k<=mx; k++){
2433 double rEstLoop = 1.0;
2435 sqlite3_stmt *p = pArg->pStmt;
2436 sqlite3_int64 nLoop, nVisit;
2439 const char *zExplain;
2440 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2443 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2444 if( iSid>mx ) mx = iSid;
2445 if( iSid!=k ) continue;
2447 rEstLoop = (double)nLoop;
2448 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2451 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2452 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2453 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2454 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2456 raw_printf(pArg->out,
2457 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2458 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2462 raw_printf(pArg->out, "---------------------------\n");
2467 ** Parameter azArray points to a zero-terminated array of strings. zStr
2468 ** points to a single nul-terminated string. Return non-zero if zStr
2469 ** is equal, according to strcmp(), to any of the strings in the array.
2470 ** Otherwise, return zero.
2472 static int str_in_array(const char *zStr, const char **azArray){
2474 for(i=0; azArray[i]; i++){
2475 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2481 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2482 ** and populate the ShellState.aiIndent[] array with the number of
2483 ** spaces each opcode should be indented before it is output.
2485 ** The indenting rules are:
2487 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2488 ** all opcodes that occur between the p2 jump destination and the opcode
2489 ** itself by 2 spaces.
2491 ** * For each "Goto", if the jump destination is earlier in the program
2492 ** and ends on one of:
2493 ** Yield SeekGt SeekLt RowSetRead Rewind
2494 ** or if the P1 parameter is one instead of zero,
2495 ** then indent all opcodes between the earlier instruction
2496 ** and "Goto" by 2 spaces.
2498 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2499 const char *zSql; /* The text of the SQL statement */
2500 const char *z; /* Used to check if this is an EXPLAIN */
2501 int *abYield = 0; /* True if op is an OP_Yield */
2502 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2503 int iOp; /* Index of operation in p->aiIndent[] */
2505 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2506 "NextIfOpen", "PrevIfOpen", 0 };
2507 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2509 const char *azGoto[] = { "Goto", 0 };
2511 /* Try to figure out if this is really an EXPLAIN statement. If this
2512 ** cannot be verified, return early. */
2513 if( sqlite3_column_count(pSql)!=8 ){
2517 zSql = sqlite3_sql(pSql);
2518 if( zSql==0 ) return;
2519 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2520 if( sqlite3_strnicmp(z, "explain", 7) ){
2525 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2527 int iAddr = sqlite3_column_int(pSql, 0);
2528 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2530 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2531 ** p2 is an instruction address, set variable p2op to the index of that
2532 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2533 ** the current instruction is part of a sub-program generated by an
2534 ** SQL trigger or foreign key. */
2535 int p2 = sqlite3_column_int(pSql, 3);
2536 int p2op = (p2 + (iOp-iAddr));
2538 /* Grow the p->aiIndent array as required */
2541 /* Do further verfication that this is explain output. Abort if
2543 static const char *explainCols[] = {
2544 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2546 for(jj=0; jj<ArraySize(explainCols); jj++){
2547 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2549 sqlite3_reset(pSql);
2555 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2556 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2558 abYield[iOp] = str_in_array(zOp, azYield);
2559 p->aiIndent[iOp] = 0;
2562 if( str_in_array(zOp, azNext) ){
2563 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2565 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2566 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2568 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2573 sqlite3_free(abYield);
2574 sqlite3_reset(pSql);
2578 ** Free the array allocated by explain_data_prepare().
2580 static void explain_data_delete(ShellState *p){
2581 sqlite3_free(p->aiIndent);
2588 ** Disable and restore .wheretrace and .selecttrace settings.
2590 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2591 extern int sqlite3SelectTrace;
2592 static int savedSelectTrace;
2594 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2595 extern int sqlite3WhereTrace;
2596 static int savedWhereTrace;
2598 static void disable_debug_trace_modes(void){
2599 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2600 savedSelectTrace = sqlite3SelectTrace;
2601 sqlite3SelectTrace = 0;
2603 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2604 savedWhereTrace = sqlite3WhereTrace;
2605 sqlite3WhereTrace = 0;
2608 static void restore_debug_trace_modes(void){
2609 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2610 sqlite3SelectTrace = savedSelectTrace;
2612 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2613 sqlite3WhereTrace = savedWhereTrace;
2618 ** Run a prepared statement
2620 static void exec_prepared_stmt(
2621 ShellState *pArg, /* Pointer to ShellState */
2622 sqlite3_stmt *pStmt, /* Statment to run */
2623 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2627 /* perform the first step. this will tell us if we
2628 ** have a result set or not and how wide it is.
2630 rc = sqlite3_step(pStmt);
2631 /* if we have a result set... */
2632 if( SQLITE_ROW == rc ){
2633 /* if we have a callback... */
2635 /* allocate space for col name ptr, value ptr, and type */
2636 int nCol = sqlite3_column_count(pStmt);
2637 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2641 char **azCols = (char **)pData; /* Names of result columns */
2642 char **azVals = &azCols[nCol]; /* Results */
2643 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2645 assert(sizeof(int) <= sizeof(char *));
2646 /* save off ptrs to column names */
2647 for(i=0; i<nCol; i++){
2648 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2651 /* extract the data and data types */
2652 for(i=0; i<nCol; i++){
2653 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2654 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2657 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2659 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2661 break; /* from for */
2665 /* if data and types extracted successfully... */
2666 if( SQLITE_ROW == rc ){
2667 /* call the supplied callback with the result row data */
2668 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2671 rc = sqlite3_step(pStmt);
2674 } while( SQLITE_ROW == rc );
2675 sqlite3_free(pData);
2679 rc = sqlite3_step(pStmt);
2680 } while( rc == SQLITE_ROW );
2686 ** Execute a statement or set of statements. Print
2687 ** any result rows/columns depending on the current mode
2688 ** set via the supplied callback.
2690 ** This is very similar to SQLite's built-in sqlite3_exec()
2691 ** function except it takes a slightly different callback
2692 ** and callback data argument.
2694 static int shell_exec(
2695 sqlite3 *db, /* An open database */
2696 const char *zSql, /* SQL to be evaluated */
2697 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2698 /* (not the same as sqlite3_exec) */
2699 ShellState *pArg, /* Pointer to ShellState */
2700 char **pzErrMsg /* Error msg written here */
2702 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2703 int rc = SQLITE_OK; /* Return Code */
2705 const char *zLeftover; /* Tail of unprocessed SQL */
2711 while( zSql[0] && (SQLITE_OK == rc) ){
2712 static const char *zStmtSql;
2713 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2714 if( SQLITE_OK != rc ){
2716 *pzErrMsg = save_err_msg(db);
2720 /* this happens for a comment or white-space */
2722 while( IsSpace(zSql[0]) ) zSql++;
2725 zStmtSql = sqlite3_sql(pStmt);
2726 if( zStmtSql==0 ) zStmtSql = "";
2727 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2729 /* save off the prepared statment handle and reset row count */
2731 pArg->pStmt = pStmt;
2735 /* echo the sql statement if echo on */
2736 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2737 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2740 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2741 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2742 sqlite3_stmt *pExplain;
2744 disable_debug_trace_modes();
2745 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2746 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2747 if( rc==SQLITE_OK ){
2748 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2749 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2750 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2751 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2752 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2755 sqlite3_finalize(pExplain);
2757 if( pArg->autoEQP>=2 ){
2758 /* Also do an EXPLAIN for ".eqp full" mode */
2759 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2760 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2761 if( rc==SQLITE_OK ){
2762 pArg->cMode = MODE_Explain;
2763 explain_data_prepare(pArg, pExplain);
2764 exec_prepared_stmt(pArg, pExplain, xCallback);
2765 explain_data_delete(pArg);
2767 sqlite3_finalize(pExplain);
2770 restore_debug_trace_modes();
2774 pArg->cMode = pArg->mode;
2775 if( pArg->autoExplain
2776 && sqlite3_column_count(pStmt)==8
2777 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2779 pArg->cMode = MODE_Explain;
2782 /* If the shell is currently in ".explain" mode, gather the extra
2783 ** data required to add indents to the output.*/
2784 if( pArg->cMode==MODE_Explain ){
2785 explain_data_prepare(pArg, pStmt);
2789 exec_prepared_stmt(pArg, pStmt, xCallback);
2790 explain_data_delete(pArg);
2792 /* print usage stats if stats on */
2793 if( pArg && pArg->statsOn ){
2794 display_stats(db, pArg, 0);
2797 /* print loop-counters if required */
2798 if( pArg && pArg->scanstatsOn ){
2799 display_scanstats(db, pArg);
2802 /* Finalize the statement just executed. If this fails, save a
2803 ** copy of the error message. Otherwise, set zSql to point to the
2804 ** next statement to execute. */
2805 rc2 = sqlite3_finalize(pStmt);
2806 if( rc!=SQLITE_NOMEM ) rc = rc2;
2807 if( rc==SQLITE_OK ){
2809 while( IsSpace(zSql[0]) ) zSql++;
2810 }else if( pzErrMsg ){
2811 *pzErrMsg = save_err_msg(db);
2814 /* clear saved stmt handle */
2825 ** Release memory previously allocated by tableColumnList().
2827 static void freeColumnList(char **azCol){
2829 for(i=1; azCol[i]; i++){
2830 sqlite3_free(azCol[i]);
2832 /* azCol[0] is a static string */
2833 sqlite3_free(azCol);
2837 ** Return a list of pointers to strings which are the names of all
2838 ** columns in table zTab. The memory to hold the names is dynamically
2839 ** allocated and must be released by the caller using a subsequent call
2840 ** to freeColumnList().
2842 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2843 ** value that needs to be preserved, then azCol[0] is filled in with the
2844 ** name of the rowid column.
2846 ** The first regular column in the table is azCol[1]. The list is terminated
2847 ** by an entry with azCol[i]==0.
2849 static char **tableColumnList(ShellState *p, const char *zTab){
2851 sqlite3_stmt *pStmt;
2855 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2856 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2857 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2860 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2861 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2864 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2865 if( nCol>=nAlloc-2 ){
2866 nAlloc = nAlloc*2 + nCol + 10;
2867 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2869 raw_printf(stderr, "Error: out of memory\n");
2873 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2874 if( sqlite3_column_int(pStmt, 5) ){
2877 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2886 sqlite3_finalize(pStmt);
2890 /* The decision of whether or not a rowid really needs to be preserved
2891 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2892 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2893 ** rowids on tables where the rowid is inaccessible because there are other
2894 ** columns in the table named "rowid", "_rowid_", and "oid".
2896 if( preserveRowid && isIPK ){
2897 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2898 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2899 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2900 ** ROWID aliases. To distinguish these cases, check to see if
2901 ** there is a "pk" entry in "PRAGMA index_list". There will be
2902 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2904 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2905 " WHERE origin='pk'", zTab);
2906 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2909 freeColumnList(azCol);
2912 rc = sqlite3_step(pStmt);
2913 sqlite3_finalize(pStmt);
2914 preserveRowid = rc==SQLITE_ROW;
2916 if( preserveRowid ){
2917 /* Only preserve the rowid if we can find a name to use for the
2919 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2922 for(i=1; i<=nCol; i++){
2923 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2926 /* At this point, we know that azRowid[j] is not the name of any
2927 ** ordinary column in the table. Verify that azRowid[j] is a valid
2928 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2929 ** tables will fail this last check */
2930 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2931 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2940 ** Toggle the reverse_unordered_selects setting.
2942 static void toggleSelectOrder(sqlite3 *db){
2943 sqlite3_stmt *pStmt = 0;
2946 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2947 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2948 iSetting = sqlite3_column_int(pStmt, 0);
2950 sqlite3_finalize(pStmt);
2951 sqlite3_snprintf(sizeof(zStmt), zStmt,
2952 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2953 sqlite3_exec(db, zStmt, 0, 0, 0);
2957 ** This is a different callback routine used for dumping the database.
2958 ** Each row received by this callback consists of a table name,
2959 ** the table type ("index" or "table") and SQL to create the table.
2960 ** This routine should print text sufficient to recreate the table.
2962 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2967 ShellState *p = (ShellState *)pArg;
2969 UNUSED_PARAMETER(azNotUsed);
2970 if( nArg!=3 ) return 1;
2975 if( strcmp(zTable, "sqlite_sequence")==0 ){
2976 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2977 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2978 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2979 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2981 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2983 if( !p->writableSchema ){
2984 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2985 p->writableSchema = 1;
2987 zIns = sqlite3_mprintf(
2988 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2989 "VALUES('table','%q','%q',0,'%q');",
2990 zTable, zTable, zSql);
2991 utf8_printf(p->out, "%s\n", zIns);
2995 printSchemaLine(p->out, zSql, ";\n");
2998 if( strcmp(zType, "table")==0 ){
3003 char *savedDestTable;
3006 azCol = tableColumnList(p, zTable);
3012 /* Always quote the table name, even if it appears to be pure ascii,
3013 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3015 appendText(&sTable, zTable, quoteChar(zTable));
3016 /* If preserving the rowid, add a column list after the table name.
3017 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3018 ** instead of the usual "INSERT INTO tab VALUES(...)".
3021 appendText(&sTable, "(", 0);
3022 appendText(&sTable, azCol[0], 0);
3023 for(i=1; azCol[i]; i++){
3024 appendText(&sTable, ",", 0);
3025 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3027 appendText(&sTable, ")", 0);
3030 /* Build an appropriate SELECT statement */
3032 appendText(&sSelect, "SELECT ", 0);
3034 appendText(&sSelect, azCol[0], 0);
3035 appendText(&sSelect, ",", 0);
3037 for(i=1; azCol[i]; i++){
3038 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3040 appendText(&sSelect, ",", 0);
3043 freeColumnList(azCol);
3044 appendText(&sSelect, " FROM ", 0);
3045 appendText(&sSelect, zTable, quoteChar(zTable));
3047 savedDestTable = p->zDestTable;
3048 savedMode = p->mode;
3049 p->zDestTable = sTable.z;
3050 p->mode = p->cMode = MODE_Insert;
3051 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3052 if( (rc&0xff)==SQLITE_CORRUPT ){
3053 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3054 toggleSelectOrder(p->db);
3055 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3056 toggleSelectOrder(p->db);
3058 p->zDestTable = savedDestTable;
3059 p->mode = savedMode;
3068 ** Run zQuery. Use dump_callback() as the callback routine so that
3069 ** the contents of the query are output as SQL statements.
3071 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3072 ** "ORDER BY rowid DESC" to the end.
3074 static int run_schema_dump_query(
3080 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3081 if( rc==SQLITE_CORRUPT ){
3083 int len = strlen30(zQuery);
3084 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3086 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3090 zQ2 = malloc( len+100 );
3091 if( zQ2==0 ) return rc;
3092 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3093 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3095 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3097 rc = SQLITE_CORRUPT;
3106 ** Text of a help message
3108 static char zHelp[] =
3109 #ifndef SQLITE_OMIT_AUTHORIZATION
3110 ".auth ON|OFF Show authorizer callbacks\n"
3112 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3113 ".bail on|off Stop after hitting an error. Default OFF\n"
3114 ".binary on|off Turn binary output on or off. Default OFF\n"
3115 ".changes on|off Show number of rows changed by SQL\n"
3116 ".check GLOB Fail if output since .testcase does not match\n"
3117 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3118 ".databases List names and files of attached databases\n"
3119 ".dbinfo ?DB? Show status information about the database\n"
3120 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3121 " If TABLE specified, only dump tables matching\n"
3122 " LIKE pattern TABLE.\n"
3123 ".echo on|off Turn command echo on or off\n"
3124 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3125 ".exit Exit this program\n"
3126 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
3127 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3128 ".headers on|off Turn display of headers on or off\n"
3129 ".help Show this message\n"
3130 ".import FILE TABLE Import data from FILE into TABLE\n"
3131 #ifndef SQLITE_OMIT_TEST_CONTROL
3132 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3134 ".indexes ?TABLE? Show names of all indexes\n"
3135 " If TABLE specified, only show indexes for tables\n"
3136 " matching LIKE pattern TABLE.\n"
3137 #ifdef SQLITE_ENABLE_IOTRACE
3138 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3140 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3141 ".lint OPTIONS Report potential schema issues. Options:\n"
3142 " fkey-indexes Find missing foreign key indexes\n"
3143 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3144 ".load FILE ?ENTRY? Load an extension library\n"
3146 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3147 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3148 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3149 " csv Comma-separated values\n"
3150 " column Left-aligned columns. (See .width)\n"
3151 " html HTML <table> code\n"
3152 " insert SQL insert statements for TABLE\n"
3153 " line One value per line\n"
3154 " list Values delimited by \"|\"\n"
3155 " quote Escape answers as for SQL\n"
3156 " tabs Tab-separated values\n"
3157 " tcl TCL list elements\n"
3158 ".nullvalue STRING Use STRING in place of NULL values\n"
3159 ".once FILENAME Output for the next SQL command only to FILENAME\n"
3160 ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
3161 " The --new starts with an empty file\n"
3162 ".output ?FILENAME? Send output to FILENAME or stdout\n"
3163 ".print STRING... Print literal STRING\n"
3164 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3165 ".quit Exit this program\n"
3166 ".read FILENAME Execute SQL in FILENAME\n"
3167 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3168 ".save FILE Write in-memory database into FILE\n"
3169 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3170 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3171 " Add --indent for pretty-printing\n"
3172 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3173 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3174 " separator for both the output mode and .import\n"
3175 #if defined(SQLITE_ENABLE_SESSION)
3176 ".session CMD ... Create or control sessions\n"
3178 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3179 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3180 ".show Show the current values for various settings\n"
3181 ".stats ?on|off? Show stats or turn stats on or off\n"
3182 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3183 ".tables ?TABLE? List names of tables\n"
3184 " If TABLE specified, only list tables matching\n"
3185 " LIKE pattern TABLE.\n"
3186 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3187 ".timeout MS Try opening locked tables for MS milliseconds\n"
3188 ".timer on|off Turn SQL timer on or off\n"
3189 ".trace FILE|off Output each SQL statement as it is run\n"
3190 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3191 ".vfslist List all available VFSes\n"
3192 ".vfsname ?AUX? Print the name of the VFS stack\n"
3193 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3194 " Negative values right-justify\n"
3197 #if defined(SQLITE_ENABLE_SESSION)
3199 ** Print help information for the ".sessions" command
3201 void session_help(ShellState *p){
3203 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3204 "If ?NAME? is omitted, the first defined session is used.\n"
3206 " attach TABLE Attach TABLE\n"
3207 " changeset FILE Write a changeset into FILE\n"
3208 " close Close one session\n"
3209 " enable ?BOOLEAN? Set or query the enable bit\n"
3210 " filter GLOB... Reject tables matching GLOBs\n"
3211 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3212 " isempty Query whether the session is empty\n"
3213 " list List currently open session names\n"
3214 " open DB NAME Open a new session on DB\n"
3215 " patchset FILE Write a patchset into FILE\n"
3221 /* Forward reference */
3222 static int process_input(ShellState *p, FILE *in);
3225 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3226 ** and return a pointer to the buffer. The caller is responsible for freeing
3229 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3232 ** For convenience, a nul-terminator byte is always appended to the data read
3233 ** from the file before the buffer is returned. This byte is not included in
3234 ** the final value of (*pnByte), if applicable.
3236 ** NULL is returned if any error is encountered. The final value of *pnByte
3237 ** is undefined in this case.
3239 static char *readFile(const char *zName, int *pnByte){
3240 FILE *in = fopen(zName, "rb");
3244 if( in==0 ) return 0;
3245 fseek(in, 0, SEEK_END);
3248 pBuf = sqlite3_malloc64( nIn+1 );
3249 if( pBuf==0 ) return 0;
3250 nRead = fread(pBuf, nIn, 1, in);
3257 if( pnByte ) *pnByte = nIn;
3262 ** Implementation of the "readfile(X)" SQL function. The entire content
3263 ** of the file named X is read and returned as a BLOB. NULL is returned
3264 ** if the file does not exist or is unreadable.
3266 static void readfileFunc(
3267 sqlite3_context *context,
3269 sqlite3_value **argv
3275 UNUSED_PARAMETER(argc);
3276 zName = (const char*)sqlite3_value_text(argv[0]);
3277 if( zName==0 ) return;
3278 pBuf = readFile(zName, &nBuf);
3279 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
3283 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3284 ** is written into file X. The number of bytes written is returned. Or
3285 ** NULL is returned if something goes wrong, such as being unable to open
3286 ** file X for writing.
3288 static void writefileFunc(
3289 sqlite3_context *context,
3291 sqlite3_value **argv
3298 UNUSED_PARAMETER(argc);
3299 zFile = (const char*)sqlite3_value_text(argv[0]);
3300 if( zFile==0 ) return;
3301 out = fopen(zFile, "wb");
3302 if( out==0 ) return;
3303 z = (const char*)sqlite3_value_blob(argv[1]);
3307 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
3310 sqlite3_result_int64(context, rc);
3313 #if defined(SQLITE_ENABLE_SESSION)
3315 ** Close a single OpenSession object and release all of its associated
3318 static void session_close(OpenSession *pSession){
3320 sqlite3session_delete(pSession->p);
3321 sqlite3_free(pSession->zName);
3322 for(i=0; i<pSession->nFilter; i++){
3323 sqlite3_free(pSession->azFilter[i]);
3325 sqlite3_free(pSession->azFilter);
3326 memset(pSession, 0, sizeof(OpenSession));
3331 ** Close all OpenSession objects and release all associated resources.
3333 #if defined(SQLITE_ENABLE_SESSION)
3334 static void session_close_all(ShellState *p){
3336 for(i=0; i<p->nSession; i++){
3337 session_close(&p->aSession[i]);
3342 # define session_close_all(X)
3346 ** Implementation of the xFilter function for an open session. Omit
3347 ** any tables named by ".session filter" but let all other table through.
3349 #if defined(SQLITE_ENABLE_SESSION)
3350 static int session_filter(void *pCtx, const char *zTab){
3351 OpenSession *pSession = (OpenSession*)pCtx;
3353 for(i=0; i<pSession->nFilter; i++){
3354 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3361 ** Make sure the database is open. If it is not, then open it. If
3362 ** the database fails to open, print an error message and exit.
3364 static void open_db(ShellState *p, int keepAlive){
3366 sqlite3_initialize();
3367 sqlite3_open(p->zDbFilename, &p->db);
3369 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3370 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3371 p->zDbFilename, sqlite3_errmsg(p->db));
3372 if( keepAlive ) return;
3375 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3376 sqlite3_enable_load_extension(p->db, 1);
3378 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
3379 readfileFunc, 0, 0);
3380 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
3381 writefileFunc, 0, 0);
3382 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3384 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3386 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3387 sha3QueryFunc, 0, 0);
3388 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3389 sha3QueryFunc, 0, 0);
3394 ** Do C-language style dequoting.
3400 ** \v -> vertical tab
3402 ** \r -> carriage return
3407 ** \NNN -> ascii character NNN in octal
3409 static void resolve_backslashes(char *z){
3412 while( *z && *z!='\\' ) z++;
3413 for(i=j=0; (c = z[i])!=0; i++, j++){
3414 if( c=='\\' && z[i+1]!=0 ){
3432 }else if( c=='\'' ){
3434 }else if( c=='\\' ){
3436 }else if( c>='0' && c<='7' ){
3438 if( z[i+1]>='0' && z[i+1]<='7' ){
3440 c = (c<<3) + z[i] - '0';
3441 if( z[i+1]>='0' && z[i+1]<='7' ){
3443 c = (c<<3) + z[i] - '0';
3454 ** Return the value of a hexadecimal digit. Return -1 if the input
3455 ** is not a hex digit.
3457 static int hexDigitValue(char c){
3458 if( c>='0' && c<='9' ) return c - '0';
3459 if( c>='a' && c<='f' ) return c - 'a' + 10;
3460 if( c>='A' && c<='F' ) return c - 'A' + 10;
3465 ** Interpret zArg as an integer value, possibly with suffixes.
3467 static sqlite3_int64 integerValue(const char *zArg){
3468 sqlite3_int64 v = 0;
3469 static const struct { char *zSuffix; int iMult; } aMult[] = {
3471 { "MiB", 1024*1024 },
3472 { "GiB", 1024*1024*1024 },
3475 { "GB", 1000000000 },
3478 { "G", 1000000000 },
3485 }else if( zArg[0]=='+' ){
3488 if( zArg[0]=='0' && zArg[1]=='x' ){
3491 while( (x = hexDigitValue(zArg[0]))>=0 ){
3496 while( IsDigit(zArg[0]) ){
3497 v = v*10 + zArg[0] - '0';
3501 for(i=0; i<ArraySize(aMult); i++){
3502 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3503 v *= aMult[i].iMult;
3507 return isNeg? -v : v;
3511 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3512 ** for TRUE and FALSE. Return the integer value if appropriate.
3514 static int booleanValue(const char *zArg){
3516 if( zArg[0]=='0' && zArg[1]=='x' ){
3517 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3519 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3521 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3522 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3525 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3528 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3534 ** Set or clear a shell flag according to a boolean value.
3536 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3537 if( booleanValue(zArg) ){
3538 ShellSetFlag(p, mFlag);
3540 ShellClearFlag(p, mFlag);
3545 ** Close an output file, assuming it is not stderr or stdout
3547 static void output_file_close(FILE *f){
3548 if( f && f!=stdout && f!=stderr ) fclose(f);
3552 ** Try to open an output file. The names "stdout" and "stderr" are
3553 ** recognized and do the right thing. NULL is returned if the output
3554 ** filename is "off".
3556 static FILE *output_file_open(const char *zFile){
3558 if( strcmp(zFile,"stdout")==0 ){
3560 }else if( strcmp(zFile, "stderr")==0 ){
3562 }else if( strcmp(zFile, "off")==0 ){
3565 f = fopen(zFile, "wb");
3567 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3573 #if !defined(SQLITE_UNTESTABLE)
3574 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3576 ** A routine for handling output from sqlite3_trace().
3578 static int sql_trace_callback(
3584 FILE *f = (FILE*)pArg;
3585 UNUSED_PARAMETER(mType);
3586 UNUSED_PARAMETER(pP);
3588 const char *z = (const char*)pX;
3589 int i = (int)strlen(z);
3590 while( i>0 && z[i-1]==';' ){ i--; }
3591 utf8_printf(f, "%.*s;\n", i, z);
3599 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3600 ** a useful spot to set a debugger breakpoint.
3602 static void test_breakpoint(void){
3603 static int nCall = 0;
3608 ** An object used to read a CSV and other files for import.
3610 typedef struct ImportCtx ImportCtx;
3612 const char *zFile; /* Name of the input file */
3613 FILE *in; /* Read the CSV text from this input stream */
3614 char *z; /* Accumulated text for a field */
3615 int n; /* Number of bytes in z */
3616 int nAlloc; /* Space allocated for z[] */
3617 int nLine; /* Current line number */
3618 int cTerm; /* Character that terminated the most recent field */
3619 int cColSep; /* The column separator character. (Usually ",") */
3620 int cRowSep; /* The row separator character. (Usually "\n") */
3623 /* Append a single byte to z[] */
3624 static void import_append_char(ImportCtx *p, int c){
3625 if( p->n+1>=p->nAlloc ){
3626 p->nAlloc += p->nAlloc + 100;
3627 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3629 raw_printf(stderr, "out of memory\n");
3633 p->z[p->n++] = (char)c;
3636 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3637 ** with the option of having a separator other than ",".
3639 ** + Input comes from p->in.
3640 ** + Store results in p->z of length p->n. Space to hold p->z comes
3641 ** from sqlite3_malloc64().
3642 ** + Use p->cSep as the column separator. The default is ",".
3643 ** + Use p->rSep as the row separator. The default is "\n".
3644 ** + Keep track of the line number in p->nLine.
3645 ** + Store the character that terminates the field in p->cTerm. Store
3646 ** EOF on end-of-file.
3647 ** + Report syntax errors on stderr
3649 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3651 int cSep = p->cColSep;
3652 int rSep = p->cRowSep;
3655 if( c==EOF || seenInterrupt ){
3661 int startLine = p->nLine;
3666 if( c==rSep ) p->nLine++;
3673 if( (c==cSep && pc==cQuote)
3674 || (c==rSep && pc==cQuote)
3675 || (c==rSep && pc=='\r' && ppc==cQuote)
3676 || (c==EOF && pc==cQuote)
3678 do{ p->n--; }while( p->z[p->n]!=cQuote );
3682 if( pc==cQuote && c!='\r' ){
3683 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3684 p->zFile, p->nLine, cQuote);
3687 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3688 p->zFile, startLine, cQuote);
3692 import_append_char(p, c);
3697 while( c!=EOF && c!=cSep && c!=rSep ){
3698 import_append_char(p, c);
3703 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3707 if( p->z ) p->z[p->n] = 0;
3711 /* Read a single field of ASCII delimited text.
3713 ** + Input comes from p->in.
3714 ** + Store results in p->z of length p->n. Space to hold p->z comes
3715 ** from sqlite3_malloc64().
3716 ** + Use p->cSep as the column separator. The default is "\x1F".
3717 ** + Use p->rSep as the row separator. The default is "\x1E".
3718 ** + Keep track of the row number in p->nLine.
3719 ** + Store the character that terminates the field in p->cTerm. Store
3720 ** EOF on end-of-file.
3721 ** + Report syntax errors on stderr
3723 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3725 int cSep = p->cColSep;
3726 int rSep = p->cRowSep;
3729 if( c==EOF || seenInterrupt ){
3733 while( c!=EOF && c!=cSep && c!=rSep ){
3734 import_append_char(p, c);
3741 if( p->z ) p->z[p->n] = 0;
3746 ** Try to transfer data for table zTable. If an error is seen while
3747 ** moving forward, try to go backwards. The backwards movement won't
3748 ** work for WITHOUT ROWID tables.
3750 static void tryToCloneData(
3755 sqlite3_stmt *pQuery = 0;
3756 sqlite3_stmt *pInsert = 0;
3761 int nTable = (int)strlen(zTable);
3764 const int spinRate = 10000;
3766 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3767 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3769 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3770 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3774 n = sqlite3_column_count(pQuery);
3775 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3777 raw_printf(stderr, "out of memory\n");
3780 sqlite3_snprintf(200+nTable,zInsert,
3781 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3782 i = (int)strlen(zInsert);
3784 memcpy(zInsert+i, ",?", 2);
3787 memcpy(zInsert+i, ");", 3);
3788 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3790 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3791 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3796 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3798 switch( sqlite3_column_type(pQuery, i) ){
3800 sqlite3_bind_null(pInsert, i+1);
3803 case SQLITE_INTEGER: {
3804 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3807 case SQLITE_FLOAT: {
3808 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3812 sqlite3_bind_text(pInsert, i+1,
3813 (const char*)sqlite3_column_text(pQuery,i),
3818 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3819 sqlite3_column_bytes(pQuery,i),
3825 rc = sqlite3_step(pInsert);
3826 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3827 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3828 sqlite3_errmsg(newDb));
3830 sqlite3_reset(pInsert);
3832 if( (cnt%spinRate)==0 ){
3833 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3837 if( rc==SQLITE_DONE ) break;
3838 sqlite3_finalize(pQuery);
3839 sqlite3_free(zQuery);
3840 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3842 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3844 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3847 } /* End for(k=0...) */
3850 sqlite3_finalize(pQuery);
3851 sqlite3_finalize(pInsert);
3852 sqlite3_free(zQuery);
3853 sqlite3_free(zInsert);
3858 ** Try to transfer all rows of the schema that match zWhere. For
3859 ** each row, invoke xForEach() on the object defined by that row.
3860 ** If an error is encountered while moving forward through the
3861 ** sqlite_master table, try again moving backwards.
3863 static void tryToCloneSchema(
3867 void (*xForEach)(ShellState*,sqlite3*,const char*)
3869 sqlite3_stmt *pQuery = 0;
3872 const unsigned char *zName;
3873 const unsigned char *zSql;
3876 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3877 " WHERE %s", zWhere);
3878 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3880 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3881 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3883 goto end_schema_xfer;
3885 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3886 zName = sqlite3_column_text(pQuery, 0);
3887 zSql = sqlite3_column_text(pQuery, 1);
3888 printf("%s... ", zName); fflush(stdout);
3889 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3891 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3892 sqlite3_free(zErrMsg);
3896 xForEach(p, newDb, (const char*)zName);
3900 if( rc!=SQLITE_DONE ){
3901 sqlite3_finalize(pQuery);
3902 sqlite3_free(zQuery);
3903 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3904 " WHERE %s ORDER BY rowid DESC", zWhere);
3905 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3907 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3908 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3910 goto end_schema_xfer;
3912 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3913 zName = sqlite3_column_text(pQuery, 0);
3914 zSql = sqlite3_column_text(pQuery, 1);
3915 printf("%s... ", zName); fflush(stdout);
3916 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3918 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3919 sqlite3_free(zErrMsg);
3923 xForEach(p, newDb, (const char*)zName);
3929 sqlite3_finalize(pQuery);
3930 sqlite3_free(zQuery);
3934 ** Open a new database file named "zNewDb". Try to recover as much information
3935 ** as possible out of the main database (which might be corrupt) and write it
3938 static void tryToClone(ShellState *p, const char *zNewDb){
3941 if( access(zNewDb,0)==0 ){
3942 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3945 rc = sqlite3_open(zNewDb, &newDb);
3947 utf8_printf(stderr, "Cannot create output database: %s\n",
3948 sqlite3_errmsg(newDb));
3950 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3951 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3952 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3953 tryToCloneSchema(p, newDb, "type!='table'", 0);
3954 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3955 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3957 sqlite3_close(newDb);
3961 ** Change the output file back to stdout
3963 static void output_reset(ShellState *p){
3964 if( p->outfile[0]=='|' ){
3965 #ifndef SQLITE_OMIT_POPEN
3969 output_file_close(p->out);
3976 ** Run an SQL command and return the single integer result.
3978 static int db_int(ShellState *p, const char *zSql){
3979 sqlite3_stmt *pStmt;
3981 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3982 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3983 res = sqlite3_column_int(pStmt,0);
3985 sqlite3_finalize(pStmt);
3990 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3992 static unsigned int get2byteInt(unsigned char *a){
3993 return (a[0]<<8) + a[1];
3995 static unsigned int get4byteInt(unsigned char *a){
3996 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4000 ** Implementation of the ".info" command.
4002 ** Return 1 on error, 2 to exit, and 0 otherwise.
4004 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4005 static const struct { const char *zName; int ofst; } aField[] = {
4006 { "file change counter:", 24 },
4007 { "database page count:", 28 },
4008 { "freelist page count:", 36 },
4009 { "schema cookie:", 40 },
4010 { "schema format:", 44 },
4011 { "default cache size:", 48 },
4012 { "autovacuum top root:", 52 },
4013 { "incremental vacuum:", 64 },
4014 { "text encoding:", 56 },
4015 { "user version:", 60 },
4016 { "application id:", 68 },
4017 { "software version:", 96 },
4019 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4020 { "number of tables:",
4021 "SELECT count(*) FROM %s WHERE type='table'" },
4022 { "number of indexes:",
4023 "SELECT count(*) FROM %s WHERE type='index'" },
4024 { "number of triggers:",
4025 "SELECT count(*) FROM %s WHERE type='trigger'" },
4026 { "number of views:",
4027 "SELECT count(*) FROM %s WHERE type='view'" },
4029 "SELECT total(length(sql)) FROM %s" },
4031 sqlite3_file *pFile = 0;
4034 char *zDb = nArg>=2 ? azArg[1] : "main";
4035 unsigned char aHdr[100];
4037 if( p->db==0 ) return 1;
4038 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
4039 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4042 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4044 raw_printf(stderr, "unable to read database header\n");
4047 i = get2byteInt(aHdr+16);
4048 if( i==1 ) i = 65536;
4049 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4050 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4051 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4052 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4053 for(i=0; i<ArraySize(aField); i++){
4054 int ofst = aField[i].ofst;
4055 unsigned int val = get4byteInt(aHdr + ofst);
4056 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4059 if( val==1 ) raw_printf(p->out, " (utf8)");
4060 if( val==2 ) raw_printf(p->out, " (utf16le)");
4061 if( val==3 ) raw_printf(p->out, " (utf16be)");
4064 raw_printf(p->out, "\n");
4067 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4068 }else if( strcmp(zDb,"temp")==0 ){
4069 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4071 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4073 for(i=0; i<ArraySize(aQuery); i++){
4074 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4075 int val = db_int(p, zSql);
4077 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4079 sqlite3_free(zSchemaTab);
4084 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4086 static int shellDatabaseError(sqlite3 *db){
4087 const char *zErr = sqlite3_errmsg(db);
4088 utf8_printf(stderr, "Error: %s\n", zErr);
4093 ** Print an out-of-memory message to stderr and return 1.
4095 static int shellNomemError(void){
4096 raw_printf(stderr, "Error: out of memory\n");
4101 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4102 ** if they match and FALSE (0) if they do not match.
4106 ** '*' Matches any sequence of zero or more characters.
4108 ** '?' Matches exactly one character.
4110 ** [...] Matches one character from the enclosed list of
4113 ** [^...] Matches one character not in the enclosed list.
4115 ** '#' Matches any sequence of one or more digits with an
4116 ** optional + or - sign in front
4118 ** ' ' Any span of whitespace matches any other span of
4121 ** Extra whitespace at the end of z[] is ignored.
4123 static int testcase_glob(const char *zGlob, const char *z){
4128 while( (c = (*(zGlob++)))!=0 ){
4130 if( !IsSpace(*z) ) return 0;
4131 while( IsSpace(*zGlob) ) zGlob++;
4132 while( IsSpace(*z) ) z++;
4134 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4135 if( c=='?' && (*(z++))==0 ) return 0;
4140 while( *z && testcase_glob(zGlob-1,z)==0 ){
4145 while( (c2 = (*(z++)))!=0 ){
4148 if( c2==0 ) return 0;
4150 if( testcase_glob(zGlob,z) ) return 1;
4154 if( (*(z++))==0 ) return 0;
4160 if( c==0 ) return 0;
4167 if( c==']' ) seen = 1;
4170 while( c2 && c2!=']' ){
4171 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4173 if( c>=prior_c && c<=c2 ) seen = 1;
4183 if( c2==0 || (seen ^ invert)==0 ) return 0;
4185 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4186 if( !IsDigit(z[0]) ) return 0;
4188 while( IsDigit(z[0]) ){ z++; }
4190 if( c!=(*(z++)) ) return 0;
4193 while( IsSpace(*z) ){ z++; }
4199 ** Compare the string as a command-line option with either one or two
4200 ** initial "-" characters.
4202 static int optionMatch(const char *zStr, const char *zOpt){
4203 if( zStr[0]!='-' ) return 0;
4205 if( zStr[0]=='-' ) zStr++;
4206 return strcmp(zStr, zOpt)==0;
4212 int shellDeleteFile(const char *zFilename){
4215 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4219 rc = unlink(zFilename);
4226 ** The implementation of SQL scalar function fkey_collate_clause(), used
4227 ** by the ".lint fkey-indexes" command. This scalar function is always
4228 ** called with four arguments - the parent table name, the parent column name,
4229 ** the child table name and the child column name.
4231 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4233 ** If either of the named tables or columns do not exist, this function
4234 ** returns an empty string. An empty string is also returned if both tables
4235 ** and columns exist but have the same default collation sequence. Or,
4236 ** if both exist but the default collation sequences are different, this
4237 ** function returns the string " COLLATE <parent-collation>", where
4238 ** <parent-collation> is the default collation sequence of the parent column.
4240 static void shellFkeyCollateClause(
4241 sqlite3_context *pCtx,
4243 sqlite3_value **apVal
4245 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4246 const char *zParent;
4247 const char *zParentCol;
4248 const char *zParentSeq;
4250 const char *zChildCol;
4251 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4255 zParent = (const char*)sqlite3_value_text(apVal[0]);
4256 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4257 zChild = (const char*)sqlite3_value_text(apVal[2]);
4258 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4260 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4261 rc = sqlite3_table_column_metadata(
4262 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4264 if( rc==SQLITE_OK ){
4265 rc = sqlite3_table_column_metadata(
4266 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4270 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4271 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4272 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4279 ** The implementation of dot-command ".lint fkey-indexes".
4281 static int lintFkeyIndexes(
4282 ShellState *pState, /* Current shell tool state */
4283 char **azArg, /* Array of arguments passed to dot command */
4284 int nArg /* Number of entries in azArg[] */
4286 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4287 FILE *out = pState->out; /* Stream to write non-error output to */
4288 int bVerbose = 0; /* If -verbose is present */
4289 int bGroupByParent = 0; /* If -groupbyparent is present */
4290 int i; /* To iterate through azArg[] */
4291 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4292 int rc; /* Return code */
4293 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4296 ** This SELECT statement returns one row for each foreign key constraint
4297 ** in the schema of the main database. The column values are:
4299 ** 0. The text of an SQL statement similar to:
4301 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4303 ** This is the same SELECT that the foreign keys implementation needs
4304 ** to run internally on child tables. If there is an index that can
4305 ** be used to optimize this query, then it can also be used by the FK
4306 ** implementation to optimize DELETE or UPDATE statements on the parent
4309 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4310 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4311 ** contains an index that can be used to optimize the query.
4313 ** 2. Human readable text that describes the child table and columns. e.g.
4315 ** "child_table(child_key1, child_key2)"
4317 ** 3. Human readable text that describes the parent table and columns. e.g.
4319 ** "parent_table(parent_key1, parent_key2)"
4321 ** 4. A full CREATE INDEX statement for an index that could be used to
4322 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4324 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4326 ** 5. The name of the parent table.
4328 ** These six values are used by the C logic below to generate the report.
4332 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4333 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4334 " || fkey_collate_clause(f.[table], f.[to], s.name, f.[from]),' AND ')"
4336 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4337 " || group_concat('*=?', ' AND ') || ')'"
4339 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4341 " f.[table] || '(' || group_concat(COALESCE(f.[to], "
4342 " (SELECT name FROM pragma_table_info(f.[table]) WHERE pk=seq+1)"
4345 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4346 " || ' ON ' || quote(s.name) || '('"
4347 " || group_concat(quote(f.[from]) ||"
4348 " fkey_collate_clause(f.[table], f.[to], s.name, f.[from]), ', ')"
4353 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4354 "GROUP BY s.name, f.id "
4355 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4358 for(i=2; i<nArg; i++){
4359 int n = (int)strlen(azArg[i]);
4360 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4363 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4368 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4371 return SQLITE_ERROR;
4375 /* Register the fkey_collate_clause() SQL function */
4376 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4377 0, shellFkeyCollateClause, 0, 0
4381 if( rc==SQLITE_OK ){
4382 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4384 if( rc==SQLITE_OK ){
4385 sqlite3_bind_int(pSql, 1, bGroupByParent);
4388 if( rc==SQLITE_OK ){
4391 while( SQLITE_ROW==sqlite3_step(pSql) ){
4393 sqlite3_stmt *pExplain = 0;
4394 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4395 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4396 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4397 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4398 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4399 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4401 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4402 if( rc!=SQLITE_OK ) break;
4403 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4404 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4405 res = (0==sqlite3_strglob(zGlob, zPlan));
4407 rc = sqlite3_finalize(pExplain);
4408 if( rc!=SQLITE_OK ) break;
4411 raw_printf(stderr, "Error: internal error");
4415 && (bVerbose || res==0)
4416 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4418 raw_printf(out, "-- Parent table %s\n", zParent);
4419 sqlite3_free(zPrev);
4420 zPrev = sqlite3_mprintf("%s", zParent);
4424 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4425 }else if( bVerbose ){
4426 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4427 zIndent, zFrom, zTarget
4432 sqlite3_free(zPrev);
4434 if( rc!=SQLITE_OK ){
4435 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4438 rc2 = sqlite3_finalize(pSql);
4439 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4441 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4444 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4451 ** Implementation of ".lint" dot command.
4453 static int lintDotCommand(
4454 ShellState *pState, /* Current shell tool state */
4455 char **azArg, /* Array of arguments passed to dot command */
4456 int nArg /* Number of entries in azArg[] */
4459 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
4460 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4461 return lintFkeyIndexes(pState, azArg, nArg);
4464 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4465 raw_printf(stderr, "Where sub-commands are:\n");
4466 raw_printf(stderr, " fkey-indexes\n");
4467 return SQLITE_ERROR;
4472 ** If an input line begins with "." then invoke this routine to
4473 ** process that line.
4475 ** Return 1 on error, 2 to exit, and 0 otherwise.
4477 static int do_meta_command(char *zLine, ShellState *p){
4484 /* Parse the input line into tokens.
4486 while( zLine[h] && nArg<ArraySize(azArg) ){
4487 while( IsSpace(zLine[h]) ){ h++; }
4488 if( zLine[h]==0 ) break;
4489 if( zLine[h]=='\'' || zLine[h]=='"' ){
4490 int delim = zLine[h++];
4491 azArg[nArg++] = &zLine[h];
4492 while( zLine[h] && zLine[h]!=delim ){
4493 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
4496 if( zLine[h]==delim ){
4499 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
4501 azArg[nArg++] = &zLine[h];
4502 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4503 if( zLine[h] ) zLine[h++] = 0;
4504 resolve_backslashes(azArg[nArg-1]);
4508 /* Process the input line.
4510 if( nArg==0 ) return 0; /* no tokens, no error */
4511 n = strlen30(azArg[0]);
4514 #ifndef SQLITE_OMIT_AUTHORIZATION
4515 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4517 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4519 goto meta_command_exit;
4522 if( booleanValue(azArg[1]) ){
4523 sqlite3_set_authorizer(p->db, shellAuth, p);
4525 sqlite3_set_authorizer(p->db, 0, 0);
4530 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4531 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4533 const char *zDestFile = 0;
4534 const char *zDb = 0;
4536 sqlite3_backup *pBackup;
4538 for(j=1; j<nArg; j++){
4539 const char *z = azArg[j];
4541 while( z[0]=='-' ) z++;
4542 /* No options to process at this time */
4544 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
4547 }else if( zDestFile==0 ){
4548 zDestFile = azArg[j];
4551 zDestFile = azArg[j];
4553 raw_printf(stderr, "too many arguments to .backup\n");
4558 raw_printf(stderr, "missing FILENAME argument on .backup\n");
4561 if( zDb==0 ) zDb = "main";
4562 rc = sqlite3_open(zDestFile, &pDest);
4563 if( rc!=SQLITE_OK ){
4564 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
4565 sqlite3_close(pDest);
4569 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4571 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4572 sqlite3_close(pDest);
4575 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4576 sqlite3_backup_finish(pBackup);
4577 if( rc==SQLITE_DONE ){
4580 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4583 sqlite3_close(pDest);
4586 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4588 bail_on_error = booleanValue(azArg[1]);
4590 raw_printf(stderr, "Usage: .bail on|off\n");
4595 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4597 if( booleanValue(azArg[1]) ){
4598 setBinaryMode(p->out, 1);
4600 setTextMode(p->out, 1);
4603 raw_printf(stderr, "Usage: .binary on|off\n");
4608 /* The undocumented ".breakpoint" command causes a call to the no-op
4609 ** routine named test_breakpoint().
4611 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4615 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4617 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
4619 raw_printf(stderr, "Usage: .changes on|off\n");
4624 /* Cancel output redirection, if it is currently set (by .testcase)
4625 ** Then read the content of the testcase-out.txt file and compare against
4626 ** azArg[1]. If there are differences, report an error and exit.
4628 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4632 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
4634 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
4635 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4637 }else if( testcase_glob(azArg[1],zRes)==0 ){
4639 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4640 p->zTestcase, azArg[1], zRes);
4643 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
4649 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4651 tryToClone(p, azArg[1]);
4653 raw_printf(stderr, "Usage: .clone FILENAME\n");
4658 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
4662 memcpy(&data, p, sizeof(data));
4663 data.showHeader = 0;
4664 data.cMode = data.mode = MODE_List;
4665 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
4667 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4668 callback, &data, &zErrMsg);
4670 utf8_printf(stderr,"Error: %s\n", zErrMsg);
4671 sqlite3_free(zErrMsg);
4676 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4677 rc = shell_dbinfo_command(p, nArg, azArg);
4680 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
4681 const char *zLike = 0;
4683 ShellClearFlag(p, SHFLG_PreserveRowid);
4684 for(i=1; i<nArg; i++){
4685 if( azArg[i][0]=='-' ){
4686 const char *z = azArg[i]+1;
4687 if( z[0]=='-' ) z++;
4688 if( strcmp(z,"preserve-rowids")==0 ){
4689 #ifdef SQLITE_OMIT_VIRTUALTABLE
4690 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4691 " with SQLITE_OMIT_VIRTUALTABLE\n");
4693 goto meta_command_exit;
4695 ShellSetFlag(p, SHFLG_PreserveRowid);
4699 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4701 goto meta_command_exit;
4704 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4706 goto meta_command_exit;
4712 /* When playing back a "dump", the content might appear in an order
4713 ** which causes immediate foreign key constraints to be violated.
4714 ** So disable foreign-key constraint enforcement to prevent problems. */
4715 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4716 raw_printf(p->out, "BEGIN TRANSACTION;\n");
4717 p->writableSchema = 0;
4718 /* Set writable_schema=ON since doing so forces SQLite to initialize
4719 ** as much of the schema as it can even if the sqlite_master table is
4721 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4724 run_schema_dump_query(p,
4725 "SELECT name, type, sql FROM sqlite_master "
4726 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4728 run_schema_dump_query(p,
4729 "SELECT name, type, sql FROM sqlite_master "
4730 "WHERE name=='sqlite_sequence'"
4732 run_table_dump_query(p,
4733 "SELECT sql FROM sqlite_master "
4734 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4738 zSql = sqlite3_mprintf(
4739 "SELECT name, type, sql FROM sqlite_master "
4740 "WHERE tbl_name LIKE %Q AND type=='table'"
4741 " AND sql NOT NULL", zLike);
4742 run_schema_dump_query(p,zSql);
4744 zSql = sqlite3_mprintf(
4745 "SELECT sql FROM sqlite_master "
4746 "WHERE sql NOT NULL"
4747 " AND type IN ('index','trigger','view')"
4748 " AND tbl_name LIKE %Q", zLike);
4749 run_table_dump_query(p, zSql, 0);
4752 if( p->writableSchema ){
4753 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
4754 p->writableSchema = 0;
4756 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4757 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
4758 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4761 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4763 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
4765 raw_printf(stderr, "Usage: .echo on|off\n");
4770 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4772 if( strcmp(azArg[1],"full")==0 ){
4775 p->autoEQP = booleanValue(azArg[1]);
4778 raw_printf(stderr, "Usage: .eqp on|off|full\n");
4783 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
4784 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
4788 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
4791 if( strcmp(azArg[1],"auto")==0 ){
4794 val = booleanValue(azArg[1]);
4797 if( val==1 && p->mode!=MODE_Explain ){
4798 p->normalMode = p->mode;
4799 p->mode = MODE_Explain;
4802 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4804 }else if( val==99 ){
4805 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4810 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
4814 memcpy(&data, p, sizeof(data));
4815 data.showHeader = 0;
4816 data.cMode = data.mode = MODE_Semi;
4817 if( nArg==2 && optionMatch(azArg[1], "indent") ){
4818 data.cMode = data.mode = MODE_Pretty;
4822 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
4824 goto meta_command_exit;
4827 rc = sqlite3_exec(p->db,
4829 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4830 " FROM sqlite_master UNION ALL"
4831 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4832 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4834 callback, &data, &zErrMsg
4836 if( rc==SQLITE_OK ){
4837 sqlite3_stmt *pStmt;
4838 rc = sqlite3_prepare_v2(p->db,
4839 "SELECT rowid FROM sqlite_master"
4840 " WHERE name GLOB 'sqlite_stat[134]'",
4842 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4843 sqlite3_finalize(pStmt);
4846 raw_printf(p->out, "/* No STAT tables available */\n");
4848 raw_printf(p->out, "ANALYZE sqlite_master;\n");
4849 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4850 callback, &data, &zErrMsg);
4851 data.cMode = data.mode = MODE_Insert;
4852 data.zDestTable = "sqlite_stat1";
4853 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4854 shell_callback, &data,&zErrMsg);
4855 data.zDestTable = "sqlite_stat3";
4856 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4857 shell_callback, &data,&zErrMsg);
4858 data.zDestTable = "sqlite_stat4";
4859 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4860 shell_callback, &data, &zErrMsg);
4861 raw_printf(p->out, "ANALYZE sqlite_master;\n");
4865 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4867 p->showHeader = booleanValue(azArg[1]);
4869 raw_printf(stderr, "Usage: .headers on|off\n");
4874 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
4875 utf8_printf(p->out, "%s", zHelp);
4878 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
4879 char *zTable; /* Insert data into this table */
4880 char *zFile; /* Name of file to extra content from */
4881 sqlite3_stmt *pStmt = NULL; /* A statement */
4882 int nCol; /* Number of columns in the table */
4883 int nByte; /* Number of bytes in an SQL string */
4884 int i, j; /* Loop counters */
4885 int needCommit; /* True to COMMIT or ROLLBACK at end */
4886 int nSep; /* Number of bytes in p->colSeparator[] */
4887 char *zSql; /* An SQL statement */
4888 ImportCtx sCtx; /* Reader context */
4889 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4890 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
4893 raw_printf(stderr, "Usage: .import FILE TABLE\n");
4894 goto meta_command_exit;
4899 memset(&sCtx, 0, sizeof(sCtx));
4901 nSep = strlen30(p->colSeparator);
4904 "Error: non-null column separator required for import\n");
4908 raw_printf(stderr, "Error: multi-character column separators not allowed"
4912 nSep = strlen30(p->rowSeparator);
4914 raw_printf(stderr, "Error: non-null row separator required for import\n");
4917 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4918 /* When importing CSV (only), if the row separator is set to the
4919 ** default output row separator, change it to the default input
4920 ** row separator. This avoids having to maintain different input
4921 ** and output row separators. */
4922 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4923 nSep = strlen30(p->rowSeparator);
4926 raw_printf(stderr, "Error: multi-character row separators not allowed"
4932 if( sCtx.zFile[0]=='|' ){
4933 #ifdef SQLITE_OMIT_POPEN
4934 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4937 sCtx.in = popen(sCtx.zFile+1, "r");
4938 sCtx.zFile = "<pipe>";
4942 sCtx.in = fopen(sCtx.zFile, "rb");
4945 if( p->mode==MODE_Ascii ){
4946 xRead = ascii_read_one_field;
4948 xRead = csv_read_one_field;
4951 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4954 sCtx.cColSep = p->colSeparator[0];
4955 sCtx.cRowSep = p->rowSeparator[0];
4956 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
4958 raw_printf(stderr, "Error: out of memory\n");
4962 nByte = strlen30(zSql);
4963 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4964 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
4965 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
4966 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
4968 while( xRead(&sCtx) ){
4969 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
4971 if( sCtx.cTerm!=sCtx.cColSep ) break;
4974 sqlite3_free(zCreate);
4975 sqlite3_free(sCtx.z);
4977 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
4980 zCreate = sqlite3_mprintf("%z\n)", zCreate);
4981 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
4982 sqlite3_free(zCreate);
4984 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
4985 sqlite3_errmsg(p->db));
4986 sqlite3_free(sCtx.z);
4990 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4994 if (pStmt) sqlite3_finalize(pStmt);
4995 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
4999 nCol = sqlite3_column_count(pStmt);
5000 sqlite3_finalize(pStmt);
5002 if( nCol==0 ) return 0; /* no columns, no error */
5003 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5005 raw_printf(stderr, "Error: out of memory\n");
5009 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5011 for(i=1; i<nCol; i++){
5017 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5020 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5021 if (pStmt) sqlite3_finalize(pStmt);
5025 needCommit = sqlite3_get_autocommit(p->db);
5026 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5028 int startLine = sCtx.nLine;
5029 for(i=0; i<nCol; i++){
5030 char *z = xRead(&sCtx);
5032 ** Did we reach end-of-file before finding any columns?
5033 ** If so, stop instead of NULL filling the remaining columns.
5035 if( z==0 && i==0 ) break;
5037 ** Did we reach end-of-file OR end-of-line before finding any
5038 ** columns in ASCII mode? If so, stop instead of NULL filling
5039 ** the remaining columns.
5041 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5042 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5043 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5044 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5045 "filling the rest with NULL\n",
5046 sCtx.zFile, startLine, nCol, i+1);
5048 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5051 if( sCtx.cTerm==sCtx.cColSep ){
5055 }while( sCtx.cTerm==sCtx.cColSep );
5056 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5058 sCtx.zFile, startLine, nCol, i);
5061 sqlite3_step(pStmt);
5062 rc = sqlite3_reset(pStmt);
5063 if( rc!=SQLITE_OK ){
5064 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5065 startLine, sqlite3_errmsg(p->db));
5068 }while( sCtx.cTerm!=EOF );
5071 sqlite3_free(sCtx.z);
5072 sqlite3_finalize(pStmt);
5073 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5076 #ifndef SQLITE_UNTESTABLE
5077 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5080 sqlite3_stmt *pStmt;
5084 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5086 goto meta_command_exit;
5089 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5090 " WHERE name='%q' AND type='index'", azArg[1]);
5091 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5093 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5094 tnum = sqlite3_column_int(pStmt, 0);
5096 sqlite3_finalize(pStmt);
5098 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5100 goto meta_command_exit;
5102 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5103 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5106 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5108 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5111 if( sqlite3_column_int(pStmt,1)==-1 ){
5114 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5119 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5121 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5124 sqlite3_finalize(pStmt);
5125 zSql = sqlite3_mprintf(
5126 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5127 azArg[2], zCollist, zCollist);
5128 sqlite3_free(zCollist);
5129 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5130 if( rc==SQLITE_OK ){
5131 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5132 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5134 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5136 utf8_printf(stdout, "%s;\n", zSql);
5138 "WARNING: writing to an imposter table will corrupt the index!\n"
5142 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5147 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5149 #ifdef SQLITE_ENABLE_IOTRACE
5150 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5151 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5152 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5156 }else if( strcmp(azArg[1], "-")==0 ){
5157 sqlite3IoTrace = iotracePrintf;
5160 iotrace = fopen(azArg[1], "w");
5162 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5166 sqlite3IoTrace = iotracePrintf;
5172 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5173 static const struct {
5174 const char *zLimitName; /* Name of a limit */
5175 int limitCode; /* Integer code for that limit */
5177 { "length", SQLITE_LIMIT_LENGTH },
5178 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5179 { "column", SQLITE_LIMIT_COLUMN },
5180 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5181 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5182 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5183 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5184 { "attached", SQLITE_LIMIT_ATTACHED },
5185 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5186 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5187 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5188 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5193 for(i=0; i<ArraySize(aLimit); i++){
5194 printf("%20s %d\n", aLimit[i].zLimitName,
5195 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5198 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5200 goto meta_command_exit;
5203 n2 = strlen30(azArg[1]);
5204 for(i=0; i<ArraySize(aLimit); i++){
5205 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5209 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5211 goto meta_command_exit;
5216 utf8_printf(stderr, "unknown limit: \"%s\"\n"
5217 "enter \".limits\" with no arguments for a list.\n",
5220 goto meta_command_exit;
5223 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5224 (int)integerValue(azArg[2]));
5226 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5227 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5231 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5233 lintDotCommand(p, azArg, nArg);
5236 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5237 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5238 const char *zFile, *zProc;
5241 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5243 goto meta_command_exit;
5246 zProc = nArg>=3 ? azArg[2] : 0;
5248 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5249 if( rc!=SQLITE_OK ){
5250 utf8_printf(stderr, "Error: %s\n", zErrMsg);
5251 sqlite3_free(zErrMsg);
5257 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5259 raw_printf(stderr, "Usage: .log FILENAME\n");
5262 const char *zFile = azArg[1];
5263 output_file_close(p->pLog);
5264 p->pLog = output_file_open(zFile);
5268 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5269 const char *zMode = nArg>=2 ? azArg[1] : "";
5270 int n2 = (int)strlen(zMode);
5272 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
5273 p->mode = MODE_Line;
5274 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5275 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
5276 p->mode = MODE_Column;
5277 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5278 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
5279 p->mode = MODE_List;
5280 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5281 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5282 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
5283 p->mode = MODE_Html;
5284 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
5286 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
5287 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5288 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
5290 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
5291 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
5292 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
5293 p->mode = MODE_List;
5294 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
5295 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
5296 p->mode = MODE_Insert;
5297 set_table_name(p, nArg>=3 ? azArg[2] : "table");
5298 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5299 p->mode = MODE_Quote;
5300 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5301 p->mode = MODE_Ascii;
5302 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5303 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
5305 raw_printf(stderr, "Error: mode should be one of: "
5306 "ascii column csv html insert line list quote tabs tcl\n");
5312 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5314 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5315 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
5317 raw_printf(stderr, "Usage: .nullvalue STRING\n");
5322 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
5323 char *zNewFilename; /* Name of the database file to open */
5324 int iName = 1; /* Index in azArg[] of the filename */
5325 int newFlag = 0; /* True to delete file before opening */
5326 /* Close the existing database */
5327 session_close_all(p);
5328 sqlite3_close(p->db);
5331 sqlite3_free(p->zFreeOnClose);
5332 p->zFreeOnClose = 0;
5333 /* Check for command-line arguments */
5334 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5335 const char *z = azArg[iName];
5336 if( optionMatch(z,"new") ){
5338 }else if( z[0]=='-' ){
5339 utf8_printf(stderr, "unknown option: %s\n", z);
5341 goto meta_command_exit;
5344 /* If a filename is specified, try to open it first */
5345 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5347 if( newFlag ) shellDeleteFile(zNewFilename);
5348 p->zDbFilename = zNewFilename;
5351 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5352 sqlite3_free(zNewFilename);
5354 p->zFreeOnClose = zNewFilename;
5358 /* As a fall-back open a TEMP database */
5365 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5367 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5369 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
5371 goto meta_command_exit;
5373 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5375 raw_printf(stderr, "Usage: .once FILE\n");
5377 goto meta_command_exit;
5384 if( zFile[0]=='|' ){
5385 #ifdef SQLITE_OMIT_POPEN
5386 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5390 p->out = popen(zFile + 1, "w");
5392 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
5396 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5400 p->out = output_file_open(zFile);
5402 if( strcmp(zFile,"off")!=0 ){
5403 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
5408 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5413 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5415 for(i=1; i<nArg; i++){
5416 if( i>1 ) raw_printf(p->out, " ");
5417 utf8_printf(p->out, "%s", azArg[i]);
5419 raw_printf(p->out, "\n");
5422 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
5424 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5427 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5431 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
5435 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5438 raw_printf(stderr, "Usage: .read FILE\n");
5440 goto meta_command_exit;
5442 alt = fopen(azArg[1], "rb");
5444 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5447 rc = process_input(p, alt);
5452 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
5453 const char *zSrcFile;
5456 sqlite3_backup *pBackup;
5460 zSrcFile = azArg[1];
5462 }else if( nArg==3 ){
5463 zSrcFile = azArg[2];
5466 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
5468 goto meta_command_exit;
5470 rc = sqlite3_open(zSrcFile, &pSrc);
5471 if( rc!=SQLITE_OK ){
5472 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
5473 sqlite3_close(pSrc);
5477 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5479 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5480 sqlite3_close(pSrc);
5483 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5484 || rc==SQLITE_BUSY ){
5485 if( rc==SQLITE_BUSY ){
5486 if( nTimeout++ >= 3 ) break;
5490 sqlite3_backup_finish(pBackup);
5491 if( rc==SQLITE_DONE ){
5493 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
5494 raw_printf(stderr, "Error: source database is busy\n");
5497 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5500 sqlite3_close(pSrc);
5504 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5506 p->scanstatsOn = booleanValue(azArg[1]);
5507 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5508 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
5511 raw_printf(stderr, "Usage: .scanstats on|off\n");
5516 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
5520 memcpy(&data, p, sizeof(data));
5521 data.showHeader = 0;
5522 data.cMode = data.mode = MODE_Semi;
5523 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5524 data.cMode = data.mode = MODE_Pretty;
5526 if( nArg==2 ) azArg[1] = azArg[2];
5528 if( nArg==2 && azArg[1][0]!='-' ){
5530 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
5531 if( strcmp(azArg[1],"sqlite_master")==0 ){
5532 char *new_argv[2], *new_colv[2];
5533 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5537 " rootpage integer,\n"
5541 new_colv[0] = "sql";
5543 callback(&data, 1, new_argv, new_colv);
5545 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
5546 char *new_argv[2], *new_colv[2];
5547 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5551 " rootpage integer,\n"
5555 new_colv[0] = "sql";
5557 callback(&data, 1, new_argv, new_colv);
5561 zSql = sqlite3_mprintf(
5563 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5564 " FROM sqlite_master UNION ALL"
5565 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5566 "WHERE lower(tbl_name) LIKE %Q"
5567 " AND type!='meta' AND sql NOTNULL "
5568 "ORDER BY rowid", azArg[1]);
5569 rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
5572 }else if( nArg==1 ){
5573 rc = sqlite3_exec(p->db,
5575 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5576 " FROM sqlite_master UNION ALL"
5577 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5578 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5580 callback, &data, &zErrMsg
5583 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5585 goto meta_command_exit;
5588 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5589 sqlite3_free(zErrMsg);
5591 }else if( rc != SQLITE_OK ){
5592 raw_printf(stderr,"Error: querying schema information\n");
5599 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5600 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
5601 sqlite3SelectTrace = (int)integerValue(azArg[1]);
5605 #if defined(SQLITE_ENABLE_SESSION)
5606 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5607 OpenSession *pSession = &p->aSession[0];
5608 char **azCmd = &azArg[1];
5610 int nCmd = nArg - 1;
5612 if( nArg<=1 ) goto session_syntax_error;
5615 for(iSes=0; iSes<p->nSession; iSes++){
5616 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5618 if( iSes<p->nSession ){
5619 pSession = &p->aSession[iSes];
5623 pSession = &p->aSession[0];
5628 /* .session attach TABLE
5629 ** Invoke the sqlite3session_attach() interface to attach a particular
5630 ** table so that it is never filtered.
5632 if( strcmp(azCmd[0],"attach")==0 ){
5633 if( nCmd!=2 ) goto session_syntax_error;
5634 if( pSession->p==0 ){
5636 raw_printf(stderr, "ERROR: No sessions are open\n");
5638 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5640 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
5646 /* .session changeset FILE
5647 ** .session patchset FILE
5648 ** Write a changeset or patchset into a file. The file is overwritten.
5650 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5652 if( nCmd!=2 ) goto session_syntax_error;
5653 if( pSession->p==0 ) goto session_not_open;
5654 out = fopen(azCmd[1], "wb");
5656 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
5660 if( azCmd[0][0]=='c' ){
5661 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
5663 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5666 printf("Error: error code %d\n", rc);
5670 && fwrite(pChng, szChng, 1, out)!=1 ){
5671 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
5674 sqlite3_free(pChng);
5680 ** Close the identified session
5682 if( strcmp(azCmd[0], "close")==0 ){
5683 if( nCmd!=1 ) goto session_syntax_error;
5685 session_close(pSession);
5686 p->aSession[iSes] = p->aSession[--p->nSession];
5690 /* .session enable ?BOOLEAN?
5691 ** Query or set the enable flag
5693 if( strcmp(azCmd[0], "enable")==0 ){
5695 if( nCmd>2 ) goto session_syntax_error;
5696 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5698 ii = sqlite3session_enable(pSession->p, ii);
5699 utf8_printf(p->out, "session %s enable flag = %d\n",
5700 pSession->zName, ii);
5704 /* .session filter GLOB ....
5705 ** Set a list of GLOB patterns of table names to be excluded.
5707 if( strcmp(azCmd[0], "filter")==0 ){
5709 if( nCmd<2 ) goto session_syntax_error;
5711 for(ii=0; ii<pSession->nFilter; ii++){
5712 sqlite3_free(pSession->azFilter[ii]);
5714 sqlite3_free(pSession->azFilter);
5715 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5716 pSession->azFilter = sqlite3_malloc( nByte );
5717 if( pSession->azFilter==0 ){
5718 raw_printf(stderr, "Error: out or memory\n");
5721 for(ii=1; ii<nCmd; ii++){
5722 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
5724 pSession->nFilter = ii-1;
5728 /* .session indirect ?BOOLEAN?
5729 ** Query or set the indirect flag
5731 if( strcmp(azCmd[0], "indirect")==0 ){
5733 if( nCmd>2 ) goto session_syntax_error;
5734 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5736 ii = sqlite3session_indirect(pSession->p, ii);
5737 utf8_printf(p->out, "session %s indirect flag = %d\n",
5738 pSession->zName, ii);
5743 ** Determine if the session is empty
5745 if( strcmp(azCmd[0], "isempty")==0 ){
5747 if( nCmd!=1 ) goto session_syntax_error;
5749 ii = sqlite3session_isempty(pSession->p);
5750 utf8_printf(p->out, "session %s isempty flag = %d\n",
5751 pSession->zName, ii);
5756 ** List all currently open sessions
5758 if( strcmp(azCmd[0],"list")==0 ){
5759 for(i=0; i<p->nSession; i++){
5760 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
5764 /* .session open DB NAME
5765 ** Open a new session called NAME on the attached database DB.
5766 ** DB is normally "main".
5768 if( strcmp(azCmd[0],"open")==0 ){
5770 if( nCmd!=3 ) goto session_syntax_error;
5772 if( zName[0]==0 ) goto session_syntax_error;
5773 for(i=0; i<p->nSession; i++){
5774 if( strcmp(p->aSession[i].zName,zName)==0 ){
5775 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
5776 goto meta_command_exit;
5779 if( p->nSession>=ArraySize(p->aSession) ){
5780 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
5781 goto meta_command_exit;
5783 pSession = &p->aSession[p->nSession];
5784 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5786 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
5788 goto meta_command_exit;
5790 pSession->nFilter = 0;
5791 sqlite3session_table_filter(pSession->p, session_filter, pSession);
5793 pSession->zName = sqlite3_mprintf("%s", zName);
5795 /* If no command name matches, show a syntax error */
5796 session_syntax_error:
5802 /* Undocumented commands for internal testing. Subject to change
5803 ** without notice. */
5804 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5805 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5807 for(i=1; i<nArg; i++){
5808 v = booleanValue(azArg[i]);
5809 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
5812 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5813 int i; sqlite3_int64 v;
5814 for(i=1; i<nArg; i++){
5816 v = integerValue(azArg[i]);
5817 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
5818 utf8_printf(p->out, "%s", zBuf);
5824 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5825 int bIsInit = 0; /* True to initialize the SELFTEST table */
5826 int bVerbose = 0; /* Verbose output */
5827 int bSelftestExists; /* True if SELFTEST already exists */
5828 char **azTest = 0; /* Content of the SELFTEST table */
5829 int nRow = 0; /* Number of rows in the SELFTEST table */
5830 int nCol = 4; /* Number of columns in the SELFTEST table */
5831 int i; /* Loop counter */
5832 int nTest = 0; /* Number of tests runs */
5833 int nErr = 0; /* Number of errors seen */
5834 ShellText str; /* Answer for a query */
5835 static char *azDefaultTest[] = {
5837 "0", "memo", "Missing SELFTEST table - default checks only", "",
5838 "1", "run", "PRAGMA integrity_check", "ok"
5840 static const int nDefaultRow = 2;
5843 for(i=1; i<nArg; i++){
5844 const char *z = azArg[i];
5845 if( z[0]=='-' && z[1]=='-' ) z++;
5846 if( strcmp(z,"-init")==0 ){
5849 if( strcmp(z,"-v")==0 ){
5853 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5854 azArg[i], azArg[0]);
5855 raw_printf(stderr, "Should be one of: --init -v\n");
5857 goto meta_command_exit;
5860 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5862 bSelftestExists = 0;
5864 bSelftestExists = 1;
5867 createSelftestTable(p);
5868 bSelftestExists = 1;
5870 if( bSelftestExists ){
5871 rc = sqlite3_get_table(p->db,
5872 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5873 &azTest, &nRow, &nCol, 0);
5875 raw_printf(stderr, "Error querying the selftest table\n");
5877 sqlite3_free_table(azTest);
5878 goto meta_command_exit;
5879 }else if( nRow==0 ){
5880 sqlite3_free_table(azTest);
5881 azTest = azDefaultTest;
5885 azTest = azDefaultTest;
5889 appendText(&str, "x", 0);
5890 for(i=1; i<=nRow; i++){
5891 int tno = atoi(azTest[i*nCol]);
5892 const char *zOp = azTest[i*nCol+1];
5893 const char *zSql = azTest[i*nCol+2];
5894 const char *zAns = azTest[i*nCol+3];
5897 char *zQuote = sqlite3_mprintf("%q", zSql);
5898 printf("%d: %s %s\n", tno, zOp, zSql);
5899 sqlite3_free(zQuote);
5901 if( strcmp(zOp,"memo")==0 ){
5902 utf8_printf(p->out, "%s\n", zSql);
5904 if( strcmp(zOp,"run")==0 ){
5908 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5911 utf8_printf(p->out, "Result: %s\n", str.z);
5913 if( rc || zErrMsg ){
5916 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5917 sqlite3_free(zErrMsg);
5918 }else if( strcmp(zAns,str.z)!=0 ){
5921 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5922 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
5927 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5933 if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
5934 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5937 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
5938 if( nArg<2 || nArg>3 ){
5939 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
5943 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
5944 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
5947 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5948 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
5952 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5953 const char *zLike = 0; /* Which table to checksum. 0 means everything */
5954 int i; /* Loop counter */
5955 int bSchema = 0; /* Also hash the schema */
5956 int bSeparate = 0; /* Hash each table separately */
5957 int iSize = 224; /* Hash algorithm to use */
5958 int bDebug = 0; /* Only show the query that would have run */
5959 sqlite3_stmt *pStmt; /* For querying tables names */
5960 char *zSql; /* SQL to be run */
5961 char *zSep; /* Separator */
5962 ShellText sSql; /* Complete SQL for the query to run the hash */
5963 ShellText sQuery; /* Set of queries used to read all content */
5965 for(i=1; i<nArg; i++){
5966 const char *z = azArg[i];
5969 if( z[0]=='-' ) z++;
5970 if( strcmp(z,"schema")==0 ){
5973 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
5974 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
5976 iSize = atoi(&z[5]);
5978 if( strcmp(z,"debug")==0 ){
5982 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5983 azArg[i], azArg[0]);
5984 raw_printf(stderr, "Should be one of: --schema"
5985 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5987 goto meta_command_exit;
5990 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5992 goto meta_command_exit;
5996 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
6000 zSql = "SELECT lower(name) FROM sqlite_master"
6001 " WHERE type='table' AND coalesce(rootpage,0)>1"
6002 " UNION ALL SELECT 'sqlite_master'"
6003 " ORDER BY 1 collate nocase";
6005 zSql = "SELECT lower(name) FROM sqlite_master"
6006 " WHERE type='table' AND coalesce(rootpage,0)>1"
6007 " AND name NOT LIKE 'sqlite_%'"
6008 " ORDER BY 1 collate nocase";
6010 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6013 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6015 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6016 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6017 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6018 if( strncmp(zTab, "sqlite_",7)!=0 ){
6019 appendText(&sQuery,"SELECT * FROM ", 0);
6020 appendText(&sQuery,zTab,'"');
6021 appendText(&sQuery," NOT INDEXED;", 0);
6022 }else if( strcmp(zTab, "sqlite_master")==0 ){
6023 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6024 " ORDER BY name;", 0);
6025 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6026 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6027 " ORDER BY name;", 0);
6028 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6029 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6030 " ORDER BY tbl,idx;", 0);
6031 }else if( strcmp(zTab, "sqlite_stat3")==0
6032 || strcmp(zTab, "sqlite_stat4")==0 ){
6033 appendText(&sQuery, "SELECT * FROM ", 0);
6034 appendText(&sQuery, zTab, 0);
6035 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6037 appendText(&sSql, zSep, 0);
6038 appendText(&sSql, sQuery.z, '\'');
6040 appendText(&sSql, ",", 0);
6041 appendText(&sSql, zTab, '\'');
6044 sqlite3_finalize(pStmt);
6046 zSql = sqlite3_mprintf(
6048 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6049 " FROM [sha3sum$query]",
6052 zSql = sqlite3_mprintf(
6054 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6055 " FROM [sha3sum$query]",
6061 utf8_printf(p->out, "%s\n", zSql);
6063 shell_exec(p->db, zSql, shell_callback, p, 0);
6069 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6074 raw_printf(stderr, "Usage: .system COMMAND\n");
6076 goto meta_command_exit;
6078 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6079 for(i=2; i<nArg; i++){
6080 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6085 if( x ) raw_printf(stderr, "System command returns %d\n", x);
6088 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
6089 static const char *azBool[] = { "off", "on", "full", "unk" };
6092 raw_printf(stderr, "Usage: .show\n");
6094 goto meta_command_exit;
6096 utf8_printf(p->out, "%12.12s: %s\n","echo",
6097 azBool[ShellHasFlag(p, SHFLG_Echo)]);
6098 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6099 utf8_printf(p->out, "%12.12s: %s\n","explain",
6100 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6101 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6102 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6103 utf8_printf(p->out, "%12.12s: ", "nullvalue");
6104 output_c_string(p->out, p->nullValue);
6105 raw_printf(p->out, "\n");
6106 utf8_printf(p->out,"%12.12s: %s\n","output",
6107 strlen30(p->outfile) ? p->outfile : "stdout");
6108 utf8_printf(p->out,"%12.12s: ", "colseparator");
6109 output_c_string(p->out, p->colSeparator);
6110 raw_printf(p->out, "\n");
6111 utf8_printf(p->out,"%12.12s: ", "rowseparator");
6112 output_c_string(p->out, p->rowSeparator);
6113 raw_printf(p->out, "\n");
6114 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6115 utf8_printf(p->out, "%12.12s: ", "width");
6116 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6117 raw_printf(p->out, "%d ", p->colWidth[i]);
6119 raw_printf(p->out, "\n");
6120 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6121 p->zDbFilename ? p->zDbFilename : "");
6124 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6126 p->statsOn = booleanValue(azArg[1]);
6127 }else if( nArg==1 ){
6128 display_stats(p->db, p, 0);
6130 raw_printf(stderr, "Usage: .stats ?on|off?\n");
6135 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6136 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6137 || strncmp(azArg[0], "indexes", n)==0) )
6139 sqlite3_stmt *pStmt;
6145 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6146 if( rc ) return shellDatabaseError(p->db);
6148 /* Create an SQL statement to query for the list of tables in the
6149 ** main and all attached databases where the table name matches the
6150 ** LIKE pattern bound to variable "?1". */
6152 zSql = sqlite3_mprintf(
6153 "SELECT name FROM sqlite_master"
6154 " WHERE type IN ('table','view')"
6155 " AND name NOT LIKE 'sqlite_%%'"
6156 " AND name LIKE ?1");
6158 /* It is an historical accident that the .indexes command shows an error
6159 ** when called with the wrong number of arguments whereas the .tables
6160 ** command does not. */
6161 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6163 goto meta_command_exit;
6165 zSql = sqlite3_mprintf(
6166 "SELECT name FROM sqlite_master"
6167 " WHERE type='index'"
6168 " AND tbl_name LIKE ?1");
6170 for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6171 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6172 if( zDbName==0 || ii==0 ) continue;
6174 zSql = sqlite3_mprintf(
6176 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6177 " WHERE type IN ('table','view')"
6178 " AND name NOT LIKE 'sqlite_%%'"
6179 " AND name LIKE ?1", zSql, zDbName, zDbName);
6181 zSql = sqlite3_mprintf(
6183 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6184 " WHERE type='index'"
6185 " AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
6188 rc = sqlite3_finalize(pStmt);
6189 if( zSql && rc==SQLITE_OK ){
6190 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6191 if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6194 if( !zSql ) return shellNomemError();
6195 if( rc ) return shellDatabaseError(p->db);
6197 /* Run the SQL statement prepared by the above block. Store the results
6198 ** as an array of nul-terminated strings in azResult[]. */
6202 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6204 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6206 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6209 int n2 = nAlloc*2 + 10;
6210 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6212 rc = shellNomemError();
6218 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6219 if( 0==azResult[nRow] ){
6220 rc = shellNomemError();
6225 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6226 rc = shellDatabaseError(p->db);
6229 /* Pretty-print the contents of array azResult[] to the output */
6230 if( rc==0 && nRow>0 ){
6231 int len, maxlen = 0;
6233 int nPrintCol, nPrintRow;
6234 for(i=0; i<nRow; i++){
6235 len = strlen30(azResult[i]);
6236 if( len>maxlen ) maxlen = len;
6238 nPrintCol = 80/(maxlen+2);
6239 if( nPrintCol<1 ) nPrintCol = 1;
6240 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6241 for(i=0; i<nPrintRow; i++){
6242 for(j=i; j<nRow; j+=nPrintRow){
6243 char *zSp = j<nPrintRow ? "" : " ";
6244 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6245 azResult[j] ? azResult[j]:"");
6247 raw_printf(p->out, "\n");
6251 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6252 sqlite3_free(azResult);
6255 /* Begin redirecting output to the file "testcase-out.txt" */
6256 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6258 p->out = output_file_open("testcase-out.txt");
6260 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
6263 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6265 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6269 #ifndef SQLITE_UNTESTABLE
6270 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
6271 static const struct {
6272 const char *zCtrlName; /* Name of a test-control option */
6273 int ctrlCode; /* Integer code for that option */
6275 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6276 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6277 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6278 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6279 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6280 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6281 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6282 { "assert", SQLITE_TESTCTRL_ASSERT },
6283 { "always", SQLITE_TESTCTRL_ALWAYS },
6284 { "reserve", SQLITE_TESTCTRL_RESERVE },
6285 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6286 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
6287 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
6288 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
6289 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
6290 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
6297 /* convert testctrl text option to value. allow any unique prefix
6298 ** of the option name, or a numerical value. */
6299 n2 = strlen30(azArg[1]);
6300 for(i=0; i<ArraySize(aCtrl); i++){
6301 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
6303 testctrl = aCtrl[i].ctrlCode;
6305 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
6311 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
6312 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
6313 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
6317 /* sqlite3_test_control(int, db, int) */
6318 case SQLITE_TESTCTRL_OPTIMIZATIONS:
6319 case SQLITE_TESTCTRL_RESERVE:
6321 int opt = (int)strtol(azArg[2], 0, 0);
6322 rc2 = sqlite3_test_control(testctrl, p->db, opt);
6323 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6325 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
6330 /* sqlite3_test_control(int) */
6331 case SQLITE_TESTCTRL_PRNG_SAVE:
6332 case SQLITE_TESTCTRL_PRNG_RESTORE:
6333 case SQLITE_TESTCTRL_PRNG_RESET:
6334 case SQLITE_TESTCTRL_BYTEORDER:
6336 rc2 = sqlite3_test_control(testctrl);
6337 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6339 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6344 /* sqlite3_test_control(int, uint) */
6345 case SQLITE_TESTCTRL_PENDING_BYTE:
6347 unsigned int opt = (unsigned int)integerValue(azArg[2]);
6348 rc2 = sqlite3_test_control(testctrl, opt);
6349 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6351 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
6352 " int option\n", azArg[1]);
6356 /* sqlite3_test_control(int, int) */
6357 case SQLITE_TESTCTRL_ASSERT:
6358 case SQLITE_TESTCTRL_ALWAYS:
6359 case SQLITE_TESTCTRL_NEVER_CORRUPT:
6361 int opt = booleanValue(azArg[2]);
6362 rc2 = sqlite3_test_control(testctrl, opt);
6363 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6365 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
6370 /* sqlite3_test_control(int, char *) */
6371 #ifdef SQLITE_N_KEYWORD
6372 case SQLITE_TESTCTRL_ISKEYWORD:
6374 const char *opt = azArg[2];
6375 rc2 = sqlite3_test_control(testctrl, opt);
6376 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6379 "Error: testctrl %s takes a single char * option\n",
6385 case SQLITE_TESTCTRL_IMPOSTER:
6387 rc2 = sqlite3_test_control(testctrl, p->db,
6389 integerValue(azArg[3]),
6390 integerValue(azArg[4]));
6391 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6393 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
6397 case SQLITE_TESTCTRL_BITVEC_TEST:
6398 case SQLITE_TESTCTRL_FAULT_INSTALL:
6399 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6400 case SQLITE_TESTCTRL_SCRATCHMALLOC:
6403 "Error: CLI support for testctrl %s not implemented\n",
6409 #endif /* !defined(SQLITE_UNTESTABLE) */
6411 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
6413 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
6416 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6418 enableTimer = booleanValue(azArg[1]);
6419 if( enableTimer && !HAS_TIMER ){
6420 raw_printf(stderr, "Error: timer not available on this system.\n");
6424 raw_printf(stderr, "Usage: .timer on|off\n");
6429 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
6432 raw_printf(stderr, "Usage: .trace FILE|off\n");
6434 goto meta_command_exit;
6436 output_file_close(p->traceOut);
6437 p->traceOut = output_file_open(azArg[1]);
6438 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6439 if( p->traceOut==0 ){
6440 sqlite3_trace_v2(p->db, 0, 0, 0);
6442 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
6447 #if SQLITE_USER_AUTHENTICATION
6448 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6450 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
6452 goto meta_command_exit;
6455 if( strcmp(azArg[1],"login")==0 ){
6457 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
6459 goto meta_command_exit;
6461 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6462 (int)strlen(azArg[3]));
6464 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
6467 }else if( strcmp(azArg[1],"add")==0 ){
6469 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
6471 goto meta_command_exit;
6473 rc = sqlite3_user_add(p->db, azArg[2],
6474 azArg[3], (int)strlen(azArg[3]),
6475 booleanValue(azArg[4]));
6477 raw_printf(stderr, "User-Add failed: %d\n", rc);
6480 }else if( strcmp(azArg[1],"edit")==0 ){
6482 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
6484 goto meta_command_exit;
6486 rc = sqlite3_user_change(p->db, azArg[2],
6487 azArg[3], (int)strlen(azArg[3]),
6488 booleanValue(azArg[4]));
6490 raw_printf(stderr, "User-Edit failed: %d\n", rc);
6493 }else if( strcmp(azArg[1],"delete")==0 ){
6495 raw_printf(stderr, "Usage: .user delete USER\n");
6497 goto meta_command_exit;
6499 rc = sqlite3_user_delete(p->db, azArg[2]);
6501 raw_printf(stderr, "User-Delete failed: %d\n", rc);
6505 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
6507 goto meta_command_exit;
6510 #endif /* SQLITE_USER_AUTHENTICATION */
6512 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
6513 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
6514 sqlite3_libversion(), sqlite3_sourceid());
6517 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6518 const char *zDbName = nArg==2 ? azArg[1] : "main";
6519 sqlite3_vfs *pVfs = 0;
6521 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6523 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6524 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6525 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6526 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6531 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6533 sqlite3_vfs *pCurrent = 0;
6535 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6537 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6538 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6539 pVfs==pCurrent ? " <--- CURRENT" : "");
6540 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6541 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6542 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6544 raw_printf(p->out, "-----------------------------------\n");
6549 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6550 const char *zDbName = nArg==2 ? azArg[1] : "main";
6553 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6555 utf8_printf(p->out, "%s\n", zVfsName);
6556 sqlite3_free(zVfsName);
6561 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6562 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
6563 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
6567 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
6569 assert( nArg<=ArraySize(azArg) );
6570 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
6571 p->colWidth[j-1] = (int)integerValue(azArg[j]);
6576 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
6577 " \"%s\". Enter \".help\" for help\n", azArg[0]);
6584 if( p->outCount==0 ) output_reset(p);
6590 ** Return TRUE if a semicolon occurs anywhere in the first N characters
6593 static int line_contains_semicolon(const char *z, int N){
6595 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6600 ** Test to see if a line consists entirely of whitespace.
6602 static int _all_whitespace(const char *z){
6604 if( IsSpace(z[0]) ) continue;
6605 if( *z=='/' && z[1]=='*' ){
6607 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6608 if( *z==0 ) return 0;
6612 if( *z=='-' && z[1]=='-' ){
6614 while( *z && *z!='\n' ){ z++; }
6615 if( *z==0 ) return 1;
6624 ** Return TRUE if the line typed in is an SQL command terminator other
6625 ** than a semi-colon. The SQL Server style "go" command is understood
6626 ** as is the Oracle "/".
6628 static int line_is_command_terminator(const char *zLine){
6629 while( IsSpace(zLine[0]) ){ zLine++; };
6630 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6631 return 1; /* Oracle */
6633 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
6634 && _all_whitespace(&zLine[2]) ){
6635 return 1; /* SQL Server */
6641 ** Return true if zSql is a complete SQL statement. Return false if it
6642 ** ends in the middle of a string literal or C-style comment.
6644 static int line_is_complete(char *zSql, int nSql){
6646 if( zSql==0 ) return 1;
6649 rc = sqlite3_complete(zSql);
6655 ** Run a single line of SQL
6657 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6662 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
6664 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6666 if( rc || zErrMsg ){
6668 if( in!=0 || !stdin_is_interactive ){
6669 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6670 "Error: near line %d:", startline);
6672 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6675 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6676 sqlite3_free(zErrMsg);
6679 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6682 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
6683 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6684 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6691 ** Read input from *in and process it. If *in==0 then input
6692 ** is interactive - the user is typing it it. Otherwise, input
6693 ** is coming from a file or device. A prompt is issued and history
6694 ** is saved only if input is interactive. An interrupt signal will
6695 ** cause this routine to exit immediately, unless input is interactive.
6697 ** Return the number of errors.
6699 static int process_input(ShellState *p, FILE *in){
6700 char *zLine = 0; /* A single input line */
6701 char *zSql = 0; /* Accumulated SQL text */
6702 int nLine; /* Length of current line */
6703 int nSql = 0; /* Bytes of zSql[] used */
6704 int nAlloc = 0; /* Allocated zSql[] space */
6705 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
6706 int rc; /* Error code */
6707 int errCnt = 0; /* Number of errors seen */
6708 int lineno = 0; /* Current line number */
6709 int startline = 0; /* Line number for start of current input */
6711 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6713 zLine = one_input_line(in, zLine, nSql>0);
6716 if( in==0 && stdin_is_interactive ) printf("\n");
6719 if( seenInterrupt ){
6724 if( nSql==0 && _all_whitespace(zLine) ){
6725 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6728 if( zLine && zLine[0]=='.' && nSql==0 ){
6729 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6730 rc = do_meta_command(zLine, p);
6731 if( rc==2 ){ /* exit requested */
6738 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
6739 memcpy(zLine,";",2);
6741 nLine = strlen30(zLine);
6742 if( nSql+nLine+2>=nAlloc ){
6743 nAlloc = nSql+nLine+100;
6744 zSql = realloc(zSql, nAlloc);
6746 raw_printf(stderr, "Error: out of memory\n");
6753 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
6754 assert( nAlloc>0 && zSql!=0 );
6755 memcpy(zSql, zLine+i, nLine+1-i);
6759 zSql[nSql++] = '\n';
6760 memcpy(zSql+nSql, zLine, nLine+1);
6763 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
6764 && sqlite3_complete(zSql) ){
6765 errCnt += runOneSqlLine(p, zSql, in, startline);
6771 }else if( nSql && _all_whitespace(zSql) ){
6772 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
6776 if( nSql && !_all_whitespace(zSql) ){
6777 runOneSqlLine(p, zSql, in, startline);
6785 ** Return a pathname which is the user's home directory. A
6786 ** 0 return indicates an error of some kind.
6788 static char *find_home_dir(int clearFlag){
6789 static char *home_dir = NULL;
6795 if( home_dir ) return home_dir;
6797 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6798 && !defined(__RTP__) && !defined(_WRS_KERNEL)
6800 struct passwd *pwent;
6801 uid_t uid = getuid();
6802 if( (pwent=getpwuid(uid)) != NULL) {
6803 home_dir = pwent->pw_dir;
6808 #if defined(_WIN32_WCE)
6809 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6814 #if defined(_WIN32) || defined(WIN32)
6816 home_dir = getenv("USERPROFILE");
6821 home_dir = getenv("HOME");
6824 #if defined(_WIN32) || defined(WIN32)
6826 char *zDrive, *zPath;
6828 zDrive = getenv("HOMEDRIVE");
6829 zPath = getenv("HOMEPATH");
6830 if( zDrive && zPath ){
6831 n = strlen30(zDrive) + strlen30(zPath) + 1;
6832 home_dir = malloc( n );
6833 if( home_dir==0 ) return 0;
6834 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6841 #endif /* !_WIN32_WCE */
6844 int n = strlen30(home_dir) + 1;
6845 char *z = malloc( n );
6846 if( z ) memcpy(z, home_dir, n);
6854 ** Read input from the file given by sqliterc_override. Or if that
6855 ** parameter is NULL, take input from ~/.sqliterc
6857 ** Returns the number of errors.
6859 static void process_sqliterc(
6860 ShellState *p, /* Configuration data */
6861 const char *sqliterc_override /* Name of config file. NULL to use default */
6863 char *home_dir = NULL;
6864 const char *sqliterc = sqliterc_override;
6868 if (sqliterc == NULL) {
6869 home_dir = find_home_dir(0);
6871 raw_printf(stderr, "-- warning: cannot find home directory;"
6872 " cannot read ~/.sqliterc\n");
6875 sqlite3_initialize();
6876 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6879 in = fopen(sqliterc,"rb");
6881 if( stdin_is_interactive ){
6882 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
6884 process_input(p,in);
6891 ** Show available command line options
6893 static const char zOptions[] =
6894 " -ascii set output mode to 'ascii'\n"
6895 " -bail stop after hitting an error\n"
6896 " -batch force batch I/O\n"
6897 " -column set output mode to 'column'\n"
6898 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
6899 " -csv set output mode to 'csv'\n"
6900 " -echo print commands before execution\n"
6901 " -init FILENAME read/process named file\n"
6902 " -[no]header turn headers on or off\n"
6903 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6904 " -heap SIZE Size of heap for memsys3 or memsys5\n"
6906 " -help show this message\n"
6907 " -html set output mode to HTML\n"
6908 " -interactive force interactive I/O\n"
6909 " -line set output mode to 'line'\n"
6910 " -list set output mode to 'list'\n"
6911 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
6912 " -mmap N default mmap size set to N\n"
6913 #ifdef SQLITE_ENABLE_MULTIPLEX
6914 " -multiplex enable the multiplexor VFS\n"
6916 " -newline SEP set output row separator. Default: '\\n'\n"
6917 " -nullvalue TEXT set text string for NULL values. Default ''\n"
6918 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
6919 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
6920 " -separator SEP set output column separator. Default: '|'\n"
6921 " -stats print memory stats before each finalize\n"
6922 " -version show SQLite version\n"
6923 " -vfs NAME use NAME as the default VFS\n"
6924 #ifdef SQLITE_ENABLE_VFSTRACE
6925 " -vfstrace enable tracing of all VFS calls\n"
6928 static void usage(int showDetail){
6930 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6931 "FILENAME is the name of an SQLite database. A new database is created\n"
6932 "if the file does not previously exist.\n", Argv0);
6934 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
6936 raw_printf(stderr, "Use the -help option for additional information\n");
6942 ** Initialize the state information in data
6944 static void main_init(ShellState *data) {
6945 memset(data, 0, sizeof(*data));
6946 data->normalMode = data->cMode = data->mode = MODE_List;
6947 data->autoExplain = 1;
6948 memcpy(data->colSeparator,SEP_Column, 2);
6949 memcpy(data->rowSeparator,SEP_Row, 2);
6950 data->showHeader = 0;
6951 data->shellFlgs = SHFLG_Lookaside;
6952 sqlite3_config(SQLITE_CONFIG_URI, 1);
6953 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
6954 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
6955 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6956 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
6960 ** Output text to the console in a font that attracts extra attention.
6963 static void printBold(const char *zText){
6964 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
6965 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
6966 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
6967 SetConsoleTextAttribute(out,
6968 FOREGROUND_RED|FOREGROUND_INTENSITY
6970 printf("%s", zText);
6971 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
6974 static void printBold(const char *zText){
6975 printf("\033[1m%s\033[0m", zText);
6980 ** Get the argument to an --option. Throw an error and die if no argument
6983 static char *cmdline_option_value(int argc, char **argv, int i){
6985 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
6986 argv[0], argv[argc-1]);
6992 #ifndef SQLITE_SHELL_IS_UTF8
6993 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6994 # define SQLITE_SHELL_IS_UTF8 (0)
6996 # define SQLITE_SHELL_IS_UTF8 (1)
7000 #if SQLITE_SHELL_IS_UTF8
7001 int SQLITE_CDECL main(int argc, char **argv){
7003 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7008 const char *zInitFile = 0;
7011 int warnInmemoryDb = 0;
7016 setBinaryMode(stdin, 0);
7017 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7018 stdin_is_interactive = isatty(0);
7019 stdout_is_console = isatty(1);
7021 #if USE_SYSTEM_SQLITE+0!=1
7022 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
7023 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7024 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7029 #if !SQLITE_SHELL_IS_UTF8
7030 sqlite3_initialize();
7031 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7033 raw_printf(stderr, "out of memory\n");
7036 for(i=0; i<argc; i++){
7037 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7039 raw_printf(stderr, "out of memory\n");
7044 assert( argc>=1 && argv && argv[0] );
7047 /* Make sure we have a valid signal handler early, before anything
7051 signal(SIGINT, interrupt_handler);
7054 #ifdef SQLITE_SHELL_DBNAME_PROC
7056 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7057 ** of a C-function that will provide the name of the database file. Use
7058 ** this compile-time option to embed this shell program in larger
7060 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7061 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7066 /* Do an initial pass through the command-line argument to locate
7067 ** the name of the database file, the name of the initialization file,
7068 ** the size of the alternative malloc heap,
7069 ** and the first command to execute.
7071 for(i=1; i<argc; i++){
7075 if( data.zDbFilename==0 ){
7076 data.zDbFilename = z;
7078 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7079 ** mean that nothing is read from stdin */
7082 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7084 raw_printf(stderr, "out of memory\n");
7090 if( z[1]=='-' ) z++;
7091 if( strcmp(z,"-separator")==0
7092 || strcmp(z,"-nullvalue")==0
7093 || strcmp(z,"-newline")==0
7094 || strcmp(z,"-cmd")==0
7096 (void)cmdline_option_value(argc, argv, ++i);
7097 }else if( strcmp(z,"-init")==0 ){
7098 zInitFile = cmdline_option_value(argc, argv, ++i);
7099 }else if( strcmp(z,"-batch")==0 ){
7100 /* Need to check for batch mode here to so we can avoid printing
7101 ** informational messages (like from process_sqliterc) before
7102 ** we do the actual processing of arguments later in a second pass.
7104 stdin_is_interactive = 0;
7105 }else if( strcmp(z,"-heap")==0 ){
7106 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7108 sqlite3_int64 szHeap;
7110 zSize = cmdline_option_value(argc, argv, ++i);
7111 szHeap = integerValue(zSize);
7112 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7113 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7115 (void)cmdline_option_value(argc, argv, ++i);
7117 }else if( strcmp(z,"-scratch")==0 ){
7119 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7120 if( sz>400000 ) sz = 400000;
7121 if( sz<2500 ) sz = 2500;
7122 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7125 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7126 data.shellFlgs |= SHFLG_Scratch;
7127 }else if( strcmp(z,"-pagecache")==0 ){
7129 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7130 if( sz>70000 ) sz = 70000;
7132 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7133 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7134 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7135 data.shellFlgs |= SHFLG_Pagecache;
7136 }else if( strcmp(z,"-lookaside")==0 ){
7138 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7140 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7142 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7143 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7144 #ifdef SQLITE_ENABLE_VFSTRACE
7145 }else if( strcmp(z,"-vfstrace")==0 ){
7146 extern int vfstrace_register(
7147 const char *zTraceName,
7148 const char *zOldVfsName,
7149 int (*xOut)(const char*,void*),
7153 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7155 #ifdef SQLITE_ENABLE_MULTIPLEX
7156 }else if( strcmp(z,"-multiplex")==0 ){
7157 extern int sqlite3_multiple_initialize(const char*,int);
7158 sqlite3_multiplex_initialize(0, 1);
7160 }else if( strcmp(z,"-mmap")==0 ){
7161 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7162 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7163 }else if( strcmp(z,"-vfs")==0 ){
7164 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7166 sqlite3_vfs_register(pVfs, 1);
7168 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7173 if( data.zDbFilename==0 ){
7174 #ifndef SQLITE_OMIT_MEMORYDB
7175 data.zDbFilename = ":memory:";
7176 warnInmemoryDb = argc==1;
7178 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7184 /* Go ahead and open the database file if it already exists. If the
7185 ** file does not exist, delay opening it. This prevents empty database
7186 ** files from being created if a user mistypes the database name argument
7187 ** to the sqlite command-line tool.
7189 if( access(data.zDbFilename, 0)==0 ){
7193 /* Process the initialization file if there is one. If no -init option
7194 ** is given on the command line, look for a file named ~/.sqliterc and
7195 ** try to process it.
7197 process_sqliterc(&data,zInitFile);
7199 /* Make a second pass through the command-line argument and set
7200 ** options. This second pass is delayed until after the initialization
7201 ** file is processed so that the command-line arguments will override
7202 ** settings in the initialization file.
7204 for(i=1; i<argc; i++){
7206 if( z[0]!='-' ) continue;
7207 if( z[1]=='-' ){ z++; }
7208 if( strcmp(z,"-init")==0 ){
7210 }else if( strcmp(z,"-html")==0 ){
7211 data.mode = MODE_Html;
7212 }else if( strcmp(z,"-list")==0 ){
7213 data.mode = MODE_List;
7214 }else if( strcmp(z,"-line")==0 ){
7215 data.mode = MODE_Line;
7216 }else if( strcmp(z,"-column")==0 ){
7217 data.mode = MODE_Column;
7218 }else if( strcmp(z,"-csv")==0 ){
7219 data.mode = MODE_Csv;
7220 memcpy(data.colSeparator,",",2);
7221 }else if( strcmp(z,"-ascii")==0 ){
7222 data.mode = MODE_Ascii;
7223 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7225 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7227 }else if( strcmp(z,"-separator")==0 ){
7228 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7229 "%s",cmdline_option_value(argc,argv,++i));
7230 }else if( strcmp(z,"-newline")==0 ){
7231 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7232 "%s",cmdline_option_value(argc,argv,++i));
7233 }else if( strcmp(z,"-nullvalue")==0 ){
7234 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
7235 "%s",cmdline_option_value(argc,argv,++i));
7236 }else if( strcmp(z,"-header")==0 ){
7237 data.showHeader = 1;
7238 }else if( strcmp(z,"-noheader")==0 ){
7239 data.showHeader = 0;
7240 }else if( strcmp(z,"-echo")==0 ){
7241 ShellSetFlag(&data, SHFLG_Echo);
7242 }else if( strcmp(z,"-eqp")==0 ){
7244 }else if( strcmp(z,"-eqpfull")==0 ){
7246 }else if( strcmp(z,"-stats")==0 ){
7248 }else if( strcmp(z,"-scanstats")==0 ){
7249 data.scanstatsOn = 1;
7250 }else if( strcmp(z,"-backslash")==0 ){
7251 /* Undocumented command-line option: -backslash
7252 ** Causes C-style backslash escapes to be evaluated in SQL statements
7253 ** prior to sending the SQL into SQLite. Useful for injecting
7254 ** crazy bytes in the middle of SQL statements for testing and debugging.
7256 ShellSetFlag(&data, SHFLG_Backslash);
7257 }else if( strcmp(z,"-bail")==0 ){
7259 }else if( strcmp(z,"-version")==0 ){
7260 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
7262 }else if( strcmp(z,"-interactive")==0 ){
7263 stdin_is_interactive = 1;
7264 }else if( strcmp(z,"-batch")==0 ){
7265 stdin_is_interactive = 0;
7266 }else if( strcmp(z,"-heap")==0 ){
7268 }else if( strcmp(z,"-scratch")==0 ){
7270 }else if( strcmp(z,"-pagecache")==0 ){
7272 }else if( strcmp(z,"-lookaside")==0 ){
7274 }else if( strcmp(z,"-mmap")==0 ){
7276 }else if( strcmp(z,"-vfs")==0 ){
7278 #ifdef SQLITE_ENABLE_VFSTRACE
7279 }else if( strcmp(z,"-vfstrace")==0 ){
7282 #ifdef SQLITE_ENABLE_MULTIPLEX
7283 }else if( strcmp(z,"-multiplex")==0 ){
7286 }else if( strcmp(z,"-help")==0 ){
7288 }else if( strcmp(z,"-cmd")==0 ){
7289 /* Run commands that follow -cmd first and separately from commands
7290 ** that simply appear on the command-line. This seems goofy. It would
7291 ** be better if all commands ran in the order that they appear. But
7292 ** we retain the goofy behavior for historical compatibility. */
7293 if( i==argc-1 ) break;
7294 z = cmdline_option_value(argc,argv,++i);
7296 rc = do_meta_command(z, &data);
7297 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
7300 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7302 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7303 if( bail_on_error ) return rc!=0 ? rc : 1;
7305 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
7306 if( bail_on_error ) return rc;
7310 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7311 raw_printf(stderr,"Use -help for a list of options.\n");
7314 data.cMode = data.mode;
7318 /* Run all arguments that do not begin with '-' as if they were separate
7319 ** command-line inputs, except for the argToSkip argument which contains
7320 ** the database filename.
7322 for(i=0; i<nCmd; i++){
7323 if( azCmd[i][0]=='.' ){
7324 rc = do_meta_command(azCmd[i], &data);
7325 if( rc ) return rc==2 ? 0 : rc;
7328 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7330 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7331 return rc!=0 ? rc : 1;
7333 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
7340 /* Run commands received from standard input
7342 if( stdin_is_interactive ){
7347 "SQLite version %s %.19s\n" /*extra-version-info*/
7348 "Enter \".help\" for usage hints.\n",
7349 sqlite3_libversion(), sqlite3_sourceid()
7351 if( warnInmemoryDb ){
7352 printf("Connected to a ");
7353 printBold("transient in-memory database");
7354 printf(".\nUse \".open FILENAME\" to reopen on a "
7355 "persistent database.\n");
7357 zHome = find_home_dir(0);
7359 nHistory = strlen30(zHome) + 20;
7360 if( (zHistory = malloc(nHistory))!=0 ){
7361 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7364 if( zHistory ){ shell_read_history(zHistory); }
7365 rc = process_input(&data, 0);
7367 shell_stifle_history(100);
7368 shell_write_history(zHistory);
7372 rc = process_input(&data, stdin);
7375 set_table_name(&data, 0);
7377 session_close_all(&data);
7378 sqlite3_close(data.db);
7380 sqlite3_free(data.zFreeOnClose);
7382 #if !SQLITE_SHELL_IS_UTF8
7383 for(i=0; i<argc; i++) sqlite3_free(argv[i]);