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