blob: 70d6c0e5e70337015becd8c13c435f098d586911 [file] [log] [blame]
drh2ce15c32017-07-11 13:34:40 +00001/*
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.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
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
19
20/*
21** Warning pragmas copied from msvc.h in the core.
22*/
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) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
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
58
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>
69
70#if !defined(_WIN32) && !defined(WIN32)
71# include <signal.h>
72# if !defined(__RTP__) && !defined(_WRS_KERNEL)
73# include <pwd.h>
74# endif
75# include <unistd.h>
76# include <sys/types.h>
77#endif
78
79#if HAVE_READLINE
80# include <readline/readline.h>
81# include <readline/history.h>
82#endif
83
84#if HAVE_EDITLINE
85# include <editline/readline.h>
86#endif
87
88#if HAVE_EDITLINE || HAVE_READLINE
89
90# define shell_add_history(X) add_history(X)
91# define shell_read_history(X) read_history(X)
92# define shell_write_history(X) write_history(X)
93# define shell_stifle_history(X) stifle_history(X)
94# define shell_readline(X) readline(X)
95
96#elif HAVE_LINENOISE
97
98# include "linenoise.h"
99# define shell_add_history(X) linenoiseHistoryAdd(X)
100# define shell_read_history(X) linenoiseHistoryLoad(X)
101# define shell_write_history(X) linenoiseHistorySave(X)
102# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103# define shell_readline(X) linenoise(X)
104
105#else
106
107# define shell_read_history(X)
108# define shell_write_history(X)
109# define shell_stifle_history(X)
110
111# define SHELL_USE_LOCAL_GETLINE 1
112#endif
113
114
115#if defined(_WIN32) || defined(WIN32)
116# include <io.h>
117# include <fcntl.h>
118# define isatty(h) _isatty(h)
119# ifndef access
120# define access(f,m) _access((f),(m))
121# endif
122# undef popen
123# define popen _popen
124# undef pclose
125# define pclose _pclose
126#else
127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
129
130# if !defined(__RTP__) && !defined(_WRS_KERNEL)
131 /* popen and pclose are not C89 functions and so are
132 ** sometimes omitted from the <stdio.h> header */
133 extern FILE *popen(const char*,const char*);
134 extern int pclose(FILE*);
135# else
136# define SQLITE_OMIT_POPEN 1
137# endif
138#endif
139
140#if defined(_WIN32_WCE)
141/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
144 */
145#define isatty(x) 1
146#endif
147
148/* ctype macros that work with signed characters */
149#define IsSpace(X) isspace((unsigned char)X)
150#define IsDigit(X) isdigit((unsigned char)X)
151#define ToLower(X) (char)tolower((unsigned char)X)
152
153#if defined(_WIN32) || defined(WIN32)
154#include <windows.h>
155
156/* string conversion routines only needed on Win32 */
157extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
158extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
160extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
161#endif
162
163/* On Windows, we normally run with output mode of TEXT so that \n characters
164** are automatically translated into \r\n. However, this behavior needs
165** to be disabled in some cases (ex: when generating CSV output and when
166** rendering quoted strings that contain \n characters). The following
167** routines take care of that.
168*/
169#if defined(_WIN32) || defined(WIN32)
170static void setBinaryMode(FILE *file, int isOutput){
171 if( isOutput ) fflush(file);
172 _setmode(_fileno(file), _O_BINARY);
173}
174static void setTextMode(FILE *file, int isOutput){
175 if( isOutput ) fflush(file);
176 _setmode(_fileno(file), _O_TEXT);
177}
178#else
179# define setBinaryMode(X,Y)
180# define setTextMode(X,Y)
181#endif
182
183
184/* True if the timer is enabled */
185static int enableTimer = 0;
186
187/* Return the current wall-clock time */
188static sqlite3_int64 timeOfDay(void){
189 static sqlite3_vfs *clockVfs = 0;
190 sqlite3_int64 t;
191 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
192 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
193 clockVfs->xCurrentTimeInt64(clockVfs, &t);
194 }else{
195 double r;
196 clockVfs->xCurrentTime(clockVfs, &r);
197 t = (sqlite3_int64)(r*86400000.0);
198 }
199 return t;
200}
201
202#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
203#include <sys/time.h>
204#include <sys/resource.h>
205
206/* VxWorks does not support getrusage() as far as we can determine */
207#if defined(_WRS_KERNEL) || defined(__RTP__)
208struct rusage {
209 struct timeval ru_utime; /* user CPU time used */
210 struct timeval ru_stime; /* system CPU time used */
211};
212#define getrusage(A,B) memset(B,0,sizeof(*B))
213#endif
214
215/* Saved resource information for the beginning of an operation */
216static struct rusage sBegin; /* CPU time at start */
217static sqlite3_int64 iBegin; /* Wall-clock time at start */
218
219/*
220** Begin timing an operation
221*/
222static void beginTimer(void){
223 if( enableTimer ){
224 getrusage(RUSAGE_SELF, &sBegin);
225 iBegin = timeOfDay();
226 }
227}
228
229/* Return the difference of two time_structs in seconds */
230static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
231 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
232 (double)(pEnd->tv_sec - pStart->tv_sec);
233}
234
235/*
236** Print the timing results.
237*/
238static void endTimer(void){
239 if( enableTimer ){
240 sqlite3_int64 iEnd = timeOfDay();
241 struct rusage sEnd;
242 getrusage(RUSAGE_SELF, &sEnd);
243 printf("Run Time: real %.3f user %f sys %f\n",
244 (iEnd - iBegin)*0.001,
245 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
246 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
247 }
248}
249
250#define BEGIN_TIMER beginTimer()
251#define END_TIMER endTimer()
252#define HAS_TIMER 1
253
254#elif (defined(_WIN32) || defined(WIN32))
255
256/* Saved resource information for the beginning of an operation */
257static HANDLE hProcess;
258static FILETIME ftKernelBegin;
259static FILETIME ftUserBegin;
260static sqlite3_int64 ftWallBegin;
261typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
262 LPFILETIME, LPFILETIME);
263static GETPROCTIMES getProcessTimesAddr = NULL;
264
265/*
266** Check to see if we have timer support. Return 1 if necessary
267** support found (or found previously).
268*/
269static int hasTimer(void){
270 if( getProcessTimesAddr ){
271 return 1;
272 } else {
273 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274 ** versions. See if the version we are running on has it, and if it
275 ** does, save off a pointer to it and the current process handle.
276 */
277 hProcess = GetCurrentProcess();
278 if( hProcess ){
279 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
280 if( NULL != hinstLib ){
281 getProcessTimesAddr =
282 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
283 if( NULL != getProcessTimesAddr ){
284 return 1;
285 }
286 FreeLibrary(hinstLib);
287 }
288 }
289 }
290 return 0;
291}
292
293/*
294** Begin timing an operation
295*/
296static void beginTimer(void){
297 if( enableTimer && getProcessTimesAddr ){
298 FILETIME ftCreation, ftExit;
299 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
300 &ftKernelBegin,&ftUserBegin);
301 ftWallBegin = timeOfDay();
302 }
303}
304
305/* Return the difference of two FILETIME structs in seconds */
306static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
307 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
308 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
309 return (double) ((i64End - i64Start) / 10000000.0);
310}
311
312/*
313** Print the timing results.
314*/
315static void endTimer(void){
316 if( enableTimer && getProcessTimesAddr){
317 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
318 sqlite3_int64 ftWallEnd = timeOfDay();
319 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
320 printf("Run Time: real %.3f user %f sys %f\n",
321 (ftWallEnd - ftWallBegin)*0.001,
322 timeDiff(&ftUserBegin, &ftUserEnd),
323 timeDiff(&ftKernelBegin, &ftKernelEnd));
324 }
325}
326
327#define BEGIN_TIMER beginTimer()
328#define END_TIMER endTimer()
329#define HAS_TIMER hasTimer()
330
331#else
332#define BEGIN_TIMER
333#define END_TIMER
334#define HAS_TIMER 0
335#endif
336
337/*
338** Used to prevent warnings about unused parameters
339*/
340#define UNUSED_PARAMETER(x) (void)(x)
341
342/*
343** If the following flag is set, then command execution stops
344** at an error if we are not interactive.
345*/
346static int bail_on_error = 0;
347
348/*
349** Threat stdin as an interactive input if the following variable
350** is true. Otherwise, assume stdin is connected to a file or pipe.
351*/
352static int stdin_is_interactive = 1;
353
354/*
355** On Windows systems we have to know if standard output is a console
356** in order to translate UTF-8 into MBCS. The following variable is
357** true if translation is required.
358*/
359static int stdout_is_console = 1;
360
361/*
362** The following is the open SQLite database. We make a pointer
363** to this database a static variable so that it can be accessed
364** by the SIGINT handler to interrupt database processing.
365*/
366static sqlite3 *globalDb = 0;
367
368/*
369** True if an interrupt (Control-C) has been received.
370*/
371static volatile int seenInterrupt = 0;
372
373/*
374** This is the name of our program. It is set in main(), used
375** in a number of other places, mostly for error messages.
376*/
377static char *Argv0;
378
379/*
380** Prompt strings. Initialized in main. Settable with
381** .prompt main continue
382*/
383static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
384static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
385
386/*
387** Render output like fprintf(). Except, if the output is going to the
388** console and if this is running on a Windows machine, translate the
389** output from UTF-8 into MBCS.
390*/
391#if defined(_WIN32) || defined(WIN32)
392void utf8_printf(FILE *out, const char *zFormat, ...){
393 va_list ap;
394 va_start(ap, zFormat);
395 if( stdout_is_console && (out==stdout || out==stderr) ){
396 char *z1 = sqlite3_vmprintf(zFormat, ap);
397 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
398 sqlite3_free(z1);
399 fputs(z2, out);
400 sqlite3_free(z2);
401 }else{
402 vfprintf(out, zFormat, ap);
403 }
404 va_end(ap);
405}
406#elif !defined(utf8_printf)
407# define utf8_printf fprintf
408#endif
409
410/*
411** Render output like fprintf(). This should not be used on anything that
412** includes string formatting (e.g. "%s").
413*/
414#if !defined(raw_printf)
415# define raw_printf fprintf
416#endif
417
418/*
419** Write I/O traces to the following stream.
420*/
421#ifdef SQLITE_ENABLE_IOTRACE
422static FILE *iotrace = 0;
423#endif
424
425/*
426** This routine works like printf in that its first argument is a
427** format string and subsequent arguments are values to be substituted
428** in place of % fields. The result of formatting this string
429** is written to iotrace.
430*/
431#ifdef SQLITE_ENABLE_IOTRACE
432static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
433 va_list ap;
434 char *z;
435 if( iotrace==0 ) return;
436 va_start(ap, zFormat);
437 z = sqlite3_vmprintf(zFormat, ap);
438 va_end(ap);
439 utf8_printf(iotrace, "%s", z);
440 sqlite3_free(z);
441}
442#endif
443
444/*
445** Output string zUtf to stream pOut as w characters. If w is negative,
446** then right-justify the text. W is the width in UTF-8 characters, not
447** in bytes. This is different from the %*.*s specification in printf
448** since with %*.*s the width is measured in bytes, not characters.
449*/
450static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
451 int i;
452 int n;
453 int aw = w<0 ? -w : w;
454 char zBuf[1000];
455 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
456 for(i=n=0; zUtf[i]; i++){
457 if( (zUtf[i]&0xc0)!=0x80 ){
458 n++;
459 if( n==aw ){
460 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
461 break;
462 }
463 }
464 }
465 if( n>=aw ){
466 utf8_printf(pOut, "%.*s", i, zUtf);
467 }else if( w<0 ){
468 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
469 }else{
470 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
471 }
472}
473
474
475/*
476** Determines if a string is a number of not.
477*/
478static int isNumber(const char *z, int *realnum){
479 if( *z=='-' || *z=='+' ) z++;
480 if( !IsDigit(*z) ){
481 return 0;
482 }
483 z++;
484 if( realnum ) *realnum = 0;
485 while( IsDigit(*z) ){ z++; }
486 if( *z=='.' ){
487 z++;
488 if( !IsDigit(*z) ) return 0;
489 while( IsDigit(*z) ){ z++; }
490 if( realnum ) *realnum = 1;
491 }
492 if( *z=='e' || *z=='E' ){
493 z++;
494 if( *z=='+' || *z=='-' ) z++;
495 if( !IsDigit(*z) ) return 0;
496 while( IsDigit(*z) ){ z++; }
497 if( realnum ) *realnum = 1;
498 }
499 return *z==0;
500}
501
502/*
503** Compute a string length that is limited to what can be stored in
504** lower 30 bits of a 32-bit signed integer.
505*/
506static int strlen30(const char *z){
507 const char *z2 = z;
508 while( *z2 ){ z2++; }
509 return 0x3fffffff & (int)(z2 - z);
510}
511
512/*
513** Return the length of a string in characters. Multibyte UTF8 characters
514** count as a single character.
515*/
516static int strlenChar(const char *z){
517 int n = 0;
518 while( *z ){
519 if( (0xc0&*(z++))!=0x80 ) n++;
520 }
521 return n;
522}
523
524/*
525** This routine reads a line of text from FILE in, stores
526** the text in memory obtained from malloc() and returns a pointer
527** to the text. NULL is returned at end of file, or if malloc()
528** fails.
529**
530** If zLine is not NULL then it is a malloced buffer returned from
531** a previous call to this routine that may be reused.
532*/
533static char *local_getline(char *zLine, FILE *in){
534 int nLine = zLine==0 ? 0 : 100;
535 int n = 0;
536
537 while( 1 ){
538 if( n+100>nLine ){
539 nLine = nLine*2 + 100;
540 zLine = realloc(zLine, nLine);
541 if( zLine==0 ) return 0;
542 }
543 if( fgets(&zLine[n], nLine - n, in)==0 ){
544 if( n==0 ){
545 free(zLine);
546 return 0;
547 }
548 zLine[n] = 0;
549 break;
550 }
551 while( zLine[n] ) n++;
552 if( n>0 && zLine[n-1]=='\n' ){
553 n--;
554 if( n>0 && zLine[n-1]=='\r' ) n--;
555 zLine[n] = 0;
556 break;
557 }
558 }
559#if defined(_WIN32) || defined(WIN32)
560 /* For interactive input on Windows systems, translate the
561 ** multi-byte characterset characters into UTF-8. */
562 if( stdin_is_interactive && in==stdin ){
563 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
564 if( zTrans ){
565 int nTrans = strlen30(zTrans)+1;
566 if( nTrans>nLine ){
567 zLine = realloc(zLine, nTrans);
568 if( zLine==0 ){
569 sqlite3_free(zTrans);
570 return 0;
571 }
572 }
573 memcpy(zLine, zTrans, nTrans);
574 sqlite3_free(zTrans);
575 }
576 }
577#endif /* defined(_WIN32) || defined(WIN32) */
578 return zLine;
579}
580
581/*
582** Retrieve a single line of input text.
583**
584** If in==0 then read from standard input and prompt before each line.
585** If isContinuation is true, then a continuation prompt is appropriate.
586** If isContinuation is zero, then the main prompt should be used.
587**
588** If zPrior is not NULL then it is a buffer from a prior call to this
589** routine that can be reused.
590**
591** The result is stored in space obtained from malloc() and must either
592** be freed by the caller or else passed back into this routine via the
593** zPrior argument for reuse.
594*/
595static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
596 char *zPrompt;
597 char *zResult;
598 if( in!=0 ){
599 zResult = local_getline(zPrior, in);
600 }else{
601 zPrompt = isContinuation ? continuePrompt : mainPrompt;
602#if SHELL_USE_LOCAL_GETLINE
603 printf("%s", zPrompt);
604 fflush(stdout);
605 zResult = local_getline(zPrior, stdin);
606#else
607 free(zPrior);
608 zResult = shell_readline(zPrompt);
609 if( zResult && *zResult ) shell_add_history(zResult);
610#endif
611 }
612 return zResult;
613}
614/*
615** A variable length string to which one can append text.
616*/
617typedef struct ShellText ShellText;
618struct ShellText {
619 char *z;
620 int n;
621 int nAlloc;
622};
623
624/*
625** Initialize and destroy a ShellText object
626*/
627static void initText(ShellText *p){
628 memset(p, 0, sizeof(*p));
629}
630static void freeText(ShellText *p){
631 free(p->z);
632 initText(p);
633}
634
635/* zIn is either a pointer to a NULL-terminated string in memory obtained
636** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637** added to zIn, and the result returned in memory obtained from malloc().
638** zIn, if it was not NULL, is freed.
639**
640** If the third argument, quote, is not '\0', then it is used as a
641** quote character for zAppend.
642*/
643static void appendText(ShellText *p, char const *zAppend, char quote){
644 int len;
645 int i;
646 int nAppend = strlen30(zAppend);
647
648 len = nAppend+p->n+1;
649 if( quote ){
650 len += 2;
651 for(i=0; i<nAppend; i++){
652 if( zAppend[i]==quote ) len++;
653 }
654 }
655
656 if( p->n+len>=p->nAlloc ){
657 p->nAlloc = p->nAlloc*2 + len + 20;
658 p->z = realloc(p->z, p->nAlloc);
659 if( p->z==0 ){
660 memset(p, 0, sizeof(*p));
661 return;
662 }
663 }
664
665 if( quote ){
666 char *zCsr = p->z+p->n;
667 *zCsr++ = quote;
668 for(i=0; i<nAppend; i++){
669 *zCsr++ = zAppend[i];
670 if( zAppend[i]==quote ) *zCsr++ = quote;
671 }
672 *zCsr++ = quote;
673 p->n = (int)(zCsr - p->z);
674 *zCsr = '\0';
675 }else{
676 memcpy(p->z+p->n, zAppend, nAppend);
677 p->n += nAppend;
678 p->z[p->n] = '\0';
679 }
680}
681
682/*
683** Attempt to determine if identifier zName needs to be quoted, either
684** because it contains non-alphanumeric characters, or because it is an
685** SQLite keyword. Be conservative in this estimate: When in doubt assume
686** that quoting is required.
687**
688** Return '"' if quoting is required. Return 0 if no quoting is required.
689*/
690static char quoteChar(const char *zName){
691 /* All SQLite keywords, in alphabetical order */
692 static const char *azKeywords[] = {
693 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
710 "WITH", "WITHOUT",
711 };
712 int i, lwr, upr, mid, c;
713 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
714 for(i=0; zName[i]; i++){
715 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
716 }
717 lwr = 0;
718 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
719 while( lwr<=upr ){
720 mid = (lwr+upr)/2;
721 c = sqlite3_stricmp(azKeywords[mid], zName);
722 if( c==0 ) return '"';
723 if( c<0 ){
724 lwr = mid+1;
725 }else{
726 upr = mid-1;
727 }
728 }
729 return 0;
730}
731
732/*
733** SQL function: shell_add_schema(S,X)
734**
735** Add the schema name X to the CREATE statement in S and return the result.
736** Examples:
737**
738** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
739**
740** Also works on
741**
742** CREATE INDEX
743** CREATE UNIQUE INDEX
744** CREATE VIEW
745** CREATE TRIGGER
746** CREATE VIRTUAL TABLE
747**
748** This UDF is used by the .schema command to insert the schema name of
749** attached databases into the middle of the sqlite_master.sql field.
750*/
751static void shellAddSchemaName(
752 sqlite3_context *pCtx,
753 int nVal,
754 sqlite3_value **apVal
755){
756 static const char *aPrefix[] = {
757 "TABLE",
758 "INDEX",
759 "UNIQUE INDEX",
760 "VIEW",
761 "TRIGGER",
762 "VIRTUAL TABLE"
763 };
764 int i = 0;
765 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
766 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
767 assert( nVal==2 );
768 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
769 for(i=0; i<sizeof(aPrefix)/sizeof(aPrefix[0]); i++){
770 int n = strlen30(aPrefix[i]);
771 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
772 char cQuote = quoteChar(zSchema);
773 char *z;
774 if( cQuote ){
775 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
776 }else{
777 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
778 }
779 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
780 return;
781 }
782 }
783 }
784 sqlite3_result_value(pCtx, apVal[0]);
785}
786
787/*
788** The source code for several run-time loadable extensions is inserted
789** below by the ../tool/mkshellc.tcl script. Before processing that included
790** code, we need to override some macros to make the included program code
791** work here in the middle of this regular program.
792*/
793#define SQLITE_EXTENSION_INIT1
794#define SQLITE_EXTENSION_INIT2(X)
795
796INCLUDE ../ext/misc/shathree.c
797INCLUDE ../ext/misc/fileio.c
798
799#if defined(SQLITE_ENABLE_SESSION)
800/*
801** State information for a single open session
802*/
803typedef struct OpenSession OpenSession;
804struct OpenSession {
805 char *zName; /* Symbolic name for this session */
806 int nFilter; /* Number of xFilter rejection GLOB patterns */
807 char **azFilter; /* Array of xFilter rejection GLOB patterns */
808 sqlite3_session *p; /* The open session */
809};
810#endif
811
812/*
813** Shell output mode information from before ".explain on",
814** saved so that it can be restored by ".explain off"
815*/
816typedef struct SavedModeInfo SavedModeInfo;
817struct SavedModeInfo {
818 int valid; /* Is there legit data in here? */
819 int mode; /* Mode prior to ".explain on" */
820 int showHeader; /* The ".header" setting prior to ".explain on" */
821 int colWidth[100]; /* Column widths prior to ".explain on" */
822};
823
824/*
825** State information about the database connection is contained in an
826** instance of the following structure.
827*/
828typedef struct ShellState ShellState;
829struct ShellState {
830 sqlite3 *db; /* The database */
831 int autoExplain; /* Automatically turn on .explain mode */
832 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
833 int statsOn; /* True to display memory stats before each finalize */
834 int scanstatsOn; /* True to display scan stats before each finalize */
835 int outCount; /* Revert to stdout when reaching zero */
836 int cnt; /* Number of records displayed so far */
837 FILE *out; /* Write results here */
838 FILE *traceOut; /* Output for sqlite3_trace() */
839 int nErr; /* Number of errors seen */
840 int mode; /* An output mode setting */
841 int cMode; /* temporary output mode for the current query */
842 int normalMode; /* Output mode before ".explain on" */
843 int writableSchema; /* True if PRAGMA writable_schema=ON */
844 int showHeader; /* True to show column names in List or Column mode */
845 int nCheck; /* Number of ".check" commands run */
846 unsigned shellFlgs; /* Various flags */
847 char *zDestTable; /* Name of destination table when MODE_Insert */
848 char zTestcase[30]; /* Name of current test case */
849 char colSeparator[20]; /* Column separator character for several modes */
850 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
851 int colWidth[100]; /* Requested width of each column when in column mode*/
852 int actualWidth[100]; /* Actual width of each column */
853 char nullValue[20]; /* The text to print when a NULL comes back from
854 ** the database */
855 char outfile[FILENAME_MAX]; /* Filename for *out */
856 const char *zDbFilename; /* name of the database file */
857 char *zFreeOnClose; /* Filename to free when closing */
858 const char *zVfs; /* Name of VFS to use */
859 sqlite3_stmt *pStmt; /* Current statement if any. */
860 FILE *pLog; /* Write log output here */
861 int *aiIndent; /* Array of indents used in MODE_Explain */
862 int nIndent; /* Size of array aiIndent[] */
863 int iIndent; /* Index of current op in aiIndent[] */
864#if defined(SQLITE_ENABLE_SESSION)
865 int nSession; /* Number of active sessions */
866 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
867#endif
868};
869
870/*
871** These are the allowed shellFlgs values
872*/
873#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
874#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
875#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
876#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
877#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
878#define SHFLG_Newlines 0x00000020 /* .dump --newline flag */
879#define SHFLG_CountChanges 0x00000040 /* .changes setting */
880#define SHFLG_Echo 0x00000080 /* .echo or --echo setting */
881
882/*
883** Macros for testing and setting shellFlgs
884*/
885#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
886#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
887#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
888
889/*
890** These are the allowed modes.
891*/
892#define MODE_Line 0 /* One column per line. Blank line between records */
893#define MODE_Column 1 /* One record per line in neat columns */
894#define MODE_List 2 /* One record per line with a separator */
895#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
896#define MODE_Html 4 /* Generate an XHTML table */
897#define MODE_Insert 5 /* Generate SQL "insert" statements */
898#define MODE_Quote 6 /* Quote values as for SQL */
899#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
900#define MODE_Csv 8 /* Quote strings, numbers are plain */
901#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
902#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
903#define MODE_Pretty 11 /* Pretty-print schemas */
904
905static const char *modeDescr[] = {
906 "line",
907 "column",
908 "list",
909 "semi",
910 "html",
911 "insert",
912 "quote",
913 "tcl",
914 "csv",
915 "explain",
916 "ascii",
917 "prettyprint",
918};
919
920/*
921** These are the column/row/line separators used by the various
922** import/export modes.
923*/
924#define SEP_Column "|"
925#define SEP_Row "\n"
926#define SEP_Tab "\t"
927#define SEP_Space " "
928#define SEP_Comma ","
929#define SEP_CrLf "\r\n"
930#define SEP_Unit "\x1F"
931#define SEP_Record "\x1E"
932
933/*
934** Number of elements in an array
935*/
936#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
937
938/*
939** A callback for the sqlite3_log() interface.
940*/
941static void shellLog(void *pArg, int iErrCode, const char *zMsg){
942 ShellState *p = (ShellState*)pArg;
943 if( p->pLog==0 ) return;
944 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
945 fflush(p->pLog);
946}
947
948/*
949** Output the given string as a hex-encoded blob (eg. X'1234' )
950*/
951static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
952 int i;
953 char *zBlob = (char *)pBlob;
954 raw_printf(out,"X'");
955 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
956 raw_printf(out,"'");
957}
958
959/*
960** Find a string that is not found anywhere in z[]. Return a pointer
961** to that string.
962**
963** Try to use zA and zB first. If both of those are already found in z[]
964** then make up some string and store it in the buffer zBuf.
965*/
966static const char *unused_string(
967 const char *z, /* Result must not appear anywhere in z */
968 const char *zA, const char *zB, /* Try these first */
969 char *zBuf /* Space to store a generated string */
970){
971 unsigned i = 0;
972 if( strstr(z, zA)==0 ) return zA;
973 if( strstr(z, zB)==0 ) return zB;
974 do{
975 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
976 }while( strstr(z,zBuf)!=0 );
977 return zBuf;
978}
979
980/*
981** Output the given string as a quoted string using SQL quoting conventions.
982**
983** See also: output_quoted_escaped_string()
984*/
985static void output_quoted_string(FILE *out, const char *z){
986 int i;
987 char c;
988 setBinaryMode(out, 1);
989 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
990 if( c==0 ){
991 utf8_printf(out,"'%s'",z);
992 }else{
993 raw_printf(out, "'");
994 while( *z ){
995 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
996 if( c=='\'' ) i++;
997 if( i ){
998 utf8_printf(out, "%.*s", i, z);
999 z += i;
1000 }
1001 if( c=='\'' ){
1002 raw_printf(out, "'");
1003 continue;
1004 }
1005 if( c==0 ){
1006 break;
1007 }
1008 z++;
1009 }
1010 raw_printf(out, "'");
1011 }
1012 setTextMode(out, 1);
1013}
1014
1015/*
1016** Output the given string as a quoted string using SQL quoting conventions.
1017** Additionallly , escape the "\n" and "\r" characters so that they do not
1018** get corrupted by end-of-line translation facilities in some operating
1019** systems.
1020**
1021** This is like output_quoted_string() but with the addition of the \r\n
1022** escape mechanism.
1023*/
1024static void output_quoted_escaped_string(FILE *out, const char *z){
1025 int i;
1026 char c;
1027 setBinaryMode(out, 1);
1028 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1029 if( c==0 ){
1030 utf8_printf(out,"'%s'",z);
1031 }else{
1032 const char *zNL = 0;
1033 const char *zCR = 0;
1034 int nNL = 0;
1035 int nCR = 0;
1036 char zBuf1[20], zBuf2[20];
1037 for(i=0; z[i]; i++){
1038 if( z[i]=='\n' ) nNL++;
1039 if( z[i]=='\r' ) nCR++;
1040 }
1041 if( nNL ){
1042 raw_printf(out, "replace(");
1043 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1044 }
1045 if( nCR ){
1046 raw_printf(out, "replace(");
1047 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1048 }
1049 raw_printf(out, "'");
1050 while( *z ){
1051 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1052 if( c=='\'' ) i++;
1053 if( i ){
1054 utf8_printf(out, "%.*s", i, z);
1055 z += i;
1056 }
1057 if( c=='\'' ){
1058 raw_printf(out, "'");
1059 continue;
1060 }
1061 if( c==0 ){
1062 break;
1063 }
1064 z++;
1065 if( c=='\n' ){
1066 raw_printf(out, "%s", zNL);
1067 continue;
1068 }
1069 raw_printf(out, "%s", zCR);
1070 }
1071 raw_printf(out, "'");
1072 if( nCR ){
1073 raw_printf(out, ",'%s',char(13))", zCR);
1074 }
1075 if( nNL ){
1076 raw_printf(out, ",'%s',char(10))", zNL);
1077 }
1078 }
1079 setTextMode(out, 1);
1080}
1081
1082/*
1083** Output the given string as a quoted according to C or TCL quoting rules.
1084*/
1085static void output_c_string(FILE *out, const char *z){
1086 unsigned int c;
1087 fputc('"', out);
1088 while( (c = *(z++))!=0 ){
1089 if( c=='\\' ){
1090 fputc(c, out);
1091 fputc(c, out);
1092 }else if( c=='"' ){
1093 fputc('\\', out);
1094 fputc('"', out);
1095 }else if( c=='\t' ){
1096 fputc('\\', out);
1097 fputc('t', out);
1098 }else if( c=='\n' ){
1099 fputc('\\', out);
1100 fputc('n', out);
1101 }else if( c=='\r' ){
1102 fputc('\\', out);
1103 fputc('r', out);
1104 }else if( !isprint(c&0xff) ){
1105 raw_printf(out, "\\%03o", c&0xff);
1106 }else{
1107 fputc(c, out);
1108 }
1109 }
1110 fputc('"', out);
1111}
1112
1113/*
1114** Output the given string with characters that are special to
1115** HTML escaped.
1116*/
1117static void output_html_string(FILE *out, const char *z){
1118 int i;
1119 if( z==0 ) z = "";
1120 while( *z ){
1121 for(i=0; z[i]
1122 && z[i]!='<'
1123 && z[i]!='&'
1124 && z[i]!='>'
1125 && z[i]!='\"'
1126 && z[i]!='\'';
1127 i++){}
1128 if( i>0 ){
1129 utf8_printf(out,"%.*s",i,z);
1130 }
1131 if( z[i]=='<' ){
1132 raw_printf(out,"&lt;");
1133 }else if( z[i]=='&' ){
1134 raw_printf(out,"&amp;");
1135 }else if( z[i]=='>' ){
1136 raw_printf(out,"&gt;");
1137 }else if( z[i]=='\"' ){
1138 raw_printf(out,"&quot;");
1139 }else if( z[i]=='\'' ){
1140 raw_printf(out,"&#39;");
1141 }else{
1142 break;
1143 }
1144 z += i + 1;
1145 }
1146}
1147
1148/*
1149** If a field contains any character identified by a 1 in the following
1150** array, then the string must be quoted for CSV.
1151*/
1152static const char needCsvQuote[] = {
1153 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1154 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1155 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1156 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1157 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1158 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1159 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1160 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1162 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1163 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1164 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1165 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1166 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1167 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1168 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1169};
1170
1171/*
1172** Output a single term of CSV. Actually, p->colSeparator is used for
1173** the separator, which may or may not be a comma. p->nullValue is
1174** the null value. Strings are quoted if necessary. The separator
1175** is only issued if bSep is true.
1176*/
1177static void output_csv(ShellState *p, const char *z, int bSep){
1178 FILE *out = p->out;
1179 if( z==0 ){
1180 utf8_printf(out,"%s",p->nullValue);
1181 }else{
1182 int i;
1183 int nSep = strlen30(p->colSeparator);
1184 for(i=0; z[i]; i++){
1185 if( needCsvQuote[((unsigned char*)z)[i]]
1186 || (z[i]==p->colSeparator[0] &&
1187 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1188 i = 0;
1189 break;
1190 }
1191 }
1192 if( i==0 ){
1193 putc('"', out);
1194 for(i=0; z[i]; i++){
1195 if( z[i]=='"' ) putc('"', out);
1196 putc(z[i], out);
1197 }
1198 putc('"', out);
1199 }else{
1200 utf8_printf(out, "%s", z);
1201 }
1202 }
1203 if( bSep ){
1204 utf8_printf(p->out, "%s", p->colSeparator);
1205 }
1206}
1207
1208#ifdef SIGINT
1209/*
1210** This routine runs when the user presses Ctrl-C
1211*/
1212static void interrupt_handler(int NotUsed){
1213 UNUSED_PARAMETER(NotUsed);
1214 seenInterrupt++;
1215 if( seenInterrupt>2 ) exit(1);
1216 if( globalDb ) sqlite3_interrupt(globalDb);
1217}
1218#endif
1219
1220#ifndef SQLITE_OMIT_AUTHORIZATION
1221/*
1222** When the ".auth ON" is set, the following authorizer callback is
1223** invoked. It always returns SQLITE_OK.
1224*/
1225static int shellAuth(
1226 void *pClientData,
1227 int op,
1228 const char *zA1,
1229 const char *zA2,
1230 const char *zA3,
1231 const char *zA4
1232){
1233 ShellState *p = (ShellState*)pClientData;
1234 static const char *azAction[] = { 0,
1235 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1236 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1237 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1238 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1239 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1240 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1241 "PRAGMA", "READ", "SELECT",
1242 "TRANSACTION", "UPDATE", "ATTACH",
1243 "DETACH", "ALTER_TABLE", "REINDEX",
1244 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1245 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1246 };
1247 int i;
1248 const char *az[4];
1249 az[0] = zA1;
1250 az[1] = zA2;
1251 az[2] = zA3;
1252 az[3] = zA4;
1253 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1254 for(i=0; i<4; i++){
1255 raw_printf(p->out, " ");
1256 if( az[i] ){
1257 output_c_string(p->out, az[i]);
1258 }else{
1259 raw_printf(p->out, "NULL");
1260 }
1261 }
1262 raw_printf(p->out, "\n");
1263 return SQLITE_OK;
1264}
1265#endif
1266
1267/*
1268** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1269**
1270** This routine converts some CREATE TABLE statements for shadow tables
1271** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1272*/
1273static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1274 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1275 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1276 }else{
1277 utf8_printf(out, "%s%s", z, zTail);
1278 }
1279}
1280static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1281 char c = z[n];
1282 z[n] = 0;
1283 printSchemaLine(out, z, zTail);
1284 z[n] = c;
1285}
1286
1287/*
1288** This is the callback routine that the shell
1289** invokes for each row of a query result.
1290*/
1291static int shell_callback(
1292 void *pArg,
1293 int nArg, /* Number of result columns */
1294 char **azArg, /* Text of each result column */
1295 char **azCol, /* Column names */
1296 int *aiType /* Column types */
1297){
1298 int i;
1299 ShellState *p = (ShellState*)pArg;
1300
1301 switch( p->cMode ){
1302 case MODE_Line: {
1303 int w = 5;
1304 if( azArg==0 ) break;
1305 for(i=0; i<nArg; i++){
1306 int len = strlen30(azCol[i] ? azCol[i] : "");
1307 if( len>w ) w = len;
1308 }
1309 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1310 for(i=0; i<nArg; i++){
1311 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1312 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1313 }
1314 break;
1315 }
1316 case MODE_Explain:
1317 case MODE_Column: {
1318 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1319 const int *colWidth;
1320 int showHdr;
1321 char *rowSep;
1322 if( p->cMode==MODE_Column ){
1323 colWidth = p->colWidth;
1324 showHdr = p->showHeader;
1325 rowSep = p->rowSeparator;
1326 }else{
1327 colWidth = aExplainWidths;
1328 showHdr = 1;
1329 rowSep = SEP_Row;
1330 }
1331 if( p->cnt++==0 ){
1332 for(i=0; i<nArg; i++){
1333 int w, n;
1334 if( i<ArraySize(p->colWidth) ){
1335 w = colWidth[i];
1336 }else{
1337 w = 0;
1338 }
1339 if( w==0 ){
1340 w = strlenChar(azCol[i] ? azCol[i] : "");
1341 if( w<10 ) w = 10;
1342 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1343 if( w<n ) w = n;
1344 }
1345 if( i<ArraySize(p->actualWidth) ){
1346 p->actualWidth[i] = w;
1347 }
1348 if( showHdr ){
1349 utf8_width_print(p->out, w, azCol[i]);
1350 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1351 }
1352 }
1353 if( showHdr ){
1354 for(i=0; i<nArg; i++){
1355 int w;
1356 if( i<ArraySize(p->actualWidth) ){
1357 w = p->actualWidth[i];
1358 if( w<0 ) w = -w;
1359 }else{
1360 w = 10;
1361 }
1362 utf8_printf(p->out,"%-*.*s%s",w,w,
1363 "----------------------------------------------------------"
1364 "----------------------------------------------------------",
1365 i==nArg-1 ? rowSep : " ");
1366 }
1367 }
1368 }
1369 if( azArg==0 ) break;
1370 for(i=0; i<nArg; i++){
1371 int w;
1372 if( i<ArraySize(p->actualWidth) ){
1373 w = p->actualWidth[i];
1374 }else{
1375 w = 10;
1376 }
1377 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1378 w = strlenChar(azArg[i]);
1379 }
1380 if( i==1 && p->aiIndent && p->pStmt ){
1381 if( p->iIndent<p->nIndent ){
1382 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1383 }
1384 p->iIndent++;
1385 }
1386 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1387 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1388 }
1389 break;
1390 }
1391 case MODE_Semi: { /* .schema and .fullschema output */
1392 printSchemaLine(p->out, azArg[0], ";\n");
1393 break;
1394 }
1395 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1396 char *z;
1397 int j;
1398 int nParen = 0;
1399 char cEnd = 0;
1400 char c;
1401 int nLine = 0;
1402 assert( nArg==1 );
1403 if( azArg[0]==0 ) break;
1404 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1405 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1406 ){
1407 utf8_printf(p->out, "%s;\n", azArg[0]);
1408 break;
1409 }
1410 z = sqlite3_mprintf("%s", azArg[0]);
1411 j = 0;
1412 for(i=0; IsSpace(z[i]); i++){}
1413 for(; (c = z[i])!=0; i++){
1414 if( IsSpace(c) ){
1415 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1416 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1417 j--;
1418 }
1419 z[j++] = c;
1420 }
1421 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1422 z[j] = 0;
1423 if( strlen30(z)>=79 ){
1424 for(i=j=0; (c = z[i])!=0; i++){
1425 if( c==cEnd ){
1426 cEnd = 0;
1427 }else if( c=='"' || c=='\'' || c=='`' ){
1428 cEnd = c;
1429 }else if( c=='[' ){
1430 cEnd = ']';
1431 }else if( c=='(' ){
1432 nParen++;
1433 }else if( c==')' ){
1434 nParen--;
1435 if( nLine>0 && nParen==0 && j>0 ){
1436 printSchemaLineN(p->out, z, j, "\n");
1437 j = 0;
1438 }
1439 }
1440 z[j++] = c;
1441 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1442 if( c=='\n' ) j--;
1443 printSchemaLineN(p->out, z, j, "\n ");
1444 j = 0;
1445 nLine++;
1446 while( IsSpace(z[i+1]) ){ i++; }
1447 }
1448 }
1449 z[j] = 0;
1450 }
1451 printSchemaLine(p->out, z, ";\n");
1452 sqlite3_free(z);
1453 break;
1454 }
1455 case MODE_List: {
1456 if( p->cnt++==0 && p->showHeader ){
1457 for(i=0; i<nArg; i++){
1458 utf8_printf(p->out,"%s%s",azCol[i],
1459 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1460 }
1461 }
1462 if( azArg==0 ) break;
1463 for(i=0; i<nArg; i++){
1464 char *z = azArg[i];
1465 if( z==0 ) z = p->nullValue;
1466 utf8_printf(p->out, "%s", z);
1467 if( i<nArg-1 ){
1468 utf8_printf(p->out, "%s", p->colSeparator);
1469 }else{
1470 utf8_printf(p->out, "%s", p->rowSeparator);
1471 }
1472 }
1473 break;
1474 }
1475 case MODE_Html: {
1476 if( p->cnt++==0 && p->showHeader ){
1477 raw_printf(p->out,"<TR>");
1478 for(i=0; i<nArg; i++){
1479 raw_printf(p->out,"<TH>");
1480 output_html_string(p->out, azCol[i]);
1481 raw_printf(p->out,"</TH>\n");
1482 }
1483 raw_printf(p->out,"</TR>\n");
1484 }
1485 if( azArg==0 ) break;
1486 raw_printf(p->out,"<TR>");
1487 for(i=0; i<nArg; i++){
1488 raw_printf(p->out,"<TD>");
1489 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1490 raw_printf(p->out,"</TD>\n");
1491 }
1492 raw_printf(p->out,"</TR>\n");
1493 break;
1494 }
1495 case MODE_Tcl: {
1496 if( p->cnt++==0 && p->showHeader ){
1497 for(i=0; i<nArg; i++){
1498 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1499 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1500 }
1501 utf8_printf(p->out, "%s", p->rowSeparator);
1502 }
1503 if( azArg==0 ) break;
1504 for(i=0; i<nArg; i++){
1505 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1506 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1507 }
1508 utf8_printf(p->out, "%s", p->rowSeparator);
1509 break;
1510 }
1511 case MODE_Csv: {
1512 setBinaryMode(p->out, 1);
1513 if( p->cnt++==0 && p->showHeader ){
1514 for(i=0; i<nArg; i++){
1515 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1516 }
1517 utf8_printf(p->out, "%s", p->rowSeparator);
1518 }
1519 if( nArg>0 ){
1520 for(i=0; i<nArg; i++){
1521 output_csv(p, azArg[i], i<nArg-1);
1522 }
1523 utf8_printf(p->out, "%s", p->rowSeparator);
1524 }
1525 setTextMode(p->out, 1);
1526 break;
1527 }
1528 case MODE_Insert: {
1529 if( azArg==0 ) break;
1530 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1531 if( p->showHeader ){
1532 raw_printf(p->out,"(");
1533 for(i=0; i<nArg; i++){
1534 if( i>0 ) raw_printf(p->out, ",");
1535 if( quoteChar(azCol[i]) ){
1536 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1537 utf8_printf(p->out, "%s", z);
1538 sqlite3_free(z);
1539 }else{
1540 raw_printf(p->out, "%s", azCol[i]);
1541 }
1542 }
1543 raw_printf(p->out,")");
1544 }
1545 p->cnt++;
1546 for(i=0; i<nArg; i++){
1547 raw_printf(p->out, i>0 ? "," : " VALUES(");
1548 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1549 utf8_printf(p->out,"NULL");
1550 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1551 if( ShellHasFlag(p, SHFLG_Newlines) ){
1552 output_quoted_string(p->out, azArg[i]);
1553 }else{
1554 output_quoted_escaped_string(p->out, azArg[i]);
1555 }
1556 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1557 utf8_printf(p->out,"%s", azArg[i]);
1558 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1559 char z[50];
1560 double r = sqlite3_column_double(p->pStmt, i);
1561 sqlite3_snprintf(50,z,"%!.20g", r);
1562 raw_printf(p->out, "%s", z);
1563 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1564 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1565 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1566 output_hex_blob(p->out, pBlob, nBlob);
1567 }else if( isNumber(azArg[i], 0) ){
1568 utf8_printf(p->out,"%s", azArg[i]);
1569 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1570 output_quoted_string(p->out, azArg[i]);
1571 }else{
1572 output_quoted_escaped_string(p->out, azArg[i]);
1573 }
1574 }
1575 raw_printf(p->out,");\n");
1576 break;
1577 }
1578 case MODE_Quote: {
1579 if( azArg==0 ) break;
1580 if( p->cnt==0 && p->showHeader ){
1581 for(i=0; i<nArg; i++){
1582 if( i>0 ) raw_printf(p->out, ",");
1583 output_quoted_string(p->out, azCol[i]);
1584 }
1585 raw_printf(p->out,"\n");
1586 }
1587 p->cnt++;
1588 for(i=0; i<nArg; i++){
1589 if( i>0 ) raw_printf(p->out, ",");
1590 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1591 utf8_printf(p->out,"NULL");
1592 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1593 output_quoted_string(p->out, azArg[i]);
1594 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1595 utf8_printf(p->out,"%s", azArg[i]);
1596 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1597 char z[50];
1598 double r = sqlite3_column_double(p->pStmt, i);
1599 sqlite3_snprintf(50,z,"%!.20g", r);
1600 raw_printf(p->out, "%s", z);
1601 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1602 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1603 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1604 output_hex_blob(p->out, pBlob, nBlob);
1605 }else if( isNumber(azArg[i], 0) ){
1606 utf8_printf(p->out,"%s", azArg[i]);
1607 }else{
1608 output_quoted_string(p->out, azArg[i]);
1609 }
1610 }
1611 raw_printf(p->out,"\n");
1612 break;
1613 }
1614 case MODE_Ascii: {
1615 if( p->cnt++==0 && p->showHeader ){
1616 for(i=0; i<nArg; i++){
1617 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1618 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1619 }
1620 utf8_printf(p->out, "%s", p->rowSeparator);
1621 }
1622 if( azArg==0 ) break;
1623 for(i=0; i<nArg; i++){
1624 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1625 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1626 }
1627 utf8_printf(p->out, "%s", p->rowSeparator);
1628 break;
1629 }
1630 }
1631 return 0;
1632}
1633
1634/*
1635** This is the callback routine that the SQLite library
1636** invokes for each row of a query result.
1637*/
1638static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1639 /* since we don't have type info, call the shell_callback with a NULL value */
1640 return shell_callback(pArg, nArg, azArg, azCol, NULL);
1641}
1642
1643/*
1644** This is the callback routine from sqlite3_exec() that appends all
1645** output onto the end of a ShellText object.
1646*/
1647static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1648 ShellText *p = (ShellText*)pArg;
1649 int i;
1650 UNUSED_PARAMETER(az);
1651 if( p->n ) appendText(p, "|", 0);
1652 for(i=0; i<nArg; i++){
1653 if( i ) appendText(p, ",", 0);
1654 if( azArg[i] ) appendText(p, azArg[i], 0);
1655 }
1656 return 0;
1657}
1658
1659/*
1660** Generate an appropriate SELFTEST table in the main database.
1661*/
1662static void createSelftestTable(ShellState *p){
1663 char *zErrMsg = 0;
1664 sqlite3_exec(p->db,
1665 "SAVEPOINT selftest_init;\n"
1666 "CREATE TABLE IF NOT EXISTS selftest(\n"
1667 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1668 " op TEXT,\n" /* Operator: memo run */
1669 " cmd TEXT,\n" /* Command text */
1670 " ans TEXT\n" /* Desired answer */
1671 ");"
1672 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1673 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1674 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1675 " 'memo','Tests generated by --init');\n"
1676 "INSERT INTO [_shell$self]\n"
1677 " SELECT 'run',\n"
1678 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1679 "FROM sqlite_master ORDER BY 2'',224))',\n"
1680 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1681 "FROM sqlite_master ORDER BY 2',224));\n"
1682 "INSERT INTO [_shell$self]\n"
1683 " SELECT 'run',"
1684 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1685 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1686 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1687 " FROM (\n"
1688 " SELECT name FROM sqlite_master\n"
1689 " WHERE type='table'\n"
1690 " AND name<>'selftest'\n"
1691 " AND coalesce(rootpage,0)>0\n"
1692 " )\n"
1693 " ORDER BY name;\n"
1694 "INSERT INTO [_shell$self]\n"
1695 " VALUES('run','PRAGMA integrity_check','ok');\n"
1696 "INSERT INTO selftest(tno,op,cmd,ans)"
1697 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1698 "DROP TABLE [_shell$self];"
1699 ,0,0,&zErrMsg);
1700 if( zErrMsg ){
1701 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1702 sqlite3_free(zErrMsg);
1703 }
1704 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1705}
1706
1707
1708/*
1709** Set the destination table field of the ShellState structure to
1710** the name of the table given. Escape any quote characters in the
1711** table name.
1712*/
1713static void set_table_name(ShellState *p, const char *zName){
1714 int i, n;
1715 int cQuote;
1716 char *z;
1717
1718 if( p->zDestTable ){
1719 free(p->zDestTable);
1720 p->zDestTable = 0;
1721 }
1722 if( zName==0 ) return;
1723 cQuote = quoteChar(zName);
1724 n = strlen30(zName);
1725 if( cQuote ) n += n+2;
1726 z = p->zDestTable = malloc( n+1 );
1727 if( z==0 ){
1728 raw_printf(stderr,"Error: out of memory\n");
1729 exit(1);
1730 }
1731 n = 0;
1732 if( cQuote ) z[n++] = cQuote;
1733 for(i=0; zName[i]; i++){
1734 z[n++] = zName[i];
1735 if( zName[i]==cQuote ) z[n++] = cQuote;
1736 }
1737 if( cQuote ) z[n++] = cQuote;
1738 z[n] = 0;
1739}
1740
1741
1742/*
1743** Execute a query statement that will generate SQL output. Print
1744** the result columns, comma-separated, on a line and then add a
1745** semicolon terminator to the end of that line.
1746**
1747** If the number of columns is 1 and that column contains text "--"
1748** then write the semicolon on a separate line. That way, if a
1749** "--" comment occurs at the end of the statement, the comment
1750** won't consume the semicolon terminator.
1751*/
1752static int run_table_dump_query(
1753 ShellState *p, /* Query context */
1754 const char *zSelect, /* SELECT statement to extract content */
1755 const char *zFirstRow /* Print before first row, if not NULL */
1756){
1757 sqlite3_stmt *pSelect;
1758 int rc;
1759 int nResult;
1760 int i;
1761 const char *z;
1762 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
1763 if( rc!=SQLITE_OK || !pSelect ){
1764 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1765 sqlite3_errmsg(p->db));
1766 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1767 return rc;
1768 }
1769 rc = sqlite3_step(pSelect);
1770 nResult = sqlite3_column_count(pSelect);
1771 while( rc==SQLITE_ROW ){
1772 if( zFirstRow ){
1773 utf8_printf(p->out, "%s", zFirstRow);
1774 zFirstRow = 0;
1775 }
1776 z = (const char*)sqlite3_column_text(pSelect, 0);
1777 utf8_printf(p->out, "%s", z);
1778 for(i=1; i<nResult; i++){
1779 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
1780 }
1781 if( z==0 ) z = "";
1782 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
1783 if( z[0] ){
1784 raw_printf(p->out, "\n;\n");
1785 }else{
1786 raw_printf(p->out, ";\n");
1787 }
1788 rc = sqlite3_step(pSelect);
1789 }
1790 rc = sqlite3_finalize(pSelect);
1791 if( rc!=SQLITE_OK ){
1792 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1793 sqlite3_errmsg(p->db));
1794 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1795 }
1796 return rc;
1797}
1798
1799/*
1800** Allocate space and save off current error string.
1801*/
1802static char *save_err_msg(
1803 sqlite3 *db /* Database to query */
1804){
1805 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1806 char *zErrMsg = sqlite3_malloc64(nErrMsg);
1807 if( zErrMsg ){
1808 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1809 }
1810 return zErrMsg;
1811}
1812
1813#ifdef __linux__
1814/*
1815** Attempt to display I/O stats on Linux using /proc/PID/io
1816*/
1817static void displayLinuxIoStats(FILE *out){
1818 FILE *in;
1819 char z[200];
1820 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
1821 in = fopen(z, "rb");
1822 if( in==0 ) return;
1823 while( fgets(z, sizeof(z), in)!=0 ){
1824 static const struct {
1825 const char *zPattern;
1826 const char *zDesc;
1827 } aTrans[] = {
1828 { "rchar: ", "Bytes received by read():" },
1829 { "wchar: ", "Bytes sent to write():" },
1830 { "syscr: ", "Read() system calls:" },
1831 { "syscw: ", "Write() system calls:" },
1832 { "read_bytes: ", "Bytes read from storage:" },
1833 { "write_bytes: ", "Bytes written to storage:" },
1834 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1835 };
1836 int i;
1837 for(i=0; i<ArraySize(aTrans); i++){
1838 int n = (int)strlen(aTrans[i].zPattern);
1839 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
1840 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
1841 break;
1842 }
1843 }
1844 }
1845 fclose(in);
1846}
1847#endif
1848
1849/*
1850** Display a single line of status using 64-bit values.
1851*/
1852static void displayStatLine(
1853 ShellState *p, /* The shell context */
1854 char *zLabel, /* Label for this one line */
1855 char *zFormat, /* Format for the result */
1856 int iStatusCtrl, /* Which status to display */
1857 int bReset /* True to reset the stats */
1858){
1859 sqlite3_int64 iCur = -1;
1860 sqlite3_int64 iHiwtr = -1;
1861 int i, nPercent;
1862 char zLine[200];
1863 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
1864 for(i=0, nPercent=0; zFormat[i]; i++){
1865 if( zFormat[i]=='%' ) nPercent++;
1866 }
1867 if( nPercent>1 ){
1868 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
1869 }else{
1870 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
1871 }
1872 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
1873}
1874
1875/*
1876** Display memory stats.
1877*/
1878static int display_stats(
1879 sqlite3 *db, /* Database to query */
1880 ShellState *pArg, /* Pointer to ShellState */
1881 int bReset /* True to reset the stats */
1882){
1883 int iCur;
1884 int iHiwtr;
1885
1886 if( pArg && pArg->out ){
1887 displayStatLine(pArg, "Memory Used:",
1888 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
1889 displayStatLine(pArg, "Number of Outstanding Allocations:",
1890 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
1891 if( pArg->shellFlgs & SHFLG_Pagecache ){
1892 displayStatLine(pArg, "Number of Pcache Pages Used:",
1893 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
1894 }
1895 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
1896 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
1897 if( pArg->shellFlgs & SHFLG_Scratch ){
1898 displayStatLine(pArg, "Number of Scratch Allocations Used:",
1899 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
1900 }
1901 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
1902 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
1903 displayStatLine(pArg, "Largest Allocation:",
1904 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
1905 displayStatLine(pArg, "Largest Pcache Allocation:",
1906 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
1907 displayStatLine(pArg, "Largest Scratch Allocation:",
1908 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
1909#ifdef YYTRACKMAXSTACKDEPTH
1910 displayStatLine(pArg, "Deepest Parser Stack:",
1911 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
1912#endif
1913 }
1914
1915 if( pArg && pArg->out && db ){
1916 if( pArg->shellFlgs & SHFLG_Lookaside ){
1917 iHiwtr = iCur = -1;
1918 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
1919 &iCur, &iHiwtr, bReset);
1920 raw_printf(pArg->out,
1921 "Lookaside Slots Used: %d (max %d)\n",
1922 iCur, iHiwtr);
1923 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
1924 &iCur, &iHiwtr, bReset);
1925 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
1926 iHiwtr);
1927 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
1928 &iCur, &iHiwtr, bReset);
1929 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
1930 iHiwtr);
1931 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
1932 &iCur, &iHiwtr, bReset);
1933 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
1934 iHiwtr);
1935 }
1936 iHiwtr = iCur = -1;
1937 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
1938 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
1939 iCur);
1940 iHiwtr = iCur = -1;
1941 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
1942 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
1943 iHiwtr = iCur = -1;
1944 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
1945 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
1946 iHiwtr = iCur = -1;
1947 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
1948 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
1949 iHiwtr = iCur = -1;
1950 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
1951 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
1952 iCur);
1953 iHiwtr = iCur = -1;
1954 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
1955 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
1956 iCur);
1957 }
1958
1959 if( pArg && pArg->out && db && pArg->pStmt ){
1960 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
1961 bReset);
1962 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
1963 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1964 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
1965 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
1966 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
1967 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
1968 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
1969 }
1970
1971#ifdef __linux__
1972 displayLinuxIoStats(pArg->out);
1973#endif
1974
1975 /* Do not remove this machine readable comment: extra-stats-output-here */
1976
1977 return 0;
1978}
1979
1980/*
1981** Display scan stats.
1982*/
1983static void display_scanstats(
1984 sqlite3 *db, /* Database to query */
1985 ShellState *pArg /* Pointer to ShellState */
1986){
1987#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
1988 UNUSED_PARAMETER(db);
1989 UNUSED_PARAMETER(pArg);
1990#else
1991 int i, k, n, mx;
1992 raw_printf(pArg->out, "-------- scanstats --------\n");
1993 mx = 0;
1994 for(k=0; k<=mx; k++){
1995 double rEstLoop = 1.0;
1996 for(i=n=0; 1; i++){
1997 sqlite3_stmt *p = pArg->pStmt;
1998 sqlite3_int64 nLoop, nVisit;
1999 double rEst;
2000 int iSid;
2001 const char *zExplain;
2002 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2003 break;
2004 }
2005 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2006 if( iSid>mx ) mx = iSid;
2007 if( iSid!=k ) continue;
2008 if( n==0 ){
2009 rEstLoop = (double)nLoop;
2010 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2011 }
2012 n++;
2013 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2014 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2015 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2016 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2017 rEstLoop *= rEst;
2018 raw_printf(pArg->out,
2019 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2020 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2021 );
2022 }
2023 }
2024 raw_printf(pArg->out, "---------------------------\n");
2025#endif
2026}
2027
2028/*
2029** Parameter azArray points to a zero-terminated array of strings. zStr
2030** points to a single nul-terminated string. Return non-zero if zStr
2031** is equal, according to strcmp(), to any of the strings in the array.
2032** Otherwise, return zero.
2033*/
2034static int str_in_array(const char *zStr, const char **azArray){
2035 int i;
2036 for(i=0; azArray[i]; i++){
2037 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2038 }
2039 return 0;
2040}
2041
2042/*
2043** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2044** and populate the ShellState.aiIndent[] array with the number of
2045** spaces each opcode should be indented before it is output.
2046**
2047** The indenting rules are:
2048**
2049** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2050** all opcodes that occur between the p2 jump destination and the opcode
2051** itself by 2 spaces.
2052**
2053** * For each "Goto", if the jump destination is earlier in the program
2054** and ends on one of:
2055** Yield SeekGt SeekLt RowSetRead Rewind
2056** or if the P1 parameter is one instead of zero,
2057** then indent all opcodes between the earlier instruction
2058** and "Goto" by 2 spaces.
2059*/
2060static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2061 const char *zSql; /* The text of the SQL statement */
2062 const char *z; /* Used to check if this is an EXPLAIN */
2063 int *abYield = 0; /* True if op is an OP_Yield */
2064 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2065 int iOp; /* Index of operation in p->aiIndent[] */
2066
2067 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2068 "NextIfOpen", "PrevIfOpen", 0 };
2069 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2070 "Rewind", 0 };
2071 const char *azGoto[] = { "Goto", 0 };
2072
2073 /* Try to figure out if this is really an EXPLAIN statement. If this
2074 ** cannot be verified, return early. */
2075 if( sqlite3_column_count(pSql)!=8 ){
2076 p->cMode = p->mode;
2077 return;
2078 }
2079 zSql = sqlite3_sql(pSql);
2080 if( zSql==0 ) return;
2081 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2082 if( sqlite3_strnicmp(z, "explain", 7) ){
2083 p->cMode = p->mode;
2084 return;
2085 }
2086
2087 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2088 int i;
2089 int iAddr = sqlite3_column_int(pSql, 0);
2090 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2091
2092 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2093 ** p2 is an instruction address, set variable p2op to the index of that
2094 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2095 ** the current instruction is part of a sub-program generated by an
2096 ** SQL trigger or foreign key. */
2097 int p2 = sqlite3_column_int(pSql, 3);
2098 int p2op = (p2 + (iOp-iAddr));
2099
2100 /* Grow the p->aiIndent array as required */
2101 if( iOp>=nAlloc ){
2102 if( iOp==0 ){
2103 /* Do further verfication that this is explain output. Abort if
2104 ** it is not */
2105 static const char *explainCols[] = {
2106 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2107 int jj;
2108 for(jj=0; jj<ArraySize(explainCols); jj++){
2109 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2110 p->cMode = p->mode;
2111 sqlite3_reset(pSql);
2112 return;
2113 }
2114 }
2115 }
2116 nAlloc += 100;
2117 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2118 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2119 }
2120 abYield[iOp] = str_in_array(zOp, azYield);
2121 p->aiIndent[iOp] = 0;
2122 p->nIndent = iOp+1;
2123
2124 if( str_in_array(zOp, azNext) ){
2125 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2126 }
2127 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2128 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2129 ){
2130 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2131 }
2132 }
2133
2134 p->iIndent = 0;
2135 sqlite3_free(abYield);
2136 sqlite3_reset(pSql);
2137}
2138
2139/*
2140** Free the array allocated by explain_data_prepare().
2141*/
2142static void explain_data_delete(ShellState *p){
2143 sqlite3_free(p->aiIndent);
2144 p->aiIndent = 0;
2145 p->nIndent = 0;
2146 p->iIndent = 0;
2147}
2148
2149/*
2150** Disable and restore .wheretrace and .selecttrace settings.
2151*/
2152#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2153extern int sqlite3SelectTrace;
2154static int savedSelectTrace;
2155#endif
2156#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2157extern int sqlite3WhereTrace;
2158static int savedWhereTrace;
2159#endif
2160static void disable_debug_trace_modes(void){
2161#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2162 savedSelectTrace = sqlite3SelectTrace;
2163 sqlite3SelectTrace = 0;
2164#endif
2165#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2166 savedWhereTrace = sqlite3WhereTrace;
2167 sqlite3WhereTrace = 0;
2168#endif
2169}
2170static void restore_debug_trace_modes(void){
2171#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2172 sqlite3SelectTrace = savedSelectTrace;
2173#endif
2174#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2175 sqlite3WhereTrace = savedWhereTrace;
2176#endif
2177}
2178
2179/*
2180** Run a prepared statement
2181*/
2182static void exec_prepared_stmt(
2183 ShellState *pArg, /* Pointer to ShellState */
2184 sqlite3_stmt *pStmt, /* Statment to run */
2185 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2186){
2187 int rc;
2188
2189 /* perform the first step. this will tell us if we
2190 ** have a result set or not and how wide it is.
2191 */
2192 rc = sqlite3_step(pStmt);
2193 /* if we have a result set... */
2194 if( SQLITE_ROW == rc ){
2195 /* if we have a callback... */
2196 if( xCallback ){
2197 /* allocate space for col name ptr, value ptr, and type */
2198 int nCol = sqlite3_column_count(pStmt);
2199 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2200 if( !pData ){
2201 rc = SQLITE_NOMEM;
2202 }else{
2203 char **azCols = (char **)pData; /* Names of result columns */
2204 char **azVals = &azCols[nCol]; /* Results */
2205 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2206 int i, x;
2207 assert(sizeof(int) <= sizeof(char *));
2208 /* save off ptrs to column names */
2209 for(i=0; i<nCol; i++){
2210 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2211 }
2212 do{
2213 /* extract the data and data types */
2214 for(i=0; i<nCol; i++){
2215 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2216 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2217 azVals[i] = "";
2218 }else{
2219 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2220 }
2221 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2222 rc = SQLITE_NOMEM;
2223 break; /* from for */
2224 }
2225 } /* end for */
2226
2227 /* if data and types extracted successfully... */
2228 if( SQLITE_ROW == rc ){
2229 /* call the supplied callback with the result row data */
2230 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2231 rc = SQLITE_ABORT;
2232 }else{
2233 rc = sqlite3_step(pStmt);
2234 }
2235 }
2236 } while( SQLITE_ROW == rc );
2237 sqlite3_free(pData);
2238 }
2239 }else{
2240 do{
2241 rc = sqlite3_step(pStmt);
2242 } while( rc == SQLITE_ROW );
2243 }
2244 }
2245}
2246
2247/*
2248** Execute a statement or set of statements. Print
2249** any result rows/columns depending on the current mode
2250** set via the supplied callback.
2251**
2252** This is very similar to SQLite's built-in sqlite3_exec()
2253** function except it takes a slightly different callback
2254** and callback data argument.
2255*/
2256static int shell_exec(
2257 sqlite3 *db, /* An open database */
2258 const char *zSql, /* SQL to be evaluated */
2259 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2260 /* (not the same as sqlite3_exec) */
2261 ShellState *pArg, /* Pointer to ShellState */
2262 char **pzErrMsg /* Error msg written here */
2263){
2264 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2265 int rc = SQLITE_OK; /* Return Code */
2266 int rc2;
2267 const char *zLeftover; /* Tail of unprocessed SQL */
2268
2269 if( pzErrMsg ){
2270 *pzErrMsg = NULL;
2271 }
2272
2273 while( zSql[0] && (SQLITE_OK == rc) ){
2274 static const char *zStmtSql;
2275 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2276 if( SQLITE_OK != rc ){
2277 if( pzErrMsg ){
2278 *pzErrMsg = save_err_msg(db);
2279 }
2280 }else{
2281 if( !pStmt ){
2282 /* this happens for a comment or white-space */
2283 zSql = zLeftover;
2284 while( IsSpace(zSql[0]) ) zSql++;
2285 continue;
2286 }
2287 zStmtSql = sqlite3_sql(pStmt);
2288 if( zStmtSql==0 ) zStmtSql = "";
2289 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2290
2291 /* save off the prepared statment handle and reset row count */
2292 if( pArg ){
2293 pArg->pStmt = pStmt;
2294 pArg->cnt = 0;
2295 }
2296
2297 /* echo the sql statement if echo on */
2298 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2299 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2300 }
2301
2302 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2303 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2304 sqlite3_stmt *pExplain;
2305 char *zEQP;
2306 disable_debug_trace_modes();
2307 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2308 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2309 if( rc==SQLITE_OK ){
2310 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2311 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2312 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2313 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2314 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2315 }
2316 }
2317 sqlite3_finalize(pExplain);
2318 sqlite3_free(zEQP);
2319 if( pArg->autoEQP>=2 ){
2320 /* Also do an EXPLAIN for ".eqp full" mode */
2321 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2322 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2323 if( rc==SQLITE_OK ){
2324 pArg->cMode = MODE_Explain;
2325 explain_data_prepare(pArg, pExplain);
2326 exec_prepared_stmt(pArg, pExplain, xCallback);
2327 explain_data_delete(pArg);
2328 }
2329 sqlite3_finalize(pExplain);
2330 sqlite3_free(zEQP);
2331 }
2332 restore_debug_trace_modes();
2333 }
2334
2335 if( pArg ){
2336 pArg->cMode = pArg->mode;
2337 if( pArg->autoExplain
2338 && sqlite3_column_count(pStmt)==8
2339 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2340 ){
2341 pArg->cMode = MODE_Explain;
2342 }
2343
2344 /* If the shell is currently in ".explain" mode, gather the extra
2345 ** data required to add indents to the output.*/
2346 if( pArg->cMode==MODE_Explain ){
2347 explain_data_prepare(pArg, pStmt);
2348 }
2349 }
2350
2351 exec_prepared_stmt(pArg, pStmt, xCallback);
2352 explain_data_delete(pArg);
2353
2354 /* print usage stats if stats on */
2355 if( pArg && pArg->statsOn ){
2356 display_stats(db, pArg, 0);
2357 }
2358
2359 /* print loop-counters if required */
2360 if( pArg && pArg->scanstatsOn ){
2361 display_scanstats(db, pArg);
2362 }
2363
2364 /* Finalize the statement just executed. If this fails, save a
2365 ** copy of the error message. Otherwise, set zSql to point to the
2366 ** next statement to execute. */
2367 rc2 = sqlite3_finalize(pStmt);
2368 if( rc!=SQLITE_NOMEM ) rc = rc2;
2369 if( rc==SQLITE_OK ){
2370 zSql = zLeftover;
2371 while( IsSpace(zSql[0]) ) zSql++;
2372 }else if( pzErrMsg ){
2373 *pzErrMsg = save_err_msg(db);
2374 }
2375
2376 /* clear saved stmt handle */
2377 if( pArg ){
2378 pArg->pStmt = NULL;
2379 }
2380 }
2381 } /* end while */
2382
2383 return rc;
2384}
2385
2386/*
2387** Release memory previously allocated by tableColumnList().
2388*/
2389static void freeColumnList(char **azCol){
2390 int i;
2391 for(i=1; azCol[i]; i++){
2392 sqlite3_free(azCol[i]);
2393 }
2394 /* azCol[0] is a static string */
2395 sqlite3_free(azCol);
2396}
2397
2398/*
2399** Return a list of pointers to strings which are the names of all
2400** columns in table zTab. The memory to hold the names is dynamically
2401** allocated and must be released by the caller using a subsequent call
2402** to freeColumnList().
2403**
2404** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2405** value that needs to be preserved, then azCol[0] is filled in with the
2406** name of the rowid column.
2407**
2408** The first regular column in the table is azCol[1]. The list is terminated
2409** by an entry with azCol[i]==0.
2410*/
2411static char **tableColumnList(ShellState *p, const char *zTab){
2412 char **azCol = 0;
2413 sqlite3_stmt *pStmt;
2414 char *zSql;
2415 int nCol = 0;
2416 int nAlloc = 0;
2417 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2418 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2419 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2420 int rc;
2421
2422 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2423 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2424 sqlite3_free(zSql);
2425 if( rc ) return 0;
2426 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2427 if( nCol>=nAlloc-2 ){
2428 nAlloc = nAlloc*2 + nCol + 10;
2429 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2430 if( azCol==0 ){
2431 raw_printf(stderr, "Error: out of memory\n");
2432 exit(1);
2433 }
2434 }
2435 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2436 if( sqlite3_column_int(pStmt, 5) ){
2437 nPK++;
2438 if( nPK==1
2439 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2440 "INTEGER")==0
2441 ){
2442 isIPK = 1;
2443 }else{
2444 isIPK = 0;
2445 }
2446 }
2447 }
2448 sqlite3_finalize(pStmt);
2449 azCol[0] = 0;
2450 azCol[nCol+1] = 0;
2451
2452 /* The decision of whether or not a rowid really needs to be preserved
2453 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2454 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2455 ** rowids on tables where the rowid is inaccessible because there are other
2456 ** columns in the table named "rowid", "_rowid_", and "oid".
2457 */
2458 if( preserveRowid && isIPK ){
2459 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2460 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2461 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2462 ** ROWID aliases. To distinguish these cases, check to see if
2463 ** there is a "pk" entry in "PRAGMA index_list". There will be
2464 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2465 */
2466 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2467 " WHERE origin='pk'", zTab);
2468 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2469 sqlite3_free(zSql);
2470 if( rc ){
2471 freeColumnList(azCol);
2472 return 0;
2473 }
2474 rc = sqlite3_step(pStmt);
2475 sqlite3_finalize(pStmt);
2476 preserveRowid = rc==SQLITE_ROW;
2477 }
2478 if( preserveRowid ){
2479 /* Only preserve the rowid if we can find a name to use for the
2480 ** rowid */
2481 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2482 int i, j;
2483 for(j=0; j<3; j++){
2484 for(i=1; i<=nCol; i++){
2485 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2486 }
2487 if( i>nCol ){
2488 /* At this point, we know that azRowid[j] is not the name of any
2489 ** ordinary column in the table. Verify that azRowid[j] is a valid
2490 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2491 ** tables will fail this last check */
2492 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2493 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2494 break;
2495 }
2496 }
2497 }
2498 return azCol;
2499}
2500
2501/*
2502** Toggle the reverse_unordered_selects setting.
2503*/
2504static void toggleSelectOrder(sqlite3 *db){
2505 sqlite3_stmt *pStmt = 0;
2506 int iSetting = 0;
2507 char zStmt[100];
2508 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2509 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2510 iSetting = sqlite3_column_int(pStmt, 0);
2511 }
2512 sqlite3_finalize(pStmt);
2513 sqlite3_snprintf(sizeof(zStmt), zStmt,
2514 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2515 sqlite3_exec(db, zStmt, 0, 0, 0);
2516}
2517
2518/*
2519** This is a different callback routine used for dumping the database.
2520** Each row received by this callback consists of a table name,
2521** the table type ("index" or "table") and SQL to create the table.
2522** This routine should print text sufficient to recreate the table.
2523*/
2524static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2525 int rc;
2526 const char *zTable;
2527 const char *zType;
2528 const char *zSql;
2529 ShellState *p = (ShellState *)pArg;
2530
2531 UNUSED_PARAMETER(azNotUsed);
2532 if( nArg!=3 ) return 1;
2533 zTable = azArg[0];
2534 zType = azArg[1];
2535 zSql = azArg[2];
2536
2537 if( strcmp(zTable, "sqlite_sequence")==0 ){
2538 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2539 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2540 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2541 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2542 return 0;
2543 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2544 char *zIns;
2545 if( !p->writableSchema ){
2546 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2547 p->writableSchema = 1;
2548 }
2549 zIns = sqlite3_mprintf(
2550 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2551 "VALUES('table','%q','%q',0,'%q');",
2552 zTable, zTable, zSql);
2553 utf8_printf(p->out, "%s\n", zIns);
2554 sqlite3_free(zIns);
2555 return 0;
2556 }else{
2557 printSchemaLine(p->out, zSql, ";\n");
2558 }
2559
2560 if( strcmp(zType, "table")==0 ){
2561 ShellText sSelect;
2562 ShellText sTable;
2563 char **azCol;
2564 int i;
2565 char *savedDestTable;
2566 int savedMode;
2567
2568 azCol = tableColumnList(p, zTable);
2569 if( azCol==0 ){
2570 p->nErr++;
2571 return 0;
2572 }
2573
2574 /* Always quote the table name, even if it appears to be pure ascii,
2575 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2576 initText(&sTable);
2577 appendText(&sTable, zTable, quoteChar(zTable));
2578 /* If preserving the rowid, add a column list after the table name.
2579 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2580 ** instead of the usual "INSERT INTO tab VALUES(...)".
2581 */
2582 if( azCol[0] ){
2583 appendText(&sTable, "(", 0);
2584 appendText(&sTable, azCol[0], 0);
2585 for(i=1; azCol[i]; i++){
2586 appendText(&sTable, ",", 0);
2587 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2588 }
2589 appendText(&sTable, ")", 0);
2590 }
2591
2592 /* Build an appropriate SELECT statement */
2593 initText(&sSelect);
2594 appendText(&sSelect, "SELECT ", 0);
2595 if( azCol[0] ){
2596 appendText(&sSelect, azCol[0], 0);
2597 appendText(&sSelect, ",", 0);
2598 }
2599 for(i=1; azCol[i]; i++){
2600 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2601 if( azCol[i+1] ){
2602 appendText(&sSelect, ",", 0);
2603 }
2604 }
2605 freeColumnList(azCol);
2606 appendText(&sSelect, " FROM ", 0);
2607 appendText(&sSelect, zTable, quoteChar(zTable));
2608
2609 savedDestTable = p->zDestTable;
2610 savedMode = p->mode;
2611 p->zDestTable = sTable.z;
2612 p->mode = p->cMode = MODE_Insert;
2613 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2614 if( (rc&0xff)==SQLITE_CORRUPT ){
2615 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2616 toggleSelectOrder(p->db);
2617 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2618 toggleSelectOrder(p->db);
2619 }
2620 p->zDestTable = savedDestTable;
2621 p->mode = savedMode;
2622 freeText(&sTable);
2623 freeText(&sSelect);
2624 if( rc ) p->nErr++;
2625 }
2626 return 0;
2627}
2628
2629/*
2630** Run zQuery. Use dump_callback() as the callback routine so that
2631** the contents of the query are output as SQL statements.
2632**
2633** If we get a SQLITE_CORRUPT error, rerun the query after appending
2634** "ORDER BY rowid DESC" to the end.
2635*/
2636static int run_schema_dump_query(
2637 ShellState *p,
2638 const char *zQuery
2639){
2640 int rc;
2641 char *zErr = 0;
2642 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2643 if( rc==SQLITE_CORRUPT ){
2644 char *zQ2;
2645 int len = strlen30(zQuery);
2646 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2647 if( zErr ){
2648 utf8_printf(p->out, "/****** %s ******/\n", zErr);
2649 sqlite3_free(zErr);
2650 zErr = 0;
2651 }
2652 zQ2 = malloc( len+100 );
2653 if( zQ2==0 ) return rc;
2654 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2655 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2656 if( rc ){
2657 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2658 }else{
2659 rc = SQLITE_CORRUPT;
2660 }
2661 sqlite3_free(zErr);
2662 free(zQ2);
2663 }
2664 return rc;
2665}
2666
2667/*
2668** Text of a help message
2669*/
2670static char zHelp[] =
2671#ifndef SQLITE_OMIT_AUTHORIZATION
2672 ".auth ON|OFF Show authorizer callbacks\n"
2673#endif
2674 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2675 ".bail on|off Stop after hitting an error. Default OFF\n"
2676 ".binary on|off Turn binary output on or off. Default OFF\n"
2677 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
2678 ".changes on|off Show number of rows changed by SQL\n"
2679 ".check GLOB Fail if output since .testcase does not match\n"
2680 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2681 ".databases List names and files of attached databases\n"
2682 ".dbinfo ?DB? Show status information about the database\n"
2683 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2684 " If TABLE specified, only dump tables matching\n"
2685 " LIKE pattern TABLE.\n"
2686 ".echo on|off Turn command echo on or off\n"
2687 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2688 ".exit Exit this program\n"
2689/* Because explain mode comes on automatically now, the ".explain" mode
2690** is removed from the help screen. It is still supported for legacy, however */
2691/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2692 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2693 ".headers on|off Turn display of headers on or off\n"
2694 ".help Show this message\n"
2695 ".import FILE TABLE Import data from FILE into TABLE\n"
2696#ifndef SQLITE_OMIT_TEST_CONTROL
2697 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
2698#endif
2699 ".indexes ?TABLE? Show names of all indexes\n"
2700 " If TABLE specified, only show indexes for tables\n"
2701 " matching LIKE pattern TABLE.\n"
2702#ifdef SQLITE_ENABLE_IOTRACE
2703 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2704#endif
2705 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2706 ".lint OPTIONS Report potential schema issues. Options:\n"
2707 " fkey-indexes Find missing foreign key indexes\n"
2708#ifndef SQLITE_OMIT_LOAD_EXTENSION
2709 ".load FILE ?ENTRY? Load an extension library\n"
2710#endif
2711 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2712 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2713 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2714 " csv Comma-separated values\n"
2715 " column Left-aligned columns. (See .width)\n"
2716 " html HTML <table> code\n"
2717 " insert SQL insert statements for TABLE\n"
2718 " line One value per line\n"
2719 " list Values delimited by \"|\"\n"
2720 " quote Escape answers as for SQL\n"
2721 " tabs Tab-separated values\n"
2722 " tcl TCL list elements\n"
2723 ".nullvalue STRING Use STRING in place of NULL values\n"
2724 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2725 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2726 " The --new option starts with an empty file\n"
2727 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2728 ".print STRING... Print literal STRING\n"
2729 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2730 ".quit Exit this program\n"
2731 ".read FILENAME Execute SQL in FILENAME\n"
2732 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2733 ".save FILE Write in-memory database into FILE\n"
2734 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2735 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2736 " Add --indent for pretty-printing\n"
2737 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
2738 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2739 " separator for both the output mode and .import\n"
2740#if defined(SQLITE_ENABLE_SESSION)
2741 ".session CMD ... Create or control sessions\n"
2742#endif
2743 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
2744 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2745 ".show Show the current values for various settings\n"
2746 ".stats ?on|off? Show stats or turn stats on or off\n"
2747 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2748 ".tables ?TABLE? List names of tables\n"
2749 " If TABLE specified, only list tables matching\n"
2750 " LIKE pattern TABLE.\n"
2751 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2752 ".timeout MS Try opening locked tables for MS milliseconds\n"
2753 ".timer on|off Turn SQL timer on or off\n"
2754 ".trace FILE|off Output each SQL statement as it is run\n"
2755 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2756 ".vfslist List all available VFSes\n"
2757 ".vfsname ?AUX? Print the name of the VFS stack\n"
2758 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2759 " Negative values right-justify\n"
2760;
2761
2762#if defined(SQLITE_ENABLE_SESSION)
2763/*
2764** Print help information for the ".sessions" command
2765*/
2766void session_help(ShellState *p){
2767 raw_printf(p->out,
2768 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2769 "If ?NAME? is omitted, the first defined session is used.\n"
2770 "Subcommands:\n"
2771 " attach TABLE Attach TABLE\n"
2772 " changeset FILE Write a changeset into FILE\n"
2773 " close Close one session\n"
2774 " enable ?BOOLEAN? Set or query the enable bit\n"
2775 " filter GLOB... Reject tables matching GLOBs\n"
2776 " indirect ?BOOLEAN? Mark or query the indirect status\n"
2777 " isempty Query whether the session is empty\n"
2778 " list List currently open session names\n"
2779 " open DB NAME Open a new session on DB\n"
2780 " patchset FILE Write a patchset into FILE\n"
2781 );
2782}
2783#endif
2784
2785
2786/* Forward reference */
2787static int process_input(ShellState *p, FILE *in);
2788
2789/*
2790** Read the content of file zName into memory obtained from sqlite3_malloc64()
2791** and return a pointer to the buffer. The caller is responsible for freeing
2792** the memory.
2793**
2794** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
2795** read.
2796**
2797** For convenience, a nul-terminator byte is always appended to the data read
2798** from the file before the buffer is returned. This byte is not included in
2799** the final value of (*pnByte), if applicable.
2800**
2801** NULL is returned if any error is encountered. The final value of *pnByte
2802** is undefined in this case.
2803*/
2804static char *readFile(const char *zName, int *pnByte){
2805 FILE *in = fopen(zName, "rb");
2806 long nIn;
2807 size_t nRead;
2808 char *pBuf;
2809 if( in==0 ) return 0;
2810 fseek(in, 0, SEEK_END);
2811 nIn = ftell(in);
2812 rewind(in);
2813 pBuf = sqlite3_malloc64( nIn+1 );
2814 if( pBuf==0 ) return 0;
2815 nRead = fread(pBuf, nIn, 1, in);
2816 fclose(in);
2817 if( nRead!=1 ){
2818 sqlite3_free(pBuf);
2819 return 0;
2820 }
2821 pBuf[nIn] = 0;
2822 if( pnByte ) *pnByte = nIn;
2823 return pBuf;
2824}
2825
2826#if defined(SQLITE_ENABLE_SESSION)
2827/*
2828** Close a single OpenSession object and release all of its associated
2829** resources.
2830*/
2831static void session_close(OpenSession *pSession){
2832 int i;
2833 sqlite3session_delete(pSession->p);
2834 sqlite3_free(pSession->zName);
2835 for(i=0; i<pSession->nFilter; i++){
2836 sqlite3_free(pSession->azFilter[i]);
2837 }
2838 sqlite3_free(pSession->azFilter);
2839 memset(pSession, 0, sizeof(OpenSession));
2840}
2841#endif
2842
2843/*
2844** Close all OpenSession objects and release all associated resources.
2845*/
2846#if defined(SQLITE_ENABLE_SESSION)
2847static void session_close_all(ShellState *p){
2848 int i;
2849 for(i=0; i<p->nSession; i++){
2850 session_close(&p->aSession[i]);
2851 }
2852 p->nSession = 0;
2853}
2854#else
2855# define session_close_all(X)
2856#endif
2857
2858/*
2859** Implementation of the xFilter function for an open session. Omit
2860** any tables named by ".session filter" but let all other table through.
2861*/
2862#if defined(SQLITE_ENABLE_SESSION)
2863static int session_filter(void *pCtx, const char *zTab){
2864 OpenSession *pSession = (OpenSession*)pCtx;
2865 int i;
2866 for(i=0; i<pSession->nFilter; i++){
2867 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
2868 }
2869 return 1;
2870}
2871#endif
2872
2873/*
2874** Make sure the database is open. If it is not, then open it. If
2875** the database fails to open, print an error message and exit.
2876*/
2877static void open_db(ShellState *p, int keepAlive){
2878 if( p->db==0 ){
2879 sqlite3_initialize();
2880 sqlite3_open(p->zDbFilename, &p->db);
2881 globalDb = p->db;
2882 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
2883 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
2884 p->zDbFilename, sqlite3_errmsg(p->db));
2885 if( keepAlive ) return;
2886 exit(1);
2887 }
2888#ifndef SQLITE_OMIT_LOAD_EXTENSION
2889 sqlite3_enable_load_extension(p->db, 1);
2890#endif
2891 sqlite3_fileio_init(p->db, 0, 0);
2892 sqlite3_shathree_init(p->db, 0, 0);
2893 sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
2894 shellAddSchemaName, 0, 0);
2895
2896 }
2897}
2898
2899/*
2900** Do C-language style dequoting.
2901**
2902** \a -> alarm
2903** \b -> backspace
2904** \t -> tab
2905** \n -> newline
2906** \v -> vertical tab
2907** \f -> form feed
2908** \r -> carriage return
2909** \s -> space
2910** \" -> "
2911** \' -> '
2912** \\ -> backslash
2913** \NNN -> ascii character NNN in octal
2914*/
2915static void resolve_backslashes(char *z){
2916 int i, j;
2917 char c;
2918 while( *z && *z!='\\' ) z++;
2919 for(i=j=0; (c = z[i])!=0; i++, j++){
2920 if( c=='\\' && z[i+1]!=0 ){
2921 c = z[++i];
2922 if( c=='a' ){
2923 c = '\a';
2924 }else if( c=='b' ){
2925 c = '\b';
2926 }else if( c=='t' ){
2927 c = '\t';
2928 }else if( c=='n' ){
2929 c = '\n';
2930 }else if( c=='v' ){
2931 c = '\v';
2932 }else if( c=='f' ){
2933 c = '\f';
2934 }else if( c=='r' ){
2935 c = '\r';
2936 }else if( c=='"' ){
2937 c = '"';
2938 }else if( c=='\'' ){
2939 c = '\'';
2940 }else if( c=='\\' ){
2941 c = '\\';
2942 }else if( c>='0' && c<='7' ){
2943 c -= '0';
2944 if( z[i+1]>='0' && z[i+1]<='7' ){
2945 i++;
2946 c = (c<<3) + z[i] - '0';
2947 if( z[i+1]>='0' && z[i+1]<='7' ){
2948 i++;
2949 c = (c<<3) + z[i] - '0';
2950 }
2951 }
2952 }
2953 }
2954 z[j] = c;
2955 }
2956 if( j<i ) z[j] = 0;
2957}
2958
2959/*
2960** Return the value of a hexadecimal digit. Return -1 if the input
2961** is not a hex digit.
2962*/
2963static int hexDigitValue(char c){
2964 if( c>='0' && c<='9' ) return c - '0';
2965 if( c>='a' && c<='f' ) return c - 'a' + 10;
2966 if( c>='A' && c<='F' ) return c - 'A' + 10;
2967 return -1;
2968}
2969
2970/*
2971** Interpret zArg as an integer value, possibly with suffixes.
2972*/
2973static sqlite3_int64 integerValue(const char *zArg){
2974 sqlite3_int64 v = 0;
2975 static const struct { char *zSuffix; int iMult; } aMult[] = {
2976 { "KiB", 1024 },
2977 { "MiB", 1024*1024 },
2978 { "GiB", 1024*1024*1024 },
2979 { "KB", 1000 },
2980 { "MB", 1000000 },
2981 { "GB", 1000000000 },
2982 { "K", 1000 },
2983 { "M", 1000000 },
2984 { "G", 1000000000 },
2985 };
2986 int i;
2987 int isNeg = 0;
2988 if( zArg[0]=='-' ){
2989 isNeg = 1;
2990 zArg++;
2991 }else if( zArg[0]=='+' ){
2992 zArg++;
2993 }
2994 if( zArg[0]=='0' && zArg[1]=='x' ){
2995 int x;
2996 zArg += 2;
2997 while( (x = hexDigitValue(zArg[0]))>=0 ){
2998 v = (v<<4) + x;
2999 zArg++;
3000 }
3001 }else{
3002 while( IsDigit(zArg[0]) ){
3003 v = v*10 + zArg[0] - '0';
3004 zArg++;
3005 }
3006 }
3007 for(i=0; i<ArraySize(aMult); i++){
3008 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3009 v *= aMult[i].iMult;
3010 break;
3011 }
3012 }
3013 return isNeg? -v : v;
3014}
3015
3016/*
3017** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3018** for TRUE and FALSE. Return the integer value if appropriate.
3019*/
3020static int booleanValue(const char *zArg){
3021 int i;
3022 if( zArg[0]=='0' && zArg[1]=='x' ){
3023 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3024 }else{
3025 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3026 }
3027 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3028 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3029 return 1;
3030 }
3031 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3032 return 0;
3033 }
3034 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3035 zArg);
3036 return 0;
3037}
3038
3039/*
3040** Set or clear a shell flag according to a boolean value.
3041*/
3042static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3043 if( booleanValue(zArg) ){
3044 ShellSetFlag(p, mFlag);
3045 }else{
3046 ShellClearFlag(p, mFlag);
3047 }
3048}
3049
3050/*
3051** Close an output file, assuming it is not stderr or stdout
3052*/
3053static void output_file_close(FILE *f){
3054 if( f && f!=stdout && f!=stderr ) fclose(f);
3055}
3056
3057/*
3058** Try to open an output file. The names "stdout" and "stderr" are
3059** recognized and do the right thing. NULL is returned if the output
3060** filename is "off".
3061*/
3062static FILE *output_file_open(const char *zFile){
3063 FILE *f;
3064 if( strcmp(zFile,"stdout")==0 ){
3065 f = stdout;
3066 }else if( strcmp(zFile, "stderr")==0 ){
3067 f = stderr;
3068 }else if( strcmp(zFile, "off")==0 ){
3069 f = 0;
3070 }else{
3071 f = fopen(zFile, "wb");
3072 if( f==0 ){
3073 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3074 }
3075 }
3076 return f;
3077}
3078
3079#if !defined(SQLITE_UNTESTABLE)
3080#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3081/*
3082** A routine for handling output from sqlite3_trace().
3083*/
3084static int sql_trace_callback(
3085 unsigned mType,
3086 void *pArg,
3087 void *pP,
3088 void *pX
3089){
3090 FILE *f = (FILE*)pArg;
3091 UNUSED_PARAMETER(mType);
3092 UNUSED_PARAMETER(pP);
3093 if( f ){
3094 const char *z = (const char*)pX;
3095 int i = (int)strlen(z);
3096 while( i>0 && z[i-1]==';' ){ i--; }
3097 utf8_printf(f, "%.*s;\n", i, z);
3098 }
3099 return 0;
3100}
3101#endif
3102#endif
3103
3104/*
3105** A no-op routine that runs with the ".breakpoint" doc-command. This is
3106** a useful spot to set a debugger breakpoint.
3107*/
3108static void test_breakpoint(void){
3109 static int nCall = 0;
3110 nCall++;
3111}
3112
3113/*
3114** An object used to read a CSV and other files for import.
3115*/
3116typedef struct ImportCtx ImportCtx;
3117struct ImportCtx {
3118 const char *zFile; /* Name of the input file */
3119 FILE *in; /* Read the CSV text from this input stream */
3120 char *z; /* Accumulated text for a field */
3121 int n; /* Number of bytes in z */
3122 int nAlloc; /* Space allocated for z[] */
3123 int nLine; /* Current line number */
3124 int bNotFirst; /* True if one or more bytes already read */
3125 int cTerm; /* Character that terminated the most recent field */
3126 int cColSep; /* The column separator character. (Usually ",") */
3127 int cRowSep; /* The row separator character. (Usually "\n") */
3128};
3129
3130/* Append a single byte to z[] */
3131static void import_append_char(ImportCtx *p, int c){
3132 if( p->n+1>=p->nAlloc ){
3133 p->nAlloc += p->nAlloc + 100;
3134 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3135 if( p->z==0 ){
3136 raw_printf(stderr, "out of memory\n");
3137 exit(1);
3138 }
3139 }
3140 p->z[p->n++] = (char)c;
3141}
3142
3143/* Read a single field of CSV text. Compatible with rfc4180 and extended
3144** with the option of having a separator other than ",".
3145**
3146** + Input comes from p->in.
3147** + Store results in p->z of length p->n. Space to hold p->z comes
3148** from sqlite3_malloc64().
3149** + Use p->cSep as the column separator. The default is ",".
3150** + Use p->rSep as the row separator. The default is "\n".
3151** + Keep track of the line number in p->nLine.
3152** + Store the character that terminates the field in p->cTerm. Store
3153** EOF on end-of-file.
3154** + Report syntax errors on stderr
3155*/
3156static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3157 int c;
3158 int cSep = p->cColSep;
3159 int rSep = p->cRowSep;
3160 p->n = 0;
3161 c = fgetc(p->in);
3162 if( c==EOF || seenInterrupt ){
3163 p->cTerm = EOF;
3164 return 0;
3165 }
3166 if( c=='"' ){
3167 int pc, ppc;
3168 int startLine = p->nLine;
3169 int cQuote = c;
3170 pc = ppc = 0;
3171 while( 1 ){
3172 c = fgetc(p->in);
3173 if( c==rSep ) p->nLine++;
3174 if( c==cQuote ){
3175 if( pc==cQuote ){
3176 pc = 0;
3177 continue;
3178 }
3179 }
3180 if( (c==cSep && pc==cQuote)
3181 || (c==rSep && pc==cQuote)
3182 || (c==rSep && pc=='\r' && ppc==cQuote)
3183 || (c==EOF && pc==cQuote)
3184 ){
3185 do{ p->n--; }while( p->z[p->n]!=cQuote );
3186 p->cTerm = c;
3187 break;
3188 }
3189 if( pc==cQuote && c!='\r' ){
3190 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3191 p->zFile, p->nLine, cQuote);
3192 }
3193 if( c==EOF ){
3194 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3195 p->zFile, startLine, cQuote);
3196 p->cTerm = c;
3197 break;
3198 }
3199 import_append_char(p, c);
3200 ppc = pc;
3201 pc = c;
3202 }
3203 }else{
3204 /* If this is the first field being parsed and it begins with the
3205 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3206 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3207 import_append_char(p, c);
3208 c = fgetc(p->in);
3209 if( (c&0xff)==0xbb ){
3210 import_append_char(p, c);
3211 c = fgetc(p->in);
3212 if( (c&0xff)==0xbf ){
3213 p->bNotFirst = 1;
3214 p->n = 0;
3215 return csv_read_one_field(p);
3216 }
3217 }
3218 }
3219 while( c!=EOF && c!=cSep && c!=rSep ){
3220 import_append_char(p, c);
3221 c = fgetc(p->in);
3222 }
3223 if( c==rSep ){
3224 p->nLine++;
3225 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3226 }
3227 p->cTerm = c;
3228 }
3229 if( p->z ) p->z[p->n] = 0;
3230 p->bNotFirst = 1;
3231 return p->z;
3232}
3233
3234/* Read a single field of ASCII delimited text.
3235**
3236** + Input comes from p->in.
3237** + Store results in p->z of length p->n. Space to hold p->z comes
3238** from sqlite3_malloc64().
3239** + Use p->cSep as the column separator. The default is "\x1F".
3240** + Use p->rSep as the row separator. The default is "\x1E".
3241** + Keep track of the row number in p->nLine.
3242** + Store the character that terminates the field in p->cTerm. Store
3243** EOF on end-of-file.
3244** + Report syntax errors on stderr
3245*/
3246static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3247 int c;
3248 int cSep = p->cColSep;
3249 int rSep = p->cRowSep;
3250 p->n = 0;
3251 c = fgetc(p->in);
3252 if( c==EOF || seenInterrupt ){
3253 p->cTerm = EOF;
3254 return 0;
3255 }
3256 while( c!=EOF && c!=cSep && c!=rSep ){
3257 import_append_char(p, c);
3258 c = fgetc(p->in);
3259 }
3260 if( c==rSep ){
3261 p->nLine++;
3262 }
3263 p->cTerm = c;
3264 if( p->z ) p->z[p->n] = 0;
3265 return p->z;
3266}
3267
3268/*
3269** Try to transfer data for table zTable. If an error is seen while
3270** moving forward, try to go backwards. The backwards movement won't
3271** work for WITHOUT ROWID tables.
3272*/
3273static void tryToCloneData(
3274 ShellState *p,
3275 sqlite3 *newDb,
3276 const char *zTable
3277){
3278 sqlite3_stmt *pQuery = 0;
3279 sqlite3_stmt *pInsert = 0;
3280 char *zQuery = 0;
3281 char *zInsert = 0;
3282 int rc;
3283 int i, j, n;
3284 int nTable = (int)strlen(zTable);
3285 int k = 0;
3286 int cnt = 0;
3287 const int spinRate = 10000;
3288
3289 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3290 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3291 if( rc ){
3292 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3293 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3294 zQuery);
3295 goto end_data_xfer;
3296 }
3297 n = sqlite3_column_count(pQuery);
3298 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3299 if( zInsert==0 ){
3300 raw_printf(stderr, "out of memory\n");
3301 goto end_data_xfer;
3302 }
3303 sqlite3_snprintf(200+nTable,zInsert,
3304 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3305 i = (int)strlen(zInsert);
3306 for(j=1; j<n; j++){
3307 memcpy(zInsert+i, ",?", 2);
3308 i += 2;
3309 }
3310 memcpy(zInsert+i, ");", 3);
3311 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3312 if( rc ){
3313 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3314 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3315 zQuery);
3316 goto end_data_xfer;
3317 }
3318 for(k=0; k<2; k++){
3319 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3320 for(i=0; i<n; i++){
3321 switch( sqlite3_column_type(pQuery, i) ){
3322 case SQLITE_NULL: {
3323 sqlite3_bind_null(pInsert, i+1);
3324 break;
3325 }
3326 case SQLITE_INTEGER: {
3327 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3328 break;
3329 }
3330 case SQLITE_FLOAT: {
3331 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3332 break;
3333 }
3334 case SQLITE_TEXT: {
3335 sqlite3_bind_text(pInsert, i+1,
3336 (const char*)sqlite3_column_text(pQuery,i),
3337 -1, SQLITE_STATIC);
3338 break;
3339 }
3340 case SQLITE_BLOB: {
3341 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3342 sqlite3_column_bytes(pQuery,i),
3343 SQLITE_STATIC);
3344 break;
3345 }
3346 }
3347 } /* End for */
3348 rc = sqlite3_step(pInsert);
3349 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3350 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3351 sqlite3_errmsg(newDb));
3352 }
3353 sqlite3_reset(pInsert);
3354 cnt++;
3355 if( (cnt%spinRate)==0 ){
3356 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3357 fflush(stdout);
3358 }
3359 } /* End while */
3360 if( rc==SQLITE_DONE ) break;
3361 sqlite3_finalize(pQuery);
3362 sqlite3_free(zQuery);
3363 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3364 zTable);
3365 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3366 if( rc ){
3367 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3368 break;
3369 }
3370 } /* End for(k=0...) */
3371
3372end_data_xfer:
3373 sqlite3_finalize(pQuery);
3374 sqlite3_finalize(pInsert);
3375 sqlite3_free(zQuery);
3376 sqlite3_free(zInsert);
3377}
3378
3379
3380/*
3381** Try to transfer all rows of the schema that match zWhere. For
3382** each row, invoke xForEach() on the object defined by that row.
3383** If an error is encountered while moving forward through the
3384** sqlite_master table, try again moving backwards.
3385*/
3386static void tryToCloneSchema(
3387 ShellState *p,
3388 sqlite3 *newDb,
3389 const char *zWhere,
3390 void (*xForEach)(ShellState*,sqlite3*,const char*)
3391){
3392 sqlite3_stmt *pQuery = 0;
3393 char *zQuery = 0;
3394 int rc;
3395 const unsigned char *zName;
3396 const unsigned char *zSql;
3397 char *zErrMsg = 0;
3398
3399 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3400 " WHERE %s", zWhere);
3401 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3402 if( rc ){
3403 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3404 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3405 zQuery);
3406 goto end_schema_xfer;
3407 }
3408 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3409 zName = sqlite3_column_text(pQuery, 0);
3410 zSql = sqlite3_column_text(pQuery, 1);
3411 printf("%s... ", zName); fflush(stdout);
3412 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3413 if( zErrMsg ){
3414 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3415 sqlite3_free(zErrMsg);
3416 zErrMsg = 0;
3417 }
3418 if( xForEach ){
3419 xForEach(p, newDb, (const char*)zName);
3420 }
3421 printf("done\n");
3422 }
3423 if( rc!=SQLITE_DONE ){
3424 sqlite3_finalize(pQuery);
3425 sqlite3_free(zQuery);
3426 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3427 " WHERE %s ORDER BY rowid DESC", zWhere);
3428 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3429 if( rc ){
3430 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3431 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3432 zQuery);
3433 goto end_schema_xfer;
3434 }
3435 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3436 zName = sqlite3_column_text(pQuery, 0);
3437 zSql = sqlite3_column_text(pQuery, 1);
3438 printf("%s... ", zName); fflush(stdout);
3439 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3440 if( zErrMsg ){
3441 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3442 sqlite3_free(zErrMsg);
3443 zErrMsg = 0;
3444 }
3445 if( xForEach ){
3446 xForEach(p, newDb, (const char*)zName);
3447 }
3448 printf("done\n");
3449 }
3450 }
3451end_schema_xfer:
3452 sqlite3_finalize(pQuery);
3453 sqlite3_free(zQuery);
3454}
3455
3456/*
3457** Open a new database file named "zNewDb". Try to recover as much information
3458** as possible out of the main database (which might be corrupt) and write it
3459** into zNewDb.
3460*/
3461static void tryToClone(ShellState *p, const char *zNewDb){
3462 int rc;
3463 sqlite3 *newDb = 0;
3464 if( access(zNewDb,0)==0 ){
3465 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3466 return;
3467 }
3468 rc = sqlite3_open(zNewDb, &newDb);
3469 if( rc ){
3470 utf8_printf(stderr, "Cannot create output database: %s\n",
3471 sqlite3_errmsg(newDb));
3472 }else{
3473 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3474 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3475 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3476 tryToCloneSchema(p, newDb, "type!='table'", 0);
3477 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3478 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3479 }
3480 sqlite3_close(newDb);
3481}
3482
3483/*
3484** Change the output file back to stdout
3485*/
3486static void output_reset(ShellState *p){
3487 if( p->outfile[0]=='|' ){
3488#ifndef SQLITE_OMIT_POPEN
3489 pclose(p->out);
3490#endif
3491 }else{
3492 output_file_close(p->out);
3493 }
3494 p->outfile[0] = 0;
3495 p->out = stdout;
3496}
3497
3498/*
3499** Run an SQL command and return the single integer result.
3500*/
3501static int db_int(ShellState *p, const char *zSql){
3502 sqlite3_stmt *pStmt;
3503 int res = 0;
3504 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3505 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3506 res = sqlite3_column_int(pStmt,0);
3507 }
3508 sqlite3_finalize(pStmt);
3509 return res;
3510}
3511
3512/*
3513** Convert a 2-byte or 4-byte big-endian integer into a native integer
3514*/
3515static unsigned int get2byteInt(unsigned char *a){
3516 return (a[0]<<8) + a[1];
3517}
3518static unsigned int get4byteInt(unsigned char *a){
3519 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3520}
3521
3522/*
3523** Implementation of the ".info" command.
3524**
3525** Return 1 on error, 2 to exit, and 0 otherwise.
3526*/
3527static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3528 static const struct { const char *zName; int ofst; } aField[] = {
3529 { "file change counter:", 24 },
3530 { "database page count:", 28 },
3531 { "freelist page count:", 36 },
3532 { "schema cookie:", 40 },
3533 { "schema format:", 44 },
3534 { "default cache size:", 48 },
3535 { "autovacuum top root:", 52 },
3536 { "incremental vacuum:", 64 },
3537 { "text encoding:", 56 },
3538 { "user version:", 60 },
3539 { "application id:", 68 },
3540 { "software version:", 96 },
3541 };
3542 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3543 { "number of tables:",
3544 "SELECT count(*) FROM %s WHERE type='table'" },
3545 { "number of indexes:",
3546 "SELECT count(*) FROM %s WHERE type='index'" },
3547 { "number of triggers:",
3548 "SELECT count(*) FROM %s WHERE type='trigger'" },
3549 { "number of views:",
3550 "SELECT count(*) FROM %s WHERE type='view'" },
3551 { "schema size:",
3552 "SELECT total(length(sql)) FROM %s" },
3553 };
3554 sqlite3_file *pFile = 0;
3555 int i;
3556 char *zSchemaTab;
3557 char *zDb = nArg>=2 ? azArg[1] : "main";
3558 unsigned char aHdr[100];
3559 open_db(p, 0);
3560 if( p->db==0 ) return 1;
3561 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
3562 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
3563 return 1;
3564 }
3565 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
3566 if( i!=SQLITE_OK ){
3567 raw_printf(stderr, "unable to read database header\n");
3568 return 1;
3569 }
3570 i = get2byteInt(aHdr+16);
3571 if( i==1 ) i = 65536;
3572 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3573 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3574 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3575 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3576 for(i=0; i<ArraySize(aField); i++){
3577 int ofst = aField[i].ofst;
3578 unsigned int val = get4byteInt(aHdr + ofst);
3579 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3580 switch( ofst ){
3581 case 56: {
3582 if( val==1 ) raw_printf(p->out, " (utf8)");
3583 if( val==2 ) raw_printf(p->out, " (utf16le)");
3584 if( val==3 ) raw_printf(p->out, " (utf16be)");
3585 }
3586 }
3587 raw_printf(p->out, "\n");
3588 }
3589 if( zDb==0 ){
3590 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3591 }else if( strcmp(zDb,"temp")==0 ){
3592 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3593 }else{
3594 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3595 }
3596 for(i=0; i<ArraySize(aQuery); i++){
3597 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3598 int val = db_int(p, zSql);
3599 sqlite3_free(zSql);
3600 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3601 }
3602 sqlite3_free(zSchemaTab);
3603 return 0;
3604}
3605
3606/*
3607** Print the current sqlite3_errmsg() value to stderr and return 1.
3608*/
3609static int shellDatabaseError(sqlite3 *db){
3610 const char *zErr = sqlite3_errmsg(db);
3611 utf8_printf(stderr, "Error: %s\n", zErr);
3612 return 1;
3613}
3614
3615/*
3616** Print an out-of-memory message to stderr and return 1.
3617*/
3618static int shellNomemError(void){
3619 raw_printf(stderr, "Error: out of memory\n");
3620 return 1;
3621}
3622
3623/*
3624** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3625** if they match and FALSE (0) if they do not match.
3626**
3627** Globbing rules:
3628**
3629** '*' Matches any sequence of zero or more characters.
3630**
3631** '?' Matches exactly one character.
3632**
3633** [...] Matches one character from the enclosed list of
3634** characters.
3635**
3636** [^...] Matches one character not in the enclosed list.
3637**
3638** '#' Matches any sequence of one or more digits with an
3639** optional + or - sign in front
3640**
3641** ' ' Any span of whitespace matches any other span of
3642** whitespace.
3643**
3644** Extra whitespace at the end of z[] is ignored.
3645*/
3646static int testcase_glob(const char *zGlob, const char *z){
3647 int c, c2;
3648 int invert;
3649 int seen;
3650
3651 while( (c = (*(zGlob++)))!=0 ){
3652 if( IsSpace(c) ){
3653 if( !IsSpace(*z) ) return 0;
3654 while( IsSpace(*zGlob) ) zGlob++;
3655 while( IsSpace(*z) ) z++;
3656 }else if( c=='*' ){
3657 while( (c=(*(zGlob++))) == '*' || c=='?' ){
3658 if( c=='?' && (*(z++))==0 ) return 0;
3659 }
3660 if( c==0 ){
3661 return 1;
3662 }else if( c=='[' ){
3663 while( *z && testcase_glob(zGlob-1,z)==0 ){
3664 z++;
3665 }
3666 return (*z)!=0;
3667 }
3668 while( (c2 = (*(z++)))!=0 ){
3669 while( c2!=c ){
3670 c2 = *(z++);
3671 if( c2==0 ) return 0;
3672 }
3673 if( testcase_glob(zGlob,z) ) return 1;
3674 }
3675 return 0;
3676 }else if( c=='?' ){
3677 if( (*(z++))==0 ) return 0;
3678 }else if( c=='[' ){
3679 int prior_c = 0;
3680 seen = 0;
3681 invert = 0;
3682 c = *(z++);
3683 if( c==0 ) return 0;
3684 c2 = *(zGlob++);
3685 if( c2=='^' ){
3686 invert = 1;
3687 c2 = *(zGlob++);
3688 }
3689 if( c2==']' ){
3690 if( c==']' ) seen = 1;
3691 c2 = *(zGlob++);
3692 }
3693 while( c2 && c2!=']' ){
3694 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3695 c2 = *(zGlob++);
3696 if( c>=prior_c && c<=c2 ) seen = 1;
3697 prior_c = 0;
3698 }else{
3699 if( c==c2 ){
3700 seen = 1;
3701 }
3702 prior_c = c2;
3703 }
3704 c2 = *(zGlob++);
3705 }
3706 if( c2==0 || (seen ^ invert)==0 ) return 0;
3707 }else if( c=='#' ){
3708 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
3709 if( !IsDigit(z[0]) ) return 0;
3710 z++;
3711 while( IsDigit(z[0]) ){ z++; }
3712 }else{
3713 if( c!=(*(z++)) ) return 0;
3714 }
3715 }
3716 while( IsSpace(*z) ){ z++; }
3717 return *z==0;
3718}
3719
3720
3721/*
3722** Compare the string as a command-line option with either one or two
3723** initial "-" characters.
3724*/
3725static int optionMatch(const char *zStr, const char *zOpt){
3726 if( zStr[0]!='-' ) return 0;
3727 zStr++;
3728 if( zStr[0]=='-' ) zStr++;
3729 return strcmp(zStr, zOpt)==0;
3730}
3731
3732/*
3733** Delete a file.
3734*/
3735int shellDeleteFile(const char *zFilename){
3736 int rc;
3737#ifdef _WIN32
3738 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
3739 rc = _wunlink(z);
3740 sqlite3_free(z);
3741#else
3742 rc = unlink(zFilename);
3743#endif
3744 return rc;
3745}
3746
3747
3748/*
3749** The implementation of SQL scalar function fkey_collate_clause(), used
3750** by the ".lint fkey-indexes" command. This scalar function is always
3751** called with four arguments - the parent table name, the parent column name,
3752** the child table name and the child column name.
3753**
3754** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
3755**
3756** If either of the named tables or columns do not exist, this function
3757** returns an empty string. An empty string is also returned if both tables
3758** and columns exist but have the same default collation sequence. Or,
3759** if both exist but the default collation sequences are different, this
3760** function returns the string " COLLATE <parent-collation>", where
3761** <parent-collation> is the default collation sequence of the parent column.
3762*/
3763static void shellFkeyCollateClause(
3764 sqlite3_context *pCtx,
3765 int nVal,
3766 sqlite3_value **apVal
3767){
3768 sqlite3 *db = sqlite3_context_db_handle(pCtx);
3769 const char *zParent;
3770 const char *zParentCol;
3771 const char *zParentSeq;
3772 const char *zChild;
3773 const char *zChildCol;
3774 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
3775 int rc;
3776
3777 assert( nVal==4 );
3778 zParent = (const char*)sqlite3_value_text(apVal[0]);
3779 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
3780 zChild = (const char*)sqlite3_value_text(apVal[2]);
3781 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
3782
3783 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
3784 rc = sqlite3_table_column_metadata(
3785 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
3786 );
3787 if( rc==SQLITE_OK ){
3788 rc = sqlite3_table_column_metadata(
3789 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
3790 );
3791 }
3792
3793 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
3794 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
3795 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
3796 sqlite3_free(z);
3797 }
3798}
3799
3800
3801/*
3802** The implementation of dot-command ".lint fkey-indexes".
3803*/
3804static int lintFkeyIndexes(
3805 ShellState *pState, /* Current shell tool state */
3806 char **azArg, /* Array of arguments passed to dot command */
3807 int nArg /* Number of entries in azArg[] */
3808){
3809 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
3810 FILE *out = pState->out; /* Stream to write non-error output to */
3811 int bVerbose = 0; /* If -verbose is present */
3812 int bGroupByParent = 0; /* If -groupbyparent is present */
3813 int i; /* To iterate through azArg[] */
3814 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
3815 int rc; /* Return code */
3816 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
3817
3818 /*
3819 ** This SELECT statement returns one row for each foreign key constraint
3820 ** in the schema of the main database. The column values are:
3821 **
3822 ** 0. The text of an SQL statement similar to:
3823 **
3824 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
3825 **
3826 ** This is the same SELECT that the foreign keys implementation needs
3827 ** to run internally on child tables. If there is an index that can
3828 ** be used to optimize this query, then it can also be used by the FK
3829 ** implementation to optimize DELETE or UPDATE statements on the parent
3830 ** table.
3831 **
3832 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
3833 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
3834 ** contains an index that can be used to optimize the query.
3835 **
3836 ** 2. Human readable text that describes the child table and columns. e.g.
3837 **
3838 ** "child_table(child_key1, child_key2)"
3839 **
3840 ** 3. Human readable text that describes the parent table and columns. e.g.
3841 **
3842 ** "parent_table(parent_key1, parent_key2)"
3843 **
3844 ** 4. A full CREATE INDEX statement for an index that could be used to
3845 ** optimize DELETE or UPDATE statements on the parent table. e.g.
3846 **
3847 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
3848 **
3849 ** 5. The name of the parent table.
3850 **
3851 ** These six values are used by the C logic below to generate the report.
3852 */
3853 const char *zSql =
3854 "SELECT "
3855 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
3856 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
3857 " || fkey_collate_clause("
3858 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
3859 ", "
3860 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
3861 " || group_concat('*=?', ' AND ') || ')'"
3862 ", "
3863 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
3864 ", "
3865 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
3866 ", "
3867 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
3868 " || ' ON ' || quote(s.name) || '('"
3869 " || group_concat(quote(f.[from]) ||"
3870 " fkey_collate_clause("
3871 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
3872 " || ');'"
3873 ", "
3874 " f.[table] "
3875 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
3876 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
3877 "GROUP BY s.name, f.id "
3878 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
3879 ;
3880 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
3881
3882 for(i=2; i<nArg; i++){
3883 int n = (int)strlen(azArg[i]);
3884 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
3885 bVerbose = 1;
3886 }
3887 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
3888 bGroupByParent = 1;
3889 zIndent = " ";
3890 }
3891 else{
3892 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
3893 azArg[0], azArg[1]
3894 );
3895 return SQLITE_ERROR;
3896 }
3897 }
3898
3899 /* Register the fkey_collate_clause() SQL function */
3900 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
3901 0, shellFkeyCollateClause, 0, 0
3902 );
3903
3904
3905 if( rc==SQLITE_OK ){
3906 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
3907 }
3908 if( rc==SQLITE_OK ){
3909 sqlite3_bind_int(pSql, 1, bGroupByParent);
3910 }
3911
3912 if( rc==SQLITE_OK ){
3913 int rc2;
3914 char *zPrev = 0;
3915 while( SQLITE_ROW==sqlite3_step(pSql) ){
3916 int res = -1;
3917 sqlite3_stmt *pExplain = 0;
3918 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
3919 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
3920 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
3921 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
3922 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
3923 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
3924
3925 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3926 if( rc!=SQLITE_OK ) break;
3927 if( SQLITE_ROW==sqlite3_step(pExplain) ){
3928 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
3929 res = (
3930 0==sqlite3_strglob(zGlob, zPlan)
3931 || 0==sqlite3_strglob(zGlobIPK, zPlan)
3932 );
3933 }
3934 rc = sqlite3_finalize(pExplain);
3935 if( rc!=SQLITE_OK ) break;
3936
3937 if( res<0 ){
3938 raw_printf(stderr, "Error: internal error");
3939 break;
3940 }else{
3941 if( bGroupByParent
3942 && (bVerbose || res==0)
3943 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
3944 ){
3945 raw_printf(out, "-- Parent table %s\n", zParent);
3946 sqlite3_free(zPrev);
3947 zPrev = sqlite3_mprintf("%s", zParent);
3948 }
3949
3950 if( res==0 ){
3951 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
3952 }else if( bVerbose ){
3953 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
3954 zIndent, zFrom, zTarget
3955 );
3956 }
3957 }
3958 }
3959 sqlite3_free(zPrev);
3960
3961 if( rc!=SQLITE_OK ){
3962 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
3963 }
3964
3965 rc2 = sqlite3_finalize(pSql);
3966 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
3967 rc = rc2;
3968 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
3969 }
3970 }else{
3971 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
3972 }
3973
3974 return rc;
3975}
3976
3977/*
3978** Implementation of ".lint" dot command.
3979*/
3980static int lintDotCommand(
3981 ShellState *pState, /* Current shell tool state */
3982 char **azArg, /* Array of arguments passed to dot command */
3983 int nArg /* Number of entries in azArg[] */
3984){
3985 int n;
3986 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
3987 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
3988 return lintFkeyIndexes(pState, azArg, nArg);
3989
3990 usage:
3991 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
3992 raw_printf(stderr, "Where sub-commands are:\n");
3993 raw_printf(stderr, " fkey-indexes\n");
3994 return SQLITE_ERROR;
3995}
3996
3997
3998/*
3999** If an input line begins with "." then invoke this routine to
4000** process that line.
4001**
4002** Return 1 on error, 2 to exit, and 0 otherwise.
4003*/
4004static int do_meta_command(char *zLine, ShellState *p){
4005 int h = 1;
4006 int nArg = 0;
4007 int n, c;
4008 int rc = 0;
4009 char *azArg[50];
4010
4011 /* Parse the input line into tokens.
4012 */
4013 while( zLine[h] && nArg<ArraySize(azArg) ){
4014 while( IsSpace(zLine[h]) ){ h++; }
4015 if( zLine[h]==0 ) break;
4016 if( zLine[h]=='\'' || zLine[h]=='"' ){
4017 int delim = zLine[h++];
4018 azArg[nArg++] = &zLine[h];
4019 while( zLine[h] && zLine[h]!=delim ){
4020 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
4021 h++;
4022 }
4023 if( zLine[h]==delim ){
4024 zLine[h++] = 0;
4025 }
4026 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
4027 }else{
4028 azArg[nArg++] = &zLine[h];
4029 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4030 if( zLine[h] ) zLine[h++] = 0;
4031 resolve_backslashes(azArg[nArg-1]);
4032 }
4033 }
4034
4035 /* Process the input line.
4036 */
4037 if( nArg==0 ) return 0; /* no tokens, no error */
4038 n = strlen30(azArg[0]);
4039 c = azArg[0][0];
4040
4041#ifndef SQLITE_OMIT_AUTHORIZATION
4042 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4043 if( nArg!=2 ){
4044 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4045 rc = 1;
4046 goto meta_command_exit;
4047 }
4048 open_db(p, 0);
4049 if( booleanValue(azArg[1]) ){
4050 sqlite3_set_authorizer(p->db, shellAuth, p);
4051 }else{
4052 sqlite3_set_authorizer(p->db, 0, 0);
4053 }
4054 }else
4055#endif
4056
4057 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4058 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4059 ){
4060 const char *zDestFile = 0;
4061 const char *zDb = 0;
4062 sqlite3 *pDest;
4063 sqlite3_backup *pBackup;
4064 int j;
4065 for(j=1; j<nArg; j++){
4066 const char *z = azArg[j];
4067 if( z[0]=='-' ){
4068 while( z[0]=='-' ) z++;
4069 /* No options to process at this time */
4070 {
4071 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
4072 return 1;
4073 }
4074 }else if( zDestFile==0 ){
4075 zDestFile = azArg[j];
4076 }else if( zDb==0 ){
4077 zDb = zDestFile;
4078 zDestFile = azArg[j];
4079 }else{
4080 raw_printf(stderr, "too many arguments to .backup\n");
4081 return 1;
4082 }
4083 }
4084 if( zDestFile==0 ){
4085 raw_printf(stderr, "missing FILENAME argument on .backup\n");
4086 return 1;
4087 }
4088 if( zDb==0 ) zDb = "main";
4089 rc = sqlite3_open(zDestFile, &pDest);
4090 if( rc!=SQLITE_OK ){
4091 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
4092 sqlite3_close(pDest);
4093 return 1;
4094 }
4095 open_db(p, 0);
4096 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4097 if( pBackup==0 ){
4098 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4099 sqlite3_close(pDest);
4100 return 1;
4101 }
4102 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4103 sqlite3_backup_finish(pBackup);
4104 if( rc==SQLITE_DONE ){
4105 rc = 0;
4106 }else{
4107 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4108 rc = 1;
4109 }
4110 sqlite3_close(pDest);
4111 }else
4112
4113 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4114 if( nArg==2 ){
4115 bail_on_error = booleanValue(azArg[1]);
4116 }else{
4117 raw_printf(stderr, "Usage: .bail on|off\n");
4118 rc = 1;
4119 }
4120 }else
4121
4122 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4123 if( nArg==2 ){
4124 if( booleanValue(azArg[1]) ){
4125 setBinaryMode(p->out, 1);
4126 }else{
4127 setTextMode(p->out, 1);
4128 }
4129 }else{
4130 raw_printf(stderr, "Usage: .binary on|off\n");
4131 rc = 1;
4132 }
4133 }else
4134
4135 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4136 if( nArg==2 ){
4137#if defined(_WIN32) || defined(WIN32)
4138 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4139 rc = !SetCurrentDirectoryW(z);
4140 sqlite3_free(z);
4141#else
4142 rc = chdir(azArg[1]);
4143#endif
4144 if( rc ){
4145 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4146 rc = 1;
4147 }
4148 }else{
4149 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4150 rc = 1;
4151 }
4152 }else
4153
4154 /* The undocumented ".breakpoint" command causes a call to the no-op
4155 ** routine named test_breakpoint().
4156 */
4157 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4158 test_breakpoint();
4159 }else
4160
4161 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4162 if( nArg==2 ){
4163 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
4164 }else{
4165 raw_printf(stderr, "Usage: .changes on|off\n");
4166 rc = 1;
4167 }
4168 }else
4169
4170 /* Cancel output redirection, if it is currently set (by .testcase)
4171 ** Then read the content of the testcase-out.txt file and compare against
4172 ** azArg[1]. If there are differences, report an error and exit.
4173 */
4174 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4175 char *zRes = 0;
4176 output_reset(p);
4177 if( nArg!=2 ){
4178 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
4179 rc = 2;
4180 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
4181 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4182 rc = 2;
4183 }else if( testcase_glob(azArg[1],zRes)==0 ){
4184 utf8_printf(stderr,
4185 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4186 p->zTestcase, azArg[1], zRes);
4187 rc = 2;
4188 }else{
4189 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
4190 p->nCheck++;
4191 }
4192 sqlite3_free(zRes);
4193 }else
4194
4195 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4196 if( nArg==2 ){
4197 tryToClone(p, azArg[1]);
4198 }else{
4199 raw_printf(stderr, "Usage: .clone FILENAME\n");
4200 rc = 1;
4201 }
4202 }else
4203
4204 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
4205 ShellState data;
4206 char *zErrMsg = 0;
4207 open_db(p, 0);
4208 memcpy(&data, p, sizeof(data));
4209 data.showHeader = 0;
4210 data.cMode = data.mode = MODE_List;
4211 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
4212 data.cnt = 0;
4213 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4214 callback, &data, &zErrMsg);
4215 if( zErrMsg ){
4216 utf8_printf(stderr,"Error: %s\n", zErrMsg);
4217 sqlite3_free(zErrMsg);
4218 rc = 1;
4219 }
4220 }else
4221
4222 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4223 rc = shell_dbinfo_command(p, nArg, azArg);
4224 }else
4225
4226 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
4227 const char *zLike = 0;
4228 int i;
4229 int savedShowHeader = p->showHeader;
4230 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
4231 for(i=1; i<nArg; i++){
4232 if( azArg[i][0]=='-' ){
4233 const char *z = azArg[i]+1;
4234 if( z[0]=='-' ) z++;
4235 if( strcmp(z,"preserve-rowids")==0 ){
4236#ifdef SQLITE_OMIT_VIRTUALTABLE
4237 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4238 " with SQLITE_OMIT_VIRTUALTABLE\n");
4239 rc = 1;
4240 goto meta_command_exit;
4241#else
4242 ShellSetFlag(p, SHFLG_PreserveRowid);
4243#endif
4244 }else
4245 if( strcmp(z,"newlines")==0 ){
4246 ShellSetFlag(p, SHFLG_Newlines);
4247 }else
4248 {
4249 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4250 rc = 1;
4251 goto meta_command_exit;
4252 }
4253 }else if( zLike ){
4254 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
4255 "?--newlines? ?LIKE-PATTERN?\n");
4256 rc = 1;
4257 goto meta_command_exit;
4258 }else{
4259 zLike = azArg[i];
4260 }
4261 }
4262 open_db(p, 0);
4263 /* When playing back a "dump", the content might appear in an order
4264 ** which causes immediate foreign key constraints to be violated.
4265 ** So disable foreign-key constraint enforcement to prevent problems. */
4266 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4267 raw_printf(p->out, "BEGIN TRANSACTION;\n");
4268 p->writableSchema = 0;
4269 p->showHeader = 0;
4270 /* Set writable_schema=ON since doing so forces SQLite to initialize
4271 ** as much of the schema as it can even if the sqlite_master table is
4272 ** corrupt. */
4273 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4274 p->nErr = 0;
4275 if( zLike==0 ){
4276 run_schema_dump_query(p,
4277 "SELECT name, type, sql FROM sqlite_master "
4278 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4279 );
4280 run_schema_dump_query(p,
4281 "SELECT name, type, sql FROM sqlite_master "
4282 "WHERE name=='sqlite_sequence'"
4283 );
4284 run_table_dump_query(p,
4285 "SELECT sql FROM sqlite_master "
4286 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4287 );
4288 }else{
4289 char *zSql;
4290 zSql = sqlite3_mprintf(
4291 "SELECT name, type, sql FROM sqlite_master "
4292 "WHERE tbl_name LIKE %Q AND type=='table'"
4293 " AND sql NOT NULL", zLike);
4294 run_schema_dump_query(p,zSql);
4295 sqlite3_free(zSql);
4296 zSql = sqlite3_mprintf(
4297 "SELECT sql FROM sqlite_master "
4298 "WHERE sql NOT NULL"
4299 " AND type IN ('index','trigger','view')"
4300 " AND tbl_name LIKE %Q", zLike);
4301 run_table_dump_query(p, zSql, 0);
4302 sqlite3_free(zSql);
4303 }
4304 if( p->writableSchema ){
4305 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
4306 p->writableSchema = 0;
4307 }
4308 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4309 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
4310 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4311 p->showHeader = savedShowHeader;
4312 }else
4313
4314 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4315 if( nArg==2 ){
4316 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
4317 }else{
4318 raw_printf(stderr, "Usage: .echo on|off\n");
4319 rc = 1;
4320 }
4321 }else
4322
4323 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4324 if( nArg==2 ){
4325 if( strcmp(azArg[1],"full")==0 ){
4326 p->autoEQP = 2;
4327 }else{
4328 p->autoEQP = booleanValue(azArg[1]);
4329 }
4330 }else{
4331 raw_printf(stderr, "Usage: .eqp on|off|full\n");
4332 rc = 1;
4333 }
4334 }else
4335
4336 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
4337 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
4338 rc = 2;
4339 }else
4340
4341 /* The ".explain" command is automatic now. It is largely pointless. It
4342 ** retained purely for backwards compatibility */
4343 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
4344 int val = 1;
4345 if( nArg>=2 ){
4346 if( strcmp(azArg[1],"auto")==0 ){
4347 val = 99;
4348 }else{
4349 val = booleanValue(azArg[1]);
4350 }
4351 }
4352 if( val==1 && p->mode!=MODE_Explain ){
4353 p->normalMode = p->mode;
4354 p->mode = MODE_Explain;
4355 p->autoExplain = 0;
4356 }else if( val==0 ){
4357 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4358 p->autoExplain = 0;
4359 }else if( val==99 ){
4360 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4361 p->autoExplain = 1;
4362 }
4363 }else
4364
4365 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
4366 ShellState data;
4367 char *zErrMsg = 0;
4368 int doStats = 0;
4369 memcpy(&data, p, sizeof(data));
4370 data.showHeader = 0;
4371 data.cMode = data.mode = MODE_Semi;
4372 if( nArg==2 && optionMatch(azArg[1], "indent") ){
4373 data.cMode = data.mode = MODE_Pretty;
4374 nArg = 1;
4375 }
4376 if( nArg!=1 ){
4377 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
4378 rc = 1;
4379 goto meta_command_exit;
4380 }
4381 open_db(p, 0);
4382 rc = sqlite3_exec(p->db,
4383 "SELECT sql FROM"
4384 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4385 " FROM sqlite_master UNION ALL"
4386 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4387 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4388 "ORDER BY rowid",
4389 callback, &data, &zErrMsg
4390 );
4391 if( rc==SQLITE_OK ){
4392 sqlite3_stmt *pStmt;
4393 rc = sqlite3_prepare_v2(p->db,
4394 "SELECT rowid FROM sqlite_master"
4395 " WHERE name GLOB 'sqlite_stat[134]'",
4396 -1, &pStmt, 0);
4397 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4398 sqlite3_finalize(pStmt);
4399 }
4400 if( doStats==0 ){
4401 raw_printf(p->out, "/* No STAT tables available */\n");
4402 }else{
4403 raw_printf(p->out, "ANALYZE sqlite_master;\n");
4404 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4405 callback, &data, &zErrMsg);
4406 data.cMode = data.mode = MODE_Insert;
4407 data.zDestTable = "sqlite_stat1";
4408 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4409 shell_callback, &data,&zErrMsg);
4410 data.zDestTable = "sqlite_stat3";
4411 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4412 shell_callback, &data,&zErrMsg);
4413 data.zDestTable = "sqlite_stat4";
4414 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4415 shell_callback, &data, &zErrMsg);
4416 raw_printf(p->out, "ANALYZE sqlite_master;\n");
4417 }
4418 }else
4419
4420 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4421 if( nArg==2 ){
4422 p->showHeader = booleanValue(azArg[1]);
4423 }else{
4424 raw_printf(stderr, "Usage: .headers on|off\n");
4425 rc = 1;
4426 }
4427 }else
4428
4429 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
4430 utf8_printf(p->out, "%s", zHelp);
4431 }else
4432
4433 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
4434 char *zTable; /* Insert data into this table */
4435 char *zFile; /* Name of file to extra content from */
4436 sqlite3_stmt *pStmt = NULL; /* A statement */
4437 int nCol; /* Number of columns in the table */
4438 int nByte; /* Number of bytes in an SQL string */
4439 int i, j; /* Loop counters */
4440 int needCommit; /* True to COMMIT or ROLLBACK at end */
4441 int nSep; /* Number of bytes in p->colSeparator[] */
4442 char *zSql; /* An SQL statement */
4443 ImportCtx sCtx; /* Reader context */
4444 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4445 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
4446
4447 if( nArg!=3 ){
4448 raw_printf(stderr, "Usage: .import FILE TABLE\n");
4449 goto meta_command_exit;
4450 }
4451 zFile = azArg[1];
4452 zTable = azArg[2];
4453 seenInterrupt = 0;
4454 memset(&sCtx, 0, sizeof(sCtx));
4455 open_db(p, 0);
4456 nSep = strlen30(p->colSeparator);
4457 if( nSep==0 ){
4458 raw_printf(stderr,
4459 "Error: non-null column separator required for import\n");
4460 return 1;
4461 }
4462 if( nSep>1 ){
4463 raw_printf(stderr, "Error: multi-character column separators not allowed"
4464 " for import\n");
4465 return 1;
4466 }
4467 nSep = strlen30(p->rowSeparator);
4468 if( nSep==0 ){
4469 raw_printf(stderr, "Error: non-null row separator required for import\n");
4470 return 1;
4471 }
4472 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4473 /* When importing CSV (only), if the row separator is set to the
4474 ** default output row separator, change it to the default input
4475 ** row separator. This avoids having to maintain different input
4476 ** and output row separators. */
4477 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4478 nSep = strlen30(p->rowSeparator);
4479 }
4480 if( nSep>1 ){
4481 raw_printf(stderr, "Error: multi-character row separators not allowed"
4482 " for import\n");
4483 return 1;
4484 }
4485 sCtx.zFile = zFile;
4486 sCtx.nLine = 1;
4487 if( sCtx.zFile[0]=='|' ){
4488#ifdef SQLITE_OMIT_POPEN
4489 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4490 return 1;
4491#else
4492 sCtx.in = popen(sCtx.zFile+1, "r");
4493 sCtx.zFile = "<pipe>";
4494 xCloser = pclose;
4495#endif
4496 }else{
4497 sCtx.in = fopen(sCtx.zFile, "rb");
4498 xCloser = fclose;
4499 }
4500 if( p->mode==MODE_Ascii ){
4501 xRead = ascii_read_one_field;
4502 }else{
4503 xRead = csv_read_one_field;
4504 }
4505 if( sCtx.in==0 ){
4506 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4507 return 1;
4508 }
4509 sCtx.cColSep = p->colSeparator[0];
4510 sCtx.cRowSep = p->rowSeparator[0];
4511 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
4512 if( zSql==0 ){
4513 raw_printf(stderr, "Error: out of memory\n");
4514 xCloser(sCtx.in);
4515 return 1;
4516 }
4517 nByte = strlen30(zSql);
4518 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4519 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
4520 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
4521 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
4522 char cSep = '(';
4523 while( xRead(&sCtx) ){
4524 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
4525 cSep = ',';
4526 if( sCtx.cTerm!=sCtx.cColSep ) break;
4527 }
4528 if( cSep=='(' ){
4529 sqlite3_free(zCreate);
4530 sqlite3_free(sCtx.z);
4531 xCloser(sCtx.in);
4532 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
4533 return 1;
4534 }
4535 zCreate = sqlite3_mprintf("%z\n)", zCreate);
4536 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
4537 sqlite3_free(zCreate);
4538 if( rc ){
4539 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
4540 sqlite3_errmsg(p->db));
4541 sqlite3_free(sCtx.z);
4542 xCloser(sCtx.in);
4543 return 1;
4544 }
4545 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4546 }
4547 sqlite3_free(zSql);
4548 if( rc ){
4549 if (pStmt) sqlite3_finalize(pStmt);
4550 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
4551 xCloser(sCtx.in);
4552 return 1;
4553 }
4554 nCol = sqlite3_column_count(pStmt);
4555 sqlite3_finalize(pStmt);
4556 pStmt = 0;
4557 if( nCol==0 ) return 0; /* no columns, no error */
4558 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
4559 if( zSql==0 ){
4560 raw_printf(stderr, "Error: out of memory\n");
4561 xCloser(sCtx.in);
4562 return 1;
4563 }
4564 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
4565 j = strlen30(zSql);
4566 for(i=1; i<nCol; i++){
4567 zSql[j++] = ',';
4568 zSql[j++] = '?';
4569 }
4570 zSql[j++] = ')';
4571 zSql[j] = 0;
4572 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4573 sqlite3_free(zSql);
4574 if( rc ){
4575 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
4576 if (pStmt) sqlite3_finalize(pStmt);
4577 xCloser(sCtx.in);
4578 return 1;
4579 }
4580 needCommit = sqlite3_get_autocommit(p->db);
4581 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
4582 do{
4583 int startLine = sCtx.nLine;
4584 for(i=0; i<nCol; i++){
4585 char *z = xRead(&sCtx);
4586 /*
4587 ** Did we reach end-of-file before finding any columns?
4588 ** If so, stop instead of NULL filling the remaining columns.
4589 */
4590 if( z==0 && i==0 ) break;
4591 /*
4592 ** Did we reach end-of-file OR end-of-line before finding any
4593 ** columns in ASCII mode? If so, stop instead of NULL filling
4594 ** the remaining columns.
4595 */
4596 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
4597 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
4598 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
4599 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
4600 "filling the rest with NULL\n",
4601 sCtx.zFile, startLine, nCol, i+1);
4602 i += 2;
4603 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
4604 }
4605 }
4606 if( sCtx.cTerm==sCtx.cColSep ){
4607 do{
4608 xRead(&sCtx);
4609 i++;
4610 }while( sCtx.cTerm==sCtx.cColSep );
4611 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
4612 "extras ignored\n",
4613 sCtx.zFile, startLine, nCol, i);
4614 }
4615 if( i>=nCol ){
4616 sqlite3_step(pStmt);
4617 rc = sqlite3_reset(pStmt);
4618 if( rc!=SQLITE_OK ){
4619 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
4620 startLine, sqlite3_errmsg(p->db));
4621 }
4622 }
4623 }while( sCtx.cTerm!=EOF );
4624
4625 xCloser(sCtx.in);
4626 sqlite3_free(sCtx.z);
4627 sqlite3_finalize(pStmt);
4628 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
4629 }else
4630
4631#ifndef SQLITE_UNTESTABLE
4632 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
4633 char *zSql;
4634 char *zCollist = 0;
4635 sqlite3_stmt *pStmt;
4636 int tnum = 0;
4637 int i;
4638 if( nArg!=3 ){
4639 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
4640 rc = 1;
4641 goto meta_command_exit;
4642 }
4643 open_db(p, 0);
4644 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
4645 " WHERE name='%q' AND type='index'", azArg[1]);
4646 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4647 sqlite3_free(zSql);
4648 if( sqlite3_step(pStmt)==SQLITE_ROW ){
4649 tnum = sqlite3_column_int(pStmt, 0);
4650 }
4651 sqlite3_finalize(pStmt);
4652 if( tnum==0 ){
4653 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
4654 rc = 1;
4655 goto meta_command_exit;
4656 }
4657 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
4658 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4659 sqlite3_free(zSql);
4660 i = 0;
4661 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4662 char zLabel[20];
4663 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
4664 i++;
4665 if( zCol==0 ){
4666 if( sqlite3_column_int(pStmt,1)==-1 ){
4667 zCol = "_ROWID_";
4668 }else{
4669 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
4670 zCol = zLabel;
4671 }
4672 }
4673 if( zCollist==0 ){
4674 zCollist = sqlite3_mprintf("\"%w\"", zCol);
4675 }else{
4676 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
4677 }
4678 }
4679 sqlite3_finalize(pStmt);
4680 zSql = sqlite3_mprintf(
4681 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
4682 azArg[2], zCollist, zCollist);
4683 sqlite3_free(zCollist);
4684 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
4685 if( rc==SQLITE_OK ){
4686 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
4687 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
4688 if( rc ){
4689 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
4690 }else{
4691 utf8_printf(stdout, "%s;\n", zSql);
4692 raw_printf(stdout,
4693 "WARNING: writing to an imposter table will corrupt the index!\n"
4694 );
4695 }
4696 }else{
4697 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
4698 rc = 1;
4699 }
4700 sqlite3_free(zSql);
4701 }else
4702#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
4703
4704#ifdef SQLITE_ENABLE_IOTRACE
4705 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
4706 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
4707 if( iotrace && iotrace!=stdout ) fclose(iotrace);
4708 iotrace = 0;
4709 if( nArg<2 ){
4710 sqlite3IoTrace = 0;
4711 }else if( strcmp(azArg[1], "-")==0 ){
4712 sqlite3IoTrace = iotracePrintf;
4713 iotrace = stdout;
4714 }else{
4715 iotrace = fopen(azArg[1], "w");
4716 if( iotrace==0 ){
4717 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
4718 sqlite3IoTrace = 0;
4719 rc = 1;
4720 }else{
4721 sqlite3IoTrace = iotracePrintf;
4722 }
4723 }
4724 }else
4725#endif
4726
4727 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
4728 static const struct {
4729 const char *zLimitName; /* Name of a limit */
4730 int limitCode; /* Integer code for that limit */
4731 } aLimit[] = {
4732 { "length", SQLITE_LIMIT_LENGTH },
4733 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
4734 { "column", SQLITE_LIMIT_COLUMN },
4735 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
4736 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
4737 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
4738 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
4739 { "attached", SQLITE_LIMIT_ATTACHED },
4740 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
4741 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
4742 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
4743 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
4744 };
4745 int i, n2;
4746 open_db(p, 0);
4747 if( nArg==1 ){
4748 for(i=0; i<ArraySize(aLimit); i++){
4749 printf("%20s %d\n", aLimit[i].zLimitName,
4750 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
4751 }
4752 }else if( nArg>3 ){
4753 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
4754 rc = 1;
4755 goto meta_command_exit;
4756 }else{
4757 int iLimit = -1;
4758 n2 = strlen30(azArg[1]);
4759 for(i=0; i<ArraySize(aLimit); i++){
4760 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
4761 if( iLimit<0 ){
4762 iLimit = i;
4763 }else{
4764 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
4765 rc = 1;
4766 goto meta_command_exit;
4767 }
4768 }
4769 }
4770 if( iLimit<0 ){
4771 utf8_printf(stderr, "unknown limit: \"%s\"\n"
4772 "enter \".limits\" with no arguments for a list.\n",
4773 azArg[1]);
4774 rc = 1;
4775 goto meta_command_exit;
4776 }
4777 if( nArg==3 ){
4778 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
4779 (int)integerValue(azArg[2]));
4780 }
4781 printf("%20s %d\n", aLimit[iLimit].zLimitName,
4782 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
4783 }
4784 }else
4785
4786 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
4787 open_db(p, 0);
4788 lintDotCommand(p, azArg, nArg);
4789 }else
4790
4791#ifndef SQLITE_OMIT_LOAD_EXTENSION
4792 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
4793 const char *zFile, *zProc;
4794 char *zErrMsg = 0;
4795 if( nArg<2 ){
4796 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
4797 rc = 1;
4798 goto meta_command_exit;
4799 }
4800 zFile = azArg[1];
4801 zProc = nArg>=3 ? azArg[2] : 0;
4802 open_db(p, 0);
4803 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
4804 if( rc!=SQLITE_OK ){
4805 utf8_printf(stderr, "Error: %s\n", zErrMsg);
4806 sqlite3_free(zErrMsg);
4807 rc = 1;
4808 }
4809 }else
4810#endif
4811
4812 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
4813 if( nArg!=2 ){
4814 raw_printf(stderr, "Usage: .log FILENAME\n");
4815 rc = 1;
4816 }else{
4817 const char *zFile = azArg[1];
4818 output_file_close(p->pLog);
4819 p->pLog = output_file_open(zFile);
4820 }
4821 }else
4822
4823 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
4824 const char *zMode = nArg>=2 ? azArg[1] : "";
4825 int n2 = (int)strlen(zMode);
4826 int c2 = zMode[0];
4827 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
4828 p->mode = MODE_Line;
4829 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4830 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
4831 p->mode = MODE_Column;
4832 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4833 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
4834 p->mode = MODE_List;
4835 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
4836 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4837 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
4838 p->mode = MODE_Html;
4839 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
4840 p->mode = MODE_Tcl;
4841 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
4842 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4843 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
4844 p->mode = MODE_Csv;
4845 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
4846 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
4847 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
4848 p->mode = MODE_List;
4849 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
4850 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
4851 p->mode = MODE_Insert;
4852 set_table_name(p, nArg>=3 ? azArg[2] : "table");
4853 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
4854 p->mode = MODE_Quote;
4855 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
4856 p->mode = MODE_Ascii;
4857 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
4858 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
4859 }else if( nArg==1 ){
4860 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
4861 }else{
4862 raw_printf(stderr, "Error: mode should be one of: "
4863 "ascii column csv html insert line list quote tabs tcl\n");
4864 rc = 1;
4865 }
4866 p->cMode = p->mode;
4867 }else
4868
4869 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
4870 if( nArg==2 ){
4871 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
4872 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
4873 }else{
4874 raw_printf(stderr, "Usage: .nullvalue STRING\n");
4875 rc = 1;
4876 }
4877 }else
4878
4879 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
4880 char *zNewFilename; /* Name of the database file to open */
4881 int iName = 1; /* Index in azArg[] of the filename */
4882 int newFlag = 0; /* True to delete file before opening */
4883 /* Close the existing database */
4884 session_close_all(p);
4885 sqlite3_close(p->db);
4886 p->db = 0;
4887 p->zDbFilename = 0;
4888 sqlite3_free(p->zFreeOnClose);
4889 p->zFreeOnClose = 0;
4890 /* Check for command-line arguments */
4891 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
4892 const char *z = azArg[iName];
4893 if( optionMatch(z,"new") ){
4894 newFlag = 1;
4895 }else if( z[0]=='-' ){
4896 utf8_printf(stderr, "unknown option: %s\n", z);
4897 rc = 1;
4898 goto meta_command_exit;
4899 }
4900 }
4901 /* If a filename is specified, try to open it first */
4902 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
4903 if( zNewFilename ){
4904 if( newFlag ) shellDeleteFile(zNewFilename);
4905 p->zDbFilename = zNewFilename;
4906 open_db(p, 1);
4907 if( p->db==0 ){
4908 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
4909 sqlite3_free(zNewFilename);
4910 }else{
4911 p->zFreeOnClose = zNewFilename;
4912 }
4913 }
4914 if( p->db==0 ){
4915 /* As a fall-back open a TEMP database */
4916 p->zDbFilename = 0;
4917 open_db(p, 0);
4918 }
4919 }else
4920
4921 if( c=='o'
4922 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
4923 ){
4924 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
4925 if( nArg>2 ){
4926 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
4927 rc = 1;
4928 goto meta_command_exit;
4929 }
4930 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
4931 if( nArg<2 ){
4932 raw_printf(stderr, "Usage: .once FILE\n");
4933 rc = 1;
4934 goto meta_command_exit;
4935 }
4936 p->outCount = 2;
4937 }else{
4938 p->outCount = 0;
4939 }
4940 output_reset(p);
4941 if( zFile[0]=='|' ){
4942#ifdef SQLITE_OMIT_POPEN
4943 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4944 rc = 1;
4945 p->out = stdout;
4946#else
4947 p->out = popen(zFile + 1, "w");
4948 if( p->out==0 ){
4949 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
4950 p->out = stdout;
4951 rc = 1;
4952 }else{
4953 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
4954 }
4955#endif
4956 }else{
4957 p->out = output_file_open(zFile);
4958 if( p->out==0 ){
4959 if( strcmp(zFile,"off")!=0 ){
4960 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
4961 }
4962 p->out = stdout;
4963 rc = 1;
4964 } else {
4965 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
4966 }
4967 }
4968 }else
4969
4970 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
4971 int i;
4972 for(i=1; i<nArg; i++){
4973 if( i>1 ) raw_printf(p->out, " ");
4974 utf8_printf(p->out, "%s", azArg[i]);
4975 }
4976 raw_printf(p->out, "\n");
4977 }else
4978
4979 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
4980 if( nArg >= 2) {
4981 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
4982 }
4983 if( nArg >= 3) {
4984 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
4985 }
4986 }else
4987
4988 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
4989 rc = 2;
4990 }else
4991
4992 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
4993 FILE *alt;
4994 if( nArg!=2 ){
4995 raw_printf(stderr, "Usage: .read FILE\n");
4996 rc = 1;
4997 goto meta_command_exit;
4998 }
4999 alt = fopen(azArg[1], "rb");
5000 if( alt==0 ){
5001 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5002 rc = 1;
5003 }else{
5004 rc = process_input(p, alt);
5005 fclose(alt);
5006 }
5007 }else
5008
5009 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
5010 const char *zSrcFile;
5011 const char *zDb;
5012 sqlite3 *pSrc;
5013 sqlite3_backup *pBackup;
5014 int nTimeout = 0;
5015
5016 if( nArg==2 ){
5017 zSrcFile = azArg[1];
5018 zDb = "main";
5019 }else if( nArg==3 ){
5020 zSrcFile = azArg[2];
5021 zDb = azArg[1];
5022 }else{
5023 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
5024 rc = 1;
5025 goto meta_command_exit;
5026 }
5027 rc = sqlite3_open(zSrcFile, &pSrc);
5028 if( rc!=SQLITE_OK ){
5029 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
5030 sqlite3_close(pSrc);
5031 return 1;
5032 }
5033 open_db(p, 0);
5034 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5035 if( pBackup==0 ){
5036 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5037 sqlite3_close(pSrc);
5038 return 1;
5039 }
5040 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5041 || rc==SQLITE_BUSY ){
5042 if( rc==SQLITE_BUSY ){
5043 if( nTimeout++ >= 3 ) break;
5044 sqlite3_sleep(100);
5045 }
5046 }
5047 sqlite3_backup_finish(pBackup);
5048 if( rc==SQLITE_DONE ){
5049 rc = 0;
5050 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
5051 raw_printf(stderr, "Error: source database is busy\n");
5052 rc = 1;
5053 }else{
5054 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5055 rc = 1;
5056 }
5057 sqlite3_close(pSrc);
5058 }else
5059
5060
5061 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5062 if( nArg==2 ){
5063 p->scanstatsOn = booleanValue(azArg[1]);
5064#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5065 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
5066#endif
5067 }else{
5068 raw_printf(stderr, "Usage: .scanstats on|off\n");
5069 rc = 1;
5070 }
5071 }else
5072
5073 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
5074 ShellText sSelect;
5075 ShellState data;
5076 char *zErrMsg = 0;
5077 const char *zDiv = 0;
5078 int iSchema = 0;
5079
5080 open_db(p, 0);
5081 memcpy(&data, p, sizeof(data));
5082 data.showHeader = 0;
5083 data.cMode = data.mode = MODE_Semi;
5084 initText(&sSelect);
5085 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5086 data.cMode = data.mode = MODE_Pretty;
5087 nArg--;
5088 if( nArg==2 ) azArg[1] = azArg[2];
5089 }
5090 if( nArg==2 && azArg[1][0]!='-' ){
5091 int i;
5092 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
5093 if( strcmp(azArg[1],"sqlite_master")==0 ){
5094 char *new_argv[2], *new_colv[2];
5095 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5096 " type text,\n"
5097 " name text,\n"
5098 " tbl_name text,\n"
5099 " rootpage integer,\n"
5100 " sql text\n"
5101 ")";
5102 new_argv[1] = 0;
5103 new_colv[0] = "sql";
5104 new_colv[1] = 0;
5105 callback(&data, 1, new_argv, new_colv);
5106 rc = SQLITE_OK;
5107 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
5108 char *new_argv[2], *new_colv[2];
5109 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5110 " type text,\n"
5111 " name text,\n"
5112 " tbl_name text,\n"
5113 " rootpage integer,\n"
5114 " sql text\n"
5115 ")";
5116 new_argv[1] = 0;
5117 new_colv[0] = "sql";
5118 new_colv[1] = 0;
5119 callback(&data, 1, new_argv, new_colv);
5120 rc = SQLITE_OK;
5121 }else{
5122 zDiv = "(";
5123 }
5124 }else if( nArg==1 ){
5125 zDiv = "(";
5126 }else{
5127 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5128 rc = 1;
5129 goto meta_command_exit;
5130 }
5131 if( zDiv ){
5132 sqlite3_stmt *pStmt = 0;
5133 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
5134 -1, &pStmt, 0);
5135 if( rc ){
5136 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5137 sqlite3_finalize(pStmt);
5138 rc = 1;
5139 goto meta_command_exit;
5140 }
5141 appendText(&sSelect, "SELECT sql FROM", 0);
5142 iSchema = 0;
5143 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5144 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
5145 char zScNum[30];
5146 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
5147 appendText(&sSelect, zDiv, 0);
5148 zDiv = " UNION ALL ";
5149 if( strcmp(zDb, "main")!=0 ){
5150 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
5151 appendText(&sSelect, zDb, '"');
5152 appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
5153 appendText(&sSelect, zScNum, 0);
5154 appendText(&sSelect, " AS snum, ", 0);
5155 appendText(&sSelect, zDb, '\'');
5156 appendText(&sSelect, " AS sname FROM ", 0);
5157 appendText(&sSelect, zDb, '"');
5158 appendText(&sSelect, ".sqlite_master", 0);
5159 }else{
5160 appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5161 appendText(&sSelect, zScNum, 0);
5162 appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
5163 }
5164 }
5165 sqlite3_finalize(pStmt);
5166 appendText(&sSelect, ") WHERE ", 0);
5167 if( nArg>1 ){
5168 char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
5169 if( strchr(azArg[1], '.') ){
5170 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
5171 }else{
5172 appendText(&sSelect, "lower(tbl_name)", 0);
5173 }
5174 appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
5175 appendText(&sSelect, zQarg, 0);
5176 appendText(&sSelect, " AND ", 0);
5177 sqlite3_free(zQarg);
5178 }
5179 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
5180 " ORDER BY snum, rowid", 0);
5181 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
5182 freeText(&sSelect);
5183 }
5184 if( zErrMsg ){
5185 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5186 sqlite3_free(zErrMsg);
5187 rc = 1;
5188 }else if( rc != SQLITE_OK ){
5189 raw_printf(stderr,"Error: querying schema information\n");
5190 rc = 1;
5191 }else{
5192 rc = 0;
5193 }
5194 }else
5195
5196#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5197 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
5198 sqlite3SelectTrace = (int)integerValue(azArg[1]);
5199 }else
5200#endif
5201
5202#if defined(SQLITE_ENABLE_SESSION)
5203 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5204 OpenSession *pSession = &p->aSession[0];
5205 char **azCmd = &azArg[1];
5206 int iSes = 0;
5207 int nCmd = nArg - 1;
5208 int i;
5209 if( nArg<=1 ) goto session_syntax_error;
5210 open_db(p, 0);
5211 if( nArg>=3 ){
5212 for(iSes=0; iSes<p->nSession; iSes++){
5213 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5214 }
5215 if( iSes<p->nSession ){
5216 pSession = &p->aSession[iSes];
5217 azCmd++;
5218 nCmd--;
5219 }else{
5220 pSession = &p->aSession[0];
5221 iSes = 0;
5222 }
5223 }
5224
5225 /* .session attach TABLE
5226 ** Invoke the sqlite3session_attach() interface to attach a particular
5227 ** table so that it is never filtered.
5228 */
5229 if( strcmp(azCmd[0],"attach")==0 ){
5230 if( nCmd!=2 ) goto session_syntax_error;
5231 if( pSession->p==0 ){
5232 session_not_open:
5233 raw_printf(stderr, "ERROR: No sessions are open\n");
5234 }else{
5235 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5236 if( rc ){
5237 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
5238 rc = 0;
5239 }
5240 }
5241 }else
5242
5243 /* .session changeset FILE
5244 ** .session patchset FILE
5245 ** Write a changeset or patchset into a file. The file is overwritten.
5246 */
5247 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5248 FILE *out = 0;
5249 if( nCmd!=2 ) goto session_syntax_error;
5250 if( pSession->p==0 ) goto session_not_open;
5251 out = fopen(azCmd[1], "wb");
5252 if( out==0 ){
5253 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
5254 }else{
5255 int szChng;
5256 void *pChng;
5257 if( azCmd[0][0]=='c' ){
5258 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
5259 }else{
5260 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5261 }
5262 if( rc ){
5263 printf("Error: error code %d\n", rc);
5264 rc = 0;
5265 }
5266 if( pChng
5267 && fwrite(pChng, szChng, 1, out)!=1 ){
5268 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
5269 szChng);
5270 }
5271 sqlite3_free(pChng);
5272 fclose(out);
5273 }
5274 }else
5275
5276 /* .session close
5277 ** Close the identified session
5278 */
5279 if( strcmp(azCmd[0], "close")==0 ){
5280 if( nCmd!=1 ) goto session_syntax_error;
5281 if( p->nSession ){
5282 session_close(pSession);
5283 p->aSession[iSes] = p->aSession[--p->nSession];
5284 }
5285 }else
5286
5287 /* .session enable ?BOOLEAN?
5288 ** Query or set the enable flag
5289 */
5290 if( strcmp(azCmd[0], "enable")==0 ){
5291 int ii;
5292 if( nCmd>2 ) goto session_syntax_error;
5293 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5294 if( p->nSession ){
5295 ii = sqlite3session_enable(pSession->p, ii);
5296 utf8_printf(p->out, "session %s enable flag = %d\n",
5297 pSession->zName, ii);
5298 }
5299 }else
5300
5301 /* .session filter GLOB ....
5302 ** Set a list of GLOB patterns of table names to be excluded.
5303 */
5304 if( strcmp(azCmd[0], "filter")==0 ){
5305 int ii, nByte;
5306 if( nCmd<2 ) goto session_syntax_error;
5307 if( p->nSession ){
5308 for(ii=0; ii<pSession->nFilter; ii++){
5309 sqlite3_free(pSession->azFilter[ii]);
5310 }
5311 sqlite3_free(pSession->azFilter);
5312 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5313 pSession->azFilter = sqlite3_malloc( nByte );
5314 if( pSession->azFilter==0 ){
5315 raw_printf(stderr, "Error: out or memory\n");
5316 exit(1);
5317 }
5318 for(ii=1; ii<nCmd; ii++){
5319 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
5320 }
5321 pSession->nFilter = ii-1;
5322 }
5323 }else
5324
5325 /* .session indirect ?BOOLEAN?
5326 ** Query or set the indirect flag
5327 */
5328 if( strcmp(azCmd[0], "indirect")==0 ){
5329 int ii;
5330 if( nCmd>2 ) goto session_syntax_error;
5331 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5332 if( p->nSession ){
5333 ii = sqlite3session_indirect(pSession->p, ii);
5334 utf8_printf(p->out, "session %s indirect flag = %d\n",
5335 pSession->zName, ii);
5336 }
5337 }else
5338
5339 /* .session isempty
5340 ** Determine if the session is empty
5341 */
5342 if( strcmp(azCmd[0], "isempty")==0 ){
5343 int ii;
5344 if( nCmd!=1 ) goto session_syntax_error;
5345 if( p->nSession ){
5346 ii = sqlite3session_isempty(pSession->p);
5347 utf8_printf(p->out, "session %s isempty flag = %d\n",
5348 pSession->zName, ii);
5349 }
5350 }else
5351
5352 /* .session list
5353 ** List all currently open sessions
5354 */
5355 if( strcmp(azCmd[0],"list")==0 ){
5356 for(i=0; i<p->nSession; i++){
5357 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
5358 }
5359 }else
5360
5361 /* .session open DB NAME
5362 ** Open a new session called NAME on the attached database DB.
5363 ** DB is normally "main".
5364 */
5365 if( strcmp(azCmd[0],"open")==0 ){
5366 char *zName;
5367 if( nCmd!=3 ) goto session_syntax_error;
5368 zName = azCmd[2];
5369 if( zName[0]==0 ) goto session_syntax_error;
5370 for(i=0; i<p->nSession; i++){
5371 if( strcmp(p->aSession[i].zName,zName)==0 ){
5372 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
5373 goto meta_command_exit;
5374 }
5375 }
5376 if( p->nSession>=ArraySize(p->aSession) ){
5377 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
5378 goto meta_command_exit;
5379 }
5380 pSession = &p->aSession[p->nSession];
5381 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5382 if( rc ){
5383 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
5384 rc = 0;
5385 goto meta_command_exit;
5386 }
5387 pSession->nFilter = 0;
5388 sqlite3session_table_filter(pSession->p, session_filter, pSession);
5389 p->nSession++;
5390 pSession->zName = sqlite3_mprintf("%s", zName);
5391 }else
5392 /* If no command name matches, show a syntax error */
5393 session_syntax_error:
5394 session_help(p);
5395 }else
5396#endif
5397
5398#ifdef SQLITE_DEBUG
5399 /* Undocumented commands for internal testing. Subject to change
5400 ** without notice. */
5401 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5402 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5403 int i, v;
5404 for(i=1; i<nArg; i++){
5405 v = booleanValue(azArg[i]);
5406 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
5407 }
5408 }
5409 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5410 int i; sqlite3_int64 v;
5411 for(i=1; i<nArg; i++){
5412 char zBuf[200];
5413 v = integerValue(azArg[i]);
5414 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
5415 utf8_printf(p->out, "%s", zBuf);
5416 }
5417 }
5418 }else
5419#endif
5420
5421 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5422 int bIsInit = 0; /* True to initialize the SELFTEST table */
5423 int bVerbose = 0; /* Verbose output */
5424 int bSelftestExists; /* True if SELFTEST already exists */
5425 int i, k; /* Loop counters */
5426 int nTest = 0; /* Number of tests runs */
5427 int nErr = 0; /* Number of errors seen */
5428 ShellText str; /* Answer for a query */
5429 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
5430
5431 open_db(p,0);
5432 for(i=1; i<nArg; i++){
5433 const char *z = azArg[i];
5434 if( z[0]=='-' && z[1]=='-' ) z++;
5435 if( strcmp(z,"-init")==0 ){
5436 bIsInit = 1;
5437 }else
5438 if( strcmp(z,"-v")==0 ){
5439 bVerbose++;
5440 }else
5441 {
5442 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5443 azArg[i], azArg[0]);
5444 raw_printf(stderr, "Should be one of: --init -v\n");
5445 rc = 1;
5446 goto meta_command_exit;
5447 }
5448 }
5449 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5450 != SQLITE_OK ){
5451 bSelftestExists = 0;
5452 }else{
5453 bSelftestExists = 1;
5454 }
5455 if( bIsInit ){
5456 createSelftestTable(p);
5457 bSelftestExists = 1;
5458 }
5459 initText(&str);
5460 appendText(&str, "x", 0);
5461 for(k=bSelftestExists; k>=0; k--){
5462 if( k==1 ){
5463 rc = sqlite3_prepare_v2(p->db,
5464 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5465 -1, &pStmt, 0);
5466 }else{
5467 rc = sqlite3_prepare_v2(p->db,
5468 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
5469 " (1,'run','PRAGMA integrity_check','ok')",
5470 -1, &pStmt, 0);
5471 }
5472 if( rc ){
5473 raw_printf(stderr, "Error querying the selftest table\n");
5474 rc = 1;
5475 sqlite3_finalize(pStmt);
5476 goto meta_command_exit;
5477 }
5478 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
5479 int tno = sqlite3_column_int(pStmt, 0);
5480 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
5481 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
5482 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
5483
5484 k = 0;
5485 if( bVerbose>0 ){
5486 char *zQuote = sqlite3_mprintf("%q", zSql);
5487 printf("%d: %s %s\n", tno, zOp, zSql);
5488 sqlite3_free(zQuote);
5489 }
5490 if( strcmp(zOp,"memo")==0 ){
5491 utf8_printf(p->out, "%s\n", zSql);
5492 }else
5493 if( strcmp(zOp,"run")==0 ){
5494 char *zErrMsg = 0;
5495 str.n = 0;
5496 str.z[0] = 0;
5497 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5498 nTest++;
5499 if( bVerbose ){
5500 utf8_printf(p->out, "Result: %s\n", str.z);
5501 }
5502 if( rc || zErrMsg ){
5503 nErr++;
5504 rc = 1;
5505 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5506 sqlite3_free(zErrMsg);
5507 }else if( strcmp(zAns,str.z)!=0 ){
5508 nErr++;
5509 rc = 1;
5510 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5511 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
5512 }
5513 }else
5514 {
5515 utf8_printf(stderr,
5516 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5517 rc = 1;
5518 break;
5519 }
5520 } /* End loop over rows of content from SELFTEST */
5521 sqlite3_finalize(pStmt);
5522 } /* End loop over k */
5523 freeText(&str);
5524 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5525 }else
5526
5527 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
5528 if( nArg<2 || nArg>3 ){
5529 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
5530 rc = 1;
5531 }
5532 if( nArg>=2 ){
5533 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
5534 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
5535 }
5536 if( nArg>=3 ){
5537 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5538 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
5539 }
5540 }else
5541
5542 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5543 const char *zLike = 0; /* Which table to checksum. 0 means everything */
5544 int i; /* Loop counter */
5545 int bSchema = 0; /* Also hash the schema */
5546 int bSeparate = 0; /* Hash each table separately */
5547 int iSize = 224; /* Hash algorithm to use */
5548 int bDebug = 0; /* Only show the query that would have run */
5549 sqlite3_stmt *pStmt; /* For querying tables names */
5550 char *zSql; /* SQL to be run */
5551 char *zSep; /* Separator */
5552 ShellText sSql; /* Complete SQL for the query to run the hash */
5553 ShellText sQuery; /* Set of queries used to read all content */
5554 open_db(p, 0);
5555 for(i=1; i<nArg; i++){
5556 const char *z = azArg[i];
5557 if( z[0]=='-' ){
5558 z++;
5559 if( z[0]=='-' ) z++;
5560 if( strcmp(z,"schema")==0 ){
5561 bSchema = 1;
5562 }else
5563 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
5564 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
5565 ){
5566 iSize = atoi(&z[5]);
5567 }else
5568 if( strcmp(z,"debug")==0 ){
5569 bDebug = 1;
5570 }else
5571 {
5572 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5573 azArg[i], azArg[0]);
5574 raw_printf(stderr, "Should be one of: --schema"
5575 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5576 rc = 1;
5577 goto meta_command_exit;
5578 }
5579 }else if( zLike ){
5580 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5581 rc = 1;
5582 goto meta_command_exit;
5583 }else{
5584 zLike = z;
5585 bSeparate = 1;
5586 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
5587 }
5588 }
5589 if( bSchema ){
5590 zSql = "SELECT lower(name) FROM sqlite_master"
5591 " WHERE type='table' AND coalesce(rootpage,0)>1"
5592 " UNION ALL SELECT 'sqlite_master'"
5593 " ORDER BY 1 collate nocase";
5594 }else{
5595 zSql = "SELECT lower(name) FROM sqlite_master"
5596 " WHERE type='table' AND coalesce(rootpage,0)>1"
5597 " AND name NOT LIKE 'sqlite_%'"
5598 " ORDER BY 1 collate nocase";
5599 }
5600 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5601 initText(&sQuery);
5602 initText(&sSql);
5603 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
5604 zSep = "VALUES(";
5605 while( SQLITE_ROW==sqlite3_step(pStmt) ){
5606 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
5607 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
5608 if( strncmp(zTab, "sqlite_",7)!=0 ){
5609 appendText(&sQuery,"SELECT * FROM ", 0);
5610 appendText(&sQuery,zTab,'"');
5611 appendText(&sQuery," NOT INDEXED;", 0);
5612 }else if( strcmp(zTab, "sqlite_master")==0 ){
5613 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
5614 " ORDER BY name;", 0);
5615 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
5616 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
5617 " ORDER BY name;", 0);
5618 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
5619 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
5620 " ORDER BY tbl,idx;", 0);
5621 }else if( strcmp(zTab, "sqlite_stat3")==0
5622 || strcmp(zTab, "sqlite_stat4")==0 ){
5623 appendText(&sQuery, "SELECT * FROM ", 0);
5624 appendText(&sQuery, zTab, 0);
5625 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
5626 }
5627 appendText(&sSql, zSep, 0);
5628 appendText(&sSql, sQuery.z, '\'');
5629 sQuery.n = 0;
5630 appendText(&sSql, ",", 0);
5631 appendText(&sSql, zTab, '\'');
5632 zSep = "),(";
5633 }
5634 sqlite3_finalize(pStmt);
5635 if( bSeparate ){
5636 zSql = sqlite3_mprintf(
5637 "%s))"
5638 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
5639 " FROM [sha3sum$query]",
5640 sSql.z, iSize);
5641 }else{
5642 zSql = sqlite3_mprintf(
5643 "%s))"
5644 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
5645 " FROM [sha3sum$query]",
5646 sSql.z, iSize);
5647 }
5648 freeText(&sQuery);
5649 freeText(&sSql);
5650 if( bDebug ){
5651 utf8_printf(p->out, "%s\n", zSql);
5652 }else{
5653 shell_exec(p->db, zSql, shell_callback, p, 0);
5654 }
5655 sqlite3_free(zSql);
5656 }else
5657
5658 if( c=='s'
5659 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
5660 ){
5661 char *zCmd;
5662 int i, x;
5663 if( nArg<2 ){
5664 raw_printf(stderr, "Usage: .system COMMAND\n");
5665 rc = 1;
5666 goto meta_command_exit;
5667 }
5668 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
5669 for(i=2; i<nArg; i++){
5670 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
5671 zCmd, azArg[i]);
5672 }
5673 x = system(zCmd);
5674 sqlite3_free(zCmd);
5675 if( x ) raw_printf(stderr, "System command returns %d\n", x);
5676 }else
5677
5678 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
5679 static const char *azBool[] = { "off", "on", "full", "unk" };
5680 int i;
5681 if( nArg!=1 ){
5682 raw_printf(stderr, "Usage: .show\n");
5683 rc = 1;
5684 goto meta_command_exit;
5685 }
5686 utf8_printf(p->out, "%12.12s: %s\n","echo",
5687 azBool[ShellHasFlag(p, SHFLG_Echo)]);
5688 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
5689 utf8_printf(p->out, "%12.12s: %s\n","explain",
5690 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
5691 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
5692 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
5693 utf8_printf(p->out, "%12.12s: ", "nullvalue");
5694 output_c_string(p->out, p->nullValue);
5695 raw_printf(p->out, "\n");
5696 utf8_printf(p->out,"%12.12s: %s\n","output",
5697 strlen30(p->outfile) ? p->outfile : "stdout");
5698 utf8_printf(p->out,"%12.12s: ", "colseparator");
5699 output_c_string(p->out, p->colSeparator);
5700 raw_printf(p->out, "\n");
5701 utf8_printf(p->out,"%12.12s: ", "rowseparator");
5702 output_c_string(p->out, p->rowSeparator);
5703 raw_printf(p->out, "\n");
5704 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
5705 utf8_printf(p->out, "%12.12s: ", "width");
5706 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
5707 raw_printf(p->out, "%d ", p->colWidth[i]);
5708 }
5709 raw_printf(p->out, "\n");
5710 utf8_printf(p->out, "%12.12s: %s\n", "filename",
5711 p->zDbFilename ? p->zDbFilename : "");
5712 }else
5713
5714 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
5715 if( nArg==2 ){
5716 p->statsOn = booleanValue(azArg[1]);
5717 }else if( nArg==1 ){
5718 display_stats(p->db, p, 0);
5719 }else{
5720 raw_printf(stderr, "Usage: .stats ?on|off?\n");
5721 rc = 1;
5722 }
5723 }else
5724
5725 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
5726 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
5727 || strncmp(azArg[0], "indexes", n)==0) )
5728 ){
5729 sqlite3_stmt *pStmt;
5730 char **azResult;
5731 int nRow, nAlloc;
5732 int ii;
5733 ShellText s;
5734 initText(&s);
5735 open_db(p, 0);
5736 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
5737 if( rc ) return shellDatabaseError(p->db);
5738
5739 if( nArg>2 && c=='i' ){
5740 /* It is an historical accident that the .indexes command shows an error
5741 ** when called with the wrong number of arguments whereas the .tables
5742 ** command does not. */
5743 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
5744 rc = 1;
5745 goto meta_command_exit;
5746 }
5747 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
5748 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
5749 if( zDbName==0 ) continue;
5750 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
5751 if( sqlite3_stricmp(zDbName, "main")==0 ){
5752 appendText(&s, "SELECT name FROM ", 0);
5753 }else{
5754 appendText(&s, "SELECT ", 0);
5755 appendText(&s, zDbName, '\'');
5756 appendText(&s, "||'.'||name FROM ", 0);
5757 }
5758 appendText(&s, zDbName, '"');
5759 appendText(&s, ".sqlite_master ", 0);
5760 if( c=='t' ){
5761 appendText(&s," WHERE type IN ('table','view')"
5762 " AND name NOT LIKE 'sqlite_%'"
5763 " AND name LIKE ?1", 0);
5764 }else{
5765 appendText(&s," WHERE type='index'"
5766 " AND tbl_name LIKE ?1", 0);
5767 }
5768 }
5769 rc = sqlite3_finalize(pStmt);
5770 appendText(&s, " ORDER BY 1", 0);
5771 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
5772 freeText(&s);
5773 if( rc ) return shellDatabaseError(p->db);
5774
5775 /* Run the SQL statement prepared by the above block. Store the results
5776 ** as an array of nul-terminated strings in azResult[]. */
5777 nRow = nAlloc = 0;
5778 azResult = 0;
5779 if( nArg>1 ){
5780 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
5781 }else{
5782 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
5783 }
5784 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5785 if( nRow>=nAlloc ){
5786 char **azNew;
5787 int n2 = nAlloc*2 + 10;
5788 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
5789 if( azNew==0 ){
5790 rc = shellNomemError();
5791 break;
5792 }
5793 nAlloc = n2;
5794 azResult = azNew;
5795 }
5796 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
5797 if( 0==azResult[nRow] ){
5798 rc = shellNomemError();
5799 break;
5800 }
5801 nRow++;
5802 }
5803 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
5804 rc = shellDatabaseError(p->db);
5805 }
5806
5807 /* Pretty-print the contents of array azResult[] to the output */
5808 if( rc==0 && nRow>0 ){
5809 int len, maxlen = 0;
5810 int i, j;
5811 int nPrintCol, nPrintRow;
5812 for(i=0; i<nRow; i++){
5813 len = strlen30(azResult[i]);
5814 if( len>maxlen ) maxlen = len;
5815 }
5816 nPrintCol = 80/(maxlen+2);
5817 if( nPrintCol<1 ) nPrintCol = 1;
5818 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
5819 for(i=0; i<nPrintRow; i++){
5820 for(j=i; j<nRow; j+=nPrintRow){
5821 char *zSp = j<nPrintRow ? "" : " ";
5822 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
5823 azResult[j] ? azResult[j]:"");
5824 }
5825 raw_printf(p->out, "\n");
5826 }
5827 }
5828
5829 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
5830 sqlite3_free(azResult);
5831 }else
5832
5833 /* Begin redirecting output to the file "testcase-out.txt" */
5834 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
5835 output_reset(p);
5836 p->out = output_file_open("testcase-out.txt");
5837 if( p->out==0 ){
5838 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
5839 }
5840 if( nArg>=2 ){
5841 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
5842 }else{
5843 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
5844 }
5845 }else
5846
5847#ifndef SQLITE_UNTESTABLE
5848 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
5849 static const struct {
5850 const char *zCtrlName; /* Name of a test-control option */
5851 int ctrlCode; /* Integer code for that option */
5852 } aCtrl[] = {
5853 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
5854 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
5855 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
5856 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
5857 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
5858 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
5859 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
5860 { "assert", SQLITE_TESTCTRL_ASSERT },
5861 { "always", SQLITE_TESTCTRL_ALWAYS },
5862 { "reserve", SQLITE_TESTCTRL_RESERVE },
5863 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
5864 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
5865 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
5866 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
5867 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
5868 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
5869 };
5870 int testctrl = -1;
5871 int rc2 = 0;
5872 int i, n2;
5873 open_db(p, 0);
5874
5875 /* convert testctrl text option to value. allow any unique prefix
5876 ** of the option name, or a numerical value. */
5877 n2 = strlen30(azArg[1]);
5878 for(i=0; i<ArraySize(aCtrl); i++){
5879 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
5880 if( testctrl<0 ){
5881 testctrl = aCtrl[i].ctrlCode;
5882 }else{
5883 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
5884 testctrl = -1;
5885 break;
5886 }
5887 }
5888 }
5889 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
5890 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
5891 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
5892 }else{
5893 switch(testctrl){
5894
5895 /* sqlite3_test_control(int, db, int) */
5896 case SQLITE_TESTCTRL_OPTIMIZATIONS:
5897 case SQLITE_TESTCTRL_RESERVE:
5898 if( nArg==3 ){
5899 int opt = (int)strtol(azArg[2], 0, 0);
5900 rc2 = sqlite3_test_control(testctrl, p->db, opt);
5901 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5902 } else {
5903 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
5904 azArg[1]);
5905 }
5906 break;
5907
5908 /* sqlite3_test_control(int) */
5909 case SQLITE_TESTCTRL_PRNG_SAVE:
5910 case SQLITE_TESTCTRL_PRNG_RESTORE:
5911 case SQLITE_TESTCTRL_PRNG_RESET:
5912 case SQLITE_TESTCTRL_BYTEORDER:
5913 if( nArg==2 ){
5914 rc2 = sqlite3_test_control(testctrl);
5915 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5916 } else {
5917 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
5918 azArg[1]);
5919 }
5920 break;
5921
5922 /* sqlite3_test_control(int, uint) */
5923 case SQLITE_TESTCTRL_PENDING_BYTE:
5924 if( nArg==3 ){
5925 unsigned int opt = (unsigned int)integerValue(azArg[2]);
5926 rc2 = sqlite3_test_control(testctrl, opt);
5927 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5928 } else {
5929 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
5930 " int option\n", azArg[1]);
5931 }
5932 break;
5933
5934 /* sqlite3_test_control(int, int) */
5935 case SQLITE_TESTCTRL_ASSERT:
5936 case SQLITE_TESTCTRL_ALWAYS:
5937 case SQLITE_TESTCTRL_NEVER_CORRUPT:
5938 if( nArg==3 ){
5939 int opt = booleanValue(azArg[2]);
5940 rc2 = sqlite3_test_control(testctrl, opt);
5941 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5942 } else {
5943 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
5944 azArg[1]);
5945 }
5946 break;
5947
5948 /* sqlite3_test_control(int, char *) */
5949#ifdef SQLITE_N_KEYWORD
5950 case SQLITE_TESTCTRL_ISKEYWORD:
5951 if( nArg==3 ){
5952 const char *opt = azArg[2];
5953 rc2 = sqlite3_test_control(testctrl, opt);
5954 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5955 } else {
5956 utf8_printf(stderr,
5957 "Error: testctrl %s takes a single char * option\n",
5958 azArg[1]);
5959 }
5960 break;
5961#endif
5962
5963 case SQLITE_TESTCTRL_IMPOSTER:
5964 if( nArg==5 ){
5965 rc2 = sqlite3_test_control(testctrl, p->db,
5966 azArg[2],
5967 integerValue(azArg[3]),
5968 integerValue(azArg[4]));
5969 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5970 }else{
5971 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
5972 }
5973 break;
5974
5975 case SQLITE_TESTCTRL_BITVEC_TEST:
5976 case SQLITE_TESTCTRL_FAULT_INSTALL:
5977 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
5978 case SQLITE_TESTCTRL_SCRATCHMALLOC:
5979 default:
5980 utf8_printf(stderr,
5981 "Error: CLI support for testctrl %s not implemented\n",
5982 azArg[1]);
5983 break;
5984 }
5985 }
5986 }else
5987#endif /* !defined(SQLITE_UNTESTABLE) */
5988
5989 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
5990 open_db(p, 0);
5991 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
5992 }else
5993
5994 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
5995 if( nArg==2 ){
5996 enableTimer = booleanValue(azArg[1]);
5997 if( enableTimer && !HAS_TIMER ){
5998 raw_printf(stderr, "Error: timer not available on this system.\n");
5999 enableTimer = 0;
6000 }
6001 }else{
6002 raw_printf(stderr, "Usage: .timer on|off\n");
6003 rc = 1;
6004 }
6005 }else
6006
6007 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
6008 open_db(p, 0);
6009 if( nArg!=2 ){
6010 raw_printf(stderr, "Usage: .trace FILE|off\n");
6011 rc = 1;
6012 goto meta_command_exit;
6013 }
6014 output_file_close(p->traceOut);
6015 p->traceOut = output_file_open(azArg[1]);
6016#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6017 if( p->traceOut==0 ){
6018 sqlite3_trace_v2(p->db, 0, 0, 0);
6019 }else{
6020 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
6021 }
6022#endif
6023 }else
6024
6025#if SQLITE_USER_AUTHENTICATION
6026 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6027 if( nArg<2 ){
6028 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
6029 rc = 1;
6030 goto meta_command_exit;
6031 }
6032 open_db(p, 0);
6033 if( strcmp(azArg[1],"login")==0 ){
6034 if( nArg!=4 ){
6035 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
6036 rc = 1;
6037 goto meta_command_exit;
6038 }
6039 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6040 (int)strlen(azArg[3]));
6041 if( rc ){
6042 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
6043 rc = 1;
6044 }
6045 }else if( strcmp(azArg[1],"add")==0 ){
6046 if( nArg!=5 ){
6047 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
6048 rc = 1;
6049 goto meta_command_exit;
6050 }
6051 rc = sqlite3_user_add(p->db, azArg[2],
6052 azArg[3], (int)strlen(azArg[3]),
6053 booleanValue(azArg[4]));
6054 if( rc ){
6055 raw_printf(stderr, "User-Add failed: %d\n", rc);
6056 rc = 1;
6057 }
6058 }else if( strcmp(azArg[1],"edit")==0 ){
6059 if( nArg!=5 ){
6060 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
6061 rc = 1;
6062 goto meta_command_exit;
6063 }
6064 rc = sqlite3_user_change(p->db, azArg[2],
6065 azArg[3], (int)strlen(azArg[3]),
6066 booleanValue(azArg[4]));
6067 if( rc ){
6068 raw_printf(stderr, "User-Edit failed: %d\n", rc);
6069 rc = 1;
6070 }
6071 }else if( strcmp(azArg[1],"delete")==0 ){
6072 if( nArg!=3 ){
6073 raw_printf(stderr, "Usage: .user delete USER\n");
6074 rc = 1;
6075 goto meta_command_exit;
6076 }
6077 rc = sqlite3_user_delete(p->db, azArg[2]);
6078 if( rc ){
6079 raw_printf(stderr, "User-Delete failed: %d\n", rc);
6080 rc = 1;
6081 }
6082 }else{
6083 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
6084 rc = 1;
6085 goto meta_command_exit;
6086 }
6087 }else
6088#endif /* SQLITE_USER_AUTHENTICATION */
6089
6090 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
6091 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
6092 sqlite3_libversion(), sqlite3_sourceid());
6093 }else
6094
6095 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6096 const char *zDbName = nArg==2 ? azArg[1] : "main";
6097 sqlite3_vfs *pVfs = 0;
6098 if( p->db ){
6099 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6100 if( pVfs ){
6101 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6102 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6103 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6104 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6105 }
6106 }
6107 }else
6108
6109 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6110 sqlite3_vfs *pVfs;
6111 sqlite3_vfs *pCurrent = 0;
6112 if( p->db ){
6113 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6114 }
6115 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6116 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6117 pVfs==pCurrent ? " <--- CURRENT" : "");
6118 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6119 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6120 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6121 if( pVfs->pNext ){
6122 raw_printf(p->out, "-----------------------------------\n");
6123 }
6124 }
6125 }else
6126
6127 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6128 const char *zDbName = nArg==2 ? azArg[1] : "main";
6129 char *zVfsName = 0;
6130 if( p->db ){
6131 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6132 if( zVfsName ){
6133 utf8_printf(p->out, "%s\n", zVfsName);
6134 sqlite3_free(zVfsName);
6135 }
6136 }
6137 }else
6138
6139#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6140 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
6141 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
6142 }else
6143#endif
6144
6145 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
6146 int j;
6147 assert( nArg<=ArraySize(azArg) );
6148 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
6149 p->colWidth[j-1] = (int)integerValue(azArg[j]);
6150 }
6151 }else
6152
6153 {
6154 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
6155 " \"%s\". Enter \".help\" for help\n", azArg[0]);
6156 rc = 1;
6157 }
6158
6159meta_command_exit:
6160 if( p->outCount ){
6161 p->outCount--;
6162 if( p->outCount==0 ) output_reset(p);
6163 }
6164 return rc;
6165}
6166
6167/*
6168** Return TRUE if a semicolon occurs anywhere in the first N characters
6169** of string z[].
6170*/
6171static int line_contains_semicolon(const char *z, int N){
6172 int i;
6173 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6174 return 0;
6175}
6176
6177/*
6178** Test to see if a line consists entirely of whitespace.
6179*/
6180static int _all_whitespace(const char *z){
6181 for(; *z; z++){
6182 if( IsSpace(z[0]) ) continue;
6183 if( *z=='/' && z[1]=='*' ){
6184 z += 2;
6185 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6186 if( *z==0 ) return 0;
6187 z++;
6188 continue;
6189 }
6190 if( *z=='-' && z[1]=='-' ){
6191 z += 2;
6192 while( *z && *z!='\n' ){ z++; }
6193 if( *z==0 ) return 1;
6194 continue;
6195 }
6196 return 0;
6197 }
6198 return 1;
6199}
6200
6201/*
6202** Return TRUE if the line typed in is an SQL command terminator other
6203** than a semi-colon. The SQL Server style "go" command is understood
6204** as is the Oracle "/".
6205*/
6206static int line_is_command_terminator(const char *zLine){
6207 while( IsSpace(zLine[0]) ){ zLine++; };
6208 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6209 return 1; /* Oracle */
6210 }
6211 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
6212 && _all_whitespace(&zLine[2]) ){
6213 return 1; /* SQL Server */
6214 }
6215 return 0;
6216}
6217
6218/*
6219** Return true if zSql is a complete SQL statement. Return false if it
6220** ends in the middle of a string literal or C-style comment.
6221*/
6222static int line_is_complete(char *zSql, int nSql){
6223 int rc;
6224 if( zSql==0 ) return 1;
6225 zSql[nSql] = ';';
6226 zSql[nSql+1] = 0;
6227 rc = sqlite3_complete(zSql);
6228 zSql[nSql] = 0;
6229 return rc;
6230}
6231
6232/*
6233** Run a single line of SQL
6234*/
6235static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6236 int rc;
6237 char *zErrMsg = 0;
6238
6239 open_db(p, 0);
6240 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
6241 BEGIN_TIMER;
6242 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6243 END_TIMER;
6244 if( rc || zErrMsg ){
6245 char zPrefix[100];
6246 if( in!=0 || !stdin_is_interactive ){
6247 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6248 "Error: near line %d:", startline);
6249 }else{
6250 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6251 }
6252 if( zErrMsg!=0 ){
6253 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6254 sqlite3_free(zErrMsg);
6255 zErrMsg = 0;
6256 }else{
6257 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6258 }
6259 return 1;
6260 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
6261 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6262 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6263 }
6264 return 0;
6265}
6266
6267
6268/*
6269** Read input from *in and process it. If *in==0 then input
6270** is interactive - the user is typing it it. Otherwise, input
6271** is coming from a file or device. A prompt is issued and history
6272** is saved only if input is interactive. An interrupt signal will
6273** cause this routine to exit immediately, unless input is interactive.
6274**
6275** Return the number of errors.
6276*/
6277static int process_input(ShellState *p, FILE *in){
6278 char *zLine = 0; /* A single input line */
6279 char *zSql = 0; /* Accumulated SQL text */
6280 int nLine; /* Length of current line */
6281 int nSql = 0; /* Bytes of zSql[] used */
6282 int nAlloc = 0; /* Allocated zSql[] space */
6283 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
6284 int rc; /* Error code */
6285 int errCnt = 0; /* Number of errors seen */
6286 int lineno = 0; /* Current line number */
6287 int startline = 0; /* Line number for start of current input */
6288
6289 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6290 fflush(p->out);
6291 zLine = one_input_line(in, zLine, nSql>0);
6292 if( zLine==0 ){
6293 /* End of input */
6294 if( in==0 && stdin_is_interactive ) printf("\n");
6295 break;
6296 }
6297 if( seenInterrupt ){
6298 if( in!=0 ) break;
6299 seenInterrupt = 0;
6300 }
6301 lineno++;
6302 if( nSql==0 && _all_whitespace(zLine) ){
6303 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6304 continue;
6305 }
6306 if( zLine && zLine[0]=='.' && nSql==0 ){
6307 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6308 rc = do_meta_command(zLine, p);
6309 if( rc==2 ){ /* exit requested */
6310 break;
6311 }else if( rc ){
6312 errCnt++;
6313 }
6314 continue;
6315 }
6316 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
6317 memcpy(zLine,";",2);
6318 }
6319 nLine = strlen30(zLine);
6320 if( nSql+nLine+2>=nAlloc ){
6321 nAlloc = nSql+nLine+100;
6322 zSql = realloc(zSql, nAlloc);
6323 if( zSql==0 ){
6324 raw_printf(stderr, "Error: out of memory\n");
6325 exit(1);
6326 }
6327 }
6328 nSqlPrior = nSql;
6329 if( nSql==0 ){
6330 int i;
6331 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
6332 assert( nAlloc>0 && zSql!=0 );
6333 memcpy(zSql, zLine+i, nLine+1-i);
6334 startline = lineno;
6335 nSql = nLine-i;
6336 }else{
6337 zSql[nSql++] = '\n';
6338 memcpy(zSql+nSql, zLine, nLine+1);
6339 nSql += nLine;
6340 }
6341 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
6342 && sqlite3_complete(zSql) ){
6343 errCnt += runOneSqlLine(p, zSql, in, startline);
6344 nSql = 0;
6345 if( p->outCount ){
6346 output_reset(p);
6347 p->outCount = 0;
6348 }
6349 }else if( nSql && _all_whitespace(zSql) ){
6350 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
6351 nSql = 0;
6352 }
6353 }
6354 if( nSql && !_all_whitespace(zSql) ){
6355 runOneSqlLine(p, zSql, in, startline);
6356 }
6357 free(zSql);
6358 free(zLine);
6359 return errCnt>0;
6360}
6361
6362/*
6363** Return a pathname which is the user's home directory. A
6364** 0 return indicates an error of some kind.
6365*/
6366static char *find_home_dir(int clearFlag){
6367 static char *home_dir = NULL;
6368 if( clearFlag ){
6369 free(home_dir);
6370 home_dir = 0;
6371 return 0;
6372 }
6373 if( home_dir ) return home_dir;
6374
6375#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6376 && !defined(__RTP__) && !defined(_WRS_KERNEL)
6377 {
6378 struct passwd *pwent;
6379 uid_t uid = getuid();
6380 if( (pwent=getpwuid(uid)) != NULL) {
6381 home_dir = pwent->pw_dir;
6382 }
6383 }
6384#endif
6385
6386#if defined(_WIN32_WCE)
6387 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6388 */
6389 home_dir = "/";
6390#else
6391
6392#if defined(_WIN32) || defined(WIN32)
6393 if (!home_dir) {
6394 home_dir = getenv("USERPROFILE");
6395 }
6396#endif
6397
6398 if (!home_dir) {
6399 home_dir = getenv("HOME");
6400 }
6401
6402#if defined(_WIN32) || defined(WIN32)
6403 if (!home_dir) {
6404 char *zDrive, *zPath;
6405 int n;
6406 zDrive = getenv("HOMEDRIVE");
6407 zPath = getenv("HOMEPATH");
6408 if( zDrive && zPath ){
6409 n = strlen30(zDrive) + strlen30(zPath) + 1;
6410 home_dir = malloc( n );
6411 if( home_dir==0 ) return 0;
6412 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6413 return home_dir;
6414 }
6415 home_dir = "c:\\";
6416 }
6417#endif
6418
6419#endif /* !_WIN32_WCE */
6420
6421 if( home_dir ){
6422 int n = strlen30(home_dir) + 1;
6423 char *z = malloc( n );
6424 if( z ) memcpy(z, home_dir, n);
6425 home_dir = z;
6426 }
6427
6428 return home_dir;
6429}
6430
6431/*
6432** Read input from the file given by sqliterc_override. Or if that
6433** parameter is NULL, take input from ~/.sqliterc
6434**
6435** Returns the number of errors.
6436*/
6437static void process_sqliterc(
6438 ShellState *p, /* Configuration data */
6439 const char *sqliterc_override /* Name of config file. NULL to use default */
6440){
6441 char *home_dir = NULL;
6442 const char *sqliterc = sqliterc_override;
6443 char *zBuf = 0;
6444 FILE *in = NULL;
6445
6446 if (sqliterc == NULL) {
6447 home_dir = find_home_dir(0);
6448 if( home_dir==0 ){
6449 raw_printf(stderr, "-- warning: cannot find home directory;"
6450 " cannot read ~/.sqliterc\n");
6451 return;
6452 }
6453 sqlite3_initialize();
6454 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6455 sqliterc = zBuf;
6456 }
6457 in = fopen(sqliterc,"rb");
6458 if( in ){
6459 if( stdin_is_interactive ){
6460 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
6461 }
6462 process_input(p,in);
6463 fclose(in);
6464 }
6465 sqlite3_free(zBuf);
6466}
6467
6468/*
6469** Show available command line options
6470*/
6471static const char zOptions[] =
6472 " -ascii set output mode to 'ascii'\n"
6473 " -bail stop after hitting an error\n"
6474 " -batch force batch I/O\n"
6475 " -column set output mode to 'column'\n"
6476 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
6477 " -csv set output mode to 'csv'\n"
6478 " -echo print commands before execution\n"
6479 " -init FILENAME read/process named file\n"
6480 " -[no]header turn headers on or off\n"
6481#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6482 " -heap SIZE Size of heap for memsys3 or memsys5\n"
6483#endif
6484 " -help show this message\n"
6485 " -html set output mode to HTML\n"
6486 " -interactive force interactive I/O\n"
6487 " -line set output mode to 'line'\n"
6488 " -list set output mode to 'list'\n"
6489 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
6490 " -mmap N default mmap size set to N\n"
6491#ifdef SQLITE_ENABLE_MULTIPLEX
6492 " -multiplex enable the multiplexor VFS\n"
6493#endif
6494 " -newline SEP set output row separator. Default: '\\n'\n"
6495 " -nullvalue TEXT set text string for NULL values. Default ''\n"
6496 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
6497 " -quote set output mode to 'quote'\n"
6498 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
6499 " -separator SEP set output column separator. Default: '|'\n"
6500 " -stats print memory stats before each finalize\n"
6501 " -version show SQLite version\n"
6502 " -vfs NAME use NAME as the default VFS\n"
6503#ifdef SQLITE_ENABLE_VFSTRACE
6504 " -vfstrace enable tracing of all VFS calls\n"
6505#endif
6506;
6507static void usage(int showDetail){
6508 utf8_printf(stderr,
6509 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6510 "FILENAME is the name of an SQLite database. A new database is created\n"
6511 "if the file does not previously exist.\n", Argv0);
6512 if( showDetail ){
6513 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
6514 }else{
6515 raw_printf(stderr, "Use the -help option for additional information\n");
6516 }
6517 exit(1);
6518}
6519
6520/*
6521** Initialize the state information in data
6522*/
6523static void main_init(ShellState *data) {
6524 memset(data, 0, sizeof(*data));
6525 data->normalMode = data->cMode = data->mode = MODE_List;
6526 data->autoExplain = 1;
6527 memcpy(data->colSeparator,SEP_Column, 2);
6528 memcpy(data->rowSeparator,SEP_Row, 2);
6529 data->showHeader = 0;
6530 data->shellFlgs = SHFLG_Lookaside;
6531 sqlite3_config(SQLITE_CONFIG_URI, 1);
6532 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
6533 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
6534 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6535 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
6536}
6537
6538/*
6539** Output text to the console in a font that attracts extra attention.
6540*/
6541#ifdef _WIN32
6542static void printBold(const char *zText){
6543 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
6544 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
6545 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
6546 SetConsoleTextAttribute(out,
6547 FOREGROUND_RED|FOREGROUND_INTENSITY
6548 );
6549 printf("%s", zText);
6550 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
6551}
6552#else
6553static void printBold(const char *zText){
6554 printf("\033[1m%s\033[0m", zText);
6555}
6556#endif
6557
6558/*
6559** Get the argument to an --option. Throw an error and die if no argument
6560** is available.
6561*/
6562static char *cmdline_option_value(int argc, char **argv, int i){
6563 if( i==argc ){
6564 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
6565 argv[0], argv[argc-1]);
6566 exit(1);
6567 }
6568 return argv[i];
6569}
6570
6571#ifndef SQLITE_SHELL_IS_UTF8
6572# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6573# define SQLITE_SHELL_IS_UTF8 (0)
6574# else
6575# define SQLITE_SHELL_IS_UTF8 (1)
6576# endif
6577#endif
6578
6579#if SQLITE_SHELL_IS_UTF8
6580int SQLITE_CDECL main(int argc, char **argv){
6581#else
6582int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
6583 char **argv;
6584#endif
6585 char *zErrMsg = 0;
6586 ShellState data;
6587 const char *zInitFile = 0;
6588 int i;
6589 int rc = 0;
6590 int warnInmemoryDb = 0;
6591 int readStdin = 1;
6592 int nCmd = 0;
6593 char **azCmd = 0;
6594
6595 setBinaryMode(stdin, 0);
6596 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
6597 stdin_is_interactive = isatty(0);
6598 stdout_is_console = isatty(1);
6599
6600#if USE_SYSTEM_SQLITE+0!=1
6601 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
6602 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
6603 sqlite3_sourceid(), SQLITE_SOURCE_ID);
6604 exit(1);
6605 }
6606#endif
6607 main_init(&data);
6608#if !SQLITE_SHELL_IS_UTF8
6609 sqlite3_initialize();
6610 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
6611 if( argv==0 ){
6612 raw_printf(stderr, "out of memory\n");
6613 exit(1);
6614 }
6615 for(i=0; i<argc; i++){
6616 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
6617 if( argv[i]==0 ){
6618 raw_printf(stderr, "out of memory\n");
6619 exit(1);
6620 }
6621 }
6622#endif
6623 assert( argc>=1 && argv && argv[0] );
6624 Argv0 = argv[0];
6625
6626 /* Make sure we have a valid signal handler early, before anything
6627 ** else is done.
6628 */
6629#ifdef SIGINT
6630 signal(SIGINT, interrupt_handler);
6631#endif
6632
6633#ifdef SQLITE_SHELL_DBNAME_PROC
6634 {
6635 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
6636 ** of a C-function that will provide the name of the database file. Use
6637 ** this compile-time option to embed this shell program in larger
6638 ** applications. */
6639 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
6640 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
6641 warnInmemoryDb = 0;
6642 }
6643#endif
6644
6645 /* Do an initial pass through the command-line argument to locate
6646 ** the name of the database file, the name of the initialization file,
6647 ** the size of the alternative malloc heap,
6648 ** and the first command to execute.
6649 */
6650 for(i=1; i<argc; i++){
6651 char *z;
6652 z = argv[i];
6653 if( z[0]!='-' ){
6654 if( data.zDbFilename==0 ){
6655 data.zDbFilename = z;
6656 }else{
6657 /* Excesss arguments are interpreted as SQL (or dot-commands) and
6658 ** mean that nothing is read from stdin */
6659 readStdin = 0;
6660 nCmd++;
6661 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
6662 if( azCmd==0 ){
6663 raw_printf(stderr, "out of memory\n");
6664 exit(1);
6665 }
6666 azCmd[nCmd-1] = z;
6667 }
6668 }
6669 if( z[1]=='-' ) z++;
6670 if( strcmp(z,"-separator")==0
6671 || strcmp(z,"-nullvalue")==0
6672 || strcmp(z,"-newline")==0
6673 || strcmp(z,"-cmd")==0
6674 ){
6675 (void)cmdline_option_value(argc, argv, ++i);
6676 }else if( strcmp(z,"-init")==0 ){
6677 zInitFile = cmdline_option_value(argc, argv, ++i);
6678 }else if( strcmp(z,"-batch")==0 ){
6679 /* Need to check for batch mode here to so we can avoid printing
6680 ** informational messages (like from process_sqliterc) before
6681 ** we do the actual processing of arguments later in a second pass.
6682 */
6683 stdin_is_interactive = 0;
6684 }else if( strcmp(z,"-heap")==0 ){
6685#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6686 const char *zSize;
6687 sqlite3_int64 szHeap;
6688
6689 zSize = cmdline_option_value(argc, argv, ++i);
6690 szHeap = integerValue(zSize);
6691 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
6692 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
6693#else
6694 (void)cmdline_option_value(argc, argv, ++i);
6695#endif
6696 }else if( strcmp(z,"-scratch")==0 ){
6697 int n, sz;
6698 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6699 if( sz>400000 ) sz = 400000;
6700 if( sz<2500 ) sz = 2500;
6701 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6702 if( n>10 ) n = 10;
6703 if( n<1 ) n = 1;
6704 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
6705 data.shellFlgs |= SHFLG_Scratch;
6706 }else if( strcmp(z,"-pagecache")==0 ){
6707 int n, sz;
6708 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6709 if( sz>70000 ) sz = 70000;
6710 if( sz<0 ) sz = 0;
6711 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6712 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
6713 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
6714 data.shellFlgs |= SHFLG_Pagecache;
6715 }else if( strcmp(z,"-lookaside")==0 ){
6716 int n, sz;
6717 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6718 if( sz<0 ) sz = 0;
6719 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6720 if( n<0 ) n = 0;
6721 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
6722 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
6723#ifdef SQLITE_ENABLE_VFSTRACE
6724 }else if( strcmp(z,"-vfstrace")==0 ){
6725 extern int vfstrace_register(
6726 const char *zTraceName,
6727 const char *zOldVfsName,
6728 int (*xOut)(const char*,void*),
6729 void *pOutArg,
6730 int makeDefault
6731 );
6732 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
6733#endif
6734#ifdef SQLITE_ENABLE_MULTIPLEX
6735 }else if( strcmp(z,"-multiplex")==0 ){
6736 extern int sqlite3_multiple_initialize(const char*,int);
6737 sqlite3_multiplex_initialize(0, 1);
6738#endif
6739 }else if( strcmp(z,"-mmap")==0 ){
6740 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
6741 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
6742 }else if( strcmp(z,"-vfs")==0 ){
6743 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
6744 if( pVfs ){
6745 sqlite3_vfs_register(pVfs, 1);
6746 }else{
6747 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
6748 exit(1);
6749 }
6750 }
6751 }
6752 if( data.zDbFilename==0 ){
6753#ifndef SQLITE_OMIT_MEMORYDB
6754 data.zDbFilename = ":memory:";
6755 warnInmemoryDb = argc==1;
6756#else
6757 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
6758 return 1;
6759#endif
6760 }
6761 data.out = stdout;
6762
6763 /* Go ahead and open the database file if it already exists. If the
6764 ** file does not exist, delay opening it. This prevents empty database
6765 ** files from being created if a user mistypes the database name argument
6766 ** to the sqlite command-line tool.
6767 */
6768 if( access(data.zDbFilename, 0)==0 ){
6769 open_db(&data, 0);
6770 }
6771
6772 /* Process the initialization file if there is one. If no -init option
6773 ** is given on the command line, look for a file named ~/.sqliterc and
6774 ** try to process it.
6775 */
6776 process_sqliterc(&data,zInitFile);
6777
6778 /* Make a second pass through the command-line argument and set
6779 ** options. This second pass is delayed until after the initialization
6780 ** file is processed so that the command-line arguments will override
6781 ** settings in the initialization file.
6782 */
6783 for(i=1; i<argc; i++){
6784 char *z = argv[i];
6785 if( z[0]!='-' ) continue;
6786 if( z[1]=='-' ){ z++; }
6787 if( strcmp(z,"-init")==0 ){
6788 i++;
6789 }else if( strcmp(z,"-html")==0 ){
6790 data.mode = MODE_Html;
6791 }else if( strcmp(z,"-list")==0 ){
6792 data.mode = MODE_List;
6793 }else if( strcmp(z,"-quote")==0 ){
6794 data.mode = MODE_Quote;
6795 }else if( strcmp(z,"-line")==0 ){
6796 data.mode = MODE_Line;
6797 }else if( strcmp(z,"-column")==0 ){
6798 data.mode = MODE_Column;
6799 }else if( strcmp(z,"-csv")==0 ){
6800 data.mode = MODE_Csv;
6801 memcpy(data.colSeparator,",",2);
6802 }else if( strcmp(z,"-ascii")==0 ){
6803 data.mode = MODE_Ascii;
6804 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
6805 SEP_Unit);
6806 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
6807 SEP_Record);
6808 }else if( strcmp(z,"-separator")==0 ){
6809 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
6810 "%s",cmdline_option_value(argc,argv,++i));
6811 }else if( strcmp(z,"-newline")==0 ){
6812 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
6813 "%s",cmdline_option_value(argc,argv,++i));
6814 }else if( strcmp(z,"-nullvalue")==0 ){
6815 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
6816 "%s",cmdline_option_value(argc,argv,++i));
6817 }else if( strcmp(z,"-header")==0 ){
6818 data.showHeader = 1;
6819 }else if( strcmp(z,"-noheader")==0 ){
6820 data.showHeader = 0;
6821 }else if( strcmp(z,"-echo")==0 ){
6822 ShellSetFlag(&data, SHFLG_Echo);
6823 }else if( strcmp(z,"-eqp")==0 ){
6824 data.autoEQP = 1;
6825 }else if( strcmp(z,"-eqpfull")==0 ){
6826 data.autoEQP = 2;
6827 }else if( strcmp(z,"-stats")==0 ){
6828 data.statsOn = 1;
6829 }else if( strcmp(z,"-scanstats")==0 ){
6830 data.scanstatsOn = 1;
6831 }else if( strcmp(z,"-backslash")==0 ){
6832 /* Undocumented command-line option: -backslash
6833 ** Causes C-style backslash escapes to be evaluated in SQL statements
6834 ** prior to sending the SQL into SQLite. Useful for injecting
6835 ** crazy bytes in the middle of SQL statements for testing and debugging.
6836 */
6837 ShellSetFlag(&data, SHFLG_Backslash);
6838 }else if( strcmp(z,"-bail")==0 ){
6839 bail_on_error = 1;
6840 }else if( strcmp(z,"-version")==0 ){
6841 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
6842 return 0;
6843 }else if( strcmp(z,"-interactive")==0 ){
6844 stdin_is_interactive = 1;
6845 }else if( strcmp(z,"-batch")==0 ){
6846 stdin_is_interactive = 0;
6847 }else if( strcmp(z,"-heap")==0 ){
6848 i++;
6849 }else if( strcmp(z,"-scratch")==0 ){
6850 i+=2;
6851 }else if( strcmp(z,"-pagecache")==0 ){
6852 i+=2;
6853 }else if( strcmp(z,"-lookaside")==0 ){
6854 i+=2;
6855 }else if( strcmp(z,"-mmap")==0 ){
6856 i++;
6857 }else if( strcmp(z,"-vfs")==0 ){
6858 i++;
6859#ifdef SQLITE_ENABLE_VFSTRACE
6860 }else if( strcmp(z,"-vfstrace")==0 ){
6861 i++;
6862#endif
6863#ifdef SQLITE_ENABLE_MULTIPLEX
6864 }else if( strcmp(z,"-multiplex")==0 ){
6865 i++;
6866#endif
6867 }else if( strcmp(z,"-help")==0 ){
6868 usage(1);
6869 }else if( strcmp(z,"-cmd")==0 ){
6870 /* Run commands that follow -cmd first and separately from commands
6871 ** that simply appear on the command-line. This seems goofy. It would
6872 ** be better if all commands ran in the order that they appear. But
6873 ** we retain the goofy behavior for historical compatibility. */
6874 if( i==argc-1 ) break;
6875 z = cmdline_option_value(argc,argv,++i);
6876 if( z[0]=='.' ){
6877 rc = do_meta_command(z, &data);
6878 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
6879 }else{
6880 open_db(&data, 0);
6881 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
6882 if( zErrMsg!=0 ){
6883 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6884 if( bail_on_error ) return rc!=0 ? rc : 1;
6885 }else if( rc!=0 ){
6886 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
6887 if( bail_on_error ) return rc;
6888 }
6889 }
6890 }else{
6891 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
6892 raw_printf(stderr,"Use -help for a list of options.\n");
6893 return 1;
6894 }
6895 data.cMode = data.mode;
6896 }
6897
6898 if( !readStdin ){
6899 /* Run all arguments that do not begin with '-' as if they were separate
6900 ** command-line inputs, except for the argToSkip argument which contains
6901 ** the database filename.
6902 */
6903 for(i=0; i<nCmd; i++){
6904 if( azCmd[i][0]=='.' ){
6905 rc = do_meta_command(azCmd[i], &data);
6906 if( rc ) return rc==2 ? 0 : rc;
6907 }else{
6908 open_db(&data, 0);
6909 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
6910 if( zErrMsg!=0 ){
6911 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6912 return rc!=0 ? rc : 1;
6913 }else if( rc!=0 ){
6914 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
6915 return rc;
6916 }
6917 }
6918 }
6919 free(azCmd);
6920 }else{
6921 /* Run commands received from standard input
6922 */
6923 if( stdin_is_interactive ){
6924 char *zHome;
6925 char *zHistory = 0;
6926 int nHistory;
6927 printf(
6928 "SQLite version %s %.19s\n" /*extra-version-info*/
6929 "Enter \".help\" for usage hints.\n",
6930 sqlite3_libversion(), sqlite3_sourceid()
6931 );
6932 if( warnInmemoryDb ){
6933 printf("Connected to a ");
6934 printBold("transient in-memory database");
6935 printf(".\nUse \".open FILENAME\" to reopen on a "
6936 "persistent database.\n");
6937 }
6938 zHome = find_home_dir(0);
6939 if( zHome ){
6940 nHistory = strlen30(zHome) + 20;
6941 if( (zHistory = malloc(nHistory))!=0 ){
6942 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
6943 }
6944 }
6945 if( zHistory ){ shell_read_history(zHistory); }
6946 rc = process_input(&data, 0);
6947 if( zHistory ){
6948 shell_stifle_history(100);
6949 shell_write_history(zHistory);
6950 free(zHistory);
6951 }
6952 }else{
6953 rc = process_input(&data, stdin);
6954 }
6955 }
6956 set_table_name(&data, 0);
6957 if( data.db ){
6958 session_close_all(&data);
6959 sqlite3_close(data.db);
6960 }
6961 sqlite3_free(data.zFreeOnClose);
6962 find_home_dir(1);
6963#if !SQLITE_SHELL_IS_UTF8
6964 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
6965 sqlite3_free(argv);
6966#endif
6967 return rc;
6968}