blob: cc375e820c1ea3bf2261978c18df046bc5160aea [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>
mistachkin1e8487d2018-07-22 06:25:35 +000082# define GETPID getpid
mistachkin562f0c82018-01-09 00:28:24 +000083# if defined(__MINGW32__)
mistachkinacae8c32018-01-05 20:08:46 +000084# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000085# ifndef S_ISLNK
86# define S_ISLNK(mode) (0)
87# endif
mistachkinacae8c32018-01-05 20:08:46 +000088# endif
mistachkin1e8487d2018-07-22 06:25:35 +000089#else
90# define GETPID (int)GetCurrentProcessId
drh2ce15c32017-07-11 13:34:40 +000091#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000092#include <sys/types.h>
93#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000094
95#if HAVE_READLINE
96# include <readline/readline.h>
97# include <readline/history.h>
98#endif
99
100#if HAVE_EDITLINE
101# include <editline/readline.h>
102#endif
103
104#if HAVE_EDITLINE || HAVE_READLINE
105
106# define shell_add_history(X) add_history(X)
107# define shell_read_history(X) read_history(X)
108# define shell_write_history(X) write_history(X)
109# define shell_stifle_history(X) stifle_history(X)
110# define shell_readline(X) readline(X)
111
112#elif HAVE_LINENOISE
113
114# include "linenoise.h"
115# define shell_add_history(X) linenoiseHistoryAdd(X)
116# define shell_read_history(X) linenoiseHistoryLoad(X)
117# define shell_write_history(X) linenoiseHistorySave(X)
118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119# define shell_readline(X) linenoise(X)
120
121#else
122
123# define shell_read_history(X)
124# define shell_write_history(X)
125# define shell_stifle_history(X)
126
127# define SHELL_USE_LOCAL_GETLINE 1
128#endif
129
130
131#if defined(_WIN32) || defined(WIN32)
132# include <io.h>
133# include <fcntl.h>
134# define isatty(h) _isatty(h)
135# ifndef access
136# define access(f,m) _access((f),(m))
137# endif
mistachkince2052b2018-03-23 00:31:53 +0000138# ifndef unlink
139# define unlink _unlink
140# endif
drh2ce15c32017-07-11 13:34:40 +0000141# undef popen
142# define popen _popen
143# undef pclose
144# define pclose _pclose
145#else
146 /* Make sure isatty() has a prototype. */
147 extern int isatty(int);
148
149# if !defined(__RTP__) && !defined(_WRS_KERNEL)
150 /* popen and pclose are not C89 functions and so are
151 ** sometimes omitted from the <stdio.h> header */
152 extern FILE *popen(const char*,const char*);
153 extern int pclose(FILE*);
154# else
155# define SQLITE_OMIT_POPEN 1
156# endif
157#endif
158
159#if defined(_WIN32_WCE)
160/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
161 * thus we always assume that we have a console. That can be
162 * overridden with the -batch command line option.
163 */
164#define isatty(x) 1
165#endif
166
167/* ctype macros that work with signed characters */
168#define IsSpace(X) isspace((unsigned char)X)
169#define IsDigit(X) isdigit((unsigned char)X)
170#define ToLower(X) (char)tolower((unsigned char)X)
171
172#if defined(_WIN32) || defined(WIN32)
173#include <windows.h>
174
175/* string conversion routines only needed on Win32 */
176extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
177extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
178extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
179extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
180#endif
181
182/* On Windows, we normally run with output mode of TEXT so that \n characters
183** are automatically translated into \r\n. However, this behavior needs
184** to be disabled in some cases (ex: when generating CSV output and when
185** rendering quoted strings that contain \n characters). The following
186** routines take care of that.
187*/
188#if defined(_WIN32) || defined(WIN32)
189static void setBinaryMode(FILE *file, int isOutput){
190 if( isOutput ) fflush(file);
191 _setmode(_fileno(file), _O_BINARY);
192}
193static void setTextMode(FILE *file, int isOutput){
194 if( isOutput ) fflush(file);
195 _setmode(_fileno(file), _O_TEXT);
196}
197#else
198# define setBinaryMode(X,Y)
199# define setTextMode(X,Y)
200#endif
201
202
203/* True if the timer is enabled */
204static int enableTimer = 0;
205
206/* Return the current wall-clock time */
207static sqlite3_int64 timeOfDay(void){
208 static sqlite3_vfs *clockVfs = 0;
209 sqlite3_int64 t;
210 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
211 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
212 clockVfs->xCurrentTimeInt64(clockVfs, &t);
213 }else{
214 double r;
215 clockVfs->xCurrentTime(clockVfs, &r);
216 t = (sqlite3_int64)(r*86400000.0);
217 }
218 return t;
219}
220
221#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
222#include <sys/time.h>
223#include <sys/resource.h>
224
225/* VxWorks does not support getrusage() as far as we can determine */
226#if defined(_WRS_KERNEL) || defined(__RTP__)
227struct rusage {
228 struct timeval ru_utime; /* user CPU time used */
229 struct timeval ru_stime; /* system CPU time used */
230};
231#define getrusage(A,B) memset(B,0,sizeof(*B))
232#endif
233
234/* Saved resource information for the beginning of an operation */
235static struct rusage sBegin; /* CPU time at start */
236static sqlite3_int64 iBegin; /* Wall-clock time at start */
237
238/*
239** Begin timing an operation
240*/
241static void beginTimer(void){
242 if( enableTimer ){
243 getrusage(RUSAGE_SELF, &sBegin);
244 iBegin = timeOfDay();
245 }
246}
247
248/* Return the difference of two time_structs in seconds */
249static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
250 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
251 (double)(pEnd->tv_sec - pStart->tv_sec);
252}
253
254/*
255** Print the timing results.
256*/
257static void endTimer(void){
258 if( enableTimer ){
259 sqlite3_int64 iEnd = timeOfDay();
260 struct rusage sEnd;
261 getrusage(RUSAGE_SELF, &sEnd);
262 printf("Run Time: real %.3f user %f sys %f\n",
263 (iEnd - iBegin)*0.001,
264 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
265 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
266 }
267}
268
269#define BEGIN_TIMER beginTimer()
270#define END_TIMER endTimer()
271#define HAS_TIMER 1
272
273#elif (defined(_WIN32) || defined(WIN32))
274
275/* Saved resource information for the beginning of an operation */
276static HANDLE hProcess;
277static FILETIME ftKernelBegin;
278static FILETIME ftUserBegin;
279static sqlite3_int64 ftWallBegin;
280typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
281 LPFILETIME, LPFILETIME);
282static GETPROCTIMES getProcessTimesAddr = NULL;
283
284/*
285** Check to see if we have timer support. Return 1 if necessary
286** support found (or found previously).
287*/
288static int hasTimer(void){
289 if( getProcessTimesAddr ){
290 return 1;
291 } else {
292 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
293 ** versions. See if the version we are running on has it, and if it
294 ** does, save off a pointer to it and the current process handle.
295 */
296 hProcess = GetCurrentProcess();
297 if( hProcess ){
298 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
299 if( NULL != hinstLib ){
300 getProcessTimesAddr =
301 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
302 if( NULL != getProcessTimesAddr ){
303 return 1;
304 }
305 FreeLibrary(hinstLib);
306 }
307 }
308 }
309 return 0;
310}
311
312/*
313** Begin timing an operation
314*/
315static void beginTimer(void){
316 if( enableTimer && getProcessTimesAddr ){
317 FILETIME ftCreation, ftExit;
318 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
319 &ftKernelBegin,&ftUserBegin);
320 ftWallBegin = timeOfDay();
321 }
322}
323
324/* Return the difference of two FILETIME structs in seconds */
325static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
326 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
327 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
328 return (double) ((i64End - i64Start) / 10000000.0);
329}
330
331/*
332** Print the timing results.
333*/
334static void endTimer(void){
335 if( enableTimer && getProcessTimesAddr){
336 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
337 sqlite3_int64 ftWallEnd = timeOfDay();
338 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
339 printf("Run Time: real %.3f user %f sys %f\n",
340 (ftWallEnd - ftWallBegin)*0.001,
341 timeDiff(&ftUserBegin, &ftUserEnd),
342 timeDiff(&ftKernelBegin, &ftKernelEnd));
343 }
344}
345
346#define BEGIN_TIMER beginTimer()
347#define END_TIMER endTimer()
348#define HAS_TIMER hasTimer()
349
350#else
351#define BEGIN_TIMER
352#define END_TIMER
353#define HAS_TIMER 0
354#endif
355
356/*
357** Used to prevent warnings about unused parameters
358*/
359#define UNUSED_PARAMETER(x) (void)(x)
360
361/*
drh5af06982018-01-10 00:53:55 +0000362** Number of elements in an array
363*/
364#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
365
366/*
drh2ce15c32017-07-11 13:34:40 +0000367** If the following flag is set, then command execution stops
368** at an error if we are not interactive.
369*/
370static int bail_on_error = 0;
371
372/*
373** Threat stdin as an interactive input if the following variable
374** is true. Otherwise, assume stdin is connected to a file or pipe.
375*/
376static int stdin_is_interactive = 1;
377
378/*
379** On Windows systems we have to know if standard output is a console
380** in order to translate UTF-8 into MBCS. The following variable is
381** true if translation is required.
382*/
383static int stdout_is_console = 1;
384
385/*
386** The following is the open SQLite database. We make a pointer
387** to this database a static variable so that it can be accessed
388** by the SIGINT handler to interrupt database processing.
389*/
390static sqlite3 *globalDb = 0;
391
392/*
393** True if an interrupt (Control-C) has been received.
394*/
395static volatile int seenInterrupt = 0;
396
397/*
398** This is the name of our program. It is set in main(), used
399** in a number of other places, mostly for error messages.
400*/
401static char *Argv0;
402
403/*
404** Prompt strings. Initialized in main. Settable with
405** .prompt main continue
406*/
407static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
408static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
409
410/*
411** Render output like fprintf(). Except, if the output is going to the
412** console and if this is running on a Windows machine, translate the
413** output from UTF-8 into MBCS.
414*/
415#if defined(_WIN32) || defined(WIN32)
416void utf8_printf(FILE *out, const char *zFormat, ...){
417 va_list ap;
418 va_start(ap, zFormat);
419 if( stdout_is_console && (out==stdout || out==stderr) ){
420 char *z1 = sqlite3_vmprintf(zFormat, ap);
421 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
422 sqlite3_free(z1);
423 fputs(z2, out);
424 sqlite3_free(z2);
425 }else{
426 vfprintf(out, zFormat, ap);
427 }
428 va_end(ap);
429}
430#elif !defined(utf8_printf)
431# define utf8_printf fprintf
432#endif
433
434/*
435** Render output like fprintf(). This should not be used on anything that
436** includes string formatting (e.g. "%s").
437*/
438#if !defined(raw_printf)
439# define raw_printf fprintf
440#endif
441
drh4b5345c2018-04-24 13:07:40 +0000442/* Indicate out-of-memory and exit. */
443static void shell_out_of_memory(void){
444 raw_printf(stderr,"Error: out of memory\n");
445 exit(1);
446}
447
drh2ce15c32017-07-11 13:34:40 +0000448/*
449** Write I/O traces to the following stream.
450*/
451#ifdef SQLITE_ENABLE_IOTRACE
452static FILE *iotrace = 0;
453#endif
454
455/*
456** This routine works like printf in that its first argument is a
457** format string and subsequent arguments are values to be substituted
458** in place of % fields. The result of formatting this string
459** is written to iotrace.
460*/
461#ifdef SQLITE_ENABLE_IOTRACE
462static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
463 va_list ap;
464 char *z;
465 if( iotrace==0 ) return;
466 va_start(ap, zFormat);
467 z = sqlite3_vmprintf(zFormat, ap);
468 va_end(ap);
469 utf8_printf(iotrace, "%s", z);
470 sqlite3_free(z);
471}
472#endif
473
474/*
475** Output string zUtf to stream pOut as w characters. If w is negative,
476** then right-justify the text. W is the width in UTF-8 characters, not
477** in bytes. This is different from the %*.*s specification in printf
478** since with %*.*s the width is measured in bytes, not characters.
479*/
480static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
481 int i;
482 int n;
483 int aw = w<0 ? -w : w;
484 char zBuf[1000];
485 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
486 for(i=n=0; zUtf[i]; i++){
487 if( (zUtf[i]&0xc0)!=0x80 ){
488 n++;
489 if( n==aw ){
490 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
491 break;
492 }
493 }
494 }
495 if( n>=aw ){
496 utf8_printf(pOut, "%.*s", i, zUtf);
497 }else if( w<0 ){
498 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
499 }else{
500 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
501 }
502}
503
504
505/*
506** Determines if a string is a number of not.
507*/
508static int isNumber(const char *z, int *realnum){
509 if( *z=='-' || *z=='+' ) z++;
510 if( !IsDigit(*z) ){
511 return 0;
512 }
513 z++;
514 if( realnum ) *realnum = 0;
515 while( IsDigit(*z) ){ z++; }
516 if( *z=='.' ){
517 z++;
518 if( !IsDigit(*z) ) return 0;
519 while( IsDigit(*z) ){ z++; }
520 if( realnum ) *realnum = 1;
521 }
522 if( *z=='e' || *z=='E' ){
523 z++;
524 if( *z=='+' || *z=='-' ) z++;
525 if( !IsDigit(*z) ) return 0;
526 while( IsDigit(*z) ){ z++; }
527 if( realnum ) *realnum = 1;
528 }
529 return *z==0;
530}
531
532/*
533** Compute a string length that is limited to what can be stored in
534** lower 30 bits of a 32-bit signed integer.
535*/
536static int strlen30(const char *z){
537 const char *z2 = z;
538 while( *z2 ){ z2++; }
539 return 0x3fffffff & (int)(z2 - z);
540}
541
542/*
543** Return the length of a string in characters. Multibyte UTF8 characters
544** count as a single character.
545*/
546static int strlenChar(const char *z){
547 int n = 0;
548 while( *z ){
549 if( (0xc0&*(z++))!=0x80 ) n++;
550 }
551 return n;
552}
553
554/*
555** This routine reads a line of text from FILE in, stores
556** the text in memory obtained from malloc() and returns a pointer
557** to the text. NULL is returned at end of file, or if malloc()
558** fails.
559**
560** If zLine is not NULL then it is a malloced buffer returned from
561** a previous call to this routine that may be reused.
562*/
563static char *local_getline(char *zLine, FILE *in){
564 int nLine = zLine==0 ? 0 : 100;
565 int n = 0;
566
567 while( 1 ){
568 if( n+100>nLine ){
569 nLine = nLine*2 + 100;
570 zLine = realloc(zLine, nLine);
drh884406b2018-07-29 18:56:35 +0000571 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000572 }
573 if( fgets(&zLine[n], nLine - n, in)==0 ){
574 if( n==0 ){
575 free(zLine);
576 return 0;
577 }
578 zLine[n] = 0;
579 break;
580 }
581 while( zLine[n] ) n++;
582 if( n>0 && zLine[n-1]=='\n' ){
583 n--;
584 if( n>0 && zLine[n-1]=='\r' ) n--;
585 zLine[n] = 0;
586 break;
587 }
588 }
589#if defined(_WIN32) || defined(WIN32)
590 /* For interactive input on Windows systems, translate the
591 ** multi-byte characterset characters into UTF-8. */
592 if( stdin_is_interactive && in==stdin ){
593 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
594 if( zTrans ){
595 int nTrans = strlen30(zTrans)+1;
596 if( nTrans>nLine ){
597 zLine = realloc(zLine, nTrans);
drh884406b2018-07-29 18:56:35 +0000598 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000599 }
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);
drh884406b2018-07-29 18:56:35 +0000745 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000746 }
747
748 if( quote ){
749 char *zCsr = p->z+p->n;
750 *zCsr++ = quote;
751 for(i=0; i<nAppend; i++){
752 *zCsr++ = zAppend[i];
753 if( zAppend[i]==quote ) *zCsr++ = quote;
754 }
755 *zCsr++ = quote;
756 p->n = (int)(zCsr - p->z);
757 *zCsr = '\0';
758 }else{
759 memcpy(p->z+p->n, zAppend, nAppend);
760 p->n += nAppend;
761 p->z[p->n] = '\0';
762 }
763}
764
765/*
766** Attempt to determine if identifier zName needs to be quoted, either
767** because it contains non-alphanumeric characters, or because it is an
768** SQLite keyword. Be conservative in this estimate: When in doubt assume
769** that quoting is required.
770**
771** Return '"' if quoting is required. Return 0 if no quoting is required.
772*/
773static char quoteChar(const char *zName){
drhfc0ec3e2018-04-25 19:02:48 +0000774 int i;
drh2ce15c32017-07-11 13:34:40 +0000775 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
776 for(i=0; zName[i]; i++){
777 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
778 }
drhfc0ec3e2018-04-25 19:02:48 +0000779 return sqlite3_keyword_check(zName, i) ? '"' : 0;
drh2ce15c32017-07-11 13:34:40 +0000780}
781
782/*
drh667a2a22018-01-02 00:04:37 +0000783** Construct a fake object name and column list to describe the structure
784** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000785*/
drh667a2a22018-01-02 00:04:37 +0000786static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000787 sqlite3 *db, /* The database connection containing the vtab */
788 const char *zSchema, /* Schema of the database holding the vtab */
789 const char *zName /* The name of the virtual table */
790){
791 sqlite3_stmt *pStmt = 0;
792 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000793 ShellText s;
794 char cQuote;
795 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000796 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000797
drh1d315cf2018-01-01 21:49:43 +0000798 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
799 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000800 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
801 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000802 initText(&s);
803 if( zSchema ){
804 cQuote = quoteChar(zSchema);
805 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
806 appendText(&s, zSchema, cQuote);
807 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000808 }
drh1d315cf2018-01-01 21:49:43 +0000809 cQuote = quoteChar(zName);
810 appendText(&s, zName, cQuote);
811 while( sqlite3_step(pStmt)==SQLITE_ROW ){
812 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000813 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000814 appendText(&s, zDiv, 0);
815 zDiv = ",";
816 cQuote = quoteChar(zCol);
817 appendText(&s, zCol, cQuote);
818 }
819 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000820 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000821 if( nRow==0 ){
822 freeText(&s);
823 s.z = 0;
824 }
drh1d315cf2018-01-01 21:49:43 +0000825 return s.z;
drhceba7922018-01-01 21:28:25 +0000826}
827
828/*
drh667a2a22018-01-02 00:04:37 +0000829** SQL function: shell_module_schema(X)
830**
831** Return a fake schema for the table-valued function or eponymous virtual
832** table X.
833*/
834static void shellModuleSchema(
835 sqlite3_context *pCtx,
836 int nVal,
837 sqlite3_value **apVal
838){
839 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
840 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
drhb9685182018-01-17 13:15:23 +0000841 UNUSED_PARAMETER(nVal);
drh667a2a22018-01-02 00:04:37 +0000842 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000843 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000844 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000845 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000846 }
847}
848
849/*
drh2ce15c32017-07-11 13:34:40 +0000850** SQL function: shell_add_schema(S,X)
851**
852** Add the schema name X to the CREATE statement in S and return the result.
853** Examples:
854**
855** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
856**
857** Also works on
858**
859** CREATE INDEX
860** CREATE UNIQUE INDEX
861** CREATE VIEW
862** CREATE TRIGGER
863** CREATE VIRTUAL TABLE
864**
865** This UDF is used by the .schema command to insert the schema name of
866** attached databases into the middle of the sqlite_master.sql field.
867*/
868static void shellAddSchemaName(
869 sqlite3_context *pCtx,
870 int nVal,
871 sqlite3_value **apVal
872){
873 static const char *aPrefix[] = {
874 "TABLE",
875 "INDEX",
876 "UNIQUE INDEX",
877 "VIEW",
878 "TRIGGER",
879 "VIRTUAL TABLE"
880 };
881 int i = 0;
882 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
883 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000884 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000885 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drhb9685182018-01-17 13:15:23 +0000886 UNUSED_PARAMETER(nVal);
drh2ce15c32017-07-11 13:34:40 +0000887 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000888 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000889 int n = strlen30(aPrefix[i]);
890 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000891 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000892 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000893 if( zSchema ){
894 char cQuote = quoteChar(zSchema);
895 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
896 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
897 }else{
898 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
899 }
drh2ce15c32017-07-11 13:34:40 +0000900 }
drh667a2a22018-01-02 00:04:37 +0000901 if( zName
902 && aPrefix[i][0]=='V'
903 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
904 ){
905 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000906 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000907 }else{
dandcfbff92018-01-08 17:05:32 +0000908 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000909 }
dandcfbff92018-01-08 17:05:32 +0000910 free(zFake);
drhceba7922018-01-01 21:28:25 +0000911 }
912 if( z ){
913 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
914 return;
915 }
drh2ce15c32017-07-11 13:34:40 +0000916 }
917 }
918 }
919 sqlite3_result_value(pCtx, apVal[0]);
920}
921
922/*
923** The source code for several run-time loadable extensions is inserted
924** below by the ../tool/mkshellc.tcl script. Before processing that included
925** code, we need to override some macros to make the included program code
926** work here in the middle of this regular program.
927*/
928#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000929#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000930
mistachkinacae8c32018-01-05 20:08:46 +0000931#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000932INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000933INCLUDE test_windirent.c
934#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000935#endif
drh2ce15c32017-07-11 13:34:40 +0000936INCLUDE ../ext/misc/shathree.c
937INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000938INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000939INCLUDE ../ext/misc/appendvfs.c
dan72afc3c2017-12-05 18:32:40 +0000940#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000941INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000942INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000943#endif
dan43efc182017-12-19 17:42:13 +0000944INCLUDE ../ext/expert/sqlite3expert.h
945INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000946
947#if defined(SQLITE_ENABLE_SESSION)
948/*
949** State information for a single open session
950*/
951typedef struct OpenSession OpenSession;
952struct OpenSession {
953 char *zName; /* Symbolic name for this session */
954 int nFilter; /* Number of xFilter rejection GLOB patterns */
955 char **azFilter; /* Array of xFilter rejection GLOB patterns */
956 sqlite3_session *p; /* The open session */
957};
958#endif
959
960/*
961** Shell output mode information from before ".explain on",
962** saved so that it can be restored by ".explain off"
963*/
964typedef struct SavedModeInfo SavedModeInfo;
965struct SavedModeInfo {
966 int valid; /* Is there legit data in here? */
967 int mode; /* Mode prior to ".explain on" */
968 int showHeader; /* The ".header" setting prior to ".explain on" */
969 int colWidth[100]; /* Column widths prior to ".explain on" */
970};
971
dan43efc182017-12-19 17:42:13 +0000972typedef struct ExpertInfo ExpertInfo;
973struct ExpertInfo {
974 sqlite3expert *pExpert;
975 int bVerbose;
976};
977
drh4b5345c2018-04-24 13:07:40 +0000978/* A single line in the EQP output */
979typedef struct EQPGraphRow EQPGraphRow;
980struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000981 int iEqpId; /* ID for this row */
982 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000983 EQPGraphRow *pNext; /* Next row in sequence */
984 char zText[1]; /* Text to display for this row */
985};
986
987/* All EQP output is collected into an instance of the following */
988typedef struct EQPGraph EQPGraph;
989struct EQPGraph {
990 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
991 EQPGraphRow *pLast; /* Last element of the pRow list */
992 char zPrefix[100]; /* Graph prefix */
993};
994
drh2ce15c32017-07-11 13:34:40 +0000995/*
996** State information about the database connection is contained in an
997** instance of the following structure.
998*/
999typedef struct ShellState ShellState;
1000struct ShellState {
1001 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001002 u8 autoExplain; /* Automatically turn on .explain mode */
1003 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001004 u8 autoEQPtest; /* autoEQP is in test mode */
drh1fa6d9f2018-01-06 21:46:01 +00001005 u8 statsOn; /* True to display memory stats before each finalize */
1006 u8 scanstatsOn; /* True to display scan stats before each finalize */
1007 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001008 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001009 u8 nEqpLevel; /* Depth of the EQP output graph */
1010 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001011 int outCount; /* Revert to stdout when reaching zero */
1012 int cnt; /* Number of records displayed so far */
1013 FILE *out; /* Write results here */
1014 FILE *traceOut; /* Output for sqlite3_trace() */
1015 int nErr; /* Number of errors seen */
1016 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001017 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001018 int cMode; /* temporary output mode for the current query */
1019 int normalMode; /* Output mode before ".explain on" */
1020 int writableSchema; /* True if PRAGMA writable_schema=ON */
1021 int showHeader; /* True to show column names in List or Column mode */
1022 int nCheck; /* Number of ".check" commands run */
1023 unsigned shellFlgs; /* Various flags */
1024 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001025 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001026 char zTestcase[30]; /* Name of current test case */
1027 char colSeparator[20]; /* Column separator character for several modes */
1028 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001029 char colSepPrior[20]; /* Saved column separator */
1030 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001031 int colWidth[100]; /* Requested width of each column when in column mode*/
1032 int actualWidth[100]; /* Actual width of each column */
1033 char nullValue[20]; /* The text to print when a NULL comes back from
1034 ** the database */
1035 char outfile[FILENAME_MAX]; /* Filename for *out */
1036 const char *zDbFilename; /* name of the database file */
1037 char *zFreeOnClose; /* Filename to free when closing */
1038 const char *zVfs; /* Name of VFS to use */
1039 sqlite3_stmt *pStmt; /* Current statement if any. */
1040 FILE *pLog; /* Write log output here */
1041 int *aiIndent; /* Array of indents used in MODE_Explain */
1042 int nIndent; /* Size of array aiIndent[] */
1043 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001044 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001045#if defined(SQLITE_ENABLE_SESSION)
1046 int nSession; /* Number of active sessions */
1047 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1048#endif
dan43efc182017-12-19 17:42:13 +00001049 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001050};
1051
drh1fa6d9f2018-01-06 21:46:01 +00001052
drhada70452017-12-21 21:02:27 +00001053/* Allowed values for ShellState.autoEQP
1054*/
drhe2ca99c2018-05-02 00:33:43 +00001055#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1056#define AUTOEQP_on 1 /* Automatic EQP is on */
1057#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1058#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001059
drh1fa6d9f2018-01-06 21:46:01 +00001060/* Allowed values for ShellState.openMode
1061*/
1062#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1063#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1064#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1065#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
drhee269a62018-02-14 23:27:43 +00001066#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
drh1fa6d9f2018-01-06 21:46:01 +00001067
drh2ce15c32017-07-11 13:34:40 +00001068/*
1069** These are the allowed shellFlgs values
1070*/
drhb2a0f752017-08-28 15:51:35 +00001071#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1072#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1073#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1074#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1075#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1076#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1077#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001078
1079/*
1080** Macros for testing and setting shellFlgs
1081*/
1082#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1083#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1084#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1085
1086/*
1087** These are the allowed modes.
1088*/
1089#define MODE_Line 0 /* One column per line. Blank line between records */
1090#define MODE_Column 1 /* One record per line in neat columns */
1091#define MODE_List 2 /* One record per line with a separator */
1092#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1093#define MODE_Html 4 /* Generate an XHTML table */
1094#define MODE_Insert 5 /* Generate SQL "insert" statements */
1095#define MODE_Quote 6 /* Quote values as for SQL */
1096#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1097#define MODE_Csv 8 /* Quote strings, numbers are plain */
1098#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1099#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1100#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001101#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001102
1103static const char *modeDescr[] = {
1104 "line",
1105 "column",
1106 "list",
1107 "semi",
1108 "html",
1109 "insert",
1110 "quote",
1111 "tcl",
1112 "csv",
1113 "explain",
1114 "ascii",
1115 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001116 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001117};
1118
1119/*
1120** These are the column/row/line separators used by the various
1121** import/export modes.
1122*/
1123#define SEP_Column "|"
1124#define SEP_Row "\n"
1125#define SEP_Tab "\t"
1126#define SEP_Space " "
1127#define SEP_Comma ","
1128#define SEP_CrLf "\r\n"
1129#define SEP_Unit "\x1F"
1130#define SEP_Record "\x1E"
1131
1132/*
drh2ce15c32017-07-11 13:34:40 +00001133** A callback for the sqlite3_log() interface.
1134*/
1135static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1136 ShellState *p = (ShellState*)pArg;
1137 if( p->pLog==0 ) return;
1138 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1139 fflush(p->pLog);
1140}
1141
1142/*
drh634c70f2018-01-10 16:50:18 +00001143** SQL function: shell_putsnl(X)
1144**
1145** Write the text X to the screen (or whatever output is being directed)
1146** adding a newline at the end, and then return X.
1147*/
1148static void shellPutsFunc(
1149 sqlite3_context *pCtx,
1150 int nVal,
1151 sqlite3_value **apVal
1152){
1153 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001154 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001155 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1156 sqlite3_result_value(pCtx, apVal[0]);
1157}
1158
1159/*
drh97913132018-01-11 00:04:00 +00001160** SQL function: edit(VALUE)
1161** edit(VALUE,EDITOR)
1162**
1163** These steps:
1164**
1165** (1) Write VALUE into a temporary file.
1166** (2) Run program EDITOR on that temporary file.
1167** (3) Read the temporary file back and return its content as the result.
1168** (4) Delete the temporary file
1169**
1170** If the EDITOR argument is omitted, use the value in the VISUAL
1171** environment variable. If still there is no EDITOR, through an error.
1172**
1173** Also throw an error if the EDITOR program returns a non-zero exit code.
1174*/
drh04a28c32018-01-31 01:38:44 +00001175#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001176static void editFunc(
1177 sqlite3_context *context,
1178 int argc,
1179 sqlite3_value **argv
1180){
1181 const char *zEditor;
1182 char *zTempFile = 0;
1183 sqlite3 *db;
1184 char *zCmd = 0;
1185 int bBin;
1186 int rc;
drhf018fd52018-08-06 02:08:53 +00001187 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001188 FILE *f = 0;
1189 sqlite3_int64 sz;
1190 sqlite3_int64 x;
1191 unsigned char *p = 0;
1192
1193 if( argc==2 ){
1194 zEditor = (const char*)sqlite3_value_text(argv[1]);
1195 }else{
1196 zEditor = getenv("VISUAL");
1197 }
1198 if( zEditor==0 ){
1199 sqlite3_result_error(context, "no editor for edit()", -1);
1200 return;
1201 }
1202 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1203 sqlite3_result_error(context, "NULL input to edit()", -1);
1204 return;
1205 }
1206 db = sqlite3_context_db_handle(context);
1207 zTempFile = 0;
1208 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1209 if( zTempFile==0 ){
1210 sqlite3_uint64 r = 0;
1211 sqlite3_randomness(sizeof(r), &r);
1212 zTempFile = sqlite3_mprintf("temp%llx", r);
1213 if( zTempFile==0 ){
1214 sqlite3_result_error_nomem(context);
1215 return;
1216 }
1217 }
1218 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001219 /* When writing the file to be edited, do \n to \r\n conversions on systems
1220 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001221 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{
drhf018fd52018-08-06 02:08:53 +00001230 const char *z = (const char*)sqlite3_value_text(argv[0]);
1231 /* Remember whether or not the value originally contained \r\n */
1232 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
drh97913132018-01-11 00:04:00 +00001233 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1234 }
1235 fclose(f);
1236 f = 0;
1237 if( x!=sz ){
1238 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1239 goto edit_func_end;
1240 }
1241 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1242 if( zCmd==0 ){
1243 sqlite3_result_error_nomem(context);
1244 goto edit_func_end;
1245 }
1246 rc = system(zCmd);
1247 sqlite3_free(zCmd);
1248 if( rc ){
1249 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1250 goto edit_func_end;
1251 }
drhf018fd52018-08-06 02:08:53 +00001252 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001253 if( f==0 ){
1254 sqlite3_result_error(context,
1255 "edit() cannot reopen temp file after edit", -1);
1256 goto edit_func_end;
1257 }
1258 fseek(f, 0, SEEK_END);
1259 sz = ftell(f);
1260 rewind(f);
1261 p = sqlite3_malloc64( sz+(bBin==0) );
1262 if( p==0 ){
1263 sqlite3_result_error_nomem(context);
1264 goto edit_func_end;
1265 }
drhf018fd52018-08-06 02:08:53 +00001266 x = fread(p, 1, sz, f);
drh97913132018-01-11 00:04:00 +00001267 fclose(f);
1268 f = 0;
1269 if( x!=sz ){
1270 sqlite3_result_error(context, "could not read back the whole file", -1);
1271 goto edit_func_end;
1272 }
1273 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001274 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001275 }else{
dan60bdcf52018-10-03 11:13:30 +00001276 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001277 if( hasCRNL ){
1278 /* If the original contains \r\n then do no conversions back to \n */
1279 j = sz;
1280 }else{
1281 /* If the file did not originally contain \r\n then convert any new
1282 ** \r\n back into \n */
1283 for(i=j=0; i<sz; i++){
1284 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1285 p[j++] = p[i];
1286 }
1287 sz = j;
1288 p[sz] = 0;
1289 }
mistachkinb71aa092018-01-23 00:05:18 +00001290 sqlite3_result_text64(context, (const char*)p, sz,
1291 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001292 }
1293 p = 0;
1294
1295edit_func_end:
1296 if( f ) fclose(f);
1297 unlink(zTempFile);
1298 sqlite3_free(zTempFile);
1299 sqlite3_free(p);
1300}
drh04a28c32018-01-31 01:38:44 +00001301#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001302
1303/*
drh3c484e82018-01-10 22:27:21 +00001304** Save or restore the current output mode
1305*/
1306static void outputModePush(ShellState *p){
1307 p->modePrior = p->mode;
1308 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1309 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1310}
1311static void outputModePop(ShellState *p){
1312 p->mode = p->modePrior;
1313 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1314 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1315}
1316
1317/*
drh2ce15c32017-07-11 13:34:40 +00001318** Output the given string as a hex-encoded blob (eg. X'1234' )
1319*/
1320static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1321 int i;
1322 char *zBlob = (char *)pBlob;
1323 raw_printf(out,"X'");
1324 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1325 raw_printf(out,"'");
1326}
1327
1328/*
1329** Find a string that is not found anywhere in z[]. Return a pointer
1330** to that string.
1331**
1332** Try to use zA and zB first. If both of those are already found in z[]
1333** then make up some string and store it in the buffer zBuf.
1334*/
1335static const char *unused_string(
1336 const char *z, /* Result must not appear anywhere in z */
1337 const char *zA, const char *zB, /* Try these first */
1338 char *zBuf /* Space to store a generated string */
1339){
1340 unsigned i = 0;
1341 if( strstr(z, zA)==0 ) return zA;
1342 if( strstr(z, zB)==0 ) return zB;
1343 do{
1344 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1345 }while( strstr(z,zBuf)!=0 );
1346 return zBuf;
1347}
1348
1349/*
1350** Output the given string as a quoted string using SQL quoting conventions.
1351**
1352** See also: output_quoted_escaped_string()
1353*/
1354static void output_quoted_string(FILE *out, const char *z){
1355 int i;
1356 char c;
1357 setBinaryMode(out, 1);
1358 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1359 if( c==0 ){
1360 utf8_printf(out,"'%s'",z);
1361 }else{
1362 raw_printf(out, "'");
1363 while( *z ){
1364 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1365 if( c=='\'' ) i++;
1366 if( i ){
1367 utf8_printf(out, "%.*s", i, z);
1368 z += i;
1369 }
1370 if( c=='\'' ){
1371 raw_printf(out, "'");
1372 continue;
1373 }
1374 if( c==0 ){
1375 break;
1376 }
1377 z++;
1378 }
1379 raw_printf(out, "'");
1380 }
1381 setTextMode(out, 1);
1382}
1383
1384/*
1385** Output the given string as a quoted string using SQL quoting conventions.
1386** Additionallly , escape the "\n" and "\r" characters so that they do not
1387** get corrupted by end-of-line translation facilities in some operating
1388** systems.
1389**
1390** This is like output_quoted_string() but with the addition of the \r\n
1391** escape mechanism.
1392*/
1393static void output_quoted_escaped_string(FILE *out, const char *z){
1394 int i;
1395 char c;
1396 setBinaryMode(out, 1);
1397 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1398 if( c==0 ){
1399 utf8_printf(out,"'%s'",z);
1400 }else{
1401 const char *zNL = 0;
1402 const char *zCR = 0;
1403 int nNL = 0;
1404 int nCR = 0;
1405 char zBuf1[20], zBuf2[20];
1406 for(i=0; z[i]; i++){
1407 if( z[i]=='\n' ) nNL++;
1408 if( z[i]=='\r' ) nCR++;
1409 }
1410 if( nNL ){
1411 raw_printf(out, "replace(");
1412 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1413 }
1414 if( nCR ){
1415 raw_printf(out, "replace(");
1416 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1417 }
1418 raw_printf(out, "'");
1419 while( *z ){
1420 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1421 if( c=='\'' ) i++;
1422 if( i ){
1423 utf8_printf(out, "%.*s", i, z);
1424 z += i;
1425 }
1426 if( c=='\'' ){
1427 raw_printf(out, "'");
1428 continue;
1429 }
1430 if( c==0 ){
1431 break;
1432 }
1433 z++;
1434 if( c=='\n' ){
1435 raw_printf(out, "%s", zNL);
1436 continue;
1437 }
1438 raw_printf(out, "%s", zCR);
1439 }
1440 raw_printf(out, "'");
1441 if( nCR ){
1442 raw_printf(out, ",'%s',char(13))", zCR);
1443 }
1444 if( nNL ){
1445 raw_printf(out, ",'%s',char(10))", zNL);
1446 }
1447 }
1448 setTextMode(out, 1);
1449}
1450
1451/*
1452** Output the given string as a quoted according to C or TCL quoting rules.
1453*/
1454static void output_c_string(FILE *out, const char *z){
1455 unsigned int c;
1456 fputc('"', out);
1457 while( (c = *(z++))!=0 ){
1458 if( c=='\\' ){
1459 fputc(c, out);
1460 fputc(c, out);
1461 }else if( c=='"' ){
1462 fputc('\\', out);
1463 fputc('"', out);
1464 }else if( c=='\t' ){
1465 fputc('\\', out);
1466 fputc('t', out);
1467 }else if( c=='\n' ){
1468 fputc('\\', out);
1469 fputc('n', out);
1470 }else if( c=='\r' ){
1471 fputc('\\', out);
1472 fputc('r', out);
1473 }else if( !isprint(c&0xff) ){
1474 raw_printf(out, "\\%03o", c&0xff);
1475 }else{
1476 fputc(c, out);
1477 }
1478 }
1479 fputc('"', out);
1480}
1481
1482/*
1483** Output the given string with characters that are special to
1484** HTML escaped.
1485*/
1486static void output_html_string(FILE *out, const char *z){
1487 int i;
1488 if( z==0 ) z = "";
1489 while( *z ){
1490 for(i=0; z[i]
1491 && z[i]!='<'
1492 && z[i]!='&'
1493 && z[i]!='>'
1494 && z[i]!='\"'
1495 && z[i]!='\'';
1496 i++){}
1497 if( i>0 ){
1498 utf8_printf(out,"%.*s",i,z);
1499 }
1500 if( z[i]=='<' ){
1501 raw_printf(out,"&lt;");
1502 }else if( z[i]=='&' ){
1503 raw_printf(out,"&amp;");
1504 }else if( z[i]=='>' ){
1505 raw_printf(out,"&gt;");
1506 }else if( z[i]=='\"' ){
1507 raw_printf(out,"&quot;");
1508 }else if( z[i]=='\'' ){
1509 raw_printf(out,"&#39;");
1510 }else{
1511 break;
1512 }
1513 z += i + 1;
1514 }
1515}
1516
1517/*
1518** If a field contains any character identified by a 1 in the following
1519** array, then the string must be quoted for CSV.
1520*/
1521static const char needCsvQuote[] = {
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, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1525 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1526 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1527 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1528 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1529 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1530 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1532 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1533 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1534 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1535 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1536 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1537 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1538};
1539
1540/*
1541** Output a single term of CSV. Actually, p->colSeparator is used for
1542** the separator, which may or may not be a comma. p->nullValue is
1543** the null value. Strings are quoted if necessary. The separator
1544** is only issued if bSep is true.
1545*/
1546static void output_csv(ShellState *p, const char *z, int bSep){
1547 FILE *out = p->out;
1548 if( z==0 ){
1549 utf8_printf(out,"%s",p->nullValue);
1550 }else{
1551 int i;
1552 int nSep = strlen30(p->colSeparator);
1553 for(i=0; z[i]; i++){
1554 if( needCsvQuote[((unsigned char*)z)[i]]
1555 || (z[i]==p->colSeparator[0] &&
1556 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1557 i = 0;
1558 break;
1559 }
1560 }
1561 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001562 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1563 utf8_printf(out, "%s", zQuoted);
1564 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001565 }else{
1566 utf8_printf(out, "%s", z);
1567 }
1568 }
1569 if( bSep ){
1570 utf8_printf(p->out, "%s", p->colSeparator);
1571 }
1572}
1573
drh2ce15c32017-07-11 13:34:40 +00001574/*
1575** This routine runs when the user presses Ctrl-C
1576*/
1577static void interrupt_handler(int NotUsed){
1578 UNUSED_PARAMETER(NotUsed);
1579 seenInterrupt++;
1580 if( seenInterrupt>2 ) exit(1);
1581 if( globalDb ) sqlite3_interrupt(globalDb);
1582}
mistachkinb4bab902017-10-27 17:09:44 +00001583
1584#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1585/*
1586** This routine runs for console events (e.g. Ctrl-C) on Win32
1587*/
1588static BOOL WINAPI ConsoleCtrlHandler(
1589 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1590){
1591 if( dwCtrlType==CTRL_C_EVENT ){
1592 interrupt_handler(0);
1593 return TRUE;
1594 }
1595 return FALSE;
1596}
drh2ce15c32017-07-11 13:34:40 +00001597#endif
1598
1599#ifndef SQLITE_OMIT_AUTHORIZATION
1600/*
1601** When the ".auth ON" is set, the following authorizer callback is
1602** invoked. It always returns SQLITE_OK.
1603*/
1604static int shellAuth(
1605 void *pClientData,
1606 int op,
1607 const char *zA1,
1608 const char *zA2,
1609 const char *zA3,
1610 const char *zA4
1611){
1612 ShellState *p = (ShellState*)pClientData;
1613 static const char *azAction[] = { 0,
1614 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1615 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1616 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1617 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1618 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1619 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1620 "PRAGMA", "READ", "SELECT",
1621 "TRANSACTION", "UPDATE", "ATTACH",
1622 "DETACH", "ALTER_TABLE", "REINDEX",
1623 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1624 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1625 };
1626 int i;
1627 const char *az[4];
1628 az[0] = zA1;
1629 az[1] = zA2;
1630 az[2] = zA3;
1631 az[3] = zA4;
1632 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1633 for(i=0; i<4; i++){
1634 raw_printf(p->out, " ");
1635 if( az[i] ){
1636 output_c_string(p->out, az[i]);
1637 }else{
1638 raw_printf(p->out, "NULL");
1639 }
1640 }
1641 raw_printf(p->out, "\n");
1642 return SQLITE_OK;
1643}
1644#endif
1645
1646/*
1647** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1648**
1649** This routine converts some CREATE TABLE statements for shadow tables
1650** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1651*/
1652static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1653 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1654 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1655 }else{
1656 utf8_printf(out, "%s%s", z, zTail);
1657 }
1658}
1659static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1660 char c = z[n];
1661 z[n] = 0;
1662 printSchemaLine(out, z, zTail);
1663 z[n] = c;
1664}
1665
1666/*
drh11be81d2018-01-06 15:46:20 +00001667** Return true if string z[] has nothing but whitespace and comments to the
1668** end of the first line.
1669*/
1670static int wsToEol(const char *z){
1671 int i;
1672 for(i=0; z[i]; i++){
1673 if( z[i]=='\n' ) return 1;
1674 if( IsSpace(z[i]) ) continue;
1675 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1676 return 0;
1677 }
1678 return 1;
1679}
drh4b5345c2018-04-24 13:07:40 +00001680
1681/*
1682** Add a new entry to the EXPLAIN QUERY PLAN data
1683*/
drhe2ca99c2018-05-02 00:33:43 +00001684static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001685 EQPGraphRow *pNew;
1686 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001687 if( p->autoEQPtest ){
1688 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1689 }
drh4b5345c2018-04-24 13:07:40 +00001690 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1691 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001692 pNew->iEqpId = iEqpId;
1693 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001694 memcpy(pNew->zText, zText, nText+1);
1695 pNew->pNext = 0;
1696 if( p->sGraph.pLast ){
1697 p->sGraph.pLast->pNext = pNew;
1698 }else{
1699 p->sGraph.pRow = pNew;
1700 }
1701 p->sGraph.pLast = pNew;
1702}
1703
1704/*
1705** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1706** in p->sGraph.
1707*/
1708static void eqp_reset(ShellState *p){
1709 EQPGraphRow *pRow, *pNext;
1710 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1711 pNext = pRow->pNext;
1712 sqlite3_free(pRow);
1713 }
1714 memset(&p->sGraph, 0, sizeof(p->sGraph));
1715}
1716
drhe2ca99c2018-05-02 00:33:43 +00001717/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001718** pOld, or return the first such line if pOld is NULL
1719*/
drhe2ca99c2018-05-02 00:33:43 +00001720static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001721 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001722 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001723 return pRow;
1724}
1725
drhe2ca99c2018-05-02 00:33:43 +00001726/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001727** recursively to render sublevels.
1728*/
drhe2ca99c2018-05-02 00:33:43 +00001729static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001730 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001731 int n = strlen30(p->sGraph.zPrefix);
1732 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001733 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1734 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001735 z = pRow->zText;
1736 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001737 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001738 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001739 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001740 p->sGraph.zPrefix[n] = 0;
1741 }
1742 }
1743}
1744
1745/*
1746** Display and reset the EXPLAIN QUERY PLAN data
1747*/
1748static void eqp_render(ShellState *p){
1749 EQPGraphRow *pRow = p->sGraph.pRow;
1750 if( pRow ){
1751 if( pRow->zText[0]=='-' ){
1752 if( pRow->pNext==0 ){
1753 eqp_reset(p);
1754 return;
1755 }
1756 utf8_printf(p->out, "%s\n", pRow->zText+3);
1757 p->sGraph.pRow = pRow->pNext;
1758 sqlite3_free(pRow);
1759 }else{
1760 utf8_printf(p->out, "QUERY PLAN\n");
1761 }
1762 p->sGraph.zPrefix[0] = 0;
1763 eqp_render_level(p, 0);
1764 eqp_reset(p);
1765 }
1766}
drh11be81d2018-01-06 15:46:20 +00001767
1768/*
drh2ce15c32017-07-11 13:34:40 +00001769** This is the callback routine that the shell
1770** invokes for each row of a query result.
1771*/
1772static int shell_callback(
1773 void *pArg,
1774 int nArg, /* Number of result columns */
1775 char **azArg, /* Text of each result column */
1776 char **azCol, /* Column names */
1777 int *aiType /* Column types */
1778){
1779 int i;
1780 ShellState *p = (ShellState*)pArg;
1781
drhb3c45232017-08-28 14:33:27 +00001782 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001783 switch( p->cMode ){
1784 case MODE_Line: {
1785 int w = 5;
1786 if( azArg==0 ) break;
1787 for(i=0; i<nArg; i++){
1788 int len = strlen30(azCol[i] ? azCol[i] : "");
1789 if( len>w ) w = len;
1790 }
1791 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1792 for(i=0; i<nArg; i++){
1793 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1794 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1795 }
1796 break;
1797 }
1798 case MODE_Explain:
1799 case MODE_Column: {
1800 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1801 const int *colWidth;
1802 int showHdr;
1803 char *rowSep;
1804 if( p->cMode==MODE_Column ){
1805 colWidth = p->colWidth;
1806 showHdr = p->showHeader;
1807 rowSep = p->rowSeparator;
1808 }else{
1809 colWidth = aExplainWidths;
1810 showHdr = 1;
1811 rowSep = SEP_Row;
1812 }
1813 if( p->cnt++==0 ){
1814 for(i=0; i<nArg; i++){
1815 int w, n;
1816 if( i<ArraySize(p->colWidth) ){
1817 w = colWidth[i];
1818 }else{
1819 w = 0;
1820 }
1821 if( w==0 ){
1822 w = strlenChar(azCol[i] ? azCol[i] : "");
1823 if( w<10 ) w = 10;
1824 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1825 if( w<n ) w = n;
1826 }
1827 if( i<ArraySize(p->actualWidth) ){
1828 p->actualWidth[i] = w;
1829 }
1830 if( showHdr ){
1831 utf8_width_print(p->out, w, azCol[i]);
1832 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1833 }
1834 }
1835 if( showHdr ){
1836 for(i=0; i<nArg; i++){
1837 int w;
1838 if( i<ArraySize(p->actualWidth) ){
1839 w = p->actualWidth[i];
1840 if( w<0 ) w = -w;
1841 }else{
1842 w = 10;
1843 }
1844 utf8_printf(p->out,"%-*.*s%s",w,w,
1845 "----------------------------------------------------------"
1846 "----------------------------------------------------------",
1847 i==nArg-1 ? rowSep : " ");
1848 }
1849 }
1850 }
1851 if( azArg==0 ) break;
1852 for(i=0; i<nArg; i++){
1853 int w;
1854 if( i<ArraySize(p->actualWidth) ){
1855 w = p->actualWidth[i];
1856 }else{
1857 w = 10;
1858 }
1859 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1860 w = strlenChar(azArg[i]);
1861 }
1862 if( i==1 && p->aiIndent && p->pStmt ){
1863 if( p->iIndent<p->nIndent ){
1864 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1865 }
1866 p->iIndent++;
1867 }
1868 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1869 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1870 }
1871 break;
1872 }
1873 case MODE_Semi: { /* .schema and .fullschema output */
1874 printSchemaLine(p->out, azArg[0], ";\n");
1875 break;
1876 }
1877 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1878 char *z;
1879 int j;
1880 int nParen = 0;
1881 char cEnd = 0;
1882 char c;
1883 int nLine = 0;
1884 assert( nArg==1 );
1885 if( azArg[0]==0 ) break;
1886 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1887 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1888 ){
1889 utf8_printf(p->out, "%s;\n", azArg[0]);
1890 break;
1891 }
1892 z = sqlite3_mprintf("%s", azArg[0]);
1893 j = 0;
1894 for(i=0; IsSpace(z[i]); i++){}
1895 for(; (c = z[i])!=0; i++){
1896 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001897 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001898 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1899 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1900 j--;
1901 }
1902 z[j++] = c;
1903 }
1904 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1905 z[j] = 0;
1906 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001907 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001908 if( c==cEnd ){
1909 cEnd = 0;
1910 }else if( c=='"' || c=='\'' || c=='`' ){
1911 cEnd = c;
1912 }else if( c=='[' ){
1913 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001914 }else if( c=='-' && z[i+1]=='-' ){
1915 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001916 }else if( c=='(' ){
1917 nParen++;
1918 }else if( c==')' ){
1919 nParen--;
1920 if( nLine>0 && nParen==0 && j>0 ){
1921 printSchemaLineN(p->out, z, j, "\n");
1922 j = 0;
1923 }
1924 }
1925 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001926 if( nParen==1 && cEnd==0
1927 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1928 ){
drh2ce15c32017-07-11 13:34:40 +00001929 if( c=='\n' ) j--;
1930 printSchemaLineN(p->out, z, j, "\n ");
1931 j = 0;
1932 nLine++;
1933 while( IsSpace(z[i+1]) ){ i++; }
1934 }
1935 }
1936 z[j] = 0;
1937 }
1938 printSchemaLine(p->out, z, ";\n");
1939 sqlite3_free(z);
1940 break;
1941 }
1942 case MODE_List: {
1943 if( p->cnt++==0 && p->showHeader ){
1944 for(i=0; i<nArg; i++){
1945 utf8_printf(p->out,"%s%s",azCol[i],
1946 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1947 }
1948 }
1949 if( azArg==0 ) break;
1950 for(i=0; i<nArg; i++){
1951 char *z = azArg[i];
1952 if( z==0 ) z = p->nullValue;
1953 utf8_printf(p->out, "%s", z);
1954 if( i<nArg-1 ){
1955 utf8_printf(p->out, "%s", p->colSeparator);
1956 }else{
1957 utf8_printf(p->out, "%s", p->rowSeparator);
1958 }
1959 }
1960 break;
1961 }
1962 case MODE_Html: {
1963 if( p->cnt++==0 && p->showHeader ){
1964 raw_printf(p->out,"<TR>");
1965 for(i=0; i<nArg; i++){
1966 raw_printf(p->out,"<TH>");
1967 output_html_string(p->out, azCol[i]);
1968 raw_printf(p->out,"</TH>\n");
1969 }
1970 raw_printf(p->out,"</TR>\n");
1971 }
1972 if( azArg==0 ) break;
1973 raw_printf(p->out,"<TR>");
1974 for(i=0; i<nArg; i++){
1975 raw_printf(p->out,"<TD>");
1976 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1977 raw_printf(p->out,"</TD>\n");
1978 }
1979 raw_printf(p->out,"</TR>\n");
1980 break;
1981 }
1982 case MODE_Tcl: {
1983 if( p->cnt++==0 && p->showHeader ){
1984 for(i=0; i<nArg; i++){
1985 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1986 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1987 }
1988 utf8_printf(p->out, "%s", p->rowSeparator);
1989 }
1990 if( azArg==0 ) break;
1991 for(i=0; i<nArg; i++){
1992 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1993 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1994 }
1995 utf8_printf(p->out, "%s", p->rowSeparator);
1996 break;
1997 }
1998 case MODE_Csv: {
1999 setBinaryMode(p->out, 1);
2000 if( p->cnt++==0 && p->showHeader ){
2001 for(i=0; i<nArg; i++){
2002 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2003 }
2004 utf8_printf(p->out, "%s", p->rowSeparator);
2005 }
2006 if( nArg>0 ){
2007 for(i=0; i<nArg; i++){
2008 output_csv(p, azArg[i], i<nArg-1);
2009 }
2010 utf8_printf(p->out, "%s", p->rowSeparator);
2011 }
2012 setTextMode(p->out, 1);
2013 break;
2014 }
2015 case MODE_Insert: {
2016 if( azArg==0 ) break;
2017 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2018 if( p->showHeader ){
2019 raw_printf(p->out,"(");
2020 for(i=0; i<nArg; i++){
2021 if( i>0 ) raw_printf(p->out, ",");
2022 if( quoteChar(azCol[i]) ){
2023 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2024 utf8_printf(p->out, "%s", z);
2025 sqlite3_free(z);
2026 }else{
2027 raw_printf(p->out, "%s", azCol[i]);
2028 }
2029 }
2030 raw_printf(p->out,")");
2031 }
2032 p->cnt++;
2033 for(i=0; i<nArg; i++){
2034 raw_printf(p->out, i>0 ? "," : " VALUES(");
2035 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2036 utf8_printf(p->out,"NULL");
2037 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2038 if( ShellHasFlag(p, SHFLG_Newlines) ){
2039 output_quoted_string(p->out, azArg[i]);
2040 }else{
2041 output_quoted_escaped_string(p->out, azArg[i]);
2042 }
2043 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2044 utf8_printf(p->out,"%s", azArg[i]);
2045 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2046 char z[50];
2047 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002048 sqlite3_uint64 ur;
2049 memcpy(&ur,&r,sizeof(r));
2050 if( ur==0x7ff0000000000000LL ){
2051 raw_printf(p->out, "1e999");
2052 }else if( ur==0xfff0000000000000LL ){
2053 raw_printf(p->out, "-1e999");
2054 }else{
2055 sqlite3_snprintf(50,z,"%!.20g", r);
2056 raw_printf(p->out, "%s", z);
2057 }
drh2ce15c32017-07-11 13:34:40 +00002058 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2059 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2060 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2061 output_hex_blob(p->out, pBlob, nBlob);
2062 }else if( isNumber(azArg[i], 0) ){
2063 utf8_printf(p->out,"%s", azArg[i]);
2064 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2065 output_quoted_string(p->out, azArg[i]);
2066 }else{
2067 output_quoted_escaped_string(p->out, azArg[i]);
2068 }
2069 }
2070 raw_printf(p->out,");\n");
2071 break;
2072 }
2073 case MODE_Quote: {
2074 if( azArg==0 ) break;
2075 if( p->cnt==0 && p->showHeader ){
2076 for(i=0; i<nArg; i++){
2077 if( i>0 ) raw_printf(p->out, ",");
2078 output_quoted_string(p->out, azCol[i]);
2079 }
2080 raw_printf(p->out,"\n");
2081 }
2082 p->cnt++;
2083 for(i=0; i<nArg; i++){
2084 if( i>0 ) raw_printf(p->out, ",");
2085 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2086 utf8_printf(p->out,"NULL");
2087 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2088 output_quoted_string(p->out, azArg[i]);
2089 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2090 utf8_printf(p->out,"%s", azArg[i]);
2091 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2092 char z[50];
2093 double r = sqlite3_column_double(p->pStmt, i);
2094 sqlite3_snprintf(50,z,"%!.20g", r);
2095 raw_printf(p->out, "%s", z);
2096 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2097 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2098 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2099 output_hex_blob(p->out, pBlob, nBlob);
2100 }else if( isNumber(azArg[i], 0) ){
2101 utf8_printf(p->out,"%s", azArg[i]);
2102 }else{
2103 output_quoted_string(p->out, azArg[i]);
2104 }
2105 }
2106 raw_printf(p->out,"\n");
2107 break;
2108 }
2109 case MODE_Ascii: {
2110 if( p->cnt++==0 && p->showHeader ){
2111 for(i=0; i<nArg; i++){
2112 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2113 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2114 }
2115 utf8_printf(p->out, "%s", p->rowSeparator);
2116 }
2117 if( azArg==0 ) break;
2118 for(i=0; i<nArg; i++){
2119 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2120 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2121 }
2122 utf8_printf(p->out, "%s", p->rowSeparator);
2123 break;
2124 }
drh4b5345c2018-04-24 13:07:40 +00002125 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002126 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002127 break;
2128 }
drh2ce15c32017-07-11 13:34:40 +00002129 }
2130 return 0;
2131}
2132
2133/*
2134** This is the callback routine that the SQLite library
2135** invokes for each row of a query result.
2136*/
2137static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2138 /* since we don't have type info, call the shell_callback with a NULL value */
2139 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2140}
2141
2142/*
2143** This is the callback routine from sqlite3_exec() that appends all
2144** output onto the end of a ShellText object.
2145*/
2146static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2147 ShellText *p = (ShellText*)pArg;
2148 int i;
2149 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002150 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002151 if( p->n ) appendText(p, "|", 0);
2152 for(i=0; i<nArg; i++){
2153 if( i ) appendText(p, ",", 0);
2154 if( azArg[i] ) appendText(p, azArg[i], 0);
2155 }
2156 return 0;
2157}
2158
2159/*
2160** Generate an appropriate SELFTEST table in the main database.
2161*/
2162static void createSelftestTable(ShellState *p){
2163 char *zErrMsg = 0;
2164 sqlite3_exec(p->db,
2165 "SAVEPOINT selftest_init;\n"
2166 "CREATE TABLE IF NOT EXISTS selftest(\n"
2167 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2168 " op TEXT,\n" /* Operator: memo run */
2169 " cmd TEXT,\n" /* Command text */
2170 " ans TEXT\n" /* Desired answer */
2171 ");"
2172 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2173 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2174 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2175 " 'memo','Tests generated by --init');\n"
2176 "INSERT INTO [_shell$self]\n"
2177 " SELECT 'run',\n"
2178 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2179 "FROM sqlite_master ORDER BY 2'',224))',\n"
2180 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2181 "FROM sqlite_master ORDER BY 2',224));\n"
2182 "INSERT INTO [_shell$self]\n"
2183 " SELECT 'run',"
2184 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2185 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2186 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2187 " FROM (\n"
2188 " SELECT name FROM sqlite_master\n"
2189 " WHERE type='table'\n"
2190 " AND name<>'selftest'\n"
2191 " AND coalesce(rootpage,0)>0\n"
2192 " )\n"
2193 " ORDER BY name;\n"
2194 "INSERT INTO [_shell$self]\n"
2195 " VALUES('run','PRAGMA integrity_check','ok');\n"
2196 "INSERT INTO selftest(tno,op,cmd,ans)"
2197 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2198 "DROP TABLE [_shell$self];"
2199 ,0,0,&zErrMsg);
2200 if( zErrMsg ){
2201 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2202 sqlite3_free(zErrMsg);
2203 }
2204 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2205}
2206
2207
2208/*
2209** Set the destination table field of the ShellState structure to
2210** the name of the table given. Escape any quote characters in the
2211** table name.
2212*/
2213static void set_table_name(ShellState *p, const char *zName){
2214 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002215 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002216 char *z;
2217
2218 if( p->zDestTable ){
2219 free(p->zDestTable);
2220 p->zDestTable = 0;
2221 }
2222 if( zName==0 ) return;
2223 cQuote = quoteChar(zName);
2224 n = strlen30(zName);
2225 if( cQuote ) n += n+2;
2226 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002227 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002228 n = 0;
2229 if( cQuote ) z[n++] = cQuote;
2230 for(i=0; zName[i]; i++){
2231 z[n++] = zName[i];
2232 if( zName[i]==cQuote ) z[n++] = cQuote;
2233 }
2234 if( cQuote ) z[n++] = cQuote;
2235 z[n] = 0;
2236}
2237
2238
2239/*
2240** Execute a query statement that will generate SQL output. Print
2241** the result columns, comma-separated, on a line and then add a
2242** semicolon terminator to the end of that line.
2243**
2244** If the number of columns is 1 and that column contains text "--"
2245** then write the semicolon on a separate line. That way, if a
2246** "--" comment occurs at the end of the statement, the comment
2247** won't consume the semicolon terminator.
2248*/
2249static int run_table_dump_query(
2250 ShellState *p, /* Query context */
2251 const char *zSelect, /* SELECT statement to extract content */
2252 const char *zFirstRow /* Print before first row, if not NULL */
2253){
2254 sqlite3_stmt *pSelect;
2255 int rc;
2256 int nResult;
2257 int i;
2258 const char *z;
2259 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2260 if( rc!=SQLITE_OK || !pSelect ){
2261 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2262 sqlite3_errmsg(p->db));
2263 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2264 return rc;
2265 }
2266 rc = sqlite3_step(pSelect);
2267 nResult = sqlite3_column_count(pSelect);
2268 while( rc==SQLITE_ROW ){
2269 if( zFirstRow ){
2270 utf8_printf(p->out, "%s", zFirstRow);
2271 zFirstRow = 0;
2272 }
2273 z = (const char*)sqlite3_column_text(pSelect, 0);
2274 utf8_printf(p->out, "%s", z);
2275 for(i=1; i<nResult; i++){
2276 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2277 }
2278 if( z==0 ) z = "";
2279 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2280 if( z[0] ){
2281 raw_printf(p->out, "\n;\n");
2282 }else{
2283 raw_printf(p->out, ";\n");
2284 }
2285 rc = sqlite3_step(pSelect);
2286 }
2287 rc = sqlite3_finalize(pSelect);
2288 if( rc!=SQLITE_OK ){
2289 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2290 sqlite3_errmsg(p->db));
2291 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2292 }
2293 return rc;
2294}
2295
2296/*
2297** Allocate space and save off current error string.
2298*/
2299static char *save_err_msg(
2300 sqlite3 *db /* Database to query */
2301){
2302 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2303 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2304 if( zErrMsg ){
2305 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2306 }
2307 return zErrMsg;
2308}
2309
2310#ifdef __linux__
2311/*
2312** Attempt to display I/O stats on Linux using /proc/PID/io
2313*/
2314static void displayLinuxIoStats(FILE *out){
2315 FILE *in;
2316 char z[200];
2317 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2318 in = fopen(z, "rb");
2319 if( in==0 ) return;
2320 while( fgets(z, sizeof(z), in)!=0 ){
2321 static const struct {
2322 const char *zPattern;
2323 const char *zDesc;
2324 } aTrans[] = {
2325 { "rchar: ", "Bytes received by read():" },
2326 { "wchar: ", "Bytes sent to write():" },
2327 { "syscr: ", "Read() system calls:" },
2328 { "syscw: ", "Write() system calls:" },
2329 { "read_bytes: ", "Bytes read from storage:" },
2330 { "write_bytes: ", "Bytes written to storage:" },
2331 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2332 };
2333 int i;
2334 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002335 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002336 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2337 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2338 break;
2339 }
2340 }
2341 }
2342 fclose(in);
2343}
2344#endif
2345
2346/*
2347** Display a single line of status using 64-bit values.
2348*/
2349static void displayStatLine(
2350 ShellState *p, /* The shell context */
2351 char *zLabel, /* Label for this one line */
2352 char *zFormat, /* Format for the result */
2353 int iStatusCtrl, /* Which status to display */
2354 int bReset /* True to reset the stats */
2355){
2356 sqlite3_int64 iCur = -1;
2357 sqlite3_int64 iHiwtr = -1;
2358 int i, nPercent;
2359 char zLine[200];
2360 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2361 for(i=0, nPercent=0; zFormat[i]; i++){
2362 if( zFormat[i]=='%' ) nPercent++;
2363 }
2364 if( nPercent>1 ){
2365 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2366 }else{
2367 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2368 }
2369 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2370}
2371
2372/*
2373** Display memory stats.
2374*/
2375static int display_stats(
2376 sqlite3 *db, /* Database to query */
2377 ShellState *pArg, /* Pointer to ShellState */
2378 int bReset /* True to reset the stats */
2379){
2380 int iCur;
2381 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002382 FILE *out;
2383 if( pArg==0 || pArg->out==0 ) return 0;
2384 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002385
drh393344f2018-03-09 16:37:05 +00002386 if( pArg->pStmt && (pArg->statsOn & 2) ){
2387 int nCol, i, x;
2388 sqlite3_stmt *pStmt = pArg->pStmt;
2389 char z[100];
2390 nCol = sqlite3_column_count(pStmt);
2391 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2392 for(i=0; i<nCol; i++){
2393 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2394 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002395#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002396 sqlite3_snprintf(30, z+x, "declared type:");
2397 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002398#endif
2399#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002400 sqlite3_snprintf(30, z+x, "database name:");
2401 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2402 sqlite3_snprintf(30, z+x, "table name:");
2403 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2404 sqlite3_snprintf(30, z+x, "origin name:");
2405 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002406#endif
drh2ce15c32017-07-11 13:34:40 +00002407 }
drh929cce82018-03-17 16:26:36 +00002408 }
drh2ce15c32017-07-11 13:34:40 +00002409
drh393344f2018-03-09 16:37:05 +00002410 displayStatLine(pArg, "Memory Used:",
2411 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2412 displayStatLine(pArg, "Number of Outstanding Allocations:",
2413 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2414 if( pArg->shellFlgs & SHFLG_Pagecache ){
2415 displayStatLine(pArg, "Number of Pcache Pages Used:",
2416 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2417 }
2418 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2419 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2420 displayStatLine(pArg, "Largest Allocation:",
2421 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2422 displayStatLine(pArg, "Largest Pcache Allocation:",
2423 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2424#ifdef YYTRACKMAXSTACKDEPTH
2425 displayStatLine(pArg, "Deepest Parser Stack:",
2426 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2427#endif
2428
2429 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002430 if( pArg->shellFlgs & SHFLG_Lookaside ){
2431 iHiwtr = iCur = -1;
2432 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2433 &iCur, &iHiwtr, bReset);
2434 raw_printf(pArg->out,
2435 "Lookaside Slots Used: %d (max %d)\n",
2436 iCur, iHiwtr);
2437 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2438 &iCur, &iHiwtr, bReset);
2439 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2440 iHiwtr);
2441 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2442 &iCur, &iHiwtr, bReset);
2443 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2444 iHiwtr);
2445 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2446 &iCur, &iHiwtr, bReset);
2447 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2448 iHiwtr);
2449 }
2450 iHiwtr = iCur = -1;
2451 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2452 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2453 iCur);
2454 iHiwtr = iCur = -1;
2455 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2456 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2457 iHiwtr = iCur = -1;
2458 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2459 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2460 iHiwtr = iCur = -1;
2461 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2462 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2463 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002464 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2465 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2466 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002467 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2468 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2469 iCur);
2470 iHiwtr = iCur = -1;
2471 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2472 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2473 iCur);
2474 }
2475
drh393344f2018-03-09 16:37:05 +00002476 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002477 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2478 bReset);
2479 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2480 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2481 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2482 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2483 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2484 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2485 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002486 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2487 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2488 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2489 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2490 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2491 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002492 }
2493
2494#ifdef __linux__
2495 displayLinuxIoStats(pArg->out);
2496#endif
2497
2498 /* Do not remove this machine readable comment: extra-stats-output-here */
2499
2500 return 0;
2501}
2502
2503/*
2504** Display scan stats.
2505*/
2506static void display_scanstats(
2507 sqlite3 *db, /* Database to query */
2508 ShellState *pArg /* Pointer to ShellState */
2509){
2510#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2511 UNUSED_PARAMETER(db);
2512 UNUSED_PARAMETER(pArg);
2513#else
2514 int i, k, n, mx;
2515 raw_printf(pArg->out, "-------- scanstats --------\n");
2516 mx = 0;
2517 for(k=0; k<=mx; k++){
2518 double rEstLoop = 1.0;
2519 for(i=n=0; 1; i++){
2520 sqlite3_stmt *p = pArg->pStmt;
2521 sqlite3_int64 nLoop, nVisit;
2522 double rEst;
2523 int iSid;
2524 const char *zExplain;
2525 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2526 break;
2527 }
2528 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2529 if( iSid>mx ) mx = iSid;
2530 if( iSid!=k ) continue;
2531 if( n==0 ){
2532 rEstLoop = (double)nLoop;
2533 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2534 }
2535 n++;
2536 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2537 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2538 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2539 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2540 rEstLoop *= rEst;
2541 raw_printf(pArg->out,
2542 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2543 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2544 );
2545 }
2546 }
2547 raw_printf(pArg->out, "---------------------------\n");
2548#endif
2549}
2550
2551/*
2552** Parameter azArray points to a zero-terminated array of strings. zStr
2553** points to a single nul-terminated string. Return non-zero if zStr
2554** is equal, according to strcmp(), to any of the strings in the array.
2555** Otherwise, return zero.
2556*/
2557static int str_in_array(const char *zStr, const char **azArray){
2558 int i;
2559 for(i=0; azArray[i]; i++){
2560 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2561 }
2562 return 0;
2563}
2564
2565/*
2566** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2567** and populate the ShellState.aiIndent[] array with the number of
2568** spaces each opcode should be indented before it is output.
2569**
2570** The indenting rules are:
2571**
2572** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2573** all opcodes that occur between the p2 jump destination and the opcode
2574** itself by 2 spaces.
2575**
2576** * For each "Goto", if the jump destination is earlier in the program
2577** and ends on one of:
2578** Yield SeekGt SeekLt RowSetRead Rewind
2579** or if the P1 parameter is one instead of zero,
2580** then indent all opcodes between the earlier instruction
2581** and "Goto" by 2 spaces.
2582*/
2583static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2584 const char *zSql; /* The text of the SQL statement */
2585 const char *z; /* Used to check if this is an EXPLAIN */
2586 int *abYield = 0; /* True if op is an OP_Yield */
2587 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2588 int iOp; /* Index of operation in p->aiIndent[] */
2589
drhf1949b62018-06-07 17:32:59 +00002590 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002591 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2592 "Rewind", 0 };
2593 const char *azGoto[] = { "Goto", 0 };
2594
2595 /* Try to figure out if this is really an EXPLAIN statement. If this
2596 ** cannot be verified, return early. */
2597 if( sqlite3_column_count(pSql)!=8 ){
2598 p->cMode = p->mode;
2599 return;
2600 }
2601 zSql = sqlite3_sql(pSql);
2602 if( zSql==0 ) return;
2603 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2604 if( sqlite3_strnicmp(z, "explain", 7) ){
2605 p->cMode = p->mode;
2606 return;
2607 }
2608
2609 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2610 int i;
2611 int iAddr = sqlite3_column_int(pSql, 0);
2612 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2613
2614 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2615 ** p2 is an instruction address, set variable p2op to the index of that
2616 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2617 ** the current instruction is part of a sub-program generated by an
2618 ** SQL trigger or foreign key. */
2619 int p2 = sqlite3_column_int(pSql, 3);
2620 int p2op = (p2 + (iOp-iAddr));
2621
2622 /* Grow the p->aiIndent array as required */
2623 if( iOp>=nAlloc ){
2624 if( iOp==0 ){
2625 /* Do further verfication that this is explain output. Abort if
2626 ** it is not */
2627 static const char *explainCols[] = {
2628 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2629 int jj;
2630 for(jj=0; jj<ArraySize(explainCols); jj++){
2631 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2632 p->cMode = p->mode;
2633 sqlite3_reset(pSql);
2634 return;
2635 }
2636 }
2637 }
2638 nAlloc += 100;
2639 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002640 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002641 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002642 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002643 }
2644 abYield[iOp] = str_in_array(zOp, azYield);
2645 p->aiIndent[iOp] = 0;
2646 p->nIndent = iOp+1;
2647
2648 if( str_in_array(zOp, azNext) ){
2649 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2650 }
2651 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2652 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2653 ){
2654 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2655 }
2656 }
2657
2658 p->iIndent = 0;
2659 sqlite3_free(abYield);
2660 sqlite3_reset(pSql);
2661}
2662
2663/*
2664** Free the array allocated by explain_data_prepare().
2665*/
2666static void explain_data_delete(ShellState *p){
2667 sqlite3_free(p->aiIndent);
2668 p->aiIndent = 0;
2669 p->nIndent = 0;
2670 p->iIndent = 0;
2671}
2672
2673/*
2674** Disable and restore .wheretrace and .selecttrace settings.
2675*/
2676#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2677extern int sqlite3SelectTrace;
2678static int savedSelectTrace;
2679#endif
2680#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2681extern int sqlite3WhereTrace;
2682static int savedWhereTrace;
2683#endif
2684static void disable_debug_trace_modes(void){
2685#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2686 savedSelectTrace = sqlite3SelectTrace;
2687 sqlite3SelectTrace = 0;
2688#endif
2689#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2690 savedWhereTrace = sqlite3WhereTrace;
2691 sqlite3WhereTrace = 0;
2692#endif
2693}
2694static void restore_debug_trace_modes(void){
2695#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2696 sqlite3SelectTrace = savedSelectTrace;
2697#endif
2698#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2699 sqlite3WhereTrace = savedWhereTrace;
2700#endif
2701}
2702
2703/*
2704** Run a prepared statement
2705*/
2706static void exec_prepared_stmt(
2707 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002708 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002709){
2710 int rc;
2711
2712 /* perform the first step. this will tell us if we
2713 ** have a result set or not and how wide it is.
2714 */
2715 rc = sqlite3_step(pStmt);
2716 /* if we have a result set... */
2717 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002718 /* allocate space for col name ptr, value ptr, and type */
2719 int nCol = sqlite3_column_count(pStmt);
2720 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2721 if( !pData ){
2722 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002723 }else{
drha10b9992018-03-09 15:24:33 +00002724 char **azCols = (char **)pData; /* Names of result columns */
2725 char **azVals = &azCols[nCol]; /* Results */
2726 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2727 int i, x;
2728 assert(sizeof(int) <= sizeof(char *));
2729 /* save off ptrs to column names */
2730 for(i=0; i<nCol; i++){
2731 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2732 }
drh2ce15c32017-07-11 13:34:40 +00002733 do{
drha10b9992018-03-09 15:24:33 +00002734 /* extract the data and data types */
2735 for(i=0; i<nCol; i++){
2736 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2737 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2738 azVals[i] = "";
2739 }else{
2740 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2741 }
2742 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2743 rc = SQLITE_NOMEM;
2744 break; /* from for */
2745 }
2746 } /* end for */
2747
2748 /* if data and types extracted successfully... */
2749 if( SQLITE_ROW == rc ){
2750 /* call the supplied callback with the result row data */
2751 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2752 rc = SQLITE_ABORT;
2753 }else{
2754 rc = sqlite3_step(pStmt);
2755 }
2756 }
2757 } while( SQLITE_ROW == rc );
2758 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002759 }
2760 }
2761}
2762
dan6b046be2018-01-09 15:25:55 +00002763#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002764/*
dan43efc182017-12-19 17:42:13 +00002765** This function is called to process SQL if the previous shell command
2766** was ".expert". It passes the SQL in the second argument directly to
2767** the sqlite3expert object.
2768**
2769** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2770** code. In this case, (*pzErr) may be set to point to a buffer containing
2771** an English language error message. It is the responsibility of the
2772** caller to eventually free this buffer using sqlite3_free().
2773*/
2774static int expertHandleSQL(
2775 ShellState *pState,
2776 const char *zSql,
2777 char **pzErr
2778){
2779 assert( pState->expert.pExpert );
2780 assert( pzErr==0 || *pzErr==0 );
2781 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2782}
2783
2784/*
2785** This function is called either to silently clean up the object
2786** created by the ".expert" command (if bCancel==1), or to generate a
2787** report from it and then clean it up (if bCancel==0).
2788**
2789** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2790** code. In this case, (*pzErr) may be set to point to a buffer containing
2791** an English language error message. It is the responsibility of the
2792** caller to eventually free this buffer using sqlite3_free().
2793*/
2794static int expertFinish(
2795 ShellState *pState,
2796 int bCancel,
2797 char **pzErr
2798){
2799 int rc = SQLITE_OK;
2800 sqlite3expert *p = pState->expert.pExpert;
2801 assert( p );
2802 assert( bCancel || pzErr==0 || *pzErr==0 );
2803 if( bCancel==0 ){
2804 FILE *out = pState->out;
2805 int bVerbose = pState->expert.bVerbose;
2806
2807 rc = sqlite3_expert_analyze(p, pzErr);
2808 if( rc==SQLITE_OK ){
2809 int nQuery = sqlite3_expert_count(p);
2810 int i;
2811
2812 if( bVerbose ){
2813 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2814 raw_printf(out, "-- Candidates -----------------------------\n");
2815 raw_printf(out, "%s\n", zCand);
2816 }
2817 for(i=0; i<nQuery; i++){
2818 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2819 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2820 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2821 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2822 if( bVerbose ){
2823 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2824 raw_printf(out, "%s\n\n", zSql);
2825 }
2826 raw_printf(out, "%s\n", zIdx);
2827 raw_printf(out, "%s\n", zEQP);
2828 }
2829 }
2830 }
2831 sqlite3_expert_destroy(p);
2832 pState->expert.pExpert = 0;
2833 return rc;
2834}
2835
dan6b046be2018-01-09 15:25:55 +00002836/*
2837** Implementation of ".expert" dot command.
2838*/
2839static int expertDotCommand(
2840 ShellState *pState, /* Current shell tool state */
2841 char **azArg, /* Array of arguments passed to dot command */
2842 int nArg /* Number of entries in azArg[] */
2843){
2844 int rc = SQLITE_OK;
2845 char *zErr = 0;
2846 int i;
2847 int iSample = 0;
2848
2849 assert( pState->expert.pExpert==0 );
2850 memset(&pState->expert, 0, sizeof(ExpertInfo));
2851
2852 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2853 char *z = azArg[i];
2854 int n;
2855 if( z[0]=='-' && z[1]=='-' ) z++;
2856 n = strlen30(z);
2857 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2858 pState->expert.bVerbose = 1;
2859 }
2860 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2861 if( i==(nArg-1) ){
2862 raw_printf(stderr, "option requires an argument: %s\n", z);
2863 rc = SQLITE_ERROR;
2864 }else{
2865 iSample = (int)integerValue(azArg[++i]);
2866 if( iSample<0 || iSample>100 ){
2867 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2868 rc = SQLITE_ERROR;
2869 }
2870 }
2871 }
2872 else{
2873 raw_printf(stderr, "unknown option: %s\n", z);
2874 rc = SQLITE_ERROR;
2875 }
2876 }
2877
2878 if( rc==SQLITE_OK ){
2879 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2880 if( pState->expert.pExpert==0 ){
2881 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2882 rc = SQLITE_ERROR;
2883 }else{
2884 sqlite3_expert_config(
2885 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2886 );
2887 }
2888 }
2889
2890 return rc;
2891}
2892#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00002893
2894/*
drh2ce15c32017-07-11 13:34:40 +00002895** Execute a statement or set of statements. Print
2896** any result rows/columns depending on the current mode
2897** set via the supplied callback.
2898**
2899** This is very similar to SQLite's built-in sqlite3_exec()
2900** function except it takes a slightly different callback
2901** and callback data argument.
2902*/
2903static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00002904 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002905 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00002906 char **pzErrMsg /* Error msg written here */
2907){
2908 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2909 int rc = SQLITE_OK; /* Return Code */
2910 int rc2;
2911 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00002912 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00002913
2914 if( pzErrMsg ){
2915 *pzErrMsg = NULL;
2916 }
2917
dan6b046be2018-01-09 15:25:55 +00002918#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00002919 if( pArg->expert.pExpert ){
2920 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2921 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2922 }
dan6b046be2018-01-09 15:25:55 +00002923#endif
dan43efc182017-12-19 17:42:13 +00002924
drh2ce15c32017-07-11 13:34:40 +00002925 while( zSql[0] && (SQLITE_OK == rc) ){
2926 static const char *zStmtSql;
2927 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2928 if( SQLITE_OK != rc ){
2929 if( pzErrMsg ){
2930 *pzErrMsg = save_err_msg(db);
2931 }
2932 }else{
2933 if( !pStmt ){
2934 /* this happens for a comment or white-space */
2935 zSql = zLeftover;
2936 while( IsSpace(zSql[0]) ) zSql++;
2937 continue;
2938 }
2939 zStmtSql = sqlite3_sql(pStmt);
2940 if( zStmtSql==0 ) zStmtSql = "";
2941 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2942
2943 /* save off the prepared statment handle and reset row count */
2944 if( pArg ){
2945 pArg->pStmt = pStmt;
2946 pArg->cnt = 0;
2947 }
2948
2949 /* echo the sql statement if echo on */
2950 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2951 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2952 }
2953
2954 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2955 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2956 sqlite3_stmt *pExplain;
2957 char *zEQP;
drhada70452017-12-21 21:02:27 +00002958 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002959 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002960 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2961 if( pArg->autoEQP>=AUTOEQP_trigger ){
2962 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2963 }
drh2ce15c32017-07-11 13:34:40 +00002964 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2965 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2966 if( rc==SQLITE_OK ){
2967 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00002968 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00002969 int iEqpId = sqlite3_column_int(pExplain, 0);
2970 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00002971 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00002972 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00002973 }
drh4b5345c2018-04-24 13:07:40 +00002974 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00002975 }
2976 sqlite3_finalize(pExplain);
2977 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002978 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002979 /* Also do an EXPLAIN for ".eqp full" mode */
2980 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2981 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2982 if( rc==SQLITE_OK ){
2983 pArg->cMode = MODE_Explain;
2984 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00002985 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00002986 explain_data_delete(pArg);
2987 }
2988 sqlite3_finalize(pExplain);
2989 sqlite3_free(zEQP);
2990 }
drh51efe092018-03-20 12:04:38 +00002991 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
2992 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
2993 /* Reprepare pStmt before reactiving trace modes */
2994 sqlite3_finalize(pStmt);
2995 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00002996 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00002997 }
drh2ce15c32017-07-11 13:34:40 +00002998 restore_debug_trace_modes();
2999 }
3000
3001 if( pArg ){
3002 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003003 if( pArg->autoExplain ){
3004 if( sqlite3_column_count(pStmt)==8
3005 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
3006 ){
3007 pArg->cMode = MODE_Explain;
3008 }
3009 if( sqlite3_column_count(pStmt)==4
3010 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
3011 pArg->cMode = MODE_EQP;
3012 }
drh2ce15c32017-07-11 13:34:40 +00003013 }
3014
3015 /* If the shell is currently in ".explain" mode, gather the extra
3016 ** data required to add indents to the output.*/
3017 if( pArg->cMode==MODE_Explain ){
3018 explain_data_prepare(pArg, pStmt);
3019 }
3020 }
3021
drha10b9992018-03-09 15:24:33 +00003022 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003023 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003024 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003025
3026 /* print usage stats if stats on */
3027 if( pArg && pArg->statsOn ){
3028 display_stats(db, pArg, 0);
3029 }
3030
3031 /* print loop-counters if required */
3032 if( pArg && pArg->scanstatsOn ){
3033 display_scanstats(db, pArg);
3034 }
3035
3036 /* Finalize the statement just executed. If this fails, save a
3037 ** copy of the error message. Otherwise, set zSql to point to the
3038 ** next statement to execute. */
3039 rc2 = sqlite3_finalize(pStmt);
3040 if( rc!=SQLITE_NOMEM ) rc = rc2;
3041 if( rc==SQLITE_OK ){
3042 zSql = zLeftover;
3043 while( IsSpace(zSql[0]) ) zSql++;
3044 }else if( pzErrMsg ){
3045 *pzErrMsg = save_err_msg(db);
3046 }
3047
3048 /* clear saved stmt handle */
3049 if( pArg ){
3050 pArg->pStmt = NULL;
3051 }
3052 }
3053 } /* end while */
3054
3055 return rc;
3056}
3057
3058/*
3059** Release memory previously allocated by tableColumnList().
3060*/
3061static void freeColumnList(char **azCol){
3062 int i;
3063 for(i=1; azCol[i]; i++){
3064 sqlite3_free(azCol[i]);
3065 }
3066 /* azCol[0] is a static string */
3067 sqlite3_free(azCol);
3068}
3069
3070/*
3071** Return a list of pointers to strings which are the names of all
3072** columns in table zTab. The memory to hold the names is dynamically
3073** allocated and must be released by the caller using a subsequent call
3074** to freeColumnList().
3075**
3076** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3077** value that needs to be preserved, then azCol[0] is filled in with the
3078** name of the rowid column.
3079**
3080** The first regular column in the table is azCol[1]. The list is terminated
3081** by an entry with azCol[i]==0.
3082*/
3083static char **tableColumnList(ShellState *p, const char *zTab){
3084 char **azCol = 0;
3085 sqlite3_stmt *pStmt;
3086 char *zSql;
3087 int nCol = 0;
3088 int nAlloc = 0;
3089 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3090 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3091 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3092 int rc;
3093
3094 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3095 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3096 sqlite3_free(zSql);
3097 if( rc ) return 0;
3098 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3099 if( nCol>=nAlloc-2 ){
3100 nAlloc = nAlloc*2 + nCol + 10;
3101 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003102 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003103 }
3104 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3105 if( sqlite3_column_int(pStmt, 5) ){
3106 nPK++;
3107 if( nPK==1
3108 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3109 "INTEGER")==0
3110 ){
3111 isIPK = 1;
3112 }else{
3113 isIPK = 0;
3114 }
3115 }
3116 }
3117 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003118 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003119 azCol[0] = 0;
3120 azCol[nCol+1] = 0;
3121
3122 /* The decision of whether or not a rowid really needs to be preserved
3123 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3124 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3125 ** rowids on tables where the rowid is inaccessible because there are other
3126 ** columns in the table named "rowid", "_rowid_", and "oid".
3127 */
3128 if( preserveRowid && isIPK ){
3129 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3130 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3131 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3132 ** ROWID aliases. To distinguish these cases, check to see if
3133 ** there is a "pk" entry in "PRAGMA index_list". There will be
3134 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3135 */
3136 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3137 " WHERE origin='pk'", zTab);
3138 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3139 sqlite3_free(zSql);
3140 if( rc ){
3141 freeColumnList(azCol);
3142 return 0;
3143 }
3144 rc = sqlite3_step(pStmt);
3145 sqlite3_finalize(pStmt);
3146 preserveRowid = rc==SQLITE_ROW;
3147 }
3148 if( preserveRowid ){
3149 /* Only preserve the rowid if we can find a name to use for the
3150 ** rowid */
3151 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3152 int i, j;
3153 for(j=0; j<3; j++){
3154 for(i=1; i<=nCol; i++){
3155 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3156 }
3157 if( i>nCol ){
3158 /* At this point, we know that azRowid[j] is not the name of any
3159 ** ordinary column in the table. Verify that azRowid[j] is a valid
3160 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3161 ** tables will fail this last check */
3162 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3163 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3164 break;
3165 }
3166 }
3167 }
3168 return azCol;
3169}
3170
3171/*
3172** Toggle the reverse_unordered_selects setting.
3173*/
3174static void toggleSelectOrder(sqlite3 *db){
3175 sqlite3_stmt *pStmt = 0;
3176 int iSetting = 0;
3177 char zStmt[100];
3178 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3179 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3180 iSetting = sqlite3_column_int(pStmt, 0);
3181 }
3182 sqlite3_finalize(pStmt);
3183 sqlite3_snprintf(sizeof(zStmt), zStmt,
3184 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3185 sqlite3_exec(db, zStmt, 0, 0, 0);
3186}
3187
3188/*
3189** This is a different callback routine used for dumping the database.
3190** Each row received by this callback consists of a table name,
3191** the table type ("index" or "table") and SQL to create the table.
3192** This routine should print text sufficient to recreate the table.
3193*/
3194static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3195 int rc;
3196 const char *zTable;
3197 const char *zType;
3198 const char *zSql;
3199 ShellState *p = (ShellState *)pArg;
3200
3201 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003202 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003203 zTable = azArg[0];
3204 zType = azArg[1];
3205 zSql = azArg[2];
3206
3207 if( strcmp(zTable, "sqlite_sequence")==0 ){
3208 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3209 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3210 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3211 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3212 return 0;
3213 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3214 char *zIns;
3215 if( !p->writableSchema ){
3216 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3217 p->writableSchema = 1;
3218 }
3219 zIns = sqlite3_mprintf(
3220 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3221 "VALUES('table','%q','%q',0,'%q');",
3222 zTable, zTable, zSql);
3223 utf8_printf(p->out, "%s\n", zIns);
3224 sqlite3_free(zIns);
3225 return 0;
3226 }else{
3227 printSchemaLine(p->out, zSql, ";\n");
3228 }
3229
3230 if( strcmp(zType, "table")==0 ){
3231 ShellText sSelect;
3232 ShellText sTable;
3233 char **azCol;
3234 int i;
3235 char *savedDestTable;
3236 int savedMode;
3237
3238 azCol = tableColumnList(p, zTable);
3239 if( azCol==0 ){
3240 p->nErr++;
3241 return 0;
3242 }
3243
3244 /* Always quote the table name, even if it appears to be pure ascii,
3245 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3246 initText(&sTable);
3247 appendText(&sTable, zTable, quoteChar(zTable));
3248 /* If preserving the rowid, add a column list after the table name.
3249 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3250 ** instead of the usual "INSERT INTO tab VALUES(...)".
3251 */
3252 if( azCol[0] ){
3253 appendText(&sTable, "(", 0);
3254 appendText(&sTable, azCol[0], 0);
3255 for(i=1; azCol[i]; i++){
3256 appendText(&sTable, ",", 0);
3257 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3258 }
3259 appendText(&sTable, ")", 0);
3260 }
3261
3262 /* Build an appropriate SELECT statement */
3263 initText(&sSelect);
3264 appendText(&sSelect, "SELECT ", 0);
3265 if( azCol[0] ){
3266 appendText(&sSelect, azCol[0], 0);
3267 appendText(&sSelect, ",", 0);
3268 }
3269 for(i=1; azCol[i]; i++){
3270 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3271 if( azCol[i+1] ){
3272 appendText(&sSelect, ",", 0);
3273 }
3274 }
3275 freeColumnList(azCol);
3276 appendText(&sSelect, " FROM ", 0);
3277 appendText(&sSelect, zTable, quoteChar(zTable));
3278
3279 savedDestTable = p->zDestTable;
3280 savedMode = p->mode;
3281 p->zDestTable = sTable.z;
3282 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003283 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003284 if( (rc&0xff)==SQLITE_CORRUPT ){
3285 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3286 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003287 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003288 toggleSelectOrder(p->db);
3289 }
3290 p->zDestTable = savedDestTable;
3291 p->mode = savedMode;
3292 freeText(&sTable);
3293 freeText(&sSelect);
3294 if( rc ) p->nErr++;
3295 }
3296 return 0;
3297}
3298
3299/*
3300** Run zQuery. Use dump_callback() as the callback routine so that
3301** the contents of the query are output as SQL statements.
3302**
3303** If we get a SQLITE_CORRUPT error, rerun the query after appending
3304** "ORDER BY rowid DESC" to the end.
3305*/
3306static int run_schema_dump_query(
3307 ShellState *p,
3308 const char *zQuery
3309){
3310 int rc;
3311 char *zErr = 0;
3312 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3313 if( rc==SQLITE_CORRUPT ){
3314 char *zQ2;
3315 int len = strlen30(zQuery);
3316 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3317 if( zErr ){
3318 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3319 sqlite3_free(zErr);
3320 zErr = 0;
3321 }
3322 zQ2 = malloc( len+100 );
3323 if( zQ2==0 ) return rc;
3324 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3325 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3326 if( rc ){
3327 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3328 }else{
3329 rc = SQLITE_CORRUPT;
3330 }
3331 sqlite3_free(zErr);
3332 free(zQ2);
3333 }
3334 return rc;
3335}
3336
3337/*
drh98aa2ab2018-09-26 16:53:51 +00003338** Text of help messages.
3339**
3340** The help text for each individual command begins with a line that starts
3341** with ".". Subsequent lines are supplimental information.
3342**
3343** There must be two or more spaces between the end of the command and the
3344** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003345*/
drh98aa2ab2018-09-26 16:53:51 +00003346static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003347#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003348 ".archive ... Manage SQL archives",
3349 " Each command must have exactly one of the following options:",
3350 " -c, --create Create a new archive",
3351 " -u, --update Update or add files to an existing archive",
3352 " -t, --list List contents of archive",
3353 " -x, --extract Extract files from archive",
3354 " Optional arguments:",
3355 " -v, --verbose Print each filename as it is processed",
3356 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3357 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3358 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3359 " -n, --dryrun Show the SQL that would have occurred",
3360 " Examples:",
3361 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3362 " .ar -tf archive.sar # List members of archive.sar",
3363 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3364 " See also:",
3365 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003366#endif
drh2ce15c32017-07-11 13:34:40 +00003367#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003368 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003369#endif
drh98aa2ab2018-09-26 16:53:51 +00003370 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3371 " --append Use the appendvfs",
3372 ".bail on|off Stop after hitting an error. Default OFF",
3373 ".binary on|off Turn binary output on or off. Default OFF",
3374 ".cd DIRECTORY Change the working directory to DIRECTORY",
3375 ".changes on|off Show number of rows changed by SQL",
3376 ".check GLOB Fail if output since .testcase does not match",
3377 ".clone NEWDB Clone data into NEWDB from the existing database",
3378 ".databases List names and files of attached databases",
3379 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3380 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003381 ".dump ?TABLE? ... Render all database content as SQL",
3382 " Options:",
3383 " --preserve-rowids Include ROWID values in the output",
3384 " --newlines Allow unescaped newline characters in output",
3385 " TABLE is LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003386 ".echo on|off Turn command echo on or off",
3387 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN",
3388 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003389 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003390 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003391/* Because explain mode comes on automatically now, the ".explain" mode
3392** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003393/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3394 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3395 ".headers on|off Turn display of headers on or off",
3396 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3397 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003398#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003399 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003400#endif
drh98aa2ab2018-09-26 16:53:51 +00003401 ".indexes ?TABLE? Show names of indexes",
3402 " If TABLE is specified, only show indexes for",
3403 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003404#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003405 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003406#endif
drh98aa2ab2018-09-26 16:53:51 +00003407 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3408 ".lint OPTIONS Report potential schema issues.",
3409 " Options:",
3410 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003411#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003412 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003413#endif
drh98aa2ab2018-09-26 16:53:51 +00003414 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3415 ".mode MODE ?TABLE? Set output mode",
3416 " MODE is one of:",
3417 " ascii Columns/rows delimited by 0x1F and 0x1E",
3418 " csv Comma-separated values",
3419 " column Left-aligned columns. (See .width)",
3420 " html HTML <table> code",
3421 " insert SQL insert statements for TABLE",
3422 " line One value per line",
3423 " list Values delimited by \"|\"",
3424 " quote Escape answers as for SQL",
3425 " tabs Tab-separated values",
3426 " tcl TCL list elements",
3427 ".nullvalue STRING Use STRING in place of NULL values",
3428 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3429 " If FILE begins with '|' then open as a pipe",
3430 " Other options:",
3431 " -e Invoke system text editor",
3432 " -x Open in a spreadsheet",
3433 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3434 " Options:",
3435 " --append Use appendvfs to append database to the end of FILE",
3436 " --new Initialize FILE to an empty database",
3437 " --readonly Open FILE readonly",
3438 " --zip FILE is a ZIP archive",
3439 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3440 " If FILE begins with '|' then open it as a pipe.",
3441 ".print STRING... Print literal STRING",
3442 ".prompt MAIN CONTINUE Replace the standard prompts",
3443 ".quit Exit this program",
3444 ".read FILE Read input from FILE",
3445 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3446 ".save FILE Write in-memory database into FILE",
3447 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3448 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3449 " Options:",
3450 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003451 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3452 " Options:",
3453 " --init Create a new SELFTEST table",
3454 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003455 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003456#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003457 ".session ?NAME? CMD ... Create or control sessions",
3458 " Subcommands:",
3459 " attach TABLE Attach TABLE",
3460 " changeset FILE Write a changeset into FILE",
3461 " close Close one session",
3462 " enable ?BOOLEAN? Set or query the enable bit",
3463 " filter GLOB... Reject tables matching GLOBs",
3464 " indirect ?BOOLEAN? Mark or query the indirect status",
3465 " isempty Query whether the session is empty",
3466 " list List currently open session names",
3467 " open DB NAME Open a new session on DB",
3468 " patchset FILE Write a patchset into FILE",
3469 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003470#endif
drheb7f2a02018-09-26 18:02:32 +00003471 ".sha3sum ... Compute a SHA3 hash of database content",
3472 " Options:",
3473 " --schema Also hash the sqlite_master table",
3474 " --sha3-224 Use the sha3-224 algorithm",
3475 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3476 " --sha3-384 Use the sha3-384 algorithm",
3477 " --sha3-512 Use the sha3-512 algorithm",
3478 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003479#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003480 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003481#endif
drh98aa2ab2018-09-26 16:53:51 +00003482 ".show Show the current values for various settings",
3483 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003484#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003485 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003486#endif
drh98aa2ab2018-09-26 16:53:51 +00003487 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3488 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3489 ".timeout MS Try opening locked tables for MS milliseconds",
3490 ".timer on|off Turn SQL timer on or off",
3491 ".trace FILE|off Output each SQL statement as it is run",
3492 ".vfsinfo ?AUX? Information about the top-level VFS",
3493 ".vfslist List all available VFSes",
3494 ".vfsname ?AUX? Print the name of the VFS stack",
3495 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3496 " Negative values right-justify",
3497};
3498
3499/*
3500** Output help text.
3501**
3502** zPattern describes the set of commands for which help text is provided.
3503** If zPattern is NULL, then show all commands, but only give a one-line
3504** description of each.
3505**
3506** Return the number of matches.
3507*/
3508static int showHelp(FILE *out, const char *zPattern){
3509 int i, j;
3510 int n = 0;
3511 char *zPat;
3512 if( zPattern==0 || zPattern[0]=='0' ){
3513 /* Show all commands, but only one line per command */
3514 for(i=0; i<ArraySize(azHelp); i++){
3515 if( azHelp[i][0]=='.' ){
3516 utf8_printf(out, "%s\n", azHelp[i]);
3517 n++;
3518 }
3519 }
3520 }else{
3521 /* Look for commands that for which zPattern is an exact prefix */
3522 zPat = sqlite3_mprintf(".%s*", zPattern);
3523 for(i=0; i<ArraySize(azHelp); i++){
3524 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3525 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003526 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003527 n++;
3528 }
3529 }
3530 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003531 if( n ){
3532 if( n==1 ){
3533 /* when zPattern is a prefix of exactly one command, then include the
3534 ** details of that command, which should begin at offset j */
3535 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3536 utf8_printf(out, "%s\n", azHelp[j]);
3537 j++;
3538 }
3539 }
3540 return n;
3541 }
3542 /* Look for commands that contain zPattern anywhere. Show the complete
3543 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003544 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3545 for(i=0; i<ArraySize(azHelp); i++){
3546 if( azHelp[i][0]=='.' ) j = i;
3547 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3548 utf8_printf(out, "%s\n", azHelp[j]);
3549 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3550 j++;
3551 utf8_printf(out, "%s\n", azHelp[j]);
3552 }
3553 i = j;
3554 n++;
3555 }
3556 }
3557 sqlite3_free(zPat);
3558 }
3559 return n;
3560}
drh2ce15c32017-07-11 13:34:40 +00003561
drh2ce15c32017-07-11 13:34:40 +00003562/* Forward reference */
3563static int process_input(ShellState *p, FILE *in);
3564
3565/*
3566** Read the content of file zName into memory obtained from sqlite3_malloc64()
3567** and return a pointer to the buffer. The caller is responsible for freeing
3568** the memory.
3569**
3570** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3571** read.
3572**
3573** For convenience, a nul-terminator byte is always appended to the data read
3574** from the file before the buffer is returned. This byte is not included in
3575** the final value of (*pnByte), if applicable.
3576**
3577** NULL is returned if any error is encountered. The final value of *pnByte
3578** is undefined in this case.
3579*/
3580static char *readFile(const char *zName, int *pnByte){
3581 FILE *in = fopen(zName, "rb");
3582 long nIn;
3583 size_t nRead;
3584 char *pBuf;
3585 if( in==0 ) return 0;
3586 fseek(in, 0, SEEK_END);
3587 nIn = ftell(in);
3588 rewind(in);
3589 pBuf = sqlite3_malloc64( nIn+1 );
3590 if( pBuf==0 ) return 0;
3591 nRead = fread(pBuf, nIn, 1, in);
3592 fclose(in);
3593 if( nRead!=1 ){
3594 sqlite3_free(pBuf);
3595 return 0;
3596 }
3597 pBuf[nIn] = 0;
3598 if( pnByte ) *pnByte = nIn;
3599 return pBuf;
3600}
3601
3602#if defined(SQLITE_ENABLE_SESSION)
3603/*
3604** Close a single OpenSession object and release all of its associated
3605** resources.
3606*/
3607static void session_close(OpenSession *pSession){
3608 int i;
3609 sqlite3session_delete(pSession->p);
3610 sqlite3_free(pSession->zName);
3611 for(i=0; i<pSession->nFilter; i++){
3612 sqlite3_free(pSession->azFilter[i]);
3613 }
3614 sqlite3_free(pSession->azFilter);
3615 memset(pSession, 0, sizeof(OpenSession));
3616}
3617#endif
3618
3619/*
3620** Close all OpenSession objects and release all associated resources.
3621*/
3622#if defined(SQLITE_ENABLE_SESSION)
3623static void session_close_all(ShellState *p){
3624 int i;
3625 for(i=0; i<p->nSession; i++){
3626 session_close(&p->aSession[i]);
3627 }
3628 p->nSession = 0;
3629}
3630#else
3631# define session_close_all(X)
3632#endif
3633
3634/*
3635** Implementation of the xFilter function for an open session. Omit
3636** any tables named by ".session filter" but let all other table through.
3637*/
3638#if defined(SQLITE_ENABLE_SESSION)
3639static int session_filter(void *pCtx, const char *zTab){
3640 OpenSession *pSession = (OpenSession*)pCtx;
3641 int i;
3642 for(i=0; i<pSession->nFilter; i++){
3643 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3644 }
3645 return 1;
3646}
3647#endif
3648
3649/*
drh1fa6d9f2018-01-06 21:46:01 +00003650** Try to deduce the type of file for zName based on its content. Return
3651** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003652**
3653** If the file does not exist or is empty but its name looks like a ZIP
3654** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3655** Otherwise, assume an ordinary database regardless of the filename if
3656** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003657*/
drhfc97c1c2018-05-14 00:41:12 +00003658int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003659 FILE *f = fopen(zName, "rb");
3660 size_t n;
3661 int rc = SHELL_OPEN_UNSPEC;
3662 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003663 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003664 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3665 return SHELL_OPEN_ZIPFILE;
3666 }else{
3667 return SHELL_OPEN_NORMAL;
3668 }
drh1bf208c2018-03-09 21:54:01 +00003669 }
drh1fa6d9f2018-01-06 21:46:01 +00003670 fseek(f, -25, SEEK_END);
3671 n = fread(zBuf, 25, 1, f);
3672 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3673 rc = SHELL_OPEN_APPENDVFS;
3674 }else{
3675 fseek(f, -22, SEEK_END);
3676 n = fread(zBuf, 22, 1, f);
3677 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3678 && zBuf[3]==0x06 ){
3679 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003680 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003681 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003682 }
3683 }
3684 fclose(f);
3685 return rc;
3686}
3687
drhbe4ccb22018-05-17 20:04:24 +00003688/* Flags for open_db().
3689**
3690** The default behavior of open_db() is to exit(1) if the database fails to
3691** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3692** but still returns without calling exit.
3693**
3694** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3695** ZIP archive if the file does not exist or is empty and its name matches
3696** the *.zip pattern.
3697*/
3698#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3699#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3700
drh1fa6d9f2018-01-06 21:46:01 +00003701/*
drh2ce15c32017-07-11 13:34:40 +00003702** Make sure the database is open. If it is not, then open it. If
3703** the database fails to open, print an error message and exit.
3704*/
drhbe4ccb22018-05-17 20:04:24 +00003705static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00003706 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00003707 if( p->openMode==SHELL_OPEN_UNSPEC ){
3708 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3709 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00003710 }else{
3711 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3712 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00003713 }
drh1fa6d9f2018-01-06 21:46:01 +00003714 }
3715 switch( p->openMode ){
3716 case SHELL_OPEN_APPENDVFS: {
3717 sqlite3_open_v2(p->zDbFilename, &p->db,
3718 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3719 break;
3720 }
3721 case SHELL_OPEN_ZIPFILE: {
3722 sqlite3_open(":memory:", &p->db);
3723 break;
3724 }
drhee269a62018-02-14 23:27:43 +00003725 case SHELL_OPEN_READONLY: {
3726 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3727 break;
3728 }
drh1fa6d9f2018-01-06 21:46:01 +00003729 case SHELL_OPEN_UNSPEC:
3730 case SHELL_OPEN_NORMAL: {
3731 sqlite3_open(p->zDbFilename, &p->db);
3732 break;
3733 }
3734 }
drh2ce15c32017-07-11 13:34:40 +00003735 globalDb = p->db;
3736 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3737 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3738 p->zDbFilename, sqlite3_errmsg(p->db));
drhbe4ccb22018-05-17 20:04:24 +00003739 if( openFlags & OPEN_DB_KEEPALIVE ) return;
drh2ce15c32017-07-11 13:34:40 +00003740 exit(1);
3741 }
3742#ifndef SQLITE_OMIT_LOAD_EXTENSION
3743 sqlite3_enable_load_extension(p->db, 1);
3744#endif
3745 sqlite3_fileio_init(p->db, 0, 0);
3746 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003747 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003748#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003749 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003750 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003751#endif
drhceba7922018-01-01 21:28:25 +00003752 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003753 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003754 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3755 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00003756 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3757 shellPutsFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003758#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00003759 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3760 editFunc, 0, 0);
3761 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3762 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003763#endif
drh1fa6d9f2018-01-06 21:46:01 +00003764 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3765 char *zSql = sqlite3_mprintf(
3766 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3767 sqlite3_exec(p->db, zSql, 0, 0, 0);
3768 sqlite3_free(zSql);
3769 }
drh2ce15c32017-07-11 13:34:40 +00003770 }
3771}
3772
drh9e804032018-05-18 17:11:50 +00003773/*
3774** Attempt to close the databaes connection. Report errors.
3775*/
3776void close_db(sqlite3 *db){
3777 int rc = sqlite3_close(db);
3778 if( rc ){
3779 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
3780 rc, sqlite3_errmsg(db));
3781 }
3782}
3783
drh56eb09b2017-07-11 13:59:07 +00003784#if HAVE_READLINE || HAVE_EDITLINE
3785/*
3786** Readline completion callbacks
3787*/
3788static char *readline_completion_generator(const char *text, int state){
3789 static sqlite3_stmt *pStmt = 0;
3790 char *zRet;
3791 if( state==0 ){
3792 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003793 sqlite3_finalize(pStmt);
3794 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3795 " FROM completion(%Q) ORDER BY 1", text);
3796 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3797 sqlite3_free(zSql);
3798 }
3799 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003800 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003801 }else{
3802 sqlite3_finalize(pStmt);
3803 pStmt = 0;
3804 zRet = 0;
3805 }
3806 return zRet;
3807}
3808static char **readline_completion(const char *zText, int iStart, int iEnd){
3809 rl_attempted_completion_over = 1;
3810 return rl_completion_matches(zText, readline_completion_generator);
3811}
3812
3813#elif HAVE_LINENOISE
3814/*
3815** Linenoise completion callback
3816*/
3817static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003818 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003819 int i, iStart;
3820 sqlite3_stmt *pStmt = 0;
3821 char *zSql;
3822 char zBuf[1000];
3823
3824 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00003825 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00003826 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3827 if( i==nLine-1 ) return;
3828 iStart = i+1;
3829 memcpy(zBuf, zLine, iStart);
3830 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3831 " FROM completion(%Q,%Q) ORDER BY 1",
3832 &zLine[iStart], zLine);
3833 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3834 sqlite3_free(zSql);
3835 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3836 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3837 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3838 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3839 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3840 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3841 linenoiseAddCompletion(lc, zBuf);
3842 }
3843 }
3844 sqlite3_finalize(pStmt);
3845}
3846#endif
3847
drh2ce15c32017-07-11 13:34:40 +00003848/*
3849** Do C-language style dequoting.
3850**
3851** \a -> alarm
3852** \b -> backspace
3853** \t -> tab
3854** \n -> newline
3855** \v -> vertical tab
3856** \f -> form feed
3857** \r -> carriage return
3858** \s -> space
3859** \" -> "
3860** \' -> '
3861** \\ -> backslash
3862** \NNN -> ascii character NNN in octal
3863*/
3864static void resolve_backslashes(char *z){
3865 int i, j;
3866 char c;
3867 while( *z && *z!='\\' ) z++;
3868 for(i=j=0; (c = z[i])!=0; i++, j++){
3869 if( c=='\\' && z[i+1]!=0 ){
3870 c = z[++i];
3871 if( c=='a' ){
3872 c = '\a';
3873 }else if( c=='b' ){
3874 c = '\b';
3875 }else if( c=='t' ){
3876 c = '\t';
3877 }else if( c=='n' ){
3878 c = '\n';
3879 }else if( c=='v' ){
3880 c = '\v';
3881 }else if( c=='f' ){
3882 c = '\f';
3883 }else if( c=='r' ){
3884 c = '\r';
3885 }else if( c=='"' ){
3886 c = '"';
3887 }else if( c=='\'' ){
3888 c = '\'';
3889 }else if( c=='\\' ){
3890 c = '\\';
3891 }else if( c>='0' && c<='7' ){
3892 c -= '0';
3893 if( z[i+1]>='0' && z[i+1]<='7' ){
3894 i++;
3895 c = (c<<3) + z[i] - '0';
3896 if( z[i+1]>='0' && z[i+1]<='7' ){
3897 i++;
3898 c = (c<<3) + z[i] - '0';
3899 }
3900 }
3901 }
3902 }
3903 z[j] = c;
3904 }
3905 if( j<i ) z[j] = 0;
3906}
3907
3908/*
drh2ce15c32017-07-11 13:34:40 +00003909** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3910** for TRUE and FALSE. Return the integer value if appropriate.
3911*/
3912static int booleanValue(const char *zArg){
3913 int i;
3914 if( zArg[0]=='0' && zArg[1]=='x' ){
3915 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3916 }else{
3917 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3918 }
3919 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3920 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3921 return 1;
3922 }
3923 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3924 return 0;
3925 }
3926 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3927 zArg);
3928 return 0;
3929}
3930
3931/*
3932** Set or clear a shell flag according to a boolean value.
3933*/
3934static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3935 if( booleanValue(zArg) ){
3936 ShellSetFlag(p, mFlag);
3937 }else{
3938 ShellClearFlag(p, mFlag);
3939 }
3940}
3941
3942/*
3943** Close an output file, assuming it is not stderr or stdout
3944*/
3945static void output_file_close(FILE *f){
3946 if( f && f!=stdout && f!=stderr ) fclose(f);
3947}
3948
3949/*
3950** Try to open an output file. The names "stdout" and "stderr" are
3951** recognized and do the right thing. NULL is returned if the output
3952** filename is "off".
3953*/
drha92a01a2018-01-10 22:15:37 +00003954static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00003955 FILE *f;
3956 if( strcmp(zFile,"stdout")==0 ){
3957 f = stdout;
3958 }else if( strcmp(zFile, "stderr")==0 ){
3959 f = stderr;
3960 }else if( strcmp(zFile, "off")==0 ){
3961 f = 0;
3962 }else{
drha92a01a2018-01-10 22:15:37 +00003963 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00003964 if( f==0 ){
3965 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3966 }
3967 }
3968 return f;
3969}
3970
drh2ce15c32017-07-11 13:34:40 +00003971#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3972/*
3973** A routine for handling output from sqlite3_trace().
3974*/
3975static int sql_trace_callback(
3976 unsigned mType,
3977 void *pArg,
3978 void *pP,
3979 void *pX
3980){
3981 FILE *f = (FILE*)pArg;
3982 UNUSED_PARAMETER(mType);
3983 UNUSED_PARAMETER(pP);
3984 if( f ){
3985 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00003986 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00003987 while( i>0 && z[i-1]==';' ){ i--; }
3988 utf8_printf(f, "%.*s;\n", i, z);
3989 }
3990 return 0;
3991}
3992#endif
drh2ce15c32017-07-11 13:34:40 +00003993
3994/*
3995** A no-op routine that runs with the ".breakpoint" doc-command. This is
3996** a useful spot to set a debugger breakpoint.
3997*/
3998static void test_breakpoint(void){
3999 static int nCall = 0;
4000 nCall++;
4001}
4002
4003/*
4004** An object used to read a CSV and other files for import.
4005*/
4006typedef struct ImportCtx ImportCtx;
4007struct ImportCtx {
4008 const char *zFile; /* Name of the input file */
4009 FILE *in; /* Read the CSV text from this input stream */
4010 char *z; /* Accumulated text for a field */
4011 int n; /* Number of bytes in z */
4012 int nAlloc; /* Space allocated for z[] */
4013 int nLine; /* Current line number */
4014 int bNotFirst; /* True if one or more bytes already read */
4015 int cTerm; /* Character that terminated the most recent field */
4016 int cColSep; /* The column separator character. (Usually ",") */
4017 int cRowSep; /* The row separator character. (Usually "\n") */
4018};
4019
4020/* Append a single byte to z[] */
4021static void import_append_char(ImportCtx *p, int c){
4022 if( p->n+1>=p->nAlloc ){
4023 p->nAlloc += p->nAlloc + 100;
4024 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004025 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004026 }
4027 p->z[p->n++] = (char)c;
4028}
4029
4030/* Read a single field of CSV text. Compatible with rfc4180 and extended
4031** with the option of having a separator other than ",".
4032**
4033** + Input comes from p->in.
4034** + Store results in p->z of length p->n. Space to hold p->z comes
4035** from sqlite3_malloc64().
4036** + Use p->cSep as the column separator. The default is ",".
4037** + Use p->rSep as the row separator. The default is "\n".
4038** + Keep track of the line number in p->nLine.
4039** + Store the character that terminates the field in p->cTerm. Store
4040** EOF on end-of-file.
4041** + Report syntax errors on stderr
4042*/
4043static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4044 int c;
4045 int cSep = p->cColSep;
4046 int rSep = p->cRowSep;
4047 p->n = 0;
4048 c = fgetc(p->in);
4049 if( c==EOF || seenInterrupt ){
4050 p->cTerm = EOF;
4051 return 0;
4052 }
4053 if( c=='"' ){
4054 int pc, ppc;
4055 int startLine = p->nLine;
4056 int cQuote = c;
4057 pc = ppc = 0;
4058 while( 1 ){
4059 c = fgetc(p->in);
4060 if( c==rSep ) p->nLine++;
4061 if( c==cQuote ){
4062 if( pc==cQuote ){
4063 pc = 0;
4064 continue;
4065 }
4066 }
4067 if( (c==cSep && pc==cQuote)
4068 || (c==rSep && pc==cQuote)
4069 || (c==rSep && pc=='\r' && ppc==cQuote)
4070 || (c==EOF && pc==cQuote)
4071 ){
4072 do{ p->n--; }while( p->z[p->n]!=cQuote );
4073 p->cTerm = c;
4074 break;
4075 }
4076 if( pc==cQuote && c!='\r' ){
4077 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4078 p->zFile, p->nLine, cQuote);
4079 }
4080 if( c==EOF ){
4081 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4082 p->zFile, startLine, cQuote);
4083 p->cTerm = c;
4084 break;
4085 }
4086 import_append_char(p, c);
4087 ppc = pc;
4088 pc = c;
4089 }
4090 }else{
4091 /* If this is the first field being parsed and it begins with the
4092 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4093 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4094 import_append_char(p, c);
4095 c = fgetc(p->in);
4096 if( (c&0xff)==0xbb ){
4097 import_append_char(p, c);
4098 c = fgetc(p->in);
4099 if( (c&0xff)==0xbf ){
4100 p->bNotFirst = 1;
4101 p->n = 0;
4102 return csv_read_one_field(p);
4103 }
4104 }
4105 }
4106 while( c!=EOF && c!=cSep && c!=rSep ){
4107 import_append_char(p, c);
4108 c = fgetc(p->in);
4109 }
4110 if( c==rSep ){
4111 p->nLine++;
4112 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4113 }
4114 p->cTerm = c;
4115 }
4116 if( p->z ) p->z[p->n] = 0;
4117 p->bNotFirst = 1;
4118 return p->z;
4119}
4120
4121/* Read a single field of ASCII delimited text.
4122**
4123** + Input comes from p->in.
4124** + Store results in p->z of length p->n. Space to hold p->z comes
4125** from sqlite3_malloc64().
4126** + Use p->cSep as the column separator. The default is "\x1F".
4127** + Use p->rSep as the row separator. The default is "\x1E".
4128** + Keep track of the row number in p->nLine.
4129** + Store the character that terminates the field in p->cTerm. Store
4130** EOF on end-of-file.
4131** + Report syntax errors on stderr
4132*/
4133static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4134 int c;
4135 int cSep = p->cColSep;
4136 int rSep = p->cRowSep;
4137 p->n = 0;
4138 c = fgetc(p->in);
4139 if( c==EOF || seenInterrupt ){
4140 p->cTerm = EOF;
4141 return 0;
4142 }
4143 while( c!=EOF && c!=cSep && c!=rSep ){
4144 import_append_char(p, c);
4145 c = fgetc(p->in);
4146 }
4147 if( c==rSep ){
4148 p->nLine++;
4149 }
4150 p->cTerm = c;
4151 if( p->z ) p->z[p->n] = 0;
4152 return p->z;
4153}
4154
4155/*
4156** Try to transfer data for table zTable. If an error is seen while
4157** moving forward, try to go backwards. The backwards movement won't
4158** work for WITHOUT ROWID tables.
4159*/
4160static void tryToCloneData(
4161 ShellState *p,
4162 sqlite3 *newDb,
4163 const char *zTable
4164){
4165 sqlite3_stmt *pQuery = 0;
4166 sqlite3_stmt *pInsert = 0;
4167 char *zQuery = 0;
4168 char *zInsert = 0;
4169 int rc;
4170 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004171 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004172 int k = 0;
4173 int cnt = 0;
4174 const int spinRate = 10000;
4175
4176 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4177 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4178 if( rc ){
4179 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4180 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4181 zQuery);
4182 goto end_data_xfer;
4183 }
4184 n = sqlite3_column_count(pQuery);
4185 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004186 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004187 sqlite3_snprintf(200+nTable,zInsert,
4188 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004189 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004190 for(j=1; j<n; j++){
4191 memcpy(zInsert+i, ",?", 2);
4192 i += 2;
4193 }
4194 memcpy(zInsert+i, ");", 3);
4195 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4196 if( rc ){
4197 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4198 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4199 zQuery);
4200 goto end_data_xfer;
4201 }
4202 for(k=0; k<2; k++){
4203 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4204 for(i=0; i<n; i++){
4205 switch( sqlite3_column_type(pQuery, i) ){
4206 case SQLITE_NULL: {
4207 sqlite3_bind_null(pInsert, i+1);
4208 break;
4209 }
4210 case SQLITE_INTEGER: {
4211 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4212 break;
4213 }
4214 case SQLITE_FLOAT: {
4215 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4216 break;
4217 }
4218 case SQLITE_TEXT: {
4219 sqlite3_bind_text(pInsert, i+1,
4220 (const char*)sqlite3_column_text(pQuery,i),
4221 -1, SQLITE_STATIC);
4222 break;
4223 }
4224 case SQLITE_BLOB: {
4225 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4226 sqlite3_column_bytes(pQuery,i),
4227 SQLITE_STATIC);
4228 break;
4229 }
4230 }
4231 } /* End for */
4232 rc = sqlite3_step(pInsert);
4233 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4234 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4235 sqlite3_errmsg(newDb));
4236 }
4237 sqlite3_reset(pInsert);
4238 cnt++;
4239 if( (cnt%spinRate)==0 ){
4240 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4241 fflush(stdout);
4242 }
4243 } /* End while */
4244 if( rc==SQLITE_DONE ) break;
4245 sqlite3_finalize(pQuery);
4246 sqlite3_free(zQuery);
4247 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4248 zTable);
4249 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4250 if( rc ){
4251 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4252 break;
4253 }
4254 } /* End for(k=0...) */
4255
4256end_data_xfer:
4257 sqlite3_finalize(pQuery);
4258 sqlite3_finalize(pInsert);
4259 sqlite3_free(zQuery);
4260 sqlite3_free(zInsert);
4261}
4262
4263
4264/*
4265** Try to transfer all rows of the schema that match zWhere. For
4266** each row, invoke xForEach() on the object defined by that row.
4267** If an error is encountered while moving forward through the
4268** sqlite_master table, try again moving backwards.
4269*/
4270static void tryToCloneSchema(
4271 ShellState *p,
4272 sqlite3 *newDb,
4273 const char *zWhere,
4274 void (*xForEach)(ShellState*,sqlite3*,const char*)
4275){
4276 sqlite3_stmt *pQuery = 0;
4277 char *zQuery = 0;
4278 int rc;
4279 const unsigned char *zName;
4280 const unsigned char *zSql;
4281 char *zErrMsg = 0;
4282
4283 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4284 " WHERE %s", zWhere);
4285 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4286 if( rc ){
4287 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4288 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4289 zQuery);
4290 goto end_schema_xfer;
4291 }
4292 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4293 zName = sqlite3_column_text(pQuery, 0);
4294 zSql = sqlite3_column_text(pQuery, 1);
4295 printf("%s... ", zName); fflush(stdout);
4296 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4297 if( zErrMsg ){
4298 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4299 sqlite3_free(zErrMsg);
4300 zErrMsg = 0;
4301 }
4302 if( xForEach ){
4303 xForEach(p, newDb, (const char*)zName);
4304 }
4305 printf("done\n");
4306 }
4307 if( rc!=SQLITE_DONE ){
4308 sqlite3_finalize(pQuery);
4309 sqlite3_free(zQuery);
4310 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4311 " WHERE %s ORDER BY rowid DESC", zWhere);
4312 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4313 if( rc ){
4314 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4315 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4316 zQuery);
4317 goto end_schema_xfer;
4318 }
4319 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4320 zName = sqlite3_column_text(pQuery, 0);
4321 zSql = sqlite3_column_text(pQuery, 1);
4322 printf("%s... ", zName); fflush(stdout);
4323 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4324 if( zErrMsg ){
4325 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4326 sqlite3_free(zErrMsg);
4327 zErrMsg = 0;
4328 }
4329 if( xForEach ){
4330 xForEach(p, newDb, (const char*)zName);
4331 }
4332 printf("done\n");
4333 }
4334 }
4335end_schema_xfer:
4336 sqlite3_finalize(pQuery);
4337 sqlite3_free(zQuery);
4338}
4339
4340/*
4341** Open a new database file named "zNewDb". Try to recover as much information
4342** as possible out of the main database (which might be corrupt) and write it
4343** into zNewDb.
4344*/
4345static void tryToClone(ShellState *p, const char *zNewDb){
4346 int rc;
4347 sqlite3 *newDb = 0;
4348 if( access(zNewDb,0)==0 ){
4349 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4350 return;
4351 }
4352 rc = sqlite3_open(zNewDb, &newDb);
4353 if( rc ){
4354 utf8_printf(stderr, "Cannot create output database: %s\n",
4355 sqlite3_errmsg(newDb));
4356 }else{
4357 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4358 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4359 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4360 tryToCloneSchema(p, newDb, "type!='table'", 0);
4361 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4362 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4363 }
drh9e804032018-05-18 17:11:50 +00004364 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004365}
4366
4367/*
drh13c20932018-01-10 21:41:55 +00004368** Change the output file back to stdout.
4369**
4370** If the p->doXdgOpen flag is set, that means the output was being
4371** redirected to a temporary file named by p->zTempFile. In that case,
4372** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004373*/
4374static void output_reset(ShellState *p){
4375 if( p->outfile[0]=='|' ){
4376#ifndef SQLITE_OMIT_POPEN
4377 pclose(p->out);
4378#endif
4379 }else{
4380 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004381#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004382 if( p->doXdgOpen ){
4383 const char *zXdgOpenCmd =
4384#if defined(_WIN32)
4385 "start";
4386#elif defined(__APPLE__)
4387 "open";
4388#else
4389 "xdg-open";
4390#endif
4391 char *zCmd;
4392 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004393 if( system(zCmd) ){
4394 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4395 }
drh13c20932018-01-10 21:41:55 +00004396 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004397 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004398 p->doXdgOpen = 0;
4399 }
drh04a28c32018-01-31 01:38:44 +00004400#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004401 }
4402 p->outfile[0] = 0;
4403 p->out = stdout;
4404}
4405
4406/*
4407** Run an SQL command and return the single integer result.
4408*/
4409static int db_int(ShellState *p, const char *zSql){
4410 sqlite3_stmt *pStmt;
4411 int res = 0;
4412 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4413 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4414 res = sqlite3_column_int(pStmt,0);
4415 }
4416 sqlite3_finalize(pStmt);
4417 return res;
4418}
4419
4420/*
4421** Convert a 2-byte or 4-byte big-endian integer into a native integer
4422*/
4423static unsigned int get2byteInt(unsigned char *a){
4424 return (a[0]<<8) + a[1];
4425}
4426static unsigned int get4byteInt(unsigned char *a){
4427 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4428}
4429
4430/*
4431** Implementation of the ".info" command.
4432**
4433** Return 1 on error, 2 to exit, and 0 otherwise.
4434*/
4435static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4436 static const struct { const char *zName; int ofst; } aField[] = {
4437 { "file change counter:", 24 },
4438 { "database page count:", 28 },
4439 { "freelist page count:", 36 },
4440 { "schema cookie:", 40 },
4441 { "schema format:", 44 },
4442 { "default cache size:", 48 },
4443 { "autovacuum top root:", 52 },
4444 { "incremental vacuum:", 64 },
4445 { "text encoding:", 56 },
4446 { "user version:", 60 },
4447 { "application id:", 68 },
4448 { "software version:", 96 },
4449 };
4450 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4451 { "number of tables:",
4452 "SELECT count(*) FROM %s WHERE type='table'" },
4453 { "number of indexes:",
4454 "SELECT count(*) FROM %s WHERE type='index'" },
4455 { "number of triggers:",
4456 "SELECT count(*) FROM %s WHERE type='trigger'" },
4457 { "number of views:",
4458 "SELECT count(*) FROM %s WHERE type='view'" },
4459 { "schema size:",
4460 "SELECT total(length(sql)) FROM %s" },
4461 };
drh2ce15c32017-07-11 13:34:40 +00004462 int i;
drhea99a312018-07-18 19:09:07 +00004463 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004464 char *zSchemaTab;
4465 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004466 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004467 unsigned char aHdr[100];
4468 open_db(p, 0);
4469 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004470 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4471 -1, &pStmt, 0);
4472 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4473 if( sqlite3_step(pStmt)==SQLITE_ROW
4474 && sqlite3_column_bytes(pStmt,0)>100
4475 ){
4476 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4477 sqlite3_finalize(pStmt);
4478 }else{
drh2ce15c32017-07-11 13:34:40 +00004479 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004480 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004481 return 1;
4482 }
4483 i = get2byteInt(aHdr+16);
4484 if( i==1 ) i = 65536;
4485 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4486 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4487 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4488 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4489 for(i=0; i<ArraySize(aField); i++){
4490 int ofst = aField[i].ofst;
4491 unsigned int val = get4byteInt(aHdr + ofst);
4492 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4493 switch( ofst ){
4494 case 56: {
4495 if( val==1 ) raw_printf(p->out, " (utf8)");
4496 if( val==2 ) raw_printf(p->out, " (utf16le)");
4497 if( val==3 ) raw_printf(p->out, " (utf16be)");
4498 }
4499 }
4500 raw_printf(p->out, "\n");
4501 }
4502 if( zDb==0 ){
4503 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4504 }else if( strcmp(zDb,"temp")==0 ){
4505 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4506 }else{
4507 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4508 }
4509 for(i=0; i<ArraySize(aQuery); i++){
4510 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4511 int val = db_int(p, zSql);
4512 sqlite3_free(zSql);
4513 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4514 }
4515 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004516 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4517 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004518 return 0;
4519}
4520
4521/*
4522** Print the current sqlite3_errmsg() value to stderr and return 1.
4523*/
4524static int shellDatabaseError(sqlite3 *db){
4525 const char *zErr = sqlite3_errmsg(db);
4526 utf8_printf(stderr, "Error: %s\n", zErr);
4527 return 1;
4528}
4529
4530/*
drh2ce15c32017-07-11 13:34:40 +00004531** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4532** if they match and FALSE (0) if they do not match.
4533**
4534** Globbing rules:
4535**
4536** '*' Matches any sequence of zero or more characters.
4537**
4538** '?' Matches exactly one character.
4539**
4540** [...] Matches one character from the enclosed list of
4541** characters.
4542**
4543** [^...] Matches one character not in the enclosed list.
4544**
4545** '#' Matches any sequence of one or more digits with an
4546** optional + or - sign in front
4547**
4548** ' ' Any span of whitespace matches any other span of
4549** whitespace.
4550**
4551** Extra whitespace at the end of z[] is ignored.
4552*/
4553static int testcase_glob(const char *zGlob, const char *z){
4554 int c, c2;
4555 int invert;
4556 int seen;
4557
4558 while( (c = (*(zGlob++)))!=0 ){
4559 if( IsSpace(c) ){
4560 if( !IsSpace(*z) ) return 0;
4561 while( IsSpace(*zGlob) ) zGlob++;
4562 while( IsSpace(*z) ) z++;
4563 }else if( c=='*' ){
4564 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4565 if( c=='?' && (*(z++))==0 ) return 0;
4566 }
4567 if( c==0 ){
4568 return 1;
4569 }else if( c=='[' ){
4570 while( *z && testcase_glob(zGlob-1,z)==0 ){
4571 z++;
4572 }
4573 return (*z)!=0;
4574 }
4575 while( (c2 = (*(z++)))!=0 ){
4576 while( c2!=c ){
4577 c2 = *(z++);
4578 if( c2==0 ) return 0;
4579 }
4580 if( testcase_glob(zGlob,z) ) return 1;
4581 }
4582 return 0;
4583 }else if( c=='?' ){
4584 if( (*(z++))==0 ) return 0;
4585 }else if( c=='[' ){
4586 int prior_c = 0;
4587 seen = 0;
4588 invert = 0;
4589 c = *(z++);
4590 if( c==0 ) return 0;
4591 c2 = *(zGlob++);
4592 if( c2=='^' ){
4593 invert = 1;
4594 c2 = *(zGlob++);
4595 }
4596 if( c2==']' ){
4597 if( c==']' ) seen = 1;
4598 c2 = *(zGlob++);
4599 }
4600 while( c2 && c2!=']' ){
4601 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4602 c2 = *(zGlob++);
4603 if( c>=prior_c && c<=c2 ) seen = 1;
4604 prior_c = 0;
4605 }else{
4606 if( c==c2 ){
4607 seen = 1;
4608 }
4609 prior_c = c2;
4610 }
4611 c2 = *(zGlob++);
4612 }
4613 if( c2==0 || (seen ^ invert)==0 ) return 0;
4614 }else if( c=='#' ){
4615 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4616 if( !IsDigit(z[0]) ) return 0;
4617 z++;
4618 while( IsDigit(z[0]) ){ z++; }
4619 }else{
4620 if( c!=(*(z++)) ) return 0;
4621 }
4622 }
4623 while( IsSpace(*z) ){ z++; }
4624 return *z==0;
4625}
4626
4627
4628/*
4629** Compare the string as a command-line option with either one or two
4630** initial "-" characters.
4631*/
4632static int optionMatch(const char *zStr, const char *zOpt){
4633 if( zStr[0]!='-' ) return 0;
4634 zStr++;
4635 if( zStr[0]=='-' ) zStr++;
4636 return strcmp(zStr, zOpt)==0;
4637}
4638
4639/*
4640** Delete a file.
4641*/
4642int shellDeleteFile(const char *zFilename){
4643 int rc;
4644#ifdef _WIN32
4645 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4646 rc = _wunlink(z);
4647 sqlite3_free(z);
4648#else
4649 rc = unlink(zFilename);
4650#endif
4651 return rc;
4652}
4653
drh13c20932018-01-10 21:41:55 +00004654/*
4655** Try to delete the temporary file (if there is one) and free the
4656** memory used to hold the name of the temp file.
4657*/
4658static void clearTempFile(ShellState *p){
4659 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00004660 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00004661 if( shellDeleteFile(p->zTempFile) ) return;
4662 sqlite3_free(p->zTempFile);
4663 p->zTempFile = 0;
4664}
4665
4666/*
4667** Create a new temp file name with the given suffix.
4668*/
4669static void newTempFile(ShellState *p, const char *zSuffix){
4670 clearTempFile(p);
4671 sqlite3_free(p->zTempFile);
4672 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00004673 if( p->db ){
4674 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
4675 }
drh13c20932018-01-10 21:41:55 +00004676 if( p->zTempFile==0 ){
4677 sqlite3_uint64 r;
4678 sqlite3_randomness(sizeof(r), &r);
4679 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
4680 }else{
4681 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
4682 }
4683 if( p->zTempFile==0 ){
4684 raw_printf(stderr, "out of memory\n");
4685 exit(1);
4686 }
4687}
4688
drh2ce15c32017-07-11 13:34:40 +00004689
4690/*
4691** The implementation of SQL scalar function fkey_collate_clause(), used
4692** by the ".lint fkey-indexes" command. This scalar function is always
4693** called with four arguments - the parent table name, the parent column name,
4694** the child table name and the child column name.
4695**
4696** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4697**
4698** If either of the named tables or columns do not exist, this function
4699** returns an empty string. An empty string is also returned if both tables
4700** and columns exist but have the same default collation sequence. Or,
4701** if both exist but the default collation sequences are different, this
4702** function returns the string " COLLATE <parent-collation>", where
4703** <parent-collation> is the default collation sequence of the parent column.
4704*/
4705static void shellFkeyCollateClause(
4706 sqlite3_context *pCtx,
4707 int nVal,
4708 sqlite3_value **apVal
4709){
4710 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4711 const char *zParent;
4712 const char *zParentCol;
4713 const char *zParentSeq;
4714 const char *zChild;
4715 const char *zChildCol;
4716 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4717 int rc;
4718
4719 assert( nVal==4 );
4720 zParent = (const char*)sqlite3_value_text(apVal[0]);
4721 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4722 zChild = (const char*)sqlite3_value_text(apVal[2]);
4723 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4724
4725 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4726 rc = sqlite3_table_column_metadata(
4727 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4728 );
4729 if( rc==SQLITE_OK ){
4730 rc = sqlite3_table_column_metadata(
4731 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4732 );
4733 }
4734
4735 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4736 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4737 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4738 sqlite3_free(z);
4739 }
4740}
4741
4742
4743/*
4744** The implementation of dot-command ".lint fkey-indexes".
4745*/
4746static int lintFkeyIndexes(
4747 ShellState *pState, /* Current shell tool state */
4748 char **azArg, /* Array of arguments passed to dot command */
4749 int nArg /* Number of entries in azArg[] */
4750){
4751 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4752 FILE *out = pState->out; /* Stream to write non-error output to */
4753 int bVerbose = 0; /* If -verbose is present */
4754 int bGroupByParent = 0; /* If -groupbyparent is present */
4755 int i; /* To iterate through azArg[] */
4756 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4757 int rc; /* Return code */
4758 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4759
4760 /*
4761 ** This SELECT statement returns one row for each foreign key constraint
4762 ** in the schema of the main database. The column values are:
4763 **
4764 ** 0. The text of an SQL statement similar to:
4765 **
danf9679312017-12-01 18:40:18 +00004766 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004767 **
danf9679312017-12-01 18:40:18 +00004768 ** This SELECT is similar to the one that the foreign keys implementation
4769 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004770 ** be used to optimize this query, then it can also be used by the FK
4771 ** implementation to optimize DELETE or UPDATE statements on the parent
4772 ** table.
4773 **
4774 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4775 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4776 ** contains an index that can be used to optimize the query.
4777 **
4778 ** 2. Human readable text that describes the child table and columns. e.g.
4779 **
4780 ** "child_table(child_key1, child_key2)"
4781 **
4782 ** 3. Human readable text that describes the parent table and columns. e.g.
4783 **
4784 ** "parent_table(parent_key1, parent_key2)"
4785 **
4786 ** 4. A full CREATE INDEX statement for an index that could be used to
4787 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4788 **
4789 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4790 **
4791 ** 5. The name of the parent table.
4792 **
4793 ** These six values are used by the C logic below to generate the report.
4794 */
4795 const char *zSql =
4796 "SELECT "
danf9679312017-12-01 18:40:18 +00004797 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004798 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4799 " || fkey_collate_clause("
4800 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4801 ", "
4802 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4803 " || group_concat('*=?', ' AND ') || ')'"
4804 ", "
4805 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4806 ", "
4807 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4808 ", "
4809 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4810 " || ' ON ' || quote(s.name) || '('"
4811 " || group_concat(quote(f.[from]) ||"
4812 " fkey_collate_clause("
4813 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4814 " || ');'"
4815 ", "
4816 " f.[table] "
4817 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4818 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4819 "GROUP BY s.name, f.id "
4820 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4821 ;
4822 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4823
4824 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004825 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004826 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4827 bVerbose = 1;
4828 }
4829 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4830 bGroupByParent = 1;
4831 zIndent = " ";
4832 }
4833 else{
4834 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4835 azArg[0], azArg[1]
4836 );
4837 return SQLITE_ERROR;
4838 }
4839 }
4840
4841 /* Register the fkey_collate_clause() SQL function */
4842 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4843 0, shellFkeyCollateClause, 0, 0
4844 );
4845
4846
4847 if( rc==SQLITE_OK ){
4848 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4849 }
4850 if( rc==SQLITE_OK ){
4851 sqlite3_bind_int(pSql, 1, bGroupByParent);
4852 }
4853
4854 if( rc==SQLITE_OK ){
4855 int rc2;
4856 char *zPrev = 0;
4857 while( SQLITE_ROW==sqlite3_step(pSql) ){
4858 int res = -1;
4859 sqlite3_stmt *pExplain = 0;
4860 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4861 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4862 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4863 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4864 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4865 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4866
4867 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4868 if( rc!=SQLITE_OK ) break;
4869 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4870 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4871 res = (
4872 0==sqlite3_strglob(zGlob, zPlan)
4873 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4874 );
4875 }
4876 rc = sqlite3_finalize(pExplain);
4877 if( rc!=SQLITE_OK ) break;
4878
4879 if( res<0 ){
4880 raw_printf(stderr, "Error: internal error");
4881 break;
4882 }else{
4883 if( bGroupByParent
4884 && (bVerbose || res==0)
4885 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4886 ){
4887 raw_printf(out, "-- Parent table %s\n", zParent);
4888 sqlite3_free(zPrev);
4889 zPrev = sqlite3_mprintf("%s", zParent);
4890 }
4891
4892 if( res==0 ){
4893 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4894 }else if( bVerbose ){
4895 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4896 zIndent, zFrom, zTarget
4897 );
4898 }
4899 }
4900 }
4901 sqlite3_free(zPrev);
4902
4903 if( rc!=SQLITE_OK ){
4904 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4905 }
4906
4907 rc2 = sqlite3_finalize(pSql);
4908 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4909 rc = rc2;
4910 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4911 }
4912 }else{
4913 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4914 }
4915
4916 return rc;
4917}
4918
4919/*
4920** Implementation of ".lint" dot command.
4921*/
4922static int lintDotCommand(
4923 ShellState *pState, /* Current shell tool state */
4924 char **azArg, /* Array of arguments passed to dot command */
4925 int nArg /* Number of entries in azArg[] */
4926){
4927 int n;
drhaf2770f2018-01-05 14:55:43 +00004928 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004929 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4930 return lintFkeyIndexes(pState, azArg, nArg);
4931
4932 usage:
4933 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4934 raw_printf(stderr, "Where sub-commands are:\n");
4935 raw_printf(stderr, " fkey-indexes\n");
4936 return SQLITE_ERROR;
4937}
4938
drhe37c0e12018-01-06 19:19:50 +00004939#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4940/*********************************************************************************
4941** The ".archive" or ".ar" command.
4942*/
danfd0245d2017-12-07 15:44:29 +00004943static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004944 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004945 int *pRc,
4946 const char *zSql,
4947 sqlite3_stmt **ppStmt
4948){
4949 *ppStmt = 0;
4950 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004951 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004952 if( rc!=SQLITE_OK ){
4953 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004954 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004955 );
4956 *pRc = rc;
4957 }
4958 }
4959}
4960
danac15e2d2017-12-14 19:15:07 +00004961static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004962 sqlite3 *db,
4963 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004964 sqlite3_stmt **ppStmt,
4965 const char *zFmt,
4966 ...
dan3f67ddf2017-12-13 20:04:53 +00004967){
danac15e2d2017-12-14 19:15:07 +00004968 *ppStmt = 0;
4969 if( *pRc==SQLITE_OK ){
4970 va_list ap;
4971 char *z;
4972 va_start(ap, zFmt);
4973 z = sqlite3_vmprintf(zFmt, ap);
dan3f67ddf2017-12-13 20:04:53 +00004974 if( z==0 ){
4975 *pRc = SQLITE_NOMEM;
4976 }else{
4977 shellPrepare(db, pRc, z, ppStmt);
4978 sqlite3_free(z);
4979 }
dan3f67ddf2017-12-13 20:04:53 +00004980 }
4981}
4982
danfd0245d2017-12-07 15:44:29 +00004983static void shellFinalize(
4984 int *pRc,
4985 sqlite3_stmt *pStmt
4986){
dan25c12182017-12-07 21:03:33 +00004987 if( pStmt ){
4988 sqlite3 *db = sqlite3_db_handle(pStmt);
4989 int rc = sqlite3_finalize(pStmt);
4990 if( *pRc==SQLITE_OK ){
4991 if( rc!=SQLITE_OK ){
4992 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4993 }
4994 *pRc = rc;
4995 }
4996 }
danfd0245d2017-12-07 15:44:29 +00004997}
4998
4999static void shellReset(
5000 int *pRc,
5001 sqlite3_stmt *pStmt
5002){
5003 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005004 if( *pRc==SQLITE_OK ){
5005 if( rc!=SQLITE_OK ){
5006 sqlite3 *db = sqlite3_db_handle(pStmt);
5007 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5008 }
5009 *pRc = rc;
5010 }
danfd0245d2017-12-07 15:44:29 +00005011}
drhe37c0e12018-01-06 19:19:50 +00005012/*
dan88be0202017-12-09 17:58:02 +00005013** Structure representing a single ".ar" command.
5014*/
5015typedef struct ArCommand ArCommand;
5016struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005017 u8 eCmd; /* An AR_CMD_* value */
5018 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005019 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005020 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005021 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005022 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005023 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005024 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005025 const char *zFile; /* --file argument, or NULL */
5026 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005027 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005028 ShellState *p; /* Shell state */
5029 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005030};
5031
5032/*
5033** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5034*/
dan0d0547f2017-12-14 15:40:42 +00005035static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005036 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005037 return SQLITE_ERROR;
5038}
5039
5040/*
5041** Print an error message for the .ar command to stderr and return
5042** SQLITE_ERROR.
5043*/
drhd0f9cdc2018-05-17 14:09:06 +00005044static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005045 va_list ap;
5046 char *z;
5047 va_start(ap, zFmt);
5048 z = sqlite3_vmprintf(zFmt, ap);
5049 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005050 utf8_printf(stderr, "Error: %s\n", z);
5051 if( pAr->fromCmdLine ){
5052 utf8_printf(stderr, "Use \"-A\" for more help\n");
5053 }else{
5054 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5055 }
dan0d0547f2017-12-14 15:40:42 +00005056 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005057 return SQLITE_ERROR;
5058}
5059
5060/*
5061** Values for ArCommand.eCmd.
5062*/
dand4b56e52017-12-12 20:04:59 +00005063#define AR_CMD_CREATE 1
5064#define AR_CMD_EXTRACT 2
5065#define AR_CMD_LIST 3
5066#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00005067#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00005068
5069/*
5070** Other (non-command) switches.
5071*/
drhb376b3d2018-01-10 13:11:51 +00005072#define AR_SWITCH_VERBOSE 6
5073#define AR_SWITCH_FILE 7
5074#define AR_SWITCH_DIRECTORY 8
drha5676c42018-01-10 15:17:34 +00005075#define AR_SWITCH_APPEND 9
drhb376b3d2018-01-10 13:11:51 +00005076#define AR_SWITCH_DRYRUN 10
dand4b56e52017-12-12 20:04:59 +00005077
5078static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5079 switch( eSwitch ){
5080 case AR_CMD_CREATE:
5081 case AR_CMD_EXTRACT:
5082 case AR_CMD_LIST:
5083 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00005084 case AR_CMD_HELP:
5085 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005086 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005087 }
dand4b56e52017-12-12 20:04:59 +00005088 pAr->eCmd = eSwitch;
5089 break;
5090
drhb376b3d2018-01-10 13:11:51 +00005091 case AR_SWITCH_DRYRUN:
5092 pAr->bDryRun = 1;
5093 break;
dand4b56e52017-12-12 20:04:59 +00005094 case AR_SWITCH_VERBOSE:
5095 pAr->bVerbose = 1;
5096 break;
drha5676c42018-01-10 15:17:34 +00005097 case AR_SWITCH_APPEND:
5098 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005099 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005100 case AR_SWITCH_FILE:
5101 pAr->zFile = zArg;
5102 break;
5103 case AR_SWITCH_DIRECTORY:
5104 pAr->zDir = zArg;
5105 break;
5106 }
5107
5108 return SQLITE_OK;
5109}
dan88be0202017-12-09 17:58:02 +00005110
5111/*
5112** Parse the command line for an ".ar" command. The results are written into
5113** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5114** successfully, otherwise an error message is written to stderr and
5115** SQLITE_ERROR returned.
5116*/
5117static int arParseCommand(
5118 char **azArg, /* Array of arguments passed to dot command */
5119 int nArg, /* Number of entries in azArg[] */
5120 ArCommand *pAr /* Populate this object */
5121){
dand4b56e52017-12-12 20:04:59 +00005122 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005123 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005124 char cShort;
5125 u8 eSwitch;
5126 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005127 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005128 { "create", 'c', AR_CMD_CREATE, 0 },
5129 { "extract", 'x', AR_CMD_EXTRACT, 0 },
5130 { "list", 't', AR_CMD_LIST, 0 },
5131 { "update", 'u', AR_CMD_UPDATE, 0 },
5132 { "help", 'h', AR_CMD_HELP, 0 },
5133 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5134 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005135 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005136 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005137 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005138 };
5139 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5140 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5141
dan88be0202017-12-09 17:58:02 +00005142 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005143 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005144 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005145 }else{
5146 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005147 if( z[0]!='-' ){
5148 /* Traditional style [tar] invocation */
5149 int i;
5150 int iArg = 2;
5151 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005152 const char *zArg = 0;
5153 struct ArSwitch *pOpt;
5154 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5155 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005156 }
dan0d0547f2017-12-14 15:40:42 +00005157 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005158 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005159 }
dand4b56e52017-12-12 20:04:59 +00005160 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005161 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005162 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005163 }
dand4b56e52017-12-12 20:04:59 +00005164 zArg = azArg[iArg++];
5165 }
5166 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005167 }
dan88be0202017-12-09 17:58:02 +00005168 pAr->nArg = nArg-iArg;
5169 if( pAr->nArg>0 ){
5170 pAr->azArg = &azArg[iArg];
5171 }
dand4b56e52017-12-12 20:04:59 +00005172 }else{
5173 /* Non-traditional invocation */
5174 int iArg;
5175 for(iArg=1; iArg<nArg; iArg++){
5176 int n;
5177 z = azArg[iArg];
5178 if( z[0]!='-' ){
5179 /* All remaining command line words are command arguments. */
5180 pAr->azArg = &azArg[iArg];
5181 pAr->nArg = nArg-iArg;
5182 break;
5183 }
drhaf2770f2018-01-05 14:55:43 +00005184 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005185
5186 if( z[1]!='-' ){
5187 int i;
5188 /* One or more short options */
5189 for(i=1; i<n; i++){
5190 const char *zArg = 0;
5191 struct ArSwitch *pOpt;
5192 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5193 if( z[i]==pOpt->cShort ) break;
5194 }
dan0d0547f2017-12-14 15:40:42 +00005195 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005196 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005197 }
dand4b56e52017-12-12 20:04:59 +00005198 if( pOpt->bArg ){
5199 if( i<(n-1) ){
5200 zArg = &z[i+1];
5201 i = n;
5202 }else{
dan0d0547f2017-12-14 15:40:42 +00005203 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005204 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005205 }
dand4b56e52017-12-12 20:04:59 +00005206 zArg = azArg[++iArg];
5207 }
5208 }
5209 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5210 }
5211 }else if( z[2]=='\0' ){
5212 /* A -- option, indicating that all remaining command line words
5213 ** are command arguments. */
5214 pAr->azArg = &azArg[iArg+1];
5215 pAr->nArg = nArg-iArg-1;
5216 break;
5217 }else{
5218 /* A long option */
5219 const char *zArg = 0; /* Argument for option, if any */
5220 struct ArSwitch *pMatch = 0; /* Matching option */
5221 struct ArSwitch *pOpt; /* Iterator */
5222 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5223 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005224 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005225 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005226 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005227 }else{
5228 pMatch = pOpt;
5229 }
5230 }
5231 }
5232
5233 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005234 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005235 }
5236 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005237 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005238 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005239 }
dand4b56e52017-12-12 20:04:59 +00005240 zArg = azArg[++iArg];
5241 }
5242 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5243 }
5244 }
dan88be0202017-12-09 17:58:02 +00005245 }
5246 }
5247
5248 return SQLITE_OK;
5249}
5250
5251/*
dan3f67ddf2017-12-13 20:04:53 +00005252** This function assumes that all arguments within the ArCommand.azArg[]
5253** array refer to archive members, as for the --extract or --list commands.
5254** It checks that each of them are present. If any specified file is not
5255** present in the archive, an error is printed to stderr and an error
5256** code returned. Otherwise, if all specified arguments are present in
5257** the archive, SQLITE_OK is returned.
5258**
5259** This function strips any trailing '/' characters from each argument.
5260** This is consistent with the way the [tar] command seems to work on
5261** Linux.
5262*/
drhb376b3d2018-01-10 13:11:51 +00005263static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005264 int rc = SQLITE_OK;
5265 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005266 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005267 sqlite3_stmt *pTest = 0;
5268
drhb376b3d2018-01-10 13:11:51 +00005269 shellPreparePrintf(pAr->db, &rc, &pTest,
5270 "SELECT name FROM %s WHERE name=$name",
5271 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005272 );
drhb376b3d2018-01-10 13:11:51 +00005273 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005274 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5275 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005276 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005277 int bOk = 0;
5278 while( n>0 && z[n-1]=='/' ) n--;
5279 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005280 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005281 if( SQLITE_ROW==sqlite3_step(pTest) ){
5282 bOk = 1;
5283 }
5284 shellReset(&rc, pTest);
5285 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005286 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005287 rc = SQLITE_ERROR;
5288 }
5289 }
5290 shellFinalize(&rc, pTest);
5291 }
dan3f67ddf2017-12-13 20:04:53 +00005292 return rc;
5293}
5294
5295/*
5296** Format a WHERE clause that can be used against the "sqlar" table to
5297** identify all archive members that match the command arguments held
5298** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5299** The caller is responsible for eventually calling sqlite3_free() on
5300** any non-NULL (*pzWhere) value.
5301*/
5302static void arWhereClause(
5303 int *pRc,
5304 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005305 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005306){
5307 char *zWhere = 0;
5308 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005309 if( pAr->nArg==0 ){
5310 zWhere = sqlite3_mprintf("1");
5311 }else{
5312 int i;
5313 const char *zSep = "";
5314 for(i=0; i<pAr->nArg; i++){
5315 const char *z = pAr->azArg[i];
5316 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005317 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5318 zWhere, zSep, z, strlen30(z)+1, z
5319 );
danac15e2d2017-12-14 19:15:07 +00005320 if( zWhere==0 ){
5321 *pRc = SQLITE_NOMEM;
5322 break;
5323 }
5324 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005325 }
dan3f67ddf2017-12-13 20:04:53 +00005326 }
5327 }
5328 *pzWhere = zWhere;
5329}
5330
5331/*
dan88be0202017-12-09 17:58:02 +00005332** Implementation of .ar "lisT" command.
5333*/
drhb376b3d2018-01-10 13:11:51 +00005334static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005335 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005336 const char *azCols[] = {
5337 "name",
drh410cad92018-01-10 17:19:16 +00005338 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005339 };
dan5a78b812017-12-27 18:54:11 +00005340
dan3f67ddf2017-12-13 20:04:53 +00005341 char *zWhere = 0;
5342 sqlite3_stmt *pSql = 0;
5343 int rc;
5344
drhb376b3d2018-01-10 13:11:51 +00005345 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005346 arWhereClause(&rc, pAr, &zWhere);
5347
drhb376b3d2018-01-10 13:11:51 +00005348 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5349 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005350 if( pAr->bDryRun ){
5351 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5352 }else{
5353 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5354 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005355 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5356 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005357 sqlite3_column_int(pSql, 1),
5358 sqlite3_column_text(pSql, 2),
5359 sqlite3_column_text(pSql, 3)
5360 );
5361 }else{
5362 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5363 }
danb5090e42017-12-27 21:13:21 +00005364 }
dan3f67ddf2017-12-13 20:04:53 +00005365 }
dan5a78b812017-12-27 18:54:11 +00005366 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005367 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005368 return rc;
dan88be0202017-12-09 17:58:02 +00005369}
5370
5371
danfd0245d2017-12-07 15:44:29 +00005372/*
5373** Implementation of .ar "eXtract" command.
5374*/
drhb376b3d2018-01-10 13:11:51 +00005375static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005376 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005377 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005378 " ($dir || name),"
5379 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005380 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5381 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005382
5383 const char *azExtraArg[] = {
5384 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005385 "data"
dan5a78b812017-12-27 18:54:11 +00005386 };
dan5a78b812017-12-27 18:54:11 +00005387
danfd0245d2017-12-07 15:44:29 +00005388 sqlite3_stmt *pSql = 0;
5389 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005390 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005391 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005392 int i, j;
dan2ad09492017-12-09 18:28:22 +00005393
dan3f67ddf2017-12-13 20:04:53 +00005394 /* If arguments are specified, check that they actually exist within
5395 ** the archive before proceeding. And formulate a WHERE clause to
5396 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005397 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005398 arWhereClause(&rc, pAr, &zWhere);
5399
5400 if( rc==SQLITE_OK ){
5401 if( pAr->zDir ){
5402 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5403 }else{
5404 zDir = sqlite3_mprintf("");
5405 }
5406 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005407 }
danfd0245d2017-12-07 15:44:29 +00005408
drhb376b3d2018-01-10 13:11:51 +00005409 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5410 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005411 );
5412
dan2ad09492017-12-09 18:28:22 +00005413 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005414 j = sqlite3_bind_parameter_index(pSql, "$dir");
5415 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005416
danac15e2d2017-12-14 19:15:07 +00005417 /* Run the SELECT statement twice. The first time, writefile() is called
5418 ** for all archive members that should be extracted. The second time,
5419 ** only for the directories. This is because the timestamps for
5420 ** extracted directories must be reset after they are populated (as
5421 ** populating them changes the timestamp). */
5422 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005423 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5424 sqlite3_bind_int(pSql, j, i);
5425 if( pAr->bDryRun ){
5426 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5427 }else{
5428 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5429 if( i==0 && pAr->bVerbose ){
5430 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5431 }
danac15e2d2017-12-14 19:15:07 +00005432 }
5433 }
5434 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005435 }
danac15e2d2017-12-14 19:15:07 +00005436 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005437 }
dan25c12182017-12-07 21:03:33 +00005438
dan2ad09492017-12-09 18:28:22 +00005439 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005440 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005441 return rc;
5442}
5443
drhb376b3d2018-01-10 13:11:51 +00005444/*
5445** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5446*/
5447static int arExecSql(ArCommand *pAr, const char *zSql){
5448 int rc;
5449 if( pAr->bDryRun ){
5450 utf8_printf(pAr->p->out, "%s\n", zSql);
5451 rc = SQLITE_OK;
5452 }else{
drh410cad92018-01-10 17:19:16 +00005453 char *zErr = 0;
5454 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5455 if( zErr ){
5456 utf8_printf(stdout, "ERROR: %s\n", zErr);
5457 sqlite3_free(zErr);
5458 }
drhb376b3d2018-01-10 13:11:51 +00005459 }
5460 return rc;
5461}
5462
dan1ad3f612017-12-11 20:22:02 +00005463
danfd0245d2017-12-07 15:44:29 +00005464/*
dan06741a32017-12-13 20:17:18 +00005465** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00005466**
5467** Create the "sqlar" table in the database if it does not already exist.
5468** Then add each file in the azFile[] array to the archive. Directories
5469** are added recursively. If argument bVerbose is non-zero, a message is
5470** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005471**
5472** The create command is the same as update, except that it drops
5473** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00005474*/
drhb376b3d2018-01-10 13:11:51 +00005475static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005476 ArCommand *pAr, /* Command arguments and options */
drhb376b3d2018-01-10 13:11:51 +00005477 int bUpdate /* true for a --create. false for --update */
danfd0245d2017-12-07 15:44:29 +00005478){
dand4b56e52017-12-12 20:04:59 +00005479 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005480 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5481 " name TEXT PRIMARY KEY, -- name of the file\n"
5482 " mode INT, -- access permissions\n"
5483 " mtime INT, -- last modification time\n"
5484 " sz INT, -- original file size\n"
5485 " data BLOB -- compressed content\n"
5486 ")";
dand4b56e52017-12-12 20:04:59 +00005487 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005488 const char *zInsertFmt[2] = {
5489 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005490 " SELECT\n"
5491 " %s,\n"
5492 " mode,\n"
5493 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005494 " CASE substr(lsmode(mode),1,1)\n"
5495 " WHEN '-' THEN length(data)\n"
5496 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005497 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005498 " sqlar_compress(data)\n"
drh634c70f2018-01-10 16:50:18 +00005499 " FROM fsdir(%Q,%Q)\n"
drh1bf208c2018-03-09 21:54:01 +00005500 " WHERE lsmode(mode) NOT LIKE '?%%';",
5501 "REPLACE INTO %s(name,mode,mtime,data)\n"
5502 " SELECT\n"
5503 " %s,\n"
5504 " mode,\n"
5505 " mtime,\n"
5506 " data\n"
5507 " FROM fsdir(%Q,%Q)\n"
5508 " WHERE lsmode(mode) NOT LIKE '?%%';"
5509 };
danfd0245d2017-12-07 15:44:29 +00005510 int i; /* For iterating through azFile[] */
5511 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005512 const char *zTab = 0; /* SQL table into which to insert */
5513 char *zSql;
5514 char zTemp[50];
danfd0245d2017-12-07 15:44:29 +00005515
drh1bf208c2018-03-09 21:54:01 +00005516 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005517 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005518 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005519 zTemp[0] = 0;
5520 if( pAr->bZip ){
5521 /* Initialize the zipfile virtual table, if necessary */
5522 if( pAr->zFile ){
5523 sqlite3_uint64 r;
5524 sqlite3_randomness(sizeof(r),&r);
5525 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5526 zTab = zTemp;
5527 zSql = sqlite3_mprintf(
5528 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5529 zTab, pAr->zFile
5530 );
5531 rc = arExecSql(pAr, zSql);
5532 sqlite3_free(zSql);
5533 }else{
5534 zTab = "zip";
5535 }
5536 }else{
5537 /* Initialize the table for an SQLAR */
5538 zTab = "sqlar";
5539 if( bUpdate==0 ){
5540 rc = arExecSql(pAr, zDrop);
5541 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5542 }
5543 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005544 }
dan88be0202017-12-09 17:58:02 +00005545 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00005546 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005547 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5548 pAr->azArg[i], pAr->zDir);
mistachkince2052b2018-03-23 00:31:53 +00005549 rc = arExecSql(pAr, zSql2);
5550 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00005551 }
drh1bf208c2018-03-09 21:54:01 +00005552end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00005553 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005554 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
danfd0245d2017-12-07 15:44:29 +00005555 }else{
drhb376b3d2018-01-10 13:11:51 +00005556 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00005557 if( pAr->bZip && pAr->zFile ){
5558 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5559 arExecSql(pAr, zSql);
5560 sqlite3_free(zSql);
5561 }
danfd0245d2017-12-07 15:44:29 +00005562 }
danfd0245d2017-12-07 15:44:29 +00005563 return rc;
5564}
5565
5566/*
5567** Implementation of ".ar" dot command.
5568*/
5569static int arDotCommand(
5570 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00005571 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00005572 char **azArg, /* Array of arguments passed to dot command */
5573 int nArg /* Number of entries in azArg[] */
5574){
dan88be0202017-12-09 17:58:02 +00005575 ArCommand cmd;
5576 int rc;
drh34660642018-01-10 17:39:54 +00005577 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00005578 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00005579 rc = arParseCommand(azArg, nArg, &cmd);
5580 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005581 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005582 cmd.p = pState;
5583 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005584 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00005585 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00005586 }else{
5587 eDbType = pState->openMode;
5588 }
5589 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00005590 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5591 if( cmd.zFile==0 ){
5592 cmd.zSrcTable = sqlite3_mprintf("zip");
5593 }else{
5594 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5595 }
dan5a78b812017-12-27 18:54:11 +00005596 }
drha5676c42018-01-10 15:17:34 +00005597 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005598 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005599 int flags;
drha5676c42018-01-10 15:17:34 +00005600 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
dand4b56e52017-12-12 20:04:59 +00005601 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5602 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5603 }else{
5604 flags = SQLITE_OPEN_READONLY;
5605 }
drha82c95b2018-01-10 14:00:00 +00005606 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005607 if( cmd.bDryRun ){
5608 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5609 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5610 }
5611 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5612 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005613 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005614 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5615 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005616 );
drha5676c42018-01-10 15:17:34 +00005617 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005618 }
drhb376b3d2018-01-10 13:11:51 +00005619 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00005620 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00005621 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5622 shellPutsFunc, 0, 0);
5623
dand4b56e52017-12-12 20:04:59 +00005624 }
drhd0f9cdc2018-05-17 14:09:06 +00005625 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00005626 if( cmd.eCmd!=AR_CMD_CREATE
5627 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5628 ){
drha5676c42018-01-10 15:17:34 +00005629 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5630 rc = SQLITE_ERROR;
5631 goto end_ar_command;
5632 }
5633 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5634 }
dand4b56e52017-12-12 20:04:59 +00005635
dan88be0202017-12-09 17:58:02 +00005636 switch( cmd.eCmd ){
5637 case AR_CMD_CREATE:
drhb376b3d2018-01-10 13:11:51 +00005638 rc = arCreateOrUpdateCommand(&cmd, 0);
dan88be0202017-12-09 17:58:02 +00005639 break;
danfd0245d2017-12-07 15:44:29 +00005640
dan88be0202017-12-09 17:58:02 +00005641 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005642 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005643 break;
5644
5645 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00005646 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005647 break;
5648
dan0d0547f2017-12-14 15:40:42 +00005649 case AR_CMD_HELP:
5650 arUsage(pState->out);
5651 break;
5652
dan88be0202017-12-09 17:58:02 +00005653 default:
5654 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb376b3d2018-01-10 13:11:51 +00005655 rc = arCreateOrUpdateCommand(&cmd, 1);
dan88be0202017-12-09 17:58:02 +00005656 break;
danfd0245d2017-12-07 15:44:29 +00005657 }
5658 }
drha5676c42018-01-10 15:17:34 +00005659end_ar_command:
5660 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00005661 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00005662 }
5663 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00005664
dan88be0202017-12-09 17:58:02 +00005665 return rc;
danfd0245d2017-12-07 15:44:29 +00005666}
drhe37c0e12018-01-06 19:19:50 +00005667/* End of the ".archive" or ".ar" command logic
5668**********************************************************************************/
5669#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00005670
drh2ce15c32017-07-11 13:34:40 +00005671
5672/*
5673** If an input line begins with "." then invoke this routine to
5674** process that line.
5675**
5676** Return 1 on error, 2 to exit, and 0 otherwise.
5677*/
5678static int do_meta_command(char *zLine, ShellState *p){
5679 int h = 1;
5680 int nArg = 0;
5681 int n, c;
5682 int rc = 0;
5683 char *azArg[50];
5684
dan6b046be2018-01-09 15:25:55 +00005685#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005686 if( p->expert.pExpert ){
5687 expertFinish(p, 1, 0);
5688 }
dan6b046be2018-01-09 15:25:55 +00005689#endif
dan43efc182017-12-19 17:42:13 +00005690
drh2ce15c32017-07-11 13:34:40 +00005691 /* Parse the input line into tokens.
5692 */
5693 while( zLine[h] && nArg<ArraySize(azArg) ){
5694 while( IsSpace(zLine[h]) ){ h++; }
5695 if( zLine[h]==0 ) break;
5696 if( zLine[h]=='\'' || zLine[h]=='"' ){
5697 int delim = zLine[h++];
5698 azArg[nArg++] = &zLine[h];
5699 while( zLine[h] && zLine[h]!=delim ){
5700 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5701 h++;
5702 }
5703 if( zLine[h]==delim ){
5704 zLine[h++] = 0;
5705 }
5706 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5707 }else{
5708 azArg[nArg++] = &zLine[h];
5709 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5710 if( zLine[h] ) zLine[h++] = 0;
5711 resolve_backslashes(azArg[nArg-1]);
5712 }
5713 }
5714
5715 /* Process the input line.
5716 */
5717 if( nArg==0 ) return 0; /* no tokens, no error */
5718 n = strlen30(azArg[0]);
5719 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00005720 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00005721
5722#ifndef SQLITE_OMIT_AUTHORIZATION
5723 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5724 if( nArg!=2 ){
5725 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5726 rc = 1;
5727 goto meta_command_exit;
5728 }
5729 open_db(p, 0);
5730 if( booleanValue(azArg[1]) ){
5731 sqlite3_set_authorizer(p->db, shellAuth, p);
5732 }else{
5733 sqlite3_set_authorizer(p->db, 0, 0);
5734 }
5735 }else
5736#endif
5737
drhe37c0e12018-01-06 19:19:50 +00005738#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5739 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00005740 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00005741 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00005742 }else
5743#endif
5744
drh2ce15c32017-07-11 13:34:40 +00005745 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5746 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5747 ){
5748 const char *zDestFile = 0;
5749 const char *zDb = 0;
5750 sqlite3 *pDest;
5751 sqlite3_backup *pBackup;
5752 int j;
drh69ed38a2018-05-14 00:23:08 +00005753 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00005754 for(j=1; j<nArg; j++){
5755 const char *z = azArg[j];
5756 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00005757 if( z[1]=='-' ) z++;
5758 if( strcmp(z, "-append")==0 ){
5759 zVfs = "apndvfs";
5760 }else
drh2ce15c32017-07-11 13:34:40 +00005761 {
5762 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5763 return 1;
5764 }
5765 }else if( zDestFile==0 ){
5766 zDestFile = azArg[j];
5767 }else if( zDb==0 ){
5768 zDb = zDestFile;
5769 zDestFile = azArg[j];
5770 }else{
drh69ed38a2018-05-14 00:23:08 +00005771 raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00005772 return 1;
5773 }
5774 }
5775 if( zDestFile==0 ){
5776 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5777 return 1;
5778 }
5779 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00005780 rc = sqlite3_open_v2(zDestFile, &pDest,
5781 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00005782 if( rc!=SQLITE_OK ){
5783 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00005784 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005785 return 1;
5786 }
5787 open_db(p, 0);
5788 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5789 if( pBackup==0 ){
5790 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00005791 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005792 return 1;
5793 }
5794 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5795 sqlite3_backup_finish(pBackup);
5796 if( rc==SQLITE_DONE ){
5797 rc = 0;
5798 }else{
5799 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5800 rc = 1;
5801 }
drh9e804032018-05-18 17:11:50 +00005802 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005803 }else
5804
5805 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5806 if( nArg==2 ){
5807 bail_on_error = booleanValue(azArg[1]);
5808 }else{
5809 raw_printf(stderr, "Usage: .bail on|off\n");
5810 rc = 1;
5811 }
5812 }else
5813
5814 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5815 if( nArg==2 ){
5816 if( booleanValue(azArg[1]) ){
5817 setBinaryMode(p->out, 1);
5818 }else{
5819 setTextMode(p->out, 1);
5820 }
5821 }else{
5822 raw_printf(stderr, "Usage: .binary on|off\n");
5823 rc = 1;
5824 }
5825 }else
5826
5827 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5828 if( nArg==2 ){
5829#if defined(_WIN32) || defined(WIN32)
5830 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5831 rc = !SetCurrentDirectoryW(z);
5832 sqlite3_free(z);
5833#else
5834 rc = chdir(azArg[1]);
5835#endif
5836 if( rc ){
5837 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5838 rc = 1;
5839 }
5840 }else{
5841 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5842 rc = 1;
5843 }
5844 }else
5845
5846 /* The undocumented ".breakpoint" command causes a call to the no-op
5847 ** routine named test_breakpoint().
5848 */
5849 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5850 test_breakpoint();
5851 }else
5852
5853 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5854 if( nArg==2 ){
5855 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5856 }else{
5857 raw_printf(stderr, "Usage: .changes on|off\n");
5858 rc = 1;
5859 }
5860 }else
5861
5862 /* Cancel output redirection, if it is currently set (by .testcase)
5863 ** Then read the content of the testcase-out.txt file and compare against
5864 ** azArg[1]. If there are differences, report an error and exit.
5865 */
5866 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5867 char *zRes = 0;
5868 output_reset(p);
5869 if( nArg!=2 ){
5870 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5871 rc = 2;
5872 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5873 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5874 rc = 2;
5875 }else if( testcase_glob(azArg[1],zRes)==0 ){
5876 utf8_printf(stderr,
5877 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5878 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005879 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005880 }else{
5881 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5882 p->nCheck++;
5883 }
5884 sqlite3_free(zRes);
5885 }else
5886
5887 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5888 if( nArg==2 ){
5889 tryToClone(p, azArg[1]);
5890 }else{
5891 raw_printf(stderr, "Usage: .clone FILENAME\n");
5892 rc = 1;
5893 }
5894 }else
5895
5896 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5897 ShellState data;
5898 char *zErrMsg = 0;
5899 open_db(p, 0);
5900 memcpy(&data, p, sizeof(data));
5901 data.showHeader = 0;
5902 data.cMode = data.mode = MODE_List;
5903 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5904 data.cnt = 0;
5905 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5906 callback, &data, &zErrMsg);
5907 if( zErrMsg ){
5908 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5909 sqlite3_free(zErrMsg);
5910 rc = 1;
5911 }
5912 }else
5913
drh7df01192018-04-28 12:43:16 +00005914 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00005915 static const struct DbConfigChoices {
5916 const char *zName;
5917 int op;
5918 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00005919 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
5920 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
5921 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
5922 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
5923 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
5924 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
5925 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
5926 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
5927 };
5928 int ii, v;
5929 open_db(p, 0);
5930 for(ii=0; ii<ArraySize(aDbConfig); ii++){
5931 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
5932 if( nArg>=3 ){
5933 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
5934 }
5935 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
5936 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
5937 if( nArg>1 ) break;
5938 }
5939 if( nArg>1 && ii==ArraySize(aDbConfig) ){
5940 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
5941 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
5942 }
5943 }else
5944
5945 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00005946 rc = shell_dbinfo_command(p, nArg, azArg);
5947 }else
5948
5949 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5950 const char *zLike = 0;
5951 int i;
5952 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00005953 int savedShellFlags = p->shellFlgs;
5954 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00005955 for(i=1; i<nArg; i++){
5956 if( azArg[i][0]=='-' ){
5957 const char *z = azArg[i]+1;
5958 if( z[0]=='-' ) z++;
5959 if( strcmp(z,"preserve-rowids")==0 ){
5960#ifdef SQLITE_OMIT_VIRTUALTABLE
5961 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5962 " with SQLITE_OMIT_VIRTUALTABLE\n");
5963 rc = 1;
5964 goto meta_command_exit;
5965#else
5966 ShellSetFlag(p, SHFLG_PreserveRowid);
5967#endif
5968 }else
5969 if( strcmp(z,"newlines")==0 ){
5970 ShellSetFlag(p, SHFLG_Newlines);
5971 }else
5972 {
5973 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5974 rc = 1;
5975 goto meta_command_exit;
5976 }
5977 }else if( zLike ){
5978 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5979 "?--newlines? ?LIKE-PATTERN?\n");
5980 rc = 1;
5981 goto meta_command_exit;
5982 }else{
5983 zLike = azArg[i];
5984 }
5985 }
5986 open_db(p, 0);
5987 /* When playing back a "dump", the content might appear in an order
5988 ** which causes immediate foreign key constraints to be violated.
5989 ** So disable foreign-key constraint enforcement to prevent problems. */
5990 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5991 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5992 p->writableSchema = 0;
5993 p->showHeader = 0;
5994 /* Set writable_schema=ON since doing so forces SQLite to initialize
5995 ** as much of the schema as it can even if the sqlite_master table is
5996 ** corrupt. */
5997 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5998 p->nErr = 0;
5999 if( zLike==0 ){
6000 run_schema_dump_query(p,
6001 "SELECT name, type, sql FROM sqlite_master "
6002 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6003 );
6004 run_schema_dump_query(p,
6005 "SELECT name, type, sql FROM sqlite_master "
6006 "WHERE name=='sqlite_sequence'"
6007 );
6008 run_table_dump_query(p,
6009 "SELECT sql FROM sqlite_master "
6010 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6011 );
6012 }else{
6013 char *zSql;
6014 zSql = sqlite3_mprintf(
6015 "SELECT name, type, sql FROM sqlite_master "
6016 "WHERE tbl_name LIKE %Q AND type=='table'"
6017 " AND sql NOT NULL", zLike);
6018 run_schema_dump_query(p,zSql);
6019 sqlite3_free(zSql);
6020 zSql = sqlite3_mprintf(
6021 "SELECT sql FROM sqlite_master "
6022 "WHERE sql NOT NULL"
6023 " AND type IN ('index','trigger','view')"
6024 " AND tbl_name LIKE %Q", zLike);
6025 run_table_dump_query(p, zSql, 0);
6026 sqlite3_free(zSql);
6027 }
6028 if( p->writableSchema ){
6029 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
6030 p->writableSchema = 0;
6031 }
6032 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6033 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
6034 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
6035 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00006036 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00006037 }else
6038
6039 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
6040 if( nArg==2 ){
6041 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
6042 }else{
6043 raw_printf(stderr, "Usage: .echo on|off\n");
6044 rc = 1;
6045 }
6046 }else
6047
6048 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
6049 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00006050 p->autoEQPtest = 0;
drh2ce15c32017-07-11 13:34:40 +00006051 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00006052 p->autoEQP = AUTOEQP_full;
6053 }else if( strcmp(azArg[1],"trigger")==0 ){
6054 p->autoEQP = AUTOEQP_trigger;
drhe2ca99c2018-05-02 00:33:43 +00006055 }else if( strcmp(azArg[1],"test")==0 ){
6056 p->autoEQP = AUTOEQP_on;
6057 p->autoEQPtest = 1;
drh2ce15c32017-07-11 13:34:40 +00006058 }else{
mistachkinb71aa092018-01-23 00:05:18 +00006059 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006060 }
6061 }else{
drhada70452017-12-21 21:02:27 +00006062 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00006063 rc = 1;
6064 }
6065 }else
6066
6067 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
6068 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
6069 rc = 2;
6070 }else
6071
6072 /* The ".explain" command is automatic now. It is largely pointless. It
6073 ** retained purely for backwards compatibility */
6074 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
6075 int val = 1;
6076 if( nArg>=2 ){
6077 if( strcmp(azArg[1],"auto")==0 ){
6078 val = 99;
6079 }else{
6080 val = booleanValue(azArg[1]);
6081 }
6082 }
6083 if( val==1 && p->mode!=MODE_Explain ){
6084 p->normalMode = p->mode;
6085 p->mode = MODE_Explain;
6086 p->autoExplain = 0;
6087 }else if( val==0 ){
6088 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6089 p->autoExplain = 0;
6090 }else if( val==99 ){
6091 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6092 p->autoExplain = 1;
6093 }
6094 }else
6095
dan6b046be2018-01-09 15:25:55 +00006096#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006097 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6098 open_db(p, 0);
6099 expertDotCommand(p, azArg, nArg);
6100 }else
dan6b046be2018-01-09 15:25:55 +00006101#endif
dan43efc182017-12-19 17:42:13 +00006102
drh2ce15c32017-07-11 13:34:40 +00006103 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6104 ShellState data;
6105 char *zErrMsg = 0;
6106 int doStats = 0;
6107 memcpy(&data, p, sizeof(data));
6108 data.showHeader = 0;
6109 data.cMode = data.mode = MODE_Semi;
6110 if( nArg==2 && optionMatch(azArg[1], "indent") ){
6111 data.cMode = data.mode = MODE_Pretty;
6112 nArg = 1;
6113 }
6114 if( nArg!=1 ){
6115 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6116 rc = 1;
6117 goto meta_command_exit;
6118 }
6119 open_db(p, 0);
6120 rc = sqlite3_exec(p->db,
6121 "SELECT sql FROM"
6122 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6123 " FROM sqlite_master UNION ALL"
6124 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6125 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6126 "ORDER BY rowid",
6127 callback, &data, &zErrMsg
6128 );
6129 if( rc==SQLITE_OK ){
6130 sqlite3_stmt *pStmt;
6131 rc = sqlite3_prepare_v2(p->db,
6132 "SELECT rowid FROM sqlite_master"
6133 " WHERE name GLOB 'sqlite_stat[134]'",
6134 -1, &pStmt, 0);
6135 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6136 sqlite3_finalize(pStmt);
6137 }
6138 if( doStats==0 ){
6139 raw_printf(p->out, "/* No STAT tables available */\n");
6140 }else{
6141 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6142 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6143 callback, &data, &zErrMsg);
6144 data.cMode = data.mode = MODE_Insert;
6145 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00006146 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006147 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00006148 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006149 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00006150 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006151 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6152 }
6153 }else
6154
6155 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6156 if( nArg==2 ){
6157 p->showHeader = booleanValue(azArg[1]);
6158 }else{
6159 raw_printf(stderr, "Usage: .headers on|off\n");
6160 rc = 1;
6161 }
6162 }else
6163
6164 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00006165 if( nArg>=2 ){
6166 int n = showHelp(p->out, azArg[1]);
6167 if( n==0 ){
6168 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
6169 }
6170 }else{
6171 showHelp(p->out, 0);
6172 }
drh2ce15c32017-07-11 13:34:40 +00006173 }else
6174
6175 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6176 char *zTable; /* Insert data into this table */
6177 char *zFile; /* Name of file to extra content from */
6178 sqlite3_stmt *pStmt = NULL; /* A statement */
6179 int nCol; /* Number of columns in the table */
6180 int nByte; /* Number of bytes in an SQL string */
6181 int i, j; /* Loop counters */
6182 int needCommit; /* True to COMMIT or ROLLBACK at end */
6183 int nSep; /* Number of bytes in p->colSeparator[] */
6184 char *zSql; /* An SQL statement */
6185 ImportCtx sCtx; /* Reader context */
6186 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6187 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
6188
6189 if( nArg!=3 ){
6190 raw_printf(stderr, "Usage: .import FILE TABLE\n");
6191 goto meta_command_exit;
6192 }
6193 zFile = azArg[1];
6194 zTable = azArg[2];
6195 seenInterrupt = 0;
6196 memset(&sCtx, 0, sizeof(sCtx));
6197 open_db(p, 0);
6198 nSep = strlen30(p->colSeparator);
6199 if( nSep==0 ){
6200 raw_printf(stderr,
6201 "Error: non-null column separator required for import\n");
6202 return 1;
6203 }
6204 if( nSep>1 ){
6205 raw_printf(stderr, "Error: multi-character column separators not allowed"
6206 " for import\n");
6207 return 1;
6208 }
6209 nSep = strlen30(p->rowSeparator);
6210 if( nSep==0 ){
6211 raw_printf(stderr, "Error: non-null row separator required for import\n");
6212 return 1;
6213 }
6214 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6215 /* When importing CSV (only), if the row separator is set to the
6216 ** default output row separator, change it to the default input
6217 ** row separator. This avoids having to maintain different input
6218 ** and output row separators. */
6219 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6220 nSep = strlen30(p->rowSeparator);
6221 }
6222 if( nSep>1 ){
6223 raw_printf(stderr, "Error: multi-character row separators not allowed"
6224 " for import\n");
6225 return 1;
6226 }
6227 sCtx.zFile = zFile;
6228 sCtx.nLine = 1;
6229 if( sCtx.zFile[0]=='|' ){
6230#ifdef SQLITE_OMIT_POPEN
6231 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6232 return 1;
6233#else
6234 sCtx.in = popen(sCtx.zFile+1, "r");
6235 sCtx.zFile = "<pipe>";
6236 xCloser = pclose;
6237#endif
6238 }else{
6239 sCtx.in = fopen(sCtx.zFile, "rb");
6240 xCloser = fclose;
6241 }
6242 if( p->mode==MODE_Ascii ){
6243 xRead = ascii_read_one_field;
6244 }else{
6245 xRead = csv_read_one_field;
6246 }
6247 if( sCtx.in==0 ){
6248 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6249 return 1;
6250 }
6251 sCtx.cColSep = p->colSeparator[0];
6252 sCtx.cRowSep = p->rowSeparator[0];
6253 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6254 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006255 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006256 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006257 }
6258 nByte = strlen30(zSql);
6259 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6260 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
6261 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6262 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6263 char cSep = '(';
6264 while( xRead(&sCtx) ){
6265 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6266 cSep = ',';
6267 if( sCtx.cTerm!=sCtx.cColSep ) break;
6268 }
6269 if( cSep=='(' ){
6270 sqlite3_free(zCreate);
6271 sqlite3_free(sCtx.z);
6272 xCloser(sCtx.in);
6273 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6274 return 1;
6275 }
6276 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6277 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6278 sqlite3_free(zCreate);
6279 if( rc ){
6280 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6281 sqlite3_errmsg(p->db));
6282 sqlite3_free(sCtx.z);
6283 xCloser(sCtx.in);
6284 return 1;
6285 }
6286 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6287 }
6288 sqlite3_free(zSql);
6289 if( rc ){
6290 if (pStmt) sqlite3_finalize(pStmt);
6291 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6292 xCloser(sCtx.in);
6293 return 1;
6294 }
6295 nCol = sqlite3_column_count(pStmt);
6296 sqlite3_finalize(pStmt);
6297 pStmt = 0;
6298 if( nCol==0 ) return 0; /* no columns, no error */
6299 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6300 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006301 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006302 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006303 }
6304 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6305 j = strlen30(zSql);
6306 for(i=1; i<nCol; i++){
6307 zSql[j++] = ',';
6308 zSql[j++] = '?';
6309 }
6310 zSql[j++] = ')';
6311 zSql[j] = 0;
6312 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6313 sqlite3_free(zSql);
6314 if( rc ){
6315 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6316 if (pStmt) sqlite3_finalize(pStmt);
6317 xCloser(sCtx.in);
6318 return 1;
6319 }
6320 needCommit = sqlite3_get_autocommit(p->db);
6321 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6322 do{
6323 int startLine = sCtx.nLine;
6324 for(i=0; i<nCol; i++){
6325 char *z = xRead(&sCtx);
6326 /*
6327 ** Did we reach end-of-file before finding any columns?
6328 ** If so, stop instead of NULL filling the remaining columns.
6329 */
6330 if( z==0 && i==0 ) break;
6331 /*
6332 ** Did we reach end-of-file OR end-of-line before finding any
6333 ** columns in ASCII mode? If so, stop instead of NULL filling
6334 ** the remaining columns.
6335 */
6336 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6337 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6338 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6339 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6340 "filling the rest with NULL\n",
6341 sCtx.zFile, startLine, nCol, i+1);
6342 i += 2;
6343 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6344 }
6345 }
6346 if( sCtx.cTerm==sCtx.cColSep ){
6347 do{
6348 xRead(&sCtx);
6349 i++;
6350 }while( sCtx.cTerm==sCtx.cColSep );
6351 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6352 "extras ignored\n",
6353 sCtx.zFile, startLine, nCol, i);
6354 }
6355 if( i>=nCol ){
6356 sqlite3_step(pStmt);
6357 rc = sqlite3_reset(pStmt);
6358 if( rc!=SQLITE_OK ){
6359 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6360 startLine, sqlite3_errmsg(p->db));
6361 }
6362 }
6363 }while( sCtx.cTerm!=EOF );
6364
6365 xCloser(sCtx.in);
6366 sqlite3_free(sCtx.z);
6367 sqlite3_finalize(pStmt);
6368 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6369 }else
6370
6371#ifndef SQLITE_UNTESTABLE
6372 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6373 char *zSql;
6374 char *zCollist = 0;
6375 sqlite3_stmt *pStmt;
6376 int tnum = 0;
6377 int i;
drh48d219a2018-04-23 18:38:48 +00006378 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6379 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6380 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00006381 rc = 1;
6382 goto meta_command_exit;
6383 }
6384 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00006385 if( nArg==2 ){
6386 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6387 goto meta_command_exit;
6388 }
drh2ce15c32017-07-11 13:34:40 +00006389 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6390 " WHERE name='%q' AND type='index'", azArg[1]);
6391 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6392 sqlite3_free(zSql);
6393 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6394 tnum = sqlite3_column_int(pStmt, 0);
6395 }
6396 sqlite3_finalize(pStmt);
6397 if( tnum==0 ){
6398 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6399 rc = 1;
6400 goto meta_command_exit;
6401 }
6402 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6403 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6404 sqlite3_free(zSql);
6405 i = 0;
6406 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6407 char zLabel[20];
6408 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6409 i++;
6410 if( zCol==0 ){
6411 if( sqlite3_column_int(pStmt,1)==-1 ){
6412 zCol = "_ROWID_";
6413 }else{
6414 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6415 zCol = zLabel;
6416 }
6417 }
6418 if( zCollist==0 ){
6419 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6420 }else{
6421 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6422 }
6423 }
6424 sqlite3_finalize(pStmt);
6425 zSql = sqlite3_mprintf(
6426 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6427 azArg[2], zCollist, zCollist);
6428 sqlite3_free(zCollist);
6429 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6430 if( rc==SQLITE_OK ){
6431 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6432 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6433 if( rc ){
6434 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6435 }else{
6436 utf8_printf(stdout, "%s;\n", zSql);
6437 raw_printf(stdout,
6438 "WARNING: writing to an imposter table will corrupt the index!\n"
6439 );
6440 }
6441 }else{
6442 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6443 rc = 1;
6444 }
6445 sqlite3_free(zSql);
6446 }else
6447#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6448
6449#ifdef SQLITE_ENABLE_IOTRACE
6450 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6451 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6452 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6453 iotrace = 0;
6454 if( nArg<2 ){
6455 sqlite3IoTrace = 0;
6456 }else if( strcmp(azArg[1], "-")==0 ){
6457 sqlite3IoTrace = iotracePrintf;
6458 iotrace = stdout;
6459 }else{
6460 iotrace = fopen(azArg[1], "w");
6461 if( iotrace==0 ){
6462 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6463 sqlite3IoTrace = 0;
6464 rc = 1;
6465 }else{
6466 sqlite3IoTrace = iotracePrintf;
6467 }
6468 }
6469 }else
6470#endif
6471
6472 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6473 static const struct {
6474 const char *zLimitName; /* Name of a limit */
6475 int limitCode; /* Integer code for that limit */
6476 } aLimit[] = {
6477 { "length", SQLITE_LIMIT_LENGTH },
6478 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6479 { "column", SQLITE_LIMIT_COLUMN },
6480 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6481 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6482 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6483 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6484 { "attached", SQLITE_LIMIT_ATTACHED },
6485 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6486 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6487 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6488 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6489 };
6490 int i, n2;
6491 open_db(p, 0);
6492 if( nArg==1 ){
6493 for(i=0; i<ArraySize(aLimit); i++){
6494 printf("%20s %d\n", aLimit[i].zLimitName,
6495 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6496 }
6497 }else if( nArg>3 ){
6498 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6499 rc = 1;
6500 goto meta_command_exit;
6501 }else{
6502 int iLimit = -1;
6503 n2 = strlen30(azArg[1]);
6504 for(i=0; i<ArraySize(aLimit); i++){
6505 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6506 if( iLimit<0 ){
6507 iLimit = i;
6508 }else{
6509 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6510 rc = 1;
6511 goto meta_command_exit;
6512 }
6513 }
6514 }
6515 if( iLimit<0 ){
6516 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6517 "enter \".limits\" with no arguments for a list.\n",
6518 azArg[1]);
6519 rc = 1;
6520 goto meta_command_exit;
6521 }
6522 if( nArg==3 ){
6523 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6524 (int)integerValue(azArg[2]));
6525 }
6526 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6527 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6528 }
6529 }else
6530
6531 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6532 open_db(p, 0);
6533 lintDotCommand(p, azArg, nArg);
6534 }else
6535
6536#ifndef SQLITE_OMIT_LOAD_EXTENSION
6537 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6538 const char *zFile, *zProc;
6539 char *zErrMsg = 0;
6540 if( nArg<2 ){
6541 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6542 rc = 1;
6543 goto meta_command_exit;
6544 }
6545 zFile = azArg[1];
6546 zProc = nArg>=3 ? azArg[2] : 0;
6547 open_db(p, 0);
6548 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6549 if( rc!=SQLITE_OK ){
6550 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6551 sqlite3_free(zErrMsg);
6552 rc = 1;
6553 }
6554 }else
6555#endif
6556
6557 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6558 if( nArg!=2 ){
6559 raw_printf(stderr, "Usage: .log FILENAME\n");
6560 rc = 1;
6561 }else{
6562 const char *zFile = azArg[1];
6563 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00006564 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00006565 }
6566 }else
6567
6568 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6569 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006570 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006571 int c2 = zMode[0];
6572 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6573 p->mode = MODE_Line;
6574 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6575 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6576 p->mode = MODE_Column;
6577 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6578 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6579 p->mode = MODE_List;
6580 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6581 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6582 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6583 p->mode = MODE_Html;
6584 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6585 p->mode = MODE_Tcl;
6586 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6587 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6588 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6589 p->mode = MODE_Csv;
6590 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6591 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6592 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6593 p->mode = MODE_List;
6594 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6595 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6596 p->mode = MODE_Insert;
6597 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6598 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6599 p->mode = MODE_Quote;
6600 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6601 p->mode = MODE_Ascii;
6602 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6603 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6604 }else if( nArg==1 ){
6605 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6606 }else{
6607 raw_printf(stderr, "Error: mode should be one of: "
6608 "ascii column csv html insert line list quote tabs tcl\n");
6609 rc = 1;
6610 }
6611 p->cMode = p->mode;
6612 }else
6613
6614 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6615 if( nArg==2 ){
6616 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6617 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6618 }else{
6619 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6620 rc = 1;
6621 }
6622 }else
6623
6624 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6625 char *zNewFilename; /* Name of the database file to open */
6626 int iName = 1; /* Index in azArg[] of the filename */
6627 int newFlag = 0; /* True to delete file before opening */
6628 /* Close the existing database */
6629 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00006630 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00006631 p->db = 0;
6632 p->zDbFilename = 0;
6633 sqlite3_free(p->zFreeOnClose);
6634 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00006635 p->openMode = SHELL_OPEN_UNSPEC;
drh2ce15c32017-07-11 13:34:40 +00006636 /* Check for command-line arguments */
6637 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6638 const char *z = azArg[iName];
6639 if( optionMatch(z,"new") ){
6640 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00006641#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00006642 }else if( optionMatch(z, "zip") ){
6643 p->openMode = SHELL_OPEN_ZIPFILE;
6644#endif
6645 }else if( optionMatch(z, "append") ){
6646 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00006647 }else if( optionMatch(z, "readonly") ){
6648 p->openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00006649 }else if( z[0]=='-' ){
6650 utf8_printf(stderr, "unknown option: %s\n", z);
6651 rc = 1;
6652 goto meta_command_exit;
6653 }
6654 }
6655 /* If a filename is specified, try to open it first */
6656 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6657 if( zNewFilename ){
6658 if( newFlag ) shellDeleteFile(zNewFilename);
6659 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00006660 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00006661 if( p->db==0 ){
6662 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6663 sqlite3_free(zNewFilename);
6664 }else{
6665 p->zFreeOnClose = zNewFilename;
6666 }
6667 }
6668 if( p->db==0 ){
6669 /* As a fall-back open a TEMP database */
6670 p->zDbFilename = 0;
6671 open_db(p, 0);
6672 }
6673 }else
6674
drh13c20932018-01-10 21:41:55 +00006675 if( (c=='o'
6676 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
6677 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00006678 ){
6679 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00006680 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00006681 if( azArg[0][0]=='e' ){
6682 /* Transform the ".excel" command into ".once -x" */
6683 nArg = 2;
6684 azArg[0] = "once";
6685 zFile = azArg[1] = "-x";
6686 n = 4;
6687 }
drh2ce15c32017-07-11 13:34:40 +00006688 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00006689 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00006690 rc = 1;
6691 goto meta_command_exit;
6692 }
6693 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6694 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00006695 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00006696 rc = 1;
6697 goto meta_command_exit;
6698 }
6699 p->outCount = 2;
6700 }else{
6701 p->outCount = 0;
6702 }
6703 output_reset(p);
drh13c20932018-01-10 21:41:55 +00006704 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00006705#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00006706 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00006707 p->doXdgOpen = 1;
6708 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00006709 if( zFile[1]=='x' ){
6710 newTempFile(p, "csv");
6711 p->mode = MODE_Csv;
6712 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6713 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6714 }else{
6715 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00006716 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00006717 }
6718 zFile = p->zTempFile;
6719 }
drh04a28c32018-01-31 01:38:44 +00006720#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00006721 if( zFile[0]=='|' ){
6722#ifdef SQLITE_OMIT_POPEN
6723 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6724 rc = 1;
6725 p->out = stdout;
6726#else
6727 p->out = popen(zFile + 1, "w");
6728 if( p->out==0 ){
6729 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6730 p->out = stdout;
6731 rc = 1;
6732 }else{
6733 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6734 }
6735#endif
6736 }else{
drha92a01a2018-01-10 22:15:37 +00006737 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00006738 if( p->out==0 ){
6739 if( strcmp(zFile,"off")!=0 ){
6740 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6741 }
6742 p->out = stdout;
6743 rc = 1;
6744 } else {
6745 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6746 }
6747 }
6748 }else
6749
6750 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6751 int i;
6752 for(i=1; i<nArg; i++){
6753 if( i>1 ) raw_printf(p->out, " ");
6754 utf8_printf(p->out, "%s", azArg[i]);
6755 }
6756 raw_printf(p->out, "\n");
6757 }else
6758
6759 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6760 if( nArg >= 2) {
6761 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6762 }
6763 if( nArg >= 3) {
6764 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6765 }
6766 }else
6767
6768 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6769 rc = 2;
6770 }else
6771
6772 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6773 FILE *alt;
6774 if( nArg!=2 ){
6775 raw_printf(stderr, "Usage: .read FILE\n");
6776 rc = 1;
6777 goto meta_command_exit;
6778 }
6779 alt = fopen(azArg[1], "rb");
6780 if( alt==0 ){
6781 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6782 rc = 1;
6783 }else{
6784 rc = process_input(p, alt);
6785 fclose(alt);
6786 }
6787 }else
6788
6789 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6790 const char *zSrcFile;
6791 const char *zDb;
6792 sqlite3 *pSrc;
6793 sqlite3_backup *pBackup;
6794 int nTimeout = 0;
6795
6796 if( nArg==2 ){
6797 zSrcFile = azArg[1];
6798 zDb = "main";
6799 }else if( nArg==3 ){
6800 zSrcFile = azArg[2];
6801 zDb = azArg[1];
6802 }else{
6803 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6804 rc = 1;
6805 goto meta_command_exit;
6806 }
6807 rc = sqlite3_open(zSrcFile, &pSrc);
6808 if( rc!=SQLITE_OK ){
6809 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00006810 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006811 return 1;
6812 }
6813 open_db(p, 0);
6814 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6815 if( pBackup==0 ){
6816 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00006817 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006818 return 1;
6819 }
6820 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6821 || rc==SQLITE_BUSY ){
6822 if( rc==SQLITE_BUSY ){
6823 if( nTimeout++ >= 3 ) break;
6824 sqlite3_sleep(100);
6825 }
6826 }
6827 sqlite3_backup_finish(pBackup);
6828 if( rc==SQLITE_DONE ){
6829 rc = 0;
6830 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6831 raw_printf(stderr, "Error: source database is busy\n");
6832 rc = 1;
6833 }else{
6834 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6835 rc = 1;
6836 }
drh9e804032018-05-18 17:11:50 +00006837 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006838 }else
6839
drh2ce15c32017-07-11 13:34:40 +00006840 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6841 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00006842 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006843#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6844 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6845#endif
6846 }else{
6847 raw_printf(stderr, "Usage: .scanstats on|off\n");
6848 rc = 1;
6849 }
6850 }else
6851
6852 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6853 ShellText sSelect;
6854 ShellState data;
6855 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006856 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006857 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006858 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006859 int bDebug = 0;
6860 int ii;
drh2ce15c32017-07-11 13:34:40 +00006861
6862 open_db(p, 0);
6863 memcpy(&data, p, sizeof(data));
6864 data.showHeader = 0;
6865 data.cMode = data.mode = MODE_Semi;
6866 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006867 for(ii=1; ii<nArg; ii++){
6868 if( optionMatch(azArg[ii],"indent") ){
6869 data.cMode = data.mode = MODE_Pretty;
6870 }else if( optionMatch(azArg[ii],"debug") ){
6871 bDebug = 1;
6872 }else if( zName==0 ){
6873 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006874 }else{
drhceba7922018-01-01 21:28:25 +00006875 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6876 rc = 1;
6877 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006878 }
drh2ce15c32017-07-11 13:34:40 +00006879 }
drhceba7922018-01-01 21:28:25 +00006880 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00006881 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
6882 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00006883 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006884 new_argv[0] = sqlite3_mprintf(
6885 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006886 " type text,\n"
6887 " name text,\n"
6888 " tbl_name text,\n"
6889 " rootpage integer,\n"
6890 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006891 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006892 new_argv[1] = 0;
6893 new_colv[0] = "sql";
6894 new_colv[1] = 0;
6895 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006896 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006897 }
drh2ce15c32017-07-11 13:34:40 +00006898 }
6899 if( zDiv ){
6900 sqlite3_stmt *pStmt = 0;
6901 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6902 -1, &pStmt, 0);
6903 if( rc ){
6904 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6905 sqlite3_finalize(pStmt);
6906 rc = 1;
6907 goto meta_command_exit;
6908 }
6909 appendText(&sSelect, "SELECT sql FROM", 0);
6910 iSchema = 0;
6911 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6912 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6913 char zScNum[30];
6914 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6915 appendText(&sSelect, zDiv, 0);
6916 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006917 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6918 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006919 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006920 }else{
drhceba7922018-01-01 21:28:25 +00006921 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006922 }
drhceba7922018-01-01 21:28:25 +00006923 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6924 appendText(&sSelect, zScNum, 0);
6925 appendText(&sSelect, " AS snum, ", 0);
6926 appendText(&sSelect, zDb, '\'');
6927 appendText(&sSelect, " AS sname FROM ", 0);
6928 appendText(&sSelect, zDb, '"');
6929 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006930 }
6931 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006932#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006933 if( zName ){
6934 appendText(&sSelect,
6935 " UNION ALL SELECT shell_module_schema(name),"
6936 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6937 }
drhcde7b772018-01-02 12:50:40 +00006938#endif
drh2ce15c32017-07-11 13:34:40 +00006939 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006940 if( zName ){
6941 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00006942 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
6943 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00006944 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006945 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6946 }else{
6947 appendText(&sSelect, "lower(tbl_name)", 0);
6948 }
mistachkin9d107262018-03-23 14:24:34 +00006949 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006950 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00006951 if( !bGlob ){
6952 appendText(&sSelect, " ESCAPE '\\' ", 0);
6953 }
drh2ce15c32017-07-11 13:34:40 +00006954 appendText(&sSelect, " AND ", 0);
6955 sqlite3_free(zQarg);
6956 }
6957 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6958 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006959 if( bDebug ){
6960 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6961 }else{
6962 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6963 }
drh2ce15c32017-07-11 13:34:40 +00006964 freeText(&sSelect);
6965 }
6966 if( zErrMsg ){
6967 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6968 sqlite3_free(zErrMsg);
6969 rc = 1;
6970 }else if( rc != SQLITE_OK ){
6971 raw_printf(stderr,"Error: querying schema information\n");
6972 rc = 1;
6973 }else{
6974 rc = 0;
6975 }
6976 }else
6977
6978#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6979 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6980 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6981 }else
6982#endif
6983
6984#if defined(SQLITE_ENABLE_SESSION)
6985 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6986 OpenSession *pSession = &p->aSession[0];
6987 char **azCmd = &azArg[1];
6988 int iSes = 0;
6989 int nCmd = nArg - 1;
6990 int i;
6991 if( nArg<=1 ) goto session_syntax_error;
6992 open_db(p, 0);
6993 if( nArg>=3 ){
6994 for(iSes=0; iSes<p->nSession; iSes++){
6995 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6996 }
6997 if( iSes<p->nSession ){
6998 pSession = &p->aSession[iSes];
6999 azCmd++;
7000 nCmd--;
7001 }else{
7002 pSession = &p->aSession[0];
7003 iSes = 0;
7004 }
7005 }
7006
7007 /* .session attach TABLE
7008 ** Invoke the sqlite3session_attach() interface to attach a particular
7009 ** table so that it is never filtered.
7010 */
7011 if( strcmp(azCmd[0],"attach")==0 ){
7012 if( nCmd!=2 ) goto session_syntax_error;
7013 if( pSession->p==0 ){
7014 session_not_open:
7015 raw_printf(stderr, "ERROR: No sessions are open\n");
7016 }else{
7017 rc = sqlite3session_attach(pSession->p, azCmd[1]);
7018 if( rc ){
7019 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
7020 rc = 0;
7021 }
7022 }
7023 }else
7024
7025 /* .session changeset FILE
7026 ** .session patchset FILE
7027 ** Write a changeset or patchset into a file. The file is overwritten.
7028 */
7029 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
7030 FILE *out = 0;
7031 if( nCmd!=2 ) goto session_syntax_error;
7032 if( pSession->p==0 ) goto session_not_open;
7033 out = fopen(azCmd[1], "wb");
7034 if( out==0 ){
7035 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
7036 }else{
7037 int szChng;
7038 void *pChng;
7039 if( azCmd[0][0]=='c' ){
7040 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
7041 }else{
7042 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
7043 }
7044 if( rc ){
7045 printf("Error: error code %d\n", rc);
7046 rc = 0;
7047 }
7048 if( pChng
7049 && fwrite(pChng, szChng, 1, out)!=1 ){
7050 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
7051 szChng);
7052 }
7053 sqlite3_free(pChng);
7054 fclose(out);
7055 }
7056 }else
7057
7058 /* .session close
7059 ** Close the identified session
7060 */
7061 if( strcmp(azCmd[0], "close")==0 ){
7062 if( nCmd!=1 ) goto session_syntax_error;
7063 if( p->nSession ){
7064 session_close(pSession);
7065 p->aSession[iSes] = p->aSession[--p->nSession];
7066 }
7067 }else
7068
7069 /* .session enable ?BOOLEAN?
7070 ** Query or set the enable flag
7071 */
7072 if( strcmp(azCmd[0], "enable")==0 ){
7073 int ii;
7074 if( nCmd>2 ) goto session_syntax_error;
7075 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7076 if( p->nSession ){
7077 ii = sqlite3session_enable(pSession->p, ii);
7078 utf8_printf(p->out, "session %s enable flag = %d\n",
7079 pSession->zName, ii);
7080 }
7081 }else
7082
7083 /* .session filter GLOB ....
7084 ** Set a list of GLOB patterns of table names to be excluded.
7085 */
7086 if( strcmp(azCmd[0], "filter")==0 ){
7087 int ii, nByte;
7088 if( nCmd<2 ) goto session_syntax_error;
7089 if( p->nSession ){
7090 for(ii=0; ii<pSession->nFilter; ii++){
7091 sqlite3_free(pSession->azFilter[ii]);
7092 }
7093 sqlite3_free(pSession->azFilter);
7094 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
7095 pSession->azFilter = sqlite3_malloc( nByte );
7096 if( pSession->azFilter==0 ){
7097 raw_printf(stderr, "Error: out or memory\n");
7098 exit(1);
7099 }
7100 for(ii=1; ii<nCmd; ii++){
7101 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
7102 }
7103 pSession->nFilter = ii-1;
7104 }
7105 }else
7106
7107 /* .session indirect ?BOOLEAN?
7108 ** Query or set the indirect flag
7109 */
7110 if( strcmp(azCmd[0], "indirect")==0 ){
7111 int ii;
7112 if( nCmd>2 ) goto session_syntax_error;
7113 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7114 if( p->nSession ){
7115 ii = sqlite3session_indirect(pSession->p, ii);
7116 utf8_printf(p->out, "session %s indirect flag = %d\n",
7117 pSession->zName, ii);
7118 }
7119 }else
7120
7121 /* .session isempty
7122 ** Determine if the session is empty
7123 */
7124 if( strcmp(azCmd[0], "isempty")==0 ){
7125 int ii;
7126 if( nCmd!=1 ) goto session_syntax_error;
7127 if( p->nSession ){
7128 ii = sqlite3session_isempty(pSession->p);
7129 utf8_printf(p->out, "session %s isempty flag = %d\n",
7130 pSession->zName, ii);
7131 }
7132 }else
7133
7134 /* .session list
7135 ** List all currently open sessions
7136 */
7137 if( strcmp(azCmd[0],"list")==0 ){
7138 for(i=0; i<p->nSession; i++){
7139 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7140 }
7141 }else
7142
7143 /* .session open DB NAME
7144 ** Open a new session called NAME on the attached database DB.
7145 ** DB is normally "main".
7146 */
7147 if( strcmp(azCmd[0],"open")==0 ){
7148 char *zName;
7149 if( nCmd!=3 ) goto session_syntax_error;
7150 zName = azCmd[2];
7151 if( zName[0]==0 ) goto session_syntax_error;
7152 for(i=0; i<p->nSession; i++){
7153 if( strcmp(p->aSession[i].zName,zName)==0 ){
7154 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7155 goto meta_command_exit;
7156 }
7157 }
7158 if( p->nSession>=ArraySize(p->aSession) ){
7159 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7160 goto meta_command_exit;
7161 }
7162 pSession = &p->aSession[p->nSession];
7163 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7164 if( rc ){
7165 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7166 rc = 0;
7167 goto meta_command_exit;
7168 }
7169 pSession->nFilter = 0;
7170 sqlite3session_table_filter(pSession->p, session_filter, pSession);
7171 p->nSession++;
7172 pSession->zName = sqlite3_mprintf("%s", zName);
7173 }else
7174 /* If no command name matches, show a syntax error */
7175 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00007176 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00007177 }else
7178#endif
7179
7180#ifdef SQLITE_DEBUG
7181 /* Undocumented commands for internal testing. Subject to change
7182 ** without notice. */
7183 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7184 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7185 int i, v;
7186 for(i=1; i<nArg; i++){
7187 v = booleanValue(azArg[i]);
7188 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7189 }
7190 }
7191 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7192 int i; sqlite3_int64 v;
7193 for(i=1; i<nArg; i++){
7194 char zBuf[200];
7195 v = integerValue(azArg[i]);
7196 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7197 utf8_printf(p->out, "%s", zBuf);
7198 }
7199 }
7200 }else
7201#endif
7202
7203 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7204 int bIsInit = 0; /* True to initialize the SELFTEST table */
7205 int bVerbose = 0; /* Verbose output */
7206 int bSelftestExists; /* True if SELFTEST already exists */
7207 int i, k; /* Loop counters */
7208 int nTest = 0; /* Number of tests runs */
7209 int nErr = 0; /* Number of errors seen */
7210 ShellText str; /* Answer for a query */
7211 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7212
7213 open_db(p,0);
7214 for(i=1; i<nArg; i++){
7215 const char *z = azArg[i];
7216 if( z[0]=='-' && z[1]=='-' ) z++;
7217 if( strcmp(z,"-init")==0 ){
7218 bIsInit = 1;
7219 }else
7220 if( strcmp(z,"-v")==0 ){
7221 bVerbose++;
7222 }else
7223 {
7224 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7225 azArg[i], azArg[0]);
7226 raw_printf(stderr, "Should be one of: --init -v\n");
7227 rc = 1;
7228 goto meta_command_exit;
7229 }
7230 }
7231 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7232 != SQLITE_OK ){
7233 bSelftestExists = 0;
7234 }else{
7235 bSelftestExists = 1;
7236 }
7237 if( bIsInit ){
7238 createSelftestTable(p);
7239 bSelftestExists = 1;
7240 }
7241 initText(&str);
7242 appendText(&str, "x", 0);
7243 for(k=bSelftestExists; k>=0; k--){
7244 if( k==1 ){
7245 rc = sqlite3_prepare_v2(p->db,
7246 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7247 -1, &pStmt, 0);
7248 }else{
7249 rc = sqlite3_prepare_v2(p->db,
7250 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7251 " (1,'run','PRAGMA integrity_check','ok')",
7252 -1, &pStmt, 0);
7253 }
7254 if( rc ){
7255 raw_printf(stderr, "Error querying the selftest table\n");
7256 rc = 1;
7257 sqlite3_finalize(pStmt);
7258 goto meta_command_exit;
7259 }
7260 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7261 int tno = sqlite3_column_int(pStmt, 0);
7262 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7263 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7264 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7265
7266 k = 0;
7267 if( bVerbose>0 ){
7268 char *zQuote = sqlite3_mprintf("%q", zSql);
7269 printf("%d: %s %s\n", tno, zOp, zSql);
7270 sqlite3_free(zQuote);
7271 }
7272 if( strcmp(zOp,"memo")==0 ){
7273 utf8_printf(p->out, "%s\n", zSql);
7274 }else
7275 if( strcmp(zOp,"run")==0 ){
7276 char *zErrMsg = 0;
7277 str.n = 0;
7278 str.z[0] = 0;
7279 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7280 nTest++;
7281 if( bVerbose ){
7282 utf8_printf(p->out, "Result: %s\n", str.z);
7283 }
7284 if( rc || zErrMsg ){
7285 nErr++;
7286 rc = 1;
7287 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7288 sqlite3_free(zErrMsg);
7289 }else if( strcmp(zAns,str.z)!=0 ){
7290 nErr++;
7291 rc = 1;
7292 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7293 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7294 }
7295 }else
7296 {
7297 utf8_printf(stderr,
7298 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7299 rc = 1;
7300 break;
7301 }
7302 } /* End loop over rows of content from SELFTEST */
7303 sqlite3_finalize(pStmt);
7304 } /* End loop over k */
7305 freeText(&str);
7306 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7307 }else
7308
7309 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7310 if( nArg<2 || nArg>3 ){
7311 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7312 rc = 1;
7313 }
7314 if( nArg>=2 ){
7315 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7316 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7317 }
7318 if( nArg>=3 ){
7319 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7320 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7321 }
7322 }else
7323
7324 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7325 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7326 int i; /* Loop counter */
7327 int bSchema = 0; /* Also hash the schema */
7328 int bSeparate = 0; /* Hash each table separately */
7329 int iSize = 224; /* Hash algorithm to use */
7330 int bDebug = 0; /* Only show the query that would have run */
7331 sqlite3_stmt *pStmt; /* For querying tables names */
7332 char *zSql; /* SQL to be run */
7333 char *zSep; /* Separator */
7334 ShellText sSql; /* Complete SQL for the query to run the hash */
7335 ShellText sQuery; /* Set of queries used to read all content */
7336 open_db(p, 0);
7337 for(i=1; i<nArg; i++){
7338 const char *z = azArg[i];
7339 if( z[0]=='-' ){
7340 z++;
7341 if( z[0]=='-' ) z++;
7342 if( strcmp(z,"schema")==0 ){
7343 bSchema = 1;
7344 }else
7345 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7346 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7347 ){
7348 iSize = atoi(&z[5]);
7349 }else
7350 if( strcmp(z,"debug")==0 ){
7351 bDebug = 1;
7352 }else
7353 {
7354 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7355 azArg[i], azArg[0]);
7356 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00007357 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00007358 rc = 1;
7359 goto meta_command_exit;
7360 }
7361 }else if( zLike ){
7362 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7363 rc = 1;
7364 goto meta_command_exit;
7365 }else{
7366 zLike = z;
7367 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00007368 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00007369 }
7370 }
7371 if( bSchema ){
7372 zSql = "SELECT lower(name) FROM sqlite_master"
7373 " WHERE type='table' AND coalesce(rootpage,0)>1"
7374 " UNION ALL SELECT 'sqlite_master'"
7375 " ORDER BY 1 collate nocase";
7376 }else{
7377 zSql = "SELECT lower(name) FROM sqlite_master"
7378 " WHERE type='table' AND coalesce(rootpage,0)>1"
7379 " AND name NOT LIKE 'sqlite_%'"
7380 " ORDER BY 1 collate nocase";
7381 }
7382 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7383 initText(&sQuery);
7384 initText(&sSql);
7385 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7386 zSep = "VALUES(";
7387 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7388 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7389 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7390 if( strncmp(zTab, "sqlite_",7)!=0 ){
7391 appendText(&sQuery,"SELECT * FROM ", 0);
7392 appendText(&sQuery,zTab,'"');
7393 appendText(&sQuery," NOT INDEXED;", 0);
7394 }else if( strcmp(zTab, "sqlite_master")==0 ){
7395 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7396 " ORDER BY name;", 0);
7397 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7398 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7399 " ORDER BY name;", 0);
7400 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7401 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7402 " ORDER BY tbl,idx;", 0);
7403 }else if( strcmp(zTab, "sqlite_stat3")==0
7404 || strcmp(zTab, "sqlite_stat4")==0 ){
7405 appendText(&sQuery, "SELECT * FROM ", 0);
7406 appendText(&sQuery, zTab, 0);
7407 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7408 }
7409 appendText(&sSql, zSep, 0);
7410 appendText(&sSql, sQuery.z, '\'');
7411 sQuery.n = 0;
7412 appendText(&sSql, ",", 0);
7413 appendText(&sSql, zTab, '\'');
7414 zSep = "),(";
7415 }
7416 sqlite3_finalize(pStmt);
7417 if( bSeparate ){
7418 zSql = sqlite3_mprintf(
7419 "%s))"
7420 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7421 " FROM [sha3sum$query]",
7422 sSql.z, iSize);
7423 }else{
7424 zSql = sqlite3_mprintf(
7425 "%s))"
7426 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7427 " FROM [sha3sum$query]",
7428 sSql.z, iSize);
7429 }
7430 freeText(&sQuery);
7431 freeText(&sSql);
7432 if( bDebug ){
7433 utf8_printf(p->out, "%s\n", zSql);
7434 }else{
drha10b9992018-03-09 15:24:33 +00007435 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00007436 }
7437 sqlite3_free(zSql);
7438 }else
7439
drh04a28c32018-01-31 01:38:44 +00007440#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00007441 if( c=='s'
7442 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7443 ){
7444 char *zCmd;
7445 int i, x;
7446 if( nArg<2 ){
7447 raw_printf(stderr, "Usage: .system COMMAND\n");
7448 rc = 1;
7449 goto meta_command_exit;
7450 }
7451 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7452 for(i=2; i<nArg; i++){
7453 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7454 zCmd, azArg[i]);
7455 }
7456 x = system(zCmd);
7457 sqlite3_free(zCmd);
7458 if( x ) raw_printf(stderr, "System command returns %d\n", x);
7459 }else
drh04a28c32018-01-31 01:38:44 +00007460#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00007461
7462 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00007463 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00007464 int i;
7465 if( nArg!=1 ){
7466 raw_printf(stderr, "Usage: .show\n");
7467 rc = 1;
7468 goto meta_command_exit;
7469 }
7470 utf8_printf(p->out, "%12.12s: %s\n","echo",
7471 azBool[ShellHasFlag(p, SHFLG_Echo)]);
7472 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7473 utf8_printf(p->out, "%12.12s: %s\n","explain",
7474 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7475 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7476 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7477 utf8_printf(p->out, "%12.12s: ", "nullvalue");
7478 output_c_string(p->out, p->nullValue);
7479 raw_printf(p->out, "\n");
7480 utf8_printf(p->out,"%12.12s: %s\n","output",
7481 strlen30(p->outfile) ? p->outfile : "stdout");
7482 utf8_printf(p->out,"%12.12s: ", "colseparator");
7483 output_c_string(p->out, p->colSeparator);
7484 raw_printf(p->out, "\n");
7485 utf8_printf(p->out,"%12.12s: ", "rowseparator");
7486 output_c_string(p->out, p->rowSeparator);
7487 raw_printf(p->out, "\n");
7488 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7489 utf8_printf(p->out, "%12.12s: ", "width");
7490 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
7491 raw_printf(p->out, "%d ", p->colWidth[i]);
7492 }
7493 raw_printf(p->out, "\n");
7494 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7495 p->zDbFilename ? p->zDbFilename : "");
7496 }else
7497
7498 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7499 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007500 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007501 }else if( nArg==1 ){
7502 display_stats(p->db, p, 0);
7503 }else{
7504 raw_printf(stderr, "Usage: .stats ?on|off?\n");
7505 rc = 1;
7506 }
7507 }else
7508
7509 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7510 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7511 || strncmp(azArg[0], "indexes", n)==0) )
7512 ){
7513 sqlite3_stmt *pStmt;
7514 char **azResult;
7515 int nRow, nAlloc;
7516 int ii;
7517 ShellText s;
7518 initText(&s);
7519 open_db(p, 0);
7520 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00007521 if( rc ){
7522 sqlite3_finalize(pStmt);
7523 return shellDatabaseError(p->db);
7524 }
drh2ce15c32017-07-11 13:34:40 +00007525
7526 if( nArg>2 && c=='i' ){
7527 /* It is an historical accident that the .indexes command shows an error
7528 ** when called with the wrong number of arguments whereas the .tables
7529 ** command does not. */
7530 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7531 rc = 1;
drh9e804032018-05-18 17:11:50 +00007532 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00007533 goto meta_command_exit;
7534 }
7535 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
7536 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
7537 if( zDbName==0 ) continue;
7538 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7539 if( sqlite3_stricmp(zDbName, "main")==0 ){
7540 appendText(&s, "SELECT name FROM ", 0);
7541 }else{
7542 appendText(&s, "SELECT ", 0);
7543 appendText(&s, zDbName, '\'');
7544 appendText(&s, "||'.'||name FROM ", 0);
7545 }
7546 appendText(&s, zDbName, '"');
7547 appendText(&s, ".sqlite_master ", 0);
7548 if( c=='t' ){
7549 appendText(&s," WHERE type IN ('table','view')"
7550 " AND name NOT LIKE 'sqlite_%'"
7551 " AND name LIKE ?1", 0);
7552 }else{
7553 appendText(&s," WHERE type='index'"
7554 " AND tbl_name LIKE ?1", 0);
7555 }
7556 }
7557 rc = sqlite3_finalize(pStmt);
7558 appendText(&s, " ORDER BY 1", 0);
7559 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7560 freeText(&s);
7561 if( rc ) return shellDatabaseError(p->db);
7562
7563 /* Run the SQL statement prepared by the above block. Store the results
7564 ** as an array of nul-terminated strings in azResult[]. */
7565 nRow = nAlloc = 0;
7566 azResult = 0;
7567 if( nArg>1 ){
7568 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
7569 }else{
7570 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7571 }
7572 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7573 if( nRow>=nAlloc ){
7574 char **azNew;
7575 int n2 = nAlloc*2 + 10;
7576 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00007577 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007578 nAlloc = n2;
7579 azResult = azNew;
7580 }
7581 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00007582 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007583 nRow++;
7584 }
7585 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7586 rc = shellDatabaseError(p->db);
7587 }
7588
7589 /* Pretty-print the contents of array azResult[] to the output */
7590 if( rc==0 && nRow>0 ){
7591 int len, maxlen = 0;
7592 int i, j;
7593 int nPrintCol, nPrintRow;
7594 for(i=0; i<nRow; i++){
7595 len = strlen30(azResult[i]);
7596 if( len>maxlen ) maxlen = len;
7597 }
7598 nPrintCol = 80/(maxlen+2);
7599 if( nPrintCol<1 ) nPrintCol = 1;
7600 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7601 for(i=0; i<nPrintRow; i++){
7602 for(j=i; j<nRow; j+=nPrintRow){
7603 char *zSp = j<nPrintRow ? "" : " ";
7604 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7605 azResult[j] ? azResult[j]:"");
7606 }
7607 raw_printf(p->out, "\n");
7608 }
7609 }
7610
7611 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7612 sqlite3_free(azResult);
7613 }else
7614
7615 /* Begin redirecting output to the file "testcase-out.txt" */
7616 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7617 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00007618 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00007619 if( p->out==0 ){
7620 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7621 }
7622 if( nArg>=2 ){
7623 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7624 }else{
7625 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7626 }
7627 }else
7628
7629#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00007630 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007631 static const struct {
7632 const char *zCtrlName; /* Name of a test-control option */
7633 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00007634 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00007635 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00007636 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7637 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7638 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7639 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7640 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7641 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7642 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drhef302e82017-11-15 19:14:08 +00007643 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7644 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7645 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00007646#ifdef YYCOVERAGE
7647 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7648#endif
drhef302e82017-11-15 19:14:08 +00007649 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7650 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7651 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7652 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7653 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00007654 };
7655 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00007656 int iCtrl = -1;
7657 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7658 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00007659 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00007660 const char *zCmd = 0;
7661
drh2ce15c32017-07-11 13:34:40 +00007662 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00007663 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00007664
7665 /* The argument can optionally begin with "-" or "--" */
7666 if( zCmd[0]=='-' && zCmd[1] ){
7667 zCmd++;
7668 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7669 }
7670
7671 /* --help lists all test-controls */
7672 if( strcmp(zCmd,"help")==0 ){
7673 utf8_printf(p->out, "Available test-controls:\n");
7674 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00007675 utf8_printf(p->out, " .testctrl %s %s\n",
7676 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00007677 }
7678 rc = 1;
7679 goto meta_command_exit;
7680 }
drh2ce15c32017-07-11 13:34:40 +00007681
7682 /* convert testctrl text option to value. allow any unique prefix
7683 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00007684 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007685 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007686 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007687 if( testctrl<0 ){
7688 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007689 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007690 }else{
drh35f51a42017-11-15 17:07:22 +00007691 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7692 "Use \".testctrl --help\" for help\n", zCmd);
7693 rc = 1;
7694 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007695 }
7696 }
7697 }
drhef302e82017-11-15 19:14:08 +00007698 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007699 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7700 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007701 }else{
7702 switch(testctrl){
7703
7704 /* sqlite3_test_control(int, db, int) */
7705 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7706 case SQLITE_TESTCTRL_RESERVE:
7707 if( nArg==3 ){
7708 int opt = (int)strtol(azArg[2], 0, 0);
7709 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007710 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007711 }
7712 break;
7713
7714 /* sqlite3_test_control(int) */
7715 case SQLITE_TESTCTRL_PRNG_SAVE:
7716 case SQLITE_TESTCTRL_PRNG_RESTORE:
7717 case SQLITE_TESTCTRL_PRNG_RESET:
7718 case SQLITE_TESTCTRL_BYTEORDER:
7719 if( nArg==2 ){
7720 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007721 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007722 }
7723 break;
7724
7725 /* sqlite3_test_control(int, uint) */
7726 case SQLITE_TESTCTRL_PENDING_BYTE:
7727 if( nArg==3 ){
7728 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7729 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007730 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007731 }
7732 break;
7733
7734 /* sqlite3_test_control(int, int) */
7735 case SQLITE_TESTCTRL_ASSERT:
7736 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007737 if( nArg==3 ){
7738 int opt = booleanValue(azArg[2]);
7739 rc2 = sqlite3_test_control(testctrl, opt);
7740 isOk = 1;
7741 }
7742 break;
7743
7744 /* sqlite3_test_control(int, int) */
7745 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007746 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7747 if( nArg==3 ){
7748 int opt = booleanValue(azArg[2]);
7749 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007750 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007751 }
7752 break;
7753
drh2ce15c32017-07-11 13:34:40 +00007754 case SQLITE_TESTCTRL_IMPOSTER:
7755 if( nArg==5 ){
7756 rc2 = sqlite3_test_control(testctrl, p->db,
7757 azArg[2],
7758 integerValue(azArg[3]),
7759 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007760 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007761 }
7762 break;
drh0d9de992017-12-26 18:04:23 +00007763
7764#ifdef YYCOVERAGE
7765 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7766 if( nArg==2 ){
7767 sqlite3_test_control(testctrl, p->out);
7768 isOk = 3;
7769 }
7770#endif
drh2ce15c32017-07-11 13:34:40 +00007771 }
7772 }
drhef302e82017-11-15 19:14:08 +00007773 if( isOk==0 && iCtrl>=0 ){
7774 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7775 rc = 1;
7776 }else if( isOk==1 ){
7777 raw_printf(p->out, "%d\n", rc2);
7778 }else if( isOk==2 ){
7779 raw_printf(p->out, "0x%08x\n", rc2);
7780 }
drh2ce15c32017-07-11 13:34:40 +00007781 }else
7782#endif /* !defined(SQLITE_UNTESTABLE) */
7783
7784 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7785 open_db(p, 0);
7786 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7787 }else
7788
7789 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7790 if( nArg==2 ){
7791 enableTimer = booleanValue(azArg[1]);
7792 if( enableTimer && !HAS_TIMER ){
7793 raw_printf(stderr, "Error: timer not available on this system.\n");
7794 enableTimer = 0;
7795 }
7796 }else{
7797 raw_printf(stderr, "Usage: .timer on|off\n");
7798 rc = 1;
7799 }
7800 }else
7801
7802 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7803 open_db(p, 0);
7804 if( nArg!=2 ){
7805 raw_printf(stderr, "Usage: .trace FILE|off\n");
7806 rc = 1;
7807 goto meta_command_exit;
7808 }
7809 output_file_close(p->traceOut);
drha92a01a2018-01-10 22:15:37 +00007810 p->traceOut = output_file_open(azArg[1], 0);
drh2ce15c32017-07-11 13:34:40 +00007811#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7812 if( p->traceOut==0 ){
7813 sqlite3_trace_v2(p->db, 0, 0, 0);
7814 }else{
7815 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7816 }
7817#endif
7818 }else
7819
7820#if SQLITE_USER_AUTHENTICATION
7821 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7822 if( nArg<2 ){
7823 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7824 rc = 1;
7825 goto meta_command_exit;
7826 }
7827 open_db(p, 0);
7828 if( strcmp(azArg[1],"login")==0 ){
7829 if( nArg!=4 ){
7830 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7831 rc = 1;
7832 goto meta_command_exit;
7833 }
drhaf2770f2018-01-05 14:55:43 +00007834 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007835 if( rc ){
7836 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7837 rc = 1;
7838 }
7839 }else if( strcmp(azArg[1],"add")==0 ){
7840 if( nArg!=5 ){
7841 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7842 rc = 1;
7843 goto meta_command_exit;
7844 }
drhaf2770f2018-01-05 14:55:43 +00007845 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007846 booleanValue(azArg[4]));
7847 if( rc ){
7848 raw_printf(stderr, "User-Add failed: %d\n", rc);
7849 rc = 1;
7850 }
7851 }else if( strcmp(azArg[1],"edit")==0 ){
7852 if( nArg!=5 ){
7853 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7854 rc = 1;
7855 goto meta_command_exit;
7856 }
drhaf2770f2018-01-05 14:55:43 +00007857 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007858 booleanValue(azArg[4]));
7859 if( rc ){
7860 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7861 rc = 1;
7862 }
7863 }else if( strcmp(azArg[1],"delete")==0 ){
7864 if( nArg!=3 ){
7865 raw_printf(stderr, "Usage: .user delete USER\n");
7866 rc = 1;
7867 goto meta_command_exit;
7868 }
7869 rc = sqlite3_user_delete(p->db, azArg[2]);
7870 if( rc ){
7871 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7872 rc = 1;
7873 }
7874 }else{
7875 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7876 rc = 1;
7877 goto meta_command_exit;
7878 }
7879 }else
7880#endif /* SQLITE_USER_AUTHENTICATION */
7881
7882 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7883 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7884 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00007885#if SQLITE_HAVE_ZLIB
7886 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
7887#endif
7888#define CTIMEOPT_VAL_(opt) #opt
7889#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7890#if defined(__clang__) && defined(__clang_major__)
7891 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
7892 CTIMEOPT_VAL(__clang_minor__) "."
7893 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
7894#elif defined(_MSC_VER)
7895 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
7896#elif defined(__GNUC__) && defined(__VERSION__)
7897 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
7898#endif
drh2ce15c32017-07-11 13:34:40 +00007899 }else
7900
7901 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7902 const char *zDbName = nArg==2 ? azArg[1] : "main";
7903 sqlite3_vfs *pVfs = 0;
7904 if( p->db ){
7905 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7906 if( pVfs ){
7907 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7908 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7909 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7910 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7911 }
7912 }
7913 }else
7914
7915 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7916 sqlite3_vfs *pVfs;
7917 sqlite3_vfs *pCurrent = 0;
7918 if( p->db ){
7919 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7920 }
7921 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7922 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7923 pVfs==pCurrent ? " <--- CURRENT" : "");
7924 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7925 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7926 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7927 if( pVfs->pNext ){
7928 raw_printf(p->out, "-----------------------------------\n");
7929 }
7930 }
7931 }else
7932
7933 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7934 const char *zDbName = nArg==2 ? azArg[1] : "main";
7935 char *zVfsName = 0;
7936 if( p->db ){
7937 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7938 if( zVfsName ){
7939 utf8_printf(p->out, "%s\n", zVfsName);
7940 sqlite3_free(zVfsName);
7941 }
7942 }
7943 }else
7944
7945#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7946 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7947 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7948 }else
7949#endif
7950
7951 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7952 int j;
7953 assert( nArg<=ArraySize(azArg) );
7954 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7955 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7956 }
7957 }else
7958
7959 {
7960 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7961 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7962 rc = 1;
7963 }
7964
7965meta_command_exit:
7966 if( p->outCount ){
7967 p->outCount--;
7968 if( p->outCount==0 ) output_reset(p);
7969 }
7970 return rc;
7971}
7972
7973/*
7974** Return TRUE if a semicolon occurs anywhere in the first N characters
7975** of string z[].
7976*/
7977static int line_contains_semicolon(const char *z, int N){
7978 int i;
7979 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7980 return 0;
7981}
7982
7983/*
7984** Test to see if a line consists entirely of whitespace.
7985*/
7986static int _all_whitespace(const char *z){
7987 for(; *z; z++){
7988 if( IsSpace(z[0]) ) continue;
7989 if( *z=='/' && z[1]=='*' ){
7990 z += 2;
7991 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7992 if( *z==0 ) return 0;
7993 z++;
7994 continue;
7995 }
7996 if( *z=='-' && z[1]=='-' ){
7997 z += 2;
7998 while( *z && *z!='\n' ){ z++; }
7999 if( *z==0 ) return 1;
8000 continue;
8001 }
8002 return 0;
8003 }
8004 return 1;
8005}
8006
8007/*
8008** Return TRUE if the line typed in is an SQL command terminator other
8009** than a semi-colon. The SQL Server style "go" command is understood
8010** as is the Oracle "/".
8011*/
8012static int line_is_command_terminator(const char *zLine){
8013 while( IsSpace(zLine[0]) ){ zLine++; };
8014 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
8015 return 1; /* Oracle */
8016 }
8017 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
8018 && _all_whitespace(&zLine[2]) ){
8019 return 1; /* SQL Server */
8020 }
8021 return 0;
8022}
8023
8024/*
drh56f17742018-01-24 01:58:49 +00008025** We need a default sqlite3_complete() implementation to use in case
8026** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
8027** any arbitrary text is a complete SQL statement. This is not very
8028** user-friendly, but it does seem to work.
8029*/
8030#ifdef SQLITE_OMIT_COMPLETE
8031int sqlite3_complete(const char *zSql){ return 1; }
8032#endif
8033
8034/*
drh2ce15c32017-07-11 13:34:40 +00008035** Return true if zSql is a complete SQL statement. Return false if it
8036** ends in the middle of a string literal or C-style comment.
8037*/
8038static int line_is_complete(char *zSql, int nSql){
8039 int rc;
8040 if( zSql==0 ) return 1;
8041 zSql[nSql] = ';';
8042 zSql[nSql+1] = 0;
8043 rc = sqlite3_complete(zSql);
8044 zSql[nSql] = 0;
8045 return rc;
8046}
8047
8048/*
drhfc29a862018-05-11 19:11:18 +00008049** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00008050*/
8051static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
8052 int rc;
8053 char *zErrMsg = 0;
8054
8055 open_db(p, 0);
8056 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
8057 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00008058 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008059 END_TIMER;
8060 if( rc || zErrMsg ){
8061 char zPrefix[100];
8062 if( in!=0 || !stdin_is_interactive ){
8063 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
8064 "Error: near line %d:", startline);
8065 }else{
8066 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
8067 }
8068 if( zErrMsg!=0 ){
8069 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
8070 sqlite3_free(zErrMsg);
8071 zErrMsg = 0;
8072 }else{
8073 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
8074 }
8075 return 1;
8076 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
8077 raw_printf(p->out, "changes: %3d total_changes: %d\n",
8078 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
8079 }
8080 return 0;
8081}
8082
8083
8084/*
8085** Read input from *in and process it. If *in==0 then input
8086** is interactive - the user is typing it it. Otherwise, input
8087** is coming from a file or device. A prompt is issued and history
8088** is saved only if input is interactive. An interrupt signal will
8089** cause this routine to exit immediately, unless input is interactive.
8090**
8091** Return the number of errors.
8092*/
8093static int process_input(ShellState *p, FILE *in){
8094 char *zLine = 0; /* A single input line */
8095 char *zSql = 0; /* Accumulated SQL text */
8096 int nLine; /* Length of current line */
8097 int nSql = 0; /* Bytes of zSql[] used */
8098 int nAlloc = 0; /* Allocated zSql[] space */
8099 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
8100 int rc; /* Error code */
8101 int errCnt = 0; /* Number of errors seen */
8102 int lineno = 0; /* Current line number */
8103 int startline = 0; /* Line number for start of current input */
8104
8105 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
8106 fflush(p->out);
8107 zLine = one_input_line(in, zLine, nSql>0);
8108 if( zLine==0 ){
8109 /* End of input */
8110 if( in==0 && stdin_is_interactive ) printf("\n");
8111 break;
8112 }
8113 if( seenInterrupt ){
8114 if( in!=0 ) break;
8115 seenInterrupt = 0;
8116 }
8117 lineno++;
8118 if( nSql==0 && _all_whitespace(zLine) ){
8119 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8120 continue;
8121 }
drh1615c372018-05-12 23:56:22 +00008122 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00008123 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00008124 if( zLine[0]=='.' ){
8125 rc = do_meta_command(zLine, p);
8126 if( rc==2 ){ /* exit requested */
8127 break;
8128 }else if( rc ){
8129 errCnt++;
8130 }
drh2ce15c32017-07-11 13:34:40 +00008131 }
8132 continue;
8133 }
8134 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8135 memcpy(zLine,";",2);
8136 }
8137 nLine = strlen30(zLine);
8138 if( nSql+nLine+2>=nAlloc ){
8139 nAlloc = nSql+nLine+100;
8140 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00008141 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008142 }
8143 nSqlPrior = nSql;
8144 if( nSql==0 ){
8145 int i;
8146 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8147 assert( nAlloc>0 && zSql!=0 );
8148 memcpy(zSql, zLine+i, nLine+1-i);
8149 startline = lineno;
8150 nSql = nLine-i;
8151 }else{
8152 zSql[nSql++] = '\n';
8153 memcpy(zSql+nSql, zLine, nLine+1);
8154 nSql += nLine;
8155 }
8156 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8157 && sqlite3_complete(zSql) ){
8158 errCnt += runOneSqlLine(p, zSql, in, startline);
8159 nSql = 0;
8160 if( p->outCount ){
8161 output_reset(p);
8162 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00008163 }else{
8164 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00008165 }
8166 }else if( nSql && _all_whitespace(zSql) ){
8167 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8168 nSql = 0;
8169 }
8170 }
8171 if( nSql && !_all_whitespace(zSql) ){
drhfc29a862018-05-11 19:11:18 +00008172 errCnt += runOneSqlLine(p, zSql, in, startline);
drh2ce15c32017-07-11 13:34:40 +00008173 }
8174 free(zSql);
8175 free(zLine);
8176 return errCnt>0;
8177}
8178
8179/*
8180** Return a pathname which is the user's home directory. A
8181** 0 return indicates an error of some kind.
8182*/
8183static char *find_home_dir(int clearFlag){
8184 static char *home_dir = NULL;
8185 if( clearFlag ){
8186 free(home_dir);
8187 home_dir = 0;
8188 return 0;
8189 }
8190 if( home_dir ) return home_dir;
8191
8192#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8193 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8194 {
8195 struct passwd *pwent;
8196 uid_t uid = getuid();
8197 if( (pwent=getpwuid(uid)) != NULL) {
8198 home_dir = pwent->pw_dir;
8199 }
8200 }
8201#endif
8202
8203#if defined(_WIN32_WCE)
8204 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8205 */
8206 home_dir = "/";
8207#else
8208
8209#if defined(_WIN32) || defined(WIN32)
8210 if (!home_dir) {
8211 home_dir = getenv("USERPROFILE");
8212 }
8213#endif
8214
8215 if (!home_dir) {
8216 home_dir = getenv("HOME");
8217 }
8218
8219#if defined(_WIN32) || defined(WIN32)
8220 if (!home_dir) {
8221 char *zDrive, *zPath;
8222 int n;
8223 zDrive = getenv("HOMEDRIVE");
8224 zPath = getenv("HOMEPATH");
8225 if( zDrive && zPath ){
8226 n = strlen30(zDrive) + strlen30(zPath) + 1;
8227 home_dir = malloc( n );
8228 if( home_dir==0 ) return 0;
8229 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8230 return home_dir;
8231 }
8232 home_dir = "c:\\";
8233 }
8234#endif
8235
8236#endif /* !_WIN32_WCE */
8237
8238 if( home_dir ){
8239 int n = strlen30(home_dir) + 1;
8240 char *z = malloc( n );
8241 if( z ) memcpy(z, home_dir, n);
8242 home_dir = z;
8243 }
8244
8245 return home_dir;
8246}
8247
8248/*
8249** Read input from the file given by sqliterc_override. Or if that
8250** parameter is NULL, take input from ~/.sqliterc
8251**
8252** Returns the number of errors.
8253*/
8254static void process_sqliterc(
8255 ShellState *p, /* Configuration data */
8256 const char *sqliterc_override /* Name of config file. NULL to use default */
8257){
8258 char *home_dir = NULL;
8259 const char *sqliterc = sqliterc_override;
8260 char *zBuf = 0;
8261 FILE *in = NULL;
8262
8263 if (sqliterc == NULL) {
8264 home_dir = find_home_dir(0);
8265 if( home_dir==0 ){
8266 raw_printf(stderr, "-- warning: cannot find home directory;"
8267 " cannot read ~/.sqliterc\n");
8268 return;
8269 }
drh2ce15c32017-07-11 13:34:40 +00008270 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8271 sqliterc = zBuf;
8272 }
8273 in = fopen(sqliterc,"rb");
8274 if( in ){
8275 if( stdin_is_interactive ){
8276 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8277 }
8278 process_input(p,in);
8279 fclose(in);
8280 }
8281 sqlite3_free(zBuf);
8282}
8283
8284/*
8285** Show available command line options
8286*/
8287static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00008288#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00008289 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00008290#endif
drh3baed312018-03-08 18:14:41 +00008291 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00008292 " -ascii set output mode to 'ascii'\n"
8293 " -bail stop after hitting an error\n"
8294 " -batch force batch I/O\n"
8295 " -column set output mode to 'column'\n"
8296 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8297 " -csv set output mode to 'csv'\n"
8298 " -echo print commands before execution\n"
8299 " -init FILENAME read/process named file\n"
8300 " -[no]header turn headers on or off\n"
8301#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8302 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8303#endif
8304 " -help show this message\n"
8305 " -html set output mode to HTML\n"
8306 " -interactive force interactive I/O\n"
8307 " -line set output mode to 'line'\n"
8308 " -list set output mode to 'list'\n"
8309 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8310 " -mmap N default mmap size set to N\n"
8311#ifdef SQLITE_ENABLE_MULTIPLEX
8312 " -multiplex enable the multiplexor VFS\n"
8313#endif
8314 " -newline SEP set output row separator. Default: '\\n'\n"
8315 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8316 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8317 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00008318 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00008319 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00008320#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8321 " -sorterref SIZE sorter references threshold size\n"
8322#endif
drh2ce15c32017-07-11 13:34:40 +00008323 " -stats print memory stats before each finalize\n"
8324 " -version show SQLite version\n"
8325 " -vfs NAME use NAME as the default VFS\n"
8326#ifdef SQLITE_ENABLE_VFSTRACE
8327 " -vfstrace enable tracing of all VFS calls\n"
8328#endif
drh3baed312018-03-08 18:14:41 +00008329#ifdef SQLITE_HAVE_ZLIB
8330 " -zip open the file as a ZIP Archive\n"
8331#endif
drh2ce15c32017-07-11 13:34:40 +00008332;
8333static void usage(int showDetail){
8334 utf8_printf(stderr,
8335 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8336 "FILENAME is the name of an SQLite database. A new database is created\n"
8337 "if the file does not previously exist.\n", Argv0);
8338 if( showDetail ){
8339 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8340 }else{
8341 raw_printf(stderr, "Use the -help option for additional information\n");
8342 }
8343 exit(1);
8344}
8345
8346/*
drhe7df8922018-04-18 10:44:58 +00008347** Internal check: Verify that the SQLite is uninitialized. Print a
8348** error message if it is initialized.
8349*/
8350static void verify_uninitialized(void){
8351 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00008352 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00008353 " initialization.\n");
8354 }
8355}
8356
8357/*
drh2ce15c32017-07-11 13:34:40 +00008358** Initialize the state information in data
8359*/
8360static void main_init(ShellState *data) {
8361 memset(data, 0, sizeof(*data));
8362 data->normalMode = data->cMode = data->mode = MODE_List;
8363 data->autoExplain = 1;
8364 memcpy(data->colSeparator,SEP_Column, 2);
8365 memcpy(data->rowSeparator,SEP_Row, 2);
8366 data->showHeader = 0;
8367 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00008368 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008369 sqlite3_config(SQLITE_CONFIG_URI, 1);
8370 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8371 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8372 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8373 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8374}
8375
8376/*
8377** Output text to the console in a font that attracts extra attention.
8378*/
8379#ifdef _WIN32
8380static void printBold(const char *zText){
8381 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8382 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8383 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8384 SetConsoleTextAttribute(out,
8385 FOREGROUND_RED|FOREGROUND_INTENSITY
8386 );
8387 printf("%s", zText);
8388 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8389}
8390#else
8391static void printBold(const char *zText){
8392 printf("\033[1m%s\033[0m", zText);
8393}
8394#endif
8395
8396/*
8397** Get the argument to an --option. Throw an error and die if no argument
8398** is available.
8399*/
8400static char *cmdline_option_value(int argc, char **argv, int i){
8401 if( i==argc ){
8402 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8403 argv[0], argv[argc-1]);
8404 exit(1);
8405 }
8406 return argv[i];
8407}
8408
8409#ifndef SQLITE_SHELL_IS_UTF8
8410# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8411# define SQLITE_SHELL_IS_UTF8 (0)
8412# else
8413# define SQLITE_SHELL_IS_UTF8 (1)
8414# endif
8415#endif
8416
8417#if SQLITE_SHELL_IS_UTF8
8418int SQLITE_CDECL main(int argc, char **argv){
8419#else
8420int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8421 char **argv;
8422#endif
8423 char *zErrMsg = 0;
8424 ShellState data;
8425 const char *zInitFile = 0;
8426 int i;
8427 int rc = 0;
8428 int warnInmemoryDb = 0;
8429 int readStdin = 1;
8430 int nCmd = 0;
8431 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00008432 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00008433#if !SQLITE_SHELL_IS_UTF8
8434 char **argvToFree = 0;
8435 int argcToFree = 0;
8436#endif
drh2ce15c32017-07-11 13:34:40 +00008437
8438 setBinaryMode(stdin, 0);
8439 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8440 stdin_is_interactive = isatty(0);
8441 stdout_is_console = isatty(1);
8442
mistachkin1e8487d2018-07-22 06:25:35 +00008443#if !defined(_WIN32_WCE)
8444 if( getenv("SQLITE_DEBUG_BREAK") ){
8445 if( isatty(0) && isatty(2) ){
8446 fprintf(stderr,
8447 "attach debugger to process %d and press any key to continue.\n",
8448 GETPID());
8449 fgetc(stdin);
8450 }else{
8451#if defined(_WIN32) || defined(WIN32)
8452 DebugBreak();
8453#elif defined(SIGTRAP)
8454 raise(SIGTRAP);
8455#endif
8456 }
8457 }
8458#endif
8459
drh2ce15c32017-07-11 13:34:40 +00008460#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00008461 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008462 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
8463 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8464 exit(1);
8465 }
8466#endif
8467 main_init(&data);
drh501ea052018-02-15 01:03:37 +00008468
8469 /* On Windows, we must translate command-line arguments into UTF-8.
8470 ** The SQLite memory allocator subsystem has to be enabled in order to
8471 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8472 ** subsequent sqlite3_config() calls will work. So copy all results into
8473 ** memory that does not come from the SQLite memory allocator.
8474 */
drh4b18c1d2018-02-04 20:33:13 +00008475#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00008476 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00008477 argvToFree = malloc(sizeof(argv[0])*argc*2);
8478 argcToFree = argc;
8479 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00008480 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008481 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00008482 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
8483 int n;
drh4b5345c2018-04-24 13:07:40 +00008484 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008485 n = (int)strlen(z);
8486 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00008487 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008488 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00008489 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00008490 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00008491 }
drh501ea052018-02-15 01:03:37 +00008492 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00008493#endif
drh501ea052018-02-15 01:03:37 +00008494
drh2ce15c32017-07-11 13:34:40 +00008495 assert( argc>=1 && argv && argv[0] );
8496 Argv0 = argv[0];
8497
8498 /* Make sure we have a valid signal handler early, before anything
8499 ** else is done.
8500 */
8501#ifdef SIGINT
8502 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00008503#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8504 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00008505#endif
8506
8507#ifdef SQLITE_SHELL_DBNAME_PROC
8508 {
8509 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8510 ** of a C-function that will provide the name of the database file. Use
8511 ** this compile-time option to embed this shell program in larger
8512 ** applications. */
8513 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8514 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8515 warnInmemoryDb = 0;
8516 }
8517#endif
8518
8519 /* Do an initial pass through the command-line argument to locate
8520 ** the name of the database file, the name of the initialization file,
8521 ** the size of the alternative malloc heap,
8522 ** and the first command to execute.
8523 */
drhe7df8922018-04-18 10:44:58 +00008524 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008525 for(i=1; i<argc; i++){
8526 char *z;
8527 z = argv[i];
8528 if( z[0]!='-' ){
8529 if( data.zDbFilename==0 ){
8530 data.zDbFilename = z;
8531 }else{
8532 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8533 ** mean that nothing is read from stdin */
8534 readStdin = 0;
8535 nCmd++;
8536 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00008537 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008538 azCmd[nCmd-1] = z;
8539 }
8540 }
8541 if( z[1]=='-' ) z++;
8542 if( strcmp(z,"-separator")==0
8543 || strcmp(z,"-nullvalue")==0
8544 || strcmp(z,"-newline")==0
8545 || strcmp(z,"-cmd")==0
8546 ){
8547 (void)cmdline_option_value(argc, argv, ++i);
8548 }else if( strcmp(z,"-init")==0 ){
8549 zInitFile = cmdline_option_value(argc, argv, ++i);
8550 }else if( strcmp(z,"-batch")==0 ){
8551 /* Need to check for batch mode here to so we can avoid printing
8552 ** informational messages (like from process_sqliterc) before
8553 ** we do the actual processing of arguments later in a second pass.
8554 */
8555 stdin_is_interactive = 0;
8556 }else if( strcmp(z,"-heap")==0 ){
8557#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8558 const char *zSize;
8559 sqlite3_int64 szHeap;
8560
8561 zSize = cmdline_option_value(argc, argv, ++i);
8562 szHeap = integerValue(zSize);
8563 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
8564 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
8565#else
8566 (void)cmdline_option_value(argc, argv, ++i);
8567#endif
drh2ce15c32017-07-11 13:34:40 +00008568 }else if( strcmp(z,"-pagecache")==0 ){
8569 int n, sz;
8570 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8571 if( sz>70000 ) sz = 70000;
8572 if( sz<0 ) sz = 0;
8573 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8574 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8575 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
8576 data.shellFlgs |= SHFLG_Pagecache;
8577 }else if( strcmp(z,"-lookaside")==0 ){
8578 int n, sz;
8579 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8580 if( sz<0 ) sz = 0;
8581 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8582 if( n<0 ) n = 0;
8583 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8584 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
8585#ifdef SQLITE_ENABLE_VFSTRACE
8586 }else if( strcmp(z,"-vfstrace")==0 ){
8587 extern int vfstrace_register(
8588 const char *zTraceName,
8589 const char *zOldVfsName,
8590 int (*xOut)(const char*,void*),
8591 void *pOutArg,
8592 int makeDefault
8593 );
8594 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
8595#endif
8596#ifdef SQLITE_ENABLE_MULTIPLEX
8597 }else if( strcmp(z,"-multiplex")==0 ){
8598 extern int sqlite3_multiple_initialize(const char*,int);
8599 sqlite3_multiplex_initialize(0, 1);
8600#endif
8601 }else if( strcmp(z,"-mmap")==0 ){
8602 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8603 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00008604#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8605 }else if( strcmp(z,"-sorterref")==0 ){
8606 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8607 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
8608#endif
drh2ce15c32017-07-11 13:34:40 +00008609 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00008610 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00008611#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00008612 }else if( strcmp(z,"-zip")==0 ){
8613 data.openMode = SHELL_OPEN_ZIPFILE;
8614#endif
8615 }else if( strcmp(z,"-append")==0 ){
8616 data.openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00008617 }else if( strcmp(z,"-readonly")==0 ){
8618 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00008619#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008620 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00008621 /* All remaining command-line arguments are passed to the ".archive"
8622 ** command, so ignore them */
8623 break;
8624#endif
drh2ce15c32017-07-11 13:34:40 +00008625 }
8626 }
drhe7df8922018-04-18 10:44:58 +00008627 verify_uninitialized();
8628
dan16a47422018-04-18 09:16:11 +00008629
drhd11b8f62018-04-25 13:27:07 +00008630#ifdef SQLITE_SHELL_INIT_PROC
8631 {
8632 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8633 ** of a C-function that will perform initialization actions on SQLite that
8634 ** occur just before or after sqlite3_initialize(). Use this compile-time
8635 ** option to embed this shell program in larger applications. */
8636 extern void SQLITE_SHELL_INIT_PROC(void);
8637 SQLITE_SHELL_INIT_PROC();
8638 }
8639#else
dan16a47422018-04-18 09:16:11 +00008640 /* All the sqlite3_config() calls have now been made. So it is safe
8641 ** to call sqlite3_initialize() and process any command line -vfs option. */
8642 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00008643#endif
8644
dan16a47422018-04-18 09:16:11 +00008645 if( zVfs ){
8646 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
8647 if( pVfs ){
8648 sqlite3_vfs_register(pVfs, 1);
8649 }else{
8650 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
8651 exit(1);
8652 }
8653 }
8654
drh2ce15c32017-07-11 13:34:40 +00008655 if( data.zDbFilename==0 ){
8656#ifndef SQLITE_OMIT_MEMORYDB
8657 data.zDbFilename = ":memory:";
8658 warnInmemoryDb = argc==1;
8659#else
8660 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
8661 return 1;
8662#endif
8663 }
8664 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00008665 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00008666
8667 /* Go ahead and open the database file if it already exists. If the
8668 ** file does not exist, delay opening it. This prevents empty database
8669 ** files from being created if a user mistypes the database name argument
8670 ** to the sqlite command-line tool.
8671 */
8672 if( access(data.zDbFilename, 0)==0 ){
8673 open_db(&data, 0);
8674 }
8675
8676 /* Process the initialization file if there is one. If no -init option
8677 ** is given on the command line, look for a file named ~/.sqliterc and
8678 ** try to process it.
8679 */
8680 process_sqliterc(&data,zInitFile);
8681
8682 /* Make a second pass through the command-line argument and set
8683 ** options. This second pass is delayed until after the initialization
8684 ** file is processed so that the command-line arguments will override
8685 ** settings in the initialization file.
8686 */
8687 for(i=1; i<argc; i++){
8688 char *z = argv[i];
8689 if( z[0]!='-' ) continue;
8690 if( z[1]=='-' ){ z++; }
8691 if( strcmp(z,"-init")==0 ){
8692 i++;
8693 }else if( strcmp(z,"-html")==0 ){
8694 data.mode = MODE_Html;
8695 }else if( strcmp(z,"-list")==0 ){
8696 data.mode = MODE_List;
8697 }else if( strcmp(z,"-quote")==0 ){
8698 data.mode = MODE_Quote;
8699 }else if( strcmp(z,"-line")==0 ){
8700 data.mode = MODE_Line;
8701 }else if( strcmp(z,"-column")==0 ){
8702 data.mode = MODE_Column;
8703 }else if( strcmp(z,"-csv")==0 ){
8704 data.mode = MODE_Csv;
8705 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00008706#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00008707 }else if( strcmp(z,"-zip")==0 ){
8708 data.openMode = SHELL_OPEN_ZIPFILE;
8709#endif
8710 }else if( strcmp(z,"-append")==0 ){
8711 data.openMode = SHELL_OPEN_APPENDVFS;
drh4aafe592018-03-23 16:08:30 +00008712 }else if( strcmp(z,"-readonly")==0 ){
8713 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00008714 }else if( strcmp(z,"-ascii")==0 ){
8715 data.mode = MODE_Ascii;
8716 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8717 SEP_Unit);
8718 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8719 SEP_Record);
8720 }else if( strcmp(z,"-separator")==0 ){
8721 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8722 "%s",cmdline_option_value(argc,argv,++i));
8723 }else if( strcmp(z,"-newline")==0 ){
8724 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8725 "%s",cmdline_option_value(argc,argv,++i));
8726 }else if( strcmp(z,"-nullvalue")==0 ){
8727 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8728 "%s",cmdline_option_value(argc,argv,++i));
8729 }else if( strcmp(z,"-header")==0 ){
8730 data.showHeader = 1;
8731 }else if( strcmp(z,"-noheader")==0 ){
8732 data.showHeader = 0;
8733 }else if( strcmp(z,"-echo")==0 ){
8734 ShellSetFlag(&data, SHFLG_Echo);
8735 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00008736 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00008737 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00008738 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00008739 }else if( strcmp(z,"-stats")==0 ){
8740 data.statsOn = 1;
8741 }else if( strcmp(z,"-scanstats")==0 ){
8742 data.scanstatsOn = 1;
8743 }else if( strcmp(z,"-backslash")==0 ){
8744 /* Undocumented command-line option: -backslash
8745 ** Causes C-style backslash escapes to be evaluated in SQL statements
8746 ** prior to sending the SQL into SQLite. Useful for injecting
8747 ** crazy bytes in the middle of SQL statements for testing and debugging.
8748 */
8749 ShellSetFlag(&data, SHFLG_Backslash);
8750 }else if( strcmp(z,"-bail")==0 ){
8751 bail_on_error = 1;
8752 }else if( strcmp(z,"-version")==0 ){
8753 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8754 return 0;
8755 }else if( strcmp(z,"-interactive")==0 ){
8756 stdin_is_interactive = 1;
8757 }else if( strcmp(z,"-batch")==0 ){
8758 stdin_is_interactive = 0;
8759 }else if( strcmp(z,"-heap")==0 ){
8760 i++;
drh2ce15c32017-07-11 13:34:40 +00008761 }else if( strcmp(z,"-pagecache")==0 ){
8762 i+=2;
8763 }else if( strcmp(z,"-lookaside")==0 ){
8764 i+=2;
8765 }else if( strcmp(z,"-mmap")==0 ){
8766 i++;
drha90d84f2018-04-18 15:21:13 +00008767#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8768 }else if( strcmp(z,"-sorterref")==0 ){
8769 i++;
8770#endif
drh2ce15c32017-07-11 13:34:40 +00008771 }else if( strcmp(z,"-vfs")==0 ){
8772 i++;
8773#ifdef SQLITE_ENABLE_VFSTRACE
8774 }else if( strcmp(z,"-vfstrace")==0 ){
8775 i++;
8776#endif
8777#ifdef SQLITE_ENABLE_MULTIPLEX
8778 }else if( strcmp(z,"-multiplex")==0 ){
8779 i++;
8780#endif
8781 }else if( strcmp(z,"-help")==0 ){
8782 usage(1);
8783 }else if( strcmp(z,"-cmd")==0 ){
8784 /* Run commands that follow -cmd first and separately from commands
8785 ** that simply appear on the command-line. This seems goofy. It would
8786 ** be better if all commands ran in the order that they appear. But
8787 ** we retain the goofy behavior for historical compatibility. */
8788 if( i==argc-1 ) break;
8789 z = cmdline_option_value(argc,argv,++i);
8790 if( z[0]=='.' ){
8791 rc = do_meta_command(z, &data);
8792 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8793 }else{
8794 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008795 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008796 if( zErrMsg!=0 ){
8797 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8798 if( bail_on_error ) return rc!=0 ? rc : 1;
8799 }else if( rc!=0 ){
8800 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8801 if( bail_on_error ) return rc;
8802 }
8803 }
drhda57d962018-03-05 19:34:05 +00008804#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008805 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00008806 if( nCmd>0 ){
8807 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
8808 " with \"%s\"\n", z);
8809 return 1;
8810 }
drhbe4ccb22018-05-17 20:04:24 +00008811 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +00008812 if( z[2] ){
8813 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +00008814 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +00008815 }else{
drhd0f9cdc2018-05-17 14:09:06 +00008816 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +00008817 }
drhda57d962018-03-05 19:34:05 +00008818 readStdin = 0;
8819 break;
8820#endif
drh2ce15c32017-07-11 13:34:40 +00008821 }else{
8822 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8823 raw_printf(stderr,"Use -help for a list of options.\n");
8824 return 1;
8825 }
8826 data.cMode = data.mode;
8827 }
8828
8829 if( !readStdin ){
8830 /* Run all arguments that do not begin with '-' as if they were separate
8831 ** command-line inputs, except for the argToSkip argument which contains
8832 ** the database filename.
8833 */
8834 for(i=0; i<nCmd; i++){
8835 if( azCmd[i][0]=='.' ){
8836 rc = do_meta_command(azCmd[i], &data);
8837 if( rc ) return rc==2 ? 0 : rc;
8838 }else{
8839 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008840 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008841 if( zErrMsg!=0 ){
8842 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8843 return rc!=0 ? rc : 1;
8844 }else if( rc!=0 ){
8845 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8846 return rc;
8847 }
8848 }
8849 }
8850 free(azCmd);
8851 }else{
8852 /* Run commands received from standard input
8853 */
8854 if( stdin_is_interactive ){
8855 char *zHome;
8856 char *zHistory = 0;
8857 int nHistory;
8858 printf(
8859 "SQLite version %s %.19s\n" /*extra-version-info*/
8860 "Enter \".help\" for usage hints.\n",
8861 sqlite3_libversion(), sqlite3_sourceid()
8862 );
8863 if( warnInmemoryDb ){
8864 printf("Connected to a ");
8865 printBold("transient in-memory database");
8866 printf(".\nUse \".open FILENAME\" to reopen on a "
8867 "persistent database.\n");
8868 }
8869 zHome = find_home_dir(0);
8870 if( zHome ){
8871 nHistory = strlen30(zHome) + 20;
8872 if( (zHistory = malloc(nHistory))!=0 ){
8873 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8874 }
8875 }
8876 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008877#if HAVE_READLINE || HAVE_EDITLINE
8878 rl_attempted_completion_function = readline_completion;
8879#elif HAVE_LINENOISE
8880 linenoiseSetCompletionCallback(linenoise_completion);
8881#endif
drh2ce15c32017-07-11 13:34:40 +00008882 rc = process_input(&data, 0);
8883 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008884 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008885 shell_write_history(zHistory);
8886 free(zHistory);
8887 }
8888 }else{
8889 rc = process_input(&data, stdin);
8890 }
8891 }
8892 set_table_name(&data, 0);
8893 if( data.db ){
8894 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +00008895 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +00008896 }
8897 sqlite3_free(data.zFreeOnClose);
8898 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +00008899 output_reset(&data);
8900 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +00008901 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +00008902#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +00008903 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
8904 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +00008905#endif
drh9e804032018-05-18 17:11:50 +00008906 /* Clear the global data structure so that valgrind will detect memory
8907 ** leaks */
8908 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +00008909 return rc;
8910}