Skip running the 'zipfile' test if the necessary static package cannot be loaded.
[sqlite.git] / src / shell.c.in
blob691e7750ad2158cb3e7e0906d064f5c50827d8fa
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
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
18 #endif
21 ** Warning pragmas copied from msvc.h in the core.
23 #if defined(_MSC_VER)
24 #pragma warning(disable : 4054)
25 #pragma warning(disable : 4055)
26 #pragma warning(disable : 4100)
27 #pragma warning(disable : 4127)
28 #pragma warning(disable : 4130)
29 #pragma warning(disable : 4152)
30 #pragma warning(disable : 4189)
31 #pragma warning(disable : 4206)
32 #pragma warning(disable : 4210)
33 #pragma warning(disable : 4232)
34 #pragma warning(disable : 4244)
35 #pragma warning(disable : 4305)
36 #pragma warning(disable : 4306)
37 #pragma warning(disable : 4702)
38 #pragma warning(disable : 4706)
39 #endif /* defined(_MSC_VER) */
42 ** No support for loadable extensions in VxWorks.
44 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45 # define SQLITE_OMIT_LOAD_EXTENSION 1
46 #endif
49 ** Enable large-file support for fopen() and friends on unix.
51 #ifndef SQLITE_DISABLE_LFS
52 # define _LARGE_FILE 1
53 # ifndef _FILE_OFFSET_BITS
54 # define _FILE_OFFSET_BITS 64
55 # endif
56 # define _LARGEFILE_SOURCE 1
57 #endif
59 #include <stdlib.h>
60 #include <string.h>
61 #include <stdio.h>
62 #include <assert.h>
63 #include "sqlite3.h"
64 #if SQLITE_USER_AUTHENTICATION
65 # include "sqlite3userauth.h"
66 #endif
67 #include <ctype.h>
68 #include <stdarg.h>
70 #if !defined(_WIN32) && !defined(WIN32)
71 # include <signal.h>
72 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
73 # include <pwd.h>
74 # endif
75 #endif
76 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW_H)
77 # include <unistd.h>
78 # include <dirent.h>
79 # if defined(__MINGW_H)
80 # define DIRENT dirent
81 # endif
82 #endif
83 #include <sys/types.h>
84 #include <sys/stat.h>
86 #if HAVE_READLINE
87 # include <readline/readline.h>
88 # include <readline/history.h>
89 #endif
91 #if HAVE_EDITLINE
92 # include <editline/readline.h>
93 #endif
95 #if HAVE_EDITLINE || HAVE_READLINE
97 # define shell_add_history(X) add_history(X)
98 # define shell_read_history(X) read_history(X)
99 # define shell_write_history(X) write_history(X)
100 # define shell_stifle_history(X) stifle_history(X)
101 # define shell_readline(X) readline(X)
103 #elif HAVE_LINENOISE
105 # include "linenoise.h"
106 # define shell_add_history(X) linenoiseHistoryAdd(X)
107 # define shell_read_history(X) linenoiseHistoryLoad(X)
108 # define shell_write_history(X) linenoiseHistorySave(X)
109 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
110 # define shell_readline(X) linenoise(X)
112 #else
114 # define shell_read_history(X)
115 # define shell_write_history(X)
116 # define shell_stifle_history(X)
118 # define SHELL_USE_LOCAL_GETLINE 1
119 #endif
122 #if defined(_WIN32) || defined(WIN32)
123 # include <io.h>
124 # include <fcntl.h>
125 # define isatty(h) _isatty(h)
126 # ifndef access
127 # define access(f,m) _access((f),(m))
128 # endif
129 # undef popen
130 # define popen _popen
131 # undef pclose
132 # define pclose _pclose
133 #else
134 /* Make sure isatty() has a prototype. */
135 extern int isatty(int);
137 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
138 /* popen and pclose are not C89 functions and so are
139 ** sometimes omitted from the <stdio.h> header */
140 extern FILE *popen(const char*,const char*);
141 extern int pclose(FILE*);
142 # else
143 # define SQLITE_OMIT_POPEN 1
144 # endif
145 #endif
147 #if defined(_WIN32_WCE)
148 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
149 * thus we always assume that we have a console. That can be
150 * overridden with the -batch command line option.
152 #define isatty(x) 1
153 #endif
155 /* ctype macros that work with signed characters */
156 #define IsSpace(X) isspace((unsigned char)X)
157 #define IsDigit(X) isdigit((unsigned char)X)
158 #define ToLower(X) (char)tolower((unsigned char)X)
160 #if defined(_WIN32) || defined(WIN32)
161 #include <windows.h>
163 /* string conversion routines only needed on Win32 */
164 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
165 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
166 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
167 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
168 #endif
170 /* On Windows, we normally run with output mode of TEXT so that \n characters
171 ** are automatically translated into \r\n. However, this behavior needs
172 ** to be disabled in some cases (ex: when generating CSV output and when
173 ** rendering quoted strings that contain \n characters). The following
174 ** routines take care of that.
176 #if defined(_WIN32) || defined(WIN32)
177 static void setBinaryMode(FILE *file, int isOutput){
178 if( isOutput ) fflush(file);
179 _setmode(_fileno(file), _O_BINARY);
181 static void setTextMode(FILE *file, int isOutput){
182 if( isOutput ) fflush(file);
183 _setmode(_fileno(file), _O_TEXT);
185 #else
186 # define setBinaryMode(X,Y)
187 # define setTextMode(X,Y)
188 #endif
191 /* True if the timer is enabled */
192 static int enableTimer = 0;
194 /* Return the current wall-clock time */
195 static sqlite3_int64 timeOfDay(void){
196 static sqlite3_vfs *clockVfs = 0;
197 sqlite3_int64 t;
198 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
199 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
200 clockVfs->xCurrentTimeInt64(clockVfs, &t);
201 }else{
202 double r;
203 clockVfs->xCurrentTime(clockVfs, &r);
204 t = (sqlite3_int64)(r*86400000.0);
206 return t;
209 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
210 #include <sys/time.h>
211 #include <sys/resource.h>
213 /* VxWorks does not support getrusage() as far as we can determine */
214 #if defined(_WRS_KERNEL) || defined(__RTP__)
215 struct rusage {
216 struct timeval ru_utime; /* user CPU time used */
217 struct timeval ru_stime; /* system CPU time used */
219 #define getrusage(A,B) memset(B,0,sizeof(*B))
220 #endif
222 /* Saved resource information for the beginning of an operation */
223 static struct rusage sBegin; /* CPU time at start */
224 static sqlite3_int64 iBegin; /* Wall-clock time at start */
227 ** Begin timing an operation
229 static void beginTimer(void){
230 if( enableTimer ){
231 getrusage(RUSAGE_SELF, &sBegin);
232 iBegin = timeOfDay();
236 /* Return the difference of two time_structs in seconds */
237 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
238 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
239 (double)(pEnd->tv_sec - pStart->tv_sec);
243 ** Print the timing results.
245 static void endTimer(void){
246 if( enableTimer ){
247 sqlite3_int64 iEnd = timeOfDay();
248 struct rusage sEnd;
249 getrusage(RUSAGE_SELF, &sEnd);
250 printf("Run Time: real %.3f user %f sys %f\n",
251 (iEnd - iBegin)*0.001,
252 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
253 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
257 #define BEGIN_TIMER beginTimer()
258 #define END_TIMER endTimer()
259 #define HAS_TIMER 1
261 #elif (defined(_WIN32) || defined(WIN32))
263 /* Saved resource information for the beginning of an operation */
264 static HANDLE hProcess;
265 static FILETIME ftKernelBegin;
266 static FILETIME ftUserBegin;
267 static sqlite3_int64 ftWallBegin;
268 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
269 LPFILETIME, LPFILETIME);
270 static GETPROCTIMES getProcessTimesAddr = NULL;
273 ** Check to see if we have timer support. Return 1 if necessary
274 ** support found (or found previously).
276 static int hasTimer(void){
277 if( getProcessTimesAddr ){
278 return 1;
279 } else {
280 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
281 ** versions. See if the version we are running on has it, and if it
282 ** does, save off a pointer to it and the current process handle.
284 hProcess = GetCurrentProcess();
285 if( hProcess ){
286 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
287 if( NULL != hinstLib ){
288 getProcessTimesAddr =
289 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
290 if( NULL != getProcessTimesAddr ){
291 return 1;
293 FreeLibrary(hinstLib);
297 return 0;
301 ** Begin timing an operation
303 static void beginTimer(void){
304 if( enableTimer && getProcessTimesAddr ){
305 FILETIME ftCreation, ftExit;
306 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
307 &ftKernelBegin,&ftUserBegin);
308 ftWallBegin = timeOfDay();
312 /* Return the difference of two FILETIME structs in seconds */
313 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
314 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
315 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
316 return (double) ((i64End - i64Start) / 10000000.0);
320 ** Print the timing results.
322 static void endTimer(void){
323 if( enableTimer && getProcessTimesAddr){
324 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
325 sqlite3_int64 ftWallEnd = timeOfDay();
326 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
327 printf("Run Time: real %.3f user %f sys %f\n",
328 (ftWallEnd - ftWallBegin)*0.001,
329 timeDiff(&ftUserBegin, &ftUserEnd),
330 timeDiff(&ftKernelBegin, &ftKernelEnd));
334 #define BEGIN_TIMER beginTimer()
335 #define END_TIMER endTimer()
336 #define HAS_TIMER hasTimer()
338 #else
339 #define BEGIN_TIMER
340 #define END_TIMER
341 #define HAS_TIMER 0
342 #endif
345 ** Used to prevent warnings about unused parameters
347 #define UNUSED_PARAMETER(x) (void)(x)
350 ** If the following flag is set, then command execution stops
351 ** at an error if we are not interactive.
353 static int bail_on_error = 0;
356 ** Threat stdin as an interactive input if the following variable
357 ** is true. Otherwise, assume stdin is connected to a file or pipe.
359 static int stdin_is_interactive = 1;
362 ** On Windows systems we have to know if standard output is a console
363 ** in order to translate UTF-8 into MBCS. The following variable is
364 ** true if translation is required.
366 static int stdout_is_console = 1;
369 ** The following is the open SQLite database. We make a pointer
370 ** to this database a static variable so that it can be accessed
371 ** by the SIGINT handler to interrupt database processing.
373 static sqlite3 *globalDb = 0;
376 ** True if an interrupt (Control-C) has been received.
378 static volatile int seenInterrupt = 0;
381 ** This is the name of our program. It is set in main(), used
382 ** in a number of other places, mostly for error messages.
384 static char *Argv0;
387 ** Prompt strings. Initialized in main. Settable with
388 ** .prompt main continue
390 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
391 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
394 ** Render output like fprintf(). Except, if the output is going to the
395 ** console and if this is running on a Windows machine, translate the
396 ** output from UTF-8 into MBCS.
398 #if defined(_WIN32) || defined(WIN32)
399 void utf8_printf(FILE *out, const char *zFormat, ...){
400 va_list ap;
401 va_start(ap, zFormat);
402 if( stdout_is_console && (out==stdout || out==stderr) ){
403 char *z1 = sqlite3_vmprintf(zFormat, ap);
404 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
405 sqlite3_free(z1);
406 fputs(z2, out);
407 sqlite3_free(z2);
408 }else{
409 vfprintf(out, zFormat, ap);
411 va_end(ap);
413 #elif !defined(utf8_printf)
414 # define utf8_printf fprintf
415 #endif
418 ** Render output like fprintf(). This should not be used on anything that
419 ** includes string formatting (e.g. "%s").
421 #if !defined(raw_printf)
422 # define raw_printf fprintf
423 #endif
426 ** Write I/O traces to the following stream.
428 #ifdef SQLITE_ENABLE_IOTRACE
429 static FILE *iotrace = 0;
430 #endif
433 ** This routine works like printf in that its first argument is a
434 ** format string and subsequent arguments are values to be substituted
435 ** in place of % fields. The result of formatting this string
436 ** is written to iotrace.
438 #ifdef SQLITE_ENABLE_IOTRACE
439 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
440 va_list ap;
441 char *z;
442 if( iotrace==0 ) return;
443 va_start(ap, zFormat);
444 z = sqlite3_vmprintf(zFormat, ap);
445 va_end(ap);
446 utf8_printf(iotrace, "%s", z);
447 sqlite3_free(z);
449 #endif
452 ** Output string zUtf to stream pOut as w characters. If w is negative,
453 ** then right-justify the text. W is the width in UTF-8 characters, not
454 ** in bytes. This is different from the %*.*s specification in printf
455 ** since with %*.*s the width is measured in bytes, not characters.
457 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
458 int i;
459 int n;
460 int aw = w<0 ? -w : w;
461 char zBuf[1000];
462 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
463 for(i=n=0; zUtf[i]; i++){
464 if( (zUtf[i]&0xc0)!=0x80 ){
465 n++;
466 if( n==aw ){
467 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
468 break;
472 if( n>=aw ){
473 utf8_printf(pOut, "%.*s", i, zUtf);
474 }else if( w<0 ){
475 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
476 }else{
477 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
483 ** Determines if a string is a number of not.
485 static int isNumber(const char *z, int *realnum){
486 if( *z=='-' || *z=='+' ) z++;
487 if( !IsDigit(*z) ){
488 return 0;
490 z++;
491 if( realnum ) *realnum = 0;
492 while( IsDigit(*z) ){ z++; }
493 if( *z=='.' ){
494 z++;
495 if( !IsDigit(*z) ) return 0;
496 while( IsDigit(*z) ){ z++; }
497 if( realnum ) *realnum = 1;
499 if( *z=='e' || *z=='E' ){
500 z++;
501 if( *z=='+' || *z=='-' ) z++;
502 if( !IsDigit(*z) ) return 0;
503 while( IsDigit(*z) ){ z++; }
504 if( realnum ) *realnum = 1;
506 return *z==0;
510 ** Compute a string length that is limited to what can be stored in
511 ** lower 30 bits of a 32-bit signed integer.
513 static int strlen30(const char *z){
514 const char *z2 = z;
515 while( *z2 ){ z2++; }
516 return 0x3fffffff & (int)(z2 - z);
520 ** Return the length of a string in characters. Multibyte UTF8 characters
521 ** count as a single character.
523 static int strlenChar(const char *z){
524 int n = 0;
525 while( *z ){
526 if( (0xc0&*(z++))!=0x80 ) n++;
528 return n;
532 ** This routine reads a line of text from FILE in, stores
533 ** the text in memory obtained from malloc() and returns a pointer
534 ** to the text. NULL is returned at end of file, or if malloc()
535 ** fails.
537 ** If zLine is not NULL then it is a malloced buffer returned from
538 ** a previous call to this routine that may be reused.
540 static char *local_getline(char *zLine, FILE *in){
541 int nLine = zLine==0 ? 0 : 100;
542 int n = 0;
544 while( 1 ){
545 if( n+100>nLine ){
546 nLine = nLine*2 + 100;
547 zLine = realloc(zLine, nLine);
548 if( zLine==0 ) return 0;
550 if( fgets(&zLine[n], nLine - n, in)==0 ){
551 if( n==0 ){
552 free(zLine);
553 return 0;
555 zLine[n] = 0;
556 break;
558 while( zLine[n] ) n++;
559 if( n>0 && zLine[n-1]=='\n' ){
560 n--;
561 if( n>0 && zLine[n-1]=='\r' ) n--;
562 zLine[n] = 0;
563 break;
566 #if defined(_WIN32) || defined(WIN32)
567 /* For interactive input on Windows systems, translate the
568 ** multi-byte characterset characters into UTF-8. */
569 if( stdin_is_interactive && in==stdin ){
570 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
571 if( zTrans ){
572 int nTrans = strlen30(zTrans)+1;
573 if( nTrans>nLine ){
574 zLine = realloc(zLine, nTrans);
575 if( zLine==0 ){
576 sqlite3_free(zTrans);
577 return 0;
580 memcpy(zLine, zTrans, nTrans);
581 sqlite3_free(zTrans);
584 #endif /* defined(_WIN32) || defined(WIN32) */
585 return zLine;
589 ** Retrieve a single line of input text.
591 ** If in==0 then read from standard input and prompt before each line.
592 ** If isContinuation is true, then a continuation prompt is appropriate.
593 ** If isContinuation is zero, then the main prompt should be used.
595 ** If zPrior is not NULL then it is a buffer from a prior call to this
596 ** routine that can be reused.
598 ** The result is stored in space obtained from malloc() and must either
599 ** be freed by the caller or else passed back into this routine via the
600 ** zPrior argument for reuse.
602 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
603 char *zPrompt;
604 char *zResult;
605 if( in!=0 ){
606 zResult = local_getline(zPrior, in);
607 }else{
608 zPrompt = isContinuation ? continuePrompt : mainPrompt;
609 #if SHELL_USE_LOCAL_GETLINE
610 printf("%s", zPrompt);
611 fflush(stdout);
612 zResult = local_getline(zPrior, stdin);
613 #else
614 free(zPrior);
615 zResult = shell_readline(zPrompt);
616 if( zResult && *zResult ) shell_add_history(zResult);
617 #endif
619 return zResult;
622 ** A variable length string to which one can append text.
624 typedef struct ShellText ShellText;
625 struct ShellText {
626 char *z;
627 int n;
628 int nAlloc;
632 ** Initialize and destroy a ShellText object
634 static void initText(ShellText *p){
635 memset(p, 0, sizeof(*p));
637 static void freeText(ShellText *p){
638 free(p->z);
639 initText(p);
642 /* zIn is either a pointer to a NULL-terminated string in memory obtained
643 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
644 ** added to zIn, and the result returned in memory obtained from malloc().
645 ** zIn, if it was not NULL, is freed.
647 ** If the third argument, quote, is not '\0', then it is used as a
648 ** quote character for zAppend.
650 static void appendText(ShellText *p, char const *zAppend, char quote){
651 int len;
652 int i;
653 int nAppend = strlen30(zAppend);
655 len = nAppend+p->n+1;
656 if( quote ){
657 len += 2;
658 for(i=0; i<nAppend; i++){
659 if( zAppend[i]==quote ) len++;
663 if( p->n+len>=p->nAlloc ){
664 p->nAlloc = p->nAlloc*2 + len + 20;
665 p->z = realloc(p->z, p->nAlloc);
666 if( p->z==0 ){
667 memset(p, 0, sizeof(*p));
668 return;
672 if( quote ){
673 char *zCsr = p->z+p->n;
674 *zCsr++ = quote;
675 for(i=0; i<nAppend; i++){
676 *zCsr++ = zAppend[i];
677 if( zAppend[i]==quote ) *zCsr++ = quote;
679 *zCsr++ = quote;
680 p->n = (int)(zCsr - p->z);
681 *zCsr = '\0';
682 }else{
683 memcpy(p->z+p->n, zAppend, nAppend);
684 p->n += nAppend;
685 p->z[p->n] = '\0';
690 ** Attempt to determine if identifier zName needs to be quoted, either
691 ** because it contains non-alphanumeric characters, or because it is an
692 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
693 ** that quoting is required.
695 ** Return '"' if quoting is required. Return 0 if no quoting is required.
697 static char quoteChar(const char *zName){
698 /* All SQLite keywords, in alphabetical order */
699 static const char *azKeywords[] = {
700 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
701 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
702 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
703 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
704 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
705 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
706 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
707 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
708 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
709 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
710 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
711 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
712 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
713 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
714 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
715 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
716 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
717 "WITH", "WITHOUT",
719 int i, lwr, upr, mid, c;
720 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
721 for(i=0; zName[i]; i++){
722 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
724 lwr = 0;
725 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
726 while( lwr<=upr ){
727 mid = (lwr+upr)/2;
728 c = sqlite3_stricmp(azKeywords[mid], zName);
729 if( c==0 ) return '"';
730 if( c<0 ){
731 lwr = mid+1;
732 }else{
733 upr = mid-1;
736 return 0;
740 ** Construct a fake object name and column list to describe the structure
741 ** of the view, virtual table, or table valued function zSchema.zName.
743 static char *shellFakeSchema(
744 sqlite3 *db, /* The database connection containing the vtab */
745 const char *zSchema, /* Schema of the database holding the vtab */
746 const char *zName /* The name of the virtual table */
748 sqlite3_stmt *pStmt = 0;
749 char *zSql;
750 ShellText s;
751 char cQuote;
752 char *zDiv = "(";
753 int nRow = 0;
755 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
756 zSchema ? zSchema : "main", zName);
757 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
758 sqlite3_free(zSql);
759 initText(&s);
760 if( zSchema ){
761 cQuote = quoteChar(zSchema);
762 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
763 appendText(&s, zSchema, cQuote);
764 appendText(&s, ".", 0);
766 cQuote = quoteChar(zName);
767 appendText(&s, zName, cQuote);
768 while( sqlite3_step(pStmt)==SQLITE_ROW ){
769 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
770 nRow++;
771 appendText(&s, zDiv, 0);
772 zDiv = ",";
773 cQuote = quoteChar(zCol);
774 appendText(&s, zCol, cQuote);
776 appendText(&s, ")", 0);
777 sqlite3_finalize(pStmt);
778 if( nRow==0 ){
779 freeText(&s);
780 s.z = 0;
782 return s.z;
786 ** SQL function: shell_module_schema(X)
788 ** Return a fake schema for the table-valued function or eponymous virtual
789 ** table X.
791 static void shellModuleSchema(
792 sqlite3_context *pCtx,
793 int nVal,
794 sqlite3_value **apVal
796 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
797 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
798 if( zFake ){
799 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %z */", zFake),
800 -1, sqlite3_free);
805 ** SQL function: shell_add_schema(S,X)
807 ** Add the schema name X to the CREATE statement in S and return the result.
808 ** Examples:
810 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
812 ** Also works on
814 ** CREATE INDEX
815 ** CREATE UNIQUE INDEX
816 ** CREATE VIEW
817 ** CREATE TRIGGER
818 ** CREATE VIRTUAL TABLE
820 ** This UDF is used by the .schema command to insert the schema name of
821 ** attached databases into the middle of the sqlite_master.sql field.
823 static void shellAddSchemaName(
824 sqlite3_context *pCtx,
825 int nVal,
826 sqlite3_value **apVal
828 static const char *aPrefix[] = {
829 "TABLE",
830 "INDEX",
831 "UNIQUE INDEX",
832 "VIEW",
833 "TRIGGER",
834 "VIRTUAL TABLE"
836 int i = 0;
837 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
838 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
839 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
840 sqlite3 *db = sqlite3_context_db_handle(pCtx);
841 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
842 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
843 int n = strlen30(aPrefix[i]);
844 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
845 char *z = 0;
846 char *zFake = 0;
847 if( zSchema ){
848 char cQuote = quoteChar(zSchema);
849 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
850 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
851 }else{
852 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
855 if( zName
856 && aPrefix[i][0]=='V'
857 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
859 if( z==0 ){
860 z = sqlite3_mprintf("%s\n/* %z */", zIn, zFake);
861 }else{
862 z = sqlite3_mprintf("%z\n/* %z */", z, zFake);
865 if( z ){
866 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
867 return;
872 sqlite3_result_value(pCtx, apVal[0]);
876 ** The source code for several run-time loadable extensions is inserted
877 ** below by the ../tool/mkshellc.tcl script. Before processing that included
878 ** code, we need to override some macros to make the included program code
879 ** work here in the middle of this regular program.
881 #define SQLITE_EXTENSION_INIT1
882 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
884 #if defined(_WIN32) && defined(_MSC_VER)
885 INCLUDE test_windirent.c
886 #define dirent DIRENT
887 #endif
888 INCLUDE ../ext/misc/shathree.c
889 INCLUDE ../ext/misc/fileio.c
890 INCLUDE ../ext/misc/completion.c
891 #ifdef SQLITE_HAVE_ZLIB
892 INCLUDE ../ext/misc/zipfile.c
893 INCLUDE ../ext/misc/sqlar.c
894 #endif
895 INCLUDE ../ext/expert/sqlite3expert.h
896 INCLUDE ../ext/expert/sqlite3expert.c
898 #if defined(SQLITE_ENABLE_SESSION)
900 ** State information for a single open session
902 typedef struct OpenSession OpenSession;
903 struct OpenSession {
904 char *zName; /* Symbolic name for this session */
905 int nFilter; /* Number of xFilter rejection GLOB patterns */
906 char **azFilter; /* Array of xFilter rejection GLOB patterns */
907 sqlite3_session *p; /* The open session */
909 #endif
912 ** Shell output mode information from before ".explain on",
913 ** saved so that it can be restored by ".explain off"
915 typedef struct SavedModeInfo SavedModeInfo;
916 struct SavedModeInfo {
917 int valid; /* Is there legit data in here? */
918 int mode; /* Mode prior to ".explain on" */
919 int showHeader; /* The ".header" setting prior to ".explain on" */
920 int colWidth[100]; /* Column widths prior to ".explain on" */
923 typedef struct ExpertInfo ExpertInfo;
924 struct ExpertInfo {
925 sqlite3expert *pExpert;
926 int bVerbose;
930 ** State information about the database connection is contained in an
931 ** instance of the following structure.
933 typedef struct ShellState ShellState;
934 struct ShellState {
935 sqlite3 *db; /* The database */
936 int autoExplain; /* Automatically turn on .explain mode */
937 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
938 int statsOn; /* True to display memory stats before each finalize */
939 int scanstatsOn; /* True to display scan stats before each finalize */
940 int outCount; /* Revert to stdout when reaching zero */
941 int cnt; /* Number of records displayed so far */
942 FILE *out; /* Write results here */
943 FILE *traceOut; /* Output for sqlite3_trace() */
944 int nErr; /* Number of errors seen */
945 int mode; /* An output mode setting */
946 int cMode; /* temporary output mode for the current query */
947 int normalMode; /* Output mode before ".explain on" */
948 int writableSchema; /* True if PRAGMA writable_schema=ON */
949 int showHeader; /* True to show column names in List or Column mode */
950 int nCheck; /* Number of ".check" commands run */
951 unsigned shellFlgs; /* Various flags */
952 char *zDestTable; /* Name of destination table when MODE_Insert */
953 char zTestcase[30]; /* Name of current test case */
954 char colSeparator[20]; /* Column separator character for several modes */
955 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
956 int colWidth[100]; /* Requested width of each column when in column mode*/
957 int actualWidth[100]; /* Actual width of each column */
958 char nullValue[20]; /* The text to print when a NULL comes back from
959 ** the database */
960 char outfile[FILENAME_MAX]; /* Filename for *out */
961 const char *zDbFilename; /* name of the database file */
962 char *zFreeOnClose; /* Filename to free when closing */
963 const char *zVfs; /* Name of VFS to use */
964 sqlite3_stmt *pStmt; /* Current statement if any. */
965 FILE *pLog; /* Write log output here */
966 int *aiIndent; /* Array of indents used in MODE_Explain */
967 int nIndent; /* Size of array aiIndent[] */
968 int iIndent; /* Index of current op in aiIndent[] */
969 #if defined(SQLITE_ENABLE_SESSION)
970 int nSession; /* Number of active sessions */
971 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
972 #endif
973 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
976 /* Allowed values for ShellState.autoEQP
978 #define AUTOEQP_off 0
979 #define AUTOEQP_on 1
980 #define AUTOEQP_trigger 2
981 #define AUTOEQP_full 3
984 ** These are the allowed shellFlgs values
986 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
987 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
988 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
989 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
990 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
991 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
992 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
995 ** Macros for testing and setting shellFlgs
997 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
998 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
999 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1002 ** These are the allowed modes.
1004 #define MODE_Line 0 /* One column per line. Blank line between records */
1005 #define MODE_Column 1 /* One record per line in neat columns */
1006 #define MODE_List 2 /* One record per line with a separator */
1007 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1008 #define MODE_Html 4 /* Generate an XHTML table */
1009 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1010 #define MODE_Quote 6 /* Quote values as for SQL */
1011 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1012 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1013 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1014 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1015 #define MODE_Pretty 11 /* Pretty-print schemas */
1017 static const char *modeDescr[] = {
1018 "line",
1019 "column",
1020 "list",
1021 "semi",
1022 "html",
1023 "insert",
1024 "quote",
1025 "tcl",
1026 "csv",
1027 "explain",
1028 "ascii",
1029 "prettyprint",
1033 ** These are the column/row/line separators used by the various
1034 ** import/export modes.
1036 #define SEP_Column "|"
1037 #define SEP_Row "\n"
1038 #define SEP_Tab "\t"
1039 #define SEP_Space " "
1040 #define SEP_Comma ","
1041 #define SEP_CrLf "\r\n"
1042 #define SEP_Unit "\x1F"
1043 #define SEP_Record "\x1E"
1046 ** Number of elements in an array
1048 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
1051 ** A callback for the sqlite3_log() interface.
1053 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1054 ShellState *p = (ShellState*)pArg;
1055 if( p->pLog==0 ) return;
1056 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1057 fflush(p->pLog);
1061 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1063 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1064 int i;
1065 char *zBlob = (char *)pBlob;
1066 raw_printf(out,"X'");
1067 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1068 raw_printf(out,"'");
1072 ** Find a string that is not found anywhere in z[]. Return a pointer
1073 ** to that string.
1075 ** Try to use zA and zB first. If both of those are already found in z[]
1076 ** then make up some string and store it in the buffer zBuf.
1078 static const char *unused_string(
1079 const char *z, /* Result must not appear anywhere in z */
1080 const char *zA, const char *zB, /* Try these first */
1081 char *zBuf /* Space to store a generated string */
1083 unsigned i = 0;
1084 if( strstr(z, zA)==0 ) return zA;
1085 if( strstr(z, zB)==0 ) return zB;
1087 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1088 }while( strstr(z,zBuf)!=0 );
1089 return zBuf;
1093 ** Output the given string as a quoted string using SQL quoting conventions.
1095 ** See also: output_quoted_escaped_string()
1097 static void output_quoted_string(FILE *out, const char *z){
1098 int i;
1099 char c;
1100 setBinaryMode(out, 1);
1101 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1102 if( c==0 ){
1103 utf8_printf(out,"'%s'",z);
1104 }else{
1105 raw_printf(out, "'");
1106 while( *z ){
1107 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1108 if( c=='\'' ) i++;
1109 if( i ){
1110 utf8_printf(out, "%.*s", i, z);
1111 z += i;
1113 if( c=='\'' ){
1114 raw_printf(out, "'");
1115 continue;
1117 if( c==0 ){
1118 break;
1120 z++;
1122 raw_printf(out, "'");
1124 setTextMode(out, 1);
1128 ** Output the given string as a quoted string using SQL quoting conventions.
1129 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1130 ** get corrupted by end-of-line translation facilities in some operating
1131 ** systems.
1133 ** This is like output_quoted_string() but with the addition of the \r\n
1134 ** escape mechanism.
1136 static void output_quoted_escaped_string(FILE *out, const char *z){
1137 int i;
1138 char c;
1139 setBinaryMode(out, 1);
1140 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1141 if( c==0 ){
1142 utf8_printf(out,"'%s'",z);
1143 }else{
1144 const char *zNL = 0;
1145 const char *zCR = 0;
1146 int nNL = 0;
1147 int nCR = 0;
1148 char zBuf1[20], zBuf2[20];
1149 for(i=0; z[i]; i++){
1150 if( z[i]=='\n' ) nNL++;
1151 if( z[i]=='\r' ) nCR++;
1153 if( nNL ){
1154 raw_printf(out, "replace(");
1155 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1157 if( nCR ){
1158 raw_printf(out, "replace(");
1159 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1161 raw_printf(out, "'");
1162 while( *z ){
1163 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1164 if( c=='\'' ) i++;
1165 if( i ){
1166 utf8_printf(out, "%.*s", i, z);
1167 z += i;
1169 if( c=='\'' ){
1170 raw_printf(out, "'");
1171 continue;
1173 if( c==0 ){
1174 break;
1176 z++;
1177 if( c=='\n' ){
1178 raw_printf(out, "%s", zNL);
1179 continue;
1181 raw_printf(out, "%s", zCR);
1183 raw_printf(out, "'");
1184 if( nCR ){
1185 raw_printf(out, ",'%s',char(13))", zCR);
1187 if( nNL ){
1188 raw_printf(out, ",'%s',char(10))", zNL);
1191 setTextMode(out, 1);
1195 ** Output the given string as a quoted according to C or TCL quoting rules.
1197 static void output_c_string(FILE *out, const char *z){
1198 unsigned int c;
1199 fputc('"', out);
1200 while( (c = *(z++))!=0 ){
1201 if( c=='\\' ){
1202 fputc(c, out);
1203 fputc(c, out);
1204 }else if( c=='"' ){
1205 fputc('\\', out);
1206 fputc('"', out);
1207 }else if( c=='\t' ){
1208 fputc('\\', out);
1209 fputc('t', out);
1210 }else if( c=='\n' ){
1211 fputc('\\', out);
1212 fputc('n', out);
1213 }else if( c=='\r' ){
1214 fputc('\\', out);
1215 fputc('r', out);
1216 }else if( !isprint(c&0xff) ){
1217 raw_printf(out, "\\%03o", c&0xff);
1218 }else{
1219 fputc(c, out);
1222 fputc('"', out);
1226 ** Output the given string with characters that are special to
1227 ** HTML escaped.
1229 static void output_html_string(FILE *out, const char *z){
1230 int i;
1231 if( z==0 ) z = "";
1232 while( *z ){
1233 for(i=0; z[i]
1234 && z[i]!='<'
1235 && z[i]!='&'
1236 && z[i]!='>'
1237 && z[i]!='\"'
1238 && z[i]!='\'';
1239 i++){}
1240 if( i>0 ){
1241 utf8_printf(out,"%.*s",i,z);
1243 if( z[i]=='<' ){
1244 raw_printf(out,"&lt;");
1245 }else if( z[i]=='&' ){
1246 raw_printf(out,"&amp;");
1247 }else if( z[i]=='>' ){
1248 raw_printf(out,"&gt;");
1249 }else if( z[i]=='\"' ){
1250 raw_printf(out,"&quot;");
1251 }else if( z[i]=='\'' ){
1252 raw_printf(out,"&#39;");
1253 }else{
1254 break;
1256 z += i + 1;
1261 ** If a field contains any character identified by a 1 in the following
1262 ** array, then the string must be quoted for CSV.
1264 static const char needCsvQuote[] = {
1265 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1266 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1267 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1268 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1272 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1273 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1274 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1275 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1276 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1277 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1278 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1279 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1280 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1284 ** Output a single term of CSV. Actually, p->colSeparator is used for
1285 ** the separator, which may or may not be a comma. p->nullValue is
1286 ** the null value. Strings are quoted if necessary. The separator
1287 ** is only issued if bSep is true.
1289 static void output_csv(ShellState *p, const char *z, int bSep){
1290 FILE *out = p->out;
1291 if( z==0 ){
1292 utf8_printf(out,"%s",p->nullValue);
1293 }else{
1294 int i;
1295 int nSep = strlen30(p->colSeparator);
1296 for(i=0; z[i]; i++){
1297 if( needCsvQuote[((unsigned char*)z)[i]]
1298 || (z[i]==p->colSeparator[0] &&
1299 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1300 i = 0;
1301 break;
1304 if( i==0 ){
1305 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1306 utf8_printf(out, "%s", zQuoted);
1307 sqlite3_free(zQuoted);
1308 }else{
1309 utf8_printf(out, "%s", z);
1312 if( bSep ){
1313 utf8_printf(p->out, "%s", p->colSeparator);
1318 ** This routine runs when the user presses Ctrl-C
1320 static void interrupt_handler(int NotUsed){
1321 UNUSED_PARAMETER(NotUsed);
1322 seenInterrupt++;
1323 if( seenInterrupt>2 ) exit(1);
1324 if( globalDb ) sqlite3_interrupt(globalDb);
1327 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1329 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1331 static BOOL WINAPI ConsoleCtrlHandler(
1332 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1334 if( dwCtrlType==CTRL_C_EVENT ){
1335 interrupt_handler(0);
1336 return TRUE;
1338 return FALSE;
1340 #endif
1342 #ifndef SQLITE_OMIT_AUTHORIZATION
1344 ** When the ".auth ON" is set, the following authorizer callback is
1345 ** invoked. It always returns SQLITE_OK.
1347 static int shellAuth(
1348 void *pClientData,
1349 int op,
1350 const char *zA1,
1351 const char *zA2,
1352 const char *zA3,
1353 const char *zA4
1355 ShellState *p = (ShellState*)pClientData;
1356 static const char *azAction[] = { 0,
1357 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1358 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1359 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1360 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1361 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1362 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1363 "PRAGMA", "READ", "SELECT",
1364 "TRANSACTION", "UPDATE", "ATTACH",
1365 "DETACH", "ALTER_TABLE", "REINDEX",
1366 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1367 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1369 int i;
1370 const char *az[4];
1371 az[0] = zA1;
1372 az[1] = zA2;
1373 az[2] = zA3;
1374 az[3] = zA4;
1375 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1376 for(i=0; i<4; i++){
1377 raw_printf(p->out, " ");
1378 if( az[i] ){
1379 output_c_string(p->out, az[i]);
1380 }else{
1381 raw_printf(p->out, "NULL");
1384 raw_printf(p->out, "\n");
1385 return SQLITE_OK;
1387 #endif
1390 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1392 ** This routine converts some CREATE TABLE statements for shadow tables
1393 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1395 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1396 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1397 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1398 }else{
1399 utf8_printf(out, "%s%s", z, zTail);
1402 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1403 char c = z[n];
1404 z[n] = 0;
1405 printSchemaLine(out, z, zTail);
1406 z[n] = c;
1410 ** This is the callback routine that the shell
1411 ** invokes for each row of a query result.
1413 static int shell_callback(
1414 void *pArg,
1415 int nArg, /* Number of result columns */
1416 char **azArg, /* Text of each result column */
1417 char **azCol, /* Column names */
1418 int *aiType /* Column types */
1420 int i;
1421 ShellState *p = (ShellState*)pArg;
1423 if( azArg==0 ) return 0;
1424 switch( p->cMode ){
1425 case MODE_Line: {
1426 int w = 5;
1427 if( azArg==0 ) break;
1428 for(i=0; i<nArg; i++){
1429 int len = strlen30(azCol[i] ? azCol[i] : "");
1430 if( len>w ) w = len;
1432 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1433 for(i=0; i<nArg; i++){
1434 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1435 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1437 break;
1439 case MODE_Explain:
1440 case MODE_Column: {
1441 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1442 const int *colWidth;
1443 int showHdr;
1444 char *rowSep;
1445 if( p->cMode==MODE_Column ){
1446 colWidth = p->colWidth;
1447 showHdr = p->showHeader;
1448 rowSep = p->rowSeparator;
1449 }else{
1450 colWidth = aExplainWidths;
1451 showHdr = 1;
1452 rowSep = SEP_Row;
1454 if( p->cnt++==0 ){
1455 for(i=0; i<nArg; i++){
1456 int w, n;
1457 if( i<ArraySize(p->colWidth) ){
1458 w = colWidth[i];
1459 }else{
1460 w = 0;
1462 if( w==0 ){
1463 w = strlenChar(azCol[i] ? azCol[i] : "");
1464 if( w<10 ) w = 10;
1465 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1466 if( w<n ) w = n;
1468 if( i<ArraySize(p->actualWidth) ){
1469 p->actualWidth[i] = w;
1471 if( showHdr ){
1472 utf8_width_print(p->out, w, azCol[i]);
1473 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1476 if( showHdr ){
1477 for(i=0; i<nArg; i++){
1478 int w;
1479 if( i<ArraySize(p->actualWidth) ){
1480 w = p->actualWidth[i];
1481 if( w<0 ) w = -w;
1482 }else{
1483 w = 10;
1485 utf8_printf(p->out,"%-*.*s%s",w,w,
1486 "----------------------------------------------------------"
1487 "----------------------------------------------------------",
1488 i==nArg-1 ? rowSep : " ");
1492 if( azArg==0 ) break;
1493 for(i=0; i<nArg; i++){
1494 int w;
1495 if( i<ArraySize(p->actualWidth) ){
1496 w = p->actualWidth[i];
1497 }else{
1498 w = 10;
1500 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1501 w = strlenChar(azArg[i]);
1503 if( i==1 && p->aiIndent && p->pStmt ){
1504 if( p->iIndent<p->nIndent ){
1505 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1507 p->iIndent++;
1509 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1510 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1512 break;
1514 case MODE_Semi: { /* .schema and .fullschema output */
1515 printSchemaLine(p->out, azArg[0], ";\n");
1516 break;
1518 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1519 char *z;
1520 int j;
1521 int nParen = 0;
1522 char cEnd = 0;
1523 char c;
1524 int nLine = 0;
1525 assert( nArg==1 );
1526 if( azArg[0]==0 ) break;
1527 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1528 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1530 utf8_printf(p->out, "%s;\n", azArg[0]);
1531 break;
1533 z = sqlite3_mprintf("%s", azArg[0]);
1534 j = 0;
1535 for(i=0; IsSpace(z[i]); i++){}
1536 for(; (c = z[i])!=0; i++){
1537 if( IsSpace(c) ){
1538 if( z[j-1]=='\r' ) z[j-1] = '\n';
1539 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1540 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1541 j--;
1543 z[j++] = c;
1545 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1546 z[j] = 0;
1547 if( strlen30(z)>=79 ){
1548 for(i=j=0; (c = z[i])!=0; i++){
1549 if( c==cEnd ){
1550 cEnd = 0;
1551 }else if( c=='"' || c=='\'' || c=='`' ){
1552 cEnd = c;
1553 }else if( c=='[' ){
1554 cEnd = ']';
1555 }else if( c=='(' ){
1556 nParen++;
1557 }else if( c==')' ){
1558 nParen--;
1559 if( nLine>0 && nParen==0 && j>0 ){
1560 printSchemaLineN(p->out, z, j, "\n");
1561 j = 0;
1564 z[j++] = c;
1565 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1566 if( c=='\n' ) j--;
1567 printSchemaLineN(p->out, z, j, "\n ");
1568 j = 0;
1569 nLine++;
1570 while( IsSpace(z[i+1]) ){ i++; }
1573 z[j] = 0;
1575 printSchemaLine(p->out, z, ";\n");
1576 sqlite3_free(z);
1577 break;
1579 case MODE_List: {
1580 if( p->cnt++==0 && p->showHeader ){
1581 for(i=0; i<nArg; i++){
1582 utf8_printf(p->out,"%s%s",azCol[i],
1583 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1586 if( azArg==0 ) break;
1587 for(i=0; i<nArg; i++){
1588 char *z = azArg[i];
1589 if( z==0 ) z = p->nullValue;
1590 utf8_printf(p->out, "%s", z);
1591 if( i<nArg-1 ){
1592 utf8_printf(p->out, "%s", p->colSeparator);
1593 }else{
1594 utf8_printf(p->out, "%s", p->rowSeparator);
1597 break;
1599 case MODE_Html: {
1600 if( p->cnt++==0 && p->showHeader ){
1601 raw_printf(p->out,"<TR>");
1602 for(i=0; i<nArg; i++){
1603 raw_printf(p->out,"<TH>");
1604 output_html_string(p->out, azCol[i]);
1605 raw_printf(p->out,"</TH>\n");
1607 raw_printf(p->out,"</TR>\n");
1609 if( azArg==0 ) break;
1610 raw_printf(p->out,"<TR>");
1611 for(i=0; i<nArg; i++){
1612 raw_printf(p->out,"<TD>");
1613 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1614 raw_printf(p->out,"</TD>\n");
1616 raw_printf(p->out,"</TR>\n");
1617 break;
1619 case MODE_Tcl: {
1620 if( p->cnt++==0 && p->showHeader ){
1621 for(i=0; i<nArg; i++){
1622 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1623 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1625 utf8_printf(p->out, "%s", p->rowSeparator);
1627 if( azArg==0 ) break;
1628 for(i=0; i<nArg; i++){
1629 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1630 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1632 utf8_printf(p->out, "%s", p->rowSeparator);
1633 break;
1635 case MODE_Csv: {
1636 setBinaryMode(p->out, 1);
1637 if( p->cnt++==0 && p->showHeader ){
1638 for(i=0; i<nArg; i++){
1639 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1641 utf8_printf(p->out, "%s", p->rowSeparator);
1643 if( nArg>0 ){
1644 for(i=0; i<nArg; i++){
1645 output_csv(p, azArg[i], i<nArg-1);
1647 utf8_printf(p->out, "%s", p->rowSeparator);
1649 setTextMode(p->out, 1);
1650 break;
1652 case MODE_Insert: {
1653 if( azArg==0 ) break;
1654 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1655 if( p->showHeader ){
1656 raw_printf(p->out,"(");
1657 for(i=0; i<nArg; i++){
1658 if( i>0 ) raw_printf(p->out, ",");
1659 if( quoteChar(azCol[i]) ){
1660 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1661 utf8_printf(p->out, "%s", z);
1662 sqlite3_free(z);
1663 }else{
1664 raw_printf(p->out, "%s", azCol[i]);
1667 raw_printf(p->out,")");
1669 p->cnt++;
1670 for(i=0; i<nArg; i++){
1671 raw_printf(p->out, i>0 ? "," : " VALUES(");
1672 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1673 utf8_printf(p->out,"NULL");
1674 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1675 if( ShellHasFlag(p, SHFLG_Newlines) ){
1676 output_quoted_string(p->out, azArg[i]);
1677 }else{
1678 output_quoted_escaped_string(p->out, azArg[i]);
1680 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1681 utf8_printf(p->out,"%s", azArg[i]);
1682 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1683 char z[50];
1684 double r = sqlite3_column_double(p->pStmt, i);
1685 sqlite3_snprintf(50,z,"%!.20g", r);
1686 raw_printf(p->out, "%s", z);
1687 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1688 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1689 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1690 output_hex_blob(p->out, pBlob, nBlob);
1691 }else if( isNumber(azArg[i], 0) ){
1692 utf8_printf(p->out,"%s", azArg[i]);
1693 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1694 output_quoted_string(p->out, azArg[i]);
1695 }else{
1696 output_quoted_escaped_string(p->out, azArg[i]);
1699 raw_printf(p->out,");\n");
1700 break;
1702 case MODE_Quote: {
1703 if( azArg==0 ) break;
1704 if( p->cnt==0 && p->showHeader ){
1705 for(i=0; i<nArg; i++){
1706 if( i>0 ) raw_printf(p->out, ",");
1707 output_quoted_string(p->out, azCol[i]);
1709 raw_printf(p->out,"\n");
1711 p->cnt++;
1712 for(i=0; i<nArg; i++){
1713 if( i>0 ) raw_printf(p->out, ",");
1714 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1715 utf8_printf(p->out,"NULL");
1716 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1717 output_quoted_string(p->out, azArg[i]);
1718 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1719 utf8_printf(p->out,"%s", azArg[i]);
1720 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1721 char z[50];
1722 double r = sqlite3_column_double(p->pStmt, i);
1723 sqlite3_snprintf(50,z,"%!.20g", r);
1724 raw_printf(p->out, "%s", z);
1725 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1726 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1727 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1728 output_hex_blob(p->out, pBlob, nBlob);
1729 }else if( isNumber(azArg[i], 0) ){
1730 utf8_printf(p->out,"%s", azArg[i]);
1731 }else{
1732 output_quoted_string(p->out, azArg[i]);
1735 raw_printf(p->out,"\n");
1736 break;
1738 case MODE_Ascii: {
1739 if( p->cnt++==0 && p->showHeader ){
1740 for(i=0; i<nArg; i++){
1741 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1742 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1744 utf8_printf(p->out, "%s", p->rowSeparator);
1746 if( azArg==0 ) break;
1747 for(i=0; i<nArg; i++){
1748 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1749 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1751 utf8_printf(p->out, "%s", p->rowSeparator);
1752 break;
1755 return 0;
1759 ** This is the callback routine that the SQLite library
1760 ** invokes for each row of a query result.
1762 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1763 /* since we don't have type info, call the shell_callback with a NULL value */
1764 return shell_callback(pArg, nArg, azArg, azCol, NULL);
1768 ** This is the callback routine from sqlite3_exec() that appends all
1769 ** output onto the end of a ShellText object.
1771 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1772 ShellText *p = (ShellText*)pArg;
1773 int i;
1774 UNUSED_PARAMETER(az);
1775 if( azArg==0 ) return 0;
1776 if( p->n ) appendText(p, "|", 0);
1777 for(i=0; i<nArg; i++){
1778 if( i ) appendText(p, ",", 0);
1779 if( azArg[i] ) appendText(p, azArg[i], 0);
1781 return 0;
1785 ** Generate an appropriate SELFTEST table in the main database.
1787 static void createSelftestTable(ShellState *p){
1788 char *zErrMsg = 0;
1789 sqlite3_exec(p->db,
1790 "SAVEPOINT selftest_init;\n"
1791 "CREATE TABLE IF NOT EXISTS selftest(\n"
1792 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1793 " op TEXT,\n" /* Operator: memo run */
1794 " cmd TEXT,\n" /* Command text */
1795 " ans TEXT\n" /* Desired answer */
1796 ");"
1797 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1798 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1799 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1800 " 'memo','Tests generated by --init');\n"
1801 "INSERT INTO [_shell$self]\n"
1802 " SELECT 'run',\n"
1803 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1804 "FROM sqlite_master ORDER BY 2'',224))',\n"
1805 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1806 "FROM sqlite_master ORDER BY 2',224));\n"
1807 "INSERT INTO [_shell$self]\n"
1808 " SELECT 'run',"
1809 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1810 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1811 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1812 " FROM (\n"
1813 " SELECT name FROM sqlite_master\n"
1814 " WHERE type='table'\n"
1815 " AND name<>'selftest'\n"
1816 " AND coalesce(rootpage,0)>0\n"
1817 " )\n"
1818 " ORDER BY name;\n"
1819 "INSERT INTO [_shell$self]\n"
1820 " VALUES('run','PRAGMA integrity_check','ok');\n"
1821 "INSERT INTO selftest(tno,op,cmd,ans)"
1822 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1823 "DROP TABLE [_shell$self];"
1824 ,0,0,&zErrMsg);
1825 if( zErrMsg ){
1826 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1827 sqlite3_free(zErrMsg);
1829 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1834 ** Set the destination table field of the ShellState structure to
1835 ** the name of the table given. Escape any quote characters in the
1836 ** table name.
1838 static void set_table_name(ShellState *p, const char *zName){
1839 int i, n;
1840 char cQuote;
1841 char *z;
1843 if( p->zDestTable ){
1844 free(p->zDestTable);
1845 p->zDestTable = 0;
1847 if( zName==0 ) return;
1848 cQuote = quoteChar(zName);
1849 n = strlen30(zName);
1850 if( cQuote ) n += n+2;
1851 z = p->zDestTable = malloc( n+1 );
1852 if( z==0 ){
1853 raw_printf(stderr,"Error: out of memory\n");
1854 exit(1);
1856 n = 0;
1857 if( cQuote ) z[n++] = cQuote;
1858 for(i=0; zName[i]; i++){
1859 z[n++] = zName[i];
1860 if( zName[i]==cQuote ) z[n++] = cQuote;
1862 if( cQuote ) z[n++] = cQuote;
1863 z[n] = 0;
1868 ** Execute a query statement that will generate SQL output. Print
1869 ** the result columns, comma-separated, on a line and then add a
1870 ** semicolon terminator to the end of that line.
1872 ** If the number of columns is 1 and that column contains text "--"
1873 ** then write the semicolon on a separate line. That way, if a
1874 ** "--" comment occurs at the end of the statement, the comment
1875 ** won't consume the semicolon terminator.
1877 static int run_table_dump_query(
1878 ShellState *p, /* Query context */
1879 const char *zSelect, /* SELECT statement to extract content */
1880 const char *zFirstRow /* Print before first row, if not NULL */
1882 sqlite3_stmt *pSelect;
1883 int rc;
1884 int nResult;
1885 int i;
1886 const char *z;
1887 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
1888 if( rc!=SQLITE_OK || !pSelect ){
1889 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1890 sqlite3_errmsg(p->db));
1891 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1892 return rc;
1894 rc = sqlite3_step(pSelect);
1895 nResult = sqlite3_column_count(pSelect);
1896 while( rc==SQLITE_ROW ){
1897 if( zFirstRow ){
1898 utf8_printf(p->out, "%s", zFirstRow);
1899 zFirstRow = 0;
1901 z = (const char*)sqlite3_column_text(pSelect, 0);
1902 utf8_printf(p->out, "%s", z);
1903 for(i=1; i<nResult; i++){
1904 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
1906 if( z==0 ) z = "";
1907 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
1908 if( z[0] ){
1909 raw_printf(p->out, "\n;\n");
1910 }else{
1911 raw_printf(p->out, ";\n");
1913 rc = sqlite3_step(pSelect);
1915 rc = sqlite3_finalize(pSelect);
1916 if( rc!=SQLITE_OK ){
1917 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1918 sqlite3_errmsg(p->db));
1919 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1921 return rc;
1925 ** Allocate space and save off current error string.
1927 static char *save_err_msg(
1928 sqlite3 *db /* Database to query */
1930 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1931 char *zErrMsg = sqlite3_malloc64(nErrMsg);
1932 if( zErrMsg ){
1933 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1935 return zErrMsg;
1938 #ifdef __linux__
1940 ** Attempt to display I/O stats on Linux using /proc/PID/io
1942 static void displayLinuxIoStats(FILE *out){
1943 FILE *in;
1944 char z[200];
1945 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
1946 in = fopen(z, "rb");
1947 if( in==0 ) return;
1948 while( fgets(z, sizeof(z), in)!=0 ){
1949 static const struct {
1950 const char *zPattern;
1951 const char *zDesc;
1952 } aTrans[] = {
1953 { "rchar: ", "Bytes received by read():" },
1954 { "wchar: ", "Bytes sent to write():" },
1955 { "syscr: ", "Read() system calls:" },
1956 { "syscw: ", "Write() system calls:" },
1957 { "read_bytes: ", "Bytes read from storage:" },
1958 { "write_bytes: ", "Bytes written to storage:" },
1959 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1961 int i;
1962 for(i=0; i<ArraySize(aTrans); i++){
1963 int n = strlen30(aTrans[i].zPattern);
1964 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
1965 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
1966 break;
1970 fclose(in);
1972 #endif
1975 ** Display a single line of status using 64-bit values.
1977 static void displayStatLine(
1978 ShellState *p, /* The shell context */
1979 char *zLabel, /* Label for this one line */
1980 char *zFormat, /* Format for the result */
1981 int iStatusCtrl, /* Which status to display */
1982 int bReset /* True to reset the stats */
1984 sqlite3_int64 iCur = -1;
1985 sqlite3_int64 iHiwtr = -1;
1986 int i, nPercent;
1987 char zLine[200];
1988 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
1989 for(i=0, nPercent=0; zFormat[i]; i++){
1990 if( zFormat[i]=='%' ) nPercent++;
1992 if( nPercent>1 ){
1993 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
1994 }else{
1995 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
1997 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2001 ** Display memory stats.
2003 static int display_stats(
2004 sqlite3 *db, /* Database to query */
2005 ShellState *pArg, /* Pointer to ShellState */
2006 int bReset /* True to reset the stats */
2008 int iCur;
2009 int iHiwtr;
2011 if( pArg && pArg->out ){
2012 displayStatLine(pArg, "Memory Used:",
2013 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2014 displayStatLine(pArg, "Number of Outstanding Allocations:",
2015 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2016 if( pArg->shellFlgs & SHFLG_Pagecache ){
2017 displayStatLine(pArg, "Number of Pcache Pages Used:",
2018 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2020 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2021 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2022 displayStatLine(pArg, "Largest Allocation:",
2023 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2024 displayStatLine(pArg, "Largest Pcache Allocation:",
2025 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2026 #ifdef YYTRACKMAXSTACKDEPTH
2027 displayStatLine(pArg, "Deepest Parser Stack:",
2028 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2029 #endif
2032 if( pArg && pArg->out && db ){
2033 if( pArg->shellFlgs & SHFLG_Lookaside ){
2034 iHiwtr = iCur = -1;
2035 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2036 &iCur, &iHiwtr, bReset);
2037 raw_printf(pArg->out,
2038 "Lookaside Slots Used: %d (max %d)\n",
2039 iCur, iHiwtr);
2040 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2041 &iCur, &iHiwtr, bReset);
2042 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2043 iHiwtr);
2044 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2045 &iCur, &iHiwtr, bReset);
2046 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2047 iHiwtr);
2048 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2049 &iCur, &iHiwtr, bReset);
2050 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2051 iHiwtr);
2053 iHiwtr = iCur = -1;
2054 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2055 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2056 iCur);
2057 iHiwtr = iCur = -1;
2058 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2059 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2060 iHiwtr = iCur = -1;
2061 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2062 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2063 iHiwtr = iCur = -1;
2064 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2065 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2066 iHiwtr = iCur = -1;
2067 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2068 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2069 iCur);
2070 iHiwtr = iCur = -1;
2071 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2072 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2073 iCur);
2076 if( pArg && pArg->out && db && pArg->pStmt ){
2077 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2078 bReset);
2079 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2080 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2081 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2082 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2083 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2084 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2085 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2088 #ifdef __linux__
2089 displayLinuxIoStats(pArg->out);
2090 #endif
2092 /* Do not remove this machine readable comment: extra-stats-output-here */
2094 return 0;
2098 ** Display scan stats.
2100 static void display_scanstats(
2101 sqlite3 *db, /* Database to query */
2102 ShellState *pArg /* Pointer to ShellState */
2104 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2105 UNUSED_PARAMETER(db);
2106 UNUSED_PARAMETER(pArg);
2107 #else
2108 int i, k, n, mx;
2109 raw_printf(pArg->out, "-------- scanstats --------\n");
2110 mx = 0;
2111 for(k=0; k<=mx; k++){
2112 double rEstLoop = 1.0;
2113 for(i=n=0; 1; i++){
2114 sqlite3_stmt *p = pArg->pStmt;
2115 sqlite3_int64 nLoop, nVisit;
2116 double rEst;
2117 int iSid;
2118 const char *zExplain;
2119 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2120 break;
2122 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2123 if( iSid>mx ) mx = iSid;
2124 if( iSid!=k ) continue;
2125 if( n==0 ){
2126 rEstLoop = (double)nLoop;
2127 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2129 n++;
2130 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2131 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2132 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2133 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2134 rEstLoop *= rEst;
2135 raw_printf(pArg->out,
2136 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2137 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2141 raw_printf(pArg->out, "---------------------------\n");
2142 #endif
2146 ** Parameter azArray points to a zero-terminated array of strings. zStr
2147 ** points to a single nul-terminated string. Return non-zero if zStr
2148 ** is equal, according to strcmp(), to any of the strings in the array.
2149 ** Otherwise, return zero.
2151 static int str_in_array(const char *zStr, const char **azArray){
2152 int i;
2153 for(i=0; azArray[i]; i++){
2154 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2156 return 0;
2160 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2161 ** and populate the ShellState.aiIndent[] array with the number of
2162 ** spaces each opcode should be indented before it is output.
2164 ** The indenting rules are:
2166 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2167 ** all opcodes that occur between the p2 jump destination and the opcode
2168 ** itself by 2 spaces.
2170 ** * For each "Goto", if the jump destination is earlier in the program
2171 ** and ends on one of:
2172 ** Yield SeekGt SeekLt RowSetRead Rewind
2173 ** or if the P1 parameter is one instead of zero,
2174 ** then indent all opcodes between the earlier instruction
2175 ** and "Goto" by 2 spaces.
2177 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2178 const char *zSql; /* The text of the SQL statement */
2179 const char *z; /* Used to check if this is an EXPLAIN */
2180 int *abYield = 0; /* True if op is an OP_Yield */
2181 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2182 int iOp; /* Index of operation in p->aiIndent[] */
2184 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2185 "NextIfOpen", "PrevIfOpen", 0 };
2186 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2187 "Rewind", 0 };
2188 const char *azGoto[] = { "Goto", 0 };
2190 /* Try to figure out if this is really an EXPLAIN statement. If this
2191 ** cannot be verified, return early. */
2192 if( sqlite3_column_count(pSql)!=8 ){
2193 p->cMode = p->mode;
2194 return;
2196 zSql = sqlite3_sql(pSql);
2197 if( zSql==0 ) return;
2198 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2199 if( sqlite3_strnicmp(z, "explain", 7) ){
2200 p->cMode = p->mode;
2201 return;
2204 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2205 int i;
2206 int iAddr = sqlite3_column_int(pSql, 0);
2207 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2209 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2210 ** p2 is an instruction address, set variable p2op to the index of that
2211 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2212 ** the current instruction is part of a sub-program generated by an
2213 ** SQL trigger or foreign key. */
2214 int p2 = sqlite3_column_int(pSql, 3);
2215 int p2op = (p2 + (iOp-iAddr));
2217 /* Grow the p->aiIndent array as required */
2218 if( iOp>=nAlloc ){
2219 if( iOp==0 ){
2220 /* Do further verfication that this is explain output. Abort if
2221 ** it is not */
2222 static const char *explainCols[] = {
2223 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2224 int jj;
2225 for(jj=0; jj<ArraySize(explainCols); jj++){
2226 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2227 p->cMode = p->mode;
2228 sqlite3_reset(pSql);
2229 return;
2233 nAlloc += 100;
2234 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2235 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2237 abYield[iOp] = str_in_array(zOp, azYield);
2238 p->aiIndent[iOp] = 0;
2239 p->nIndent = iOp+1;
2241 if( str_in_array(zOp, azNext) ){
2242 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2244 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2245 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2247 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2251 p->iIndent = 0;
2252 sqlite3_free(abYield);
2253 sqlite3_reset(pSql);
2257 ** Free the array allocated by explain_data_prepare().
2259 static void explain_data_delete(ShellState *p){
2260 sqlite3_free(p->aiIndent);
2261 p->aiIndent = 0;
2262 p->nIndent = 0;
2263 p->iIndent = 0;
2267 ** Disable and restore .wheretrace and .selecttrace settings.
2269 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2270 extern int sqlite3SelectTrace;
2271 static int savedSelectTrace;
2272 #endif
2273 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2274 extern int sqlite3WhereTrace;
2275 static int savedWhereTrace;
2276 #endif
2277 static void disable_debug_trace_modes(void){
2278 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2279 savedSelectTrace = sqlite3SelectTrace;
2280 sqlite3SelectTrace = 0;
2281 #endif
2282 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2283 savedWhereTrace = sqlite3WhereTrace;
2284 sqlite3WhereTrace = 0;
2285 #endif
2287 static void restore_debug_trace_modes(void){
2288 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2289 sqlite3SelectTrace = savedSelectTrace;
2290 #endif
2291 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2292 sqlite3WhereTrace = savedWhereTrace;
2293 #endif
2297 ** Run a prepared statement
2299 static void exec_prepared_stmt(
2300 ShellState *pArg, /* Pointer to ShellState */
2301 sqlite3_stmt *pStmt, /* Statment to run */
2302 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2304 int rc;
2306 /* perform the first step. this will tell us if we
2307 ** have a result set or not and how wide it is.
2309 rc = sqlite3_step(pStmt);
2310 /* if we have a result set... */
2311 if( SQLITE_ROW == rc ){
2312 /* if we have a callback... */
2313 if( xCallback ){
2314 /* allocate space for col name ptr, value ptr, and type */
2315 int nCol = sqlite3_column_count(pStmt);
2316 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2317 if( !pData ){
2318 rc = SQLITE_NOMEM;
2319 }else{
2320 char **azCols = (char **)pData; /* Names of result columns */
2321 char **azVals = &azCols[nCol]; /* Results */
2322 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2323 int i, x;
2324 assert(sizeof(int) <= sizeof(char *));
2325 /* save off ptrs to column names */
2326 for(i=0; i<nCol; i++){
2327 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2330 /* extract the data and data types */
2331 for(i=0; i<nCol; i++){
2332 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2333 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2334 azVals[i] = "";
2335 }else{
2336 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2338 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2339 rc = SQLITE_NOMEM;
2340 break; /* from for */
2342 } /* end for */
2344 /* if data and types extracted successfully... */
2345 if( SQLITE_ROW == rc ){
2346 /* call the supplied callback with the result row data */
2347 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2348 rc = SQLITE_ABORT;
2349 }else{
2350 rc = sqlite3_step(pStmt);
2353 } while( SQLITE_ROW == rc );
2354 sqlite3_free(pData);
2356 }else{
2358 rc = sqlite3_step(pStmt);
2359 } while( rc == SQLITE_ROW );
2365 ** This function is called to process SQL if the previous shell command
2366 ** was ".expert". It passes the SQL in the second argument directly to
2367 ** the sqlite3expert object.
2369 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2370 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2371 ** an English language error message. It is the responsibility of the
2372 ** caller to eventually free this buffer using sqlite3_free().
2374 static int expertHandleSQL(
2375 ShellState *pState,
2376 const char *zSql,
2377 char **pzErr
2379 assert( pState->expert.pExpert );
2380 assert( pzErr==0 || *pzErr==0 );
2381 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2385 ** This function is called either to silently clean up the object
2386 ** created by the ".expert" command (if bCancel==1), or to generate a
2387 ** report from it and then clean it up (if bCancel==0).
2389 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2390 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2391 ** an English language error message. It is the responsibility of the
2392 ** caller to eventually free this buffer using sqlite3_free().
2394 static int expertFinish(
2395 ShellState *pState,
2396 int bCancel,
2397 char **pzErr
2399 int rc = SQLITE_OK;
2400 sqlite3expert *p = pState->expert.pExpert;
2401 assert( p );
2402 assert( bCancel || pzErr==0 || *pzErr==0 );
2403 if( bCancel==0 ){
2404 FILE *out = pState->out;
2405 int bVerbose = pState->expert.bVerbose;
2407 rc = sqlite3_expert_analyze(p, pzErr);
2408 if( rc==SQLITE_OK ){
2409 int nQuery = sqlite3_expert_count(p);
2410 int i;
2412 if( bVerbose ){
2413 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2414 raw_printf(out, "-- Candidates -----------------------------\n");
2415 raw_printf(out, "%s\n", zCand);
2417 for(i=0; i<nQuery; i++){
2418 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2419 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2420 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2421 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2422 if( bVerbose ){
2423 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2424 raw_printf(out, "%s\n\n", zSql);
2426 raw_printf(out, "%s\n", zIdx);
2427 raw_printf(out, "%s\n", zEQP);
2431 sqlite3_expert_destroy(p);
2432 pState->expert.pExpert = 0;
2433 return rc;
2438 ** Execute a statement or set of statements. Print
2439 ** any result rows/columns depending on the current mode
2440 ** set via the supplied callback.
2442 ** This is very similar to SQLite's built-in sqlite3_exec()
2443 ** function except it takes a slightly different callback
2444 ** and callback data argument.
2446 static int shell_exec(
2447 sqlite3 *db, /* An open database */
2448 const char *zSql, /* SQL to be evaluated */
2449 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2450 /* (not the same as sqlite3_exec) */
2451 ShellState *pArg, /* Pointer to ShellState */
2452 char **pzErrMsg /* Error msg written here */
2454 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2455 int rc = SQLITE_OK; /* Return Code */
2456 int rc2;
2457 const char *zLeftover; /* Tail of unprocessed SQL */
2459 if( pzErrMsg ){
2460 *pzErrMsg = NULL;
2463 if( pArg->expert.pExpert ){
2464 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2465 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2468 while( zSql[0] && (SQLITE_OK == rc) ){
2469 static const char *zStmtSql;
2470 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2471 if( SQLITE_OK != rc ){
2472 if( pzErrMsg ){
2473 *pzErrMsg = save_err_msg(db);
2475 }else{
2476 if( !pStmt ){
2477 /* this happens for a comment or white-space */
2478 zSql = zLeftover;
2479 while( IsSpace(zSql[0]) ) zSql++;
2480 continue;
2482 zStmtSql = sqlite3_sql(pStmt);
2483 if( zStmtSql==0 ) zStmtSql = "";
2484 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2486 /* save off the prepared statment handle and reset row count */
2487 if( pArg ){
2488 pArg->pStmt = pStmt;
2489 pArg->cnt = 0;
2492 /* echo the sql statement if echo on */
2493 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2494 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2497 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2498 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2499 sqlite3_stmt *pExplain;
2500 char *zEQP;
2501 int triggerEQP = 0;
2502 disable_debug_trace_modes();
2503 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2504 if( pArg->autoEQP>=AUTOEQP_trigger ){
2505 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2507 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2508 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2509 if( rc==SQLITE_OK ){
2510 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2511 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2512 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2513 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2514 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2517 sqlite3_finalize(pExplain);
2518 sqlite3_free(zEQP);
2519 if( pArg->autoEQP>=AUTOEQP_full ){
2520 /* Also do an EXPLAIN for ".eqp full" mode */
2521 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2522 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2523 if( rc==SQLITE_OK ){
2524 pArg->cMode = MODE_Explain;
2525 explain_data_prepare(pArg, pExplain);
2526 exec_prepared_stmt(pArg, pExplain, xCallback);
2527 explain_data_delete(pArg);
2529 sqlite3_finalize(pExplain);
2530 sqlite3_free(zEQP);
2532 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
2533 restore_debug_trace_modes();
2536 if( pArg ){
2537 pArg->cMode = pArg->mode;
2538 if( pArg->autoExplain
2539 && sqlite3_column_count(pStmt)==8
2540 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2542 pArg->cMode = MODE_Explain;
2545 /* If the shell is currently in ".explain" mode, gather the extra
2546 ** data required to add indents to the output.*/
2547 if( pArg->cMode==MODE_Explain ){
2548 explain_data_prepare(pArg, pStmt);
2552 exec_prepared_stmt(pArg, pStmt, xCallback);
2553 explain_data_delete(pArg);
2555 /* print usage stats if stats on */
2556 if( pArg && pArg->statsOn ){
2557 display_stats(db, pArg, 0);
2560 /* print loop-counters if required */
2561 if( pArg && pArg->scanstatsOn ){
2562 display_scanstats(db, pArg);
2565 /* Finalize the statement just executed. If this fails, save a
2566 ** copy of the error message. Otherwise, set zSql to point to the
2567 ** next statement to execute. */
2568 rc2 = sqlite3_finalize(pStmt);
2569 if( rc!=SQLITE_NOMEM ) rc = rc2;
2570 if( rc==SQLITE_OK ){
2571 zSql = zLeftover;
2572 while( IsSpace(zSql[0]) ) zSql++;
2573 }else if( pzErrMsg ){
2574 *pzErrMsg = save_err_msg(db);
2577 /* clear saved stmt handle */
2578 if( pArg ){
2579 pArg->pStmt = NULL;
2582 } /* end while */
2584 return rc;
2588 ** Release memory previously allocated by tableColumnList().
2590 static void freeColumnList(char **azCol){
2591 int i;
2592 for(i=1; azCol[i]; i++){
2593 sqlite3_free(azCol[i]);
2595 /* azCol[0] is a static string */
2596 sqlite3_free(azCol);
2600 ** Return a list of pointers to strings which are the names of all
2601 ** columns in table zTab. The memory to hold the names is dynamically
2602 ** allocated and must be released by the caller using a subsequent call
2603 ** to freeColumnList().
2605 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2606 ** value that needs to be preserved, then azCol[0] is filled in with the
2607 ** name of the rowid column.
2609 ** The first regular column in the table is azCol[1]. The list is terminated
2610 ** by an entry with azCol[i]==0.
2612 static char **tableColumnList(ShellState *p, const char *zTab){
2613 char **azCol = 0;
2614 sqlite3_stmt *pStmt;
2615 char *zSql;
2616 int nCol = 0;
2617 int nAlloc = 0;
2618 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2619 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2620 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2621 int rc;
2623 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2624 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2625 sqlite3_free(zSql);
2626 if( rc ) return 0;
2627 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2628 if( nCol>=nAlloc-2 ){
2629 nAlloc = nAlloc*2 + nCol + 10;
2630 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2631 if( azCol==0 ){
2632 raw_printf(stderr, "Error: out of memory\n");
2633 exit(1);
2636 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2637 if( sqlite3_column_int(pStmt, 5) ){
2638 nPK++;
2639 if( nPK==1
2640 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2641 "INTEGER")==0
2643 isIPK = 1;
2644 }else{
2645 isIPK = 0;
2649 sqlite3_finalize(pStmt);
2650 if( azCol==0 ) return 0;
2651 azCol[0] = 0;
2652 azCol[nCol+1] = 0;
2654 /* The decision of whether or not a rowid really needs to be preserved
2655 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2656 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2657 ** rowids on tables where the rowid is inaccessible because there are other
2658 ** columns in the table named "rowid", "_rowid_", and "oid".
2660 if( preserveRowid && isIPK ){
2661 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2662 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2663 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2664 ** ROWID aliases. To distinguish these cases, check to see if
2665 ** there is a "pk" entry in "PRAGMA index_list". There will be
2666 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2668 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2669 " WHERE origin='pk'", zTab);
2670 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2671 sqlite3_free(zSql);
2672 if( rc ){
2673 freeColumnList(azCol);
2674 return 0;
2676 rc = sqlite3_step(pStmt);
2677 sqlite3_finalize(pStmt);
2678 preserveRowid = rc==SQLITE_ROW;
2680 if( preserveRowid ){
2681 /* Only preserve the rowid if we can find a name to use for the
2682 ** rowid */
2683 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2684 int i, j;
2685 for(j=0; j<3; j++){
2686 for(i=1; i<=nCol; i++){
2687 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2689 if( i>nCol ){
2690 /* At this point, we know that azRowid[j] is not the name of any
2691 ** ordinary column in the table. Verify that azRowid[j] is a valid
2692 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2693 ** tables will fail this last check */
2694 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2695 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2696 break;
2700 return azCol;
2704 ** Toggle the reverse_unordered_selects setting.
2706 static void toggleSelectOrder(sqlite3 *db){
2707 sqlite3_stmt *pStmt = 0;
2708 int iSetting = 0;
2709 char zStmt[100];
2710 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2711 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2712 iSetting = sqlite3_column_int(pStmt, 0);
2714 sqlite3_finalize(pStmt);
2715 sqlite3_snprintf(sizeof(zStmt), zStmt,
2716 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2717 sqlite3_exec(db, zStmt, 0, 0, 0);
2721 ** This is a different callback routine used for dumping the database.
2722 ** Each row received by this callback consists of a table name,
2723 ** the table type ("index" or "table") and SQL to create the table.
2724 ** This routine should print text sufficient to recreate the table.
2726 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2727 int rc;
2728 const char *zTable;
2729 const char *zType;
2730 const char *zSql;
2731 ShellState *p = (ShellState *)pArg;
2733 UNUSED_PARAMETER(azNotUsed);
2734 if( nArg!=3 || azArg==0 ) return 0;
2735 zTable = azArg[0];
2736 zType = azArg[1];
2737 zSql = azArg[2];
2739 if( strcmp(zTable, "sqlite_sequence")==0 ){
2740 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2741 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2742 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2743 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2744 return 0;
2745 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2746 char *zIns;
2747 if( !p->writableSchema ){
2748 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2749 p->writableSchema = 1;
2751 zIns = sqlite3_mprintf(
2752 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2753 "VALUES('table','%q','%q',0,'%q');",
2754 zTable, zTable, zSql);
2755 utf8_printf(p->out, "%s\n", zIns);
2756 sqlite3_free(zIns);
2757 return 0;
2758 }else{
2759 printSchemaLine(p->out, zSql, ";\n");
2762 if( strcmp(zType, "table")==0 ){
2763 ShellText sSelect;
2764 ShellText sTable;
2765 char **azCol;
2766 int i;
2767 char *savedDestTable;
2768 int savedMode;
2770 azCol = tableColumnList(p, zTable);
2771 if( azCol==0 ){
2772 p->nErr++;
2773 return 0;
2776 /* Always quote the table name, even if it appears to be pure ascii,
2777 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2778 initText(&sTable);
2779 appendText(&sTable, zTable, quoteChar(zTable));
2780 /* If preserving the rowid, add a column list after the table name.
2781 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2782 ** instead of the usual "INSERT INTO tab VALUES(...)".
2784 if( azCol[0] ){
2785 appendText(&sTable, "(", 0);
2786 appendText(&sTable, azCol[0], 0);
2787 for(i=1; azCol[i]; i++){
2788 appendText(&sTable, ",", 0);
2789 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2791 appendText(&sTable, ")", 0);
2794 /* Build an appropriate SELECT statement */
2795 initText(&sSelect);
2796 appendText(&sSelect, "SELECT ", 0);
2797 if( azCol[0] ){
2798 appendText(&sSelect, azCol[0], 0);
2799 appendText(&sSelect, ",", 0);
2801 for(i=1; azCol[i]; i++){
2802 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2803 if( azCol[i+1] ){
2804 appendText(&sSelect, ",", 0);
2807 freeColumnList(azCol);
2808 appendText(&sSelect, " FROM ", 0);
2809 appendText(&sSelect, zTable, quoteChar(zTable));
2811 savedDestTable = p->zDestTable;
2812 savedMode = p->mode;
2813 p->zDestTable = sTable.z;
2814 p->mode = p->cMode = MODE_Insert;
2815 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2816 if( (rc&0xff)==SQLITE_CORRUPT ){
2817 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2818 toggleSelectOrder(p->db);
2819 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2820 toggleSelectOrder(p->db);
2822 p->zDestTable = savedDestTable;
2823 p->mode = savedMode;
2824 freeText(&sTable);
2825 freeText(&sSelect);
2826 if( rc ) p->nErr++;
2828 return 0;
2832 ** Run zQuery. Use dump_callback() as the callback routine so that
2833 ** the contents of the query are output as SQL statements.
2835 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
2836 ** "ORDER BY rowid DESC" to the end.
2838 static int run_schema_dump_query(
2839 ShellState *p,
2840 const char *zQuery
2842 int rc;
2843 char *zErr = 0;
2844 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2845 if( rc==SQLITE_CORRUPT ){
2846 char *zQ2;
2847 int len = strlen30(zQuery);
2848 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2849 if( zErr ){
2850 utf8_printf(p->out, "/****** %s ******/\n", zErr);
2851 sqlite3_free(zErr);
2852 zErr = 0;
2854 zQ2 = malloc( len+100 );
2855 if( zQ2==0 ) return rc;
2856 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2857 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2858 if( rc ){
2859 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2860 }else{
2861 rc = SQLITE_CORRUPT;
2863 sqlite3_free(zErr);
2864 free(zQ2);
2866 return rc;
2870 ** Text of a help message
2872 static char zHelp[] =
2873 #ifndef SQLITE_OMIT_AUTHORIZATION
2874 ".auth ON|OFF Show authorizer callbacks\n"
2875 #endif
2876 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2877 ".bail on|off Stop after hitting an error. Default OFF\n"
2878 ".binary on|off Turn binary output on or off. Default OFF\n"
2879 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
2880 ".changes on|off Show number of rows changed by SQL\n"
2881 ".check GLOB Fail if output since .testcase does not match\n"
2882 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2883 ".databases List names and files of attached databases\n"
2884 ".dbinfo ?DB? Show status information about the database\n"
2885 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2886 " If TABLE specified, only dump tables matching\n"
2887 " LIKE pattern TABLE.\n"
2888 ".echo on|off Turn command echo on or off\n"
2889 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2890 ".exit Exit this program\n"
2891 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
2892 /* Because explain mode comes on automatically now, the ".explain" mode
2893 ** is removed from the help screen. It is still supported for legacy, however */
2894 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2895 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2896 ".headers on|off Turn display of headers on or off\n"
2897 ".help Show this message\n"
2898 ".import FILE TABLE Import data from FILE into TABLE\n"
2899 #ifndef SQLITE_OMIT_TEST_CONTROL
2900 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
2901 #endif
2902 ".indexes ?TABLE? Show names of all indexes\n"
2903 " If TABLE specified, only show indexes for tables\n"
2904 " matching LIKE pattern TABLE.\n"
2905 #ifdef SQLITE_ENABLE_IOTRACE
2906 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2907 #endif
2908 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2909 ".lint OPTIONS Report potential schema issues. Options:\n"
2910 " fkey-indexes Find missing foreign key indexes\n"
2911 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2912 ".load FILE ?ENTRY? Load an extension library\n"
2913 #endif
2914 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2915 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2916 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2917 " csv Comma-separated values\n"
2918 " column Left-aligned columns. (See .width)\n"
2919 " html HTML <table> code\n"
2920 " insert SQL insert statements for TABLE\n"
2921 " line One value per line\n"
2922 " list Values delimited by \"|\"\n"
2923 " quote Escape answers as for SQL\n"
2924 " tabs Tab-separated values\n"
2925 " tcl TCL list elements\n"
2926 ".nullvalue STRING Use STRING in place of NULL values\n"
2927 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2928 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2929 " The --new option starts with an empty file\n"
2930 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2931 ".print STRING... Print literal STRING\n"
2932 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2933 ".quit Exit this program\n"
2934 ".read FILENAME Execute SQL in FILENAME\n"
2935 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2936 ".save FILE Write in-memory database into FILE\n"
2937 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2938 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2939 " Add --indent for pretty-printing\n"
2940 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
2941 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2942 " separator for both the output mode and .import\n"
2943 #if defined(SQLITE_ENABLE_SESSION)
2944 ".session CMD ... Create or control sessions\n"
2945 #endif
2946 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
2947 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2948 ".show Show the current values for various settings\n"
2949 ".stats ?on|off? Show stats or turn stats on or off\n"
2950 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2951 ".tables ?TABLE? List names of tables\n"
2952 " If TABLE specified, only list tables matching\n"
2953 " LIKE pattern TABLE.\n"
2954 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2955 ".timeout MS Try opening locked tables for MS milliseconds\n"
2956 ".timer on|off Turn SQL timer on or off\n"
2957 ".trace FILE|off Output each SQL statement as it is run\n"
2958 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2959 ".vfslist List all available VFSes\n"
2960 ".vfsname ?AUX? Print the name of the VFS stack\n"
2961 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2962 " Negative values right-justify\n"
2965 #if defined(SQLITE_ENABLE_SESSION)
2967 ** Print help information for the ".sessions" command
2969 void session_help(ShellState *p){
2970 raw_printf(p->out,
2971 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2972 "If ?NAME? is omitted, the first defined session is used.\n"
2973 "Subcommands:\n"
2974 " attach TABLE Attach TABLE\n"
2975 " changeset FILE Write a changeset into FILE\n"
2976 " close Close one session\n"
2977 " enable ?BOOLEAN? Set or query the enable bit\n"
2978 " filter GLOB... Reject tables matching GLOBs\n"
2979 " indirect ?BOOLEAN? Mark or query the indirect status\n"
2980 " isempty Query whether the session is empty\n"
2981 " list List currently open session names\n"
2982 " open DB NAME Open a new session on DB\n"
2983 " patchset FILE Write a patchset into FILE\n"
2986 #endif
2989 /* Forward reference */
2990 static int process_input(ShellState *p, FILE *in);
2993 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
2994 ** and return a pointer to the buffer. The caller is responsible for freeing
2995 ** the memory.
2997 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
2998 ** read.
3000 ** For convenience, a nul-terminator byte is always appended to the data read
3001 ** from the file before the buffer is returned. This byte is not included in
3002 ** the final value of (*pnByte), if applicable.
3004 ** NULL is returned if any error is encountered. The final value of *pnByte
3005 ** is undefined in this case.
3007 static char *readFile(const char *zName, int *pnByte){
3008 FILE *in = fopen(zName, "rb");
3009 long nIn;
3010 size_t nRead;
3011 char *pBuf;
3012 if( in==0 ) return 0;
3013 fseek(in, 0, SEEK_END);
3014 nIn = ftell(in);
3015 rewind(in);
3016 pBuf = sqlite3_malloc64( nIn+1 );
3017 if( pBuf==0 ) return 0;
3018 nRead = fread(pBuf, nIn, 1, in);
3019 fclose(in);
3020 if( nRead!=1 ){
3021 sqlite3_free(pBuf);
3022 return 0;
3024 pBuf[nIn] = 0;
3025 if( pnByte ) *pnByte = nIn;
3026 return pBuf;
3029 #if defined(SQLITE_ENABLE_SESSION)
3031 ** Close a single OpenSession object and release all of its associated
3032 ** resources.
3034 static void session_close(OpenSession *pSession){
3035 int i;
3036 sqlite3session_delete(pSession->p);
3037 sqlite3_free(pSession->zName);
3038 for(i=0; i<pSession->nFilter; i++){
3039 sqlite3_free(pSession->azFilter[i]);
3041 sqlite3_free(pSession->azFilter);
3042 memset(pSession, 0, sizeof(OpenSession));
3044 #endif
3047 ** Close all OpenSession objects and release all associated resources.
3049 #if defined(SQLITE_ENABLE_SESSION)
3050 static void session_close_all(ShellState *p){
3051 int i;
3052 for(i=0; i<p->nSession; i++){
3053 session_close(&p->aSession[i]);
3055 p->nSession = 0;
3057 #else
3058 # define session_close_all(X)
3059 #endif
3062 ** Implementation of the xFilter function for an open session. Omit
3063 ** any tables named by ".session filter" but let all other table through.
3065 #if defined(SQLITE_ENABLE_SESSION)
3066 static int session_filter(void *pCtx, const char *zTab){
3067 OpenSession *pSession = (OpenSession*)pCtx;
3068 int i;
3069 for(i=0; i<pSession->nFilter; i++){
3070 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3072 return 1;
3074 #endif
3077 ** Make sure the database is open. If it is not, then open it. If
3078 ** the database fails to open, print an error message and exit.
3080 static void open_db(ShellState *p, int keepAlive){
3081 if( p->db==0 ){
3082 sqlite3_initialize();
3083 sqlite3_open(p->zDbFilename, &p->db);
3084 globalDb = p->db;
3085 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3086 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3087 p->zDbFilename, sqlite3_errmsg(p->db));
3088 if( keepAlive ) return;
3089 exit(1);
3091 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3092 sqlite3_enable_load_extension(p->db, 1);
3093 #endif
3094 sqlite3_fileio_init(p->db, 0, 0);
3095 sqlite3_shathree_init(p->db, 0, 0);
3096 sqlite3_completion_init(p->db, 0, 0);
3097 #ifdef SQLITE_HAVE_ZLIB
3098 sqlite3_zipfile_init(p->db, 0, 0);
3099 sqlite3_sqlar_init(p->db, 0, 0);
3100 #endif
3101 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
3102 shellAddSchemaName, 0, 0);
3103 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3104 shellModuleSchema, 0, 0);
3108 #if HAVE_READLINE || HAVE_EDITLINE
3110 ** Readline completion callbacks
3112 static char *readline_completion_generator(const char *text, int state){
3113 static sqlite3_stmt *pStmt = 0;
3114 char *zRet;
3115 if( state==0 ){
3116 char *zSql;
3117 sqlite3_finalize(pStmt);
3118 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3119 " FROM completion(%Q) ORDER BY 1", text);
3120 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3121 sqlite3_free(zSql);
3123 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3124 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
3125 }else{
3126 sqlite3_finalize(pStmt);
3127 pStmt = 0;
3128 zRet = 0;
3130 return zRet;
3132 static char **readline_completion(const char *zText, int iStart, int iEnd){
3133 rl_attempted_completion_over = 1;
3134 return rl_completion_matches(zText, readline_completion_generator);
3137 #elif HAVE_LINENOISE
3139 ** Linenoise completion callback
3141 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
3142 int nLine = strlen30(zLine);
3143 int i, iStart;
3144 sqlite3_stmt *pStmt = 0;
3145 char *zSql;
3146 char zBuf[1000];
3148 if( nLine>sizeof(zBuf)-30 ) return;
3149 if( zLine[0]=='.' ) return;
3150 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3151 if( i==nLine-1 ) return;
3152 iStart = i+1;
3153 memcpy(zBuf, zLine, iStart);
3154 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3155 " FROM completion(%Q,%Q) ORDER BY 1",
3156 &zLine[iStart], zLine);
3157 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3158 sqlite3_free(zSql);
3159 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3160 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3161 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3162 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3163 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3164 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3165 linenoiseAddCompletion(lc, zBuf);
3168 sqlite3_finalize(pStmt);
3170 #endif
3173 ** Do C-language style dequoting.
3175 ** \a -> alarm
3176 ** \b -> backspace
3177 ** \t -> tab
3178 ** \n -> newline
3179 ** \v -> vertical tab
3180 ** \f -> form feed
3181 ** \r -> carriage return
3182 ** \s -> space
3183 ** \" -> "
3184 ** \' -> '
3185 ** \\ -> backslash
3186 ** \NNN -> ascii character NNN in octal
3188 static void resolve_backslashes(char *z){
3189 int i, j;
3190 char c;
3191 while( *z && *z!='\\' ) z++;
3192 for(i=j=0; (c = z[i])!=0; i++, j++){
3193 if( c=='\\' && z[i+1]!=0 ){
3194 c = z[++i];
3195 if( c=='a' ){
3196 c = '\a';
3197 }else if( c=='b' ){
3198 c = '\b';
3199 }else if( c=='t' ){
3200 c = '\t';
3201 }else if( c=='n' ){
3202 c = '\n';
3203 }else if( c=='v' ){
3204 c = '\v';
3205 }else if( c=='f' ){
3206 c = '\f';
3207 }else if( c=='r' ){
3208 c = '\r';
3209 }else if( c=='"' ){
3210 c = '"';
3211 }else if( c=='\'' ){
3212 c = '\'';
3213 }else if( c=='\\' ){
3214 c = '\\';
3215 }else if( c>='0' && c<='7' ){
3216 c -= '0';
3217 if( z[i+1]>='0' && z[i+1]<='7' ){
3218 i++;
3219 c = (c<<3) + z[i] - '0';
3220 if( z[i+1]>='0' && z[i+1]<='7' ){
3221 i++;
3222 c = (c<<3) + z[i] - '0';
3227 z[j] = c;
3229 if( j<i ) z[j] = 0;
3233 ** Return the value of a hexadecimal digit. Return -1 if the input
3234 ** is not a hex digit.
3236 static int hexDigitValue(char c){
3237 if( c>='0' && c<='9' ) return c - '0';
3238 if( c>='a' && c<='f' ) return c - 'a' + 10;
3239 if( c>='A' && c<='F' ) return c - 'A' + 10;
3240 return -1;
3244 ** Interpret zArg as an integer value, possibly with suffixes.
3246 static sqlite3_int64 integerValue(const char *zArg){
3247 sqlite3_int64 v = 0;
3248 static const struct { char *zSuffix; int iMult; } aMult[] = {
3249 { "KiB", 1024 },
3250 { "MiB", 1024*1024 },
3251 { "GiB", 1024*1024*1024 },
3252 { "KB", 1000 },
3253 { "MB", 1000000 },
3254 { "GB", 1000000000 },
3255 { "K", 1000 },
3256 { "M", 1000000 },
3257 { "G", 1000000000 },
3259 int i;
3260 int isNeg = 0;
3261 if( zArg[0]=='-' ){
3262 isNeg = 1;
3263 zArg++;
3264 }else if( zArg[0]=='+' ){
3265 zArg++;
3267 if( zArg[0]=='0' && zArg[1]=='x' ){
3268 int x;
3269 zArg += 2;
3270 while( (x = hexDigitValue(zArg[0]))>=0 ){
3271 v = (v<<4) + x;
3272 zArg++;
3274 }else{
3275 while( IsDigit(zArg[0]) ){
3276 v = v*10 + zArg[0] - '0';
3277 zArg++;
3280 for(i=0; i<ArraySize(aMult); i++){
3281 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3282 v *= aMult[i].iMult;
3283 break;
3286 return isNeg? -v : v;
3290 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3291 ** for TRUE and FALSE. Return the integer value if appropriate.
3293 static int booleanValue(const char *zArg){
3294 int i;
3295 if( zArg[0]=='0' && zArg[1]=='x' ){
3296 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3297 }else{
3298 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3300 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3301 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3302 return 1;
3304 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3305 return 0;
3307 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3308 zArg);
3309 return 0;
3313 ** Set or clear a shell flag according to a boolean value.
3315 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3316 if( booleanValue(zArg) ){
3317 ShellSetFlag(p, mFlag);
3318 }else{
3319 ShellClearFlag(p, mFlag);
3324 ** Close an output file, assuming it is not stderr or stdout
3326 static void output_file_close(FILE *f){
3327 if( f && f!=stdout && f!=stderr ) fclose(f);
3331 ** Try to open an output file. The names "stdout" and "stderr" are
3332 ** recognized and do the right thing. NULL is returned if the output
3333 ** filename is "off".
3335 static FILE *output_file_open(const char *zFile){
3336 FILE *f;
3337 if( strcmp(zFile,"stdout")==0 ){
3338 f = stdout;
3339 }else if( strcmp(zFile, "stderr")==0 ){
3340 f = stderr;
3341 }else if( strcmp(zFile, "off")==0 ){
3342 f = 0;
3343 }else{
3344 f = fopen(zFile, "wb");
3345 if( f==0 ){
3346 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3349 return f;
3352 #if !defined(SQLITE_UNTESTABLE)
3353 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3355 ** A routine for handling output from sqlite3_trace().
3357 static int sql_trace_callback(
3358 unsigned mType,
3359 void *pArg,
3360 void *pP,
3361 void *pX
3363 FILE *f = (FILE*)pArg;
3364 UNUSED_PARAMETER(mType);
3365 UNUSED_PARAMETER(pP);
3366 if( f ){
3367 const char *z = (const char*)pX;
3368 int i = strlen30(z);
3369 while( i>0 && z[i-1]==';' ){ i--; }
3370 utf8_printf(f, "%.*s;\n", i, z);
3372 return 0;
3374 #endif
3375 #endif
3378 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3379 ** a useful spot to set a debugger breakpoint.
3381 static void test_breakpoint(void){
3382 static int nCall = 0;
3383 nCall++;
3387 ** An object used to read a CSV and other files for import.
3389 typedef struct ImportCtx ImportCtx;
3390 struct ImportCtx {
3391 const char *zFile; /* Name of the input file */
3392 FILE *in; /* Read the CSV text from this input stream */
3393 char *z; /* Accumulated text for a field */
3394 int n; /* Number of bytes in z */
3395 int nAlloc; /* Space allocated for z[] */
3396 int nLine; /* Current line number */
3397 int bNotFirst; /* True if one or more bytes already read */
3398 int cTerm; /* Character that terminated the most recent field */
3399 int cColSep; /* The column separator character. (Usually ",") */
3400 int cRowSep; /* The row separator character. (Usually "\n") */
3403 /* Append a single byte to z[] */
3404 static void import_append_char(ImportCtx *p, int c){
3405 if( p->n+1>=p->nAlloc ){
3406 p->nAlloc += p->nAlloc + 100;
3407 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3408 if( p->z==0 ){
3409 raw_printf(stderr, "out of memory\n");
3410 exit(1);
3413 p->z[p->n++] = (char)c;
3416 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3417 ** with the option of having a separator other than ",".
3419 ** + Input comes from p->in.
3420 ** + Store results in p->z of length p->n. Space to hold p->z comes
3421 ** from sqlite3_malloc64().
3422 ** + Use p->cSep as the column separator. The default is ",".
3423 ** + Use p->rSep as the row separator. The default is "\n".
3424 ** + Keep track of the line number in p->nLine.
3425 ** + Store the character that terminates the field in p->cTerm. Store
3426 ** EOF on end-of-file.
3427 ** + Report syntax errors on stderr
3429 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3430 int c;
3431 int cSep = p->cColSep;
3432 int rSep = p->cRowSep;
3433 p->n = 0;
3434 c = fgetc(p->in);
3435 if( c==EOF || seenInterrupt ){
3436 p->cTerm = EOF;
3437 return 0;
3439 if( c=='"' ){
3440 int pc, ppc;
3441 int startLine = p->nLine;
3442 int cQuote = c;
3443 pc = ppc = 0;
3444 while( 1 ){
3445 c = fgetc(p->in);
3446 if( c==rSep ) p->nLine++;
3447 if( c==cQuote ){
3448 if( pc==cQuote ){
3449 pc = 0;
3450 continue;
3453 if( (c==cSep && pc==cQuote)
3454 || (c==rSep && pc==cQuote)
3455 || (c==rSep && pc=='\r' && ppc==cQuote)
3456 || (c==EOF && pc==cQuote)
3458 do{ p->n--; }while( p->z[p->n]!=cQuote );
3459 p->cTerm = c;
3460 break;
3462 if( pc==cQuote && c!='\r' ){
3463 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3464 p->zFile, p->nLine, cQuote);
3466 if( c==EOF ){
3467 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3468 p->zFile, startLine, cQuote);
3469 p->cTerm = c;
3470 break;
3472 import_append_char(p, c);
3473 ppc = pc;
3474 pc = c;
3476 }else{
3477 /* If this is the first field being parsed and it begins with the
3478 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3479 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3480 import_append_char(p, c);
3481 c = fgetc(p->in);
3482 if( (c&0xff)==0xbb ){
3483 import_append_char(p, c);
3484 c = fgetc(p->in);
3485 if( (c&0xff)==0xbf ){
3486 p->bNotFirst = 1;
3487 p->n = 0;
3488 return csv_read_one_field(p);
3492 while( c!=EOF && c!=cSep && c!=rSep ){
3493 import_append_char(p, c);
3494 c = fgetc(p->in);
3496 if( c==rSep ){
3497 p->nLine++;
3498 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3500 p->cTerm = c;
3502 if( p->z ) p->z[p->n] = 0;
3503 p->bNotFirst = 1;
3504 return p->z;
3507 /* Read a single field of ASCII delimited text.
3509 ** + Input comes from p->in.
3510 ** + Store results in p->z of length p->n. Space to hold p->z comes
3511 ** from sqlite3_malloc64().
3512 ** + Use p->cSep as the column separator. The default is "\x1F".
3513 ** + Use p->rSep as the row separator. The default is "\x1E".
3514 ** + Keep track of the row number in p->nLine.
3515 ** + Store the character that terminates the field in p->cTerm. Store
3516 ** EOF on end-of-file.
3517 ** + Report syntax errors on stderr
3519 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3520 int c;
3521 int cSep = p->cColSep;
3522 int rSep = p->cRowSep;
3523 p->n = 0;
3524 c = fgetc(p->in);
3525 if( c==EOF || seenInterrupt ){
3526 p->cTerm = EOF;
3527 return 0;
3529 while( c!=EOF && c!=cSep && c!=rSep ){
3530 import_append_char(p, c);
3531 c = fgetc(p->in);
3533 if( c==rSep ){
3534 p->nLine++;
3536 p->cTerm = c;
3537 if( p->z ) p->z[p->n] = 0;
3538 return p->z;
3542 ** Try to transfer data for table zTable. If an error is seen while
3543 ** moving forward, try to go backwards. The backwards movement won't
3544 ** work for WITHOUT ROWID tables.
3546 static void tryToCloneData(
3547 ShellState *p,
3548 sqlite3 *newDb,
3549 const char *zTable
3551 sqlite3_stmt *pQuery = 0;
3552 sqlite3_stmt *pInsert = 0;
3553 char *zQuery = 0;
3554 char *zInsert = 0;
3555 int rc;
3556 int i, j, n;
3557 int nTable = strlen30(zTable);
3558 int k = 0;
3559 int cnt = 0;
3560 const int spinRate = 10000;
3562 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3563 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3564 if( rc ){
3565 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3566 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3567 zQuery);
3568 goto end_data_xfer;
3570 n = sqlite3_column_count(pQuery);
3571 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3572 if( zInsert==0 ){
3573 raw_printf(stderr, "out of memory\n");
3574 goto end_data_xfer;
3576 sqlite3_snprintf(200+nTable,zInsert,
3577 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3578 i = strlen30(zInsert);
3579 for(j=1; j<n; j++){
3580 memcpy(zInsert+i, ",?", 2);
3581 i += 2;
3583 memcpy(zInsert+i, ");", 3);
3584 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3585 if( rc ){
3586 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3587 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3588 zQuery);
3589 goto end_data_xfer;
3591 for(k=0; k<2; k++){
3592 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3593 for(i=0; i<n; i++){
3594 switch( sqlite3_column_type(pQuery, i) ){
3595 case SQLITE_NULL: {
3596 sqlite3_bind_null(pInsert, i+1);
3597 break;
3599 case SQLITE_INTEGER: {
3600 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3601 break;
3603 case SQLITE_FLOAT: {
3604 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3605 break;
3607 case SQLITE_TEXT: {
3608 sqlite3_bind_text(pInsert, i+1,
3609 (const char*)sqlite3_column_text(pQuery,i),
3610 -1, SQLITE_STATIC);
3611 break;
3613 case SQLITE_BLOB: {
3614 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3615 sqlite3_column_bytes(pQuery,i),
3616 SQLITE_STATIC);
3617 break;
3620 } /* End for */
3621 rc = sqlite3_step(pInsert);
3622 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3623 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3624 sqlite3_errmsg(newDb));
3626 sqlite3_reset(pInsert);
3627 cnt++;
3628 if( (cnt%spinRate)==0 ){
3629 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3630 fflush(stdout);
3632 } /* End while */
3633 if( rc==SQLITE_DONE ) break;
3634 sqlite3_finalize(pQuery);
3635 sqlite3_free(zQuery);
3636 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3637 zTable);
3638 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3639 if( rc ){
3640 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3641 break;
3643 } /* End for(k=0...) */
3645 end_data_xfer:
3646 sqlite3_finalize(pQuery);
3647 sqlite3_finalize(pInsert);
3648 sqlite3_free(zQuery);
3649 sqlite3_free(zInsert);
3654 ** Try to transfer all rows of the schema that match zWhere. For
3655 ** each row, invoke xForEach() on the object defined by that row.
3656 ** If an error is encountered while moving forward through the
3657 ** sqlite_master table, try again moving backwards.
3659 static void tryToCloneSchema(
3660 ShellState *p,
3661 sqlite3 *newDb,
3662 const char *zWhere,
3663 void (*xForEach)(ShellState*,sqlite3*,const char*)
3665 sqlite3_stmt *pQuery = 0;
3666 char *zQuery = 0;
3667 int rc;
3668 const unsigned char *zName;
3669 const unsigned char *zSql;
3670 char *zErrMsg = 0;
3672 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3673 " WHERE %s", zWhere);
3674 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3675 if( rc ){
3676 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3677 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3678 zQuery);
3679 goto end_schema_xfer;
3681 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3682 zName = sqlite3_column_text(pQuery, 0);
3683 zSql = sqlite3_column_text(pQuery, 1);
3684 printf("%s... ", zName); fflush(stdout);
3685 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3686 if( zErrMsg ){
3687 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3688 sqlite3_free(zErrMsg);
3689 zErrMsg = 0;
3691 if( xForEach ){
3692 xForEach(p, newDb, (const char*)zName);
3694 printf("done\n");
3696 if( rc!=SQLITE_DONE ){
3697 sqlite3_finalize(pQuery);
3698 sqlite3_free(zQuery);
3699 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3700 " WHERE %s ORDER BY rowid DESC", zWhere);
3701 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3702 if( rc ){
3703 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3704 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3705 zQuery);
3706 goto end_schema_xfer;
3708 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3709 zName = sqlite3_column_text(pQuery, 0);
3710 zSql = sqlite3_column_text(pQuery, 1);
3711 printf("%s... ", zName); fflush(stdout);
3712 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3713 if( zErrMsg ){
3714 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3715 sqlite3_free(zErrMsg);
3716 zErrMsg = 0;
3718 if( xForEach ){
3719 xForEach(p, newDb, (const char*)zName);
3721 printf("done\n");
3724 end_schema_xfer:
3725 sqlite3_finalize(pQuery);
3726 sqlite3_free(zQuery);
3730 ** Open a new database file named "zNewDb". Try to recover as much information
3731 ** as possible out of the main database (which might be corrupt) and write it
3732 ** into zNewDb.
3734 static void tryToClone(ShellState *p, const char *zNewDb){
3735 int rc;
3736 sqlite3 *newDb = 0;
3737 if( access(zNewDb,0)==0 ){
3738 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3739 return;
3741 rc = sqlite3_open(zNewDb, &newDb);
3742 if( rc ){
3743 utf8_printf(stderr, "Cannot create output database: %s\n",
3744 sqlite3_errmsg(newDb));
3745 }else{
3746 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3747 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3748 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3749 tryToCloneSchema(p, newDb, "type!='table'", 0);
3750 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3751 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3753 sqlite3_close(newDb);
3757 ** Change the output file back to stdout
3759 static void output_reset(ShellState *p){
3760 if( p->outfile[0]=='|' ){
3761 #ifndef SQLITE_OMIT_POPEN
3762 pclose(p->out);
3763 #endif
3764 }else{
3765 output_file_close(p->out);
3767 p->outfile[0] = 0;
3768 p->out = stdout;
3772 ** Run an SQL command and return the single integer result.
3774 static int db_int(ShellState *p, const char *zSql){
3775 sqlite3_stmt *pStmt;
3776 int res = 0;
3777 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3778 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3779 res = sqlite3_column_int(pStmt,0);
3781 sqlite3_finalize(pStmt);
3782 return res;
3786 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3788 static unsigned int get2byteInt(unsigned char *a){
3789 return (a[0]<<8) + a[1];
3791 static unsigned int get4byteInt(unsigned char *a){
3792 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3796 ** Implementation of the ".info" command.
3798 ** Return 1 on error, 2 to exit, and 0 otherwise.
3800 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3801 static const struct { const char *zName; int ofst; } aField[] = {
3802 { "file change counter:", 24 },
3803 { "database page count:", 28 },
3804 { "freelist page count:", 36 },
3805 { "schema cookie:", 40 },
3806 { "schema format:", 44 },
3807 { "default cache size:", 48 },
3808 { "autovacuum top root:", 52 },
3809 { "incremental vacuum:", 64 },
3810 { "text encoding:", 56 },
3811 { "user version:", 60 },
3812 { "application id:", 68 },
3813 { "software version:", 96 },
3815 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3816 { "number of tables:",
3817 "SELECT count(*) FROM %s WHERE type='table'" },
3818 { "number of indexes:",
3819 "SELECT count(*) FROM %s WHERE type='index'" },
3820 { "number of triggers:",
3821 "SELECT count(*) FROM %s WHERE type='trigger'" },
3822 { "number of views:",
3823 "SELECT count(*) FROM %s WHERE type='view'" },
3824 { "schema size:",
3825 "SELECT total(length(sql)) FROM %s" },
3827 int i;
3828 char *zSchemaTab;
3829 char *zDb = nArg>=2 ? azArg[1] : "main";
3830 sqlite3_stmt *pStmt = 0;
3831 unsigned char aHdr[100];
3832 open_db(p, 0);
3833 if( p->db==0 ) return 1;
3834 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
3835 -1, &pStmt, 0);
3836 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
3837 if( sqlite3_step(pStmt)==SQLITE_ROW
3838 && sqlite3_column_bytes(pStmt,0)>100
3840 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
3841 sqlite3_finalize(pStmt);
3842 }else{
3843 raw_printf(stderr, "unable to read database header\n");
3844 sqlite3_finalize(pStmt);
3845 return 1;
3847 i = get2byteInt(aHdr+16);
3848 if( i==1 ) i = 65536;
3849 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3850 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3851 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3852 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3853 for(i=0; i<ArraySize(aField); i++){
3854 int ofst = aField[i].ofst;
3855 unsigned int val = get4byteInt(aHdr + ofst);
3856 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3857 switch( ofst ){
3858 case 56: {
3859 if( val==1 ) raw_printf(p->out, " (utf8)");
3860 if( val==2 ) raw_printf(p->out, " (utf16le)");
3861 if( val==3 ) raw_printf(p->out, " (utf16be)");
3864 raw_printf(p->out, "\n");
3866 if( zDb==0 ){
3867 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3868 }else if( strcmp(zDb,"temp")==0 ){
3869 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3870 }else{
3871 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3873 for(i=0; i<ArraySize(aQuery); i++){
3874 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3875 int val = db_int(p, zSql);
3876 sqlite3_free(zSql);
3877 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3879 sqlite3_free(zSchemaTab);
3880 return 0;
3884 ** Print the current sqlite3_errmsg() value to stderr and return 1.
3886 static int shellDatabaseError(sqlite3 *db){
3887 const char *zErr = sqlite3_errmsg(db);
3888 utf8_printf(stderr, "Error: %s\n", zErr);
3889 return 1;
3893 ** Print an out-of-memory message to stderr and return 1.
3895 static int shellNomemError(void){
3896 raw_printf(stderr, "Error: out of memory\n");
3897 return 1;
3901 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3902 ** if they match and FALSE (0) if they do not match.
3904 ** Globbing rules:
3906 ** '*' Matches any sequence of zero or more characters.
3908 ** '?' Matches exactly one character.
3910 ** [...] Matches one character from the enclosed list of
3911 ** characters.
3913 ** [^...] Matches one character not in the enclosed list.
3915 ** '#' Matches any sequence of one or more digits with an
3916 ** optional + or - sign in front
3918 ** ' ' Any span of whitespace matches any other span of
3919 ** whitespace.
3921 ** Extra whitespace at the end of z[] is ignored.
3923 static int testcase_glob(const char *zGlob, const char *z){
3924 int c, c2;
3925 int invert;
3926 int seen;
3928 while( (c = (*(zGlob++)))!=0 ){
3929 if( IsSpace(c) ){
3930 if( !IsSpace(*z) ) return 0;
3931 while( IsSpace(*zGlob) ) zGlob++;
3932 while( IsSpace(*z) ) z++;
3933 }else if( c=='*' ){
3934 while( (c=(*(zGlob++))) == '*' || c=='?' ){
3935 if( c=='?' && (*(z++))==0 ) return 0;
3937 if( c==0 ){
3938 return 1;
3939 }else if( c=='[' ){
3940 while( *z && testcase_glob(zGlob-1,z)==0 ){
3941 z++;
3943 return (*z)!=0;
3945 while( (c2 = (*(z++)))!=0 ){
3946 while( c2!=c ){
3947 c2 = *(z++);
3948 if( c2==0 ) return 0;
3950 if( testcase_glob(zGlob,z) ) return 1;
3952 return 0;
3953 }else if( c=='?' ){
3954 if( (*(z++))==0 ) return 0;
3955 }else if( c=='[' ){
3956 int prior_c = 0;
3957 seen = 0;
3958 invert = 0;
3959 c = *(z++);
3960 if( c==0 ) return 0;
3961 c2 = *(zGlob++);
3962 if( c2=='^' ){
3963 invert = 1;
3964 c2 = *(zGlob++);
3966 if( c2==']' ){
3967 if( c==']' ) seen = 1;
3968 c2 = *(zGlob++);
3970 while( c2 && c2!=']' ){
3971 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3972 c2 = *(zGlob++);
3973 if( c>=prior_c && c<=c2 ) seen = 1;
3974 prior_c = 0;
3975 }else{
3976 if( c==c2 ){
3977 seen = 1;
3979 prior_c = c2;
3981 c2 = *(zGlob++);
3983 if( c2==0 || (seen ^ invert)==0 ) return 0;
3984 }else if( c=='#' ){
3985 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
3986 if( !IsDigit(z[0]) ) return 0;
3987 z++;
3988 while( IsDigit(z[0]) ){ z++; }
3989 }else{
3990 if( c!=(*(z++)) ) return 0;
3993 while( IsSpace(*z) ){ z++; }
3994 return *z==0;
3999 ** Compare the string as a command-line option with either one or two
4000 ** initial "-" characters.
4002 static int optionMatch(const char *zStr, const char *zOpt){
4003 if( zStr[0]!='-' ) return 0;
4004 zStr++;
4005 if( zStr[0]=='-' ) zStr++;
4006 return strcmp(zStr, zOpt)==0;
4010 ** Delete a file.
4012 int shellDeleteFile(const char *zFilename){
4013 int rc;
4014 #ifdef _WIN32
4015 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4016 rc = _wunlink(z);
4017 sqlite3_free(z);
4018 #else
4019 rc = unlink(zFilename);
4020 #endif
4021 return rc;
4026 ** The implementation of SQL scalar function fkey_collate_clause(), used
4027 ** by the ".lint fkey-indexes" command. This scalar function is always
4028 ** called with four arguments - the parent table name, the parent column name,
4029 ** the child table name and the child column name.
4031 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4033 ** If either of the named tables or columns do not exist, this function
4034 ** returns an empty string. An empty string is also returned if both tables
4035 ** and columns exist but have the same default collation sequence. Or,
4036 ** if both exist but the default collation sequences are different, this
4037 ** function returns the string " COLLATE <parent-collation>", where
4038 ** <parent-collation> is the default collation sequence of the parent column.
4040 static void shellFkeyCollateClause(
4041 sqlite3_context *pCtx,
4042 int nVal,
4043 sqlite3_value **apVal
4045 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4046 const char *zParent;
4047 const char *zParentCol;
4048 const char *zParentSeq;
4049 const char *zChild;
4050 const char *zChildCol;
4051 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4052 int rc;
4054 assert( nVal==4 );
4055 zParent = (const char*)sqlite3_value_text(apVal[0]);
4056 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4057 zChild = (const char*)sqlite3_value_text(apVal[2]);
4058 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4060 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4061 rc = sqlite3_table_column_metadata(
4062 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4064 if( rc==SQLITE_OK ){
4065 rc = sqlite3_table_column_metadata(
4066 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4070 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4071 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4072 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4073 sqlite3_free(z);
4079 ** The implementation of dot-command ".lint fkey-indexes".
4081 static int lintFkeyIndexes(
4082 ShellState *pState, /* Current shell tool state */
4083 char **azArg, /* Array of arguments passed to dot command */
4084 int nArg /* Number of entries in azArg[] */
4086 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4087 FILE *out = pState->out; /* Stream to write non-error output to */
4088 int bVerbose = 0; /* If -verbose is present */
4089 int bGroupByParent = 0; /* If -groupbyparent is present */
4090 int i; /* To iterate through azArg[] */
4091 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4092 int rc; /* Return code */
4093 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4096 ** This SELECT statement returns one row for each foreign key constraint
4097 ** in the schema of the main database. The column values are:
4099 ** 0. The text of an SQL statement similar to:
4101 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4103 ** This SELECT is similar to the one that the foreign keys implementation
4104 ** needs to run internally on child tables. If there is an index that can
4105 ** be used to optimize this query, then it can also be used by the FK
4106 ** implementation to optimize DELETE or UPDATE statements on the parent
4107 ** table.
4109 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4110 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4111 ** contains an index that can be used to optimize the query.
4113 ** 2. Human readable text that describes the child table and columns. e.g.
4115 ** "child_table(child_key1, child_key2)"
4117 ** 3. Human readable text that describes the parent table and columns. e.g.
4119 ** "parent_table(parent_key1, parent_key2)"
4121 ** 4. A full CREATE INDEX statement for an index that could be used to
4122 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4124 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4126 ** 5. The name of the parent table.
4128 ** These six values are used by the C logic below to generate the report.
4130 const char *zSql =
4131 "SELECT "
4132 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4133 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4134 " || fkey_collate_clause("
4135 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4136 ", "
4137 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4138 " || group_concat('*=?', ' AND ') || ')'"
4139 ", "
4140 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4141 ", "
4142 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4143 ", "
4144 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4145 " || ' ON ' || quote(s.name) || '('"
4146 " || group_concat(quote(f.[from]) ||"
4147 " fkey_collate_clause("
4148 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4149 " || ');'"
4150 ", "
4151 " f.[table] "
4152 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4153 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4154 "GROUP BY s.name, f.id "
4155 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4157 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4159 for(i=2; i<nArg; i++){
4160 int n = strlen30(azArg[i]);
4161 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4162 bVerbose = 1;
4164 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4165 bGroupByParent = 1;
4166 zIndent = " ";
4168 else{
4169 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4170 azArg[0], azArg[1]
4172 return SQLITE_ERROR;
4176 /* Register the fkey_collate_clause() SQL function */
4177 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4178 0, shellFkeyCollateClause, 0, 0
4182 if( rc==SQLITE_OK ){
4183 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4185 if( rc==SQLITE_OK ){
4186 sqlite3_bind_int(pSql, 1, bGroupByParent);
4189 if( rc==SQLITE_OK ){
4190 int rc2;
4191 char *zPrev = 0;
4192 while( SQLITE_ROW==sqlite3_step(pSql) ){
4193 int res = -1;
4194 sqlite3_stmt *pExplain = 0;
4195 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4196 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4197 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4198 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4199 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4200 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4202 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4203 if( rc!=SQLITE_OK ) break;
4204 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4205 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4206 res = (
4207 0==sqlite3_strglob(zGlob, zPlan)
4208 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4211 rc = sqlite3_finalize(pExplain);
4212 if( rc!=SQLITE_OK ) break;
4214 if( res<0 ){
4215 raw_printf(stderr, "Error: internal error");
4216 break;
4217 }else{
4218 if( bGroupByParent
4219 && (bVerbose || res==0)
4220 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4222 raw_printf(out, "-- Parent table %s\n", zParent);
4223 sqlite3_free(zPrev);
4224 zPrev = sqlite3_mprintf("%s", zParent);
4227 if( res==0 ){
4228 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4229 }else if( bVerbose ){
4230 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4231 zIndent, zFrom, zTarget
4236 sqlite3_free(zPrev);
4238 if( rc!=SQLITE_OK ){
4239 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4242 rc2 = sqlite3_finalize(pSql);
4243 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4244 rc = rc2;
4245 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4247 }else{
4248 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4251 return rc;
4255 ** Implementation of ".lint" dot command.
4257 static int lintDotCommand(
4258 ShellState *pState, /* Current shell tool state */
4259 char **azArg, /* Array of arguments passed to dot command */
4260 int nArg /* Number of entries in azArg[] */
4262 int n;
4263 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
4264 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4265 return lintFkeyIndexes(pState, azArg, nArg);
4267 usage:
4268 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4269 raw_printf(stderr, "Where sub-commands are:\n");
4270 raw_printf(stderr, " fkey-indexes\n");
4271 return SQLITE_ERROR;
4274 static void shellPrepare(
4275 sqlite3 *db,
4276 int *pRc,
4277 const char *zSql,
4278 sqlite3_stmt **ppStmt
4280 *ppStmt = 0;
4281 if( *pRc==SQLITE_OK ){
4282 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
4283 if( rc!=SQLITE_OK ){
4284 raw_printf(stderr, "sql error: %s (%d)\n",
4285 sqlite3_errmsg(db), sqlite3_errcode(db)
4287 *pRc = rc;
4292 static void shellPreparePrintf(
4293 sqlite3 *db,
4294 int *pRc,
4295 sqlite3_stmt **ppStmt,
4296 const char *zFmt,
4299 *ppStmt = 0;
4300 if( *pRc==SQLITE_OK ){
4301 va_list ap;
4302 char *z;
4303 va_start(ap, zFmt);
4304 z = sqlite3_vmprintf(zFmt, ap);
4305 if( z==0 ){
4306 *pRc = SQLITE_NOMEM;
4307 }else{
4308 shellPrepare(db, pRc, z, ppStmt);
4309 sqlite3_free(z);
4314 static void shellFinalize(
4315 int *pRc,
4316 sqlite3_stmt *pStmt
4318 if( pStmt ){
4319 sqlite3 *db = sqlite3_db_handle(pStmt);
4320 int rc = sqlite3_finalize(pStmt);
4321 if( *pRc==SQLITE_OK ){
4322 if( rc!=SQLITE_OK ){
4323 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4325 *pRc = rc;
4330 static void shellReset(
4331 int *pRc,
4332 sqlite3_stmt *pStmt
4334 int rc = sqlite3_reset(pStmt);
4335 if( *pRc==SQLITE_OK ){
4336 if( rc!=SQLITE_OK ){
4337 sqlite3 *db = sqlite3_db_handle(pStmt);
4338 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4340 *pRc = rc;
4345 ** Structure representing a single ".ar" command.
4347 typedef struct ArCommand ArCommand;
4348 struct ArCommand {
4349 int eCmd; /* An AR_CMD_* value */
4350 const char *zFile; /* --file argument, or NULL */
4351 const char *zDir; /* --directory argument, or NULL */
4352 int bVerbose; /* True if --verbose */
4353 int bZip; /* True if --zip */
4354 int nArg; /* Number of command arguments */
4355 char **azArg; /* Array of command arguments */
4359 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4361 static int arUsage(FILE *f){
4362 raw_printf(f,
4363 "\n"
4364 "Usage: .ar [OPTION...] [FILE...]\n"
4365 "The .ar command manages sqlar archives.\n"
4366 "\n"
4367 "Examples:\n"
4368 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4369 " .ar -tf archive.sar # List members of archive.sar\n"
4370 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4371 "\n"
4372 "Each command line must feature exactly one command option:\n"
4373 " -c, --create Create a new archive\n"
4374 " -u, --update Update or add files to an existing archive\n"
4375 " -t, --list List contents of archive\n"
4376 " -x, --extract Extract files from archive\n"
4377 "\n"
4378 "And zero or more optional options:\n"
4379 " -v, --verbose Print each filename as it is processed\n"
4380 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4381 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4382 "\n"
4383 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4384 "\n"
4386 return SQLITE_ERROR;
4390 ** Print an error message for the .ar command to stderr and return
4391 ** SQLITE_ERROR.
4393 static int arErrorMsg(const char *zFmt, ...){
4394 va_list ap;
4395 char *z;
4396 va_start(ap, zFmt);
4397 z = sqlite3_vmprintf(zFmt, ap);
4398 va_end(ap);
4399 raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
4400 sqlite3_free(z);
4401 return SQLITE_ERROR;
4405 ** Values for ArCommand.eCmd.
4407 #define AR_CMD_CREATE 1
4408 #define AR_CMD_EXTRACT 2
4409 #define AR_CMD_LIST 3
4410 #define AR_CMD_UPDATE 4
4411 #define AR_CMD_HELP 5
4414 ** Other (non-command) switches.
4416 #define AR_SWITCH_VERBOSE 6
4417 #define AR_SWITCH_FILE 7
4418 #define AR_SWITCH_DIRECTORY 8
4419 #define AR_SWITCH_ZIP 9
4421 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4422 switch( eSwitch ){
4423 case AR_CMD_CREATE:
4424 case AR_CMD_EXTRACT:
4425 case AR_CMD_LIST:
4426 case AR_CMD_UPDATE:
4427 case AR_CMD_HELP:
4428 if( pAr->eCmd ){
4429 return arErrorMsg("multiple command options");
4431 pAr->eCmd = eSwitch;
4432 break;
4434 case AR_SWITCH_VERBOSE:
4435 pAr->bVerbose = 1;
4436 break;
4437 case AR_SWITCH_ZIP:
4438 pAr->bZip = 1;
4439 break;
4441 case AR_SWITCH_FILE:
4442 pAr->zFile = zArg;
4443 break;
4444 case AR_SWITCH_DIRECTORY:
4445 pAr->zDir = zArg;
4446 break;
4449 return SQLITE_OK;
4453 ** Parse the command line for an ".ar" command. The results are written into
4454 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4455 ** successfully, otherwise an error message is written to stderr and
4456 ** SQLITE_ERROR returned.
4458 static int arParseCommand(
4459 char **azArg, /* Array of arguments passed to dot command */
4460 int nArg, /* Number of entries in azArg[] */
4461 ArCommand *pAr /* Populate this object */
4463 struct ArSwitch {
4464 char cShort;
4465 const char *zLong;
4466 int eSwitch;
4467 int bArg;
4468 } aSwitch[] = {
4469 { 'c', "create", AR_CMD_CREATE, 0 },
4470 { 'x', "extract", AR_CMD_EXTRACT, 0 },
4471 { 't', "list", AR_CMD_LIST, 0 },
4472 { 'u', "update", AR_CMD_UPDATE, 0 },
4473 { 'h', "help", AR_CMD_HELP, 0 },
4474 { 'v', "verbose", AR_SWITCH_VERBOSE, 0 },
4475 { 'f', "file", AR_SWITCH_FILE, 1 },
4476 { 'C', "directory", AR_SWITCH_DIRECTORY, 1 },
4477 { 'z', "zip", AR_SWITCH_ZIP, 0 }
4479 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
4480 struct ArSwitch *pEnd = &aSwitch[nSwitch];
4482 if( nArg<=1 ){
4483 return arUsage(stderr);
4484 }else{
4485 char *z = azArg[1];
4486 memset(pAr, 0, sizeof(ArCommand));
4488 if( z[0]!='-' ){
4489 /* Traditional style [tar] invocation */
4490 int i;
4491 int iArg = 2;
4492 for(i=0; z[i]; i++){
4493 const char *zArg = 0;
4494 struct ArSwitch *pOpt;
4495 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4496 if( z[i]==pOpt->cShort ) break;
4498 if( pOpt==pEnd ){
4499 return arErrorMsg("unrecognized option: %c", z[i]);
4501 if( pOpt->bArg ){
4502 if( iArg>=nArg ){
4503 return arErrorMsg("option requires an argument: %c",z[i]);
4505 zArg = azArg[iArg++];
4507 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4509 pAr->nArg = nArg-iArg;
4510 if( pAr->nArg>0 ){
4511 pAr->azArg = &azArg[iArg];
4513 }else{
4514 /* Non-traditional invocation */
4515 int iArg;
4516 for(iArg=1; iArg<nArg; iArg++){
4517 int n;
4518 z = azArg[iArg];
4519 if( z[0]!='-' ){
4520 /* All remaining command line words are command arguments. */
4521 pAr->azArg = &azArg[iArg];
4522 pAr->nArg = nArg-iArg;
4523 break;
4525 n = strlen30(z);
4527 if( z[1]!='-' ){
4528 int i;
4529 /* One or more short options */
4530 for(i=1; i<n; i++){
4531 const char *zArg = 0;
4532 struct ArSwitch *pOpt;
4533 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4534 if( z[i]==pOpt->cShort ) break;
4536 if( pOpt==pEnd ){
4537 return arErrorMsg("unrecognized option: %c\n", z[i]);
4539 if( pOpt->bArg ){
4540 if( i<(n-1) ){
4541 zArg = &z[i+1];
4542 i = n;
4543 }else{
4544 if( iArg>=(nArg-1) ){
4545 return arErrorMsg("option requires an argument: %c\n",z[i]);
4547 zArg = azArg[++iArg];
4550 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4552 }else if( z[2]=='\0' ){
4553 /* A -- option, indicating that all remaining command line words
4554 ** are command arguments. */
4555 pAr->azArg = &azArg[iArg+1];
4556 pAr->nArg = nArg-iArg-1;
4557 break;
4558 }else{
4559 /* A long option */
4560 const char *zArg = 0; /* Argument for option, if any */
4561 struct ArSwitch *pMatch = 0; /* Matching option */
4562 struct ArSwitch *pOpt; /* Iterator */
4563 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4564 const char *zLong = pOpt->zLong;
4565 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
4566 if( pMatch ){
4567 return arErrorMsg("ambiguous option: %s",z);
4568 }else{
4569 pMatch = pOpt;
4574 if( pMatch==0 ){
4575 return arErrorMsg("unrecognized option: %s", z);
4577 if( pMatch->bArg ){
4578 if( iArg>=(nArg-1) ){
4579 return arErrorMsg("option requires an argument: %s", z);
4581 zArg = azArg[++iArg];
4583 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
4589 return SQLITE_OK;
4593 ** This function assumes that all arguments within the ArCommand.azArg[]
4594 ** array refer to archive members, as for the --extract or --list commands.
4595 ** It checks that each of them are present. If any specified file is not
4596 ** present in the archive, an error is printed to stderr and an error
4597 ** code returned. Otherwise, if all specified arguments are present in
4598 ** the archive, SQLITE_OK is returned.
4600 ** This function strips any trailing '/' characters from each argument.
4601 ** This is consistent with the way the [tar] command seems to work on
4602 ** Linux.
4604 static int arCheckEntries(sqlite3 *db, ArCommand *pAr){
4605 int rc = SQLITE_OK;
4606 if( pAr->nArg ){
4607 int i;
4608 sqlite3_stmt *pTest = 0;
4610 shellPreparePrintf(db, &rc, &pTest, "SELECT name FROM %s WHERE name=?1",
4611 pAr->bZip ? "zipfile(?2)" : "sqlar"
4613 if( rc==SQLITE_OK && pAr->bZip ){
4614 sqlite3_bind_text(pTest, 2, pAr->zFile, -1, SQLITE_TRANSIENT);
4616 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4617 char *z = pAr->azArg[i];
4618 int n = strlen30(z);
4619 int bOk = 0;
4620 while( n>0 && z[n-1]=='/' ) n--;
4621 z[n] = '\0';
4622 sqlite3_bind_text(pTest, 1, z, -1, SQLITE_STATIC);
4623 if( SQLITE_ROW==sqlite3_step(pTest) ){
4624 bOk = 1;
4626 shellReset(&rc, pTest);
4627 if( rc==SQLITE_OK && bOk==0 ){
4628 raw_printf(stderr, "not found in archive: %s\n", z);
4629 rc = SQLITE_ERROR;
4632 shellFinalize(&rc, pTest);
4635 return rc;
4639 ** Format a WHERE clause that can be used against the "sqlar" table to
4640 ** identify all archive members that match the command arguments held
4641 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
4642 ** The caller is responsible for eventually calling sqlite3_free() on
4643 ** any non-NULL (*pzWhere) value.
4645 static void arWhereClause(
4646 int *pRc,
4647 ArCommand *pAr,
4648 char **pzWhere /* OUT: New WHERE clause */
4650 char *zWhere = 0;
4651 if( *pRc==SQLITE_OK ){
4652 if( pAr->nArg==0 ){
4653 zWhere = sqlite3_mprintf("1");
4654 }else{
4655 int i;
4656 const char *zSep = "";
4657 for(i=0; i<pAr->nArg; i++){
4658 const char *z = pAr->azArg[i];
4659 zWhere = sqlite3_mprintf(
4660 "%z%s name = '%q' OR name BETWEEN '%q/' AND '%q0'",
4661 zWhere, zSep, z, z, z
4663 if( zWhere==0 ){
4664 *pRc = SQLITE_NOMEM;
4665 break;
4667 zSep = " OR ";
4671 *pzWhere = zWhere;
4675 ** Argument zMode must point to a buffer at least 11 bytes in size. This
4676 ** function populates this buffer with the string interpretation of
4677 ** the unix file mode passed as the second argument (e.g. "drwxr-xr-x").
4679 static void shellModeToString(char *zMode, int mode){
4680 int i;
4682 /* Magic numbers copied from [man 2 stat] */
4683 if( mode & 0040000 ){
4684 zMode[0] = 'd';
4685 }else if( (mode & 0120000)==0120000 ){
4686 zMode[0] = 'l';
4687 }else{
4688 zMode[0] = '-';
4691 for(i=0; i<3; i++){
4692 int m = (mode >> ((2-i)*3));
4693 char *a = &zMode[1 + i*3];
4694 a[0] = (m & 0x4) ? 'r' : '-';
4695 a[1] = (m & 0x2) ? 'w' : '-';
4696 a[2] = (m & 0x1) ? 'x' : '-';
4698 zMode[10] = '\0';
4702 ** Implementation of .ar "lisT" command.
4704 static int arListCommand(ShellState *p, sqlite3 *db, ArCommand *pAr){
4705 const char *zSql = "SELECT %s FROM %s WHERE %s";
4706 const char *zTbl = (pAr->bZip ? "zipfile(?)" : "sqlar");
4707 const char *azCols[] = {
4708 "name",
4709 "mode, sz, datetime(mtime, 'unixepoch'), name"
4712 char *zWhere = 0;
4713 sqlite3_stmt *pSql = 0;
4714 int rc;
4716 rc = arCheckEntries(db, pAr);
4717 arWhereClause(&rc, pAr, &zWhere);
4719 shellPreparePrintf(db, &rc, &pSql, zSql, azCols[pAr->bVerbose], zTbl, zWhere);
4720 if( rc==SQLITE_OK && pAr->bZip ){
4721 sqlite3_bind_text(pSql, 1, pAr->zFile, -1, SQLITE_TRANSIENT);
4723 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4724 if( pAr->bVerbose ){
4725 char zMode[11];
4726 shellModeToString(zMode, sqlite3_column_int(pSql, 0));
4728 raw_printf(p->out, "%s % 10d %s %s\n", zMode,
4729 sqlite3_column_int(pSql, 1),
4730 sqlite3_column_text(pSql, 2),
4731 sqlite3_column_text(pSql, 3)
4733 }else{
4734 raw_printf(p->out, "%s\n", sqlite3_column_text(pSql, 0));
4738 shellFinalize(&rc, pSql);
4739 return rc;
4744 ** Implementation of .ar "eXtract" command.
4746 static int arExtractCommand(ShellState *p, sqlite3 *db, ArCommand *pAr){
4747 const char *zSql1 =
4748 "SELECT "
4749 " :1 || name, "
4750 " writefile(?1 || name, %s, mode, mtime) "
4751 "FROM %s WHERE (%s) AND (data IS NULL OR ?2 = 0)";
4753 const char *azExtraArg[] = {
4754 "sqlar_uncompress(data, sz)",
4755 "zipfile_uncompress(data, sz, method)"
4757 const char *azSource[] = {
4758 "sqlar", "zipfile(?3)"
4763 sqlite3_stmt *pSql = 0;
4764 int rc = SQLITE_OK;
4765 char *zDir = 0;
4766 char *zWhere = 0;
4767 int i;
4769 /* If arguments are specified, check that they actually exist within
4770 ** the archive before proceeding. And formulate a WHERE clause to
4771 ** match them. */
4772 rc = arCheckEntries(db, pAr);
4773 arWhereClause(&rc, pAr, &zWhere);
4775 if( rc==SQLITE_OK ){
4776 if( pAr->zDir ){
4777 zDir = sqlite3_mprintf("%s/", pAr->zDir);
4778 }else{
4779 zDir = sqlite3_mprintf("");
4781 if( zDir==0 ) rc = SQLITE_NOMEM;
4784 shellPreparePrintf(db, &rc, &pSql, zSql1,
4785 azExtraArg[pAr->bZip], azSource[pAr->bZip], zWhere
4788 if( rc==SQLITE_OK ){
4789 sqlite3_bind_text(pSql, 1, zDir, -1, SQLITE_STATIC);
4790 if( pAr->bZip ){
4791 sqlite3_bind_text(pSql, 3, pAr->zFile, -1, SQLITE_STATIC);
4794 /* Run the SELECT statement twice. The first time, writefile() is called
4795 ** for all archive members that should be extracted. The second time,
4796 ** only for the directories. This is because the timestamps for
4797 ** extracted directories must be reset after they are populated (as
4798 ** populating them changes the timestamp). */
4799 for(i=0; i<2; i++){
4800 sqlite3_bind_int(pSql, 2, i);
4801 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4802 if( i==0 && pAr->bVerbose ){
4803 raw_printf(p->out, "%s\n", sqlite3_column_text(pSql, 0));
4806 shellReset(&rc, pSql);
4808 shellFinalize(&rc, pSql);
4811 sqlite3_free(zDir);
4812 sqlite3_free(zWhere);
4813 return rc;
4818 ** Implementation of .ar "create" and "update" commands.
4820 ** Create the "sqlar" table in the database if it does not already exist.
4821 ** Then add each file in the azFile[] array to the archive. Directories
4822 ** are added recursively. If argument bVerbose is non-zero, a message is
4823 ** printed on stdout for each file archived.
4825 ** The create command is the same as update, except that it drops
4826 ** any existing "sqlar" table before beginning.
4828 static int arCreateUpdate(
4829 ShellState *p, /* Shell state pointer */
4830 sqlite3 *db,
4831 ArCommand *pAr, /* Command arguments and options */
4832 int bUpdate
4834 const char *zSql = "SELECT name, mode, mtime, data FROM fsdir(?, ?)";
4835 const char *zCreate =
4836 "CREATE TABLE IF NOT EXISTS sqlar("
4837 "name TEXT PRIMARY KEY, -- name of the file\n"
4838 "mode INT, -- access permissions\n"
4839 "mtime INT, -- last modification time\n"
4840 "sz INT, -- original file size\n"
4841 "data BLOB -- compressed content\n"
4842 ")";
4843 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
4844 const char *zInsert = "REPLACE INTO sqlar VALUES(?,?,?,?,sqlar_compress(?))";
4846 sqlite3_stmt *pStmt = 0; /* Directory traverser */
4847 sqlite3_stmt *pInsert = 0; /* Compilation of zInsert */
4848 int i; /* For iterating through azFile[] */
4849 int rc; /* Return code */
4851 assert( pAr->bZip==0 );
4853 rc = sqlite3_exec(db, "SAVEPOINT ar;", 0, 0, 0);
4854 if( rc!=SQLITE_OK ) return rc;
4856 if( bUpdate==0 ){
4857 rc = sqlite3_exec(db, zDrop, 0, 0, 0);
4858 if( rc!=SQLITE_OK ) return rc;
4861 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
4862 shellPrepare(db, &rc, zInsert, &pInsert);
4863 shellPrepare(db, &rc, zSql, &pStmt);
4864 sqlite3_bind_text(pStmt, 2, pAr->zDir, -1, SQLITE_STATIC);
4866 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4867 sqlite3_bind_text(pStmt, 1, pAr->azArg[i], -1, SQLITE_STATIC);
4868 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
4869 int sz;
4870 const char *zName = (const char*)sqlite3_column_text(pStmt, 0);
4871 int mode = sqlite3_column_int(pStmt, 1);
4872 unsigned int mtime = sqlite3_column_int(pStmt, 2);
4874 if( pAr->bVerbose ){
4875 raw_printf(p->out, "%s\n", zName);
4878 sqlite3_bind_text(pInsert, 1, zName, -1, SQLITE_STATIC);
4879 sqlite3_bind_int(pInsert, 2, mode);
4880 sqlite3_bind_int64(pInsert, 3, (sqlite3_int64)mtime);
4882 if( S_ISDIR(mode) ){
4883 sz = 0;
4884 sqlite3_bind_null(pInsert, 5);
4885 }else{
4886 sqlite3_bind_value(pInsert, 5, sqlite3_column_value(pStmt, 3));
4887 if( S_ISLNK(mode) ){
4888 sz = -1;
4889 }else{
4890 sz = sqlite3_column_bytes(pStmt, 3);
4894 sqlite3_bind_int(pInsert, 4, sz);
4895 sqlite3_step(pInsert);
4896 rc = sqlite3_reset(pInsert);
4898 shellReset(&rc, pStmt);
4901 if( rc!=SQLITE_OK ){
4902 sqlite3_exec(db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
4903 }else{
4904 rc = sqlite3_exec(db, "RELEASE ar;", 0, 0, 0);
4906 shellFinalize(&rc, pStmt);
4907 shellFinalize(&rc, pInsert);
4908 return rc;
4912 ** Implementation of .ar "Create" command.
4914 ** Create the "sqlar" table in the database if it does not already exist.
4915 ** Then add each file in the azFile[] array to the archive. Directories
4916 ** are added recursively. If argument bVerbose is non-zero, a message is
4917 ** printed on stdout for each file archived.
4919 static int arCreateCommand(
4920 ShellState *p, /* Shell state pointer */
4921 sqlite3 *db,
4922 ArCommand *pAr /* Command arguments and options */
4924 return arCreateUpdate(p, db, pAr, 0);
4928 ** Implementation of .ar "Update" command.
4930 static int arUpdateCmd(ShellState *p, sqlite3 *db, ArCommand *pAr){
4931 return arCreateUpdate(p, db, pAr, 1);
4936 ** Implementation of ".ar" dot command.
4938 static int arDotCommand(
4939 ShellState *pState, /* Current shell tool state */
4940 char **azArg, /* Array of arguments passed to dot command */
4941 int nArg /* Number of entries in azArg[] */
4943 ArCommand cmd;
4944 int rc;
4945 rc = arParseCommand(azArg, nArg, &cmd);
4946 if( rc==SQLITE_OK ){
4947 sqlite3 *db = 0; /* Database handle to use as archive */
4949 if( cmd.bZip ){
4950 if( cmd.zFile==0 ){
4951 raw_printf(stderr, "zip format requires a --file switch\n");
4952 return SQLITE_ERROR;
4953 }else
4954 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
4955 raw_printf(stderr, "zip archives are read-only\n");
4956 return SQLITE_ERROR;
4958 db = pState->db;
4959 }else if( cmd.zFile ){
4960 int flags;
4961 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
4962 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
4963 }else{
4964 flags = SQLITE_OPEN_READONLY;
4966 rc = sqlite3_open_v2(cmd.zFile, &db, flags, 0);
4967 if( rc!=SQLITE_OK ){
4968 raw_printf(stderr, "cannot open file: %s (%s)\n",
4969 cmd.zFile, sqlite3_errmsg(db)
4971 sqlite3_close(db);
4972 return rc;
4974 sqlite3_fileio_init(db, 0, 0);
4975 #ifdef SQLITE_HAVE_ZLIB
4976 sqlite3_sqlar_init(db, 0, 0);
4977 #endif
4978 }else{
4979 db = pState->db;
4982 switch( cmd.eCmd ){
4983 case AR_CMD_CREATE:
4984 rc = arCreateCommand(pState, db, &cmd);
4985 break;
4987 case AR_CMD_EXTRACT:
4988 rc = arExtractCommand(pState, db, &cmd);
4989 break;
4991 case AR_CMD_LIST:
4992 rc = arListCommand(pState, db, &cmd);
4993 break;
4995 case AR_CMD_HELP:
4996 arUsage(pState->out);
4997 break;
4999 default:
5000 assert( cmd.eCmd==AR_CMD_UPDATE );
5001 rc = arUpdateCmd(pState, db, &cmd);
5002 break;
5005 if( cmd.zFile ){
5006 sqlite3_close(db);
5010 return rc;
5014 ** Implementation of ".expert" dot command.
5016 static int expertDotCommand(
5017 ShellState *pState, /* Current shell tool state */
5018 char **azArg, /* Array of arguments passed to dot command */
5019 int nArg /* Number of entries in azArg[] */
5021 int rc = SQLITE_OK;
5022 char *zErr = 0;
5023 int i;
5024 int iSample = 0;
5026 assert( pState->expert.pExpert==0 );
5027 memset(&pState->expert, 0, sizeof(ExpertInfo));
5029 for(i=1; rc==SQLITE_OK && i<nArg; i++){
5030 char *z = azArg[i];
5031 int n;
5032 if( z[0]=='-' && z[1]=='-' ) z++;
5033 n = strlen30(z);
5034 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
5035 pState->expert.bVerbose = 1;
5037 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
5038 if( i==(nArg-1) ){
5039 raw_printf(stderr, "option requires an argument: %s\n", z);
5040 rc = SQLITE_ERROR;
5041 }else{
5042 iSample = (int)integerValue(azArg[++i]);
5043 if( iSample<0 || iSample>100 ){
5044 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
5045 rc = SQLITE_ERROR;
5049 else{
5050 raw_printf(stderr, "unknown option: %s\n", z);
5051 rc = SQLITE_ERROR;
5055 if( rc==SQLITE_OK ){
5056 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
5057 if( pState->expert.pExpert==0 ){
5058 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
5059 rc = SQLITE_ERROR;
5060 }else{
5061 sqlite3_expert_config(
5062 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
5067 return rc;
5072 ** If an input line begins with "." then invoke this routine to
5073 ** process that line.
5075 ** Return 1 on error, 2 to exit, and 0 otherwise.
5077 static int do_meta_command(char *zLine, ShellState *p){
5078 int h = 1;
5079 int nArg = 0;
5080 int n, c;
5081 int rc = 0;
5082 char *azArg[50];
5084 if( p->expert.pExpert ){
5085 expertFinish(p, 1, 0);
5088 /* Parse the input line into tokens.
5090 while( zLine[h] && nArg<ArraySize(azArg) ){
5091 while( IsSpace(zLine[h]) ){ h++; }
5092 if( zLine[h]==0 ) break;
5093 if( zLine[h]=='\'' || zLine[h]=='"' ){
5094 int delim = zLine[h++];
5095 azArg[nArg++] = &zLine[h];
5096 while( zLine[h] && zLine[h]!=delim ){
5097 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5098 h++;
5100 if( zLine[h]==delim ){
5101 zLine[h++] = 0;
5103 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5104 }else{
5105 azArg[nArg++] = &zLine[h];
5106 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5107 if( zLine[h] ) zLine[h++] = 0;
5108 resolve_backslashes(azArg[nArg-1]);
5112 /* Process the input line.
5114 if( nArg==0 ) return 0; /* no tokens, no error */
5115 n = strlen30(azArg[0]);
5116 c = azArg[0][0];
5118 #ifndef SQLITE_OMIT_AUTHORIZATION
5119 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5120 if( nArg!=2 ){
5121 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5122 rc = 1;
5123 goto meta_command_exit;
5125 open_db(p, 0);
5126 if( booleanValue(azArg[1]) ){
5127 sqlite3_set_authorizer(p->db, shellAuth, p);
5128 }else{
5129 sqlite3_set_authorizer(p->db, 0, 0);
5131 }else
5132 #endif
5134 #ifndef SQLITE_OMIT_VIRTUALTABLE
5135 if( c=='a' && strncmp(azArg[0], "ar", n)==0 ){
5136 open_db(p, 0);
5137 rc = arDotCommand(p, azArg, nArg);
5138 }else
5139 #endif
5141 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5142 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5144 const char *zDestFile = 0;
5145 const char *zDb = 0;
5146 sqlite3 *pDest;
5147 sqlite3_backup *pBackup;
5148 int j;
5149 for(j=1; j<nArg; j++){
5150 const char *z = azArg[j];
5151 if( z[0]=='-' ){
5152 while( z[0]=='-' ) z++;
5153 /* No options to process at this time */
5155 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5156 return 1;
5158 }else if( zDestFile==0 ){
5159 zDestFile = azArg[j];
5160 }else if( zDb==0 ){
5161 zDb = zDestFile;
5162 zDestFile = azArg[j];
5163 }else{
5164 raw_printf(stderr, "too many arguments to .backup\n");
5165 return 1;
5168 if( zDestFile==0 ){
5169 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5170 return 1;
5172 if( zDb==0 ) zDb = "main";
5173 rc = sqlite3_open(zDestFile, &pDest);
5174 if( rc!=SQLITE_OK ){
5175 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5176 sqlite3_close(pDest);
5177 return 1;
5179 open_db(p, 0);
5180 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5181 if( pBackup==0 ){
5182 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5183 sqlite3_close(pDest);
5184 return 1;
5186 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5187 sqlite3_backup_finish(pBackup);
5188 if( rc==SQLITE_DONE ){
5189 rc = 0;
5190 }else{
5191 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5192 rc = 1;
5194 sqlite3_close(pDest);
5195 }else
5197 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5198 if( nArg==2 ){
5199 bail_on_error = booleanValue(azArg[1]);
5200 }else{
5201 raw_printf(stderr, "Usage: .bail on|off\n");
5202 rc = 1;
5204 }else
5206 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5207 if( nArg==2 ){
5208 if( booleanValue(azArg[1]) ){
5209 setBinaryMode(p->out, 1);
5210 }else{
5211 setTextMode(p->out, 1);
5213 }else{
5214 raw_printf(stderr, "Usage: .binary on|off\n");
5215 rc = 1;
5217 }else
5219 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5220 if( nArg==2 ){
5221 #if defined(_WIN32) || defined(WIN32)
5222 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5223 rc = !SetCurrentDirectoryW(z);
5224 sqlite3_free(z);
5225 #else
5226 rc = chdir(azArg[1]);
5227 #endif
5228 if( rc ){
5229 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5230 rc = 1;
5232 }else{
5233 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5234 rc = 1;
5236 }else
5238 /* The undocumented ".breakpoint" command causes a call to the no-op
5239 ** routine named test_breakpoint().
5241 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5242 test_breakpoint();
5243 }else
5245 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5246 if( nArg==2 ){
5247 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5248 }else{
5249 raw_printf(stderr, "Usage: .changes on|off\n");
5250 rc = 1;
5252 }else
5254 /* Cancel output redirection, if it is currently set (by .testcase)
5255 ** Then read the content of the testcase-out.txt file and compare against
5256 ** azArg[1]. If there are differences, report an error and exit.
5258 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5259 char *zRes = 0;
5260 output_reset(p);
5261 if( nArg!=2 ){
5262 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5263 rc = 2;
5264 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5265 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5266 rc = 2;
5267 }else if( testcase_glob(azArg[1],zRes)==0 ){
5268 utf8_printf(stderr,
5269 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5270 p->zTestcase, azArg[1], zRes);
5271 rc = 1;
5272 }else{
5273 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5274 p->nCheck++;
5276 sqlite3_free(zRes);
5277 }else
5279 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5280 if( nArg==2 ){
5281 tryToClone(p, azArg[1]);
5282 }else{
5283 raw_printf(stderr, "Usage: .clone FILENAME\n");
5284 rc = 1;
5286 }else
5288 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5289 ShellState data;
5290 char *zErrMsg = 0;
5291 open_db(p, 0);
5292 memcpy(&data, p, sizeof(data));
5293 data.showHeader = 0;
5294 data.cMode = data.mode = MODE_List;
5295 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5296 data.cnt = 0;
5297 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5298 callback, &data, &zErrMsg);
5299 if( zErrMsg ){
5300 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5301 sqlite3_free(zErrMsg);
5302 rc = 1;
5304 }else
5306 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5307 rc = shell_dbinfo_command(p, nArg, azArg);
5308 }else
5310 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5311 const char *zLike = 0;
5312 int i;
5313 int savedShowHeader = p->showHeader;
5314 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5315 for(i=1; i<nArg; i++){
5316 if( azArg[i][0]=='-' ){
5317 const char *z = azArg[i]+1;
5318 if( z[0]=='-' ) z++;
5319 if( strcmp(z,"preserve-rowids")==0 ){
5320 #ifdef SQLITE_OMIT_VIRTUALTABLE
5321 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5322 " with SQLITE_OMIT_VIRTUALTABLE\n");
5323 rc = 1;
5324 goto meta_command_exit;
5325 #else
5326 ShellSetFlag(p, SHFLG_PreserveRowid);
5327 #endif
5328 }else
5329 if( strcmp(z,"newlines")==0 ){
5330 ShellSetFlag(p, SHFLG_Newlines);
5331 }else
5333 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5334 rc = 1;
5335 goto meta_command_exit;
5337 }else if( zLike ){
5338 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5339 "?--newlines? ?LIKE-PATTERN?\n");
5340 rc = 1;
5341 goto meta_command_exit;
5342 }else{
5343 zLike = azArg[i];
5346 open_db(p, 0);
5347 /* When playing back a "dump", the content might appear in an order
5348 ** which causes immediate foreign key constraints to be violated.
5349 ** So disable foreign-key constraint enforcement to prevent problems. */
5350 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5351 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5352 p->writableSchema = 0;
5353 p->showHeader = 0;
5354 /* Set writable_schema=ON since doing so forces SQLite to initialize
5355 ** as much of the schema as it can even if the sqlite_master table is
5356 ** corrupt. */
5357 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5358 p->nErr = 0;
5359 if( zLike==0 ){
5360 run_schema_dump_query(p,
5361 "SELECT name, type, sql FROM sqlite_master "
5362 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5364 run_schema_dump_query(p,
5365 "SELECT name, type, sql FROM sqlite_master "
5366 "WHERE name=='sqlite_sequence'"
5368 run_table_dump_query(p,
5369 "SELECT sql FROM sqlite_master "
5370 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5372 }else{
5373 char *zSql;
5374 zSql = sqlite3_mprintf(
5375 "SELECT name, type, sql FROM sqlite_master "
5376 "WHERE tbl_name LIKE %Q AND type=='table'"
5377 " AND sql NOT NULL", zLike);
5378 run_schema_dump_query(p,zSql);
5379 sqlite3_free(zSql);
5380 zSql = sqlite3_mprintf(
5381 "SELECT sql FROM sqlite_master "
5382 "WHERE sql NOT NULL"
5383 " AND type IN ('index','trigger','view')"
5384 " AND tbl_name LIKE %Q", zLike);
5385 run_table_dump_query(p, zSql, 0);
5386 sqlite3_free(zSql);
5388 if( p->writableSchema ){
5389 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5390 p->writableSchema = 0;
5392 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5393 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5394 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5395 p->showHeader = savedShowHeader;
5396 }else
5398 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5399 if( nArg==2 ){
5400 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5401 }else{
5402 raw_printf(stderr, "Usage: .echo on|off\n");
5403 rc = 1;
5405 }else
5407 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5408 if( nArg==2 ){
5409 if( strcmp(azArg[1],"full")==0 ){
5410 p->autoEQP = AUTOEQP_full;
5411 }else if( strcmp(azArg[1],"trigger")==0 ){
5412 p->autoEQP = AUTOEQP_trigger;
5413 }else{
5414 p->autoEQP = booleanValue(azArg[1]);
5416 }else{
5417 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
5418 rc = 1;
5420 }else
5422 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5423 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5424 rc = 2;
5425 }else
5427 /* The ".explain" command is automatic now. It is largely pointless. It
5428 ** retained purely for backwards compatibility */
5429 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5430 int val = 1;
5431 if( nArg>=2 ){
5432 if( strcmp(azArg[1],"auto")==0 ){
5433 val = 99;
5434 }else{
5435 val = booleanValue(azArg[1]);
5438 if( val==1 && p->mode!=MODE_Explain ){
5439 p->normalMode = p->mode;
5440 p->mode = MODE_Explain;
5441 p->autoExplain = 0;
5442 }else if( val==0 ){
5443 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5444 p->autoExplain = 0;
5445 }else if( val==99 ){
5446 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5447 p->autoExplain = 1;
5449 }else
5451 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
5452 open_db(p, 0);
5453 expertDotCommand(p, azArg, nArg);
5454 }else
5456 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
5457 ShellState data;
5458 char *zErrMsg = 0;
5459 int doStats = 0;
5460 memcpy(&data, p, sizeof(data));
5461 data.showHeader = 0;
5462 data.cMode = data.mode = MODE_Semi;
5463 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5464 data.cMode = data.mode = MODE_Pretty;
5465 nArg = 1;
5467 if( nArg!=1 ){
5468 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
5469 rc = 1;
5470 goto meta_command_exit;
5472 open_db(p, 0);
5473 rc = sqlite3_exec(p->db,
5474 "SELECT sql FROM"
5475 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5476 " FROM sqlite_master UNION ALL"
5477 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5478 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5479 "ORDER BY rowid",
5480 callback, &data, &zErrMsg
5482 if( rc==SQLITE_OK ){
5483 sqlite3_stmt *pStmt;
5484 rc = sqlite3_prepare_v2(p->db,
5485 "SELECT rowid FROM sqlite_master"
5486 " WHERE name GLOB 'sqlite_stat[134]'",
5487 -1, &pStmt, 0);
5488 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5489 sqlite3_finalize(pStmt);
5491 if( doStats==0 ){
5492 raw_printf(p->out, "/* No STAT tables available */\n");
5493 }else{
5494 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5495 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5496 callback, &data, &zErrMsg);
5497 data.cMode = data.mode = MODE_Insert;
5498 data.zDestTable = "sqlite_stat1";
5499 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5500 shell_callback, &data,&zErrMsg);
5501 data.zDestTable = "sqlite_stat3";
5502 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5503 shell_callback, &data,&zErrMsg);
5504 data.zDestTable = "sqlite_stat4";
5505 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5506 shell_callback, &data, &zErrMsg);
5507 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5509 }else
5511 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5512 if( nArg==2 ){
5513 p->showHeader = booleanValue(azArg[1]);
5514 }else{
5515 raw_printf(stderr, "Usage: .headers on|off\n");
5516 rc = 1;
5518 }else
5520 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
5521 utf8_printf(p->out, "%s", zHelp);
5522 }else
5524 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
5525 char *zTable; /* Insert data into this table */
5526 char *zFile; /* Name of file to extra content from */
5527 sqlite3_stmt *pStmt = NULL; /* A statement */
5528 int nCol; /* Number of columns in the table */
5529 int nByte; /* Number of bytes in an SQL string */
5530 int i, j; /* Loop counters */
5531 int needCommit; /* True to COMMIT or ROLLBACK at end */
5532 int nSep; /* Number of bytes in p->colSeparator[] */
5533 char *zSql; /* An SQL statement */
5534 ImportCtx sCtx; /* Reader context */
5535 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5536 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
5538 if( nArg!=3 ){
5539 raw_printf(stderr, "Usage: .import FILE TABLE\n");
5540 goto meta_command_exit;
5542 zFile = azArg[1];
5543 zTable = azArg[2];
5544 seenInterrupt = 0;
5545 memset(&sCtx, 0, sizeof(sCtx));
5546 open_db(p, 0);
5547 nSep = strlen30(p->colSeparator);
5548 if( nSep==0 ){
5549 raw_printf(stderr,
5550 "Error: non-null column separator required for import\n");
5551 return 1;
5553 if( nSep>1 ){
5554 raw_printf(stderr, "Error: multi-character column separators not allowed"
5555 " for import\n");
5556 return 1;
5558 nSep = strlen30(p->rowSeparator);
5559 if( nSep==0 ){
5560 raw_printf(stderr, "Error: non-null row separator required for import\n");
5561 return 1;
5563 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5564 /* When importing CSV (only), if the row separator is set to the
5565 ** default output row separator, change it to the default input
5566 ** row separator. This avoids having to maintain different input
5567 ** and output row separators. */
5568 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5569 nSep = strlen30(p->rowSeparator);
5571 if( nSep>1 ){
5572 raw_printf(stderr, "Error: multi-character row separators not allowed"
5573 " for import\n");
5574 return 1;
5576 sCtx.zFile = zFile;
5577 sCtx.nLine = 1;
5578 if( sCtx.zFile[0]=='|' ){
5579 #ifdef SQLITE_OMIT_POPEN
5580 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5581 return 1;
5582 #else
5583 sCtx.in = popen(sCtx.zFile+1, "r");
5584 sCtx.zFile = "<pipe>";
5585 xCloser = pclose;
5586 #endif
5587 }else{
5588 sCtx.in = fopen(sCtx.zFile, "rb");
5589 xCloser = fclose;
5591 if( p->mode==MODE_Ascii ){
5592 xRead = ascii_read_one_field;
5593 }else{
5594 xRead = csv_read_one_field;
5596 if( sCtx.in==0 ){
5597 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5598 return 1;
5600 sCtx.cColSep = p->colSeparator[0];
5601 sCtx.cRowSep = p->rowSeparator[0];
5602 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
5603 if( zSql==0 ){
5604 raw_printf(stderr, "Error: out of memory\n");
5605 xCloser(sCtx.in);
5606 return 1;
5608 nByte = strlen30(zSql);
5609 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5610 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
5611 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
5612 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5613 char cSep = '(';
5614 while( xRead(&sCtx) ){
5615 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
5616 cSep = ',';
5617 if( sCtx.cTerm!=sCtx.cColSep ) break;
5619 if( cSep=='(' ){
5620 sqlite3_free(zCreate);
5621 sqlite3_free(sCtx.z);
5622 xCloser(sCtx.in);
5623 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
5624 return 1;
5626 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5627 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5628 sqlite3_free(zCreate);
5629 if( rc ){
5630 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
5631 sqlite3_errmsg(p->db));
5632 sqlite3_free(sCtx.z);
5633 xCloser(sCtx.in);
5634 return 1;
5636 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5638 sqlite3_free(zSql);
5639 if( rc ){
5640 if (pStmt) sqlite3_finalize(pStmt);
5641 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
5642 xCloser(sCtx.in);
5643 return 1;
5645 nCol = sqlite3_column_count(pStmt);
5646 sqlite3_finalize(pStmt);
5647 pStmt = 0;
5648 if( nCol==0 ) return 0; /* no columns, no error */
5649 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5650 if( zSql==0 ){
5651 raw_printf(stderr, "Error: out of memory\n");
5652 xCloser(sCtx.in);
5653 return 1;
5655 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5656 j = strlen30(zSql);
5657 for(i=1; i<nCol; i++){
5658 zSql[j++] = ',';
5659 zSql[j++] = '?';
5661 zSql[j++] = ')';
5662 zSql[j] = 0;
5663 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5664 sqlite3_free(zSql);
5665 if( rc ){
5666 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5667 if (pStmt) sqlite3_finalize(pStmt);
5668 xCloser(sCtx.in);
5669 return 1;
5671 needCommit = sqlite3_get_autocommit(p->db);
5672 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5674 int startLine = sCtx.nLine;
5675 for(i=0; i<nCol; i++){
5676 char *z = xRead(&sCtx);
5678 ** Did we reach end-of-file before finding any columns?
5679 ** If so, stop instead of NULL filling the remaining columns.
5681 if( z==0 && i==0 ) break;
5683 ** Did we reach end-of-file OR end-of-line before finding any
5684 ** columns in ASCII mode? If so, stop instead of NULL filling
5685 ** the remaining columns.
5687 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5688 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5689 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5690 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5691 "filling the rest with NULL\n",
5692 sCtx.zFile, startLine, nCol, i+1);
5693 i += 2;
5694 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5697 if( sCtx.cTerm==sCtx.cColSep ){
5699 xRead(&sCtx);
5700 i++;
5701 }while( sCtx.cTerm==sCtx.cColSep );
5702 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5703 "extras ignored\n",
5704 sCtx.zFile, startLine, nCol, i);
5706 if( i>=nCol ){
5707 sqlite3_step(pStmt);
5708 rc = sqlite3_reset(pStmt);
5709 if( rc!=SQLITE_OK ){
5710 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5711 startLine, sqlite3_errmsg(p->db));
5714 }while( sCtx.cTerm!=EOF );
5716 xCloser(sCtx.in);
5717 sqlite3_free(sCtx.z);
5718 sqlite3_finalize(pStmt);
5719 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5720 }else
5722 #ifndef SQLITE_UNTESTABLE
5723 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5724 char *zSql;
5725 char *zCollist = 0;
5726 sqlite3_stmt *pStmt;
5727 int tnum = 0;
5728 int i;
5729 if( nArg!=3 ){
5730 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5731 rc = 1;
5732 goto meta_command_exit;
5734 open_db(p, 0);
5735 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5736 " WHERE name='%q' AND type='index'", azArg[1]);
5737 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5738 sqlite3_free(zSql);
5739 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5740 tnum = sqlite3_column_int(pStmt, 0);
5742 sqlite3_finalize(pStmt);
5743 if( tnum==0 ){
5744 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5745 rc = 1;
5746 goto meta_command_exit;
5748 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5749 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5750 sqlite3_free(zSql);
5751 i = 0;
5752 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5753 char zLabel[20];
5754 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5755 i++;
5756 if( zCol==0 ){
5757 if( sqlite3_column_int(pStmt,1)==-1 ){
5758 zCol = "_ROWID_";
5759 }else{
5760 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5761 zCol = zLabel;
5764 if( zCollist==0 ){
5765 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5766 }else{
5767 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5770 sqlite3_finalize(pStmt);
5771 zSql = sqlite3_mprintf(
5772 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5773 azArg[2], zCollist, zCollist);
5774 sqlite3_free(zCollist);
5775 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5776 if( rc==SQLITE_OK ){
5777 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5778 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5779 if( rc ){
5780 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5781 }else{
5782 utf8_printf(stdout, "%s;\n", zSql);
5783 raw_printf(stdout,
5784 "WARNING: writing to an imposter table will corrupt the index!\n"
5787 }else{
5788 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5789 rc = 1;
5791 sqlite3_free(zSql);
5792 }else
5793 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5795 #ifdef SQLITE_ENABLE_IOTRACE
5796 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5797 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5798 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5799 iotrace = 0;
5800 if( nArg<2 ){
5801 sqlite3IoTrace = 0;
5802 }else if( strcmp(azArg[1], "-")==0 ){
5803 sqlite3IoTrace = iotracePrintf;
5804 iotrace = stdout;
5805 }else{
5806 iotrace = fopen(azArg[1], "w");
5807 if( iotrace==0 ){
5808 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5809 sqlite3IoTrace = 0;
5810 rc = 1;
5811 }else{
5812 sqlite3IoTrace = iotracePrintf;
5815 }else
5816 #endif
5818 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5819 static const struct {
5820 const char *zLimitName; /* Name of a limit */
5821 int limitCode; /* Integer code for that limit */
5822 } aLimit[] = {
5823 { "length", SQLITE_LIMIT_LENGTH },
5824 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5825 { "column", SQLITE_LIMIT_COLUMN },
5826 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5827 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5828 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5829 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5830 { "attached", SQLITE_LIMIT_ATTACHED },
5831 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5832 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5833 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5834 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5836 int i, n2;
5837 open_db(p, 0);
5838 if( nArg==1 ){
5839 for(i=0; i<ArraySize(aLimit); i++){
5840 printf("%20s %d\n", aLimit[i].zLimitName,
5841 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5843 }else if( nArg>3 ){
5844 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5845 rc = 1;
5846 goto meta_command_exit;
5847 }else{
5848 int iLimit = -1;
5849 n2 = strlen30(azArg[1]);
5850 for(i=0; i<ArraySize(aLimit); i++){
5851 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5852 if( iLimit<0 ){
5853 iLimit = i;
5854 }else{
5855 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5856 rc = 1;
5857 goto meta_command_exit;
5861 if( iLimit<0 ){
5862 utf8_printf(stderr, "unknown limit: \"%s\"\n"
5863 "enter \".limits\" with no arguments for a list.\n",
5864 azArg[1]);
5865 rc = 1;
5866 goto meta_command_exit;
5868 if( nArg==3 ){
5869 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5870 (int)integerValue(azArg[2]));
5872 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5873 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5875 }else
5877 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5878 open_db(p, 0);
5879 lintDotCommand(p, azArg, nArg);
5880 }else
5882 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5883 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5884 const char *zFile, *zProc;
5885 char *zErrMsg = 0;
5886 if( nArg<2 ){
5887 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5888 rc = 1;
5889 goto meta_command_exit;
5891 zFile = azArg[1];
5892 zProc = nArg>=3 ? azArg[2] : 0;
5893 open_db(p, 0);
5894 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5895 if( rc!=SQLITE_OK ){
5896 utf8_printf(stderr, "Error: %s\n", zErrMsg);
5897 sqlite3_free(zErrMsg);
5898 rc = 1;
5900 }else
5901 #endif
5903 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5904 if( nArg!=2 ){
5905 raw_printf(stderr, "Usage: .log FILENAME\n");
5906 rc = 1;
5907 }else{
5908 const char *zFile = azArg[1];
5909 output_file_close(p->pLog);
5910 p->pLog = output_file_open(zFile);
5912 }else
5914 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5915 const char *zMode = nArg>=2 ? azArg[1] : "";
5916 int n2 = strlen30(zMode);
5917 int c2 = zMode[0];
5918 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
5919 p->mode = MODE_Line;
5920 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5921 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
5922 p->mode = MODE_Column;
5923 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5924 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
5925 p->mode = MODE_List;
5926 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5927 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5928 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
5929 p->mode = MODE_Html;
5930 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
5931 p->mode = MODE_Tcl;
5932 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
5933 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5934 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
5935 p->mode = MODE_Csv;
5936 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
5937 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
5938 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
5939 p->mode = MODE_List;
5940 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
5941 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
5942 p->mode = MODE_Insert;
5943 set_table_name(p, nArg>=3 ? azArg[2] : "table");
5944 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5945 p->mode = MODE_Quote;
5946 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5947 p->mode = MODE_Ascii;
5948 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5949 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
5950 }else if( nArg==1 ){
5951 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
5952 }else{
5953 raw_printf(stderr, "Error: mode should be one of: "
5954 "ascii column csv html insert line list quote tabs tcl\n");
5955 rc = 1;
5957 p->cMode = p->mode;
5958 }else
5960 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5961 if( nArg==2 ){
5962 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5963 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
5964 }else{
5965 raw_printf(stderr, "Usage: .nullvalue STRING\n");
5966 rc = 1;
5968 }else
5970 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
5971 char *zNewFilename; /* Name of the database file to open */
5972 int iName = 1; /* Index in azArg[] of the filename */
5973 int newFlag = 0; /* True to delete file before opening */
5974 /* Close the existing database */
5975 session_close_all(p);
5976 sqlite3_close(p->db);
5977 p->db = 0;
5978 p->zDbFilename = 0;
5979 sqlite3_free(p->zFreeOnClose);
5980 p->zFreeOnClose = 0;
5981 /* Check for command-line arguments */
5982 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5983 const char *z = azArg[iName];
5984 if( optionMatch(z,"new") ){
5985 newFlag = 1;
5986 }else if( z[0]=='-' ){
5987 utf8_printf(stderr, "unknown option: %s\n", z);
5988 rc = 1;
5989 goto meta_command_exit;
5992 /* If a filename is specified, try to open it first */
5993 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5994 if( zNewFilename ){
5995 if( newFlag ) shellDeleteFile(zNewFilename);
5996 p->zDbFilename = zNewFilename;
5997 open_db(p, 1);
5998 if( p->db==0 ){
5999 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6000 sqlite3_free(zNewFilename);
6001 }else{
6002 p->zFreeOnClose = zNewFilename;
6005 if( p->db==0 ){
6006 /* As a fall-back open a TEMP database */
6007 p->zDbFilename = 0;
6008 open_db(p, 0);
6010 }else
6012 if( c=='o'
6013 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
6015 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6016 if( nArg>2 ){
6017 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
6018 rc = 1;
6019 goto meta_command_exit;
6021 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6022 if( nArg<2 ){
6023 raw_printf(stderr, "Usage: .once FILE\n");
6024 rc = 1;
6025 goto meta_command_exit;
6027 p->outCount = 2;
6028 }else{
6029 p->outCount = 0;
6031 output_reset(p);
6032 if( zFile[0]=='|' ){
6033 #ifdef SQLITE_OMIT_POPEN
6034 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6035 rc = 1;
6036 p->out = stdout;
6037 #else
6038 p->out = popen(zFile + 1, "w");
6039 if( p->out==0 ){
6040 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6041 p->out = stdout;
6042 rc = 1;
6043 }else{
6044 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6046 #endif
6047 }else{
6048 p->out = output_file_open(zFile);
6049 if( p->out==0 ){
6050 if( strcmp(zFile,"off")!=0 ){
6051 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6053 p->out = stdout;
6054 rc = 1;
6055 } else {
6056 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6059 }else
6061 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6062 int i;
6063 for(i=1; i<nArg; i++){
6064 if( i>1 ) raw_printf(p->out, " ");
6065 utf8_printf(p->out, "%s", azArg[i]);
6067 raw_printf(p->out, "\n");
6068 }else
6070 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6071 if( nArg >= 2) {
6072 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6074 if( nArg >= 3) {
6075 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6077 }else
6079 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6080 rc = 2;
6081 }else
6083 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6084 FILE *alt;
6085 if( nArg!=2 ){
6086 raw_printf(stderr, "Usage: .read FILE\n");
6087 rc = 1;
6088 goto meta_command_exit;
6090 alt = fopen(azArg[1], "rb");
6091 if( alt==0 ){
6092 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6093 rc = 1;
6094 }else{
6095 rc = process_input(p, alt);
6096 fclose(alt);
6098 }else
6100 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6101 const char *zSrcFile;
6102 const char *zDb;
6103 sqlite3 *pSrc;
6104 sqlite3_backup *pBackup;
6105 int nTimeout = 0;
6107 if( nArg==2 ){
6108 zSrcFile = azArg[1];
6109 zDb = "main";
6110 }else if( nArg==3 ){
6111 zSrcFile = azArg[2];
6112 zDb = azArg[1];
6113 }else{
6114 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6115 rc = 1;
6116 goto meta_command_exit;
6118 rc = sqlite3_open(zSrcFile, &pSrc);
6119 if( rc!=SQLITE_OK ){
6120 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6121 sqlite3_close(pSrc);
6122 return 1;
6124 open_db(p, 0);
6125 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6126 if( pBackup==0 ){
6127 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6128 sqlite3_close(pSrc);
6129 return 1;
6131 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6132 || rc==SQLITE_BUSY ){
6133 if( rc==SQLITE_BUSY ){
6134 if( nTimeout++ >= 3 ) break;
6135 sqlite3_sleep(100);
6138 sqlite3_backup_finish(pBackup);
6139 if( rc==SQLITE_DONE ){
6140 rc = 0;
6141 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6142 raw_printf(stderr, "Error: source database is busy\n");
6143 rc = 1;
6144 }else{
6145 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6146 rc = 1;
6148 sqlite3_close(pSrc);
6149 }else
6152 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6153 if( nArg==2 ){
6154 p->scanstatsOn = booleanValue(azArg[1]);
6155 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6156 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6157 #endif
6158 }else{
6159 raw_printf(stderr, "Usage: .scanstats on|off\n");
6160 rc = 1;
6162 }else
6164 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6165 ShellText sSelect;
6166 ShellState data;
6167 char *zErrMsg = 0;
6168 const char *zDiv = "(";
6169 const char *zName = 0;
6170 int iSchema = 0;
6171 int bDebug = 0;
6172 int ii;
6174 open_db(p, 0);
6175 memcpy(&data, p, sizeof(data));
6176 data.showHeader = 0;
6177 data.cMode = data.mode = MODE_Semi;
6178 initText(&sSelect);
6179 for(ii=1; ii<nArg; ii++){
6180 if( optionMatch(azArg[ii],"indent") ){
6181 data.cMode = data.mode = MODE_Pretty;
6182 }else if( optionMatch(azArg[ii],"debug") ){
6183 bDebug = 1;
6184 }else if( zName==0 ){
6185 zName = azArg[ii];
6186 }else{
6187 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6188 rc = 1;
6189 goto meta_command_exit;
6192 if( zName!=0 ){
6193 int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
6194 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
6195 char *new_argv[2], *new_colv[2];
6196 new_argv[0] = sqlite3_mprintf(
6197 "CREATE TABLE %s (\n"
6198 " type text,\n"
6199 " name text,\n"
6200 " tbl_name text,\n"
6201 " rootpage integer,\n"
6202 " sql text\n"
6203 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
6204 new_argv[1] = 0;
6205 new_colv[0] = "sql";
6206 new_colv[1] = 0;
6207 callback(&data, 1, new_argv, new_colv);
6208 sqlite3_free(new_argv[0]);
6211 if( zDiv ){
6212 sqlite3_stmt *pStmt = 0;
6213 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6214 -1, &pStmt, 0);
6215 if( rc ){
6216 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6217 sqlite3_finalize(pStmt);
6218 rc = 1;
6219 goto meta_command_exit;
6221 appendText(&sSelect, "SELECT sql FROM", 0);
6222 iSchema = 0;
6223 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6224 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6225 char zScNum[30];
6226 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6227 appendText(&sSelect, zDiv, 0);
6228 zDiv = " UNION ALL ";
6229 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6230 if( sqlite3_stricmp(zDb, "main")!=0 ){
6231 appendText(&sSelect, zDb, '"');
6232 }else{
6233 appendText(&sSelect, "NULL", 0);
6235 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6236 appendText(&sSelect, zScNum, 0);
6237 appendText(&sSelect, " AS snum, ", 0);
6238 appendText(&sSelect, zDb, '\'');
6239 appendText(&sSelect, " AS sname FROM ", 0);
6240 appendText(&sSelect, zDb, '"');
6241 appendText(&sSelect, ".sqlite_master", 0);
6243 sqlite3_finalize(pStmt);
6244 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6245 if( zName ){
6246 appendText(&sSelect,
6247 " UNION ALL SELECT shell_module_schema(name),"
6248 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6250 #endif
6251 appendText(&sSelect, ") WHERE ", 0);
6252 if( zName ){
6253 char *zQarg = sqlite3_mprintf("%Q", zName);
6254 if( strchr(zName, '.') ){
6255 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6256 }else{
6257 appendText(&sSelect, "lower(tbl_name)", 0);
6259 appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
6260 appendText(&sSelect, zQarg, 0);
6261 appendText(&sSelect, " AND ", 0);
6262 sqlite3_free(zQarg);
6264 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6265 " ORDER BY snum, rowid", 0);
6266 if( bDebug ){
6267 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6268 }else{
6269 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6271 freeText(&sSelect);
6273 if( zErrMsg ){
6274 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6275 sqlite3_free(zErrMsg);
6276 rc = 1;
6277 }else if( rc != SQLITE_OK ){
6278 raw_printf(stderr,"Error: querying schema information\n");
6279 rc = 1;
6280 }else{
6281 rc = 0;
6283 }else
6285 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6286 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6287 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6288 }else
6289 #endif
6291 #if defined(SQLITE_ENABLE_SESSION)
6292 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6293 OpenSession *pSession = &p->aSession[0];
6294 char **azCmd = &azArg[1];
6295 int iSes = 0;
6296 int nCmd = nArg - 1;
6297 int i;
6298 if( nArg<=1 ) goto session_syntax_error;
6299 open_db(p, 0);
6300 if( nArg>=3 ){
6301 for(iSes=0; iSes<p->nSession; iSes++){
6302 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6304 if( iSes<p->nSession ){
6305 pSession = &p->aSession[iSes];
6306 azCmd++;
6307 nCmd--;
6308 }else{
6309 pSession = &p->aSession[0];
6310 iSes = 0;
6314 /* .session attach TABLE
6315 ** Invoke the sqlite3session_attach() interface to attach a particular
6316 ** table so that it is never filtered.
6318 if( strcmp(azCmd[0],"attach")==0 ){
6319 if( nCmd!=2 ) goto session_syntax_error;
6320 if( pSession->p==0 ){
6321 session_not_open:
6322 raw_printf(stderr, "ERROR: No sessions are open\n");
6323 }else{
6324 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6325 if( rc ){
6326 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6327 rc = 0;
6330 }else
6332 /* .session changeset FILE
6333 ** .session patchset FILE
6334 ** Write a changeset or patchset into a file. The file is overwritten.
6336 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6337 FILE *out = 0;
6338 if( nCmd!=2 ) goto session_syntax_error;
6339 if( pSession->p==0 ) goto session_not_open;
6340 out = fopen(azCmd[1], "wb");
6341 if( out==0 ){
6342 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6343 }else{
6344 int szChng;
6345 void *pChng;
6346 if( azCmd[0][0]=='c' ){
6347 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6348 }else{
6349 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6351 if( rc ){
6352 printf("Error: error code %d\n", rc);
6353 rc = 0;
6355 if( pChng
6356 && fwrite(pChng, szChng, 1, out)!=1 ){
6357 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6358 szChng);
6360 sqlite3_free(pChng);
6361 fclose(out);
6363 }else
6365 /* .session close
6366 ** Close the identified session
6368 if( strcmp(azCmd[0], "close")==0 ){
6369 if( nCmd!=1 ) goto session_syntax_error;
6370 if( p->nSession ){
6371 session_close(pSession);
6372 p->aSession[iSes] = p->aSession[--p->nSession];
6374 }else
6376 /* .session enable ?BOOLEAN?
6377 ** Query or set the enable flag
6379 if( strcmp(azCmd[0], "enable")==0 ){
6380 int ii;
6381 if( nCmd>2 ) goto session_syntax_error;
6382 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6383 if( p->nSession ){
6384 ii = sqlite3session_enable(pSession->p, ii);
6385 utf8_printf(p->out, "session %s enable flag = %d\n",
6386 pSession->zName, ii);
6388 }else
6390 /* .session filter GLOB ....
6391 ** Set a list of GLOB patterns of table names to be excluded.
6393 if( strcmp(azCmd[0], "filter")==0 ){
6394 int ii, nByte;
6395 if( nCmd<2 ) goto session_syntax_error;
6396 if( p->nSession ){
6397 for(ii=0; ii<pSession->nFilter; ii++){
6398 sqlite3_free(pSession->azFilter[ii]);
6400 sqlite3_free(pSession->azFilter);
6401 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6402 pSession->azFilter = sqlite3_malloc( nByte );
6403 if( pSession->azFilter==0 ){
6404 raw_printf(stderr, "Error: out or memory\n");
6405 exit(1);
6407 for(ii=1; ii<nCmd; ii++){
6408 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6410 pSession->nFilter = ii-1;
6412 }else
6414 /* .session indirect ?BOOLEAN?
6415 ** Query or set the indirect flag
6417 if( strcmp(azCmd[0], "indirect")==0 ){
6418 int ii;
6419 if( nCmd>2 ) goto session_syntax_error;
6420 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6421 if( p->nSession ){
6422 ii = sqlite3session_indirect(pSession->p, ii);
6423 utf8_printf(p->out, "session %s indirect flag = %d\n",
6424 pSession->zName, ii);
6426 }else
6428 /* .session isempty
6429 ** Determine if the session is empty
6431 if( strcmp(azCmd[0], "isempty")==0 ){
6432 int ii;
6433 if( nCmd!=1 ) goto session_syntax_error;
6434 if( p->nSession ){
6435 ii = sqlite3session_isempty(pSession->p);
6436 utf8_printf(p->out, "session %s isempty flag = %d\n",
6437 pSession->zName, ii);
6439 }else
6441 /* .session list
6442 ** List all currently open sessions
6444 if( strcmp(azCmd[0],"list")==0 ){
6445 for(i=0; i<p->nSession; i++){
6446 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
6448 }else
6450 /* .session open DB NAME
6451 ** Open a new session called NAME on the attached database DB.
6452 ** DB is normally "main".
6454 if( strcmp(azCmd[0],"open")==0 ){
6455 char *zName;
6456 if( nCmd!=3 ) goto session_syntax_error;
6457 zName = azCmd[2];
6458 if( zName[0]==0 ) goto session_syntax_error;
6459 for(i=0; i<p->nSession; i++){
6460 if( strcmp(p->aSession[i].zName,zName)==0 ){
6461 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
6462 goto meta_command_exit;
6465 if( p->nSession>=ArraySize(p->aSession) ){
6466 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
6467 goto meta_command_exit;
6469 pSession = &p->aSession[p->nSession];
6470 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6471 if( rc ){
6472 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
6473 rc = 0;
6474 goto meta_command_exit;
6476 pSession->nFilter = 0;
6477 sqlite3session_table_filter(pSession->p, session_filter, pSession);
6478 p->nSession++;
6479 pSession->zName = sqlite3_mprintf("%s", zName);
6480 }else
6481 /* If no command name matches, show a syntax error */
6482 session_syntax_error:
6483 session_help(p);
6484 }else
6485 #endif
6487 #ifdef SQLITE_DEBUG
6488 /* Undocumented commands for internal testing. Subject to change
6489 ** without notice. */
6490 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6491 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6492 int i, v;
6493 for(i=1; i<nArg; i++){
6494 v = booleanValue(azArg[i]);
6495 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
6498 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6499 int i; sqlite3_int64 v;
6500 for(i=1; i<nArg; i++){
6501 char zBuf[200];
6502 v = integerValue(azArg[i]);
6503 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
6504 utf8_printf(p->out, "%s", zBuf);
6507 }else
6508 #endif
6510 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6511 int bIsInit = 0; /* True to initialize the SELFTEST table */
6512 int bVerbose = 0; /* Verbose output */
6513 int bSelftestExists; /* True if SELFTEST already exists */
6514 int i, k; /* Loop counters */
6515 int nTest = 0; /* Number of tests runs */
6516 int nErr = 0; /* Number of errors seen */
6517 ShellText str; /* Answer for a query */
6518 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
6520 open_db(p,0);
6521 for(i=1; i<nArg; i++){
6522 const char *z = azArg[i];
6523 if( z[0]=='-' && z[1]=='-' ) z++;
6524 if( strcmp(z,"-init")==0 ){
6525 bIsInit = 1;
6526 }else
6527 if( strcmp(z,"-v")==0 ){
6528 bVerbose++;
6529 }else
6531 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6532 azArg[i], azArg[0]);
6533 raw_printf(stderr, "Should be one of: --init -v\n");
6534 rc = 1;
6535 goto meta_command_exit;
6538 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6539 != SQLITE_OK ){
6540 bSelftestExists = 0;
6541 }else{
6542 bSelftestExists = 1;
6544 if( bIsInit ){
6545 createSelftestTable(p);
6546 bSelftestExists = 1;
6548 initText(&str);
6549 appendText(&str, "x", 0);
6550 for(k=bSelftestExists; k>=0; k--){
6551 if( k==1 ){
6552 rc = sqlite3_prepare_v2(p->db,
6553 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6554 -1, &pStmt, 0);
6555 }else{
6556 rc = sqlite3_prepare_v2(p->db,
6557 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6558 " (1,'run','PRAGMA integrity_check','ok')",
6559 -1, &pStmt, 0);
6561 if( rc ){
6562 raw_printf(stderr, "Error querying the selftest table\n");
6563 rc = 1;
6564 sqlite3_finalize(pStmt);
6565 goto meta_command_exit;
6567 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6568 int tno = sqlite3_column_int(pStmt, 0);
6569 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6570 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6571 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
6573 k = 0;
6574 if( bVerbose>0 ){
6575 char *zQuote = sqlite3_mprintf("%q", zSql);
6576 printf("%d: %s %s\n", tno, zOp, zSql);
6577 sqlite3_free(zQuote);
6579 if( strcmp(zOp,"memo")==0 ){
6580 utf8_printf(p->out, "%s\n", zSql);
6581 }else
6582 if( strcmp(zOp,"run")==0 ){
6583 char *zErrMsg = 0;
6584 str.n = 0;
6585 str.z[0] = 0;
6586 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6587 nTest++;
6588 if( bVerbose ){
6589 utf8_printf(p->out, "Result: %s\n", str.z);
6591 if( rc || zErrMsg ){
6592 nErr++;
6593 rc = 1;
6594 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6595 sqlite3_free(zErrMsg);
6596 }else if( strcmp(zAns,str.z)!=0 ){
6597 nErr++;
6598 rc = 1;
6599 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6600 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6602 }else
6604 utf8_printf(stderr,
6605 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6606 rc = 1;
6607 break;
6609 } /* End loop over rows of content from SELFTEST */
6610 sqlite3_finalize(pStmt);
6611 } /* End loop over k */
6612 freeText(&str);
6613 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6614 }else
6616 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
6617 if( nArg<2 || nArg>3 ){
6618 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
6619 rc = 1;
6621 if( nArg>=2 ){
6622 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
6623 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
6625 if( nArg>=3 ){
6626 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6627 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
6629 }else
6631 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6632 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6633 int i; /* Loop counter */
6634 int bSchema = 0; /* Also hash the schema */
6635 int bSeparate = 0; /* Hash each table separately */
6636 int iSize = 224; /* Hash algorithm to use */
6637 int bDebug = 0; /* Only show the query that would have run */
6638 sqlite3_stmt *pStmt; /* For querying tables names */
6639 char *zSql; /* SQL to be run */
6640 char *zSep; /* Separator */
6641 ShellText sSql; /* Complete SQL for the query to run the hash */
6642 ShellText sQuery; /* Set of queries used to read all content */
6643 open_db(p, 0);
6644 for(i=1; i<nArg; i++){
6645 const char *z = azArg[i];
6646 if( z[0]=='-' ){
6647 z++;
6648 if( z[0]=='-' ) z++;
6649 if( strcmp(z,"schema")==0 ){
6650 bSchema = 1;
6651 }else
6652 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6653 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6655 iSize = atoi(&z[5]);
6656 }else
6657 if( strcmp(z,"debug")==0 ){
6658 bDebug = 1;
6659 }else
6661 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6662 azArg[i], azArg[0]);
6663 raw_printf(stderr, "Should be one of: --schema"
6664 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6665 rc = 1;
6666 goto meta_command_exit;
6668 }else if( zLike ){
6669 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6670 rc = 1;
6671 goto meta_command_exit;
6672 }else{
6673 zLike = z;
6674 bSeparate = 1;
6675 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
6678 if( bSchema ){
6679 zSql = "SELECT lower(name) FROM sqlite_master"
6680 " WHERE type='table' AND coalesce(rootpage,0)>1"
6681 " UNION ALL SELECT 'sqlite_master'"
6682 " ORDER BY 1 collate nocase";
6683 }else{
6684 zSql = "SELECT lower(name) FROM sqlite_master"
6685 " WHERE type='table' AND coalesce(rootpage,0)>1"
6686 " AND name NOT LIKE 'sqlite_%'"
6687 " ORDER BY 1 collate nocase";
6689 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6690 initText(&sQuery);
6691 initText(&sSql);
6692 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6693 zSep = "VALUES(";
6694 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6695 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6696 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6697 if( strncmp(zTab, "sqlite_",7)!=0 ){
6698 appendText(&sQuery,"SELECT * FROM ", 0);
6699 appendText(&sQuery,zTab,'"');
6700 appendText(&sQuery," NOT INDEXED;", 0);
6701 }else if( strcmp(zTab, "sqlite_master")==0 ){
6702 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6703 " ORDER BY name;", 0);
6704 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6705 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6706 " ORDER BY name;", 0);
6707 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6708 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6709 " ORDER BY tbl,idx;", 0);
6710 }else if( strcmp(zTab, "sqlite_stat3")==0
6711 || strcmp(zTab, "sqlite_stat4")==0 ){
6712 appendText(&sQuery, "SELECT * FROM ", 0);
6713 appendText(&sQuery, zTab, 0);
6714 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6716 appendText(&sSql, zSep, 0);
6717 appendText(&sSql, sQuery.z, '\'');
6718 sQuery.n = 0;
6719 appendText(&sSql, ",", 0);
6720 appendText(&sSql, zTab, '\'');
6721 zSep = "),(";
6723 sqlite3_finalize(pStmt);
6724 if( bSeparate ){
6725 zSql = sqlite3_mprintf(
6726 "%s))"
6727 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6728 " FROM [sha3sum$query]",
6729 sSql.z, iSize);
6730 }else{
6731 zSql = sqlite3_mprintf(
6732 "%s))"
6733 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6734 " FROM [sha3sum$query]",
6735 sSql.z, iSize);
6737 freeText(&sQuery);
6738 freeText(&sSql);
6739 if( bDebug ){
6740 utf8_printf(p->out, "%s\n", zSql);
6741 }else{
6742 shell_exec(p->db, zSql, shell_callback, p, 0);
6744 sqlite3_free(zSql);
6745 }else
6747 if( c=='s'
6748 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6750 char *zCmd;
6751 int i, x;
6752 if( nArg<2 ){
6753 raw_printf(stderr, "Usage: .system COMMAND\n");
6754 rc = 1;
6755 goto meta_command_exit;
6757 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6758 for(i=2; i<nArg; i++){
6759 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6760 zCmd, azArg[i]);
6762 x = system(zCmd);
6763 sqlite3_free(zCmd);
6764 if( x ) raw_printf(stderr, "System command returns %d\n", x);
6765 }else
6767 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
6768 static const char *azBool[] = { "off", "on", "trigger", "full"};
6769 int i;
6770 if( nArg!=1 ){
6771 raw_printf(stderr, "Usage: .show\n");
6772 rc = 1;
6773 goto meta_command_exit;
6775 utf8_printf(p->out, "%12.12s: %s\n","echo",
6776 azBool[ShellHasFlag(p, SHFLG_Echo)]);
6777 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6778 utf8_printf(p->out, "%12.12s: %s\n","explain",
6779 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6780 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6781 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6782 utf8_printf(p->out, "%12.12s: ", "nullvalue");
6783 output_c_string(p->out, p->nullValue);
6784 raw_printf(p->out, "\n");
6785 utf8_printf(p->out,"%12.12s: %s\n","output",
6786 strlen30(p->outfile) ? p->outfile : "stdout");
6787 utf8_printf(p->out,"%12.12s: ", "colseparator");
6788 output_c_string(p->out, p->colSeparator);
6789 raw_printf(p->out, "\n");
6790 utf8_printf(p->out,"%12.12s: ", "rowseparator");
6791 output_c_string(p->out, p->rowSeparator);
6792 raw_printf(p->out, "\n");
6793 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6794 utf8_printf(p->out, "%12.12s: ", "width");
6795 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6796 raw_printf(p->out, "%d ", p->colWidth[i]);
6798 raw_printf(p->out, "\n");
6799 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6800 p->zDbFilename ? p->zDbFilename : "");
6801 }else
6803 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6804 if( nArg==2 ){
6805 p->statsOn = booleanValue(azArg[1]);
6806 }else if( nArg==1 ){
6807 display_stats(p->db, p, 0);
6808 }else{
6809 raw_printf(stderr, "Usage: .stats ?on|off?\n");
6810 rc = 1;
6812 }else
6814 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6815 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6816 || strncmp(azArg[0], "indexes", n)==0) )
6818 sqlite3_stmt *pStmt;
6819 char **azResult;
6820 int nRow, nAlloc;
6821 int ii;
6822 ShellText s;
6823 initText(&s);
6824 open_db(p, 0);
6825 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6826 if( rc ) return shellDatabaseError(p->db);
6828 if( nArg>2 && c=='i' ){
6829 /* It is an historical accident that the .indexes command shows an error
6830 ** when called with the wrong number of arguments whereas the .tables
6831 ** command does not. */
6832 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6833 rc = 1;
6834 goto meta_command_exit;
6836 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6837 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6838 if( zDbName==0 ) continue;
6839 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6840 if( sqlite3_stricmp(zDbName, "main")==0 ){
6841 appendText(&s, "SELECT name FROM ", 0);
6842 }else{
6843 appendText(&s, "SELECT ", 0);
6844 appendText(&s, zDbName, '\'');
6845 appendText(&s, "||'.'||name FROM ", 0);
6847 appendText(&s, zDbName, '"');
6848 appendText(&s, ".sqlite_master ", 0);
6849 if( c=='t' ){
6850 appendText(&s," WHERE type IN ('table','view')"
6851 " AND name NOT LIKE 'sqlite_%'"
6852 " AND name LIKE ?1", 0);
6853 }else{
6854 appendText(&s," WHERE type='index'"
6855 " AND tbl_name LIKE ?1", 0);
6858 rc = sqlite3_finalize(pStmt);
6859 appendText(&s, " ORDER BY 1", 0);
6860 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6861 freeText(&s);
6862 if( rc ) return shellDatabaseError(p->db);
6864 /* Run the SQL statement prepared by the above block. Store the results
6865 ** as an array of nul-terminated strings in azResult[]. */
6866 nRow = nAlloc = 0;
6867 azResult = 0;
6868 if( nArg>1 ){
6869 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6870 }else{
6871 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6873 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6874 if( nRow>=nAlloc ){
6875 char **azNew;
6876 int n2 = nAlloc*2 + 10;
6877 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6878 if( azNew==0 ){
6879 rc = shellNomemError();
6880 break;
6882 nAlloc = n2;
6883 azResult = azNew;
6885 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6886 if( 0==azResult[nRow] ){
6887 rc = shellNomemError();
6888 break;
6890 nRow++;
6892 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6893 rc = shellDatabaseError(p->db);
6896 /* Pretty-print the contents of array azResult[] to the output */
6897 if( rc==0 && nRow>0 ){
6898 int len, maxlen = 0;
6899 int i, j;
6900 int nPrintCol, nPrintRow;
6901 for(i=0; i<nRow; i++){
6902 len = strlen30(azResult[i]);
6903 if( len>maxlen ) maxlen = len;
6905 nPrintCol = 80/(maxlen+2);
6906 if( nPrintCol<1 ) nPrintCol = 1;
6907 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6908 for(i=0; i<nPrintRow; i++){
6909 for(j=i; j<nRow; j+=nPrintRow){
6910 char *zSp = j<nPrintRow ? "" : " ";
6911 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6912 azResult[j] ? azResult[j]:"");
6914 raw_printf(p->out, "\n");
6918 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6919 sqlite3_free(azResult);
6920 }else
6922 /* Begin redirecting output to the file "testcase-out.txt" */
6923 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6924 output_reset(p);
6925 p->out = output_file_open("testcase-out.txt");
6926 if( p->out==0 ){
6927 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
6929 if( nArg>=2 ){
6930 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6931 }else{
6932 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6934 }else
6936 #ifndef SQLITE_UNTESTABLE
6937 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
6938 static const struct {
6939 const char *zCtrlName; /* Name of a test-control option */
6940 int ctrlCode; /* Integer code for that option */
6941 const char *zUsage; /* Usage notes */
6942 } aCtrl[] = {
6943 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
6944 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
6945 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
6946 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
6947 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
6948 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
6949 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
6950 #ifdef SQLITE_N_KEYWORD
6951 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" },
6952 #endif
6953 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
6954 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
6955 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
6956 #ifdef YYCOVERAGE
6957 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
6958 #endif
6959 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
6960 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
6961 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
6962 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
6963 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
6965 int testctrl = -1;
6966 int iCtrl = -1;
6967 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
6968 int isOk = 0;
6969 int i, n2;
6970 const char *zCmd = 0;
6972 open_db(p, 0);
6973 zCmd = nArg>=2 ? azArg[1] : "help";
6975 /* The argument can optionally begin with "-" or "--" */
6976 if( zCmd[0]=='-' && zCmd[1] ){
6977 zCmd++;
6978 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
6981 /* --help lists all test-controls */
6982 if( strcmp(zCmd,"help")==0 ){
6983 utf8_printf(p->out, "Available test-controls:\n");
6984 for(i=0; i<ArraySize(aCtrl); i++){
6985 utf8_printf(p->out, " .testctrl %s %s\n",
6986 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
6988 rc = 1;
6989 goto meta_command_exit;
6992 /* convert testctrl text option to value. allow any unique prefix
6993 ** of the option name, or a numerical value. */
6994 n2 = strlen30(zCmd);
6995 for(i=0; i<ArraySize(aCtrl); i++){
6996 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
6997 if( testctrl<0 ){
6998 testctrl = aCtrl[i].ctrlCode;
6999 iCtrl = i;
7000 }else{
7001 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7002 "Use \".testctrl --help\" for help\n", zCmd);
7003 rc = 1;
7004 goto meta_command_exit;
7008 if( testctrl<0 ){
7009 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7010 "Use \".testctrl --help\" for help\n", zCmd);
7011 }else{
7012 switch(testctrl){
7014 /* sqlite3_test_control(int, db, int) */
7015 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7016 case SQLITE_TESTCTRL_RESERVE:
7017 if( nArg==3 ){
7018 int opt = (int)strtol(azArg[2], 0, 0);
7019 rc2 = sqlite3_test_control(testctrl, p->db, opt);
7020 isOk = 3;
7022 break;
7024 /* sqlite3_test_control(int) */
7025 case SQLITE_TESTCTRL_PRNG_SAVE:
7026 case SQLITE_TESTCTRL_PRNG_RESTORE:
7027 case SQLITE_TESTCTRL_PRNG_RESET:
7028 case SQLITE_TESTCTRL_BYTEORDER:
7029 if( nArg==2 ){
7030 rc2 = sqlite3_test_control(testctrl);
7031 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
7033 break;
7035 /* sqlite3_test_control(int, uint) */
7036 case SQLITE_TESTCTRL_PENDING_BYTE:
7037 if( nArg==3 ){
7038 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7039 rc2 = sqlite3_test_control(testctrl, opt);
7040 isOk = 3;
7042 break;
7044 /* sqlite3_test_control(int, int) */
7045 case SQLITE_TESTCTRL_ASSERT:
7046 case SQLITE_TESTCTRL_ALWAYS:
7047 if( nArg==3 ){
7048 int opt = booleanValue(azArg[2]);
7049 rc2 = sqlite3_test_control(testctrl, opt);
7050 isOk = 1;
7052 break;
7054 /* sqlite3_test_control(int, int) */
7055 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
7056 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7057 if( nArg==3 ){
7058 int opt = booleanValue(azArg[2]);
7059 rc2 = sqlite3_test_control(testctrl, opt);
7060 isOk = 3;
7062 break;
7064 /* sqlite3_test_control(int, char *) */
7065 #ifdef SQLITE_N_KEYWORD
7066 case SQLITE_TESTCTRL_ISKEYWORD:
7067 if( nArg==3 ){
7068 const char *opt = azArg[2];
7069 rc2 = sqlite3_test_control(testctrl, opt);
7070 isOk = 1;
7072 break;
7073 #endif
7075 case SQLITE_TESTCTRL_IMPOSTER:
7076 if( nArg==5 ){
7077 rc2 = sqlite3_test_control(testctrl, p->db,
7078 azArg[2],
7079 integerValue(azArg[3]),
7080 integerValue(azArg[4]));
7081 isOk = 3;
7083 break;
7085 #ifdef YYCOVERAGE
7086 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7087 if( nArg==2 ){
7088 sqlite3_test_control(testctrl, p->out);
7089 isOk = 3;
7091 #endif
7094 if( isOk==0 && iCtrl>=0 ){
7095 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7096 rc = 1;
7097 }else if( isOk==1 ){
7098 raw_printf(p->out, "%d\n", rc2);
7099 }else if( isOk==2 ){
7100 raw_printf(p->out, "0x%08x\n", rc2);
7102 }else
7103 #endif /* !defined(SQLITE_UNTESTABLE) */
7105 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7106 open_db(p, 0);
7107 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7108 }else
7110 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7111 if( nArg==2 ){
7112 enableTimer = booleanValue(azArg[1]);
7113 if( enableTimer && !HAS_TIMER ){
7114 raw_printf(stderr, "Error: timer not available on this system.\n");
7115 enableTimer = 0;
7117 }else{
7118 raw_printf(stderr, "Usage: .timer on|off\n");
7119 rc = 1;
7121 }else
7123 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7124 open_db(p, 0);
7125 if( nArg!=2 ){
7126 raw_printf(stderr, "Usage: .trace FILE|off\n");
7127 rc = 1;
7128 goto meta_command_exit;
7130 output_file_close(p->traceOut);
7131 p->traceOut = output_file_open(azArg[1]);
7132 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7133 if( p->traceOut==0 ){
7134 sqlite3_trace_v2(p->db, 0, 0, 0);
7135 }else{
7136 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7138 #endif
7139 }else
7141 #if SQLITE_USER_AUTHENTICATION
7142 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7143 if( nArg<2 ){
7144 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7145 rc = 1;
7146 goto meta_command_exit;
7148 open_db(p, 0);
7149 if( strcmp(azArg[1],"login")==0 ){
7150 if( nArg!=4 ){
7151 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7152 rc = 1;
7153 goto meta_command_exit;
7155 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
7156 if( rc ){
7157 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7158 rc = 1;
7160 }else if( strcmp(azArg[1],"add")==0 ){
7161 if( nArg!=5 ){
7162 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7163 rc = 1;
7164 goto meta_command_exit;
7166 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
7167 booleanValue(azArg[4]));
7168 if( rc ){
7169 raw_printf(stderr, "User-Add failed: %d\n", rc);
7170 rc = 1;
7172 }else if( strcmp(azArg[1],"edit")==0 ){
7173 if( nArg!=5 ){
7174 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7175 rc = 1;
7176 goto meta_command_exit;
7178 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
7179 booleanValue(azArg[4]));
7180 if( rc ){
7181 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7182 rc = 1;
7184 }else if( strcmp(azArg[1],"delete")==0 ){
7185 if( nArg!=3 ){
7186 raw_printf(stderr, "Usage: .user delete USER\n");
7187 rc = 1;
7188 goto meta_command_exit;
7190 rc = sqlite3_user_delete(p->db, azArg[2]);
7191 if( rc ){
7192 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7193 rc = 1;
7195 }else{
7196 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7197 rc = 1;
7198 goto meta_command_exit;
7200 }else
7201 #endif /* SQLITE_USER_AUTHENTICATION */
7203 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7204 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7205 sqlite3_libversion(), sqlite3_sourceid());
7206 }else
7208 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7209 const char *zDbName = nArg==2 ? azArg[1] : "main";
7210 sqlite3_vfs *pVfs = 0;
7211 if( p->db ){
7212 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7213 if( pVfs ){
7214 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7215 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7216 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7217 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7220 }else
7222 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7223 sqlite3_vfs *pVfs;
7224 sqlite3_vfs *pCurrent = 0;
7225 if( p->db ){
7226 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7228 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7229 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7230 pVfs==pCurrent ? " <--- CURRENT" : "");
7231 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7232 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7233 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7234 if( pVfs->pNext ){
7235 raw_printf(p->out, "-----------------------------------\n");
7238 }else
7240 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7241 const char *zDbName = nArg==2 ? azArg[1] : "main";
7242 char *zVfsName = 0;
7243 if( p->db ){
7244 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7245 if( zVfsName ){
7246 utf8_printf(p->out, "%s\n", zVfsName);
7247 sqlite3_free(zVfsName);
7250 }else
7252 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7253 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7254 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7255 }else
7256 #endif
7258 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7259 int j;
7260 assert( nArg<=ArraySize(azArg) );
7261 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7262 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7264 }else
7267 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7268 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7269 rc = 1;
7272 meta_command_exit:
7273 if( p->outCount ){
7274 p->outCount--;
7275 if( p->outCount==0 ) output_reset(p);
7277 return rc;
7281 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7282 ** of string z[].
7284 static int line_contains_semicolon(const char *z, int N){
7285 int i;
7286 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7287 return 0;
7291 ** Test to see if a line consists entirely of whitespace.
7293 static int _all_whitespace(const char *z){
7294 for(; *z; z++){
7295 if( IsSpace(z[0]) ) continue;
7296 if( *z=='/' && z[1]=='*' ){
7297 z += 2;
7298 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7299 if( *z==0 ) return 0;
7300 z++;
7301 continue;
7303 if( *z=='-' && z[1]=='-' ){
7304 z += 2;
7305 while( *z && *z!='\n' ){ z++; }
7306 if( *z==0 ) return 1;
7307 continue;
7309 return 0;
7311 return 1;
7315 ** Return TRUE if the line typed in is an SQL command terminator other
7316 ** than a semi-colon. The SQL Server style "go" command is understood
7317 ** as is the Oracle "/".
7319 static int line_is_command_terminator(const char *zLine){
7320 while( IsSpace(zLine[0]) ){ zLine++; };
7321 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7322 return 1; /* Oracle */
7324 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7325 && _all_whitespace(&zLine[2]) ){
7326 return 1; /* SQL Server */
7328 return 0;
7332 ** Return true if zSql is a complete SQL statement. Return false if it
7333 ** ends in the middle of a string literal or C-style comment.
7335 static int line_is_complete(char *zSql, int nSql){
7336 int rc;
7337 if( zSql==0 ) return 1;
7338 zSql[nSql] = ';';
7339 zSql[nSql+1] = 0;
7340 rc = sqlite3_complete(zSql);
7341 zSql[nSql] = 0;
7342 return rc;
7346 ** Run a single line of SQL
7348 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7349 int rc;
7350 char *zErrMsg = 0;
7352 open_db(p, 0);
7353 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7354 BEGIN_TIMER;
7355 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
7356 END_TIMER;
7357 if( rc || zErrMsg ){
7358 char zPrefix[100];
7359 if( in!=0 || !stdin_is_interactive ){
7360 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7361 "Error: near line %d:", startline);
7362 }else{
7363 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7365 if( zErrMsg!=0 ){
7366 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7367 sqlite3_free(zErrMsg);
7368 zErrMsg = 0;
7369 }else{
7370 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7372 return 1;
7373 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7374 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7375 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7377 return 0;
7382 ** Read input from *in and process it. If *in==0 then input
7383 ** is interactive - the user is typing it it. Otherwise, input
7384 ** is coming from a file or device. A prompt is issued and history
7385 ** is saved only if input is interactive. An interrupt signal will
7386 ** cause this routine to exit immediately, unless input is interactive.
7388 ** Return the number of errors.
7390 static int process_input(ShellState *p, FILE *in){
7391 char *zLine = 0; /* A single input line */
7392 char *zSql = 0; /* Accumulated SQL text */
7393 int nLine; /* Length of current line */
7394 int nSql = 0; /* Bytes of zSql[] used */
7395 int nAlloc = 0; /* Allocated zSql[] space */
7396 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7397 int rc; /* Error code */
7398 int errCnt = 0; /* Number of errors seen */
7399 int lineno = 0; /* Current line number */
7400 int startline = 0; /* Line number for start of current input */
7402 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7403 fflush(p->out);
7404 zLine = one_input_line(in, zLine, nSql>0);
7405 if( zLine==0 ){
7406 /* End of input */
7407 if( in==0 && stdin_is_interactive ) printf("\n");
7408 break;
7410 if( seenInterrupt ){
7411 if( in!=0 ) break;
7412 seenInterrupt = 0;
7414 lineno++;
7415 if( nSql==0 && _all_whitespace(zLine) ){
7416 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7417 continue;
7419 if( zLine && zLine[0]=='.' && nSql==0 ){
7420 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7421 rc = do_meta_command(zLine, p);
7422 if( rc==2 ){ /* exit requested */
7423 break;
7424 }else if( rc ){
7425 errCnt++;
7427 continue;
7429 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
7430 memcpy(zLine,";",2);
7432 nLine = strlen30(zLine);
7433 if( nSql+nLine+2>=nAlloc ){
7434 nAlloc = nSql+nLine+100;
7435 zSql = realloc(zSql, nAlloc);
7436 if( zSql==0 ){
7437 raw_printf(stderr, "Error: out of memory\n");
7438 exit(1);
7441 nSqlPrior = nSql;
7442 if( nSql==0 ){
7443 int i;
7444 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
7445 assert( nAlloc>0 && zSql!=0 );
7446 memcpy(zSql, zLine+i, nLine+1-i);
7447 startline = lineno;
7448 nSql = nLine-i;
7449 }else{
7450 zSql[nSql++] = '\n';
7451 memcpy(zSql+nSql, zLine, nLine+1);
7452 nSql += nLine;
7454 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
7455 && sqlite3_complete(zSql) ){
7456 errCnt += runOneSqlLine(p, zSql, in, startline);
7457 nSql = 0;
7458 if( p->outCount ){
7459 output_reset(p);
7460 p->outCount = 0;
7462 }else if( nSql && _all_whitespace(zSql) ){
7463 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
7464 nSql = 0;
7467 if( nSql && !_all_whitespace(zSql) ){
7468 runOneSqlLine(p, zSql, in, startline);
7470 free(zSql);
7471 free(zLine);
7472 return errCnt>0;
7476 ** Return a pathname which is the user's home directory. A
7477 ** 0 return indicates an error of some kind.
7479 static char *find_home_dir(int clearFlag){
7480 static char *home_dir = NULL;
7481 if( clearFlag ){
7482 free(home_dir);
7483 home_dir = 0;
7484 return 0;
7486 if( home_dir ) return home_dir;
7488 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7489 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7491 struct passwd *pwent;
7492 uid_t uid = getuid();
7493 if( (pwent=getpwuid(uid)) != NULL) {
7494 home_dir = pwent->pw_dir;
7497 #endif
7499 #if defined(_WIN32_WCE)
7500 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7502 home_dir = "/";
7503 #else
7505 #if defined(_WIN32) || defined(WIN32)
7506 if (!home_dir) {
7507 home_dir = getenv("USERPROFILE");
7509 #endif
7511 if (!home_dir) {
7512 home_dir = getenv("HOME");
7515 #if defined(_WIN32) || defined(WIN32)
7516 if (!home_dir) {
7517 char *zDrive, *zPath;
7518 int n;
7519 zDrive = getenv("HOMEDRIVE");
7520 zPath = getenv("HOMEPATH");
7521 if( zDrive && zPath ){
7522 n = strlen30(zDrive) + strlen30(zPath) + 1;
7523 home_dir = malloc( n );
7524 if( home_dir==0 ) return 0;
7525 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7526 return home_dir;
7528 home_dir = "c:\\";
7530 #endif
7532 #endif /* !_WIN32_WCE */
7534 if( home_dir ){
7535 int n = strlen30(home_dir) + 1;
7536 char *z = malloc( n );
7537 if( z ) memcpy(z, home_dir, n);
7538 home_dir = z;
7541 return home_dir;
7545 ** Read input from the file given by sqliterc_override. Or if that
7546 ** parameter is NULL, take input from ~/.sqliterc
7548 ** Returns the number of errors.
7550 static void process_sqliterc(
7551 ShellState *p, /* Configuration data */
7552 const char *sqliterc_override /* Name of config file. NULL to use default */
7554 char *home_dir = NULL;
7555 const char *sqliterc = sqliterc_override;
7556 char *zBuf = 0;
7557 FILE *in = NULL;
7559 if (sqliterc == NULL) {
7560 home_dir = find_home_dir(0);
7561 if( home_dir==0 ){
7562 raw_printf(stderr, "-- warning: cannot find home directory;"
7563 " cannot read ~/.sqliterc\n");
7564 return;
7566 sqlite3_initialize();
7567 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7568 sqliterc = zBuf;
7570 in = fopen(sqliterc,"rb");
7571 if( in ){
7572 if( stdin_is_interactive ){
7573 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
7575 process_input(p,in);
7576 fclose(in);
7578 sqlite3_free(zBuf);
7582 ** Show available command line options
7584 static const char zOptions[] =
7585 " -ascii set output mode to 'ascii'\n"
7586 " -bail stop after hitting an error\n"
7587 " -batch force batch I/O\n"
7588 " -column set output mode to 'column'\n"
7589 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7590 " -csv set output mode to 'csv'\n"
7591 " -echo print commands before execution\n"
7592 " -init FILENAME read/process named file\n"
7593 " -[no]header turn headers on or off\n"
7594 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7595 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7596 #endif
7597 " -help show this message\n"
7598 " -html set output mode to HTML\n"
7599 " -interactive force interactive I/O\n"
7600 " -line set output mode to 'line'\n"
7601 " -list set output mode to 'list'\n"
7602 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7603 " -mmap N default mmap size set to N\n"
7604 #ifdef SQLITE_ENABLE_MULTIPLEX
7605 " -multiplex enable the multiplexor VFS\n"
7606 #endif
7607 " -newline SEP set output row separator. Default: '\\n'\n"
7608 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7609 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7610 " -quote set output mode to 'quote'\n"
7611 " -separator SEP set output column separator. Default: '|'\n"
7612 " -stats print memory stats before each finalize\n"
7613 " -version show SQLite version\n"
7614 " -vfs NAME use NAME as the default VFS\n"
7615 #ifdef SQLITE_ENABLE_VFSTRACE
7616 " -vfstrace enable tracing of all VFS calls\n"
7617 #endif
7619 static void usage(int showDetail){
7620 utf8_printf(stderr,
7621 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7622 "FILENAME is the name of an SQLite database. A new database is created\n"
7623 "if the file does not previously exist.\n", Argv0);
7624 if( showDetail ){
7625 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
7626 }else{
7627 raw_printf(stderr, "Use the -help option for additional information\n");
7629 exit(1);
7633 ** Initialize the state information in data
7635 static void main_init(ShellState *data) {
7636 memset(data, 0, sizeof(*data));
7637 data->normalMode = data->cMode = data->mode = MODE_List;
7638 data->autoExplain = 1;
7639 memcpy(data->colSeparator,SEP_Column, 2);
7640 memcpy(data->rowSeparator,SEP_Row, 2);
7641 data->showHeader = 0;
7642 data->shellFlgs = SHFLG_Lookaside;
7643 sqlite3_config(SQLITE_CONFIG_URI, 1);
7644 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
7645 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
7646 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7647 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
7651 ** Output text to the console in a font that attracts extra attention.
7653 #ifdef _WIN32
7654 static void printBold(const char *zText){
7655 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7656 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7657 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7658 SetConsoleTextAttribute(out,
7659 FOREGROUND_RED|FOREGROUND_INTENSITY
7661 printf("%s", zText);
7662 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
7664 #else
7665 static void printBold(const char *zText){
7666 printf("\033[1m%s\033[0m", zText);
7668 #endif
7671 ** Get the argument to an --option. Throw an error and die if no argument
7672 ** is available.
7674 static char *cmdline_option_value(int argc, char **argv, int i){
7675 if( i==argc ){
7676 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
7677 argv[0], argv[argc-1]);
7678 exit(1);
7680 return argv[i];
7683 #ifndef SQLITE_SHELL_IS_UTF8
7684 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7685 # define SQLITE_SHELL_IS_UTF8 (0)
7686 # else
7687 # define SQLITE_SHELL_IS_UTF8 (1)
7688 # endif
7689 #endif
7691 #if SQLITE_SHELL_IS_UTF8
7692 int SQLITE_CDECL main(int argc, char **argv){
7693 #else
7694 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7695 char **argv;
7696 #endif
7697 char *zErrMsg = 0;
7698 ShellState data;
7699 const char *zInitFile = 0;
7700 int i;
7701 int rc = 0;
7702 int warnInmemoryDb = 0;
7703 int readStdin = 1;
7704 int nCmd = 0;
7705 char **azCmd = 0;
7707 setBinaryMode(stdin, 0);
7708 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7709 stdin_is_interactive = isatty(0);
7710 stdout_is_console = isatty(1);
7712 #if USE_SYSTEM_SQLITE+0!=1
7713 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
7714 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7715 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7716 exit(1);
7718 #endif
7719 main_init(&data);
7720 #if !SQLITE_SHELL_IS_UTF8
7721 sqlite3_initialize();
7722 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7723 if( argv==0 ){
7724 raw_printf(stderr, "out of memory\n");
7725 exit(1);
7727 for(i=0; i<argc; i++){
7728 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7729 if( argv[i]==0 ){
7730 raw_printf(stderr, "out of memory\n");
7731 exit(1);
7734 #endif
7735 assert( argc>=1 && argv && argv[0] );
7736 Argv0 = argv[0];
7738 /* Make sure we have a valid signal handler early, before anything
7739 ** else is done.
7741 #ifdef SIGINT
7742 signal(SIGINT, interrupt_handler);
7743 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
7744 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
7745 #endif
7747 #ifdef SQLITE_SHELL_DBNAME_PROC
7749 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7750 ** of a C-function that will provide the name of the database file. Use
7751 ** this compile-time option to embed this shell program in larger
7752 ** applications. */
7753 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7754 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7755 warnInmemoryDb = 0;
7757 #endif
7759 /* Do an initial pass through the command-line argument to locate
7760 ** the name of the database file, the name of the initialization file,
7761 ** the size of the alternative malloc heap,
7762 ** and the first command to execute.
7764 for(i=1; i<argc; i++){
7765 char *z;
7766 z = argv[i];
7767 if( z[0]!='-' ){
7768 if( data.zDbFilename==0 ){
7769 data.zDbFilename = z;
7770 }else{
7771 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7772 ** mean that nothing is read from stdin */
7773 readStdin = 0;
7774 nCmd++;
7775 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7776 if( azCmd==0 ){
7777 raw_printf(stderr, "out of memory\n");
7778 exit(1);
7780 azCmd[nCmd-1] = z;
7783 if( z[1]=='-' ) z++;
7784 if( strcmp(z,"-separator")==0
7785 || strcmp(z,"-nullvalue")==0
7786 || strcmp(z,"-newline")==0
7787 || strcmp(z,"-cmd")==0
7789 (void)cmdline_option_value(argc, argv, ++i);
7790 }else if( strcmp(z,"-init")==0 ){
7791 zInitFile = cmdline_option_value(argc, argv, ++i);
7792 }else if( strcmp(z,"-batch")==0 ){
7793 /* Need to check for batch mode here to so we can avoid printing
7794 ** informational messages (like from process_sqliterc) before
7795 ** we do the actual processing of arguments later in a second pass.
7797 stdin_is_interactive = 0;
7798 }else if( strcmp(z,"-heap")==0 ){
7799 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7800 const char *zSize;
7801 sqlite3_int64 szHeap;
7803 zSize = cmdline_option_value(argc, argv, ++i);
7804 szHeap = integerValue(zSize);
7805 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7806 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7807 #else
7808 (void)cmdline_option_value(argc, argv, ++i);
7809 #endif
7810 }else if( strcmp(z,"-pagecache")==0 ){
7811 int n, sz;
7812 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7813 if( sz>70000 ) sz = 70000;
7814 if( sz<0 ) sz = 0;
7815 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7816 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7817 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7818 data.shellFlgs |= SHFLG_Pagecache;
7819 }else if( strcmp(z,"-lookaside")==0 ){
7820 int n, sz;
7821 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7822 if( sz<0 ) sz = 0;
7823 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7824 if( n<0 ) n = 0;
7825 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7826 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7827 #ifdef SQLITE_ENABLE_VFSTRACE
7828 }else if( strcmp(z,"-vfstrace")==0 ){
7829 extern int vfstrace_register(
7830 const char *zTraceName,
7831 const char *zOldVfsName,
7832 int (*xOut)(const char*,void*),
7833 void *pOutArg,
7834 int makeDefault
7836 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7837 #endif
7838 #ifdef SQLITE_ENABLE_MULTIPLEX
7839 }else if( strcmp(z,"-multiplex")==0 ){
7840 extern int sqlite3_multiple_initialize(const char*,int);
7841 sqlite3_multiplex_initialize(0, 1);
7842 #endif
7843 }else if( strcmp(z,"-mmap")==0 ){
7844 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7845 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7846 }else if( strcmp(z,"-vfs")==0 ){
7847 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7848 if( pVfs ){
7849 sqlite3_vfs_register(pVfs, 1);
7850 }else{
7851 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7852 exit(1);
7856 if( data.zDbFilename==0 ){
7857 #ifndef SQLITE_OMIT_MEMORYDB
7858 data.zDbFilename = ":memory:";
7859 warnInmemoryDb = argc==1;
7860 #else
7861 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7862 return 1;
7863 #endif
7865 data.out = stdout;
7867 /* Go ahead and open the database file if it already exists. If the
7868 ** file does not exist, delay opening it. This prevents empty database
7869 ** files from being created if a user mistypes the database name argument
7870 ** to the sqlite command-line tool.
7872 if( access(data.zDbFilename, 0)==0 ){
7873 open_db(&data, 0);
7876 /* Process the initialization file if there is one. If no -init option
7877 ** is given on the command line, look for a file named ~/.sqliterc and
7878 ** try to process it.
7880 process_sqliterc(&data,zInitFile);
7882 /* Make a second pass through the command-line argument and set
7883 ** options. This second pass is delayed until after the initialization
7884 ** file is processed so that the command-line arguments will override
7885 ** settings in the initialization file.
7887 for(i=1; i<argc; i++){
7888 char *z = argv[i];
7889 if( z[0]!='-' ) continue;
7890 if( z[1]=='-' ){ z++; }
7891 if( strcmp(z,"-init")==0 ){
7892 i++;
7893 }else if( strcmp(z,"-html")==0 ){
7894 data.mode = MODE_Html;
7895 }else if( strcmp(z,"-list")==0 ){
7896 data.mode = MODE_List;
7897 }else if( strcmp(z,"-quote")==0 ){
7898 data.mode = MODE_Quote;
7899 }else if( strcmp(z,"-line")==0 ){
7900 data.mode = MODE_Line;
7901 }else if( strcmp(z,"-column")==0 ){
7902 data.mode = MODE_Column;
7903 }else if( strcmp(z,"-csv")==0 ){
7904 data.mode = MODE_Csv;
7905 memcpy(data.colSeparator,",",2);
7906 }else if( strcmp(z,"-ascii")==0 ){
7907 data.mode = MODE_Ascii;
7908 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7909 SEP_Unit);
7910 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7911 SEP_Record);
7912 }else if( strcmp(z,"-separator")==0 ){
7913 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7914 "%s",cmdline_option_value(argc,argv,++i));
7915 }else if( strcmp(z,"-newline")==0 ){
7916 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7917 "%s",cmdline_option_value(argc,argv,++i));
7918 }else if( strcmp(z,"-nullvalue")==0 ){
7919 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
7920 "%s",cmdline_option_value(argc,argv,++i));
7921 }else if( strcmp(z,"-header")==0 ){
7922 data.showHeader = 1;
7923 }else if( strcmp(z,"-noheader")==0 ){
7924 data.showHeader = 0;
7925 }else if( strcmp(z,"-echo")==0 ){
7926 ShellSetFlag(&data, SHFLG_Echo);
7927 }else if( strcmp(z,"-eqp")==0 ){
7928 data.autoEQP = AUTOEQP_on;
7929 }else if( strcmp(z,"-eqpfull")==0 ){
7930 data.autoEQP = AUTOEQP_full;
7931 }else if( strcmp(z,"-stats")==0 ){
7932 data.statsOn = 1;
7933 }else if( strcmp(z,"-scanstats")==0 ){
7934 data.scanstatsOn = 1;
7935 }else if( strcmp(z,"-backslash")==0 ){
7936 /* Undocumented command-line option: -backslash
7937 ** Causes C-style backslash escapes to be evaluated in SQL statements
7938 ** prior to sending the SQL into SQLite. Useful for injecting
7939 ** crazy bytes in the middle of SQL statements for testing and debugging.
7941 ShellSetFlag(&data, SHFLG_Backslash);
7942 }else if( strcmp(z,"-bail")==0 ){
7943 bail_on_error = 1;
7944 }else if( strcmp(z,"-version")==0 ){
7945 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
7946 return 0;
7947 }else if( strcmp(z,"-interactive")==0 ){
7948 stdin_is_interactive = 1;
7949 }else if( strcmp(z,"-batch")==0 ){
7950 stdin_is_interactive = 0;
7951 }else if( strcmp(z,"-heap")==0 ){
7952 i++;
7953 }else if( strcmp(z,"-pagecache")==0 ){
7954 i+=2;
7955 }else if( strcmp(z,"-lookaside")==0 ){
7956 i+=2;
7957 }else if( strcmp(z,"-mmap")==0 ){
7958 i++;
7959 }else if( strcmp(z,"-vfs")==0 ){
7960 i++;
7961 #ifdef SQLITE_ENABLE_VFSTRACE
7962 }else if( strcmp(z,"-vfstrace")==0 ){
7963 i++;
7964 #endif
7965 #ifdef SQLITE_ENABLE_MULTIPLEX
7966 }else if( strcmp(z,"-multiplex")==0 ){
7967 i++;
7968 #endif
7969 }else if( strcmp(z,"-help")==0 ){
7970 usage(1);
7971 }else if( strcmp(z,"-cmd")==0 ){
7972 /* Run commands that follow -cmd first and separately from commands
7973 ** that simply appear on the command-line. This seems goofy. It would
7974 ** be better if all commands ran in the order that they appear. But
7975 ** we retain the goofy behavior for historical compatibility. */
7976 if( i==argc-1 ) break;
7977 z = cmdline_option_value(argc,argv,++i);
7978 if( z[0]=='.' ){
7979 rc = do_meta_command(z, &data);
7980 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
7981 }else{
7982 open_db(&data, 0);
7983 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7984 if( zErrMsg!=0 ){
7985 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7986 if( bail_on_error ) return rc!=0 ? rc : 1;
7987 }else if( rc!=0 ){
7988 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
7989 if( bail_on_error ) return rc;
7992 }else{
7993 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7994 raw_printf(stderr,"Use -help for a list of options.\n");
7995 return 1;
7997 data.cMode = data.mode;
8000 if( !readStdin ){
8001 /* Run all arguments that do not begin with '-' as if they were separate
8002 ** command-line inputs, except for the argToSkip argument which contains
8003 ** the database filename.
8005 for(i=0; i<nCmd; i++){
8006 if( azCmd[i][0]=='.' ){
8007 rc = do_meta_command(azCmd[i], &data);
8008 if( rc ) return rc==2 ? 0 : rc;
8009 }else{
8010 open_db(&data, 0);
8011 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
8012 if( zErrMsg!=0 ){
8013 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8014 return rc!=0 ? rc : 1;
8015 }else if( rc!=0 ){
8016 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8017 return rc;
8021 free(azCmd);
8022 }else{
8023 /* Run commands received from standard input
8025 if( stdin_is_interactive ){
8026 char *zHome;
8027 char *zHistory = 0;
8028 int nHistory;
8029 printf(
8030 "SQLite version %s %.19s\n" /*extra-version-info*/
8031 "Enter \".help\" for usage hints.\n",
8032 sqlite3_libversion(), sqlite3_sourceid()
8034 if( warnInmemoryDb ){
8035 printf("Connected to a ");
8036 printBold("transient in-memory database");
8037 printf(".\nUse \".open FILENAME\" to reopen on a "
8038 "persistent database.\n");
8040 zHome = find_home_dir(0);
8041 if( zHome ){
8042 nHistory = strlen30(zHome) + 20;
8043 if( (zHistory = malloc(nHistory))!=0 ){
8044 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8047 if( zHistory ){ shell_read_history(zHistory); }
8048 #if HAVE_READLINE || HAVE_EDITLINE
8049 rl_attempted_completion_function = readline_completion;
8050 #elif HAVE_LINENOISE
8051 linenoiseSetCompletionCallback(linenoise_completion);
8052 #endif
8053 rc = process_input(&data, 0);
8054 if( zHistory ){
8055 shell_stifle_history(2000);
8056 shell_write_history(zHistory);
8057 free(zHistory);
8059 }else{
8060 rc = process_input(&data, stdin);
8063 set_table_name(&data, 0);
8064 if( data.db ){
8065 session_close_all(&data);
8066 sqlite3_close(data.db);
8068 sqlite3_free(data.zFreeOnClose);
8069 find_home_dir(1);
8070 #if !SQLITE_SHELL_IS_UTF8
8071 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
8072 sqlite3_free(argv);
8073 #endif
8074 return rc;