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