blob: 38a8991b9d58457aff95f3584610ee808b77bbb0 [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"
drh1e506b52018-01-05 21:01:37 +000064typedef sqlite3_int64 i64;
65typedef sqlite3_uint64 u64;
drh1fa6d9f2018-01-06 21:46:01 +000066typedef unsigned char u8;
drh2ce15c32017-07-11 13:34:40 +000067#if SQLITE_USER_AUTHENTICATION
68# include "sqlite3userauth.h"
69#endif
70#include <ctype.h>
71#include <stdarg.h>
72
73#if !defined(_WIN32) && !defined(WIN32)
74# include <signal.h>
75# if !defined(__RTP__) && !defined(_WRS_KERNEL)
76# include <pwd.h>
77# endif
mistachkinacae8c32018-01-05 20:08:46 +000078#endif
mistachkin562f0c82018-01-09 00:28:24 +000079#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
drh2ce15c32017-07-11 13:34:40 +000080# include <unistd.h>
mistachkinacae8c32018-01-05 20:08:46 +000081# include <dirent.h>
mistachkin562f0c82018-01-09 00:28:24 +000082# if defined(__MINGW32__)
mistachkinacae8c32018-01-05 20:08:46 +000083# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000084# ifndef S_ISLNK
85# define S_ISLNK(mode) (0)
86# endif
mistachkinacae8c32018-01-05 20:08:46 +000087# endif
drh2ce15c32017-07-11 13:34:40 +000088#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000089#include <sys/types.h>
90#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000091
92#if HAVE_READLINE
93# include <readline/readline.h>
94# include <readline/history.h>
95#endif
96
97#if HAVE_EDITLINE
98# include <editline/readline.h>
99#endif
100
101#if HAVE_EDITLINE || HAVE_READLINE
102
103# define shell_add_history(X) add_history(X)
104# define shell_read_history(X) read_history(X)
105# define shell_write_history(X) write_history(X)
106# define shell_stifle_history(X) stifle_history(X)
107# define shell_readline(X) readline(X)
108
109#elif HAVE_LINENOISE
110
111# include "linenoise.h"
112# define shell_add_history(X) linenoiseHistoryAdd(X)
113# define shell_read_history(X) linenoiseHistoryLoad(X)
114# define shell_write_history(X) linenoiseHistorySave(X)
115# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
116# define shell_readline(X) linenoise(X)
117
118#else
119
120# define shell_read_history(X)
121# define shell_write_history(X)
122# define shell_stifle_history(X)
123
124# define SHELL_USE_LOCAL_GETLINE 1
125#endif
126
127
128#if defined(_WIN32) || defined(WIN32)
129# include <io.h>
130# include <fcntl.h>
131# define isatty(h) _isatty(h)
132# ifndef access
133# define access(f,m) _access((f),(m))
134# endif
mistachkince2052b2018-03-23 00:31:53 +0000135# ifndef unlink
136# define unlink _unlink
137# endif
drh2ce15c32017-07-11 13:34:40 +0000138# undef popen
139# define popen _popen
140# undef pclose
141# define pclose _pclose
142#else
143 /* Make sure isatty() has a prototype. */
144 extern int isatty(int);
145
146# if !defined(__RTP__) && !defined(_WRS_KERNEL)
147 /* popen and pclose are not C89 functions and so are
148 ** sometimes omitted from the <stdio.h> header */
149 extern FILE *popen(const char*,const char*);
150 extern int pclose(FILE*);
151# else
152# define SQLITE_OMIT_POPEN 1
153# endif
154#endif
155
156#if defined(_WIN32_WCE)
157/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
158 * thus we always assume that we have a console. That can be
159 * overridden with the -batch command line option.
160 */
161#define isatty(x) 1
162#endif
163
164/* ctype macros that work with signed characters */
165#define IsSpace(X) isspace((unsigned char)X)
166#define IsDigit(X) isdigit((unsigned char)X)
167#define ToLower(X) (char)tolower((unsigned char)X)
168
169#if defined(_WIN32) || defined(WIN32)
170#include <windows.h>
171
172/* string conversion routines only needed on Win32 */
173extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
174extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
175extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
176extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
177#endif
178
179/* On Windows, we normally run with output mode of TEXT so that \n characters
180** are automatically translated into \r\n. However, this behavior needs
181** to be disabled in some cases (ex: when generating CSV output and when
182** rendering quoted strings that contain \n characters). The following
183** routines take care of that.
184*/
185#if defined(_WIN32) || defined(WIN32)
186static void setBinaryMode(FILE *file, int isOutput){
187 if( isOutput ) fflush(file);
188 _setmode(_fileno(file), _O_BINARY);
189}
190static void setTextMode(FILE *file, int isOutput){
191 if( isOutput ) fflush(file);
192 _setmode(_fileno(file), _O_TEXT);
193}
194#else
195# define setBinaryMode(X,Y)
196# define setTextMode(X,Y)
197#endif
198
199
200/* True if the timer is enabled */
201static int enableTimer = 0;
202
203/* Return the current wall-clock time */
204static sqlite3_int64 timeOfDay(void){
205 static sqlite3_vfs *clockVfs = 0;
206 sqlite3_int64 t;
207 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
208 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
209 clockVfs->xCurrentTimeInt64(clockVfs, &t);
210 }else{
211 double r;
212 clockVfs->xCurrentTime(clockVfs, &r);
213 t = (sqlite3_int64)(r*86400000.0);
214 }
215 return t;
216}
217
218#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
219#include <sys/time.h>
220#include <sys/resource.h>
221
222/* VxWorks does not support getrusage() as far as we can determine */
223#if defined(_WRS_KERNEL) || defined(__RTP__)
224struct rusage {
225 struct timeval ru_utime; /* user CPU time used */
226 struct timeval ru_stime; /* system CPU time used */
227};
228#define getrusage(A,B) memset(B,0,sizeof(*B))
229#endif
230
231/* Saved resource information for the beginning of an operation */
232static struct rusage sBegin; /* CPU time at start */
233static sqlite3_int64 iBegin; /* Wall-clock time at start */
234
235/*
236** Begin timing an operation
237*/
238static void beginTimer(void){
239 if( enableTimer ){
240 getrusage(RUSAGE_SELF, &sBegin);
241 iBegin = timeOfDay();
242 }
243}
244
245/* Return the difference of two time_structs in seconds */
246static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
247 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
248 (double)(pEnd->tv_sec - pStart->tv_sec);
249}
250
251/*
252** Print the timing results.
253*/
254static void endTimer(void){
255 if( enableTimer ){
256 sqlite3_int64 iEnd = timeOfDay();
257 struct rusage sEnd;
258 getrusage(RUSAGE_SELF, &sEnd);
259 printf("Run Time: real %.3f user %f sys %f\n",
260 (iEnd - iBegin)*0.001,
261 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
262 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
263 }
264}
265
266#define BEGIN_TIMER beginTimer()
267#define END_TIMER endTimer()
268#define HAS_TIMER 1
269
270#elif (defined(_WIN32) || defined(WIN32))
271
272/* Saved resource information for the beginning of an operation */
273static HANDLE hProcess;
274static FILETIME ftKernelBegin;
275static FILETIME ftUserBegin;
276static sqlite3_int64 ftWallBegin;
277typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
278 LPFILETIME, LPFILETIME);
279static GETPROCTIMES getProcessTimesAddr = NULL;
280
281/*
282** Check to see if we have timer support. Return 1 if necessary
283** support found (or found previously).
284*/
285static int hasTimer(void){
286 if( getProcessTimesAddr ){
287 return 1;
288 } else {
289 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
290 ** versions. See if the version we are running on has it, and if it
291 ** does, save off a pointer to it and the current process handle.
292 */
293 hProcess = GetCurrentProcess();
294 if( hProcess ){
295 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
296 if( NULL != hinstLib ){
297 getProcessTimesAddr =
298 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
299 if( NULL != getProcessTimesAddr ){
300 return 1;
301 }
302 FreeLibrary(hinstLib);
303 }
304 }
305 }
306 return 0;
307}
308
309/*
310** Begin timing an operation
311*/
312static void beginTimer(void){
313 if( enableTimer && getProcessTimesAddr ){
314 FILETIME ftCreation, ftExit;
315 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
316 &ftKernelBegin,&ftUserBegin);
317 ftWallBegin = timeOfDay();
318 }
319}
320
321/* Return the difference of two FILETIME structs in seconds */
322static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
323 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
324 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
325 return (double) ((i64End - i64Start) / 10000000.0);
326}
327
328/*
329** Print the timing results.
330*/
331static void endTimer(void){
332 if( enableTimer && getProcessTimesAddr){
333 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
334 sqlite3_int64 ftWallEnd = timeOfDay();
335 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
336 printf("Run Time: real %.3f user %f sys %f\n",
337 (ftWallEnd - ftWallBegin)*0.001,
338 timeDiff(&ftUserBegin, &ftUserEnd),
339 timeDiff(&ftKernelBegin, &ftKernelEnd));
340 }
341}
342
343#define BEGIN_TIMER beginTimer()
344#define END_TIMER endTimer()
345#define HAS_TIMER hasTimer()
346
347#else
348#define BEGIN_TIMER
349#define END_TIMER
350#define HAS_TIMER 0
351#endif
352
353/*
354** Used to prevent warnings about unused parameters
355*/
356#define UNUSED_PARAMETER(x) (void)(x)
357
358/*
drh5af06982018-01-10 00:53:55 +0000359** Number of elements in an array
360*/
361#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
362
363/*
drh2ce15c32017-07-11 13:34:40 +0000364** If the following flag is set, then command execution stops
365** at an error if we are not interactive.
366*/
367static int bail_on_error = 0;
368
369/*
370** Threat stdin as an interactive input if the following variable
371** is true. Otherwise, assume stdin is connected to a file or pipe.
372*/
373static int stdin_is_interactive = 1;
374
375/*
376** On Windows systems we have to know if standard output is a console
377** in order to translate UTF-8 into MBCS. The following variable is
378** true if translation is required.
379*/
380static int stdout_is_console = 1;
381
382/*
383** The following is the open SQLite database. We make a pointer
384** to this database a static variable so that it can be accessed
385** by the SIGINT handler to interrupt database processing.
386*/
387static sqlite3 *globalDb = 0;
388
389/*
390** True if an interrupt (Control-C) has been received.
391*/
392static volatile int seenInterrupt = 0;
393
394/*
395** This is the name of our program. It is set in main(), used
396** in a number of other places, mostly for error messages.
397*/
398static char *Argv0;
399
400/*
401** Prompt strings. Initialized in main. Settable with
402** .prompt main continue
403*/
404static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
405static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
406
407/*
408** Render output like fprintf(). Except, if the output is going to the
409** console and if this is running on a Windows machine, translate the
410** output from UTF-8 into MBCS.
411*/
412#if defined(_WIN32) || defined(WIN32)
413void utf8_printf(FILE *out, const char *zFormat, ...){
414 va_list ap;
415 va_start(ap, zFormat);
416 if( stdout_is_console && (out==stdout || out==stderr) ){
417 char *z1 = sqlite3_vmprintf(zFormat, ap);
418 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
419 sqlite3_free(z1);
420 fputs(z2, out);
421 sqlite3_free(z2);
422 }else{
423 vfprintf(out, zFormat, ap);
424 }
425 va_end(ap);
426}
427#elif !defined(utf8_printf)
428# define utf8_printf fprintf
429#endif
430
431/*
432** Render output like fprintf(). This should not be used on anything that
433** includes string formatting (e.g. "%s").
434*/
435#if !defined(raw_printf)
436# define raw_printf fprintf
437#endif
438
drh4b5345c2018-04-24 13:07:40 +0000439/* Indicate out-of-memory and exit. */
440static void shell_out_of_memory(void){
441 raw_printf(stderr,"Error: out of memory\n");
442 exit(1);
443}
444
drh2ce15c32017-07-11 13:34:40 +0000445/*
446** Write I/O traces to the following stream.
447*/
448#ifdef SQLITE_ENABLE_IOTRACE
449static FILE *iotrace = 0;
450#endif
451
452/*
453** This routine works like printf in that its first argument is a
454** format string and subsequent arguments are values to be substituted
455** in place of % fields. The result of formatting this string
456** is written to iotrace.
457*/
458#ifdef SQLITE_ENABLE_IOTRACE
459static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
460 va_list ap;
461 char *z;
462 if( iotrace==0 ) return;
463 va_start(ap, zFormat);
464 z = sqlite3_vmprintf(zFormat, ap);
465 va_end(ap);
466 utf8_printf(iotrace, "%s", z);
467 sqlite3_free(z);
468}
469#endif
470
471/*
472** Output string zUtf to stream pOut as w characters. If w is negative,
473** then right-justify the text. W is the width in UTF-8 characters, not
474** in bytes. This is different from the %*.*s specification in printf
475** since with %*.*s the width is measured in bytes, not characters.
476*/
477static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
478 int i;
479 int n;
480 int aw = w<0 ? -w : w;
481 char zBuf[1000];
482 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
483 for(i=n=0; zUtf[i]; i++){
484 if( (zUtf[i]&0xc0)!=0x80 ){
485 n++;
486 if( n==aw ){
487 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
488 break;
489 }
490 }
491 }
492 if( n>=aw ){
493 utf8_printf(pOut, "%.*s", i, zUtf);
494 }else if( w<0 ){
495 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
496 }else{
497 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
498 }
499}
500
501
502/*
503** Determines if a string is a number of not.
504*/
505static int isNumber(const char *z, int *realnum){
506 if( *z=='-' || *z=='+' ) z++;
507 if( !IsDigit(*z) ){
508 return 0;
509 }
510 z++;
511 if( realnum ) *realnum = 0;
512 while( IsDigit(*z) ){ z++; }
513 if( *z=='.' ){
514 z++;
515 if( !IsDigit(*z) ) return 0;
516 while( IsDigit(*z) ){ z++; }
517 if( realnum ) *realnum = 1;
518 }
519 if( *z=='e' || *z=='E' ){
520 z++;
521 if( *z=='+' || *z=='-' ) z++;
522 if( !IsDigit(*z) ) return 0;
523 while( IsDigit(*z) ){ z++; }
524 if( realnum ) *realnum = 1;
525 }
526 return *z==0;
527}
528
529/*
530** Compute a string length that is limited to what can be stored in
531** lower 30 bits of a 32-bit signed integer.
532*/
533static int strlen30(const char *z){
534 const char *z2 = z;
535 while( *z2 ){ z2++; }
536 return 0x3fffffff & (int)(z2 - z);
537}
538
539/*
540** Return the length of a string in characters. Multibyte UTF8 characters
541** count as a single character.
542*/
543static int strlenChar(const char *z){
544 int n = 0;
545 while( *z ){
546 if( (0xc0&*(z++))!=0x80 ) n++;
547 }
548 return n;
549}
550
551/*
552** This routine reads a line of text from FILE in, stores
553** the text in memory obtained from malloc() and returns a pointer
554** to the text. NULL is returned at end of file, or if malloc()
555** fails.
556**
557** If zLine is not NULL then it is a malloced buffer returned from
558** a previous call to this routine that may be reused.
559*/
560static char *local_getline(char *zLine, FILE *in){
561 int nLine = zLine==0 ? 0 : 100;
562 int n = 0;
563
564 while( 1 ){
565 if( n+100>nLine ){
566 nLine = nLine*2 + 100;
567 zLine = realloc(zLine, nLine);
568 if( zLine==0 ) return 0;
569 }
570 if( fgets(&zLine[n], nLine - n, in)==0 ){
571 if( n==0 ){
572 free(zLine);
573 return 0;
574 }
575 zLine[n] = 0;
576 break;
577 }
578 while( zLine[n] ) n++;
579 if( n>0 && zLine[n-1]=='\n' ){
580 n--;
581 if( n>0 && zLine[n-1]=='\r' ) n--;
582 zLine[n] = 0;
583 break;
584 }
585 }
586#if defined(_WIN32) || defined(WIN32)
587 /* For interactive input on Windows systems, translate the
588 ** multi-byte characterset characters into UTF-8. */
589 if( stdin_is_interactive && in==stdin ){
590 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
591 if( zTrans ){
592 int nTrans = strlen30(zTrans)+1;
593 if( nTrans>nLine ){
594 zLine = realloc(zLine, nTrans);
595 if( zLine==0 ){
596 sqlite3_free(zTrans);
597 return 0;
598 }
599 }
600 memcpy(zLine, zTrans, nTrans);
601 sqlite3_free(zTrans);
602 }
603 }
604#endif /* defined(_WIN32) || defined(WIN32) */
605 return zLine;
606}
607
608/*
609** Retrieve a single line of input text.
610**
611** If in==0 then read from standard input and prompt before each line.
612** If isContinuation is true, then a continuation prompt is appropriate.
613** If isContinuation is zero, then the main prompt should be used.
614**
615** If zPrior is not NULL then it is a buffer from a prior call to this
616** routine that can be reused.
617**
618** The result is stored in space obtained from malloc() and must either
619** be freed by the caller or else passed back into this routine via the
620** zPrior argument for reuse.
621*/
622static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
623 char *zPrompt;
624 char *zResult;
625 if( in!=0 ){
626 zResult = local_getline(zPrior, in);
627 }else{
628 zPrompt = isContinuation ? continuePrompt : mainPrompt;
629#if SHELL_USE_LOCAL_GETLINE
630 printf("%s", zPrompt);
631 fflush(stdout);
632 zResult = local_getline(zPrior, stdin);
633#else
634 free(zPrior);
635 zResult = shell_readline(zPrompt);
636 if( zResult && *zResult ) shell_add_history(zResult);
637#endif
638 }
639 return zResult;
640}
drh5af06982018-01-10 00:53:55 +0000641
642
643/*
644** Return the value of a hexadecimal digit. Return -1 if the input
645** is not a hex digit.
646*/
647static int hexDigitValue(char c){
648 if( c>='0' && c<='9' ) return c - '0';
649 if( c>='a' && c<='f' ) return c - 'a' + 10;
650 if( c>='A' && c<='F' ) return c - 'A' + 10;
651 return -1;
652}
653
654/*
655** Interpret zArg as an integer value, possibly with suffixes.
656*/
657static sqlite3_int64 integerValue(const char *zArg){
658 sqlite3_int64 v = 0;
659 static const struct { char *zSuffix; int iMult; } aMult[] = {
660 { "KiB", 1024 },
661 { "MiB", 1024*1024 },
662 { "GiB", 1024*1024*1024 },
663 { "KB", 1000 },
664 { "MB", 1000000 },
665 { "GB", 1000000000 },
666 { "K", 1000 },
667 { "M", 1000000 },
668 { "G", 1000000000 },
669 };
670 int i;
671 int isNeg = 0;
672 if( zArg[0]=='-' ){
673 isNeg = 1;
674 zArg++;
675 }else if( zArg[0]=='+' ){
676 zArg++;
677 }
678 if( zArg[0]=='0' && zArg[1]=='x' ){
679 int x;
680 zArg += 2;
681 while( (x = hexDigitValue(zArg[0]))>=0 ){
682 v = (v<<4) + x;
683 zArg++;
684 }
685 }else{
686 while( IsDigit(zArg[0]) ){
687 v = v*10 + zArg[0] - '0';
688 zArg++;
689 }
690 }
691 for(i=0; i<ArraySize(aMult); i++){
692 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
693 v *= aMult[i].iMult;
694 break;
695 }
696 }
697 return isNeg? -v : v;
698}
699
drh2ce15c32017-07-11 13:34:40 +0000700/*
701** A variable length string to which one can append text.
702*/
703typedef struct ShellText ShellText;
704struct ShellText {
705 char *z;
706 int n;
707 int nAlloc;
708};
709
710/*
711** Initialize and destroy a ShellText object
712*/
713static void initText(ShellText *p){
714 memset(p, 0, sizeof(*p));
715}
716static void freeText(ShellText *p){
717 free(p->z);
718 initText(p);
719}
720
721/* zIn is either a pointer to a NULL-terminated string in memory obtained
722** from malloc(), or a NULL pointer. The string pointed to by zAppend is
723** added to zIn, and the result returned in memory obtained from malloc().
724** zIn, if it was not NULL, is freed.
725**
726** If the third argument, quote, is not '\0', then it is used as a
727** quote character for zAppend.
728*/
729static void appendText(ShellText *p, char const *zAppend, char quote){
730 int len;
731 int i;
732 int nAppend = strlen30(zAppend);
733
734 len = nAppend+p->n+1;
735 if( quote ){
736 len += 2;
737 for(i=0; i<nAppend; i++){
738 if( zAppend[i]==quote ) len++;
739 }
740 }
741
742 if( p->n+len>=p->nAlloc ){
743 p->nAlloc = p->nAlloc*2 + len + 20;
744 p->z = realloc(p->z, p->nAlloc);
745 if( p->z==0 ){
746 memset(p, 0, sizeof(*p));
747 return;
748 }
749 }
750
751 if( quote ){
752 char *zCsr = p->z+p->n;
753 *zCsr++ = quote;
754 for(i=0; i<nAppend; i++){
755 *zCsr++ = zAppend[i];
756 if( zAppend[i]==quote ) *zCsr++ = quote;
757 }
758 *zCsr++ = quote;
759 p->n = (int)(zCsr - p->z);
760 *zCsr = '\0';
761 }else{
762 memcpy(p->z+p->n, zAppend, nAppend);
763 p->n += nAppend;
764 p->z[p->n] = '\0';
765 }
766}
767
768/*
769** Attempt to determine if identifier zName needs to be quoted, either
770** because it contains non-alphanumeric characters, or because it is an
771** SQLite keyword. Be conservative in this estimate: When in doubt assume
772** that quoting is required.
773**
774** Return '"' if quoting is required. Return 0 if no quoting is required.
775*/
776static char quoteChar(const char *zName){
drhfc0ec3e2018-04-25 19:02:48 +0000777 int i;
drh2ce15c32017-07-11 13:34:40 +0000778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
779 for(i=0; zName[i]; i++){
780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
781 }
drhfc0ec3e2018-04-25 19:02:48 +0000782 return sqlite3_keyword_check(zName, i) ? '"' : 0;
drh2ce15c32017-07-11 13:34:40 +0000783}
784
785/*
drh667a2a22018-01-02 00:04:37 +0000786** Construct a fake object name and column list to describe the structure
787** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000788*/
drh667a2a22018-01-02 00:04:37 +0000789static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000790 sqlite3 *db, /* The database connection containing the vtab */
791 const char *zSchema, /* Schema of the database holding the vtab */
792 const char *zName /* The name of the virtual table */
793){
794 sqlite3_stmt *pStmt = 0;
795 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000796 ShellText s;
797 char cQuote;
798 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000799 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000800
drh1d315cf2018-01-01 21:49:43 +0000801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
804 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000805 initText(&s);
806 if( zSchema ){
807 cQuote = quoteChar(zSchema);
808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
809 appendText(&s, zSchema, cQuote);
810 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000811 }
drh1d315cf2018-01-01 21:49:43 +0000812 cQuote = quoteChar(zName);
813 appendText(&s, zName, cQuote);
814 while( sqlite3_step(pStmt)==SQLITE_ROW ){
815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000816 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000817 appendText(&s, zDiv, 0);
818 zDiv = ",";
819 cQuote = quoteChar(zCol);
820 appendText(&s, zCol, cQuote);
821 }
822 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000823 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000824 if( nRow==0 ){
825 freeText(&s);
826 s.z = 0;
827 }
drh1d315cf2018-01-01 21:49:43 +0000828 return s.z;
drhceba7922018-01-01 21:28:25 +0000829}
830
831/*
drh667a2a22018-01-02 00:04:37 +0000832** SQL function: shell_module_schema(X)
833**
834** Return a fake schema for the table-valued function or eponymous virtual
835** table X.
836*/
837static void shellModuleSchema(
838 sqlite3_context *pCtx,
839 int nVal,
840 sqlite3_value **apVal
841){
842 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
drhb9685182018-01-17 13:15:23 +0000844 UNUSED_PARAMETER(nVal);
drh667a2a22018-01-02 00:04:37 +0000845 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000847 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000848 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000849 }
850}
851
852/*
drh2ce15c32017-07-11 13:34:40 +0000853** SQL function: shell_add_schema(S,X)
854**
855** Add the schema name X to the CREATE statement in S and return the result.
856** Examples:
857**
858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
859**
860** Also works on
861**
862** CREATE INDEX
863** CREATE UNIQUE INDEX
864** CREATE VIEW
865** CREATE TRIGGER
866** CREATE VIRTUAL TABLE
867**
868** This UDF is used by the .schema command to insert the schema name of
869** attached databases into the middle of the sqlite_master.sql field.
870*/
871static void shellAddSchemaName(
872 sqlite3_context *pCtx,
873 int nVal,
874 sqlite3_value **apVal
875){
876 static const char *aPrefix[] = {
877 "TABLE",
878 "INDEX",
879 "UNIQUE INDEX",
880 "VIEW",
881 "TRIGGER",
882 "VIRTUAL TABLE"
883 };
884 int i = 0;
885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000887 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000888 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drhb9685182018-01-17 13:15:23 +0000889 UNUSED_PARAMETER(nVal);
drh2ce15c32017-07-11 13:34:40 +0000890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000892 int n = strlen30(aPrefix[i]);
893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000894 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000895 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000896 if( zSchema ){
897 char cQuote = quoteChar(zSchema);
898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
900 }else{
901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
902 }
drh2ce15c32017-07-11 13:34:40 +0000903 }
drh667a2a22018-01-02 00:04:37 +0000904 if( zName
905 && aPrefix[i][0]=='V'
906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
907 ){
908 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000910 }else{
dandcfbff92018-01-08 17:05:32 +0000911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000912 }
dandcfbff92018-01-08 17:05:32 +0000913 free(zFake);
drhceba7922018-01-01 21:28:25 +0000914 }
915 if( z ){
916 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
917 return;
918 }
drh2ce15c32017-07-11 13:34:40 +0000919 }
920 }
921 }
922 sqlite3_result_value(pCtx, apVal[0]);
923}
924
925/*
926** The source code for several run-time loadable extensions is inserted
927** below by the ../tool/mkshellc.tcl script. Before processing that included
928** code, we need to override some macros to make the included program code
929** work here in the middle of this regular program.
930*/
931#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000932#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000933
mistachkinacae8c32018-01-05 20:08:46 +0000934#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000935INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000936INCLUDE test_windirent.c
937#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000938#endif
drh2ce15c32017-07-11 13:34:40 +0000939INCLUDE ../ext/misc/shathree.c
940INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000941INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000942INCLUDE ../ext/misc/appendvfs.c
dan72afc3c2017-12-05 18:32:40 +0000943#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000944INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000945INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000946#endif
dan43efc182017-12-19 17:42:13 +0000947INCLUDE ../ext/expert/sqlite3expert.h
948INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000949
950#if defined(SQLITE_ENABLE_SESSION)
951/*
952** State information for a single open session
953*/
954typedef struct OpenSession OpenSession;
955struct OpenSession {
956 char *zName; /* Symbolic name for this session */
957 int nFilter; /* Number of xFilter rejection GLOB patterns */
958 char **azFilter; /* Array of xFilter rejection GLOB patterns */
959 sqlite3_session *p; /* The open session */
960};
961#endif
962
963/*
964** Shell output mode information from before ".explain on",
965** saved so that it can be restored by ".explain off"
966*/
967typedef struct SavedModeInfo SavedModeInfo;
968struct SavedModeInfo {
969 int valid; /* Is there legit data in here? */
970 int mode; /* Mode prior to ".explain on" */
971 int showHeader; /* The ".header" setting prior to ".explain on" */
972 int colWidth[100]; /* Column widths prior to ".explain on" */
973};
974
dan43efc182017-12-19 17:42:13 +0000975typedef struct ExpertInfo ExpertInfo;
976struct ExpertInfo {
977 sqlite3expert *pExpert;
978 int bVerbose;
979};
980
drh4b5345c2018-04-24 13:07:40 +0000981/* A single line in the EQP output */
982typedef struct EQPGraphRow EQPGraphRow;
983struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000984 int iEqpId; /* ID for this row */
985 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000986 EQPGraphRow *pNext; /* Next row in sequence */
987 char zText[1]; /* Text to display for this row */
988};
989
990/* All EQP output is collected into an instance of the following */
991typedef struct EQPGraph EQPGraph;
992struct EQPGraph {
993 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
994 EQPGraphRow *pLast; /* Last element of the pRow list */
995 char zPrefix[100]; /* Graph prefix */
996};
997
drh2ce15c32017-07-11 13:34:40 +0000998/*
999** State information about the database connection is contained in an
1000** instance of the following structure.
1001*/
1002typedef struct ShellState ShellState;
1003struct ShellState {
1004 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001005 u8 autoExplain; /* Automatically turn on .explain mode */
1006 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001007 u8 autoEQPtest; /* autoEQP is in test mode */
drh1fa6d9f2018-01-06 21:46:01 +00001008 u8 statsOn; /* True to display memory stats before each finalize */
1009 u8 scanstatsOn; /* True to display scan stats before each finalize */
1010 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001011 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001012 u8 nEqpLevel; /* Depth of the EQP output graph */
1013 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001014 int outCount; /* Revert to stdout when reaching zero */
1015 int cnt; /* Number of records displayed so far */
1016 FILE *out; /* Write results here */
1017 FILE *traceOut; /* Output for sqlite3_trace() */
1018 int nErr; /* Number of errors seen */
1019 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001020 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001021 int cMode; /* temporary output mode for the current query */
1022 int normalMode; /* Output mode before ".explain on" */
1023 int writableSchema; /* True if PRAGMA writable_schema=ON */
1024 int showHeader; /* True to show column names in List or Column mode */
1025 int nCheck; /* Number of ".check" commands run */
1026 unsigned shellFlgs; /* Various flags */
1027 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001028 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001029 char zTestcase[30]; /* Name of current test case */
1030 char colSeparator[20]; /* Column separator character for several modes */
1031 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001032 char colSepPrior[20]; /* Saved column separator */
1033 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001034 int colWidth[100]; /* Requested width of each column when in column mode*/
1035 int actualWidth[100]; /* Actual width of each column */
1036 char nullValue[20]; /* The text to print when a NULL comes back from
1037 ** the database */
1038 char outfile[FILENAME_MAX]; /* Filename for *out */
1039 const char *zDbFilename; /* name of the database file */
1040 char *zFreeOnClose; /* Filename to free when closing */
1041 const char *zVfs; /* Name of VFS to use */
1042 sqlite3_stmt *pStmt; /* Current statement if any. */
1043 FILE *pLog; /* Write log output here */
1044 int *aiIndent; /* Array of indents used in MODE_Explain */
1045 int nIndent; /* Size of array aiIndent[] */
1046 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001047 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001048#if defined(SQLITE_ENABLE_SESSION)
1049 int nSession; /* Number of active sessions */
1050 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1051#endif
dan43efc182017-12-19 17:42:13 +00001052 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001053};
1054
drh1fa6d9f2018-01-06 21:46:01 +00001055
drhada70452017-12-21 21:02:27 +00001056/* Allowed values for ShellState.autoEQP
1057*/
drhe2ca99c2018-05-02 00:33:43 +00001058#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1059#define AUTOEQP_on 1 /* Automatic EQP is on */
1060#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1061#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001062
drh1fa6d9f2018-01-06 21:46:01 +00001063/* Allowed values for ShellState.openMode
1064*/
1065#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1066#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1067#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1068#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
drhee269a62018-02-14 23:27:43 +00001069#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
drh1fa6d9f2018-01-06 21:46:01 +00001070
drh2ce15c32017-07-11 13:34:40 +00001071/*
1072** These are the allowed shellFlgs values
1073*/
drhb2a0f752017-08-28 15:51:35 +00001074#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1075#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1076#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1077#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1078#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1079#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1080#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001081
1082/*
1083** Macros for testing and setting shellFlgs
1084*/
1085#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1086#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1087#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1088
1089/*
1090** These are the allowed modes.
1091*/
1092#define MODE_Line 0 /* One column per line. Blank line between records */
1093#define MODE_Column 1 /* One record per line in neat columns */
1094#define MODE_List 2 /* One record per line with a separator */
1095#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1096#define MODE_Html 4 /* Generate an XHTML table */
1097#define MODE_Insert 5 /* Generate SQL "insert" statements */
1098#define MODE_Quote 6 /* Quote values as for SQL */
1099#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1100#define MODE_Csv 8 /* Quote strings, numbers are plain */
1101#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1102#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1103#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001104#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001105
1106static const char *modeDescr[] = {
1107 "line",
1108 "column",
1109 "list",
1110 "semi",
1111 "html",
1112 "insert",
1113 "quote",
1114 "tcl",
1115 "csv",
1116 "explain",
1117 "ascii",
1118 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001119 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001120};
1121
1122/*
1123** These are the column/row/line separators used by the various
1124** import/export modes.
1125*/
1126#define SEP_Column "|"
1127#define SEP_Row "\n"
1128#define SEP_Tab "\t"
1129#define SEP_Space " "
1130#define SEP_Comma ","
1131#define SEP_CrLf "\r\n"
1132#define SEP_Unit "\x1F"
1133#define SEP_Record "\x1E"
1134
1135/*
drh2ce15c32017-07-11 13:34:40 +00001136** A callback for the sqlite3_log() interface.
1137*/
1138static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1139 ShellState *p = (ShellState*)pArg;
1140 if( p->pLog==0 ) return;
1141 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1142 fflush(p->pLog);
1143}
1144
1145/*
drh634c70f2018-01-10 16:50:18 +00001146** SQL function: shell_putsnl(X)
1147**
1148** Write the text X to the screen (or whatever output is being directed)
1149** adding a newline at the end, and then return X.
1150*/
1151static void shellPutsFunc(
1152 sqlite3_context *pCtx,
1153 int nVal,
1154 sqlite3_value **apVal
1155){
1156 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001157 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001158 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1159 sqlite3_result_value(pCtx, apVal[0]);
1160}
1161
1162/*
drh97913132018-01-11 00:04:00 +00001163** SQL function: edit(VALUE)
1164** edit(VALUE,EDITOR)
1165**
1166** These steps:
1167**
1168** (1) Write VALUE into a temporary file.
1169** (2) Run program EDITOR on that temporary file.
1170** (3) Read the temporary file back and return its content as the result.
1171** (4) Delete the temporary file
1172**
1173** If the EDITOR argument is omitted, use the value in the VISUAL
1174** environment variable. If still there is no EDITOR, through an error.
1175**
1176** Also throw an error if the EDITOR program returns a non-zero exit code.
1177*/
drh04a28c32018-01-31 01:38:44 +00001178#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001179static void editFunc(
1180 sqlite3_context *context,
1181 int argc,
1182 sqlite3_value **argv
1183){
1184 const char *zEditor;
1185 char *zTempFile = 0;
1186 sqlite3 *db;
1187 char *zCmd = 0;
1188 int bBin;
1189 int rc;
1190 FILE *f = 0;
1191 sqlite3_int64 sz;
1192 sqlite3_int64 x;
1193 unsigned char *p = 0;
1194
1195 if( argc==2 ){
1196 zEditor = (const char*)sqlite3_value_text(argv[1]);
1197 }else{
1198 zEditor = getenv("VISUAL");
1199 }
1200 if( zEditor==0 ){
1201 sqlite3_result_error(context, "no editor for edit()", -1);
1202 return;
1203 }
1204 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1205 sqlite3_result_error(context, "NULL input to edit()", -1);
1206 return;
1207 }
1208 db = sqlite3_context_db_handle(context);
1209 zTempFile = 0;
1210 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1211 if( zTempFile==0 ){
1212 sqlite3_uint64 r = 0;
1213 sqlite3_randomness(sizeof(r), &r);
1214 zTempFile = sqlite3_mprintf("temp%llx", r);
1215 if( zTempFile==0 ){
1216 sqlite3_result_error_nomem(context);
1217 return;
1218 }
1219 }
1220 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1221 f = fopen(zTempFile, bBin ? "wb" : "w");
1222 if( f==0 ){
1223 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1224 goto edit_func_end;
1225 }
1226 sz = sqlite3_value_bytes(argv[0]);
1227 if( bBin ){
1228 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1229 }else{
1230 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1231 }
1232 fclose(f);
1233 f = 0;
1234 if( x!=sz ){
1235 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1236 goto edit_func_end;
1237 }
1238 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1239 if( zCmd==0 ){
1240 sqlite3_result_error_nomem(context);
1241 goto edit_func_end;
1242 }
1243 rc = system(zCmd);
1244 sqlite3_free(zCmd);
1245 if( rc ){
1246 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1247 goto edit_func_end;
1248 }
1249 f = fopen(zTempFile, bBin ? "rb" : "r");
1250 if( f==0 ){
1251 sqlite3_result_error(context,
1252 "edit() cannot reopen temp file after edit", -1);
1253 goto edit_func_end;
1254 }
1255 fseek(f, 0, SEEK_END);
1256 sz = ftell(f);
1257 rewind(f);
1258 p = sqlite3_malloc64( sz+(bBin==0) );
1259 if( p==0 ){
1260 sqlite3_result_error_nomem(context);
1261 goto edit_func_end;
1262 }
1263 if( bBin ){
1264 x = fread(p, 1, sz, f);
1265 }else{
1266 x = fread(p, 1, sz, f);
1267 p[sz] = 0;
1268 }
1269 fclose(f);
1270 f = 0;
1271 if( x!=sz ){
1272 sqlite3_result_error(context, "could not read back the whole file", -1);
1273 goto edit_func_end;
1274 }
1275 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001276 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001277 }else{
mistachkinb71aa092018-01-23 00:05:18 +00001278 sqlite3_result_text64(context, (const char*)p, sz,
1279 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001280 }
1281 p = 0;
1282
1283edit_func_end:
1284 if( f ) fclose(f);
1285 unlink(zTempFile);
1286 sqlite3_free(zTempFile);
1287 sqlite3_free(p);
1288}
drh04a28c32018-01-31 01:38:44 +00001289#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001290
1291/*
drh3c484e82018-01-10 22:27:21 +00001292** Save or restore the current output mode
1293*/
1294static void outputModePush(ShellState *p){
1295 p->modePrior = p->mode;
1296 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1297 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1298}
1299static void outputModePop(ShellState *p){
1300 p->mode = p->modePrior;
1301 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1302 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1303}
1304
1305/*
drh2ce15c32017-07-11 13:34:40 +00001306** Output the given string as a hex-encoded blob (eg. X'1234' )
1307*/
1308static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1309 int i;
1310 char *zBlob = (char *)pBlob;
1311 raw_printf(out,"X'");
1312 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1313 raw_printf(out,"'");
1314}
1315
1316/*
1317** Find a string that is not found anywhere in z[]. Return a pointer
1318** to that string.
1319**
1320** Try to use zA and zB first. If both of those are already found in z[]
1321** then make up some string and store it in the buffer zBuf.
1322*/
1323static const char *unused_string(
1324 const char *z, /* Result must not appear anywhere in z */
1325 const char *zA, const char *zB, /* Try these first */
1326 char *zBuf /* Space to store a generated string */
1327){
1328 unsigned i = 0;
1329 if( strstr(z, zA)==0 ) return zA;
1330 if( strstr(z, zB)==0 ) return zB;
1331 do{
1332 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1333 }while( strstr(z,zBuf)!=0 );
1334 return zBuf;
1335}
1336
1337/*
1338** Output the given string as a quoted string using SQL quoting conventions.
1339**
1340** See also: output_quoted_escaped_string()
1341*/
1342static void output_quoted_string(FILE *out, const char *z){
1343 int i;
1344 char c;
1345 setBinaryMode(out, 1);
1346 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1347 if( c==0 ){
1348 utf8_printf(out,"'%s'",z);
1349 }else{
1350 raw_printf(out, "'");
1351 while( *z ){
1352 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1353 if( c=='\'' ) i++;
1354 if( i ){
1355 utf8_printf(out, "%.*s", i, z);
1356 z += i;
1357 }
1358 if( c=='\'' ){
1359 raw_printf(out, "'");
1360 continue;
1361 }
1362 if( c==0 ){
1363 break;
1364 }
1365 z++;
1366 }
1367 raw_printf(out, "'");
1368 }
1369 setTextMode(out, 1);
1370}
1371
1372/*
1373** Output the given string as a quoted string using SQL quoting conventions.
1374** Additionallly , escape the "\n" and "\r" characters so that they do not
1375** get corrupted by end-of-line translation facilities in some operating
1376** systems.
1377**
1378** This is like output_quoted_string() but with the addition of the \r\n
1379** escape mechanism.
1380*/
1381static void output_quoted_escaped_string(FILE *out, const char *z){
1382 int i;
1383 char c;
1384 setBinaryMode(out, 1);
1385 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1386 if( c==0 ){
1387 utf8_printf(out,"'%s'",z);
1388 }else{
1389 const char *zNL = 0;
1390 const char *zCR = 0;
1391 int nNL = 0;
1392 int nCR = 0;
1393 char zBuf1[20], zBuf2[20];
1394 for(i=0; z[i]; i++){
1395 if( z[i]=='\n' ) nNL++;
1396 if( z[i]=='\r' ) nCR++;
1397 }
1398 if( nNL ){
1399 raw_printf(out, "replace(");
1400 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1401 }
1402 if( nCR ){
1403 raw_printf(out, "replace(");
1404 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1405 }
1406 raw_printf(out, "'");
1407 while( *z ){
1408 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1409 if( c=='\'' ) i++;
1410 if( i ){
1411 utf8_printf(out, "%.*s", i, z);
1412 z += i;
1413 }
1414 if( c=='\'' ){
1415 raw_printf(out, "'");
1416 continue;
1417 }
1418 if( c==0 ){
1419 break;
1420 }
1421 z++;
1422 if( c=='\n' ){
1423 raw_printf(out, "%s", zNL);
1424 continue;
1425 }
1426 raw_printf(out, "%s", zCR);
1427 }
1428 raw_printf(out, "'");
1429 if( nCR ){
1430 raw_printf(out, ",'%s',char(13))", zCR);
1431 }
1432 if( nNL ){
1433 raw_printf(out, ",'%s',char(10))", zNL);
1434 }
1435 }
1436 setTextMode(out, 1);
1437}
1438
1439/*
1440** Output the given string as a quoted according to C or TCL quoting rules.
1441*/
1442static void output_c_string(FILE *out, const char *z){
1443 unsigned int c;
1444 fputc('"', out);
1445 while( (c = *(z++))!=0 ){
1446 if( c=='\\' ){
1447 fputc(c, out);
1448 fputc(c, out);
1449 }else if( c=='"' ){
1450 fputc('\\', out);
1451 fputc('"', out);
1452 }else if( c=='\t' ){
1453 fputc('\\', out);
1454 fputc('t', out);
1455 }else if( c=='\n' ){
1456 fputc('\\', out);
1457 fputc('n', out);
1458 }else if( c=='\r' ){
1459 fputc('\\', out);
1460 fputc('r', out);
1461 }else if( !isprint(c&0xff) ){
1462 raw_printf(out, "\\%03o", c&0xff);
1463 }else{
1464 fputc(c, out);
1465 }
1466 }
1467 fputc('"', out);
1468}
1469
1470/*
1471** Output the given string with characters that are special to
1472** HTML escaped.
1473*/
1474static void output_html_string(FILE *out, const char *z){
1475 int i;
1476 if( z==0 ) z = "";
1477 while( *z ){
1478 for(i=0; z[i]
1479 && z[i]!='<'
1480 && z[i]!='&'
1481 && z[i]!='>'
1482 && z[i]!='\"'
1483 && z[i]!='\'';
1484 i++){}
1485 if( i>0 ){
1486 utf8_printf(out,"%.*s",i,z);
1487 }
1488 if( z[i]=='<' ){
1489 raw_printf(out,"&lt;");
1490 }else if( z[i]=='&' ){
1491 raw_printf(out,"&amp;");
1492 }else if( z[i]=='>' ){
1493 raw_printf(out,"&gt;");
1494 }else if( z[i]=='\"' ){
1495 raw_printf(out,"&quot;");
1496 }else if( z[i]=='\'' ){
1497 raw_printf(out,"&#39;");
1498 }else{
1499 break;
1500 }
1501 z += i + 1;
1502 }
1503}
1504
1505/*
1506** If a field contains any character identified by a 1 in the following
1507** array, then the string must be quoted for CSV.
1508*/
1509static const char needCsvQuote[] = {
1510 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1511 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1512 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1513 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1514 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1515 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1516 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1518 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1519 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1520 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1526};
1527
1528/*
1529** Output a single term of CSV. Actually, p->colSeparator is used for
1530** the separator, which may or may not be a comma. p->nullValue is
1531** the null value. Strings are quoted if necessary. The separator
1532** is only issued if bSep is true.
1533*/
1534static void output_csv(ShellState *p, const char *z, int bSep){
1535 FILE *out = p->out;
1536 if( z==0 ){
1537 utf8_printf(out,"%s",p->nullValue);
1538 }else{
1539 int i;
1540 int nSep = strlen30(p->colSeparator);
1541 for(i=0; z[i]; i++){
1542 if( needCsvQuote[((unsigned char*)z)[i]]
1543 || (z[i]==p->colSeparator[0] &&
1544 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1545 i = 0;
1546 break;
1547 }
1548 }
1549 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001550 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1551 utf8_printf(out, "%s", zQuoted);
1552 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001553 }else{
1554 utf8_printf(out, "%s", z);
1555 }
1556 }
1557 if( bSep ){
1558 utf8_printf(p->out, "%s", p->colSeparator);
1559 }
1560}
1561
drh2ce15c32017-07-11 13:34:40 +00001562/*
1563** This routine runs when the user presses Ctrl-C
1564*/
1565static void interrupt_handler(int NotUsed){
1566 UNUSED_PARAMETER(NotUsed);
1567 seenInterrupt++;
1568 if( seenInterrupt>2 ) exit(1);
1569 if( globalDb ) sqlite3_interrupt(globalDb);
1570}
mistachkinb4bab902017-10-27 17:09:44 +00001571
1572#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1573/*
1574** This routine runs for console events (e.g. Ctrl-C) on Win32
1575*/
1576static BOOL WINAPI ConsoleCtrlHandler(
1577 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1578){
1579 if( dwCtrlType==CTRL_C_EVENT ){
1580 interrupt_handler(0);
1581 return TRUE;
1582 }
1583 return FALSE;
1584}
drh2ce15c32017-07-11 13:34:40 +00001585#endif
1586
1587#ifndef SQLITE_OMIT_AUTHORIZATION
1588/*
1589** When the ".auth ON" is set, the following authorizer callback is
1590** invoked. It always returns SQLITE_OK.
1591*/
1592static int shellAuth(
1593 void *pClientData,
1594 int op,
1595 const char *zA1,
1596 const char *zA2,
1597 const char *zA3,
1598 const char *zA4
1599){
1600 ShellState *p = (ShellState*)pClientData;
1601 static const char *azAction[] = { 0,
1602 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1603 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1604 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1605 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1606 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1607 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1608 "PRAGMA", "READ", "SELECT",
1609 "TRANSACTION", "UPDATE", "ATTACH",
1610 "DETACH", "ALTER_TABLE", "REINDEX",
1611 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1612 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1613 };
1614 int i;
1615 const char *az[4];
1616 az[0] = zA1;
1617 az[1] = zA2;
1618 az[2] = zA3;
1619 az[3] = zA4;
1620 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1621 for(i=0; i<4; i++){
1622 raw_printf(p->out, " ");
1623 if( az[i] ){
1624 output_c_string(p->out, az[i]);
1625 }else{
1626 raw_printf(p->out, "NULL");
1627 }
1628 }
1629 raw_printf(p->out, "\n");
1630 return SQLITE_OK;
1631}
1632#endif
1633
1634/*
1635** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1636**
1637** This routine converts some CREATE TABLE statements for shadow tables
1638** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1639*/
1640static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1641 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1642 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1643 }else{
1644 utf8_printf(out, "%s%s", z, zTail);
1645 }
1646}
1647static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1648 char c = z[n];
1649 z[n] = 0;
1650 printSchemaLine(out, z, zTail);
1651 z[n] = c;
1652}
1653
1654/*
drh11be81d2018-01-06 15:46:20 +00001655** Return true if string z[] has nothing but whitespace and comments to the
1656** end of the first line.
1657*/
1658static int wsToEol(const char *z){
1659 int i;
1660 for(i=0; z[i]; i++){
1661 if( z[i]=='\n' ) return 1;
1662 if( IsSpace(z[i]) ) continue;
1663 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1664 return 0;
1665 }
1666 return 1;
1667}
drh4b5345c2018-04-24 13:07:40 +00001668
1669/*
1670** Add a new entry to the EXPLAIN QUERY PLAN data
1671*/
drhe2ca99c2018-05-02 00:33:43 +00001672static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001673 EQPGraphRow *pNew;
1674 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001675 if( p->autoEQPtest ){
1676 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1677 }
drh4b5345c2018-04-24 13:07:40 +00001678 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1679 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001680 pNew->iEqpId = iEqpId;
1681 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001682 memcpy(pNew->zText, zText, nText+1);
1683 pNew->pNext = 0;
1684 if( p->sGraph.pLast ){
1685 p->sGraph.pLast->pNext = pNew;
1686 }else{
1687 p->sGraph.pRow = pNew;
1688 }
1689 p->sGraph.pLast = pNew;
1690}
1691
1692/*
1693** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1694** in p->sGraph.
1695*/
1696static void eqp_reset(ShellState *p){
1697 EQPGraphRow *pRow, *pNext;
1698 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1699 pNext = pRow->pNext;
1700 sqlite3_free(pRow);
1701 }
1702 memset(&p->sGraph, 0, sizeof(p->sGraph));
1703}
1704
drhe2ca99c2018-05-02 00:33:43 +00001705/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001706** pOld, or return the first such line if pOld is NULL
1707*/
drhe2ca99c2018-05-02 00:33:43 +00001708static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001709 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001710 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001711 return pRow;
1712}
1713
drhe2ca99c2018-05-02 00:33:43 +00001714/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001715** recursively to render sublevels.
1716*/
drhe2ca99c2018-05-02 00:33:43 +00001717static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001718 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001719 int n = strlen30(p->sGraph.zPrefix);
1720 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001721 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1722 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001723 z = pRow->zText;
1724 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001725 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001726 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001727 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001728 p->sGraph.zPrefix[n] = 0;
1729 }
1730 }
1731}
1732
1733/*
1734** Display and reset the EXPLAIN QUERY PLAN data
1735*/
1736static void eqp_render(ShellState *p){
1737 EQPGraphRow *pRow = p->sGraph.pRow;
1738 if( pRow ){
1739 if( pRow->zText[0]=='-' ){
1740 if( pRow->pNext==0 ){
1741 eqp_reset(p);
1742 return;
1743 }
1744 utf8_printf(p->out, "%s\n", pRow->zText+3);
1745 p->sGraph.pRow = pRow->pNext;
1746 sqlite3_free(pRow);
1747 }else{
1748 utf8_printf(p->out, "QUERY PLAN\n");
1749 }
1750 p->sGraph.zPrefix[0] = 0;
1751 eqp_render_level(p, 0);
1752 eqp_reset(p);
1753 }
1754}
drh11be81d2018-01-06 15:46:20 +00001755
1756/*
drh2ce15c32017-07-11 13:34:40 +00001757** This is the callback routine that the shell
1758** invokes for each row of a query result.
1759*/
1760static int shell_callback(
1761 void *pArg,
1762 int nArg, /* Number of result columns */
1763 char **azArg, /* Text of each result column */
1764 char **azCol, /* Column names */
1765 int *aiType /* Column types */
1766){
1767 int i;
1768 ShellState *p = (ShellState*)pArg;
1769
drhb3c45232017-08-28 14:33:27 +00001770 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001771 switch( p->cMode ){
1772 case MODE_Line: {
1773 int w = 5;
1774 if( azArg==0 ) break;
1775 for(i=0; i<nArg; i++){
1776 int len = strlen30(azCol[i] ? azCol[i] : "");
1777 if( len>w ) w = len;
1778 }
1779 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1780 for(i=0; i<nArg; i++){
1781 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1782 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1783 }
1784 break;
1785 }
1786 case MODE_Explain:
1787 case MODE_Column: {
1788 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1789 const int *colWidth;
1790 int showHdr;
1791 char *rowSep;
1792 if( p->cMode==MODE_Column ){
1793 colWidth = p->colWidth;
1794 showHdr = p->showHeader;
1795 rowSep = p->rowSeparator;
1796 }else{
1797 colWidth = aExplainWidths;
1798 showHdr = 1;
1799 rowSep = SEP_Row;
1800 }
1801 if( p->cnt++==0 ){
1802 for(i=0; i<nArg; i++){
1803 int w, n;
1804 if( i<ArraySize(p->colWidth) ){
1805 w = colWidth[i];
1806 }else{
1807 w = 0;
1808 }
1809 if( w==0 ){
1810 w = strlenChar(azCol[i] ? azCol[i] : "");
1811 if( w<10 ) w = 10;
1812 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1813 if( w<n ) w = n;
1814 }
1815 if( i<ArraySize(p->actualWidth) ){
1816 p->actualWidth[i] = w;
1817 }
1818 if( showHdr ){
1819 utf8_width_print(p->out, w, azCol[i]);
1820 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1821 }
1822 }
1823 if( showHdr ){
1824 for(i=0; i<nArg; i++){
1825 int w;
1826 if( i<ArraySize(p->actualWidth) ){
1827 w = p->actualWidth[i];
1828 if( w<0 ) w = -w;
1829 }else{
1830 w = 10;
1831 }
1832 utf8_printf(p->out,"%-*.*s%s",w,w,
1833 "----------------------------------------------------------"
1834 "----------------------------------------------------------",
1835 i==nArg-1 ? rowSep : " ");
1836 }
1837 }
1838 }
1839 if( azArg==0 ) break;
1840 for(i=0; i<nArg; i++){
1841 int w;
1842 if( i<ArraySize(p->actualWidth) ){
1843 w = p->actualWidth[i];
1844 }else{
1845 w = 10;
1846 }
1847 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1848 w = strlenChar(azArg[i]);
1849 }
1850 if( i==1 && p->aiIndent && p->pStmt ){
1851 if( p->iIndent<p->nIndent ){
1852 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1853 }
1854 p->iIndent++;
1855 }
1856 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1857 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1858 }
1859 break;
1860 }
1861 case MODE_Semi: { /* .schema and .fullschema output */
1862 printSchemaLine(p->out, azArg[0], ";\n");
1863 break;
1864 }
1865 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1866 char *z;
1867 int j;
1868 int nParen = 0;
1869 char cEnd = 0;
1870 char c;
1871 int nLine = 0;
1872 assert( nArg==1 );
1873 if( azArg[0]==0 ) break;
1874 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1875 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1876 ){
1877 utf8_printf(p->out, "%s;\n", azArg[0]);
1878 break;
1879 }
1880 z = sqlite3_mprintf("%s", azArg[0]);
1881 j = 0;
1882 for(i=0; IsSpace(z[i]); i++){}
1883 for(; (c = z[i])!=0; i++){
1884 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001885 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001886 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1887 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1888 j--;
1889 }
1890 z[j++] = c;
1891 }
1892 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1893 z[j] = 0;
1894 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001895 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001896 if( c==cEnd ){
1897 cEnd = 0;
1898 }else if( c=='"' || c=='\'' || c=='`' ){
1899 cEnd = c;
1900 }else if( c=='[' ){
1901 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001902 }else if( c=='-' && z[i+1]=='-' ){
1903 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001904 }else if( c=='(' ){
1905 nParen++;
1906 }else if( c==')' ){
1907 nParen--;
1908 if( nLine>0 && nParen==0 && j>0 ){
1909 printSchemaLineN(p->out, z, j, "\n");
1910 j = 0;
1911 }
1912 }
1913 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001914 if( nParen==1 && cEnd==0
1915 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1916 ){
drh2ce15c32017-07-11 13:34:40 +00001917 if( c=='\n' ) j--;
1918 printSchemaLineN(p->out, z, j, "\n ");
1919 j = 0;
1920 nLine++;
1921 while( IsSpace(z[i+1]) ){ i++; }
1922 }
1923 }
1924 z[j] = 0;
1925 }
1926 printSchemaLine(p->out, z, ";\n");
1927 sqlite3_free(z);
1928 break;
1929 }
1930 case MODE_List: {
1931 if( p->cnt++==0 && p->showHeader ){
1932 for(i=0; i<nArg; i++){
1933 utf8_printf(p->out,"%s%s",azCol[i],
1934 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1935 }
1936 }
1937 if( azArg==0 ) break;
1938 for(i=0; i<nArg; i++){
1939 char *z = azArg[i];
1940 if( z==0 ) z = p->nullValue;
1941 utf8_printf(p->out, "%s", z);
1942 if( i<nArg-1 ){
1943 utf8_printf(p->out, "%s", p->colSeparator);
1944 }else{
1945 utf8_printf(p->out, "%s", p->rowSeparator);
1946 }
1947 }
1948 break;
1949 }
1950 case MODE_Html: {
1951 if( p->cnt++==0 && p->showHeader ){
1952 raw_printf(p->out,"<TR>");
1953 for(i=0; i<nArg; i++){
1954 raw_printf(p->out,"<TH>");
1955 output_html_string(p->out, azCol[i]);
1956 raw_printf(p->out,"</TH>\n");
1957 }
1958 raw_printf(p->out,"</TR>\n");
1959 }
1960 if( azArg==0 ) break;
1961 raw_printf(p->out,"<TR>");
1962 for(i=0; i<nArg; i++){
1963 raw_printf(p->out,"<TD>");
1964 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1965 raw_printf(p->out,"</TD>\n");
1966 }
1967 raw_printf(p->out,"</TR>\n");
1968 break;
1969 }
1970 case MODE_Tcl: {
1971 if( p->cnt++==0 && p->showHeader ){
1972 for(i=0; i<nArg; i++){
1973 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1974 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1975 }
1976 utf8_printf(p->out, "%s", p->rowSeparator);
1977 }
1978 if( azArg==0 ) break;
1979 for(i=0; i<nArg; i++){
1980 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1981 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1982 }
1983 utf8_printf(p->out, "%s", p->rowSeparator);
1984 break;
1985 }
1986 case MODE_Csv: {
1987 setBinaryMode(p->out, 1);
1988 if( p->cnt++==0 && p->showHeader ){
1989 for(i=0; i<nArg; i++){
1990 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1991 }
1992 utf8_printf(p->out, "%s", p->rowSeparator);
1993 }
1994 if( nArg>0 ){
1995 for(i=0; i<nArg; i++){
1996 output_csv(p, azArg[i], i<nArg-1);
1997 }
1998 utf8_printf(p->out, "%s", p->rowSeparator);
1999 }
2000 setTextMode(p->out, 1);
2001 break;
2002 }
2003 case MODE_Insert: {
2004 if( azArg==0 ) break;
2005 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2006 if( p->showHeader ){
2007 raw_printf(p->out,"(");
2008 for(i=0; i<nArg; i++){
2009 if( i>0 ) raw_printf(p->out, ",");
2010 if( quoteChar(azCol[i]) ){
2011 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2012 utf8_printf(p->out, "%s", z);
2013 sqlite3_free(z);
2014 }else{
2015 raw_printf(p->out, "%s", azCol[i]);
2016 }
2017 }
2018 raw_printf(p->out,")");
2019 }
2020 p->cnt++;
2021 for(i=0; i<nArg; i++){
2022 raw_printf(p->out, i>0 ? "," : " VALUES(");
2023 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2024 utf8_printf(p->out,"NULL");
2025 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2026 if( ShellHasFlag(p, SHFLG_Newlines) ){
2027 output_quoted_string(p->out, azArg[i]);
2028 }else{
2029 output_quoted_escaped_string(p->out, azArg[i]);
2030 }
2031 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2032 utf8_printf(p->out,"%s", azArg[i]);
2033 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2034 char z[50];
2035 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002036 sqlite3_uint64 ur;
2037 memcpy(&ur,&r,sizeof(r));
2038 if( ur==0x7ff0000000000000LL ){
2039 raw_printf(p->out, "1e999");
2040 }else if( ur==0xfff0000000000000LL ){
2041 raw_printf(p->out, "-1e999");
2042 }else{
2043 sqlite3_snprintf(50,z,"%!.20g", r);
2044 raw_printf(p->out, "%s", z);
2045 }
drh2ce15c32017-07-11 13:34:40 +00002046 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2047 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2048 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2049 output_hex_blob(p->out, pBlob, nBlob);
2050 }else if( isNumber(azArg[i], 0) ){
2051 utf8_printf(p->out,"%s", azArg[i]);
2052 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2053 output_quoted_string(p->out, azArg[i]);
2054 }else{
2055 output_quoted_escaped_string(p->out, azArg[i]);
2056 }
2057 }
2058 raw_printf(p->out,");\n");
2059 break;
2060 }
2061 case MODE_Quote: {
2062 if( azArg==0 ) break;
2063 if( p->cnt==0 && p->showHeader ){
2064 for(i=0; i<nArg; i++){
2065 if( i>0 ) raw_printf(p->out, ",");
2066 output_quoted_string(p->out, azCol[i]);
2067 }
2068 raw_printf(p->out,"\n");
2069 }
2070 p->cnt++;
2071 for(i=0; i<nArg; i++){
2072 if( i>0 ) raw_printf(p->out, ",");
2073 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2074 utf8_printf(p->out,"NULL");
2075 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2076 output_quoted_string(p->out, azArg[i]);
2077 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2078 utf8_printf(p->out,"%s", azArg[i]);
2079 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2080 char z[50];
2081 double r = sqlite3_column_double(p->pStmt, i);
2082 sqlite3_snprintf(50,z,"%!.20g", r);
2083 raw_printf(p->out, "%s", z);
2084 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2085 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2086 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2087 output_hex_blob(p->out, pBlob, nBlob);
2088 }else if( isNumber(azArg[i], 0) ){
2089 utf8_printf(p->out,"%s", azArg[i]);
2090 }else{
2091 output_quoted_string(p->out, azArg[i]);
2092 }
2093 }
2094 raw_printf(p->out,"\n");
2095 break;
2096 }
2097 case MODE_Ascii: {
2098 if( p->cnt++==0 && p->showHeader ){
2099 for(i=0; i<nArg; i++){
2100 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2101 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2102 }
2103 utf8_printf(p->out, "%s", p->rowSeparator);
2104 }
2105 if( azArg==0 ) break;
2106 for(i=0; i<nArg; i++){
2107 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2108 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2109 }
2110 utf8_printf(p->out, "%s", p->rowSeparator);
2111 break;
2112 }
drh4b5345c2018-04-24 13:07:40 +00002113 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002114 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002115 break;
2116 }
drh2ce15c32017-07-11 13:34:40 +00002117 }
2118 return 0;
2119}
2120
2121/*
2122** This is the callback routine that the SQLite library
2123** invokes for each row of a query result.
2124*/
2125static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2126 /* since we don't have type info, call the shell_callback with a NULL value */
2127 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2128}
2129
2130/*
2131** This is the callback routine from sqlite3_exec() that appends all
2132** output onto the end of a ShellText object.
2133*/
2134static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2135 ShellText *p = (ShellText*)pArg;
2136 int i;
2137 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002138 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002139 if( p->n ) appendText(p, "|", 0);
2140 for(i=0; i<nArg; i++){
2141 if( i ) appendText(p, ",", 0);
2142 if( azArg[i] ) appendText(p, azArg[i], 0);
2143 }
2144 return 0;
2145}
2146
2147/*
2148** Generate an appropriate SELFTEST table in the main database.
2149*/
2150static void createSelftestTable(ShellState *p){
2151 char *zErrMsg = 0;
2152 sqlite3_exec(p->db,
2153 "SAVEPOINT selftest_init;\n"
2154 "CREATE TABLE IF NOT EXISTS selftest(\n"
2155 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2156 " op TEXT,\n" /* Operator: memo run */
2157 " cmd TEXT,\n" /* Command text */
2158 " ans TEXT\n" /* Desired answer */
2159 ");"
2160 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2161 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2162 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2163 " 'memo','Tests generated by --init');\n"
2164 "INSERT INTO [_shell$self]\n"
2165 " SELECT 'run',\n"
2166 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2167 "FROM sqlite_master ORDER BY 2'',224))',\n"
2168 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2169 "FROM sqlite_master ORDER BY 2',224));\n"
2170 "INSERT INTO [_shell$self]\n"
2171 " SELECT 'run',"
2172 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2173 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2174 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2175 " FROM (\n"
2176 " SELECT name FROM sqlite_master\n"
2177 " WHERE type='table'\n"
2178 " AND name<>'selftest'\n"
2179 " AND coalesce(rootpage,0)>0\n"
2180 " )\n"
2181 " ORDER BY name;\n"
2182 "INSERT INTO [_shell$self]\n"
2183 " VALUES('run','PRAGMA integrity_check','ok');\n"
2184 "INSERT INTO selftest(tno,op,cmd,ans)"
2185 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2186 "DROP TABLE [_shell$self];"
2187 ,0,0,&zErrMsg);
2188 if( zErrMsg ){
2189 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2190 sqlite3_free(zErrMsg);
2191 }
2192 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2193}
2194
2195
2196/*
2197** Set the destination table field of the ShellState structure to
2198** the name of the table given. Escape any quote characters in the
2199** table name.
2200*/
2201static void set_table_name(ShellState *p, const char *zName){
2202 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002203 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002204 char *z;
2205
2206 if( p->zDestTable ){
2207 free(p->zDestTable);
2208 p->zDestTable = 0;
2209 }
2210 if( zName==0 ) return;
2211 cQuote = quoteChar(zName);
2212 n = strlen30(zName);
2213 if( cQuote ) n += n+2;
2214 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002215 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002216 n = 0;
2217 if( cQuote ) z[n++] = cQuote;
2218 for(i=0; zName[i]; i++){
2219 z[n++] = zName[i];
2220 if( zName[i]==cQuote ) z[n++] = cQuote;
2221 }
2222 if( cQuote ) z[n++] = cQuote;
2223 z[n] = 0;
2224}
2225
2226
2227/*
2228** Execute a query statement that will generate SQL output. Print
2229** the result columns, comma-separated, on a line and then add a
2230** semicolon terminator to the end of that line.
2231**
2232** If the number of columns is 1 and that column contains text "--"
2233** then write the semicolon on a separate line. That way, if a
2234** "--" comment occurs at the end of the statement, the comment
2235** won't consume the semicolon terminator.
2236*/
2237static int run_table_dump_query(
2238 ShellState *p, /* Query context */
2239 const char *zSelect, /* SELECT statement to extract content */
2240 const char *zFirstRow /* Print before first row, if not NULL */
2241){
2242 sqlite3_stmt *pSelect;
2243 int rc;
2244 int nResult;
2245 int i;
2246 const char *z;
2247 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2248 if( rc!=SQLITE_OK || !pSelect ){
2249 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2250 sqlite3_errmsg(p->db));
2251 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2252 return rc;
2253 }
2254 rc = sqlite3_step(pSelect);
2255 nResult = sqlite3_column_count(pSelect);
2256 while( rc==SQLITE_ROW ){
2257 if( zFirstRow ){
2258 utf8_printf(p->out, "%s", zFirstRow);
2259 zFirstRow = 0;
2260 }
2261 z = (const char*)sqlite3_column_text(pSelect, 0);
2262 utf8_printf(p->out, "%s", z);
2263 for(i=1; i<nResult; i++){
2264 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2265 }
2266 if( z==0 ) z = "";
2267 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2268 if( z[0] ){
2269 raw_printf(p->out, "\n;\n");
2270 }else{
2271 raw_printf(p->out, ";\n");
2272 }
2273 rc = sqlite3_step(pSelect);
2274 }
2275 rc = sqlite3_finalize(pSelect);
2276 if( rc!=SQLITE_OK ){
2277 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2278 sqlite3_errmsg(p->db));
2279 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2280 }
2281 return rc;
2282}
2283
2284/*
2285** Allocate space and save off current error string.
2286*/
2287static char *save_err_msg(
2288 sqlite3 *db /* Database to query */
2289){
2290 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2291 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2292 if( zErrMsg ){
2293 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2294 }
2295 return zErrMsg;
2296}
2297
2298#ifdef __linux__
2299/*
2300** Attempt to display I/O stats on Linux using /proc/PID/io
2301*/
2302static void displayLinuxIoStats(FILE *out){
2303 FILE *in;
2304 char z[200];
2305 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2306 in = fopen(z, "rb");
2307 if( in==0 ) return;
2308 while( fgets(z, sizeof(z), in)!=0 ){
2309 static const struct {
2310 const char *zPattern;
2311 const char *zDesc;
2312 } aTrans[] = {
2313 { "rchar: ", "Bytes received by read():" },
2314 { "wchar: ", "Bytes sent to write():" },
2315 { "syscr: ", "Read() system calls:" },
2316 { "syscw: ", "Write() system calls:" },
2317 { "read_bytes: ", "Bytes read from storage:" },
2318 { "write_bytes: ", "Bytes written to storage:" },
2319 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2320 };
2321 int i;
2322 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002323 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002324 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2325 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2326 break;
2327 }
2328 }
2329 }
2330 fclose(in);
2331}
2332#endif
2333
2334/*
2335** Display a single line of status using 64-bit values.
2336*/
2337static void displayStatLine(
2338 ShellState *p, /* The shell context */
2339 char *zLabel, /* Label for this one line */
2340 char *zFormat, /* Format for the result */
2341 int iStatusCtrl, /* Which status to display */
2342 int bReset /* True to reset the stats */
2343){
2344 sqlite3_int64 iCur = -1;
2345 sqlite3_int64 iHiwtr = -1;
2346 int i, nPercent;
2347 char zLine[200];
2348 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2349 for(i=0, nPercent=0; zFormat[i]; i++){
2350 if( zFormat[i]=='%' ) nPercent++;
2351 }
2352 if( nPercent>1 ){
2353 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2354 }else{
2355 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2356 }
2357 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2358}
2359
2360/*
2361** Display memory stats.
2362*/
2363static int display_stats(
2364 sqlite3 *db, /* Database to query */
2365 ShellState *pArg, /* Pointer to ShellState */
2366 int bReset /* True to reset the stats */
2367){
2368 int iCur;
2369 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002370 FILE *out;
2371 if( pArg==0 || pArg->out==0 ) return 0;
2372 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002373
drh393344f2018-03-09 16:37:05 +00002374 if( pArg->pStmt && (pArg->statsOn & 2) ){
2375 int nCol, i, x;
2376 sqlite3_stmt *pStmt = pArg->pStmt;
2377 char z[100];
2378 nCol = sqlite3_column_count(pStmt);
2379 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2380 for(i=0; i<nCol; i++){
2381 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2382 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002383#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002384 sqlite3_snprintf(30, z+x, "declared type:");
2385 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002386#endif
2387#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002388 sqlite3_snprintf(30, z+x, "database name:");
2389 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2390 sqlite3_snprintf(30, z+x, "table name:");
2391 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2392 sqlite3_snprintf(30, z+x, "origin name:");
2393 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002394#endif
drh2ce15c32017-07-11 13:34:40 +00002395 }
drh929cce82018-03-17 16:26:36 +00002396 }
drh2ce15c32017-07-11 13:34:40 +00002397
drh393344f2018-03-09 16:37:05 +00002398 displayStatLine(pArg, "Memory Used:",
2399 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2400 displayStatLine(pArg, "Number of Outstanding Allocations:",
2401 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2402 if( pArg->shellFlgs & SHFLG_Pagecache ){
2403 displayStatLine(pArg, "Number of Pcache Pages Used:",
2404 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2405 }
2406 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2407 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2408 displayStatLine(pArg, "Largest Allocation:",
2409 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2410 displayStatLine(pArg, "Largest Pcache Allocation:",
2411 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2412#ifdef YYTRACKMAXSTACKDEPTH
2413 displayStatLine(pArg, "Deepest Parser Stack:",
2414 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2415#endif
2416
2417 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002418 if( pArg->shellFlgs & SHFLG_Lookaside ){
2419 iHiwtr = iCur = -1;
2420 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2421 &iCur, &iHiwtr, bReset);
2422 raw_printf(pArg->out,
2423 "Lookaside Slots Used: %d (max %d)\n",
2424 iCur, iHiwtr);
2425 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2426 &iCur, &iHiwtr, bReset);
2427 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2428 iHiwtr);
2429 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2430 &iCur, &iHiwtr, bReset);
2431 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2432 iHiwtr);
2433 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2434 &iCur, &iHiwtr, bReset);
2435 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2436 iHiwtr);
2437 }
2438 iHiwtr = iCur = -1;
2439 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2440 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2441 iCur);
2442 iHiwtr = iCur = -1;
2443 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2444 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2445 iHiwtr = iCur = -1;
2446 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2447 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2448 iHiwtr = iCur = -1;
2449 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2450 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2451 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002452 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2453 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2454 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002455 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2456 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2457 iCur);
2458 iHiwtr = iCur = -1;
2459 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2460 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2461 iCur);
2462 }
2463
drh393344f2018-03-09 16:37:05 +00002464 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002465 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2466 bReset);
2467 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2468 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2469 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2470 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2471 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2472 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2473 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002474 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2475 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2476 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2477 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2478 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2479 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002480 }
2481
2482#ifdef __linux__
2483 displayLinuxIoStats(pArg->out);
2484#endif
2485
2486 /* Do not remove this machine readable comment: extra-stats-output-here */
2487
2488 return 0;
2489}
2490
2491/*
2492** Display scan stats.
2493*/
2494static void display_scanstats(
2495 sqlite3 *db, /* Database to query */
2496 ShellState *pArg /* Pointer to ShellState */
2497){
2498#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2499 UNUSED_PARAMETER(db);
2500 UNUSED_PARAMETER(pArg);
2501#else
2502 int i, k, n, mx;
2503 raw_printf(pArg->out, "-------- scanstats --------\n");
2504 mx = 0;
2505 for(k=0; k<=mx; k++){
2506 double rEstLoop = 1.0;
2507 for(i=n=0; 1; i++){
2508 sqlite3_stmt *p = pArg->pStmt;
2509 sqlite3_int64 nLoop, nVisit;
2510 double rEst;
2511 int iSid;
2512 const char *zExplain;
2513 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2514 break;
2515 }
2516 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2517 if( iSid>mx ) mx = iSid;
2518 if( iSid!=k ) continue;
2519 if( n==0 ){
2520 rEstLoop = (double)nLoop;
2521 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2522 }
2523 n++;
2524 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2525 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2526 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2527 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2528 rEstLoop *= rEst;
2529 raw_printf(pArg->out,
2530 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2531 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2532 );
2533 }
2534 }
2535 raw_printf(pArg->out, "---------------------------\n");
2536#endif
2537}
2538
2539/*
2540** Parameter azArray points to a zero-terminated array of strings. zStr
2541** points to a single nul-terminated string. Return non-zero if zStr
2542** is equal, according to strcmp(), to any of the strings in the array.
2543** Otherwise, return zero.
2544*/
2545static int str_in_array(const char *zStr, const char **azArray){
2546 int i;
2547 for(i=0; azArray[i]; i++){
2548 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2549 }
2550 return 0;
2551}
2552
2553/*
2554** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2555** and populate the ShellState.aiIndent[] array with the number of
2556** spaces each opcode should be indented before it is output.
2557**
2558** The indenting rules are:
2559**
2560** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2561** all opcodes that occur between the p2 jump destination and the opcode
2562** itself by 2 spaces.
2563**
2564** * For each "Goto", if the jump destination is earlier in the program
2565** and ends on one of:
2566** Yield SeekGt SeekLt RowSetRead Rewind
2567** or if the P1 parameter is one instead of zero,
2568** then indent all opcodes between the earlier instruction
2569** and "Goto" by 2 spaces.
2570*/
2571static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2572 const char *zSql; /* The text of the SQL statement */
2573 const char *z; /* Used to check if this is an EXPLAIN */
2574 int *abYield = 0; /* True if op is an OP_Yield */
2575 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2576 int iOp; /* Index of operation in p->aiIndent[] */
2577
drhf1949b62018-06-07 17:32:59 +00002578 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002579 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2580 "Rewind", 0 };
2581 const char *azGoto[] = { "Goto", 0 };
2582
2583 /* Try to figure out if this is really an EXPLAIN statement. If this
2584 ** cannot be verified, return early. */
2585 if( sqlite3_column_count(pSql)!=8 ){
2586 p->cMode = p->mode;
2587 return;
2588 }
2589 zSql = sqlite3_sql(pSql);
2590 if( zSql==0 ) return;
2591 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2592 if( sqlite3_strnicmp(z, "explain", 7) ){
2593 p->cMode = p->mode;
2594 return;
2595 }
2596
2597 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2598 int i;
2599 int iAddr = sqlite3_column_int(pSql, 0);
2600 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2601
2602 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2603 ** p2 is an instruction address, set variable p2op to the index of that
2604 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2605 ** the current instruction is part of a sub-program generated by an
2606 ** SQL trigger or foreign key. */
2607 int p2 = sqlite3_column_int(pSql, 3);
2608 int p2op = (p2 + (iOp-iAddr));
2609
2610 /* Grow the p->aiIndent array as required */
2611 if( iOp>=nAlloc ){
2612 if( iOp==0 ){
2613 /* Do further verfication that this is explain output. Abort if
2614 ** it is not */
2615 static const char *explainCols[] = {
2616 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2617 int jj;
2618 for(jj=0; jj<ArraySize(explainCols); jj++){
2619 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2620 p->cMode = p->mode;
2621 sqlite3_reset(pSql);
2622 return;
2623 }
2624 }
2625 }
2626 nAlloc += 100;
2627 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2628 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2629 }
2630 abYield[iOp] = str_in_array(zOp, azYield);
2631 p->aiIndent[iOp] = 0;
2632 p->nIndent = iOp+1;
2633
2634 if( str_in_array(zOp, azNext) ){
2635 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2636 }
2637 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2638 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2639 ){
2640 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2641 }
2642 }
2643
2644 p->iIndent = 0;
2645 sqlite3_free(abYield);
2646 sqlite3_reset(pSql);
2647}
2648
2649/*
2650** Free the array allocated by explain_data_prepare().
2651*/
2652static void explain_data_delete(ShellState *p){
2653 sqlite3_free(p->aiIndent);
2654 p->aiIndent = 0;
2655 p->nIndent = 0;
2656 p->iIndent = 0;
2657}
2658
2659/*
2660** Disable and restore .wheretrace and .selecttrace settings.
2661*/
2662#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2663extern int sqlite3SelectTrace;
2664static int savedSelectTrace;
2665#endif
2666#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2667extern int sqlite3WhereTrace;
2668static int savedWhereTrace;
2669#endif
2670static void disable_debug_trace_modes(void){
2671#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2672 savedSelectTrace = sqlite3SelectTrace;
2673 sqlite3SelectTrace = 0;
2674#endif
2675#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2676 savedWhereTrace = sqlite3WhereTrace;
2677 sqlite3WhereTrace = 0;
2678#endif
2679}
2680static void restore_debug_trace_modes(void){
2681#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2682 sqlite3SelectTrace = savedSelectTrace;
2683#endif
2684#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2685 sqlite3WhereTrace = savedWhereTrace;
2686#endif
2687}
2688
2689/*
2690** Run a prepared statement
2691*/
2692static void exec_prepared_stmt(
2693 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002694 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002695){
2696 int rc;
2697
2698 /* perform the first step. this will tell us if we
2699 ** have a result set or not and how wide it is.
2700 */
2701 rc = sqlite3_step(pStmt);
2702 /* if we have a result set... */
2703 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002704 /* allocate space for col name ptr, value ptr, and type */
2705 int nCol = sqlite3_column_count(pStmt);
2706 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2707 if( !pData ){
2708 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002709 }else{
drha10b9992018-03-09 15:24:33 +00002710 char **azCols = (char **)pData; /* Names of result columns */
2711 char **azVals = &azCols[nCol]; /* Results */
2712 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2713 int i, x;
2714 assert(sizeof(int) <= sizeof(char *));
2715 /* save off ptrs to column names */
2716 for(i=0; i<nCol; i++){
2717 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2718 }
drh2ce15c32017-07-11 13:34:40 +00002719 do{
drha10b9992018-03-09 15:24:33 +00002720 /* extract the data and data types */
2721 for(i=0; i<nCol; i++){
2722 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2723 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2724 azVals[i] = "";
2725 }else{
2726 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2727 }
2728 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2729 rc = SQLITE_NOMEM;
2730 break; /* from for */
2731 }
2732 } /* end for */
2733
2734 /* if data and types extracted successfully... */
2735 if( SQLITE_ROW == rc ){
2736 /* call the supplied callback with the result row data */
2737 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2738 rc = SQLITE_ABORT;
2739 }else{
2740 rc = sqlite3_step(pStmt);
2741 }
2742 }
2743 } while( SQLITE_ROW == rc );
2744 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002745 }
2746 }
2747}
2748
dan6b046be2018-01-09 15:25:55 +00002749#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002750/*
dan43efc182017-12-19 17:42:13 +00002751** This function is called to process SQL if the previous shell command
2752** was ".expert". It passes the SQL in the second argument directly to
2753** the sqlite3expert object.
2754**
2755** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2756** code. In this case, (*pzErr) may be set to point to a buffer containing
2757** an English language error message. It is the responsibility of the
2758** caller to eventually free this buffer using sqlite3_free().
2759*/
2760static int expertHandleSQL(
2761 ShellState *pState,
2762 const char *zSql,
2763 char **pzErr
2764){
2765 assert( pState->expert.pExpert );
2766 assert( pzErr==0 || *pzErr==0 );
2767 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2768}
2769
2770/*
2771** This function is called either to silently clean up the object
2772** created by the ".expert" command (if bCancel==1), or to generate a
2773** report from it and then clean it up (if bCancel==0).
2774**
2775** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2776** code. In this case, (*pzErr) may be set to point to a buffer containing
2777** an English language error message. It is the responsibility of the
2778** caller to eventually free this buffer using sqlite3_free().
2779*/
2780static int expertFinish(
2781 ShellState *pState,
2782 int bCancel,
2783 char **pzErr
2784){
2785 int rc = SQLITE_OK;
2786 sqlite3expert *p = pState->expert.pExpert;
2787 assert( p );
2788 assert( bCancel || pzErr==0 || *pzErr==0 );
2789 if( bCancel==0 ){
2790 FILE *out = pState->out;
2791 int bVerbose = pState->expert.bVerbose;
2792
2793 rc = sqlite3_expert_analyze(p, pzErr);
2794 if( rc==SQLITE_OK ){
2795 int nQuery = sqlite3_expert_count(p);
2796 int i;
2797
2798 if( bVerbose ){
2799 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2800 raw_printf(out, "-- Candidates -----------------------------\n");
2801 raw_printf(out, "%s\n", zCand);
2802 }
2803 for(i=0; i<nQuery; i++){
2804 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2805 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2806 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2807 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2808 if( bVerbose ){
2809 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2810 raw_printf(out, "%s\n\n", zSql);
2811 }
2812 raw_printf(out, "%s\n", zIdx);
2813 raw_printf(out, "%s\n", zEQP);
2814 }
2815 }
2816 }
2817 sqlite3_expert_destroy(p);
2818 pState->expert.pExpert = 0;
2819 return rc;
2820}
2821
dan6b046be2018-01-09 15:25:55 +00002822/*
2823** Implementation of ".expert" dot command.
2824*/
2825static int expertDotCommand(
2826 ShellState *pState, /* Current shell tool state */
2827 char **azArg, /* Array of arguments passed to dot command */
2828 int nArg /* Number of entries in azArg[] */
2829){
2830 int rc = SQLITE_OK;
2831 char *zErr = 0;
2832 int i;
2833 int iSample = 0;
2834
2835 assert( pState->expert.pExpert==0 );
2836 memset(&pState->expert, 0, sizeof(ExpertInfo));
2837
2838 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2839 char *z = azArg[i];
2840 int n;
2841 if( z[0]=='-' && z[1]=='-' ) z++;
2842 n = strlen30(z);
2843 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2844 pState->expert.bVerbose = 1;
2845 }
2846 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2847 if( i==(nArg-1) ){
2848 raw_printf(stderr, "option requires an argument: %s\n", z);
2849 rc = SQLITE_ERROR;
2850 }else{
2851 iSample = (int)integerValue(azArg[++i]);
2852 if( iSample<0 || iSample>100 ){
2853 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2854 rc = SQLITE_ERROR;
2855 }
2856 }
2857 }
2858 else{
2859 raw_printf(stderr, "unknown option: %s\n", z);
2860 rc = SQLITE_ERROR;
2861 }
2862 }
2863
2864 if( rc==SQLITE_OK ){
2865 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2866 if( pState->expert.pExpert==0 ){
2867 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2868 rc = SQLITE_ERROR;
2869 }else{
2870 sqlite3_expert_config(
2871 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2872 );
2873 }
2874 }
2875
2876 return rc;
2877}
2878#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00002879
2880/*
drh2ce15c32017-07-11 13:34:40 +00002881** Execute a statement or set of statements. Print
2882** any result rows/columns depending on the current mode
2883** set via the supplied callback.
2884**
2885** This is very similar to SQLite's built-in sqlite3_exec()
2886** function except it takes a slightly different callback
2887** and callback data argument.
2888*/
2889static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00002890 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002891 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00002892 char **pzErrMsg /* Error msg written here */
2893){
2894 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2895 int rc = SQLITE_OK; /* Return Code */
2896 int rc2;
2897 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00002898 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00002899
2900 if( pzErrMsg ){
2901 *pzErrMsg = NULL;
2902 }
2903
dan6b046be2018-01-09 15:25:55 +00002904#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00002905 if( pArg->expert.pExpert ){
2906 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2907 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2908 }
dan6b046be2018-01-09 15:25:55 +00002909#endif
dan43efc182017-12-19 17:42:13 +00002910
drh2ce15c32017-07-11 13:34:40 +00002911 while( zSql[0] && (SQLITE_OK == rc) ){
2912 static const char *zStmtSql;
2913 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2914 if( SQLITE_OK != rc ){
2915 if( pzErrMsg ){
2916 *pzErrMsg = save_err_msg(db);
2917 }
2918 }else{
2919 if( !pStmt ){
2920 /* this happens for a comment or white-space */
2921 zSql = zLeftover;
2922 while( IsSpace(zSql[0]) ) zSql++;
2923 continue;
2924 }
2925 zStmtSql = sqlite3_sql(pStmt);
2926 if( zStmtSql==0 ) zStmtSql = "";
2927 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2928
2929 /* save off the prepared statment handle and reset row count */
2930 if( pArg ){
2931 pArg->pStmt = pStmt;
2932 pArg->cnt = 0;
2933 }
2934
2935 /* echo the sql statement if echo on */
2936 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2937 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2938 }
2939
2940 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2941 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2942 sqlite3_stmt *pExplain;
2943 char *zEQP;
drhada70452017-12-21 21:02:27 +00002944 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002945 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002946 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2947 if( pArg->autoEQP>=AUTOEQP_trigger ){
2948 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2949 }
drh2ce15c32017-07-11 13:34:40 +00002950 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2951 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2952 if( rc==SQLITE_OK ){
2953 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00002954 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00002955 int iEqpId = sqlite3_column_int(pExplain, 0);
2956 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00002957 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00002958 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00002959 }
drh4b5345c2018-04-24 13:07:40 +00002960 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00002961 }
2962 sqlite3_finalize(pExplain);
2963 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002964 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002965 /* Also do an EXPLAIN for ".eqp full" mode */
2966 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2967 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2968 if( rc==SQLITE_OK ){
2969 pArg->cMode = MODE_Explain;
2970 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00002971 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00002972 explain_data_delete(pArg);
2973 }
2974 sqlite3_finalize(pExplain);
2975 sqlite3_free(zEQP);
2976 }
drh51efe092018-03-20 12:04:38 +00002977 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
2978 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
2979 /* Reprepare pStmt before reactiving trace modes */
2980 sqlite3_finalize(pStmt);
2981 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00002982 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00002983 }
drh2ce15c32017-07-11 13:34:40 +00002984 restore_debug_trace_modes();
2985 }
2986
2987 if( pArg ){
2988 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00002989 if( pArg->autoExplain ){
2990 if( sqlite3_column_count(pStmt)==8
2991 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2992 ){
2993 pArg->cMode = MODE_Explain;
2994 }
2995 if( sqlite3_column_count(pStmt)==4
2996 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
2997 pArg->cMode = MODE_EQP;
2998 }
drh2ce15c32017-07-11 13:34:40 +00002999 }
3000
3001 /* If the shell is currently in ".explain" mode, gather the extra
3002 ** data required to add indents to the output.*/
3003 if( pArg->cMode==MODE_Explain ){
3004 explain_data_prepare(pArg, pStmt);
3005 }
3006 }
3007
drha10b9992018-03-09 15:24:33 +00003008 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003009 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003010 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003011
3012 /* print usage stats if stats on */
3013 if( pArg && pArg->statsOn ){
3014 display_stats(db, pArg, 0);
3015 }
3016
3017 /* print loop-counters if required */
3018 if( pArg && pArg->scanstatsOn ){
3019 display_scanstats(db, pArg);
3020 }
3021
3022 /* Finalize the statement just executed. If this fails, save a
3023 ** copy of the error message. Otherwise, set zSql to point to the
3024 ** next statement to execute. */
3025 rc2 = sqlite3_finalize(pStmt);
3026 if( rc!=SQLITE_NOMEM ) rc = rc2;
3027 if( rc==SQLITE_OK ){
3028 zSql = zLeftover;
3029 while( IsSpace(zSql[0]) ) zSql++;
3030 }else if( pzErrMsg ){
3031 *pzErrMsg = save_err_msg(db);
3032 }
3033
3034 /* clear saved stmt handle */
3035 if( pArg ){
3036 pArg->pStmt = NULL;
3037 }
3038 }
3039 } /* end while */
3040
3041 return rc;
3042}
3043
3044/*
3045** Release memory previously allocated by tableColumnList().
3046*/
3047static void freeColumnList(char **azCol){
3048 int i;
3049 for(i=1; azCol[i]; i++){
3050 sqlite3_free(azCol[i]);
3051 }
3052 /* azCol[0] is a static string */
3053 sqlite3_free(azCol);
3054}
3055
3056/*
3057** Return a list of pointers to strings which are the names of all
3058** columns in table zTab. The memory to hold the names is dynamically
3059** allocated and must be released by the caller using a subsequent call
3060** to freeColumnList().
3061**
3062** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3063** value that needs to be preserved, then azCol[0] is filled in with the
3064** name of the rowid column.
3065**
3066** The first regular column in the table is azCol[1]. The list is terminated
3067** by an entry with azCol[i]==0.
3068*/
3069static char **tableColumnList(ShellState *p, const char *zTab){
3070 char **azCol = 0;
3071 sqlite3_stmt *pStmt;
3072 char *zSql;
3073 int nCol = 0;
3074 int nAlloc = 0;
3075 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3076 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3077 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3078 int rc;
3079
3080 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3081 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3082 sqlite3_free(zSql);
3083 if( rc ) return 0;
3084 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3085 if( nCol>=nAlloc-2 ){
3086 nAlloc = nAlloc*2 + nCol + 10;
3087 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003088 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003089 }
3090 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3091 if( sqlite3_column_int(pStmt, 5) ){
3092 nPK++;
3093 if( nPK==1
3094 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3095 "INTEGER")==0
3096 ){
3097 isIPK = 1;
3098 }else{
3099 isIPK = 0;
3100 }
3101 }
3102 }
3103 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003104 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003105 azCol[0] = 0;
3106 azCol[nCol+1] = 0;
3107
3108 /* The decision of whether or not a rowid really needs to be preserved
3109 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3110 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3111 ** rowids on tables where the rowid is inaccessible because there are other
3112 ** columns in the table named "rowid", "_rowid_", and "oid".
3113 */
3114 if( preserveRowid && isIPK ){
3115 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3116 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3117 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3118 ** ROWID aliases. To distinguish these cases, check to see if
3119 ** there is a "pk" entry in "PRAGMA index_list". There will be
3120 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3121 */
3122 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3123 " WHERE origin='pk'", zTab);
3124 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3125 sqlite3_free(zSql);
3126 if( rc ){
3127 freeColumnList(azCol);
3128 return 0;
3129 }
3130 rc = sqlite3_step(pStmt);
3131 sqlite3_finalize(pStmt);
3132 preserveRowid = rc==SQLITE_ROW;
3133 }
3134 if( preserveRowid ){
3135 /* Only preserve the rowid if we can find a name to use for the
3136 ** rowid */
3137 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3138 int i, j;
3139 for(j=0; j<3; j++){
3140 for(i=1; i<=nCol; i++){
3141 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3142 }
3143 if( i>nCol ){
3144 /* At this point, we know that azRowid[j] is not the name of any
3145 ** ordinary column in the table. Verify that azRowid[j] is a valid
3146 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3147 ** tables will fail this last check */
3148 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3149 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3150 break;
3151 }
3152 }
3153 }
3154 return azCol;
3155}
3156
3157/*
3158** Toggle the reverse_unordered_selects setting.
3159*/
3160static void toggleSelectOrder(sqlite3 *db){
3161 sqlite3_stmt *pStmt = 0;
3162 int iSetting = 0;
3163 char zStmt[100];
3164 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3165 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3166 iSetting = sqlite3_column_int(pStmt, 0);
3167 }
3168 sqlite3_finalize(pStmt);
3169 sqlite3_snprintf(sizeof(zStmt), zStmt,
3170 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3171 sqlite3_exec(db, zStmt, 0, 0, 0);
3172}
3173
3174/*
3175** This is a different callback routine used for dumping the database.
3176** Each row received by this callback consists of a table name,
3177** the table type ("index" or "table") and SQL to create the table.
3178** This routine should print text sufficient to recreate the table.
3179*/
3180static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3181 int rc;
3182 const char *zTable;
3183 const char *zType;
3184 const char *zSql;
3185 ShellState *p = (ShellState *)pArg;
3186
3187 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003188 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003189 zTable = azArg[0];
3190 zType = azArg[1];
3191 zSql = azArg[2];
3192
3193 if( strcmp(zTable, "sqlite_sequence")==0 ){
3194 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3195 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3196 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3197 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3198 return 0;
3199 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3200 char *zIns;
3201 if( !p->writableSchema ){
3202 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3203 p->writableSchema = 1;
3204 }
3205 zIns = sqlite3_mprintf(
3206 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3207 "VALUES('table','%q','%q',0,'%q');",
3208 zTable, zTable, zSql);
3209 utf8_printf(p->out, "%s\n", zIns);
3210 sqlite3_free(zIns);
3211 return 0;
3212 }else{
3213 printSchemaLine(p->out, zSql, ";\n");
3214 }
3215
3216 if( strcmp(zType, "table")==0 ){
3217 ShellText sSelect;
3218 ShellText sTable;
3219 char **azCol;
3220 int i;
3221 char *savedDestTable;
3222 int savedMode;
3223
3224 azCol = tableColumnList(p, zTable);
3225 if( azCol==0 ){
3226 p->nErr++;
3227 return 0;
3228 }
3229
3230 /* Always quote the table name, even if it appears to be pure ascii,
3231 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3232 initText(&sTable);
3233 appendText(&sTable, zTable, quoteChar(zTable));
3234 /* If preserving the rowid, add a column list after the table name.
3235 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3236 ** instead of the usual "INSERT INTO tab VALUES(...)".
3237 */
3238 if( azCol[0] ){
3239 appendText(&sTable, "(", 0);
3240 appendText(&sTable, azCol[0], 0);
3241 for(i=1; azCol[i]; i++){
3242 appendText(&sTable, ",", 0);
3243 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3244 }
3245 appendText(&sTable, ")", 0);
3246 }
3247
3248 /* Build an appropriate SELECT statement */
3249 initText(&sSelect);
3250 appendText(&sSelect, "SELECT ", 0);
3251 if( azCol[0] ){
3252 appendText(&sSelect, azCol[0], 0);
3253 appendText(&sSelect, ",", 0);
3254 }
3255 for(i=1; azCol[i]; i++){
3256 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3257 if( azCol[i+1] ){
3258 appendText(&sSelect, ",", 0);
3259 }
3260 }
3261 freeColumnList(azCol);
3262 appendText(&sSelect, " FROM ", 0);
3263 appendText(&sSelect, zTable, quoteChar(zTable));
3264
3265 savedDestTable = p->zDestTable;
3266 savedMode = p->mode;
3267 p->zDestTable = sTable.z;
3268 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003269 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003270 if( (rc&0xff)==SQLITE_CORRUPT ){
3271 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3272 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003273 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003274 toggleSelectOrder(p->db);
3275 }
3276 p->zDestTable = savedDestTable;
3277 p->mode = savedMode;
3278 freeText(&sTable);
3279 freeText(&sSelect);
3280 if( rc ) p->nErr++;
3281 }
3282 return 0;
3283}
3284
3285/*
3286** Run zQuery. Use dump_callback() as the callback routine so that
3287** the contents of the query are output as SQL statements.
3288**
3289** If we get a SQLITE_CORRUPT error, rerun the query after appending
3290** "ORDER BY rowid DESC" to the end.
3291*/
3292static int run_schema_dump_query(
3293 ShellState *p,
3294 const char *zQuery
3295){
3296 int rc;
3297 char *zErr = 0;
3298 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3299 if( rc==SQLITE_CORRUPT ){
3300 char *zQ2;
3301 int len = strlen30(zQuery);
3302 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3303 if( zErr ){
3304 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3305 sqlite3_free(zErr);
3306 zErr = 0;
3307 }
3308 zQ2 = malloc( len+100 );
3309 if( zQ2==0 ) return rc;
3310 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3311 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3312 if( rc ){
3313 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3314 }else{
3315 rc = SQLITE_CORRUPT;
3316 }
3317 sqlite3_free(zErr);
3318 free(zQ2);
3319 }
3320 return rc;
3321}
3322
3323/*
3324** Text of a help message
3325*/
3326static char zHelp[] =
drhe37c0e12018-01-06 19:19:50 +00003327#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3328 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3329#endif
drh2ce15c32017-07-11 13:34:40 +00003330#ifndef SQLITE_OMIT_AUTHORIZATION
3331 ".auth ON|OFF Show authorizer callbacks\n"
3332#endif
3333 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drh69ed38a2018-05-14 00:23:08 +00003334 " Add \"--append\" to open using appendvfs.\n"
drh2ce15c32017-07-11 13:34:40 +00003335 ".bail on|off Stop after hitting an error. Default OFF\n"
3336 ".binary on|off Turn binary output on or off. Default OFF\n"
3337 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3338 ".changes on|off Show number of rows changed by SQL\n"
3339 ".check GLOB Fail if output since .testcase does not match\n"
3340 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3341 ".databases List names and files of attached databases\n"
drh7df01192018-04-28 12:43:16 +00003342 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options\n"
drh2ce15c32017-07-11 13:34:40 +00003343 ".dbinfo ?DB? Show status information about the database\n"
3344 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3345 " If TABLE specified, only dump tables matching\n"
3346 " LIKE pattern TABLE.\n"
3347 ".echo on|off Turn command echo on or off\n"
3348 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh13c20932018-01-10 21:41:55 +00003349 ".excel Display the output of next command in a spreadsheet\n"
drh2ce15c32017-07-11 13:34:40 +00003350 ".exit Exit this program\n"
dan2e1ea572017-12-21 18:55:24 +00003351 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
drh2ce15c32017-07-11 13:34:40 +00003352/* Because explain mode comes on automatically now, the ".explain" mode
3353** is removed from the help screen. It is still supported for legacy, however */
3354/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3355 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3356 ".headers on|off Turn display of headers on or off\n"
3357 ".help Show this message\n"
3358 ".import FILE TABLE Import data from FILE into TABLE\n"
3359#ifndef SQLITE_OMIT_TEST_CONTROL
3360 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3361#endif
3362 ".indexes ?TABLE? Show names of all indexes\n"
3363 " If TABLE specified, only show indexes for tables\n"
3364 " matching LIKE pattern TABLE.\n"
3365#ifdef SQLITE_ENABLE_IOTRACE
3366 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3367#endif
3368 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3369 ".lint OPTIONS Report potential schema issues. Options:\n"
3370 " fkey-indexes Find missing foreign key indexes\n"
3371#ifndef SQLITE_OMIT_LOAD_EXTENSION
3372 ".load FILE ?ENTRY? Load an extension library\n"
3373#endif
3374 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3375 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3376 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3377 " csv Comma-separated values\n"
3378 " column Left-aligned columns. (See .width)\n"
3379 " html HTML <table> code\n"
3380 " insert SQL insert statements for TABLE\n"
3381 " line One value per line\n"
3382 " list Values delimited by \"|\"\n"
3383 " quote Escape answers as for SQL\n"
3384 " tabs Tab-separated values\n"
3385 " tcl TCL list elements\n"
3386 ".nullvalue STRING Use STRING in place of NULL values\n"
drh536c3452018-01-11 00:38:39 +00003387 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
3388 " or invoke system text editor (-e) or spreadsheet (-x)\n"
3389 " on the output.\n"
drh2ce15c32017-07-11 13:34:40 +00003390 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3391 " The --new option starts with an empty file\n"
drhee269a62018-02-14 23:27:43 +00003392 " Other options: --readonly --append --zip\n"
drh536c3452018-01-11 00:38:39 +00003393 ".output ?FILE? Send output to FILE or stdout\n"
drh2ce15c32017-07-11 13:34:40 +00003394 ".print STRING... Print literal STRING\n"
3395 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3396 ".quit Exit this program\n"
3397 ".read FILENAME Execute SQL in FILENAME\n"
3398 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3399 ".save FILE Write in-memory database into FILE\n"
3400 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3401 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3402 " Add --indent for pretty-printing\n"
3403 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3404 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3405 " separator for both the output mode and .import\n"
3406#if defined(SQLITE_ENABLE_SESSION)
3407 ".session CMD ... Create or control sessions\n"
3408#endif
3409 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh04a28c32018-01-31 01:38:44 +00003410#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00003411 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drh04a28c32018-01-31 01:38:44 +00003412#endif
drh2ce15c32017-07-11 13:34:40 +00003413 ".show Show the current values for various settings\n"
3414 ".stats ?on|off? Show stats or turn stats on or off\n"
drh04a28c32018-01-31 01:38:44 +00003415#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00003416 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
drh04a28c32018-01-31 01:38:44 +00003417#endif
drh2ce15c32017-07-11 13:34:40 +00003418 ".tables ?TABLE? List names of tables\n"
3419 " If TABLE specified, only list tables matching\n"
3420 " LIKE pattern TABLE.\n"
3421 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3422 ".timeout MS Try opening locked tables for MS milliseconds\n"
3423 ".timer on|off Turn SQL timer on or off\n"
3424 ".trace FILE|off Output each SQL statement as it is run\n"
3425 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3426 ".vfslist List all available VFSes\n"
3427 ".vfsname ?AUX? Print the name of the VFS stack\n"
3428 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3429 " Negative values right-justify\n"
3430;
3431
3432#if defined(SQLITE_ENABLE_SESSION)
3433/*
3434** Print help information for the ".sessions" command
3435*/
3436void session_help(ShellState *p){
3437 raw_printf(p->out,
3438 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3439 "If ?NAME? is omitted, the first defined session is used.\n"
3440 "Subcommands:\n"
3441 " attach TABLE Attach TABLE\n"
3442 " changeset FILE Write a changeset into FILE\n"
3443 " close Close one session\n"
3444 " enable ?BOOLEAN? Set or query the enable bit\n"
3445 " filter GLOB... Reject tables matching GLOBs\n"
3446 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3447 " isempty Query whether the session is empty\n"
3448 " list List currently open session names\n"
3449 " open DB NAME Open a new session on DB\n"
3450 " patchset FILE Write a patchset into FILE\n"
3451 );
3452}
3453#endif
3454
3455
3456/* Forward reference */
3457static int process_input(ShellState *p, FILE *in);
3458
3459/*
3460** Read the content of file zName into memory obtained from sqlite3_malloc64()
3461** and return a pointer to the buffer. The caller is responsible for freeing
3462** the memory.
3463**
3464** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3465** read.
3466**
3467** For convenience, a nul-terminator byte is always appended to the data read
3468** from the file before the buffer is returned. This byte is not included in
3469** the final value of (*pnByte), if applicable.
3470**
3471** NULL is returned if any error is encountered. The final value of *pnByte
3472** is undefined in this case.
3473*/
3474static char *readFile(const char *zName, int *pnByte){
3475 FILE *in = fopen(zName, "rb");
3476 long nIn;
3477 size_t nRead;
3478 char *pBuf;
3479 if( in==0 ) return 0;
3480 fseek(in, 0, SEEK_END);
3481 nIn = ftell(in);
3482 rewind(in);
3483 pBuf = sqlite3_malloc64( nIn+1 );
3484 if( pBuf==0 ) return 0;
3485 nRead = fread(pBuf, nIn, 1, in);
3486 fclose(in);
3487 if( nRead!=1 ){
3488 sqlite3_free(pBuf);
3489 return 0;
3490 }
3491 pBuf[nIn] = 0;
3492 if( pnByte ) *pnByte = nIn;
3493 return pBuf;
3494}
3495
3496#if defined(SQLITE_ENABLE_SESSION)
3497/*
3498** Close a single OpenSession object and release all of its associated
3499** resources.
3500*/
3501static void session_close(OpenSession *pSession){
3502 int i;
3503 sqlite3session_delete(pSession->p);
3504 sqlite3_free(pSession->zName);
3505 for(i=0; i<pSession->nFilter; i++){
3506 sqlite3_free(pSession->azFilter[i]);
3507 }
3508 sqlite3_free(pSession->azFilter);
3509 memset(pSession, 0, sizeof(OpenSession));
3510}
3511#endif
3512
3513/*
3514** Close all OpenSession objects and release all associated resources.
3515*/
3516#if defined(SQLITE_ENABLE_SESSION)
3517static void session_close_all(ShellState *p){
3518 int i;
3519 for(i=0; i<p->nSession; i++){
3520 session_close(&p->aSession[i]);
3521 }
3522 p->nSession = 0;
3523}
3524#else
3525# define session_close_all(X)
3526#endif
3527
3528/*
3529** Implementation of the xFilter function for an open session. Omit
3530** any tables named by ".session filter" but let all other table through.
3531*/
3532#if defined(SQLITE_ENABLE_SESSION)
3533static int session_filter(void *pCtx, const char *zTab){
3534 OpenSession *pSession = (OpenSession*)pCtx;
3535 int i;
3536 for(i=0; i<pSession->nFilter; i++){
3537 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3538 }
3539 return 1;
3540}
3541#endif
3542
3543/*
drh1fa6d9f2018-01-06 21:46:01 +00003544** Try to deduce the type of file for zName based on its content. Return
3545** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003546**
3547** If the file does not exist or is empty but its name looks like a ZIP
3548** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3549** Otherwise, assume an ordinary database regardless of the filename if
3550** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003551*/
drhfc97c1c2018-05-14 00:41:12 +00003552int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003553 FILE *f = fopen(zName, "rb");
3554 size_t n;
3555 int rc = SHELL_OPEN_UNSPEC;
3556 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003557 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003558 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3559 return SHELL_OPEN_ZIPFILE;
3560 }else{
3561 return SHELL_OPEN_NORMAL;
3562 }
drh1bf208c2018-03-09 21:54:01 +00003563 }
drh1fa6d9f2018-01-06 21:46:01 +00003564 fseek(f, -25, SEEK_END);
3565 n = fread(zBuf, 25, 1, f);
3566 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3567 rc = SHELL_OPEN_APPENDVFS;
3568 }else{
3569 fseek(f, -22, SEEK_END);
3570 n = fread(zBuf, 22, 1, f);
3571 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3572 && zBuf[3]==0x06 ){
3573 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003574 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003575 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003576 }
3577 }
3578 fclose(f);
3579 return rc;
3580}
3581
drhbe4ccb22018-05-17 20:04:24 +00003582/* Flags for open_db().
3583**
3584** The default behavior of open_db() is to exit(1) if the database fails to
3585** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3586** but still returns without calling exit.
3587**
3588** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3589** ZIP archive if the file does not exist or is empty and its name matches
3590** the *.zip pattern.
3591*/
3592#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3593#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3594
drh1fa6d9f2018-01-06 21:46:01 +00003595/*
drh2ce15c32017-07-11 13:34:40 +00003596** Make sure the database is open. If it is not, then open it. If
3597** the database fails to open, print an error message and exit.
3598*/
drhbe4ccb22018-05-17 20:04:24 +00003599static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00003600 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00003601 if( p->openMode==SHELL_OPEN_UNSPEC ){
3602 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3603 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00003604 }else{
3605 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3606 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00003607 }
drh1fa6d9f2018-01-06 21:46:01 +00003608 }
3609 switch( p->openMode ){
3610 case SHELL_OPEN_APPENDVFS: {
3611 sqlite3_open_v2(p->zDbFilename, &p->db,
3612 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3613 break;
3614 }
3615 case SHELL_OPEN_ZIPFILE: {
3616 sqlite3_open(":memory:", &p->db);
3617 break;
3618 }
drhee269a62018-02-14 23:27:43 +00003619 case SHELL_OPEN_READONLY: {
3620 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3621 break;
3622 }
drh1fa6d9f2018-01-06 21:46:01 +00003623 case SHELL_OPEN_UNSPEC:
3624 case SHELL_OPEN_NORMAL: {
3625 sqlite3_open(p->zDbFilename, &p->db);
3626 break;
3627 }
3628 }
drh2ce15c32017-07-11 13:34:40 +00003629 globalDb = p->db;
3630 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3631 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3632 p->zDbFilename, sqlite3_errmsg(p->db));
drhbe4ccb22018-05-17 20:04:24 +00003633 if( openFlags & OPEN_DB_KEEPALIVE ) return;
drh2ce15c32017-07-11 13:34:40 +00003634 exit(1);
3635 }
3636#ifndef SQLITE_OMIT_LOAD_EXTENSION
3637 sqlite3_enable_load_extension(p->db, 1);
3638#endif
3639 sqlite3_fileio_init(p->db, 0, 0);
3640 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003641 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003642#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003643 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003644 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003645#endif
drhceba7922018-01-01 21:28:25 +00003646 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003647 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003648 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3649 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00003650 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3651 shellPutsFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003652#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00003653 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3654 editFunc, 0, 0);
3655 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3656 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003657#endif
drh1fa6d9f2018-01-06 21:46:01 +00003658 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3659 char *zSql = sqlite3_mprintf(
3660 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3661 sqlite3_exec(p->db, zSql, 0, 0, 0);
3662 sqlite3_free(zSql);
3663 }
drh2ce15c32017-07-11 13:34:40 +00003664 }
3665}
3666
drh9e804032018-05-18 17:11:50 +00003667/*
3668** Attempt to close the databaes connection. Report errors.
3669*/
3670void close_db(sqlite3 *db){
3671 int rc = sqlite3_close(db);
3672 if( rc ){
3673 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
3674 rc, sqlite3_errmsg(db));
3675 }
3676}
3677
drh56eb09b2017-07-11 13:59:07 +00003678#if HAVE_READLINE || HAVE_EDITLINE
3679/*
3680** Readline completion callbacks
3681*/
3682static char *readline_completion_generator(const char *text, int state){
3683 static sqlite3_stmt *pStmt = 0;
3684 char *zRet;
3685 if( state==0 ){
3686 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003687 sqlite3_finalize(pStmt);
3688 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3689 " FROM completion(%Q) ORDER BY 1", text);
3690 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3691 sqlite3_free(zSql);
3692 }
3693 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003694 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003695 }else{
3696 sqlite3_finalize(pStmt);
3697 pStmt = 0;
3698 zRet = 0;
3699 }
3700 return zRet;
3701}
3702static char **readline_completion(const char *zText, int iStart, int iEnd){
3703 rl_attempted_completion_over = 1;
3704 return rl_completion_matches(zText, readline_completion_generator);
3705}
3706
3707#elif HAVE_LINENOISE
3708/*
3709** Linenoise completion callback
3710*/
3711static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003712 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003713 int i, iStart;
3714 sqlite3_stmt *pStmt = 0;
3715 char *zSql;
3716 char zBuf[1000];
3717
3718 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00003719 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00003720 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3721 if( i==nLine-1 ) return;
3722 iStart = i+1;
3723 memcpy(zBuf, zLine, iStart);
3724 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3725 " FROM completion(%Q,%Q) ORDER BY 1",
3726 &zLine[iStart], zLine);
3727 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3728 sqlite3_free(zSql);
3729 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3730 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3731 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3732 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3733 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3734 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3735 linenoiseAddCompletion(lc, zBuf);
3736 }
3737 }
3738 sqlite3_finalize(pStmt);
3739}
3740#endif
3741
drh2ce15c32017-07-11 13:34:40 +00003742/*
3743** Do C-language style dequoting.
3744**
3745** \a -> alarm
3746** \b -> backspace
3747** \t -> tab
3748** \n -> newline
3749** \v -> vertical tab
3750** \f -> form feed
3751** \r -> carriage return
3752** \s -> space
3753** \" -> "
3754** \' -> '
3755** \\ -> backslash
3756** \NNN -> ascii character NNN in octal
3757*/
3758static void resolve_backslashes(char *z){
3759 int i, j;
3760 char c;
3761 while( *z && *z!='\\' ) z++;
3762 for(i=j=0; (c = z[i])!=0; i++, j++){
3763 if( c=='\\' && z[i+1]!=0 ){
3764 c = z[++i];
3765 if( c=='a' ){
3766 c = '\a';
3767 }else if( c=='b' ){
3768 c = '\b';
3769 }else if( c=='t' ){
3770 c = '\t';
3771 }else if( c=='n' ){
3772 c = '\n';
3773 }else if( c=='v' ){
3774 c = '\v';
3775 }else if( c=='f' ){
3776 c = '\f';
3777 }else if( c=='r' ){
3778 c = '\r';
3779 }else if( c=='"' ){
3780 c = '"';
3781 }else if( c=='\'' ){
3782 c = '\'';
3783 }else if( c=='\\' ){
3784 c = '\\';
3785 }else if( c>='0' && c<='7' ){
3786 c -= '0';
3787 if( z[i+1]>='0' && z[i+1]<='7' ){
3788 i++;
3789 c = (c<<3) + z[i] - '0';
3790 if( z[i+1]>='0' && z[i+1]<='7' ){
3791 i++;
3792 c = (c<<3) + z[i] - '0';
3793 }
3794 }
3795 }
3796 }
3797 z[j] = c;
3798 }
3799 if( j<i ) z[j] = 0;
3800}
3801
3802/*
drh2ce15c32017-07-11 13:34:40 +00003803** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3804** for TRUE and FALSE. Return the integer value if appropriate.
3805*/
3806static int booleanValue(const char *zArg){
3807 int i;
3808 if( zArg[0]=='0' && zArg[1]=='x' ){
3809 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3810 }else{
3811 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3812 }
3813 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3814 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3815 return 1;
3816 }
3817 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3818 return 0;
3819 }
3820 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3821 zArg);
3822 return 0;
3823}
3824
3825/*
3826** Set or clear a shell flag according to a boolean value.
3827*/
3828static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3829 if( booleanValue(zArg) ){
3830 ShellSetFlag(p, mFlag);
3831 }else{
3832 ShellClearFlag(p, mFlag);
3833 }
3834}
3835
3836/*
3837** Close an output file, assuming it is not stderr or stdout
3838*/
3839static void output_file_close(FILE *f){
3840 if( f && f!=stdout && f!=stderr ) fclose(f);
3841}
3842
3843/*
3844** Try to open an output file. The names "stdout" and "stderr" are
3845** recognized and do the right thing. NULL is returned if the output
3846** filename is "off".
3847*/
drha92a01a2018-01-10 22:15:37 +00003848static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00003849 FILE *f;
3850 if( strcmp(zFile,"stdout")==0 ){
3851 f = stdout;
3852 }else if( strcmp(zFile, "stderr")==0 ){
3853 f = stderr;
3854 }else if( strcmp(zFile, "off")==0 ){
3855 f = 0;
3856 }else{
drha92a01a2018-01-10 22:15:37 +00003857 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00003858 if( f==0 ){
3859 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3860 }
3861 }
3862 return f;
3863}
3864
drh2ce15c32017-07-11 13:34:40 +00003865#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3866/*
3867** A routine for handling output from sqlite3_trace().
3868*/
3869static int sql_trace_callback(
3870 unsigned mType,
3871 void *pArg,
3872 void *pP,
3873 void *pX
3874){
3875 FILE *f = (FILE*)pArg;
3876 UNUSED_PARAMETER(mType);
3877 UNUSED_PARAMETER(pP);
3878 if( f ){
3879 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00003880 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00003881 while( i>0 && z[i-1]==';' ){ i--; }
3882 utf8_printf(f, "%.*s;\n", i, z);
3883 }
3884 return 0;
3885}
3886#endif
drh2ce15c32017-07-11 13:34:40 +00003887
3888/*
3889** A no-op routine that runs with the ".breakpoint" doc-command. This is
3890** a useful spot to set a debugger breakpoint.
3891*/
3892static void test_breakpoint(void){
3893 static int nCall = 0;
3894 nCall++;
3895}
3896
3897/*
3898** An object used to read a CSV and other files for import.
3899*/
3900typedef struct ImportCtx ImportCtx;
3901struct ImportCtx {
3902 const char *zFile; /* Name of the input file */
3903 FILE *in; /* Read the CSV text from this input stream */
3904 char *z; /* Accumulated text for a field */
3905 int n; /* Number of bytes in z */
3906 int nAlloc; /* Space allocated for z[] */
3907 int nLine; /* Current line number */
3908 int bNotFirst; /* True if one or more bytes already read */
3909 int cTerm; /* Character that terminated the most recent field */
3910 int cColSep; /* The column separator character. (Usually ",") */
3911 int cRowSep; /* The row separator character. (Usually "\n") */
3912};
3913
3914/* Append a single byte to z[] */
3915static void import_append_char(ImportCtx *p, int c){
3916 if( p->n+1>=p->nAlloc ){
3917 p->nAlloc += p->nAlloc + 100;
3918 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00003919 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003920 }
3921 p->z[p->n++] = (char)c;
3922}
3923
3924/* Read a single field of CSV text. Compatible with rfc4180 and extended
3925** with the option of having a separator other than ",".
3926**
3927** + Input comes from p->in.
3928** + Store results in p->z of length p->n. Space to hold p->z comes
3929** from sqlite3_malloc64().
3930** + Use p->cSep as the column separator. The default is ",".
3931** + Use p->rSep as the row separator. The default is "\n".
3932** + Keep track of the line number in p->nLine.
3933** + Store the character that terminates the field in p->cTerm. Store
3934** EOF on end-of-file.
3935** + Report syntax errors on stderr
3936*/
3937static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3938 int c;
3939 int cSep = p->cColSep;
3940 int rSep = p->cRowSep;
3941 p->n = 0;
3942 c = fgetc(p->in);
3943 if( c==EOF || seenInterrupt ){
3944 p->cTerm = EOF;
3945 return 0;
3946 }
3947 if( c=='"' ){
3948 int pc, ppc;
3949 int startLine = p->nLine;
3950 int cQuote = c;
3951 pc = ppc = 0;
3952 while( 1 ){
3953 c = fgetc(p->in);
3954 if( c==rSep ) p->nLine++;
3955 if( c==cQuote ){
3956 if( pc==cQuote ){
3957 pc = 0;
3958 continue;
3959 }
3960 }
3961 if( (c==cSep && pc==cQuote)
3962 || (c==rSep && pc==cQuote)
3963 || (c==rSep && pc=='\r' && ppc==cQuote)
3964 || (c==EOF && pc==cQuote)
3965 ){
3966 do{ p->n--; }while( p->z[p->n]!=cQuote );
3967 p->cTerm = c;
3968 break;
3969 }
3970 if( pc==cQuote && c!='\r' ){
3971 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3972 p->zFile, p->nLine, cQuote);
3973 }
3974 if( c==EOF ){
3975 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3976 p->zFile, startLine, cQuote);
3977 p->cTerm = c;
3978 break;
3979 }
3980 import_append_char(p, c);
3981 ppc = pc;
3982 pc = c;
3983 }
3984 }else{
3985 /* If this is the first field being parsed and it begins with the
3986 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3987 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3988 import_append_char(p, c);
3989 c = fgetc(p->in);
3990 if( (c&0xff)==0xbb ){
3991 import_append_char(p, c);
3992 c = fgetc(p->in);
3993 if( (c&0xff)==0xbf ){
3994 p->bNotFirst = 1;
3995 p->n = 0;
3996 return csv_read_one_field(p);
3997 }
3998 }
3999 }
4000 while( c!=EOF && c!=cSep && c!=rSep ){
4001 import_append_char(p, c);
4002 c = fgetc(p->in);
4003 }
4004 if( c==rSep ){
4005 p->nLine++;
4006 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4007 }
4008 p->cTerm = c;
4009 }
4010 if( p->z ) p->z[p->n] = 0;
4011 p->bNotFirst = 1;
4012 return p->z;
4013}
4014
4015/* Read a single field of ASCII delimited text.
4016**
4017** + Input comes from p->in.
4018** + Store results in p->z of length p->n. Space to hold p->z comes
4019** from sqlite3_malloc64().
4020** + Use p->cSep as the column separator. The default is "\x1F".
4021** + Use p->rSep as the row separator. The default is "\x1E".
4022** + Keep track of the row number in p->nLine.
4023** + Store the character that terminates the field in p->cTerm. Store
4024** EOF on end-of-file.
4025** + Report syntax errors on stderr
4026*/
4027static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4028 int c;
4029 int cSep = p->cColSep;
4030 int rSep = p->cRowSep;
4031 p->n = 0;
4032 c = fgetc(p->in);
4033 if( c==EOF || seenInterrupt ){
4034 p->cTerm = EOF;
4035 return 0;
4036 }
4037 while( c!=EOF && c!=cSep && c!=rSep ){
4038 import_append_char(p, c);
4039 c = fgetc(p->in);
4040 }
4041 if( c==rSep ){
4042 p->nLine++;
4043 }
4044 p->cTerm = c;
4045 if( p->z ) p->z[p->n] = 0;
4046 return p->z;
4047}
4048
4049/*
4050** Try to transfer data for table zTable. If an error is seen while
4051** moving forward, try to go backwards. The backwards movement won't
4052** work for WITHOUT ROWID tables.
4053*/
4054static void tryToCloneData(
4055 ShellState *p,
4056 sqlite3 *newDb,
4057 const char *zTable
4058){
4059 sqlite3_stmt *pQuery = 0;
4060 sqlite3_stmt *pInsert = 0;
4061 char *zQuery = 0;
4062 char *zInsert = 0;
4063 int rc;
4064 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004065 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004066 int k = 0;
4067 int cnt = 0;
4068 const int spinRate = 10000;
4069
4070 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4071 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4072 if( rc ){
4073 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4074 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4075 zQuery);
4076 goto end_data_xfer;
4077 }
4078 n = sqlite3_column_count(pQuery);
4079 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004080 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004081 sqlite3_snprintf(200+nTable,zInsert,
4082 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004083 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004084 for(j=1; j<n; j++){
4085 memcpy(zInsert+i, ",?", 2);
4086 i += 2;
4087 }
4088 memcpy(zInsert+i, ");", 3);
4089 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4090 if( rc ){
4091 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4092 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4093 zQuery);
4094 goto end_data_xfer;
4095 }
4096 for(k=0; k<2; k++){
4097 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4098 for(i=0; i<n; i++){
4099 switch( sqlite3_column_type(pQuery, i) ){
4100 case SQLITE_NULL: {
4101 sqlite3_bind_null(pInsert, i+1);
4102 break;
4103 }
4104 case SQLITE_INTEGER: {
4105 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4106 break;
4107 }
4108 case SQLITE_FLOAT: {
4109 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4110 break;
4111 }
4112 case SQLITE_TEXT: {
4113 sqlite3_bind_text(pInsert, i+1,
4114 (const char*)sqlite3_column_text(pQuery,i),
4115 -1, SQLITE_STATIC);
4116 break;
4117 }
4118 case SQLITE_BLOB: {
4119 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4120 sqlite3_column_bytes(pQuery,i),
4121 SQLITE_STATIC);
4122 break;
4123 }
4124 }
4125 } /* End for */
4126 rc = sqlite3_step(pInsert);
4127 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4128 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4129 sqlite3_errmsg(newDb));
4130 }
4131 sqlite3_reset(pInsert);
4132 cnt++;
4133 if( (cnt%spinRate)==0 ){
4134 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4135 fflush(stdout);
4136 }
4137 } /* End while */
4138 if( rc==SQLITE_DONE ) break;
4139 sqlite3_finalize(pQuery);
4140 sqlite3_free(zQuery);
4141 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4142 zTable);
4143 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4144 if( rc ){
4145 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4146 break;
4147 }
4148 } /* End for(k=0...) */
4149
4150end_data_xfer:
4151 sqlite3_finalize(pQuery);
4152 sqlite3_finalize(pInsert);
4153 sqlite3_free(zQuery);
4154 sqlite3_free(zInsert);
4155}
4156
4157
4158/*
4159** Try to transfer all rows of the schema that match zWhere. For
4160** each row, invoke xForEach() on the object defined by that row.
4161** If an error is encountered while moving forward through the
4162** sqlite_master table, try again moving backwards.
4163*/
4164static void tryToCloneSchema(
4165 ShellState *p,
4166 sqlite3 *newDb,
4167 const char *zWhere,
4168 void (*xForEach)(ShellState*,sqlite3*,const char*)
4169){
4170 sqlite3_stmt *pQuery = 0;
4171 char *zQuery = 0;
4172 int rc;
4173 const unsigned char *zName;
4174 const unsigned char *zSql;
4175 char *zErrMsg = 0;
4176
4177 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4178 " WHERE %s", zWhere);
4179 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4180 if( rc ){
4181 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4182 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4183 zQuery);
4184 goto end_schema_xfer;
4185 }
4186 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4187 zName = sqlite3_column_text(pQuery, 0);
4188 zSql = sqlite3_column_text(pQuery, 1);
4189 printf("%s... ", zName); fflush(stdout);
4190 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4191 if( zErrMsg ){
4192 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4193 sqlite3_free(zErrMsg);
4194 zErrMsg = 0;
4195 }
4196 if( xForEach ){
4197 xForEach(p, newDb, (const char*)zName);
4198 }
4199 printf("done\n");
4200 }
4201 if( rc!=SQLITE_DONE ){
4202 sqlite3_finalize(pQuery);
4203 sqlite3_free(zQuery);
4204 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4205 " WHERE %s ORDER BY rowid DESC", zWhere);
4206 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4207 if( rc ){
4208 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4209 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4210 zQuery);
4211 goto end_schema_xfer;
4212 }
4213 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4214 zName = sqlite3_column_text(pQuery, 0);
4215 zSql = sqlite3_column_text(pQuery, 1);
4216 printf("%s... ", zName); fflush(stdout);
4217 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4218 if( zErrMsg ){
4219 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4220 sqlite3_free(zErrMsg);
4221 zErrMsg = 0;
4222 }
4223 if( xForEach ){
4224 xForEach(p, newDb, (const char*)zName);
4225 }
4226 printf("done\n");
4227 }
4228 }
4229end_schema_xfer:
4230 sqlite3_finalize(pQuery);
4231 sqlite3_free(zQuery);
4232}
4233
4234/*
4235** Open a new database file named "zNewDb". Try to recover as much information
4236** as possible out of the main database (which might be corrupt) and write it
4237** into zNewDb.
4238*/
4239static void tryToClone(ShellState *p, const char *zNewDb){
4240 int rc;
4241 sqlite3 *newDb = 0;
4242 if( access(zNewDb,0)==0 ){
4243 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4244 return;
4245 }
4246 rc = sqlite3_open(zNewDb, &newDb);
4247 if( rc ){
4248 utf8_printf(stderr, "Cannot create output database: %s\n",
4249 sqlite3_errmsg(newDb));
4250 }else{
4251 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4252 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4253 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4254 tryToCloneSchema(p, newDb, "type!='table'", 0);
4255 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4256 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4257 }
drh9e804032018-05-18 17:11:50 +00004258 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004259}
4260
4261/*
drh13c20932018-01-10 21:41:55 +00004262** Change the output file back to stdout.
4263**
4264** If the p->doXdgOpen flag is set, that means the output was being
4265** redirected to a temporary file named by p->zTempFile. In that case,
4266** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004267*/
4268static void output_reset(ShellState *p){
4269 if( p->outfile[0]=='|' ){
4270#ifndef SQLITE_OMIT_POPEN
4271 pclose(p->out);
4272#endif
4273 }else{
4274 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004275#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004276 if( p->doXdgOpen ){
4277 const char *zXdgOpenCmd =
4278#if defined(_WIN32)
4279 "start";
4280#elif defined(__APPLE__)
4281 "open";
4282#else
4283 "xdg-open";
4284#endif
4285 char *zCmd;
4286 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004287 if( system(zCmd) ){
4288 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4289 }
drh13c20932018-01-10 21:41:55 +00004290 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004291 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004292 p->doXdgOpen = 0;
4293 }
drh04a28c32018-01-31 01:38:44 +00004294#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004295 }
4296 p->outfile[0] = 0;
4297 p->out = stdout;
4298}
4299
4300/*
4301** Run an SQL command and return the single integer result.
4302*/
4303static int db_int(ShellState *p, const char *zSql){
4304 sqlite3_stmt *pStmt;
4305 int res = 0;
4306 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4307 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4308 res = sqlite3_column_int(pStmt,0);
4309 }
4310 sqlite3_finalize(pStmt);
4311 return res;
4312}
4313
4314/*
4315** Convert a 2-byte or 4-byte big-endian integer into a native integer
4316*/
4317static unsigned int get2byteInt(unsigned char *a){
4318 return (a[0]<<8) + a[1];
4319}
4320static unsigned int get4byteInt(unsigned char *a){
4321 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4322}
4323
4324/*
4325** Implementation of the ".info" command.
4326**
4327** Return 1 on error, 2 to exit, and 0 otherwise.
4328*/
4329static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4330 static const struct { const char *zName; int ofst; } aField[] = {
4331 { "file change counter:", 24 },
4332 { "database page count:", 28 },
4333 { "freelist page count:", 36 },
4334 { "schema cookie:", 40 },
4335 { "schema format:", 44 },
4336 { "default cache size:", 48 },
4337 { "autovacuum top root:", 52 },
4338 { "incremental vacuum:", 64 },
4339 { "text encoding:", 56 },
4340 { "user version:", 60 },
4341 { "application id:", 68 },
4342 { "software version:", 96 },
4343 };
4344 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4345 { "number of tables:",
4346 "SELECT count(*) FROM %s WHERE type='table'" },
4347 { "number of indexes:",
4348 "SELECT count(*) FROM %s WHERE type='index'" },
4349 { "number of triggers:",
4350 "SELECT count(*) FROM %s WHERE type='trigger'" },
4351 { "number of views:",
4352 "SELECT count(*) FROM %s WHERE type='view'" },
4353 { "schema size:",
4354 "SELECT total(length(sql)) FROM %s" },
4355 };
drh2ce15c32017-07-11 13:34:40 +00004356 int i;
4357 char *zSchemaTab;
4358 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004359 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004360 unsigned char aHdr[100];
4361 open_db(p, 0);
4362 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004363 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4364 -1, &pStmt, 0);
4365 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4366 if( sqlite3_step(pStmt)==SQLITE_ROW
4367 && sqlite3_column_bytes(pStmt,0)>100
4368 ){
4369 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4370 sqlite3_finalize(pStmt);
4371 }else{
drh2ce15c32017-07-11 13:34:40 +00004372 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004373 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004374 return 1;
4375 }
4376 i = get2byteInt(aHdr+16);
4377 if( i==1 ) i = 65536;
4378 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4379 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4380 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4381 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4382 for(i=0; i<ArraySize(aField); i++){
4383 int ofst = aField[i].ofst;
4384 unsigned int val = get4byteInt(aHdr + ofst);
4385 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4386 switch( ofst ){
4387 case 56: {
4388 if( val==1 ) raw_printf(p->out, " (utf8)");
4389 if( val==2 ) raw_printf(p->out, " (utf16le)");
4390 if( val==3 ) raw_printf(p->out, " (utf16be)");
4391 }
4392 }
4393 raw_printf(p->out, "\n");
4394 }
4395 if( zDb==0 ){
4396 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4397 }else if( strcmp(zDb,"temp")==0 ){
4398 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4399 }else{
4400 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4401 }
4402 for(i=0; i<ArraySize(aQuery); i++){
4403 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4404 int val = db_int(p, zSql);
4405 sqlite3_free(zSql);
4406 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4407 }
4408 sqlite3_free(zSchemaTab);
4409 return 0;
4410}
4411
4412/*
4413** Print the current sqlite3_errmsg() value to stderr and return 1.
4414*/
4415static int shellDatabaseError(sqlite3 *db){
4416 const char *zErr = sqlite3_errmsg(db);
4417 utf8_printf(stderr, "Error: %s\n", zErr);
4418 return 1;
4419}
4420
4421/*
drh2ce15c32017-07-11 13:34:40 +00004422** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4423** if they match and FALSE (0) if they do not match.
4424**
4425** Globbing rules:
4426**
4427** '*' Matches any sequence of zero or more characters.
4428**
4429** '?' Matches exactly one character.
4430**
4431** [...] Matches one character from the enclosed list of
4432** characters.
4433**
4434** [^...] Matches one character not in the enclosed list.
4435**
4436** '#' Matches any sequence of one or more digits with an
4437** optional + or - sign in front
4438**
4439** ' ' Any span of whitespace matches any other span of
4440** whitespace.
4441**
4442** Extra whitespace at the end of z[] is ignored.
4443*/
4444static int testcase_glob(const char *zGlob, const char *z){
4445 int c, c2;
4446 int invert;
4447 int seen;
4448
4449 while( (c = (*(zGlob++)))!=0 ){
4450 if( IsSpace(c) ){
4451 if( !IsSpace(*z) ) return 0;
4452 while( IsSpace(*zGlob) ) zGlob++;
4453 while( IsSpace(*z) ) z++;
4454 }else if( c=='*' ){
4455 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4456 if( c=='?' && (*(z++))==0 ) return 0;
4457 }
4458 if( c==0 ){
4459 return 1;
4460 }else if( c=='[' ){
4461 while( *z && testcase_glob(zGlob-1,z)==0 ){
4462 z++;
4463 }
4464 return (*z)!=0;
4465 }
4466 while( (c2 = (*(z++)))!=0 ){
4467 while( c2!=c ){
4468 c2 = *(z++);
4469 if( c2==0 ) return 0;
4470 }
4471 if( testcase_glob(zGlob,z) ) return 1;
4472 }
4473 return 0;
4474 }else if( c=='?' ){
4475 if( (*(z++))==0 ) return 0;
4476 }else if( c=='[' ){
4477 int prior_c = 0;
4478 seen = 0;
4479 invert = 0;
4480 c = *(z++);
4481 if( c==0 ) return 0;
4482 c2 = *(zGlob++);
4483 if( c2=='^' ){
4484 invert = 1;
4485 c2 = *(zGlob++);
4486 }
4487 if( c2==']' ){
4488 if( c==']' ) seen = 1;
4489 c2 = *(zGlob++);
4490 }
4491 while( c2 && c2!=']' ){
4492 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4493 c2 = *(zGlob++);
4494 if( c>=prior_c && c<=c2 ) seen = 1;
4495 prior_c = 0;
4496 }else{
4497 if( c==c2 ){
4498 seen = 1;
4499 }
4500 prior_c = c2;
4501 }
4502 c2 = *(zGlob++);
4503 }
4504 if( c2==0 || (seen ^ invert)==0 ) return 0;
4505 }else if( c=='#' ){
4506 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4507 if( !IsDigit(z[0]) ) return 0;
4508 z++;
4509 while( IsDigit(z[0]) ){ z++; }
4510 }else{
4511 if( c!=(*(z++)) ) return 0;
4512 }
4513 }
4514 while( IsSpace(*z) ){ z++; }
4515 return *z==0;
4516}
4517
4518
4519/*
4520** Compare the string as a command-line option with either one or two
4521** initial "-" characters.
4522*/
4523static int optionMatch(const char *zStr, const char *zOpt){
4524 if( zStr[0]!='-' ) return 0;
4525 zStr++;
4526 if( zStr[0]=='-' ) zStr++;
4527 return strcmp(zStr, zOpt)==0;
4528}
4529
4530/*
4531** Delete a file.
4532*/
4533int shellDeleteFile(const char *zFilename){
4534 int rc;
4535#ifdef _WIN32
4536 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4537 rc = _wunlink(z);
4538 sqlite3_free(z);
4539#else
4540 rc = unlink(zFilename);
4541#endif
4542 return rc;
4543}
4544
drh13c20932018-01-10 21:41:55 +00004545/*
4546** Try to delete the temporary file (if there is one) and free the
4547** memory used to hold the name of the temp file.
4548*/
4549static void clearTempFile(ShellState *p){
4550 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00004551 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00004552 if( shellDeleteFile(p->zTempFile) ) return;
4553 sqlite3_free(p->zTempFile);
4554 p->zTempFile = 0;
4555}
4556
4557/*
4558** Create a new temp file name with the given suffix.
4559*/
4560static void newTempFile(ShellState *p, const char *zSuffix){
4561 clearTempFile(p);
4562 sqlite3_free(p->zTempFile);
4563 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00004564 if( p->db ){
4565 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
4566 }
drh13c20932018-01-10 21:41:55 +00004567 if( p->zTempFile==0 ){
4568 sqlite3_uint64 r;
4569 sqlite3_randomness(sizeof(r), &r);
4570 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
4571 }else{
4572 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
4573 }
4574 if( p->zTempFile==0 ){
4575 raw_printf(stderr, "out of memory\n");
4576 exit(1);
4577 }
4578}
4579
drh2ce15c32017-07-11 13:34:40 +00004580
4581/*
4582** The implementation of SQL scalar function fkey_collate_clause(), used
4583** by the ".lint fkey-indexes" command. This scalar function is always
4584** called with four arguments - the parent table name, the parent column name,
4585** the child table name and the child column name.
4586**
4587** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4588**
4589** If either of the named tables or columns do not exist, this function
4590** returns an empty string. An empty string is also returned if both tables
4591** and columns exist but have the same default collation sequence. Or,
4592** if both exist but the default collation sequences are different, this
4593** function returns the string " COLLATE <parent-collation>", where
4594** <parent-collation> is the default collation sequence of the parent column.
4595*/
4596static void shellFkeyCollateClause(
4597 sqlite3_context *pCtx,
4598 int nVal,
4599 sqlite3_value **apVal
4600){
4601 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4602 const char *zParent;
4603 const char *zParentCol;
4604 const char *zParentSeq;
4605 const char *zChild;
4606 const char *zChildCol;
4607 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4608 int rc;
4609
4610 assert( nVal==4 );
4611 zParent = (const char*)sqlite3_value_text(apVal[0]);
4612 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4613 zChild = (const char*)sqlite3_value_text(apVal[2]);
4614 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4615
4616 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4617 rc = sqlite3_table_column_metadata(
4618 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4619 );
4620 if( rc==SQLITE_OK ){
4621 rc = sqlite3_table_column_metadata(
4622 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4623 );
4624 }
4625
4626 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4627 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4628 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4629 sqlite3_free(z);
4630 }
4631}
4632
4633
4634/*
4635** The implementation of dot-command ".lint fkey-indexes".
4636*/
4637static int lintFkeyIndexes(
4638 ShellState *pState, /* Current shell tool state */
4639 char **azArg, /* Array of arguments passed to dot command */
4640 int nArg /* Number of entries in azArg[] */
4641){
4642 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4643 FILE *out = pState->out; /* Stream to write non-error output to */
4644 int bVerbose = 0; /* If -verbose is present */
4645 int bGroupByParent = 0; /* If -groupbyparent is present */
4646 int i; /* To iterate through azArg[] */
4647 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4648 int rc; /* Return code */
4649 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4650
4651 /*
4652 ** This SELECT statement returns one row for each foreign key constraint
4653 ** in the schema of the main database. The column values are:
4654 **
4655 ** 0. The text of an SQL statement similar to:
4656 **
danf9679312017-12-01 18:40:18 +00004657 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004658 **
danf9679312017-12-01 18:40:18 +00004659 ** This SELECT is similar to the one that the foreign keys implementation
4660 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004661 ** be used to optimize this query, then it can also be used by the FK
4662 ** implementation to optimize DELETE or UPDATE statements on the parent
4663 ** table.
4664 **
4665 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4666 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4667 ** contains an index that can be used to optimize the query.
4668 **
4669 ** 2. Human readable text that describes the child table and columns. e.g.
4670 **
4671 ** "child_table(child_key1, child_key2)"
4672 **
4673 ** 3. Human readable text that describes the parent table and columns. e.g.
4674 **
4675 ** "parent_table(parent_key1, parent_key2)"
4676 **
4677 ** 4. A full CREATE INDEX statement for an index that could be used to
4678 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4679 **
4680 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4681 **
4682 ** 5. The name of the parent table.
4683 **
4684 ** These six values are used by the C logic below to generate the report.
4685 */
4686 const char *zSql =
4687 "SELECT "
danf9679312017-12-01 18:40:18 +00004688 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004689 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4690 " || fkey_collate_clause("
4691 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4692 ", "
4693 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4694 " || group_concat('*=?', ' AND ') || ')'"
4695 ", "
4696 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4697 ", "
4698 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4699 ", "
4700 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4701 " || ' ON ' || quote(s.name) || '('"
4702 " || group_concat(quote(f.[from]) ||"
4703 " fkey_collate_clause("
4704 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4705 " || ');'"
4706 ", "
4707 " f.[table] "
4708 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4709 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4710 "GROUP BY s.name, f.id "
4711 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4712 ;
4713 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4714
4715 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004716 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004717 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4718 bVerbose = 1;
4719 }
4720 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4721 bGroupByParent = 1;
4722 zIndent = " ";
4723 }
4724 else{
4725 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4726 azArg[0], azArg[1]
4727 );
4728 return SQLITE_ERROR;
4729 }
4730 }
4731
4732 /* Register the fkey_collate_clause() SQL function */
4733 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4734 0, shellFkeyCollateClause, 0, 0
4735 );
4736
4737
4738 if( rc==SQLITE_OK ){
4739 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4740 }
4741 if( rc==SQLITE_OK ){
4742 sqlite3_bind_int(pSql, 1, bGroupByParent);
4743 }
4744
4745 if( rc==SQLITE_OK ){
4746 int rc2;
4747 char *zPrev = 0;
4748 while( SQLITE_ROW==sqlite3_step(pSql) ){
4749 int res = -1;
4750 sqlite3_stmt *pExplain = 0;
4751 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4752 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4753 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4754 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4755 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4756 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4757
4758 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4759 if( rc!=SQLITE_OK ) break;
4760 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4761 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4762 res = (
4763 0==sqlite3_strglob(zGlob, zPlan)
4764 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4765 );
4766 }
4767 rc = sqlite3_finalize(pExplain);
4768 if( rc!=SQLITE_OK ) break;
4769
4770 if( res<0 ){
4771 raw_printf(stderr, "Error: internal error");
4772 break;
4773 }else{
4774 if( bGroupByParent
4775 && (bVerbose || res==0)
4776 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4777 ){
4778 raw_printf(out, "-- Parent table %s\n", zParent);
4779 sqlite3_free(zPrev);
4780 zPrev = sqlite3_mprintf("%s", zParent);
4781 }
4782
4783 if( res==0 ){
4784 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4785 }else if( bVerbose ){
4786 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4787 zIndent, zFrom, zTarget
4788 );
4789 }
4790 }
4791 }
4792 sqlite3_free(zPrev);
4793
4794 if( rc!=SQLITE_OK ){
4795 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4796 }
4797
4798 rc2 = sqlite3_finalize(pSql);
4799 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4800 rc = rc2;
4801 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4802 }
4803 }else{
4804 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4805 }
4806
4807 return rc;
4808}
4809
4810/*
4811** Implementation of ".lint" dot command.
4812*/
4813static int lintDotCommand(
4814 ShellState *pState, /* Current shell tool state */
4815 char **azArg, /* Array of arguments passed to dot command */
4816 int nArg /* Number of entries in azArg[] */
4817){
4818 int n;
drhaf2770f2018-01-05 14:55:43 +00004819 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004820 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4821 return lintFkeyIndexes(pState, azArg, nArg);
4822
4823 usage:
4824 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4825 raw_printf(stderr, "Where sub-commands are:\n");
4826 raw_printf(stderr, " fkey-indexes\n");
4827 return SQLITE_ERROR;
4828}
4829
drhe37c0e12018-01-06 19:19:50 +00004830#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4831/*********************************************************************************
4832** The ".archive" or ".ar" command.
4833*/
danfd0245d2017-12-07 15:44:29 +00004834static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004835 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004836 int *pRc,
4837 const char *zSql,
4838 sqlite3_stmt **ppStmt
4839){
4840 *ppStmt = 0;
4841 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004842 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004843 if( rc!=SQLITE_OK ){
4844 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004845 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004846 );
4847 *pRc = rc;
4848 }
4849 }
4850}
4851
danac15e2d2017-12-14 19:15:07 +00004852static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004853 sqlite3 *db,
4854 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004855 sqlite3_stmt **ppStmt,
4856 const char *zFmt,
4857 ...
dan3f67ddf2017-12-13 20:04:53 +00004858){
danac15e2d2017-12-14 19:15:07 +00004859 *ppStmt = 0;
4860 if( *pRc==SQLITE_OK ){
4861 va_list ap;
4862 char *z;
4863 va_start(ap, zFmt);
4864 z = sqlite3_vmprintf(zFmt, ap);
dan3f67ddf2017-12-13 20:04:53 +00004865 if( z==0 ){
4866 *pRc = SQLITE_NOMEM;
4867 }else{
4868 shellPrepare(db, pRc, z, ppStmt);
4869 sqlite3_free(z);
4870 }
dan3f67ddf2017-12-13 20:04:53 +00004871 }
4872}
4873
danfd0245d2017-12-07 15:44:29 +00004874static void shellFinalize(
4875 int *pRc,
4876 sqlite3_stmt *pStmt
4877){
dan25c12182017-12-07 21:03:33 +00004878 if( pStmt ){
4879 sqlite3 *db = sqlite3_db_handle(pStmt);
4880 int rc = sqlite3_finalize(pStmt);
4881 if( *pRc==SQLITE_OK ){
4882 if( rc!=SQLITE_OK ){
4883 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4884 }
4885 *pRc = rc;
4886 }
4887 }
danfd0245d2017-12-07 15:44:29 +00004888}
4889
4890static void shellReset(
4891 int *pRc,
4892 sqlite3_stmt *pStmt
4893){
4894 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00004895 if( *pRc==SQLITE_OK ){
4896 if( rc!=SQLITE_OK ){
4897 sqlite3 *db = sqlite3_db_handle(pStmt);
4898 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4899 }
4900 *pRc = rc;
4901 }
danfd0245d2017-12-07 15:44:29 +00004902}
drhe37c0e12018-01-06 19:19:50 +00004903/*
dan88be0202017-12-09 17:58:02 +00004904** Structure representing a single ".ar" command.
4905*/
4906typedef struct ArCommand ArCommand;
4907struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00004908 u8 eCmd; /* An AR_CMD_* value */
4909 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00004910 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00004911 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00004912 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00004913 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00004914 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00004915 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00004916 const char *zFile; /* --file argument, or NULL */
4917 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00004918 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00004919 ShellState *p; /* Shell state */
4920 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00004921};
4922
4923/*
4924** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4925*/
dan0d0547f2017-12-14 15:40:42 +00004926static int arUsage(FILE *f){
4927 raw_printf(f,
4928"\n"
4929"Usage: .ar [OPTION...] [FILE...]\n"
4930"The .ar command manages sqlar archives.\n"
4931"\n"
4932"Examples:\n"
4933" .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4934" .ar -tf archive.sar # List members of archive.sar\n"
4935" .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4936"\n"
4937"Each command line must feature exactly one command option:\n"
4938" -c, --create Create a new archive\n"
4939" -u, --update Update or add files to an existing archive\n"
4940" -t, --list List contents of archive\n"
4941" -x, --extract Extract files from archive\n"
4942"\n"
4943"And zero or more optional options:\n"
4944" -v, --verbose Print each filename as it is processed\n"
4945" -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
drhca7733b2018-01-10 18:09:20 +00004946" -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
dan0d0547f2017-12-14 15:40:42 +00004947" -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
drhb376b3d2018-01-10 13:11:51 +00004948" -n, --dryrun Show the SQL that would have occurred\n"
dan0d0547f2017-12-14 15:40:42 +00004949"\n"
4950"See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4951"\n"
4952);
4953 return SQLITE_ERROR;
4954}
4955
4956/*
4957** Print an error message for the .ar command to stderr and return
4958** SQLITE_ERROR.
4959*/
drhd0f9cdc2018-05-17 14:09:06 +00004960static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00004961 va_list ap;
4962 char *z;
4963 va_start(ap, zFmt);
4964 z = sqlite3_vmprintf(zFmt, ap);
4965 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00004966 utf8_printf(stderr, "Error: %s\n", z);
4967 if( pAr->fromCmdLine ){
4968 utf8_printf(stderr, "Use \"-A\" for more help\n");
4969 }else{
4970 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
4971 }
dan0d0547f2017-12-14 15:40:42 +00004972 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00004973 return SQLITE_ERROR;
4974}
4975
4976/*
4977** Values for ArCommand.eCmd.
4978*/
dand4b56e52017-12-12 20:04:59 +00004979#define AR_CMD_CREATE 1
4980#define AR_CMD_EXTRACT 2
4981#define AR_CMD_LIST 3
4982#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00004983#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00004984
4985/*
4986** Other (non-command) switches.
4987*/
drhb376b3d2018-01-10 13:11:51 +00004988#define AR_SWITCH_VERBOSE 6
4989#define AR_SWITCH_FILE 7
4990#define AR_SWITCH_DIRECTORY 8
drha5676c42018-01-10 15:17:34 +00004991#define AR_SWITCH_APPEND 9
drhb376b3d2018-01-10 13:11:51 +00004992#define AR_SWITCH_DRYRUN 10
dand4b56e52017-12-12 20:04:59 +00004993
4994static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4995 switch( eSwitch ){
4996 case AR_CMD_CREATE:
4997 case AR_CMD_EXTRACT:
4998 case AR_CMD_LIST:
4999 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00005000 case AR_CMD_HELP:
5001 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005002 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005003 }
dand4b56e52017-12-12 20:04:59 +00005004 pAr->eCmd = eSwitch;
5005 break;
5006
drhb376b3d2018-01-10 13:11:51 +00005007 case AR_SWITCH_DRYRUN:
5008 pAr->bDryRun = 1;
5009 break;
dand4b56e52017-12-12 20:04:59 +00005010 case AR_SWITCH_VERBOSE:
5011 pAr->bVerbose = 1;
5012 break;
drha5676c42018-01-10 15:17:34 +00005013 case AR_SWITCH_APPEND:
5014 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005015 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005016 case AR_SWITCH_FILE:
5017 pAr->zFile = zArg;
5018 break;
5019 case AR_SWITCH_DIRECTORY:
5020 pAr->zDir = zArg;
5021 break;
5022 }
5023
5024 return SQLITE_OK;
5025}
dan88be0202017-12-09 17:58:02 +00005026
5027/*
5028** Parse the command line for an ".ar" command. The results are written into
5029** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5030** successfully, otherwise an error message is written to stderr and
5031** SQLITE_ERROR returned.
5032*/
5033static int arParseCommand(
5034 char **azArg, /* Array of arguments passed to dot command */
5035 int nArg, /* Number of entries in azArg[] */
5036 ArCommand *pAr /* Populate this object */
5037){
dand4b56e52017-12-12 20:04:59 +00005038 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005039 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005040 char cShort;
5041 u8 eSwitch;
5042 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005043 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005044 { "create", 'c', AR_CMD_CREATE, 0 },
5045 { "extract", 'x', AR_CMD_EXTRACT, 0 },
5046 { "list", 't', AR_CMD_LIST, 0 },
5047 { "update", 'u', AR_CMD_UPDATE, 0 },
5048 { "help", 'h', AR_CMD_HELP, 0 },
5049 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5050 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005051 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005052 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005053 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005054 };
5055 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5056 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5057
dan88be0202017-12-09 17:58:02 +00005058 if( nArg<=1 ){
dan0d0547f2017-12-14 15:40:42 +00005059 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005060 }else{
5061 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005062 if( z[0]!='-' ){
5063 /* Traditional style [tar] invocation */
5064 int i;
5065 int iArg = 2;
5066 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005067 const char *zArg = 0;
5068 struct ArSwitch *pOpt;
5069 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5070 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005071 }
dan0d0547f2017-12-14 15:40:42 +00005072 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005073 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005074 }
dand4b56e52017-12-12 20:04:59 +00005075 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005076 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005077 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005078 }
dand4b56e52017-12-12 20:04:59 +00005079 zArg = azArg[iArg++];
5080 }
5081 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005082 }
dan88be0202017-12-09 17:58:02 +00005083 pAr->nArg = nArg-iArg;
5084 if( pAr->nArg>0 ){
5085 pAr->azArg = &azArg[iArg];
5086 }
dand4b56e52017-12-12 20:04:59 +00005087 }else{
5088 /* Non-traditional invocation */
5089 int iArg;
5090 for(iArg=1; iArg<nArg; iArg++){
5091 int n;
5092 z = azArg[iArg];
5093 if( z[0]!='-' ){
5094 /* All remaining command line words are command arguments. */
5095 pAr->azArg = &azArg[iArg];
5096 pAr->nArg = nArg-iArg;
5097 break;
5098 }
drhaf2770f2018-01-05 14:55:43 +00005099 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005100
5101 if( z[1]!='-' ){
5102 int i;
5103 /* One or more short options */
5104 for(i=1; i<n; i++){
5105 const char *zArg = 0;
5106 struct ArSwitch *pOpt;
5107 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5108 if( z[i]==pOpt->cShort ) break;
5109 }
dan0d0547f2017-12-14 15:40:42 +00005110 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005111 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005112 }
dand4b56e52017-12-12 20:04:59 +00005113 if( pOpt->bArg ){
5114 if( i<(n-1) ){
5115 zArg = &z[i+1];
5116 i = n;
5117 }else{
dan0d0547f2017-12-14 15:40:42 +00005118 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005119 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005120 }
dand4b56e52017-12-12 20:04:59 +00005121 zArg = azArg[++iArg];
5122 }
5123 }
5124 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5125 }
5126 }else if( z[2]=='\0' ){
5127 /* A -- option, indicating that all remaining command line words
5128 ** are command arguments. */
5129 pAr->azArg = &azArg[iArg+1];
5130 pAr->nArg = nArg-iArg-1;
5131 break;
5132 }else{
5133 /* A long option */
5134 const char *zArg = 0; /* Argument for option, if any */
5135 struct ArSwitch *pMatch = 0; /* Matching option */
5136 struct ArSwitch *pOpt; /* Iterator */
5137 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5138 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005139 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005140 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005141 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005142 }else{
5143 pMatch = pOpt;
5144 }
5145 }
5146 }
5147
5148 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005149 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005150 }
5151 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005152 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005153 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005154 }
dand4b56e52017-12-12 20:04:59 +00005155 zArg = azArg[++iArg];
5156 }
5157 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5158 }
5159 }
dan88be0202017-12-09 17:58:02 +00005160 }
5161 }
5162
5163 return SQLITE_OK;
5164}
5165
5166/*
dan3f67ddf2017-12-13 20:04:53 +00005167** This function assumes that all arguments within the ArCommand.azArg[]
5168** array refer to archive members, as for the --extract or --list commands.
5169** It checks that each of them are present. If any specified file is not
5170** present in the archive, an error is printed to stderr and an error
5171** code returned. Otherwise, if all specified arguments are present in
5172** the archive, SQLITE_OK is returned.
5173**
5174** This function strips any trailing '/' characters from each argument.
5175** This is consistent with the way the [tar] command seems to work on
5176** Linux.
5177*/
drhb376b3d2018-01-10 13:11:51 +00005178static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005179 int rc = SQLITE_OK;
5180 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005181 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005182 sqlite3_stmt *pTest = 0;
5183
drhb376b3d2018-01-10 13:11:51 +00005184 shellPreparePrintf(pAr->db, &rc, &pTest,
5185 "SELECT name FROM %s WHERE name=$name",
5186 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005187 );
drhb376b3d2018-01-10 13:11:51 +00005188 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005189 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5190 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005191 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005192 int bOk = 0;
5193 while( n>0 && z[n-1]=='/' ) n--;
5194 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005195 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005196 if( SQLITE_ROW==sqlite3_step(pTest) ){
5197 bOk = 1;
5198 }
5199 shellReset(&rc, pTest);
5200 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005201 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005202 rc = SQLITE_ERROR;
5203 }
5204 }
5205 shellFinalize(&rc, pTest);
5206 }
dan3f67ddf2017-12-13 20:04:53 +00005207 return rc;
5208}
5209
5210/*
5211** Format a WHERE clause that can be used against the "sqlar" table to
5212** identify all archive members that match the command arguments held
5213** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5214** The caller is responsible for eventually calling sqlite3_free() on
5215** any non-NULL (*pzWhere) value.
5216*/
5217static void arWhereClause(
5218 int *pRc,
5219 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005220 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005221){
5222 char *zWhere = 0;
5223 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005224 if( pAr->nArg==0 ){
5225 zWhere = sqlite3_mprintf("1");
5226 }else{
5227 int i;
5228 const char *zSep = "";
5229 for(i=0; i<pAr->nArg; i++){
5230 const char *z = pAr->azArg[i];
5231 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005232 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5233 zWhere, zSep, z, strlen30(z)+1, z
5234 );
danac15e2d2017-12-14 19:15:07 +00005235 if( zWhere==0 ){
5236 *pRc = SQLITE_NOMEM;
5237 break;
5238 }
5239 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005240 }
dan3f67ddf2017-12-13 20:04:53 +00005241 }
5242 }
5243 *pzWhere = zWhere;
5244}
5245
5246/*
dan88be0202017-12-09 17:58:02 +00005247** Implementation of .ar "lisT" command.
5248*/
drhb376b3d2018-01-10 13:11:51 +00005249static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005250 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005251 const char *azCols[] = {
5252 "name",
drh410cad92018-01-10 17:19:16 +00005253 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005254 };
dan5a78b812017-12-27 18:54:11 +00005255
dan3f67ddf2017-12-13 20:04:53 +00005256 char *zWhere = 0;
5257 sqlite3_stmt *pSql = 0;
5258 int rc;
5259
drhb376b3d2018-01-10 13:11:51 +00005260 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005261 arWhereClause(&rc, pAr, &zWhere);
5262
drhb376b3d2018-01-10 13:11:51 +00005263 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5264 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005265 if( pAr->bDryRun ){
5266 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5267 }else{
5268 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5269 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005270 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5271 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005272 sqlite3_column_int(pSql, 1),
5273 sqlite3_column_text(pSql, 2),
5274 sqlite3_column_text(pSql, 3)
5275 );
5276 }else{
5277 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5278 }
danb5090e42017-12-27 21:13:21 +00005279 }
dan3f67ddf2017-12-13 20:04:53 +00005280 }
dan5a78b812017-12-27 18:54:11 +00005281 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005282 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005283 return rc;
dan88be0202017-12-09 17:58:02 +00005284}
5285
5286
danfd0245d2017-12-07 15:44:29 +00005287/*
5288** Implementation of .ar "eXtract" command.
5289*/
drhb376b3d2018-01-10 13:11:51 +00005290static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005291 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005292 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005293 " ($dir || name),"
5294 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005295 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5296 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005297
5298 const char *azExtraArg[] = {
5299 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005300 "data"
dan5a78b812017-12-27 18:54:11 +00005301 };
dan5a78b812017-12-27 18:54:11 +00005302
danfd0245d2017-12-07 15:44:29 +00005303 sqlite3_stmt *pSql = 0;
5304 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005305 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005306 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005307 int i, j;
dan2ad09492017-12-09 18:28:22 +00005308
dan3f67ddf2017-12-13 20:04:53 +00005309 /* If arguments are specified, check that they actually exist within
5310 ** the archive before proceeding. And formulate a WHERE clause to
5311 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005312 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005313 arWhereClause(&rc, pAr, &zWhere);
5314
5315 if( rc==SQLITE_OK ){
5316 if( pAr->zDir ){
5317 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5318 }else{
5319 zDir = sqlite3_mprintf("");
5320 }
5321 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005322 }
danfd0245d2017-12-07 15:44:29 +00005323
drhb376b3d2018-01-10 13:11:51 +00005324 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5325 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005326 );
5327
dan2ad09492017-12-09 18:28:22 +00005328 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005329 j = sqlite3_bind_parameter_index(pSql, "$dir");
5330 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005331
danac15e2d2017-12-14 19:15:07 +00005332 /* Run the SELECT statement twice. The first time, writefile() is called
5333 ** for all archive members that should be extracted. The second time,
5334 ** only for the directories. This is because the timestamps for
5335 ** extracted directories must be reset after they are populated (as
5336 ** populating them changes the timestamp). */
5337 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005338 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5339 sqlite3_bind_int(pSql, j, i);
5340 if( pAr->bDryRun ){
5341 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5342 }else{
5343 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5344 if( i==0 && pAr->bVerbose ){
5345 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5346 }
danac15e2d2017-12-14 19:15:07 +00005347 }
5348 }
5349 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005350 }
danac15e2d2017-12-14 19:15:07 +00005351 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005352 }
dan25c12182017-12-07 21:03:33 +00005353
dan2ad09492017-12-09 18:28:22 +00005354 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005355 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005356 return rc;
5357}
5358
drhb376b3d2018-01-10 13:11:51 +00005359/*
5360** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5361*/
5362static int arExecSql(ArCommand *pAr, const char *zSql){
5363 int rc;
5364 if( pAr->bDryRun ){
5365 utf8_printf(pAr->p->out, "%s\n", zSql);
5366 rc = SQLITE_OK;
5367 }else{
drh410cad92018-01-10 17:19:16 +00005368 char *zErr = 0;
5369 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5370 if( zErr ){
5371 utf8_printf(stdout, "ERROR: %s\n", zErr);
5372 sqlite3_free(zErr);
5373 }
drhb376b3d2018-01-10 13:11:51 +00005374 }
5375 return rc;
5376}
5377
dan1ad3f612017-12-11 20:22:02 +00005378
danfd0245d2017-12-07 15:44:29 +00005379/*
dan06741a32017-12-13 20:17:18 +00005380** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00005381**
5382** Create the "sqlar" table in the database if it does not already exist.
5383** Then add each file in the azFile[] array to the archive. Directories
5384** are added recursively. If argument bVerbose is non-zero, a message is
5385** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005386**
5387** The create command is the same as update, except that it drops
5388** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00005389*/
drhb376b3d2018-01-10 13:11:51 +00005390static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005391 ArCommand *pAr, /* Command arguments and options */
drhb376b3d2018-01-10 13:11:51 +00005392 int bUpdate /* true for a --create. false for --update */
danfd0245d2017-12-07 15:44:29 +00005393){
dand4b56e52017-12-12 20:04:59 +00005394 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005395 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5396 " name TEXT PRIMARY KEY, -- name of the file\n"
5397 " mode INT, -- access permissions\n"
5398 " mtime INT, -- last modification time\n"
5399 " sz INT, -- original file size\n"
5400 " data BLOB -- compressed content\n"
5401 ")";
dand4b56e52017-12-12 20:04:59 +00005402 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005403 const char *zInsertFmt[2] = {
5404 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005405 " SELECT\n"
5406 " %s,\n"
5407 " mode,\n"
5408 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005409 " CASE substr(lsmode(mode),1,1)\n"
5410 " WHEN '-' THEN length(data)\n"
5411 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005412 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005413 " sqlar_compress(data)\n"
drh634c70f2018-01-10 16:50:18 +00005414 " FROM fsdir(%Q,%Q)\n"
drh1bf208c2018-03-09 21:54:01 +00005415 " WHERE lsmode(mode) NOT LIKE '?%%';",
5416 "REPLACE INTO %s(name,mode,mtime,data)\n"
5417 " SELECT\n"
5418 " %s,\n"
5419 " mode,\n"
5420 " mtime,\n"
5421 " data\n"
5422 " FROM fsdir(%Q,%Q)\n"
5423 " WHERE lsmode(mode) NOT LIKE '?%%';"
5424 };
danfd0245d2017-12-07 15:44:29 +00005425 int i; /* For iterating through azFile[] */
5426 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005427 const char *zTab = 0; /* SQL table into which to insert */
5428 char *zSql;
5429 char zTemp[50];
danfd0245d2017-12-07 15:44:29 +00005430
drh1bf208c2018-03-09 21:54:01 +00005431 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005432 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005433 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005434 zTemp[0] = 0;
5435 if( pAr->bZip ){
5436 /* Initialize the zipfile virtual table, if necessary */
5437 if( pAr->zFile ){
5438 sqlite3_uint64 r;
5439 sqlite3_randomness(sizeof(r),&r);
5440 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5441 zTab = zTemp;
5442 zSql = sqlite3_mprintf(
5443 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5444 zTab, pAr->zFile
5445 );
5446 rc = arExecSql(pAr, zSql);
5447 sqlite3_free(zSql);
5448 }else{
5449 zTab = "zip";
5450 }
5451 }else{
5452 /* Initialize the table for an SQLAR */
5453 zTab = "sqlar";
5454 if( bUpdate==0 ){
5455 rc = arExecSql(pAr, zDrop);
5456 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5457 }
5458 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005459 }
dan88be0202017-12-09 17:58:02 +00005460 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00005461 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005462 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5463 pAr->azArg[i], pAr->zDir);
mistachkince2052b2018-03-23 00:31:53 +00005464 rc = arExecSql(pAr, zSql2);
5465 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00005466 }
drh1bf208c2018-03-09 21:54:01 +00005467end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00005468 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005469 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
danfd0245d2017-12-07 15:44:29 +00005470 }else{
drhb376b3d2018-01-10 13:11:51 +00005471 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00005472 if( pAr->bZip && pAr->zFile ){
5473 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5474 arExecSql(pAr, zSql);
5475 sqlite3_free(zSql);
5476 }
danfd0245d2017-12-07 15:44:29 +00005477 }
danfd0245d2017-12-07 15:44:29 +00005478 return rc;
5479}
5480
5481/*
5482** Implementation of ".ar" dot command.
5483*/
5484static int arDotCommand(
5485 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00005486 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00005487 char **azArg, /* Array of arguments passed to dot command */
5488 int nArg /* Number of entries in azArg[] */
5489){
dan88be0202017-12-09 17:58:02 +00005490 ArCommand cmd;
5491 int rc;
drh34660642018-01-10 17:39:54 +00005492 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00005493 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00005494 rc = arParseCommand(azArg, nArg, &cmd);
5495 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005496 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005497 cmd.p = pState;
5498 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005499 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00005500 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00005501 }else{
5502 eDbType = pState->openMode;
5503 }
5504 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00005505 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5506 if( cmd.zFile==0 ){
5507 cmd.zSrcTable = sqlite3_mprintf("zip");
5508 }else{
5509 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5510 }
dan5a78b812017-12-27 18:54:11 +00005511 }
drha5676c42018-01-10 15:17:34 +00005512 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005513 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005514 int flags;
drha5676c42018-01-10 15:17:34 +00005515 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
dand4b56e52017-12-12 20:04:59 +00005516 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5517 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5518 }else{
5519 flags = SQLITE_OPEN_READONLY;
5520 }
drha82c95b2018-01-10 14:00:00 +00005521 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005522 if( cmd.bDryRun ){
5523 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5524 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5525 }
5526 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5527 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005528 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005529 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5530 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005531 );
drha5676c42018-01-10 15:17:34 +00005532 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005533 }
drhb376b3d2018-01-10 13:11:51 +00005534 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00005535 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00005536 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5537 shellPutsFunc, 0, 0);
5538
dand4b56e52017-12-12 20:04:59 +00005539 }
drhd0f9cdc2018-05-17 14:09:06 +00005540 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00005541 if( cmd.eCmd!=AR_CMD_CREATE
5542 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5543 ){
drha5676c42018-01-10 15:17:34 +00005544 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5545 rc = SQLITE_ERROR;
5546 goto end_ar_command;
5547 }
5548 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5549 }
dand4b56e52017-12-12 20:04:59 +00005550
dan88be0202017-12-09 17:58:02 +00005551 switch( cmd.eCmd ){
5552 case AR_CMD_CREATE:
drhb376b3d2018-01-10 13:11:51 +00005553 rc = arCreateOrUpdateCommand(&cmd, 0);
dan88be0202017-12-09 17:58:02 +00005554 break;
danfd0245d2017-12-07 15:44:29 +00005555
dan88be0202017-12-09 17:58:02 +00005556 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005557 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005558 break;
5559
5560 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00005561 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005562 break;
5563
dan0d0547f2017-12-14 15:40:42 +00005564 case AR_CMD_HELP:
5565 arUsage(pState->out);
5566 break;
5567
dan88be0202017-12-09 17:58:02 +00005568 default:
5569 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb376b3d2018-01-10 13:11:51 +00005570 rc = arCreateOrUpdateCommand(&cmd, 1);
dan88be0202017-12-09 17:58:02 +00005571 break;
danfd0245d2017-12-07 15:44:29 +00005572 }
5573 }
drha5676c42018-01-10 15:17:34 +00005574end_ar_command:
5575 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00005576 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00005577 }
5578 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00005579
dan88be0202017-12-09 17:58:02 +00005580 return rc;
danfd0245d2017-12-07 15:44:29 +00005581}
drhe37c0e12018-01-06 19:19:50 +00005582/* End of the ".archive" or ".ar" command logic
5583**********************************************************************************/
5584#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00005585
drh2ce15c32017-07-11 13:34:40 +00005586
5587/*
5588** If an input line begins with "." then invoke this routine to
5589** process that line.
5590**
5591** Return 1 on error, 2 to exit, and 0 otherwise.
5592*/
5593static int do_meta_command(char *zLine, ShellState *p){
5594 int h = 1;
5595 int nArg = 0;
5596 int n, c;
5597 int rc = 0;
5598 char *azArg[50];
5599
dan6b046be2018-01-09 15:25:55 +00005600#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005601 if( p->expert.pExpert ){
5602 expertFinish(p, 1, 0);
5603 }
dan6b046be2018-01-09 15:25:55 +00005604#endif
dan43efc182017-12-19 17:42:13 +00005605
drh2ce15c32017-07-11 13:34:40 +00005606 /* Parse the input line into tokens.
5607 */
5608 while( zLine[h] && nArg<ArraySize(azArg) ){
5609 while( IsSpace(zLine[h]) ){ h++; }
5610 if( zLine[h]==0 ) break;
5611 if( zLine[h]=='\'' || zLine[h]=='"' ){
5612 int delim = zLine[h++];
5613 azArg[nArg++] = &zLine[h];
5614 while( zLine[h] && zLine[h]!=delim ){
5615 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5616 h++;
5617 }
5618 if( zLine[h]==delim ){
5619 zLine[h++] = 0;
5620 }
5621 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5622 }else{
5623 azArg[nArg++] = &zLine[h];
5624 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5625 if( zLine[h] ) zLine[h++] = 0;
5626 resolve_backslashes(azArg[nArg-1]);
5627 }
5628 }
5629
5630 /* Process the input line.
5631 */
5632 if( nArg==0 ) return 0; /* no tokens, no error */
5633 n = strlen30(azArg[0]);
5634 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00005635 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00005636
5637#ifndef SQLITE_OMIT_AUTHORIZATION
5638 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5639 if( nArg!=2 ){
5640 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5641 rc = 1;
5642 goto meta_command_exit;
5643 }
5644 open_db(p, 0);
5645 if( booleanValue(azArg[1]) ){
5646 sqlite3_set_authorizer(p->db, shellAuth, p);
5647 }else{
5648 sqlite3_set_authorizer(p->db, 0, 0);
5649 }
5650 }else
5651#endif
5652
drhe37c0e12018-01-06 19:19:50 +00005653#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5654 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00005655 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00005656 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00005657 }else
5658#endif
5659
drh2ce15c32017-07-11 13:34:40 +00005660 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5661 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5662 ){
5663 const char *zDestFile = 0;
5664 const char *zDb = 0;
5665 sqlite3 *pDest;
5666 sqlite3_backup *pBackup;
5667 int j;
drh69ed38a2018-05-14 00:23:08 +00005668 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00005669 for(j=1; j<nArg; j++){
5670 const char *z = azArg[j];
5671 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00005672 if( z[1]=='-' ) z++;
5673 if( strcmp(z, "-append")==0 ){
5674 zVfs = "apndvfs";
5675 }else
drh2ce15c32017-07-11 13:34:40 +00005676 {
5677 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5678 return 1;
5679 }
5680 }else if( zDestFile==0 ){
5681 zDestFile = azArg[j];
5682 }else if( zDb==0 ){
5683 zDb = zDestFile;
5684 zDestFile = azArg[j];
5685 }else{
drh69ed38a2018-05-14 00:23:08 +00005686 raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00005687 return 1;
5688 }
5689 }
5690 if( zDestFile==0 ){
5691 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5692 return 1;
5693 }
5694 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00005695 rc = sqlite3_open_v2(zDestFile, &pDest,
5696 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00005697 if( rc!=SQLITE_OK ){
5698 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00005699 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005700 return 1;
5701 }
5702 open_db(p, 0);
5703 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5704 if( pBackup==0 ){
5705 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00005706 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005707 return 1;
5708 }
5709 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5710 sqlite3_backup_finish(pBackup);
5711 if( rc==SQLITE_DONE ){
5712 rc = 0;
5713 }else{
5714 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5715 rc = 1;
5716 }
drh9e804032018-05-18 17:11:50 +00005717 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005718 }else
5719
5720 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5721 if( nArg==2 ){
5722 bail_on_error = booleanValue(azArg[1]);
5723 }else{
5724 raw_printf(stderr, "Usage: .bail on|off\n");
5725 rc = 1;
5726 }
5727 }else
5728
5729 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5730 if( nArg==2 ){
5731 if( booleanValue(azArg[1]) ){
5732 setBinaryMode(p->out, 1);
5733 }else{
5734 setTextMode(p->out, 1);
5735 }
5736 }else{
5737 raw_printf(stderr, "Usage: .binary on|off\n");
5738 rc = 1;
5739 }
5740 }else
5741
5742 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5743 if( nArg==2 ){
5744#if defined(_WIN32) || defined(WIN32)
5745 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5746 rc = !SetCurrentDirectoryW(z);
5747 sqlite3_free(z);
5748#else
5749 rc = chdir(azArg[1]);
5750#endif
5751 if( rc ){
5752 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5753 rc = 1;
5754 }
5755 }else{
5756 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5757 rc = 1;
5758 }
5759 }else
5760
5761 /* The undocumented ".breakpoint" command causes a call to the no-op
5762 ** routine named test_breakpoint().
5763 */
5764 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5765 test_breakpoint();
5766 }else
5767
5768 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5769 if( nArg==2 ){
5770 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5771 }else{
5772 raw_printf(stderr, "Usage: .changes on|off\n");
5773 rc = 1;
5774 }
5775 }else
5776
5777 /* Cancel output redirection, if it is currently set (by .testcase)
5778 ** Then read the content of the testcase-out.txt file and compare against
5779 ** azArg[1]. If there are differences, report an error and exit.
5780 */
5781 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5782 char *zRes = 0;
5783 output_reset(p);
5784 if( nArg!=2 ){
5785 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5786 rc = 2;
5787 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5788 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5789 rc = 2;
5790 }else if( testcase_glob(azArg[1],zRes)==0 ){
5791 utf8_printf(stderr,
5792 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5793 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005794 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005795 }else{
5796 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5797 p->nCheck++;
5798 }
5799 sqlite3_free(zRes);
5800 }else
5801
5802 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5803 if( nArg==2 ){
5804 tryToClone(p, azArg[1]);
5805 }else{
5806 raw_printf(stderr, "Usage: .clone FILENAME\n");
5807 rc = 1;
5808 }
5809 }else
5810
5811 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5812 ShellState data;
5813 char *zErrMsg = 0;
5814 open_db(p, 0);
5815 memcpy(&data, p, sizeof(data));
5816 data.showHeader = 0;
5817 data.cMode = data.mode = MODE_List;
5818 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5819 data.cnt = 0;
5820 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5821 callback, &data, &zErrMsg);
5822 if( zErrMsg ){
5823 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5824 sqlite3_free(zErrMsg);
5825 rc = 1;
5826 }
5827 }else
5828
drh7df01192018-04-28 12:43:16 +00005829 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
5830 static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
5831 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
5832 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
5833 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
5834 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
5835 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
5836 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
5837 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
5838 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
5839 };
5840 int ii, v;
5841 open_db(p, 0);
5842 for(ii=0; ii<ArraySize(aDbConfig); ii++){
5843 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
5844 if( nArg>=3 ){
5845 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
5846 }
5847 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
5848 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
5849 if( nArg>1 ) break;
5850 }
5851 if( nArg>1 && ii==ArraySize(aDbConfig) ){
5852 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
5853 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
5854 }
5855 }else
5856
5857 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00005858 rc = shell_dbinfo_command(p, nArg, azArg);
5859 }else
5860
5861 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5862 const char *zLike = 0;
5863 int i;
5864 int savedShowHeader = p->showHeader;
5865 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5866 for(i=1; i<nArg; i++){
5867 if( azArg[i][0]=='-' ){
5868 const char *z = azArg[i]+1;
5869 if( z[0]=='-' ) z++;
5870 if( strcmp(z,"preserve-rowids")==0 ){
5871#ifdef SQLITE_OMIT_VIRTUALTABLE
5872 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5873 " with SQLITE_OMIT_VIRTUALTABLE\n");
5874 rc = 1;
5875 goto meta_command_exit;
5876#else
5877 ShellSetFlag(p, SHFLG_PreserveRowid);
5878#endif
5879 }else
5880 if( strcmp(z,"newlines")==0 ){
5881 ShellSetFlag(p, SHFLG_Newlines);
5882 }else
5883 {
5884 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5885 rc = 1;
5886 goto meta_command_exit;
5887 }
5888 }else if( zLike ){
5889 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5890 "?--newlines? ?LIKE-PATTERN?\n");
5891 rc = 1;
5892 goto meta_command_exit;
5893 }else{
5894 zLike = azArg[i];
5895 }
5896 }
5897 open_db(p, 0);
5898 /* When playing back a "dump", the content might appear in an order
5899 ** which causes immediate foreign key constraints to be violated.
5900 ** So disable foreign-key constraint enforcement to prevent problems. */
5901 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5902 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5903 p->writableSchema = 0;
5904 p->showHeader = 0;
5905 /* Set writable_schema=ON since doing so forces SQLite to initialize
5906 ** as much of the schema as it can even if the sqlite_master table is
5907 ** corrupt. */
5908 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5909 p->nErr = 0;
5910 if( zLike==0 ){
5911 run_schema_dump_query(p,
5912 "SELECT name, type, sql FROM sqlite_master "
5913 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5914 );
5915 run_schema_dump_query(p,
5916 "SELECT name, type, sql FROM sqlite_master "
5917 "WHERE name=='sqlite_sequence'"
5918 );
5919 run_table_dump_query(p,
5920 "SELECT sql FROM sqlite_master "
5921 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5922 );
5923 }else{
5924 char *zSql;
5925 zSql = sqlite3_mprintf(
5926 "SELECT name, type, sql FROM sqlite_master "
5927 "WHERE tbl_name LIKE %Q AND type=='table'"
5928 " AND sql NOT NULL", zLike);
5929 run_schema_dump_query(p,zSql);
5930 sqlite3_free(zSql);
5931 zSql = sqlite3_mprintf(
5932 "SELECT sql FROM sqlite_master "
5933 "WHERE sql NOT NULL"
5934 " AND type IN ('index','trigger','view')"
5935 " AND tbl_name LIKE %Q", zLike);
5936 run_table_dump_query(p, zSql, 0);
5937 sqlite3_free(zSql);
5938 }
5939 if( p->writableSchema ){
5940 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5941 p->writableSchema = 0;
5942 }
5943 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5944 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5945 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5946 p->showHeader = savedShowHeader;
5947 }else
5948
5949 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5950 if( nArg==2 ){
5951 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5952 }else{
5953 raw_printf(stderr, "Usage: .echo on|off\n");
5954 rc = 1;
5955 }
5956 }else
5957
5958 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5959 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00005960 p->autoEQPtest = 0;
drh2ce15c32017-07-11 13:34:40 +00005961 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00005962 p->autoEQP = AUTOEQP_full;
5963 }else if( strcmp(azArg[1],"trigger")==0 ){
5964 p->autoEQP = AUTOEQP_trigger;
drhe2ca99c2018-05-02 00:33:43 +00005965 }else if( strcmp(azArg[1],"test")==0 ){
5966 p->autoEQP = AUTOEQP_on;
5967 p->autoEQPtest = 1;
drh2ce15c32017-07-11 13:34:40 +00005968 }else{
mistachkinb71aa092018-01-23 00:05:18 +00005969 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00005970 }
5971 }else{
drhada70452017-12-21 21:02:27 +00005972 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00005973 rc = 1;
5974 }
5975 }else
5976
5977 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5978 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5979 rc = 2;
5980 }else
5981
5982 /* The ".explain" command is automatic now. It is largely pointless. It
5983 ** retained purely for backwards compatibility */
5984 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5985 int val = 1;
5986 if( nArg>=2 ){
5987 if( strcmp(azArg[1],"auto")==0 ){
5988 val = 99;
5989 }else{
5990 val = booleanValue(azArg[1]);
5991 }
5992 }
5993 if( val==1 && p->mode!=MODE_Explain ){
5994 p->normalMode = p->mode;
5995 p->mode = MODE_Explain;
5996 p->autoExplain = 0;
5997 }else if( val==0 ){
5998 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5999 p->autoExplain = 0;
6000 }else if( val==99 ){
6001 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6002 p->autoExplain = 1;
6003 }
6004 }else
6005
dan6b046be2018-01-09 15:25:55 +00006006#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006007 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6008 open_db(p, 0);
6009 expertDotCommand(p, azArg, nArg);
6010 }else
dan6b046be2018-01-09 15:25:55 +00006011#endif
dan43efc182017-12-19 17:42:13 +00006012
drh2ce15c32017-07-11 13:34:40 +00006013 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6014 ShellState data;
6015 char *zErrMsg = 0;
6016 int doStats = 0;
6017 memcpy(&data, p, sizeof(data));
6018 data.showHeader = 0;
6019 data.cMode = data.mode = MODE_Semi;
6020 if( nArg==2 && optionMatch(azArg[1], "indent") ){
6021 data.cMode = data.mode = MODE_Pretty;
6022 nArg = 1;
6023 }
6024 if( nArg!=1 ){
6025 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6026 rc = 1;
6027 goto meta_command_exit;
6028 }
6029 open_db(p, 0);
6030 rc = sqlite3_exec(p->db,
6031 "SELECT sql FROM"
6032 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6033 " FROM sqlite_master UNION ALL"
6034 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6035 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6036 "ORDER BY rowid",
6037 callback, &data, &zErrMsg
6038 );
6039 if( rc==SQLITE_OK ){
6040 sqlite3_stmt *pStmt;
6041 rc = sqlite3_prepare_v2(p->db,
6042 "SELECT rowid FROM sqlite_master"
6043 " WHERE name GLOB 'sqlite_stat[134]'",
6044 -1, &pStmt, 0);
6045 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6046 sqlite3_finalize(pStmt);
6047 }
6048 if( doStats==0 ){
6049 raw_printf(p->out, "/* No STAT tables available */\n");
6050 }else{
6051 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6052 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6053 callback, &data, &zErrMsg);
6054 data.cMode = data.mode = MODE_Insert;
6055 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00006056 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006057 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00006058 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006059 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00006060 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006061 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6062 }
6063 }else
6064
6065 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6066 if( nArg==2 ){
6067 p->showHeader = booleanValue(azArg[1]);
6068 }else{
6069 raw_printf(stderr, "Usage: .headers on|off\n");
6070 rc = 1;
6071 }
6072 }else
6073
6074 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
6075 utf8_printf(p->out, "%s", zHelp);
6076 }else
6077
6078 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6079 char *zTable; /* Insert data into this table */
6080 char *zFile; /* Name of file to extra content from */
6081 sqlite3_stmt *pStmt = NULL; /* A statement */
6082 int nCol; /* Number of columns in the table */
6083 int nByte; /* Number of bytes in an SQL string */
6084 int i, j; /* Loop counters */
6085 int needCommit; /* True to COMMIT or ROLLBACK at end */
6086 int nSep; /* Number of bytes in p->colSeparator[] */
6087 char *zSql; /* An SQL statement */
6088 ImportCtx sCtx; /* Reader context */
6089 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6090 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
6091
6092 if( nArg!=3 ){
6093 raw_printf(stderr, "Usage: .import FILE TABLE\n");
6094 goto meta_command_exit;
6095 }
6096 zFile = azArg[1];
6097 zTable = azArg[2];
6098 seenInterrupt = 0;
6099 memset(&sCtx, 0, sizeof(sCtx));
6100 open_db(p, 0);
6101 nSep = strlen30(p->colSeparator);
6102 if( nSep==0 ){
6103 raw_printf(stderr,
6104 "Error: non-null column separator required for import\n");
6105 return 1;
6106 }
6107 if( nSep>1 ){
6108 raw_printf(stderr, "Error: multi-character column separators not allowed"
6109 " for import\n");
6110 return 1;
6111 }
6112 nSep = strlen30(p->rowSeparator);
6113 if( nSep==0 ){
6114 raw_printf(stderr, "Error: non-null row separator required for import\n");
6115 return 1;
6116 }
6117 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6118 /* When importing CSV (only), if the row separator is set to the
6119 ** default output row separator, change it to the default input
6120 ** row separator. This avoids having to maintain different input
6121 ** and output row separators. */
6122 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6123 nSep = strlen30(p->rowSeparator);
6124 }
6125 if( nSep>1 ){
6126 raw_printf(stderr, "Error: multi-character row separators not allowed"
6127 " for import\n");
6128 return 1;
6129 }
6130 sCtx.zFile = zFile;
6131 sCtx.nLine = 1;
6132 if( sCtx.zFile[0]=='|' ){
6133#ifdef SQLITE_OMIT_POPEN
6134 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6135 return 1;
6136#else
6137 sCtx.in = popen(sCtx.zFile+1, "r");
6138 sCtx.zFile = "<pipe>";
6139 xCloser = pclose;
6140#endif
6141 }else{
6142 sCtx.in = fopen(sCtx.zFile, "rb");
6143 xCloser = fclose;
6144 }
6145 if( p->mode==MODE_Ascii ){
6146 xRead = ascii_read_one_field;
6147 }else{
6148 xRead = csv_read_one_field;
6149 }
6150 if( sCtx.in==0 ){
6151 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6152 return 1;
6153 }
6154 sCtx.cColSep = p->colSeparator[0];
6155 sCtx.cRowSep = p->rowSeparator[0];
6156 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6157 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006158 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006159 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006160 }
6161 nByte = strlen30(zSql);
6162 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6163 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
6164 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6165 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6166 char cSep = '(';
6167 while( xRead(&sCtx) ){
6168 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6169 cSep = ',';
6170 if( sCtx.cTerm!=sCtx.cColSep ) break;
6171 }
6172 if( cSep=='(' ){
6173 sqlite3_free(zCreate);
6174 sqlite3_free(sCtx.z);
6175 xCloser(sCtx.in);
6176 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6177 return 1;
6178 }
6179 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6180 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6181 sqlite3_free(zCreate);
6182 if( rc ){
6183 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6184 sqlite3_errmsg(p->db));
6185 sqlite3_free(sCtx.z);
6186 xCloser(sCtx.in);
6187 return 1;
6188 }
6189 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6190 }
6191 sqlite3_free(zSql);
6192 if( rc ){
6193 if (pStmt) sqlite3_finalize(pStmt);
6194 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6195 xCloser(sCtx.in);
6196 return 1;
6197 }
6198 nCol = sqlite3_column_count(pStmt);
6199 sqlite3_finalize(pStmt);
6200 pStmt = 0;
6201 if( nCol==0 ) return 0; /* no columns, no error */
6202 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6203 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006204 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006205 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006206 }
6207 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6208 j = strlen30(zSql);
6209 for(i=1; i<nCol; i++){
6210 zSql[j++] = ',';
6211 zSql[j++] = '?';
6212 }
6213 zSql[j++] = ')';
6214 zSql[j] = 0;
6215 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6216 sqlite3_free(zSql);
6217 if( rc ){
6218 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6219 if (pStmt) sqlite3_finalize(pStmt);
6220 xCloser(sCtx.in);
6221 return 1;
6222 }
6223 needCommit = sqlite3_get_autocommit(p->db);
6224 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6225 do{
6226 int startLine = sCtx.nLine;
6227 for(i=0; i<nCol; i++){
6228 char *z = xRead(&sCtx);
6229 /*
6230 ** Did we reach end-of-file before finding any columns?
6231 ** If so, stop instead of NULL filling the remaining columns.
6232 */
6233 if( z==0 && i==0 ) break;
6234 /*
6235 ** Did we reach end-of-file OR end-of-line before finding any
6236 ** columns in ASCII mode? If so, stop instead of NULL filling
6237 ** the remaining columns.
6238 */
6239 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6240 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6241 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6242 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6243 "filling the rest with NULL\n",
6244 sCtx.zFile, startLine, nCol, i+1);
6245 i += 2;
6246 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6247 }
6248 }
6249 if( sCtx.cTerm==sCtx.cColSep ){
6250 do{
6251 xRead(&sCtx);
6252 i++;
6253 }while( sCtx.cTerm==sCtx.cColSep );
6254 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6255 "extras ignored\n",
6256 sCtx.zFile, startLine, nCol, i);
6257 }
6258 if( i>=nCol ){
6259 sqlite3_step(pStmt);
6260 rc = sqlite3_reset(pStmt);
6261 if( rc!=SQLITE_OK ){
6262 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6263 startLine, sqlite3_errmsg(p->db));
6264 }
6265 }
6266 }while( sCtx.cTerm!=EOF );
6267
6268 xCloser(sCtx.in);
6269 sqlite3_free(sCtx.z);
6270 sqlite3_finalize(pStmt);
6271 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6272 }else
6273
6274#ifndef SQLITE_UNTESTABLE
6275 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6276 char *zSql;
6277 char *zCollist = 0;
6278 sqlite3_stmt *pStmt;
6279 int tnum = 0;
6280 int i;
drh48d219a2018-04-23 18:38:48 +00006281 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6282 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6283 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00006284 rc = 1;
6285 goto meta_command_exit;
6286 }
6287 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00006288 if( nArg==2 ){
6289 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6290 goto meta_command_exit;
6291 }
drh2ce15c32017-07-11 13:34:40 +00006292 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6293 " WHERE name='%q' AND type='index'", azArg[1]);
6294 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6295 sqlite3_free(zSql);
6296 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6297 tnum = sqlite3_column_int(pStmt, 0);
6298 }
6299 sqlite3_finalize(pStmt);
6300 if( tnum==0 ){
6301 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6302 rc = 1;
6303 goto meta_command_exit;
6304 }
6305 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6306 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6307 sqlite3_free(zSql);
6308 i = 0;
6309 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6310 char zLabel[20];
6311 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6312 i++;
6313 if( zCol==0 ){
6314 if( sqlite3_column_int(pStmt,1)==-1 ){
6315 zCol = "_ROWID_";
6316 }else{
6317 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6318 zCol = zLabel;
6319 }
6320 }
6321 if( zCollist==0 ){
6322 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6323 }else{
6324 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6325 }
6326 }
6327 sqlite3_finalize(pStmt);
6328 zSql = sqlite3_mprintf(
6329 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6330 azArg[2], zCollist, zCollist);
6331 sqlite3_free(zCollist);
6332 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6333 if( rc==SQLITE_OK ){
6334 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6335 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6336 if( rc ){
6337 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6338 }else{
6339 utf8_printf(stdout, "%s;\n", zSql);
6340 raw_printf(stdout,
6341 "WARNING: writing to an imposter table will corrupt the index!\n"
6342 );
6343 }
6344 }else{
6345 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6346 rc = 1;
6347 }
6348 sqlite3_free(zSql);
6349 }else
6350#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6351
6352#ifdef SQLITE_ENABLE_IOTRACE
6353 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6354 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6355 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6356 iotrace = 0;
6357 if( nArg<2 ){
6358 sqlite3IoTrace = 0;
6359 }else if( strcmp(azArg[1], "-")==0 ){
6360 sqlite3IoTrace = iotracePrintf;
6361 iotrace = stdout;
6362 }else{
6363 iotrace = fopen(azArg[1], "w");
6364 if( iotrace==0 ){
6365 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6366 sqlite3IoTrace = 0;
6367 rc = 1;
6368 }else{
6369 sqlite3IoTrace = iotracePrintf;
6370 }
6371 }
6372 }else
6373#endif
6374
6375 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6376 static const struct {
6377 const char *zLimitName; /* Name of a limit */
6378 int limitCode; /* Integer code for that limit */
6379 } aLimit[] = {
6380 { "length", SQLITE_LIMIT_LENGTH },
6381 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6382 { "column", SQLITE_LIMIT_COLUMN },
6383 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6384 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6385 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6386 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6387 { "attached", SQLITE_LIMIT_ATTACHED },
6388 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6389 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6390 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6391 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6392 };
6393 int i, n2;
6394 open_db(p, 0);
6395 if( nArg==1 ){
6396 for(i=0; i<ArraySize(aLimit); i++){
6397 printf("%20s %d\n", aLimit[i].zLimitName,
6398 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6399 }
6400 }else if( nArg>3 ){
6401 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6402 rc = 1;
6403 goto meta_command_exit;
6404 }else{
6405 int iLimit = -1;
6406 n2 = strlen30(azArg[1]);
6407 for(i=0; i<ArraySize(aLimit); i++){
6408 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6409 if( iLimit<0 ){
6410 iLimit = i;
6411 }else{
6412 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6413 rc = 1;
6414 goto meta_command_exit;
6415 }
6416 }
6417 }
6418 if( iLimit<0 ){
6419 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6420 "enter \".limits\" with no arguments for a list.\n",
6421 azArg[1]);
6422 rc = 1;
6423 goto meta_command_exit;
6424 }
6425 if( nArg==3 ){
6426 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6427 (int)integerValue(azArg[2]));
6428 }
6429 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6430 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6431 }
6432 }else
6433
6434 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6435 open_db(p, 0);
6436 lintDotCommand(p, azArg, nArg);
6437 }else
6438
6439#ifndef SQLITE_OMIT_LOAD_EXTENSION
6440 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6441 const char *zFile, *zProc;
6442 char *zErrMsg = 0;
6443 if( nArg<2 ){
6444 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6445 rc = 1;
6446 goto meta_command_exit;
6447 }
6448 zFile = azArg[1];
6449 zProc = nArg>=3 ? azArg[2] : 0;
6450 open_db(p, 0);
6451 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6452 if( rc!=SQLITE_OK ){
6453 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6454 sqlite3_free(zErrMsg);
6455 rc = 1;
6456 }
6457 }else
6458#endif
6459
6460 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6461 if( nArg!=2 ){
6462 raw_printf(stderr, "Usage: .log FILENAME\n");
6463 rc = 1;
6464 }else{
6465 const char *zFile = azArg[1];
6466 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00006467 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00006468 }
6469 }else
6470
6471 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6472 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006473 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006474 int c2 = zMode[0];
6475 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6476 p->mode = MODE_Line;
6477 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6478 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6479 p->mode = MODE_Column;
6480 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6481 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6482 p->mode = MODE_List;
6483 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6484 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6485 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6486 p->mode = MODE_Html;
6487 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6488 p->mode = MODE_Tcl;
6489 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6490 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6491 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6492 p->mode = MODE_Csv;
6493 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6494 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6495 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6496 p->mode = MODE_List;
6497 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6498 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6499 p->mode = MODE_Insert;
6500 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6501 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6502 p->mode = MODE_Quote;
6503 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6504 p->mode = MODE_Ascii;
6505 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6506 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6507 }else if( nArg==1 ){
6508 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6509 }else{
6510 raw_printf(stderr, "Error: mode should be one of: "
6511 "ascii column csv html insert line list quote tabs tcl\n");
6512 rc = 1;
6513 }
6514 p->cMode = p->mode;
6515 }else
6516
6517 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6518 if( nArg==2 ){
6519 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6520 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6521 }else{
6522 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6523 rc = 1;
6524 }
6525 }else
6526
6527 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6528 char *zNewFilename; /* Name of the database file to open */
6529 int iName = 1; /* Index in azArg[] of the filename */
6530 int newFlag = 0; /* True to delete file before opening */
6531 /* Close the existing database */
6532 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00006533 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00006534 p->db = 0;
6535 p->zDbFilename = 0;
6536 sqlite3_free(p->zFreeOnClose);
6537 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00006538 p->openMode = SHELL_OPEN_UNSPEC;
drh2ce15c32017-07-11 13:34:40 +00006539 /* Check for command-line arguments */
6540 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6541 const char *z = azArg[iName];
6542 if( optionMatch(z,"new") ){
6543 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00006544#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00006545 }else if( optionMatch(z, "zip") ){
6546 p->openMode = SHELL_OPEN_ZIPFILE;
6547#endif
6548 }else if( optionMatch(z, "append") ){
6549 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00006550 }else if( optionMatch(z, "readonly") ){
6551 p->openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00006552 }else if( z[0]=='-' ){
6553 utf8_printf(stderr, "unknown option: %s\n", z);
6554 rc = 1;
6555 goto meta_command_exit;
6556 }
6557 }
6558 /* If a filename is specified, try to open it first */
6559 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6560 if( zNewFilename ){
6561 if( newFlag ) shellDeleteFile(zNewFilename);
6562 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00006563 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00006564 if( p->db==0 ){
6565 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6566 sqlite3_free(zNewFilename);
6567 }else{
6568 p->zFreeOnClose = zNewFilename;
6569 }
6570 }
6571 if( p->db==0 ){
6572 /* As a fall-back open a TEMP database */
6573 p->zDbFilename = 0;
6574 open_db(p, 0);
6575 }
6576 }else
6577
drh13c20932018-01-10 21:41:55 +00006578 if( (c=='o'
6579 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
6580 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00006581 ){
6582 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00006583 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00006584 if( azArg[0][0]=='e' ){
6585 /* Transform the ".excel" command into ".once -x" */
6586 nArg = 2;
6587 azArg[0] = "once";
6588 zFile = azArg[1] = "-x";
6589 n = 4;
6590 }
drh2ce15c32017-07-11 13:34:40 +00006591 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00006592 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00006593 rc = 1;
6594 goto meta_command_exit;
6595 }
6596 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6597 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00006598 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00006599 rc = 1;
6600 goto meta_command_exit;
6601 }
6602 p->outCount = 2;
6603 }else{
6604 p->outCount = 0;
6605 }
6606 output_reset(p);
drh13c20932018-01-10 21:41:55 +00006607 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00006608#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00006609 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00006610 p->doXdgOpen = 1;
6611 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00006612 if( zFile[1]=='x' ){
6613 newTempFile(p, "csv");
6614 p->mode = MODE_Csv;
6615 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6616 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6617 }else{
6618 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00006619 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00006620 }
6621 zFile = p->zTempFile;
6622 }
drh04a28c32018-01-31 01:38:44 +00006623#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00006624 if( zFile[0]=='|' ){
6625#ifdef SQLITE_OMIT_POPEN
6626 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6627 rc = 1;
6628 p->out = stdout;
6629#else
6630 p->out = popen(zFile + 1, "w");
6631 if( p->out==0 ){
6632 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6633 p->out = stdout;
6634 rc = 1;
6635 }else{
6636 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6637 }
6638#endif
6639 }else{
drha92a01a2018-01-10 22:15:37 +00006640 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00006641 if( p->out==0 ){
6642 if( strcmp(zFile,"off")!=0 ){
6643 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6644 }
6645 p->out = stdout;
6646 rc = 1;
6647 } else {
6648 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6649 }
6650 }
6651 }else
6652
6653 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6654 int i;
6655 for(i=1; i<nArg; i++){
6656 if( i>1 ) raw_printf(p->out, " ");
6657 utf8_printf(p->out, "%s", azArg[i]);
6658 }
6659 raw_printf(p->out, "\n");
6660 }else
6661
6662 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6663 if( nArg >= 2) {
6664 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6665 }
6666 if( nArg >= 3) {
6667 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6668 }
6669 }else
6670
6671 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6672 rc = 2;
6673 }else
6674
6675 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6676 FILE *alt;
6677 if( nArg!=2 ){
6678 raw_printf(stderr, "Usage: .read FILE\n");
6679 rc = 1;
6680 goto meta_command_exit;
6681 }
6682 alt = fopen(azArg[1], "rb");
6683 if( alt==0 ){
6684 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6685 rc = 1;
6686 }else{
6687 rc = process_input(p, alt);
6688 fclose(alt);
6689 }
6690 }else
6691
6692 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6693 const char *zSrcFile;
6694 const char *zDb;
6695 sqlite3 *pSrc;
6696 sqlite3_backup *pBackup;
6697 int nTimeout = 0;
6698
6699 if( nArg==2 ){
6700 zSrcFile = azArg[1];
6701 zDb = "main";
6702 }else if( nArg==3 ){
6703 zSrcFile = azArg[2];
6704 zDb = azArg[1];
6705 }else{
6706 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6707 rc = 1;
6708 goto meta_command_exit;
6709 }
6710 rc = sqlite3_open(zSrcFile, &pSrc);
6711 if( rc!=SQLITE_OK ){
6712 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00006713 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006714 return 1;
6715 }
6716 open_db(p, 0);
6717 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6718 if( pBackup==0 ){
6719 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00006720 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006721 return 1;
6722 }
6723 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6724 || rc==SQLITE_BUSY ){
6725 if( rc==SQLITE_BUSY ){
6726 if( nTimeout++ >= 3 ) break;
6727 sqlite3_sleep(100);
6728 }
6729 }
6730 sqlite3_backup_finish(pBackup);
6731 if( rc==SQLITE_DONE ){
6732 rc = 0;
6733 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6734 raw_printf(stderr, "Error: source database is busy\n");
6735 rc = 1;
6736 }else{
6737 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6738 rc = 1;
6739 }
drh9e804032018-05-18 17:11:50 +00006740 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006741 }else
6742
drh2ce15c32017-07-11 13:34:40 +00006743 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6744 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00006745 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006746#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6747 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6748#endif
6749 }else{
6750 raw_printf(stderr, "Usage: .scanstats on|off\n");
6751 rc = 1;
6752 }
6753 }else
6754
6755 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6756 ShellText sSelect;
6757 ShellState data;
6758 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006759 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006760 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006761 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006762 int bDebug = 0;
6763 int ii;
drh2ce15c32017-07-11 13:34:40 +00006764
6765 open_db(p, 0);
6766 memcpy(&data, p, sizeof(data));
6767 data.showHeader = 0;
6768 data.cMode = data.mode = MODE_Semi;
6769 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006770 for(ii=1; ii<nArg; ii++){
6771 if( optionMatch(azArg[ii],"indent") ){
6772 data.cMode = data.mode = MODE_Pretty;
6773 }else if( optionMatch(azArg[ii],"debug") ){
6774 bDebug = 1;
6775 }else if( zName==0 ){
6776 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006777 }else{
drhceba7922018-01-01 21:28:25 +00006778 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6779 rc = 1;
6780 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006781 }
drh2ce15c32017-07-11 13:34:40 +00006782 }
drhceba7922018-01-01 21:28:25 +00006783 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00006784 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
6785 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00006786 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006787 new_argv[0] = sqlite3_mprintf(
6788 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006789 " type text,\n"
6790 " name text,\n"
6791 " tbl_name text,\n"
6792 " rootpage integer,\n"
6793 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006794 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006795 new_argv[1] = 0;
6796 new_colv[0] = "sql";
6797 new_colv[1] = 0;
6798 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006799 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006800 }
drh2ce15c32017-07-11 13:34:40 +00006801 }
6802 if( zDiv ){
6803 sqlite3_stmt *pStmt = 0;
6804 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6805 -1, &pStmt, 0);
6806 if( rc ){
6807 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6808 sqlite3_finalize(pStmt);
6809 rc = 1;
6810 goto meta_command_exit;
6811 }
6812 appendText(&sSelect, "SELECT sql FROM", 0);
6813 iSchema = 0;
6814 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6815 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6816 char zScNum[30];
6817 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6818 appendText(&sSelect, zDiv, 0);
6819 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006820 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6821 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006822 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006823 }else{
drhceba7922018-01-01 21:28:25 +00006824 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006825 }
drhceba7922018-01-01 21:28:25 +00006826 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6827 appendText(&sSelect, zScNum, 0);
6828 appendText(&sSelect, " AS snum, ", 0);
6829 appendText(&sSelect, zDb, '\'');
6830 appendText(&sSelect, " AS sname FROM ", 0);
6831 appendText(&sSelect, zDb, '"');
6832 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006833 }
6834 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006835#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006836 if( zName ){
6837 appendText(&sSelect,
6838 " UNION ALL SELECT shell_module_schema(name),"
6839 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6840 }
drhcde7b772018-01-02 12:50:40 +00006841#endif
drh2ce15c32017-07-11 13:34:40 +00006842 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006843 if( zName ){
6844 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00006845 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
6846 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00006847 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006848 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6849 }else{
6850 appendText(&sSelect, "lower(tbl_name)", 0);
6851 }
mistachkin9d107262018-03-23 14:24:34 +00006852 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006853 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00006854 if( !bGlob ){
6855 appendText(&sSelect, " ESCAPE '\\' ", 0);
6856 }
drh2ce15c32017-07-11 13:34:40 +00006857 appendText(&sSelect, " AND ", 0);
6858 sqlite3_free(zQarg);
6859 }
6860 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6861 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006862 if( bDebug ){
6863 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6864 }else{
6865 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6866 }
drh2ce15c32017-07-11 13:34:40 +00006867 freeText(&sSelect);
6868 }
6869 if( zErrMsg ){
6870 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6871 sqlite3_free(zErrMsg);
6872 rc = 1;
6873 }else if( rc != SQLITE_OK ){
6874 raw_printf(stderr,"Error: querying schema information\n");
6875 rc = 1;
6876 }else{
6877 rc = 0;
6878 }
6879 }else
6880
6881#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6882 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6883 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6884 }else
6885#endif
6886
6887#if defined(SQLITE_ENABLE_SESSION)
6888 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6889 OpenSession *pSession = &p->aSession[0];
6890 char **azCmd = &azArg[1];
6891 int iSes = 0;
6892 int nCmd = nArg - 1;
6893 int i;
6894 if( nArg<=1 ) goto session_syntax_error;
6895 open_db(p, 0);
6896 if( nArg>=3 ){
6897 for(iSes=0; iSes<p->nSession; iSes++){
6898 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6899 }
6900 if( iSes<p->nSession ){
6901 pSession = &p->aSession[iSes];
6902 azCmd++;
6903 nCmd--;
6904 }else{
6905 pSession = &p->aSession[0];
6906 iSes = 0;
6907 }
6908 }
6909
6910 /* .session attach TABLE
6911 ** Invoke the sqlite3session_attach() interface to attach a particular
6912 ** table so that it is never filtered.
6913 */
6914 if( strcmp(azCmd[0],"attach")==0 ){
6915 if( nCmd!=2 ) goto session_syntax_error;
6916 if( pSession->p==0 ){
6917 session_not_open:
6918 raw_printf(stderr, "ERROR: No sessions are open\n");
6919 }else{
6920 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6921 if( rc ){
6922 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6923 rc = 0;
6924 }
6925 }
6926 }else
6927
6928 /* .session changeset FILE
6929 ** .session patchset FILE
6930 ** Write a changeset or patchset into a file. The file is overwritten.
6931 */
6932 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6933 FILE *out = 0;
6934 if( nCmd!=2 ) goto session_syntax_error;
6935 if( pSession->p==0 ) goto session_not_open;
6936 out = fopen(azCmd[1], "wb");
6937 if( out==0 ){
6938 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6939 }else{
6940 int szChng;
6941 void *pChng;
6942 if( azCmd[0][0]=='c' ){
6943 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6944 }else{
6945 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6946 }
6947 if( rc ){
6948 printf("Error: error code %d\n", rc);
6949 rc = 0;
6950 }
6951 if( pChng
6952 && fwrite(pChng, szChng, 1, out)!=1 ){
6953 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6954 szChng);
6955 }
6956 sqlite3_free(pChng);
6957 fclose(out);
6958 }
6959 }else
6960
6961 /* .session close
6962 ** Close the identified session
6963 */
6964 if( strcmp(azCmd[0], "close")==0 ){
6965 if( nCmd!=1 ) goto session_syntax_error;
6966 if( p->nSession ){
6967 session_close(pSession);
6968 p->aSession[iSes] = p->aSession[--p->nSession];
6969 }
6970 }else
6971
6972 /* .session enable ?BOOLEAN?
6973 ** Query or set the enable flag
6974 */
6975 if( strcmp(azCmd[0], "enable")==0 ){
6976 int ii;
6977 if( nCmd>2 ) goto session_syntax_error;
6978 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6979 if( p->nSession ){
6980 ii = sqlite3session_enable(pSession->p, ii);
6981 utf8_printf(p->out, "session %s enable flag = %d\n",
6982 pSession->zName, ii);
6983 }
6984 }else
6985
6986 /* .session filter GLOB ....
6987 ** Set a list of GLOB patterns of table names to be excluded.
6988 */
6989 if( strcmp(azCmd[0], "filter")==0 ){
6990 int ii, nByte;
6991 if( nCmd<2 ) goto session_syntax_error;
6992 if( p->nSession ){
6993 for(ii=0; ii<pSession->nFilter; ii++){
6994 sqlite3_free(pSession->azFilter[ii]);
6995 }
6996 sqlite3_free(pSession->azFilter);
6997 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6998 pSession->azFilter = sqlite3_malloc( nByte );
6999 if( pSession->azFilter==0 ){
7000 raw_printf(stderr, "Error: out or memory\n");
7001 exit(1);
7002 }
7003 for(ii=1; ii<nCmd; ii++){
7004 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
7005 }
7006 pSession->nFilter = ii-1;
7007 }
7008 }else
7009
7010 /* .session indirect ?BOOLEAN?
7011 ** Query or set the indirect flag
7012 */
7013 if( strcmp(azCmd[0], "indirect")==0 ){
7014 int ii;
7015 if( nCmd>2 ) goto session_syntax_error;
7016 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7017 if( p->nSession ){
7018 ii = sqlite3session_indirect(pSession->p, ii);
7019 utf8_printf(p->out, "session %s indirect flag = %d\n",
7020 pSession->zName, ii);
7021 }
7022 }else
7023
7024 /* .session isempty
7025 ** Determine if the session is empty
7026 */
7027 if( strcmp(azCmd[0], "isempty")==0 ){
7028 int ii;
7029 if( nCmd!=1 ) goto session_syntax_error;
7030 if( p->nSession ){
7031 ii = sqlite3session_isempty(pSession->p);
7032 utf8_printf(p->out, "session %s isempty flag = %d\n",
7033 pSession->zName, ii);
7034 }
7035 }else
7036
7037 /* .session list
7038 ** List all currently open sessions
7039 */
7040 if( strcmp(azCmd[0],"list")==0 ){
7041 for(i=0; i<p->nSession; i++){
7042 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7043 }
7044 }else
7045
7046 /* .session open DB NAME
7047 ** Open a new session called NAME on the attached database DB.
7048 ** DB is normally "main".
7049 */
7050 if( strcmp(azCmd[0],"open")==0 ){
7051 char *zName;
7052 if( nCmd!=3 ) goto session_syntax_error;
7053 zName = azCmd[2];
7054 if( zName[0]==0 ) goto session_syntax_error;
7055 for(i=0; i<p->nSession; i++){
7056 if( strcmp(p->aSession[i].zName,zName)==0 ){
7057 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7058 goto meta_command_exit;
7059 }
7060 }
7061 if( p->nSession>=ArraySize(p->aSession) ){
7062 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7063 goto meta_command_exit;
7064 }
7065 pSession = &p->aSession[p->nSession];
7066 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7067 if( rc ){
7068 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7069 rc = 0;
7070 goto meta_command_exit;
7071 }
7072 pSession->nFilter = 0;
7073 sqlite3session_table_filter(pSession->p, session_filter, pSession);
7074 p->nSession++;
7075 pSession->zName = sqlite3_mprintf("%s", zName);
7076 }else
7077 /* If no command name matches, show a syntax error */
7078 session_syntax_error:
7079 session_help(p);
7080 }else
7081#endif
7082
7083#ifdef SQLITE_DEBUG
7084 /* Undocumented commands for internal testing. Subject to change
7085 ** without notice. */
7086 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7087 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7088 int i, v;
7089 for(i=1; i<nArg; i++){
7090 v = booleanValue(azArg[i]);
7091 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7092 }
7093 }
7094 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7095 int i; sqlite3_int64 v;
7096 for(i=1; i<nArg; i++){
7097 char zBuf[200];
7098 v = integerValue(azArg[i]);
7099 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7100 utf8_printf(p->out, "%s", zBuf);
7101 }
7102 }
7103 }else
7104#endif
7105
7106 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7107 int bIsInit = 0; /* True to initialize the SELFTEST table */
7108 int bVerbose = 0; /* Verbose output */
7109 int bSelftestExists; /* True if SELFTEST already exists */
7110 int i, k; /* Loop counters */
7111 int nTest = 0; /* Number of tests runs */
7112 int nErr = 0; /* Number of errors seen */
7113 ShellText str; /* Answer for a query */
7114 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7115
7116 open_db(p,0);
7117 for(i=1; i<nArg; i++){
7118 const char *z = azArg[i];
7119 if( z[0]=='-' && z[1]=='-' ) z++;
7120 if( strcmp(z,"-init")==0 ){
7121 bIsInit = 1;
7122 }else
7123 if( strcmp(z,"-v")==0 ){
7124 bVerbose++;
7125 }else
7126 {
7127 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7128 azArg[i], azArg[0]);
7129 raw_printf(stderr, "Should be one of: --init -v\n");
7130 rc = 1;
7131 goto meta_command_exit;
7132 }
7133 }
7134 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7135 != SQLITE_OK ){
7136 bSelftestExists = 0;
7137 }else{
7138 bSelftestExists = 1;
7139 }
7140 if( bIsInit ){
7141 createSelftestTable(p);
7142 bSelftestExists = 1;
7143 }
7144 initText(&str);
7145 appendText(&str, "x", 0);
7146 for(k=bSelftestExists; k>=0; k--){
7147 if( k==1 ){
7148 rc = sqlite3_prepare_v2(p->db,
7149 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7150 -1, &pStmt, 0);
7151 }else{
7152 rc = sqlite3_prepare_v2(p->db,
7153 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7154 " (1,'run','PRAGMA integrity_check','ok')",
7155 -1, &pStmt, 0);
7156 }
7157 if( rc ){
7158 raw_printf(stderr, "Error querying the selftest table\n");
7159 rc = 1;
7160 sqlite3_finalize(pStmt);
7161 goto meta_command_exit;
7162 }
7163 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7164 int tno = sqlite3_column_int(pStmt, 0);
7165 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7166 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7167 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7168
7169 k = 0;
7170 if( bVerbose>0 ){
7171 char *zQuote = sqlite3_mprintf("%q", zSql);
7172 printf("%d: %s %s\n", tno, zOp, zSql);
7173 sqlite3_free(zQuote);
7174 }
7175 if( strcmp(zOp,"memo")==0 ){
7176 utf8_printf(p->out, "%s\n", zSql);
7177 }else
7178 if( strcmp(zOp,"run")==0 ){
7179 char *zErrMsg = 0;
7180 str.n = 0;
7181 str.z[0] = 0;
7182 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7183 nTest++;
7184 if( bVerbose ){
7185 utf8_printf(p->out, "Result: %s\n", str.z);
7186 }
7187 if( rc || zErrMsg ){
7188 nErr++;
7189 rc = 1;
7190 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7191 sqlite3_free(zErrMsg);
7192 }else if( strcmp(zAns,str.z)!=0 ){
7193 nErr++;
7194 rc = 1;
7195 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7196 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7197 }
7198 }else
7199 {
7200 utf8_printf(stderr,
7201 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7202 rc = 1;
7203 break;
7204 }
7205 } /* End loop over rows of content from SELFTEST */
7206 sqlite3_finalize(pStmt);
7207 } /* End loop over k */
7208 freeText(&str);
7209 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7210 }else
7211
7212 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7213 if( nArg<2 || nArg>3 ){
7214 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7215 rc = 1;
7216 }
7217 if( nArg>=2 ){
7218 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7219 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7220 }
7221 if( nArg>=3 ){
7222 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7223 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7224 }
7225 }else
7226
7227 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7228 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7229 int i; /* Loop counter */
7230 int bSchema = 0; /* Also hash the schema */
7231 int bSeparate = 0; /* Hash each table separately */
7232 int iSize = 224; /* Hash algorithm to use */
7233 int bDebug = 0; /* Only show the query that would have run */
7234 sqlite3_stmt *pStmt; /* For querying tables names */
7235 char *zSql; /* SQL to be run */
7236 char *zSep; /* Separator */
7237 ShellText sSql; /* Complete SQL for the query to run the hash */
7238 ShellText sQuery; /* Set of queries used to read all content */
7239 open_db(p, 0);
7240 for(i=1; i<nArg; i++){
7241 const char *z = azArg[i];
7242 if( z[0]=='-' ){
7243 z++;
7244 if( z[0]=='-' ) z++;
7245 if( strcmp(z,"schema")==0 ){
7246 bSchema = 1;
7247 }else
7248 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7249 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7250 ){
7251 iSize = atoi(&z[5]);
7252 }else
7253 if( strcmp(z,"debug")==0 ){
7254 bDebug = 1;
7255 }else
7256 {
7257 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7258 azArg[i], azArg[0]);
7259 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00007260 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00007261 rc = 1;
7262 goto meta_command_exit;
7263 }
7264 }else if( zLike ){
7265 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7266 rc = 1;
7267 goto meta_command_exit;
7268 }else{
7269 zLike = z;
7270 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00007271 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00007272 }
7273 }
7274 if( bSchema ){
7275 zSql = "SELECT lower(name) FROM sqlite_master"
7276 " WHERE type='table' AND coalesce(rootpage,0)>1"
7277 " UNION ALL SELECT 'sqlite_master'"
7278 " ORDER BY 1 collate nocase";
7279 }else{
7280 zSql = "SELECT lower(name) FROM sqlite_master"
7281 " WHERE type='table' AND coalesce(rootpage,0)>1"
7282 " AND name NOT LIKE 'sqlite_%'"
7283 " ORDER BY 1 collate nocase";
7284 }
7285 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7286 initText(&sQuery);
7287 initText(&sSql);
7288 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7289 zSep = "VALUES(";
7290 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7291 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7292 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7293 if( strncmp(zTab, "sqlite_",7)!=0 ){
7294 appendText(&sQuery,"SELECT * FROM ", 0);
7295 appendText(&sQuery,zTab,'"');
7296 appendText(&sQuery," NOT INDEXED;", 0);
7297 }else if( strcmp(zTab, "sqlite_master")==0 ){
7298 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7299 " ORDER BY name;", 0);
7300 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7301 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7302 " ORDER BY name;", 0);
7303 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7304 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7305 " ORDER BY tbl,idx;", 0);
7306 }else if( strcmp(zTab, "sqlite_stat3")==0
7307 || strcmp(zTab, "sqlite_stat4")==0 ){
7308 appendText(&sQuery, "SELECT * FROM ", 0);
7309 appendText(&sQuery, zTab, 0);
7310 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7311 }
7312 appendText(&sSql, zSep, 0);
7313 appendText(&sSql, sQuery.z, '\'');
7314 sQuery.n = 0;
7315 appendText(&sSql, ",", 0);
7316 appendText(&sSql, zTab, '\'');
7317 zSep = "),(";
7318 }
7319 sqlite3_finalize(pStmt);
7320 if( bSeparate ){
7321 zSql = sqlite3_mprintf(
7322 "%s))"
7323 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7324 " FROM [sha3sum$query]",
7325 sSql.z, iSize);
7326 }else{
7327 zSql = sqlite3_mprintf(
7328 "%s))"
7329 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7330 " FROM [sha3sum$query]",
7331 sSql.z, iSize);
7332 }
7333 freeText(&sQuery);
7334 freeText(&sSql);
7335 if( bDebug ){
7336 utf8_printf(p->out, "%s\n", zSql);
7337 }else{
drha10b9992018-03-09 15:24:33 +00007338 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00007339 }
7340 sqlite3_free(zSql);
7341 }else
7342
drh04a28c32018-01-31 01:38:44 +00007343#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00007344 if( c=='s'
7345 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7346 ){
7347 char *zCmd;
7348 int i, x;
7349 if( nArg<2 ){
7350 raw_printf(stderr, "Usage: .system COMMAND\n");
7351 rc = 1;
7352 goto meta_command_exit;
7353 }
7354 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7355 for(i=2; i<nArg; i++){
7356 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7357 zCmd, azArg[i]);
7358 }
7359 x = system(zCmd);
7360 sqlite3_free(zCmd);
7361 if( x ) raw_printf(stderr, "System command returns %d\n", x);
7362 }else
drh04a28c32018-01-31 01:38:44 +00007363#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00007364
7365 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00007366 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00007367 int i;
7368 if( nArg!=1 ){
7369 raw_printf(stderr, "Usage: .show\n");
7370 rc = 1;
7371 goto meta_command_exit;
7372 }
7373 utf8_printf(p->out, "%12.12s: %s\n","echo",
7374 azBool[ShellHasFlag(p, SHFLG_Echo)]);
7375 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7376 utf8_printf(p->out, "%12.12s: %s\n","explain",
7377 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7378 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7379 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7380 utf8_printf(p->out, "%12.12s: ", "nullvalue");
7381 output_c_string(p->out, p->nullValue);
7382 raw_printf(p->out, "\n");
7383 utf8_printf(p->out,"%12.12s: %s\n","output",
7384 strlen30(p->outfile) ? p->outfile : "stdout");
7385 utf8_printf(p->out,"%12.12s: ", "colseparator");
7386 output_c_string(p->out, p->colSeparator);
7387 raw_printf(p->out, "\n");
7388 utf8_printf(p->out,"%12.12s: ", "rowseparator");
7389 output_c_string(p->out, p->rowSeparator);
7390 raw_printf(p->out, "\n");
7391 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7392 utf8_printf(p->out, "%12.12s: ", "width");
7393 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
7394 raw_printf(p->out, "%d ", p->colWidth[i]);
7395 }
7396 raw_printf(p->out, "\n");
7397 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7398 p->zDbFilename ? p->zDbFilename : "");
7399 }else
7400
7401 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7402 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007403 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007404 }else if( nArg==1 ){
7405 display_stats(p->db, p, 0);
7406 }else{
7407 raw_printf(stderr, "Usage: .stats ?on|off?\n");
7408 rc = 1;
7409 }
7410 }else
7411
7412 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7413 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7414 || strncmp(azArg[0], "indexes", n)==0) )
7415 ){
7416 sqlite3_stmt *pStmt;
7417 char **azResult;
7418 int nRow, nAlloc;
7419 int ii;
7420 ShellText s;
7421 initText(&s);
7422 open_db(p, 0);
7423 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00007424 if( rc ){
7425 sqlite3_finalize(pStmt);
7426 return shellDatabaseError(p->db);
7427 }
drh2ce15c32017-07-11 13:34:40 +00007428
7429 if( nArg>2 && c=='i' ){
7430 /* It is an historical accident that the .indexes command shows an error
7431 ** when called with the wrong number of arguments whereas the .tables
7432 ** command does not. */
7433 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7434 rc = 1;
drh9e804032018-05-18 17:11:50 +00007435 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00007436 goto meta_command_exit;
7437 }
7438 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
7439 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
7440 if( zDbName==0 ) continue;
7441 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7442 if( sqlite3_stricmp(zDbName, "main")==0 ){
7443 appendText(&s, "SELECT name FROM ", 0);
7444 }else{
7445 appendText(&s, "SELECT ", 0);
7446 appendText(&s, zDbName, '\'');
7447 appendText(&s, "||'.'||name FROM ", 0);
7448 }
7449 appendText(&s, zDbName, '"');
7450 appendText(&s, ".sqlite_master ", 0);
7451 if( c=='t' ){
7452 appendText(&s," WHERE type IN ('table','view')"
7453 " AND name NOT LIKE 'sqlite_%'"
7454 " AND name LIKE ?1", 0);
7455 }else{
7456 appendText(&s," WHERE type='index'"
7457 " AND tbl_name LIKE ?1", 0);
7458 }
7459 }
7460 rc = sqlite3_finalize(pStmt);
7461 appendText(&s, " ORDER BY 1", 0);
7462 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7463 freeText(&s);
7464 if( rc ) return shellDatabaseError(p->db);
7465
7466 /* Run the SQL statement prepared by the above block. Store the results
7467 ** as an array of nul-terminated strings in azResult[]. */
7468 nRow = nAlloc = 0;
7469 azResult = 0;
7470 if( nArg>1 ){
7471 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
7472 }else{
7473 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7474 }
7475 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7476 if( nRow>=nAlloc ){
7477 char **azNew;
7478 int n2 = nAlloc*2 + 10;
7479 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00007480 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007481 nAlloc = n2;
7482 azResult = azNew;
7483 }
7484 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00007485 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007486 nRow++;
7487 }
7488 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7489 rc = shellDatabaseError(p->db);
7490 }
7491
7492 /* Pretty-print the contents of array azResult[] to the output */
7493 if( rc==0 && nRow>0 ){
7494 int len, maxlen = 0;
7495 int i, j;
7496 int nPrintCol, nPrintRow;
7497 for(i=0; i<nRow; i++){
7498 len = strlen30(azResult[i]);
7499 if( len>maxlen ) maxlen = len;
7500 }
7501 nPrintCol = 80/(maxlen+2);
7502 if( nPrintCol<1 ) nPrintCol = 1;
7503 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7504 for(i=0; i<nPrintRow; i++){
7505 for(j=i; j<nRow; j+=nPrintRow){
7506 char *zSp = j<nPrintRow ? "" : " ";
7507 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7508 azResult[j] ? azResult[j]:"");
7509 }
7510 raw_printf(p->out, "\n");
7511 }
7512 }
7513
7514 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7515 sqlite3_free(azResult);
7516 }else
7517
7518 /* Begin redirecting output to the file "testcase-out.txt" */
7519 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7520 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00007521 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00007522 if( p->out==0 ){
7523 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7524 }
7525 if( nArg>=2 ){
7526 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7527 }else{
7528 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7529 }
7530 }else
7531
7532#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00007533 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007534 static const struct {
7535 const char *zCtrlName; /* Name of a test-control option */
7536 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00007537 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00007538 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00007539 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7540 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7541 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7542 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7543 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7544 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7545 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drhef302e82017-11-15 19:14:08 +00007546 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7547 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7548 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00007549#ifdef YYCOVERAGE
7550 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7551#endif
drhef302e82017-11-15 19:14:08 +00007552 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7553 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7554 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7555 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7556 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00007557 };
7558 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00007559 int iCtrl = -1;
7560 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7561 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00007562 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00007563 const char *zCmd = 0;
7564
drh2ce15c32017-07-11 13:34:40 +00007565 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00007566 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00007567
7568 /* The argument can optionally begin with "-" or "--" */
7569 if( zCmd[0]=='-' && zCmd[1] ){
7570 zCmd++;
7571 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7572 }
7573
7574 /* --help lists all test-controls */
7575 if( strcmp(zCmd,"help")==0 ){
7576 utf8_printf(p->out, "Available test-controls:\n");
7577 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00007578 utf8_printf(p->out, " .testctrl %s %s\n",
7579 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00007580 }
7581 rc = 1;
7582 goto meta_command_exit;
7583 }
drh2ce15c32017-07-11 13:34:40 +00007584
7585 /* convert testctrl text option to value. allow any unique prefix
7586 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00007587 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007588 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007589 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007590 if( testctrl<0 ){
7591 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007592 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007593 }else{
drh35f51a42017-11-15 17:07:22 +00007594 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7595 "Use \".testctrl --help\" for help\n", zCmd);
7596 rc = 1;
7597 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007598 }
7599 }
7600 }
drhef302e82017-11-15 19:14:08 +00007601 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007602 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7603 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007604 }else{
7605 switch(testctrl){
7606
7607 /* sqlite3_test_control(int, db, int) */
7608 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7609 case SQLITE_TESTCTRL_RESERVE:
7610 if( nArg==3 ){
7611 int opt = (int)strtol(azArg[2], 0, 0);
7612 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007613 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007614 }
7615 break;
7616
7617 /* sqlite3_test_control(int) */
7618 case SQLITE_TESTCTRL_PRNG_SAVE:
7619 case SQLITE_TESTCTRL_PRNG_RESTORE:
7620 case SQLITE_TESTCTRL_PRNG_RESET:
7621 case SQLITE_TESTCTRL_BYTEORDER:
7622 if( nArg==2 ){
7623 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007624 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007625 }
7626 break;
7627
7628 /* sqlite3_test_control(int, uint) */
7629 case SQLITE_TESTCTRL_PENDING_BYTE:
7630 if( nArg==3 ){
7631 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7632 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007633 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007634 }
7635 break;
7636
7637 /* sqlite3_test_control(int, int) */
7638 case SQLITE_TESTCTRL_ASSERT:
7639 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007640 if( nArg==3 ){
7641 int opt = booleanValue(azArg[2]);
7642 rc2 = sqlite3_test_control(testctrl, opt);
7643 isOk = 1;
7644 }
7645 break;
7646
7647 /* sqlite3_test_control(int, int) */
7648 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007649 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7650 if( nArg==3 ){
7651 int opt = booleanValue(azArg[2]);
7652 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007653 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007654 }
7655 break;
7656
drh2ce15c32017-07-11 13:34:40 +00007657 case SQLITE_TESTCTRL_IMPOSTER:
7658 if( nArg==5 ){
7659 rc2 = sqlite3_test_control(testctrl, p->db,
7660 azArg[2],
7661 integerValue(azArg[3]),
7662 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007663 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007664 }
7665 break;
drh0d9de992017-12-26 18:04:23 +00007666
7667#ifdef YYCOVERAGE
7668 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7669 if( nArg==2 ){
7670 sqlite3_test_control(testctrl, p->out);
7671 isOk = 3;
7672 }
7673#endif
drh2ce15c32017-07-11 13:34:40 +00007674 }
7675 }
drhef302e82017-11-15 19:14:08 +00007676 if( isOk==0 && iCtrl>=0 ){
7677 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7678 rc = 1;
7679 }else if( isOk==1 ){
7680 raw_printf(p->out, "%d\n", rc2);
7681 }else if( isOk==2 ){
7682 raw_printf(p->out, "0x%08x\n", rc2);
7683 }
drh2ce15c32017-07-11 13:34:40 +00007684 }else
7685#endif /* !defined(SQLITE_UNTESTABLE) */
7686
7687 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7688 open_db(p, 0);
7689 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7690 }else
7691
7692 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7693 if( nArg==2 ){
7694 enableTimer = booleanValue(azArg[1]);
7695 if( enableTimer && !HAS_TIMER ){
7696 raw_printf(stderr, "Error: timer not available on this system.\n");
7697 enableTimer = 0;
7698 }
7699 }else{
7700 raw_printf(stderr, "Usage: .timer on|off\n");
7701 rc = 1;
7702 }
7703 }else
7704
7705 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7706 open_db(p, 0);
7707 if( nArg!=2 ){
7708 raw_printf(stderr, "Usage: .trace FILE|off\n");
7709 rc = 1;
7710 goto meta_command_exit;
7711 }
7712 output_file_close(p->traceOut);
drha92a01a2018-01-10 22:15:37 +00007713 p->traceOut = output_file_open(azArg[1], 0);
drh2ce15c32017-07-11 13:34:40 +00007714#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7715 if( p->traceOut==0 ){
7716 sqlite3_trace_v2(p->db, 0, 0, 0);
7717 }else{
7718 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7719 }
7720#endif
7721 }else
7722
7723#if SQLITE_USER_AUTHENTICATION
7724 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7725 if( nArg<2 ){
7726 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7727 rc = 1;
7728 goto meta_command_exit;
7729 }
7730 open_db(p, 0);
7731 if( strcmp(azArg[1],"login")==0 ){
7732 if( nArg!=4 ){
7733 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7734 rc = 1;
7735 goto meta_command_exit;
7736 }
drhaf2770f2018-01-05 14:55:43 +00007737 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007738 if( rc ){
7739 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7740 rc = 1;
7741 }
7742 }else if( strcmp(azArg[1],"add")==0 ){
7743 if( nArg!=5 ){
7744 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7745 rc = 1;
7746 goto meta_command_exit;
7747 }
drhaf2770f2018-01-05 14:55:43 +00007748 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007749 booleanValue(azArg[4]));
7750 if( rc ){
7751 raw_printf(stderr, "User-Add failed: %d\n", rc);
7752 rc = 1;
7753 }
7754 }else if( strcmp(azArg[1],"edit")==0 ){
7755 if( nArg!=5 ){
7756 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7757 rc = 1;
7758 goto meta_command_exit;
7759 }
drhaf2770f2018-01-05 14:55:43 +00007760 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007761 booleanValue(azArg[4]));
7762 if( rc ){
7763 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7764 rc = 1;
7765 }
7766 }else if( strcmp(azArg[1],"delete")==0 ){
7767 if( nArg!=3 ){
7768 raw_printf(stderr, "Usage: .user delete USER\n");
7769 rc = 1;
7770 goto meta_command_exit;
7771 }
7772 rc = sqlite3_user_delete(p->db, azArg[2]);
7773 if( rc ){
7774 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7775 rc = 1;
7776 }
7777 }else{
7778 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7779 rc = 1;
7780 goto meta_command_exit;
7781 }
7782 }else
7783#endif /* SQLITE_USER_AUTHENTICATION */
7784
7785 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7786 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7787 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00007788#if SQLITE_HAVE_ZLIB
7789 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
7790#endif
7791#define CTIMEOPT_VAL_(opt) #opt
7792#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7793#if defined(__clang__) && defined(__clang_major__)
7794 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
7795 CTIMEOPT_VAL(__clang_minor__) "."
7796 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
7797#elif defined(_MSC_VER)
7798 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
7799#elif defined(__GNUC__) && defined(__VERSION__)
7800 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
7801#endif
drh2ce15c32017-07-11 13:34:40 +00007802 }else
7803
7804 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7805 const char *zDbName = nArg==2 ? azArg[1] : "main";
7806 sqlite3_vfs *pVfs = 0;
7807 if( p->db ){
7808 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7809 if( pVfs ){
7810 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7811 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7812 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7813 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7814 }
7815 }
7816 }else
7817
7818 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7819 sqlite3_vfs *pVfs;
7820 sqlite3_vfs *pCurrent = 0;
7821 if( p->db ){
7822 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7823 }
7824 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7825 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7826 pVfs==pCurrent ? " <--- CURRENT" : "");
7827 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7828 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7829 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7830 if( pVfs->pNext ){
7831 raw_printf(p->out, "-----------------------------------\n");
7832 }
7833 }
7834 }else
7835
7836 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7837 const char *zDbName = nArg==2 ? azArg[1] : "main";
7838 char *zVfsName = 0;
7839 if( p->db ){
7840 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7841 if( zVfsName ){
7842 utf8_printf(p->out, "%s\n", zVfsName);
7843 sqlite3_free(zVfsName);
7844 }
7845 }
7846 }else
7847
7848#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7849 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7850 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7851 }else
7852#endif
7853
7854 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7855 int j;
7856 assert( nArg<=ArraySize(azArg) );
7857 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7858 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7859 }
7860 }else
7861
7862 {
7863 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7864 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7865 rc = 1;
7866 }
7867
7868meta_command_exit:
7869 if( p->outCount ){
7870 p->outCount--;
7871 if( p->outCount==0 ) output_reset(p);
7872 }
7873 return rc;
7874}
7875
7876/*
7877** Return TRUE if a semicolon occurs anywhere in the first N characters
7878** of string z[].
7879*/
7880static int line_contains_semicolon(const char *z, int N){
7881 int i;
7882 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7883 return 0;
7884}
7885
7886/*
7887** Test to see if a line consists entirely of whitespace.
7888*/
7889static int _all_whitespace(const char *z){
7890 for(; *z; z++){
7891 if( IsSpace(z[0]) ) continue;
7892 if( *z=='/' && z[1]=='*' ){
7893 z += 2;
7894 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7895 if( *z==0 ) return 0;
7896 z++;
7897 continue;
7898 }
7899 if( *z=='-' && z[1]=='-' ){
7900 z += 2;
7901 while( *z && *z!='\n' ){ z++; }
7902 if( *z==0 ) return 1;
7903 continue;
7904 }
7905 return 0;
7906 }
7907 return 1;
7908}
7909
7910/*
7911** Return TRUE if the line typed in is an SQL command terminator other
7912** than a semi-colon. The SQL Server style "go" command is understood
7913** as is the Oracle "/".
7914*/
7915static int line_is_command_terminator(const char *zLine){
7916 while( IsSpace(zLine[0]) ){ zLine++; };
7917 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7918 return 1; /* Oracle */
7919 }
7920 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7921 && _all_whitespace(&zLine[2]) ){
7922 return 1; /* SQL Server */
7923 }
7924 return 0;
7925}
7926
7927/*
drh56f17742018-01-24 01:58:49 +00007928** We need a default sqlite3_complete() implementation to use in case
7929** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
7930** any arbitrary text is a complete SQL statement. This is not very
7931** user-friendly, but it does seem to work.
7932*/
7933#ifdef SQLITE_OMIT_COMPLETE
7934int sqlite3_complete(const char *zSql){ return 1; }
7935#endif
7936
7937/*
drh2ce15c32017-07-11 13:34:40 +00007938** Return true if zSql is a complete SQL statement. Return false if it
7939** ends in the middle of a string literal or C-style comment.
7940*/
7941static int line_is_complete(char *zSql, int nSql){
7942 int rc;
7943 if( zSql==0 ) return 1;
7944 zSql[nSql] = ';';
7945 zSql[nSql+1] = 0;
7946 rc = sqlite3_complete(zSql);
7947 zSql[nSql] = 0;
7948 return rc;
7949}
7950
7951/*
drhfc29a862018-05-11 19:11:18 +00007952** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00007953*/
7954static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7955 int rc;
7956 char *zErrMsg = 0;
7957
7958 open_db(p, 0);
7959 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7960 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00007961 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007962 END_TIMER;
7963 if( rc || zErrMsg ){
7964 char zPrefix[100];
7965 if( in!=0 || !stdin_is_interactive ){
7966 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7967 "Error: near line %d:", startline);
7968 }else{
7969 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7970 }
7971 if( zErrMsg!=0 ){
7972 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7973 sqlite3_free(zErrMsg);
7974 zErrMsg = 0;
7975 }else{
7976 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7977 }
7978 return 1;
7979 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7980 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7981 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7982 }
7983 return 0;
7984}
7985
7986
7987/*
7988** Read input from *in and process it. If *in==0 then input
7989** is interactive - the user is typing it it. Otherwise, input
7990** is coming from a file or device. A prompt is issued and history
7991** is saved only if input is interactive. An interrupt signal will
7992** cause this routine to exit immediately, unless input is interactive.
7993**
7994** Return the number of errors.
7995*/
7996static int process_input(ShellState *p, FILE *in){
7997 char *zLine = 0; /* A single input line */
7998 char *zSql = 0; /* Accumulated SQL text */
7999 int nLine; /* Length of current line */
8000 int nSql = 0; /* Bytes of zSql[] used */
8001 int nAlloc = 0; /* Allocated zSql[] space */
8002 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
8003 int rc; /* Error code */
8004 int errCnt = 0; /* Number of errors seen */
8005 int lineno = 0; /* Current line number */
8006 int startline = 0; /* Line number for start of current input */
8007
8008 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
8009 fflush(p->out);
8010 zLine = one_input_line(in, zLine, nSql>0);
8011 if( zLine==0 ){
8012 /* End of input */
8013 if( in==0 && stdin_is_interactive ) printf("\n");
8014 break;
8015 }
8016 if( seenInterrupt ){
8017 if( in!=0 ) break;
8018 seenInterrupt = 0;
8019 }
8020 lineno++;
8021 if( nSql==0 && _all_whitespace(zLine) ){
8022 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8023 continue;
8024 }
drh1615c372018-05-12 23:56:22 +00008025 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00008026 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00008027 if( zLine[0]=='.' ){
8028 rc = do_meta_command(zLine, p);
8029 if( rc==2 ){ /* exit requested */
8030 break;
8031 }else if( rc ){
8032 errCnt++;
8033 }
drh2ce15c32017-07-11 13:34:40 +00008034 }
8035 continue;
8036 }
8037 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8038 memcpy(zLine,";",2);
8039 }
8040 nLine = strlen30(zLine);
8041 if( nSql+nLine+2>=nAlloc ){
8042 nAlloc = nSql+nLine+100;
8043 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00008044 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008045 }
8046 nSqlPrior = nSql;
8047 if( nSql==0 ){
8048 int i;
8049 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8050 assert( nAlloc>0 && zSql!=0 );
8051 memcpy(zSql, zLine+i, nLine+1-i);
8052 startline = lineno;
8053 nSql = nLine-i;
8054 }else{
8055 zSql[nSql++] = '\n';
8056 memcpy(zSql+nSql, zLine, nLine+1);
8057 nSql += nLine;
8058 }
8059 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8060 && sqlite3_complete(zSql) ){
8061 errCnt += runOneSqlLine(p, zSql, in, startline);
8062 nSql = 0;
8063 if( p->outCount ){
8064 output_reset(p);
8065 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00008066 }else{
8067 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00008068 }
8069 }else if( nSql && _all_whitespace(zSql) ){
8070 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8071 nSql = 0;
8072 }
8073 }
8074 if( nSql && !_all_whitespace(zSql) ){
drhfc29a862018-05-11 19:11:18 +00008075 errCnt += runOneSqlLine(p, zSql, in, startline);
drh2ce15c32017-07-11 13:34:40 +00008076 }
8077 free(zSql);
8078 free(zLine);
8079 return errCnt>0;
8080}
8081
8082/*
8083** Return a pathname which is the user's home directory. A
8084** 0 return indicates an error of some kind.
8085*/
8086static char *find_home_dir(int clearFlag){
8087 static char *home_dir = NULL;
8088 if( clearFlag ){
8089 free(home_dir);
8090 home_dir = 0;
8091 return 0;
8092 }
8093 if( home_dir ) return home_dir;
8094
8095#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8096 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8097 {
8098 struct passwd *pwent;
8099 uid_t uid = getuid();
8100 if( (pwent=getpwuid(uid)) != NULL) {
8101 home_dir = pwent->pw_dir;
8102 }
8103 }
8104#endif
8105
8106#if defined(_WIN32_WCE)
8107 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8108 */
8109 home_dir = "/";
8110#else
8111
8112#if defined(_WIN32) || defined(WIN32)
8113 if (!home_dir) {
8114 home_dir = getenv("USERPROFILE");
8115 }
8116#endif
8117
8118 if (!home_dir) {
8119 home_dir = getenv("HOME");
8120 }
8121
8122#if defined(_WIN32) || defined(WIN32)
8123 if (!home_dir) {
8124 char *zDrive, *zPath;
8125 int n;
8126 zDrive = getenv("HOMEDRIVE");
8127 zPath = getenv("HOMEPATH");
8128 if( zDrive && zPath ){
8129 n = strlen30(zDrive) + strlen30(zPath) + 1;
8130 home_dir = malloc( n );
8131 if( home_dir==0 ) return 0;
8132 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8133 return home_dir;
8134 }
8135 home_dir = "c:\\";
8136 }
8137#endif
8138
8139#endif /* !_WIN32_WCE */
8140
8141 if( home_dir ){
8142 int n = strlen30(home_dir) + 1;
8143 char *z = malloc( n );
8144 if( z ) memcpy(z, home_dir, n);
8145 home_dir = z;
8146 }
8147
8148 return home_dir;
8149}
8150
8151/*
8152** Read input from the file given by sqliterc_override. Or if that
8153** parameter is NULL, take input from ~/.sqliterc
8154**
8155** Returns the number of errors.
8156*/
8157static void process_sqliterc(
8158 ShellState *p, /* Configuration data */
8159 const char *sqliterc_override /* Name of config file. NULL to use default */
8160){
8161 char *home_dir = NULL;
8162 const char *sqliterc = sqliterc_override;
8163 char *zBuf = 0;
8164 FILE *in = NULL;
8165
8166 if (sqliterc == NULL) {
8167 home_dir = find_home_dir(0);
8168 if( home_dir==0 ){
8169 raw_printf(stderr, "-- warning: cannot find home directory;"
8170 " cannot read ~/.sqliterc\n");
8171 return;
8172 }
drh2ce15c32017-07-11 13:34:40 +00008173 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8174 sqliterc = zBuf;
8175 }
8176 in = fopen(sqliterc,"rb");
8177 if( in ){
8178 if( stdin_is_interactive ){
8179 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8180 }
8181 process_input(p,in);
8182 fclose(in);
8183 }
8184 sqlite3_free(zBuf);
8185}
8186
8187/*
8188** Show available command line options
8189*/
8190static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00008191#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00008192 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00008193#endif
drh3baed312018-03-08 18:14:41 +00008194 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00008195 " -ascii set output mode to 'ascii'\n"
8196 " -bail stop after hitting an error\n"
8197 " -batch force batch I/O\n"
8198 " -column set output mode to 'column'\n"
8199 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8200 " -csv set output mode to 'csv'\n"
8201 " -echo print commands before execution\n"
8202 " -init FILENAME read/process named file\n"
8203 " -[no]header turn headers on or off\n"
8204#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8205 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8206#endif
8207 " -help show this message\n"
8208 " -html set output mode to HTML\n"
8209 " -interactive force interactive I/O\n"
8210 " -line set output mode to 'line'\n"
8211 " -list set output mode to 'list'\n"
8212 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8213 " -mmap N default mmap size set to N\n"
8214#ifdef SQLITE_ENABLE_MULTIPLEX
8215 " -multiplex enable the multiplexor VFS\n"
8216#endif
8217 " -newline SEP set output row separator. Default: '\\n'\n"
8218 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8219 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8220 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00008221 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00008222 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00008223#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8224 " -sorterref SIZE sorter references threshold size\n"
8225#endif
drh2ce15c32017-07-11 13:34:40 +00008226 " -stats print memory stats before each finalize\n"
8227 " -version show SQLite version\n"
8228 " -vfs NAME use NAME as the default VFS\n"
8229#ifdef SQLITE_ENABLE_VFSTRACE
8230 " -vfstrace enable tracing of all VFS calls\n"
8231#endif
drh3baed312018-03-08 18:14:41 +00008232#ifdef SQLITE_HAVE_ZLIB
8233 " -zip open the file as a ZIP Archive\n"
8234#endif
drh2ce15c32017-07-11 13:34:40 +00008235;
8236static void usage(int showDetail){
8237 utf8_printf(stderr,
8238 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8239 "FILENAME is the name of an SQLite database. A new database is created\n"
8240 "if the file does not previously exist.\n", Argv0);
8241 if( showDetail ){
8242 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8243 }else{
8244 raw_printf(stderr, "Use the -help option for additional information\n");
8245 }
8246 exit(1);
8247}
8248
8249/*
drhe7df8922018-04-18 10:44:58 +00008250** Internal check: Verify that the SQLite is uninitialized. Print a
8251** error message if it is initialized.
8252*/
8253static void verify_uninitialized(void){
8254 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00008255 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00008256 " initialization.\n");
8257 }
8258}
8259
8260/*
drh2ce15c32017-07-11 13:34:40 +00008261** Initialize the state information in data
8262*/
8263static void main_init(ShellState *data) {
8264 memset(data, 0, sizeof(*data));
8265 data->normalMode = data->cMode = data->mode = MODE_List;
8266 data->autoExplain = 1;
8267 memcpy(data->colSeparator,SEP_Column, 2);
8268 memcpy(data->rowSeparator,SEP_Row, 2);
8269 data->showHeader = 0;
8270 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00008271 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008272 sqlite3_config(SQLITE_CONFIG_URI, 1);
8273 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8274 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8275 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8276 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8277}
8278
8279/*
8280** Output text to the console in a font that attracts extra attention.
8281*/
8282#ifdef _WIN32
8283static void printBold(const char *zText){
8284 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8285 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8286 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8287 SetConsoleTextAttribute(out,
8288 FOREGROUND_RED|FOREGROUND_INTENSITY
8289 );
8290 printf("%s", zText);
8291 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8292}
8293#else
8294static void printBold(const char *zText){
8295 printf("\033[1m%s\033[0m", zText);
8296}
8297#endif
8298
8299/*
8300** Get the argument to an --option. Throw an error and die if no argument
8301** is available.
8302*/
8303static char *cmdline_option_value(int argc, char **argv, int i){
8304 if( i==argc ){
8305 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8306 argv[0], argv[argc-1]);
8307 exit(1);
8308 }
8309 return argv[i];
8310}
8311
8312#ifndef SQLITE_SHELL_IS_UTF8
8313# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8314# define SQLITE_SHELL_IS_UTF8 (0)
8315# else
8316# define SQLITE_SHELL_IS_UTF8 (1)
8317# endif
8318#endif
8319
8320#if SQLITE_SHELL_IS_UTF8
8321int SQLITE_CDECL main(int argc, char **argv){
8322#else
8323int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8324 char **argv;
8325#endif
8326 char *zErrMsg = 0;
8327 ShellState data;
8328 const char *zInitFile = 0;
8329 int i;
8330 int rc = 0;
8331 int warnInmemoryDb = 0;
8332 int readStdin = 1;
8333 int nCmd = 0;
8334 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00008335 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00008336#if !SQLITE_SHELL_IS_UTF8
8337 char **argvToFree = 0;
8338 int argcToFree = 0;
8339#endif
drh2ce15c32017-07-11 13:34:40 +00008340
8341 setBinaryMode(stdin, 0);
8342 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8343 stdin_is_interactive = isatty(0);
8344 stdout_is_console = isatty(1);
8345
8346#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00008347 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008348 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
8349 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8350 exit(1);
8351 }
8352#endif
8353 main_init(&data);
drh501ea052018-02-15 01:03:37 +00008354
8355 /* On Windows, we must translate command-line arguments into UTF-8.
8356 ** The SQLite memory allocator subsystem has to be enabled in order to
8357 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8358 ** subsequent sqlite3_config() calls will work. So copy all results into
8359 ** memory that does not come from the SQLite memory allocator.
8360 */
drh4b18c1d2018-02-04 20:33:13 +00008361#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00008362 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00008363 argvToFree = malloc(sizeof(argv[0])*argc*2);
8364 argcToFree = argc;
8365 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00008366 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008367 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00008368 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
8369 int n;
drh4b5345c2018-04-24 13:07:40 +00008370 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008371 n = (int)strlen(z);
8372 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00008373 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008374 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00008375 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00008376 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00008377 }
drh501ea052018-02-15 01:03:37 +00008378 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00008379#endif
drh501ea052018-02-15 01:03:37 +00008380
drh2ce15c32017-07-11 13:34:40 +00008381 assert( argc>=1 && argv && argv[0] );
8382 Argv0 = argv[0];
8383
8384 /* Make sure we have a valid signal handler early, before anything
8385 ** else is done.
8386 */
8387#ifdef SIGINT
8388 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00008389#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8390 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00008391#endif
8392
8393#ifdef SQLITE_SHELL_DBNAME_PROC
8394 {
8395 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8396 ** of a C-function that will provide the name of the database file. Use
8397 ** this compile-time option to embed this shell program in larger
8398 ** applications. */
8399 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8400 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8401 warnInmemoryDb = 0;
8402 }
8403#endif
8404
8405 /* Do an initial pass through the command-line argument to locate
8406 ** the name of the database file, the name of the initialization file,
8407 ** the size of the alternative malloc heap,
8408 ** and the first command to execute.
8409 */
drhe7df8922018-04-18 10:44:58 +00008410 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008411 for(i=1; i<argc; i++){
8412 char *z;
8413 z = argv[i];
8414 if( z[0]!='-' ){
8415 if( data.zDbFilename==0 ){
8416 data.zDbFilename = z;
8417 }else{
8418 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8419 ** mean that nothing is read from stdin */
8420 readStdin = 0;
8421 nCmd++;
8422 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00008423 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008424 azCmd[nCmd-1] = z;
8425 }
8426 }
8427 if( z[1]=='-' ) z++;
8428 if( strcmp(z,"-separator")==0
8429 || strcmp(z,"-nullvalue")==0
8430 || strcmp(z,"-newline")==0
8431 || strcmp(z,"-cmd")==0
8432 ){
8433 (void)cmdline_option_value(argc, argv, ++i);
8434 }else if( strcmp(z,"-init")==0 ){
8435 zInitFile = cmdline_option_value(argc, argv, ++i);
8436 }else if( strcmp(z,"-batch")==0 ){
8437 /* Need to check for batch mode here to so we can avoid printing
8438 ** informational messages (like from process_sqliterc) before
8439 ** we do the actual processing of arguments later in a second pass.
8440 */
8441 stdin_is_interactive = 0;
8442 }else if( strcmp(z,"-heap")==0 ){
8443#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8444 const char *zSize;
8445 sqlite3_int64 szHeap;
8446
8447 zSize = cmdline_option_value(argc, argv, ++i);
8448 szHeap = integerValue(zSize);
8449 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
8450 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
8451#else
8452 (void)cmdline_option_value(argc, argv, ++i);
8453#endif
drh2ce15c32017-07-11 13:34:40 +00008454 }else if( strcmp(z,"-pagecache")==0 ){
8455 int n, sz;
8456 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8457 if( sz>70000 ) sz = 70000;
8458 if( sz<0 ) sz = 0;
8459 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8460 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8461 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
8462 data.shellFlgs |= SHFLG_Pagecache;
8463 }else if( strcmp(z,"-lookaside")==0 ){
8464 int n, sz;
8465 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8466 if( sz<0 ) sz = 0;
8467 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8468 if( n<0 ) n = 0;
8469 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8470 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
8471#ifdef SQLITE_ENABLE_VFSTRACE
8472 }else if( strcmp(z,"-vfstrace")==0 ){
8473 extern int vfstrace_register(
8474 const char *zTraceName,
8475 const char *zOldVfsName,
8476 int (*xOut)(const char*,void*),
8477 void *pOutArg,
8478 int makeDefault
8479 );
8480 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
8481#endif
8482#ifdef SQLITE_ENABLE_MULTIPLEX
8483 }else if( strcmp(z,"-multiplex")==0 ){
8484 extern int sqlite3_multiple_initialize(const char*,int);
8485 sqlite3_multiplex_initialize(0, 1);
8486#endif
8487 }else if( strcmp(z,"-mmap")==0 ){
8488 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8489 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00008490#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8491 }else if( strcmp(z,"-sorterref")==0 ){
8492 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8493 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
8494#endif
drh2ce15c32017-07-11 13:34:40 +00008495 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00008496 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00008497#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00008498 }else if( strcmp(z,"-zip")==0 ){
8499 data.openMode = SHELL_OPEN_ZIPFILE;
8500#endif
8501 }else if( strcmp(z,"-append")==0 ){
8502 data.openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00008503 }else if( strcmp(z,"-readonly")==0 ){
8504 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00008505#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008506 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00008507 /* All remaining command-line arguments are passed to the ".archive"
8508 ** command, so ignore them */
8509 break;
8510#endif
drh2ce15c32017-07-11 13:34:40 +00008511 }
8512 }
drhe7df8922018-04-18 10:44:58 +00008513 verify_uninitialized();
8514
dan16a47422018-04-18 09:16:11 +00008515
drhd11b8f62018-04-25 13:27:07 +00008516#ifdef SQLITE_SHELL_INIT_PROC
8517 {
8518 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8519 ** of a C-function that will perform initialization actions on SQLite that
8520 ** occur just before or after sqlite3_initialize(). Use this compile-time
8521 ** option to embed this shell program in larger applications. */
8522 extern void SQLITE_SHELL_INIT_PROC(void);
8523 SQLITE_SHELL_INIT_PROC();
8524 }
8525#else
dan16a47422018-04-18 09:16:11 +00008526 /* All the sqlite3_config() calls have now been made. So it is safe
8527 ** to call sqlite3_initialize() and process any command line -vfs option. */
8528 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00008529#endif
8530
dan16a47422018-04-18 09:16:11 +00008531 if( zVfs ){
8532 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
8533 if( pVfs ){
8534 sqlite3_vfs_register(pVfs, 1);
8535 }else{
8536 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
8537 exit(1);
8538 }
8539 }
8540
drh2ce15c32017-07-11 13:34:40 +00008541 if( data.zDbFilename==0 ){
8542#ifndef SQLITE_OMIT_MEMORYDB
8543 data.zDbFilename = ":memory:";
8544 warnInmemoryDb = argc==1;
8545#else
8546 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
8547 return 1;
8548#endif
8549 }
8550 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00008551 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00008552
8553 /* Go ahead and open the database file if it already exists. If the
8554 ** file does not exist, delay opening it. This prevents empty database
8555 ** files from being created if a user mistypes the database name argument
8556 ** to the sqlite command-line tool.
8557 */
8558 if( access(data.zDbFilename, 0)==0 ){
8559 open_db(&data, 0);
8560 }
8561
8562 /* Process the initialization file if there is one. If no -init option
8563 ** is given on the command line, look for a file named ~/.sqliterc and
8564 ** try to process it.
8565 */
8566 process_sqliterc(&data,zInitFile);
8567
8568 /* Make a second pass through the command-line argument and set
8569 ** options. This second pass is delayed until after the initialization
8570 ** file is processed so that the command-line arguments will override
8571 ** settings in the initialization file.
8572 */
8573 for(i=1; i<argc; i++){
8574 char *z = argv[i];
8575 if( z[0]!='-' ) continue;
8576 if( z[1]=='-' ){ z++; }
8577 if( strcmp(z,"-init")==0 ){
8578 i++;
8579 }else if( strcmp(z,"-html")==0 ){
8580 data.mode = MODE_Html;
8581 }else if( strcmp(z,"-list")==0 ){
8582 data.mode = MODE_List;
8583 }else if( strcmp(z,"-quote")==0 ){
8584 data.mode = MODE_Quote;
8585 }else if( strcmp(z,"-line")==0 ){
8586 data.mode = MODE_Line;
8587 }else if( strcmp(z,"-column")==0 ){
8588 data.mode = MODE_Column;
8589 }else if( strcmp(z,"-csv")==0 ){
8590 data.mode = MODE_Csv;
8591 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00008592#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00008593 }else if( strcmp(z,"-zip")==0 ){
8594 data.openMode = SHELL_OPEN_ZIPFILE;
8595#endif
8596 }else if( strcmp(z,"-append")==0 ){
8597 data.openMode = SHELL_OPEN_APPENDVFS;
drh4aafe592018-03-23 16:08:30 +00008598 }else if( strcmp(z,"-readonly")==0 ){
8599 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00008600 }else if( strcmp(z,"-ascii")==0 ){
8601 data.mode = MODE_Ascii;
8602 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8603 SEP_Unit);
8604 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8605 SEP_Record);
8606 }else if( strcmp(z,"-separator")==0 ){
8607 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8608 "%s",cmdline_option_value(argc,argv,++i));
8609 }else if( strcmp(z,"-newline")==0 ){
8610 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8611 "%s",cmdline_option_value(argc,argv,++i));
8612 }else if( strcmp(z,"-nullvalue")==0 ){
8613 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8614 "%s",cmdline_option_value(argc,argv,++i));
8615 }else if( strcmp(z,"-header")==0 ){
8616 data.showHeader = 1;
8617 }else if( strcmp(z,"-noheader")==0 ){
8618 data.showHeader = 0;
8619 }else if( strcmp(z,"-echo")==0 ){
8620 ShellSetFlag(&data, SHFLG_Echo);
8621 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00008622 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00008623 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00008624 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00008625 }else if( strcmp(z,"-stats")==0 ){
8626 data.statsOn = 1;
8627 }else if( strcmp(z,"-scanstats")==0 ){
8628 data.scanstatsOn = 1;
8629 }else if( strcmp(z,"-backslash")==0 ){
8630 /* Undocumented command-line option: -backslash
8631 ** Causes C-style backslash escapes to be evaluated in SQL statements
8632 ** prior to sending the SQL into SQLite. Useful for injecting
8633 ** crazy bytes in the middle of SQL statements for testing and debugging.
8634 */
8635 ShellSetFlag(&data, SHFLG_Backslash);
8636 }else if( strcmp(z,"-bail")==0 ){
8637 bail_on_error = 1;
8638 }else if( strcmp(z,"-version")==0 ){
8639 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8640 return 0;
8641 }else if( strcmp(z,"-interactive")==0 ){
8642 stdin_is_interactive = 1;
8643 }else if( strcmp(z,"-batch")==0 ){
8644 stdin_is_interactive = 0;
8645 }else if( strcmp(z,"-heap")==0 ){
8646 i++;
drh2ce15c32017-07-11 13:34:40 +00008647 }else if( strcmp(z,"-pagecache")==0 ){
8648 i+=2;
8649 }else if( strcmp(z,"-lookaside")==0 ){
8650 i+=2;
8651 }else if( strcmp(z,"-mmap")==0 ){
8652 i++;
drha90d84f2018-04-18 15:21:13 +00008653#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8654 }else if( strcmp(z,"-sorterref")==0 ){
8655 i++;
8656#endif
drh2ce15c32017-07-11 13:34:40 +00008657 }else if( strcmp(z,"-vfs")==0 ){
8658 i++;
8659#ifdef SQLITE_ENABLE_VFSTRACE
8660 }else if( strcmp(z,"-vfstrace")==0 ){
8661 i++;
8662#endif
8663#ifdef SQLITE_ENABLE_MULTIPLEX
8664 }else if( strcmp(z,"-multiplex")==0 ){
8665 i++;
8666#endif
8667 }else if( strcmp(z,"-help")==0 ){
8668 usage(1);
8669 }else if( strcmp(z,"-cmd")==0 ){
8670 /* Run commands that follow -cmd first and separately from commands
8671 ** that simply appear on the command-line. This seems goofy. It would
8672 ** be better if all commands ran in the order that they appear. But
8673 ** we retain the goofy behavior for historical compatibility. */
8674 if( i==argc-1 ) break;
8675 z = cmdline_option_value(argc,argv,++i);
8676 if( z[0]=='.' ){
8677 rc = do_meta_command(z, &data);
8678 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8679 }else{
8680 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008681 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008682 if( zErrMsg!=0 ){
8683 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8684 if( bail_on_error ) return rc!=0 ? rc : 1;
8685 }else if( rc!=0 ){
8686 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8687 if( bail_on_error ) return rc;
8688 }
8689 }
drhda57d962018-03-05 19:34:05 +00008690#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008691 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00008692 if( nCmd>0 ){
8693 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
8694 " with \"%s\"\n", z);
8695 return 1;
8696 }
drhbe4ccb22018-05-17 20:04:24 +00008697 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +00008698 if( z[2] ){
8699 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +00008700 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +00008701 }else{
drhd0f9cdc2018-05-17 14:09:06 +00008702 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +00008703 }
drhda57d962018-03-05 19:34:05 +00008704 readStdin = 0;
8705 break;
8706#endif
drh2ce15c32017-07-11 13:34:40 +00008707 }else{
8708 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8709 raw_printf(stderr,"Use -help for a list of options.\n");
8710 return 1;
8711 }
8712 data.cMode = data.mode;
8713 }
8714
8715 if( !readStdin ){
8716 /* Run all arguments that do not begin with '-' as if they were separate
8717 ** command-line inputs, except for the argToSkip argument which contains
8718 ** the database filename.
8719 */
8720 for(i=0; i<nCmd; i++){
8721 if( azCmd[i][0]=='.' ){
8722 rc = do_meta_command(azCmd[i], &data);
8723 if( rc ) return rc==2 ? 0 : rc;
8724 }else{
8725 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008726 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008727 if( zErrMsg!=0 ){
8728 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8729 return rc!=0 ? rc : 1;
8730 }else if( rc!=0 ){
8731 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8732 return rc;
8733 }
8734 }
8735 }
8736 free(azCmd);
8737 }else{
8738 /* Run commands received from standard input
8739 */
8740 if( stdin_is_interactive ){
8741 char *zHome;
8742 char *zHistory = 0;
8743 int nHistory;
8744 printf(
8745 "SQLite version %s %.19s\n" /*extra-version-info*/
8746 "Enter \".help\" for usage hints.\n",
8747 sqlite3_libversion(), sqlite3_sourceid()
8748 );
8749 if( warnInmemoryDb ){
8750 printf("Connected to a ");
8751 printBold("transient in-memory database");
8752 printf(".\nUse \".open FILENAME\" to reopen on a "
8753 "persistent database.\n");
8754 }
8755 zHome = find_home_dir(0);
8756 if( zHome ){
8757 nHistory = strlen30(zHome) + 20;
8758 if( (zHistory = malloc(nHistory))!=0 ){
8759 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8760 }
8761 }
8762 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008763#if HAVE_READLINE || HAVE_EDITLINE
8764 rl_attempted_completion_function = readline_completion;
8765#elif HAVE_LINENOISE
8766 linenoiseSetCompletionCallback(linenoise_completion);
8767#endif
drh2ce15c32017-07-11 13:34:40 +00008768 rc = process_input(&data, 0);
8769 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008770 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008771 shell_write_history(zHistory);
8772 free(zHistory);
8773 }
8774 }else{
8775 rc = process_input(&data, stdin);
8776 }
8777 }
8778 set_table_name(&data, 0);
8779 if( data.db ){
8780 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +00008781 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +00008782 }
8783 sqlite3_free(data.zFreeOnClose);
8784 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +00008785 output_reset(&data);
8786 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +00008787 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +00008788#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +00008789 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
8790 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +00008791#endif
drh9e804032018-05-18 17:11:50 +00008792 /* Clear the global data structure so that valgrind will detect memory
8793 ** leaks */
8794 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +00008795 return rc;
8796}